From e0d5221957bf0d7857f924f1f2ae63d490de0a0a Mon Sep 17 00:00:00 2001 From: Casper van Donderen Date: Wed, 22 Jun 2011 13:54:56 +0200 Subject: Move all other demos in qtbase to examples. Change-Id: Iab0e7364d1f6b348d0e3033ea9304139f5bd6d0d Reviewed-on: http://codereview.qt.nokia.com/617 Reviewed-by: Qt Sanity Bot Reviewed-by: David Boddie --- demos/README | 39 - demos/books/bookdelegate.cpp | 126 -- demos/books/bookdelegate.h | 73 - demos/books/books.pro | 23 - demos/books/books.qrc | 5 - demos/books/bookwindow.cpp | 121 -- demos/books/bookwindow.h | 64 - demos/books/bookwindow.ui | 149 -- demos/books/images/star.png | Bin 782 -> 0 bytes demos/books/initdb.h | 125 -- demos/books/main.cpp | 56 - demos/boxes/3rdparty/fbm.c | 207 --- demos/boxes/3rdparty/fbm.h | 40 - demos/boxes/basic.fsh | 73 - demos/boxes/basic.vsh | 61 - demos/boxes/boxes.pro | 49 - demos/boxes/boxes.qrc | 25 - demos/boxes/cubemap_negx.jpg | Bin 41060 -> 0 bytes demos/boxes/cubemap_negy.jpg | Bin 15520 -> 0 bytes demos/boxes/cubemap_negz.jpg | Bin 68911 -> 0 bytes demos/boxes/cubemap_posx.jpg | Bin 74915 -> 0 bytes demos/boxes/cubemap_posy.jpg | Bin 24193 -> 0 bytes demos/boxes/cubemap_posz.jpg | Bin 57881 -> 0 bytes demos/boxes/dotted.fsh | 66 - demos/boxes/fresnel.fsh | 79 -- demos/boxes/glass.fsh | 76 - demos/boxes/glbuffers.cpp | 402 ------ demos/boxes/glbuffers.h | 366 ----- demos/boxes/glextensions.cpp | 98 -- demos/boxes/glextensions.h | 202 --- demos/boxes/gltrianglemesh.h | 91 -- demos/boxes/granite.fsh | 76 - demos/boxes/main.cpp | 150 -- demos/boxes/marble.fsh | 71 - demos/boxes/parameters.par | 5 - demos/boxes/qt-logo.jpg | Bin 40886 -> 0 bytes demos/boxes/qt-logo.png | Bin 13923 -> 0 bytes demos/boxes/qtbox.cpp | 480 ------- demos/boxes/qtbox.h | 118 -- demos/boxes/reflection.fsh | 54 - demos/boxes/refraction.fsh | 70 - demos/boxes/roundedbox.cpp | 161 --- demos/boxes/roundedbox.h | 72 - demos/boxes/scene.cpp | 1085 -------------- demos/boxes/scene.h | 245 ---- demos/boxes/smiley.png | Bin 14508 -> 0 bytes demos/boxes/square.jpg | Bin 14542 -> 0 bytes demos/boxes/trackball.cpp | 160 --- demos/boxes/trackball.h | 79 -- demos/boxes/wood.fsh | 70 - demos/chip/chip.cpp | 183 --- demos/chip/chip.h | 68 - demos/chip/chip.pro | 20 - demos/chip/fileprint.png | Bin 1456 -> 0 bytes demos/chip/images.qrc | 10 - demos/chip/main.cpp | 57 - demos/chip/mainwindow.cpp | 109 -- demos/chip/mainwindow.h | 68 - demos/chip/qt4logo.png | Bin 48333 -> 0 bytes demos/chip/rotateleft.png | Bin 1754 -> 0 bytes demos/chip/rotateright.png | Bin 1732 -> 0 bytes demos/chip/view.cpp | 276 ---- demos/chip/view.h | 104 -- demos/chip/zoomin.png | Bin 1622 -> 0 bytes demos/chip/zoomout.png | Bin 1601 -> 0 bytes demos/composition/composition.cpp | 544 -------- demos/composition/composition.h | 193 --- demos/composition/composition.html | 23 - demos/composition/composition.pro | 29 - demos/composition/composition.qrc | 8 - demos/composition/flower.jpg | Bin 49616 -> 0 bytes demos/composition/flower_alpha.jpg | Bin 67326 -> 0 bytes demos/composition/main.cpp | 68 - demos/deform/deform.pro | 24 - demos/deform/deform.qrc | 6 - demos/deform/main.cpp | 72 - demos/deform/pathdeform.cpp | 647 --------- demos/deform/pathdeform.h | 153 -- demos/deform/pathdeform.html | 24 - demos/demos.pro | 98 -- demos/embedded/digiflip/digiflip.cpp | 425 ------ demos/embedded/digiflip/digiflip.pro | 11 - demos/embedded/embedded.pro | 12 - demos/embedded/flickable/flickable.cpp | 284 ---- demos/embedded/flickable/flickable.h | 80 -- demos/embedded/flickable/flickable.pro | 12 - demos/embedded/flickable/main.cpp | 233 ---- demos/embedded/flightinfo/aircraft.png | Bin 20200 -> 0 bytes demos/embedded/flightinfo/flightinfo.cpp | 399 ------ demos/embedded/flightinfo/flightinfo.pro | 17 - demos/embedded/flightinfo/flightinfo.qrc | 5 - demos/embedded/flightinfo/form.ui | 226 --- demos/embedded/lightmaps/lightmaps.cpp | 287 ---- demos/embedded/lightmaps/lightmaps.h | 88 -- demos/embedded/lightmaps/lightmaps.pro | 21 - demos/embedded/lightmaps/main.cpp | 63 - demos/embedded/lightmaps/mapzoom.cpp | 147 -- demos/embedded/lightmaps/mapzoom.h | 69 - demos/embedded/lightmaps/slippymap.cpp | 213 --- demos/embedded/lightmaps/slippymap.h | 87 -- demos/embedded/raycasting/raycasting.cpp | 391 ------ demos/embedded/raycasting/raycasting.pro | 13 - demos/embedded/raycasting/raycasting.qrc | 5 - demos/embedded/raycasting/textures.png | Bin 17669 -> 0 bytes demos/embedded/styledemo/files/add.png | Bin 1474 -> 0 bytes demos/embedded/styledemo/files/application.qss | 125 -- demos/embedded/styledemo/files/blue.qss | 38 - demos/embedded/styledemo/files/khaki.qss | 99 -- demos/embedded/styledemo/files/nature_1.jpg | Bin 167443 -> 0 bytes demos/embedded/styledemo/files/nostyle.qss | 0 demos/embedded/styledemo/files/remove.png | Bin 865 -> 0 bytes demos/embedded/styledemo/files/transparent.qss | 139 -- demos/embedded/styledemo/main.cpp | 59 - demos/embedded/styledemo/styledemo.pro | 17 - demos/embedded/styledemo/styledemo.qrc | 13 - demos/embedded/styledemo/stylewidget.cpp | 112 -- demos/embedded/styledemo/stylewidget.h | 65 - demos/embedded/styledemo/stylewidget.ui | 417 ------ demos/embeddeddialogs/No-Ones-Laughing-3.jpg | Bin 30730 -> 0 bytes demos/embeddeddialogs/customproxy.cpp | 167 --- demos/embeddeddialogs/customproxy.h | 76 - demos/embeddeddialogs/embeddeddialog.cpp | 106 -- demos/embeddeddialogs/embeddeddialog.h | 66 - demos/embeddeddialogs/embeddeddialog.ui | 87 -- demos/embeddeddialogs/embeddeddialogs.pro | 19 - demos/embeddeddialogs/embeddeddialogs.qrc | 5 - demos/embeddeddialogs/main.cpp | 83 -- demos/gradients/gradients.cpp | 516 ------- demos/gradients/gradients.h | 170 --- demos/gradients/gradients.html | 31 - demos/gradients/gradients.pro | 20 - demos/gradients/gradients.qrc | 6 - demos/gradients/main.cpp | 63 - demos/interview/README | 2 - demos/interview/images/folder.png | Bin 3910 -> 0 bytes demos/interview/images/interview.png | Bin 174 -> 0 bytes demos/interview/images/services.png | Bin 3749 -> 0 bytes demos/interview/interview.pro | 19 - demos/interview/interview.qrc | 7 - demos/interview/main.cpp | 95 -- demos/interview/model.cpp | 147 -- demos/interview/model.h | 90 -- demos/macmainwindow/macmainwindow.h | 137 -- demos/macmainwindow/macmainwindow.mm | 347 ----- demos/macmainwindow/macmainwindow.pro | 23 - demos/macmainwindow/main.cpp | 66 - demos/mainwindow/colorswatch.cpp | 746 ---------- demos/mainwindow/colorswatch.h | 136 -- demos/mainwindow/main.cpp | 164 --- demos/mainwindow/mainwindow.cpp | 514 ------- demos/mainwindow/mainwindow.h | 90 -- demos/mainwindow/mainwindow.pro | 17 - demos/mainwindow/mainwindow.qrc | 8 - demos/mainwindow/qt.png | Bin 2037 -> 0 bytes demos/mainwindow/titlebarCenter.png | Bin 146 -> 0 bytes demos/mainwindow/titlebarLeft.png | Bin 5148 -> 0 bytes demos/mainwindow/titlebarRight.png | Bin 2704 -> 0 bytes demos/mainwindow/toolbar.cpp | 383 ----- demos/mainwindow/toolbar.h | 118 -- demos/pathstroke/main.cpp | 71 - demos/pathstroke/pathstroke.cpp | 686 --------- demos/pathstroke/pathstroke.h | 171 --- demos/pathstroke/pathstroke.html | 20 - demos/pathstroke/pathstroke.pro | 24 - demos/pathstroke/pathstroke.qrc | 6 - demos/shared/arthurstyle.cpp | 452 ------ demos/shared/arthurstyle.h | 79 -- demos/shared/arthurwidgets.cpp | 371 ----- demos/shared/arthurwidgets.h | 137 -- demos/shared/hoverpoints.cpp | 415 ------ demos/shared/hoverpoints.h | 162 --- demos/shared/images/bg_pattern.png | Bin 104 -> 0 bytes demos/shared/images/button_normal_cap_left.png | Bin 654 -> 0 bytes demos/shared/images/button_normal_cap_right.png | Bin 674 -> 0 bytes demos/shared/images/button_normal_stretch.png | Bin 185 -> 0 bytes demos/shared/images/button_pressed_cap_left.png | Bin 710 -> 0 bytes demos/shared/images/button_pressed_cap_right.png | Bin 785 -> 0 bytes demos/shared/images/button_pressed_stretch.png | Bin 217 -> 0 bytes demos/shared/images/curve_thing_edit-6.png | Bin 58097 -> 0 bytes demos/shared/images/frame_bottom.png | Bin 166 -> 0 bytes demos/shared/images/frame_bottomleft.png | Bin 602 -> 0 bytes demos/shared/images/frame_bottomright.png | Bin 553 -> 0 bytes demos/shared/images/frame_left.png | Bin 182 -> 0 bytes demos/shared/images/frame_right.png | Bin 175 -> 0 bytes demos/shared/images/frame_top.png | Bin 188 -> 0 bytes demos/shared/images/frame_topleft.png | Bin 801 -> 0 bytes demos/shared/images/frame_topright.png | Bin 851 -> 0 bytes demos/shared/images/groupframe_bottom_left.png | Bin 397 -> 0 bytes demos/shared/images/groupframe_bottom_right.png | Bin 383 -> 0 bytes demos/shared/images/groupframe_bottom_stretch.png | Bin 141 -> 0 bytes demos/shared/images/groupframe_left_stretch.png | Bin 132 -> 0 bytes demos/shared/images/groupframe_right_stretch.png | Bin 113 -> 0 bytes demos/shared/images/groupframe_top_stretch.png | Bin 115 -> 0 bytes demos/shared/images/groupframe_topleft.png | Bin 412 -> 0 bytes demos/shared/images/groupframe_topright.png | Bin 449 -> 0 bytes demos/shared/images/line_dash_dot.png | Bin 151 -> 0 bytes demos/shared/images/line_dash_dot_dot.png | Bin 155 -> 0 bytes demos/shared/images/line_dashed.png | Bin 121 -> 0 bytes demos/shared/images/line_dotted.png | Bin 116 -> 0 bytes demos/shared/images/line_solid.png | Bin 110 -> 0 bytes demos/shared/images/radiobutton-off.png | Bin 442 -> 0 bytes demos/shared/images/radiobutton-on.png | Bin 474 -> 0 bytes demos/shared/images/radiobutton_off.png | Bin 442 -> 0 bytes demos/shared/images/radiobutton_on.png | Bin 499 -> 0 bytes demos/shared/images/slider_bar.png | Bin 748 -> 0 bytes demos/shared/images/slider_thumb_off.png | Bin 823 -> 0 bytes demos/shared/images/slider_thumb_on.png | Bin 798 -> 0 bytes demos/shared/images/title_cap_left.png | Bin 179 -> 0 bytes demos/shared/images/title_cap_right.png | Bin 184 -> 0 bytes demos/shared/images/title_stretch.png | Bin 106 -> 0 bytes demos/shared/shared.pri | 21 - demos/shared/shared.pro | 39 - demos/shared/shared.qrc | 39 - demos/spreadsheet/images/interview.png | Bin 174 -> 0 bytes demos/spreadsheet/main.cpp | 55 - demos/spreadsheet/printview.cpp | 59 - demos/spreadsheet/printview.h | 60 - demos/spreadsheet/spreadsheet.cpp | 633 --------- demos/spreadsheet/spreadsheet.h | 124 -- demos/spreadsheet/spreadsheet.pro | 34 - demos/spreadsheet/spreadsheet.qrc | 5 - demos/spreadsheet/spreadsheetdelegate.cpp | 114 -- demos/spreadsheet/spreadsheetdelegate.h | 65 - demos/spreadsheet/spreadsheetitem.cpp | 167 --- demos/spreadsheet/spreadsheetitem.h | 73 - demos/sqlbrowser/browser.cpp | 247 ---- demos/sqlbrowser/browser.h | 99 -- demos/sqlbrowser/browserwidget.ui | 199 --- demos/sqlbrowser/connectionwidget.cpp | 165 --- demos/sqlbrowser/connectionwidget.h | 79 -- demos/sqlbrowser/main.cpp | 91 -- demos/sqlbrowser/qsqlconnectiondialog.cpp | 115 -- demos/sqlbrowser/qsqlconnectiondialog.h | 74 - demos/sqlbrowser/qsqlconnectiondialog.ui | 224 --- demos/sqlbrowser/sqlbrowser.pro | 25 - demos/sub-attaq/animationmanager.cpp | 98 -- demos/sub-attaq/animationmanager.h | 73 - demos/sub-attaq/boat.cpp | 272 ---- demos/sub-attaq/boat.h | 95 -- demos/sub-attaq/boat_p.h | 232 --- demos/sub-attaq/bomb.cpp | 118 -- demos/sub-attaq/bomb.h | 67 - demos/sub-attaq/data.xml | 39 - demos/sub-attaq/graphicsscene.cpp | 282 ---- demos/sub-attaq/graphicsscene.h | 122 -- demos/sub-attaq/main.cpp | 57 - demos/sub-attaq/mainwindow.cpp | 82 -- demos/sub-attaq/mainwindow.h | 63 - demos/sub-attaq/pics/big/background.png | Bin 48858 -> 0 bytes demos/sub-attaq/pics/big/boat.png | Bin 5198 -> 0 bytes demos/sub-attaq/pics/big/bomb.png | Bin 760 -> 0 bytes demos/sub-attaq/pics/big/explosion/boat/step1.png | Bin 5760 -> 0 bytes demos/sub-attaq/pics/big/explosion/boat/step2.png | Bin 9976 -> 0 bytes demos/sub-attaq/pics/big/explosion/boat/step3.png | Bin 12411 -> 0 bytes demos/sub-attaq/pics/big/explosion/boat/step4.png | Bin 15438 -> 0 bytes .../pics/big/explosion/submarine/step1.png | Bin 3354 -> 0 bytes .../pics/big/explosion/submarine/step2.png | Bin 6205 -> 0 bytes .../pics/big/explosion/submarine/step3.png | Bin 6678 -> 0 bytes .../pics/big/explosion/submarine/step4.png | Bin 6666 -> 0 bytes demos/sub-attaq/pics/big/submarine.png | Bin 3202 -> 0 bytes demos/sub-attaq/pics/big/surface.png | Bin 575 -> 0 bytes demos/sub-attaq/pics/big/torpedo.png | Bin 951 -> 0 bytes demos/sub-attaq/pics/scalable/background-n810.svg | 171 --- demos/sub-attaq/pics/scalable/background.svg | 171 --- demos/sub-attaq/pics/scalable/boat.svg | 279 ---- demos/sub-attaq/pics/scalable/bomb.svg | 138 -- demos/sub-attaq/pics/scalable/sand.svg | 103 -- demos/sub-attaq/pics/scalable/see.svg | 44 - demos/sub-attaq/pics/scalable/sky.svg | 45 - demos/sub-attaq/pics/scalable/sub-attaq.svg | 1473 -------------------- demos/sub-attaq/pics/scalable/submarine.svg | 214 --- demos/sub-attaq/pics/scalable/surface.svg | 49 - demos/sub-attaq/pics/scalable/torpedo.svg | 127 -- demos/sub-attaq/pics/small/background.png | Bin 34634 -> 0 bytes demos/sub-attaq/pics/small/boat.png | Bin 2394 -> 0 bytes demos/sub-attaq/pics/small/bomb.png | Bin 760 -> 0 bytes demos/sub-attaq/pics/small/submarine.png | Bin 1338 -> 0 bytes demos/sub-attaq/pics/small/surface.png | Bin 502 -> 0 bytes demos/sub-attaq/pics/small/torpedo.png | Bin 951 -> 0 bytes demos/sub-attaq/pics/welcome/logo-a.png | Bin 5972 -> 0 bytes demos/sub-attaq/pics/welcome/logo-a2.png | Bin 5969 -> 0 bytes demos/sub-attaq/pics/welcome/logo-b.png | Bin 6869 -> 0 bytes demos/sub-attaq/pics/welcome/logo-dash.png | Bin 2255 -> 0 bytes demos/sub-attaq/pics/welcome/logo-excl.png | Bin 2740 -> 0 bytes demos/sub-attaq/pics/welcome/logo-q.png | Bin 7016 -> 0 bytes demos/sub-attaq/pics/welcome/logo-s.png | Bin 5817 -> 0 bytes demos/sub-attaq/pics/welcome/logo-t.png | Bin 3717 -> 0 bytes demos/sub-attaq/pics/welcome/logo-t2.png | Bin 3688 -> 0 bytes demos/sub-attaq/pics/welcome/logo-u.png | Bin 5374 -> 0 bytes demos/sub-attaq/pixmapitem.cpp | 76 - demos/sub-attaq/pixmapitem.h | 63 - demos/sub-attaq/progressitem.cpp | 67 - demos/sub-attaq/progressitem.h | 61 - demos/sub-attaq/qanimationstate.cpp | 150 -- demos/sub-attaq/qanimationstate.h | 92 -- demos/sub-attaq/states.cpp | 330 ----- demos/sub-attaq/states.h | 180 --- demos/sub-attaq/sub-attaq.pro | 41 - demos/sub-attaq/subattaq.qrc | 39 - demos/sub-attaq/submarine.cpp | 182 --- demos/sub-attaq/submarine.h | 93 -- demos/sub-attaq/submarine_p.h | 137 -- demos/sub-attaq/textinformationitem.cpp | 54 - demos/sub-attaq/textinformationitem.h | 55 - demos/sub-attaq/torpedo.cpp | 114 -- demos/sub-attaq/torpedo.h | 67 - demos/textedit/example.html | 79 -- demos/textedit/images/logo32.png | Bin 1410 -> 0 bytes demos/textedit/images/mac/editcopy.png | Bin 1468 -> 0 bytes demos/textedit/images/mac/editcut.png | Bin 1512 -> 0 bytes demos/textedit/images/mac/editpaste.png | Bin 1906 -> 0 bytes demos/textedit/images/mac/editredo.png | Bin 1752 -> 0 bytes demos/textedit/images/mac/editundo.png | Bin 1746 -> 0 bytes demos/textedit/images/mac/exportpdf.png | Bin 1215 -> 0 bytes demos/textedit/images/mac/filenew.png | Bin 1172 -> 0 bytes demos/textedit/images/mac/fileopen.png | Bin 2168 -> 0 bytes demos/textedit/images/mac/fileprint.png | Bin 2087 -> 0 bytes demos/textedit/images/mac/filesave.png | Bin 1206 -> 0 bytes demos/textedit/images/mac/textbold.png | Bin 1611 -> 0 bytes demos/textedit/images/mac/textcenter.png | Bin 1404 -> 0 bytes demos/textedit/images/mac/textitalic.png | Bin 1164 -> 0 bytes demos/textedit/images/mac/textjustify.png | Bin 1257 -> 0 bytes demos/textedit/images/mac/textleft.png | Bin 1235 -> 0 bytes demos/textedit/images/mac/textright.png | Bin 1406 -> 0 bytes demos/textedit/images/mac/textunder.png | Bin 1183 -> 0 bytes demos/textedit/images/mac/zoomin.png | Bin 1696 -> 0 bytes demos/textedit/images/mac/zoomout.png | Bin 1662 -> 0 bytes demos/textedit/images/win/editcopy.png | Bin 1325 -> 0 bytes demos/textedit/images/win/editcut.png | Bin 1896 -> 0 bytes demos/textedit/images/win/editpaste.png | Bin 1482 -> 0 bytes demos/textedit/images/win/editredo.png | Bin 1787 -> 0 bytes demos/textedit/images/win/editundo.png | Bin 1768 -> 0 bytes demos/textedit/images/win/exportpdf.png | Bin 1059 -> 0 bytes demos/textedit/images/win/filenew.png | Bin 768 -> 0 bytes demos/textedit/images/win/fileopen.png | Bin 1662 -> 0 bytes demos/textedit/images/win/fileprint.png | Bin 1456 -> 0 bytes demos/textedit/images/win/filesave.png | Bin 1205 -> 0 bytes demos/textedit/images/win/textbold.png | Bin 1134 -> 0 bytes demos/textedit/images/win/textcenter.png | Bin 627 -> 0 bytes demos/textedit/images/win/textitalic.png | Bin 829 -> 0 bytes demos/textedit/images/win/textjustify.png | Bin 695 -> 0 bytes demos/textedit/images/win/textleft.png | Bin 673 -> 0 bytes demos/textedit/images/win/textright.png | Bin 677 -> 0 bytes demos/textedit/images/win/textunder.png | Bin 971 -> 0 bytes demos/textedit/images/win/zoomin.png | Bin 1208 -> 0 bytes demos/textedit/images/win/zoomout.png | Bin 1226 -> 0 bytes demos/textedit/main.cpp | 54 - demos/textedit/textedit.cpp | 734 ---------- demos/textedit/textedit.h | 129 -- demos/textedit/textedit.pro | 22 - demos/textedit/textedit.qdoc | 45 - demos/textedit/textedit.qrc | 44 - demos/undo/commands.cpp | 180 --- demos/undo/commands.h | 112 -- demos/undo/document.cpp | 445 ------ demos/undo/document.h | 125 -- demos/undo/icons/background.png | Bin 93 -> 0 bytes demos/undo/icons/blue.png | Bin 1659 -> 0 bytes demos/undo/icons/circle.png | Bin 1359 -> 0 bytes demos/undo/icons/exit.png | Bin 1731 -> 0 bytes demos/undo/icons/fileclose.png | Bin 1121 -> 0 bytes demos/undo/icons/filenew.png | Bin 1266 -> 0 bytes demos/undo/icons/fileopen.png | Bin 1771 -> 0 bytes demos/undo/icons/filesave.png | Bin 1022 -> 0 bytes demos/undo/icons/green.png | Bin 1766 -> 0 bytes demos/undo/icons/ok.png | Bin 979 -> 0 bytes demos/undo/icons/rectangle.png | Bin 690 -> 0 bytes demos/undo/icons/red.png | Bin 1653 -> 0 bytes demos/undo/icons/redo.png | Bin 985 -> 0 bytes demos/undo/icons/remove.png | Bin 1833 -> 0 bytes demos/undo/icons/triangle.png | Bin 850 -> 0 bytes demos/undo/icons/undo.png | Bin 962 -> 0 bytes demos/undo/main.cpp | 56 - demos/undo/mainwindow.cpp | 446 ------ demos/undo/mainwindow.h | 87 -- demos/undo/mainwindow.ui | 322 ----- demos/undo/undo.pro | 18 - demos/undo/undo.qrc | 20 - examples/animation/sub-attaq/animationmanager.cpp | 98 ++ examples/animation/sub-attaq/animationmanager.h | 73 + examples/animation/sub-attaq/boat.cpp | 272 ++++ examples/animation/sub-attaq/boat.h | 95 ++ examples/animation/sub-attaq/boat_p.h | 232 +++ examples/animation/sub-attaq/bomb.cpp | 118 ++ examples/animation/sub-attaq/bomb.h | 67 + examples/animation/sub-attaq/data.xml | 39 + examples/animation/sub-attaq/graphicsscene.cpp | 282 ++++ examples/animation/sub-attaq/graphicsscene.h | 122 ++ examples/animation/sub-attaq/main.cpp | 57 + examples/animation/sub-attaq/mainwindow.cpp | 82 ++ examples/animation/sub-attaq/mainwindow.h | 63 + .../animation/sub-attaq/pics/big/background.png | Bin 0 -> 48858 bytes examples/animation/sub-attaq/pics/big/boat.png | Bin 0 -> 5198 bytes examples/animation/sub-attaq/pics/big/bomb.png | Bin 0 -> 760 bytes .../sub-attaq/pics/big/explosion/boat/step1.png | Bin 0 -> 5760 bytes .../sub-attaq/pics/big/explosion/boat/step2.png | Bin 0 -> 9976 bytes .../sub-attaq/pics/big/explosion/boat/step3.png | Bin 0 -> 12411 bytes .../sub-attaq/pics/big/explosion/boat/step4.png | Bin 0 -> 15438 bytes .../pics/big/explosion/submarine/step1.png | Bin 0 -> 3354 bytes .../pics/big/explosion/submarine/step2.png | Bin 0 -> 6205 bytes .../pics/big/explosion/submarine/step3.png | Bin 0 -> 6678 bytes .../pics/big/explosion/submarine/step4.png | Bin 0 -> 6666 bytes .../animation/sub-attaq/pics/big/submarine.png | Bin 0 -> 3202 bytes examples/animation/sub-attaq/pics/big/surface.png | Bin 0 -> 575 bytes examples/animation/sub-attaq/pics/big/torpedo.png | Bin 0 -> 951 bytes .../sub-attaq/pics/scalable/background-n810.svg | 171 +++ .../sub-attaq/pics/scalable/background.svg | 171 +++ .../animation/sub-attaq/pics/scalable/boat.svg | 279 ++++ .../animation/sub-attaq/pics/scalable/bomb.svg | 138 ++ .../animation/sub-attaq/pics/scalable/sand.svg | 103 ++ examples/animation/sub-attaq/pics/scalable/see.svg | 44 + examples/animation/sub-attaq/pics/scalable/sky.svg | 45 + .../sub-attaq/pics/scalable/sub-attaq.svg | 1473 ++++++++++++++++++++ .../sub-attaq/pics/scalable/submarine.svg | 214 +++ .../animation/sub-attaq/pics/scalable/surface.svg | 49 + .../animation/sub-attaq/pics/scalable/torpedo.svg | 127 ++ .../animation/sub-attaq/pics/small/background.png | Bin 0 -> 34634 bytes examples/animation/sub-attaq/pics/small/boat.png | Bin 0 -> 2394 bytes examples/animation/sub-attaq/pics/small/bomb.png | Bin 0 -> 760 bytes .../animation/sub-attaq/pics/small/submarine.png | Bin 0 -> 1338 bytes .../animation/sub-attaq/pics/small/surface.png | Bin 0 -> 502 bytes .../animation/sub-attaq/pics/small/torpedo.png | Bin 0 -> 951 bytes .../animation/sub-attaq/pics/welcome/logo-a.png | Bin 0 -> 5972 bytes .../animation/sub-attaq/pics/welcome/logo-a2.png | Bin 0 -> 5969 bytes .../animation/sub-attaq/pics/welcome/logo-b.png | Bin 0 -> 6869 bytes .../animation/sub-attaq/pics/welcome/logo-dash.png | Bin 0 -> 2255 bytes .../animation/sub-attaq/pics/welcome/logo-excl.png | Bin 0 -> 2740 bytes .../animation/sub-attaq/pics/welcome/logo-q.png | Bin 0 -> 7016 bytes .../animation/sub-attaq/pics/welcome/logo-s.png | Bin 0 -> 5817 bytes .../animation/sub-attaq/pics/welcome/logo-t.png | Bin 0 -> 3717 bytes .../animation/sub-attaq/pics/welcome/logo-t2.png | Bin 0 -> 3688 bytes .../animation/sub-attaq/pics/welcome/logo-u.png | Bin 0 -> 5374 bytes examples/animation/sub-attaq/pixmapitem.cpp | 76 + examples/animation/sub-attaq/pixmapitem.h | 63 + examples/animation/sub-attaq/progressitem.cpp | 67 + examples/animation/sub-attaq/progressitem.h | 61 + examples/animation/sub-attaq/qanimationstate.cpp | 150 ++ examples/animation/sub-attaq/qanimationstate.h | 92 ++ examples/animation/sub-attaq/states.cpp | 330 +++++ examples/animation/sub-attaq/states.h | 180 +++ examples/animation/sub-attaq/sub-attaq.pro | 41 + examples/animation/sub-attaq/subattaq.qrc | 39 + examples/animation/sub-attaq/submarine.cpp | 182 +++ examples/animation/sub-attaq/submarine.h | 93 ++ examples/animation/sub-attaq/submarine_p.h | 137 ++ .../animation/sub-attaq/textinformationitem.cpp | 54 + examples/animation/sub-attaq/textinformationitem.h | 55 + examples/animation/sub-attaq/torpedo.cpp | 114 ++ examples/animation/sub-attaq/torpedo.h | 67 + examples/embedded/digiflip/digiflip.cpp | 425 ++++++ examples/embedded/digiflip/digiflip.pro | 11 + examples/embedded/embedded.pro | 12 + examples/embedded/flickable/flickable.cpp | 284 ++++ examples/embedded/flickable/flickable.h | 80 ++ examples/embedded/flickable/flickable.pro | 12 + examples/embedded/flickable/main.cpp | 233 ++++ examples/embedded/flightinfo/aircraft.png | Bin 0 -> 20200 bytes examples/embedded/flightinfo/flightinfo.cpp | 399 ++++++ examples/embedded/flightinfo/flightinfo.pro | 17 + examples/embedded/flightinfo/flightinfo.qrc | 5 + examples/embedded/flightinfo/form.ui | 226 +++ examples/embedded/lightmaps/lightmaps.cpp | 287 ++++ examples/embedded/lightmaps/lightmaps.h | 88 ++ examples/embedded/lightmaps/lightmaps.pro | 21 + examples/embedded/lightmaps/main.cpp | 63 + examples/embedded/lightmaps/mapzoom.cpp | 147 ++ examples/embedded/lightmaps/mapzoom.h | 69 + examples/embedded/lightmaps/slippymap.cpp | 213 +++ examples/embedded/lightmaps/slippymap.h | 87 ++ examples/embedded/raycasting/raycasting.cpp | 391 ++++++ examples/embedded/raycasting/raycasting.pro | 13 + examples/embedded/raycasting/raycasting.qrc | 5 + examples/embedded/raycasting/textures.png | Bin 0 -> 17669 bytes examples/embedded/styledemo/files/add.png | Bin 0 -> 1474 bytes examples/embedded/styledemo/files/application.qss | 125 ++ examples/embedded/styledemo/files/blue.qss | 38 + examples/embedded/styledemo/files/khaki.qss | 99 ++ examples/embedded/styledemo/files/nature_1.jpg | Bin 0 -> 167443 bytes examples/embedded/styledemo/files/nostyle.qss | 0 examples/embedded/styledemo/files/remove.png | Bin 0 -> 865 bytes examples/embedded/styledemo/files/transparent.qss | 139 ++ examples/embedded/styledemo/main.cpp | 59 + examples/embedded/styledemo/styledemo.pro | 17 + examples/embedded/styledemo/styledemo.qrc | 13 + examples/embedded/styledemo/stylewidget.cpp | 112 ++ examples/embedded/styledemo/stylewidget.h | 65 + examples/embedded/styledemo/stylewidget.ui | 417 ++++++ examples/graphicsview/boxes/3rdparty/fbm.c | 207 +++ examples/graphicsview/boxes/3rdparty/fbm.h | 40 + examples/graphicsview/boxes/basic.fsh | 73 + examples/graphicsview/boxes/basic.vsh | 61 + examples/graphicsview/boxes/boxes.pro | 49 + examples/graphicsview/boxes/boxes.qrc | 25 + examples/graphicsview/boxes/cubemap_negx.jpg | Bin 0 -> 41060 bytes examples/graphicsview/boxes/cubemap_negy.jpg | Bin 0 -> 15520 bytes examples/graphicsview/boxes/cubemap_negz.jpg | Bin 0 -> 68911 bytes examples/graphicsview/boxes/cubemap_posx.jpg | Bin 0 -> 74915 bytes examples/graphicsview/boxes/cubemap_posy.jpg | Bin 0 -> 24193 bytes examples/graphicsview/boxes/cubemap_posz.jpg | Bin 0 -> 57881 bytes examples/graphicsview/boxes/dotted.fsh | 66 + examples/graphicsview/boxes/fresnel.fsh | 79 ++ examples/graphicsview/boxes/glass.fsh | 76 + examples/graphicsview/boxes/glbuffers.cpp | 402 ++++++ examples/graphicsview/boxes/glbuffers.h | 366 +++++ examples/graphicsview/boxes/glextensions.cpp | 98 ++ examples/graphicsview/boxes/glextensions.h | 202 +++ examples/graphicsview/boxes/gltrianglemesh.h | 91 ++ examples/graphicsview/boxes/granite.fsh | 76 + examples/graphicsview/boxes/main.cpp | 150 ++ examples/graphicsview/boxes/marble.fsh | 71 + examples/graphicsview/boxes/parameters.par | 5 + examples/graphicsview/boxes/qt-logo.jpg | Bin 0 -> 40886 bytes examples/graphicsview/boxes/qt-logo.png | Bin 0 -> 13923 bytes examples/graphicsview/boxes/qtbox.cpp | 480 +++++++ examples/graphicsview/boxes/qtbox.h | 118 ++ examples/graphicsview/boxes/reflection.fsh | 54 + examples/graphicsview/boxes/refraction.fsh | 70 + examples/graphicsview/boxes/roundedbox.cpp | 161 +++ examples/graphicsview/boxes/roundedbox.h | 72 + examples/graphicsview/boxes/scene.cpp | 1085 ++++++++++++++ examples/graphicsview/boxes/scene.h | 245 ++++ examples/graphicsview/boxes/smiley.png | Bin 0 -> 14508 bytes examples/graphicsview/boxes/square.jpg | Bin 0 -> 14542 bytes examples/graphicsview/boxes/trackball.cpp | 160 +++ examples/graphicsview/boxes/trackball.h | 79 ++ examples/graphicsview/boxes/wood.fsh | 70 + examples/graphicsview/chip/chip.cpp | 183 +++ examples/graphicsview/chip/chip.h | 68 + examples/graphicsview/chip/chip.pro | 20 + examples/graphicsview/chip/fileprint.png | Bin 0 -> 1456 bytes examples/graphicsview/chip/images.qrc | 10 + examples/graphicsview/chip/main.cpp | 57 + examples/graphicsview/chip/mainwindow.cpp | 109 ++ examples/graphicsview/chip/mainwindow.h | 68 + examples/graphicsview/chip/qt4logo.png | Bin 0 -> 48333 bytes examples/graphicsview/chip/rotateleft.png | Bin 0 -> 1754 bytes examples/graphicsview/chip/rotateright.png | Bin 0 -> 1732 bytes examples/graphicsview/chip/view.cpp | 276 ++++ examples/graphicsview/chip/view.h | 104 ++ examples/graphicsview/chip/zoomin.png | Bin 0 -> 1622 bytes examples/graphicsview/chip/zoomout.png | Bin 0 -> 1601 bytes .../embeddeddialogs/No-Ones-Laughing-3.jpg | Bin 0 -> 30730 bytes .../graphicsview/embeddeddialogs/customproxy.cpp | 167 +++ .../graphicsview/embeddeddialogs/customproxy.h | 76 + .../embeddeddialogs/embeddeddialog.cpp | 106 ++ .../graphicsview/embeddeddialogs/embeddeddialog.h | 66 + .../graphicsview/embeddeddialogs/embeddeddialog.ui | 87 ++ .../embeddeddialogs/embeddeddialogs.pro | 19 + .../embeddeddialogs/embeddeddialogs.qrc | 5 + examples/graphicsview/embeddeddialogs/main.cpp | 83 ++ examples/itemviews/interview/README | 2 + examples/itemviews/interview/images/folder.png | Bin 0 -> 3910 bytes examples/itemviews/interview/images/interview.png | Bin 0 -> 174 bytes examples/itemviews/interview/images/services.png | Bin 0 -> 3749 bytes examples/itemviews/interview/interview.pro | 19 + examples/itemviews/interview/interview.qrc | 7 + examples/itemviews/interview/main.cpp | 95 ++ examples/itemviews/interview/model.cpp | 147 ++ examples/itemviews/interview/model.h | 90 ++ .../itemviews/spreadsheet/images/interview.png | Bin 0 -> 174 bytes examples/itemviews/spreadsheet/main.cpp | 55 + examples/itemviews/spreadsheet/printview.cpp | 59 + examples/itemviews/spreadsheet/printview.h | 60 + examples/itemviews/spreadsheet/spreadsheet.cpp | 633 +++++++++ examples/itemviews/spreadsheet/spreadsheet.h | 124 ++ examples/itemviews/spreadsheet/spreadsheet.pro | 34 + examples/itemviews/spreadsheet/spreadsheet.qrc | 5 + .../itemviews/spreadsheet/spreadsheetdelegate.cpp | 114 ++ .../itemviews/spreadsheet/spreadsheetdelegate.h | 65 + examples/itemviews/spreadsheet/spreadsheetitem.cpp | 167 +++ examples/itemviews/spreadsheet/spreadsheetitem.h | 73 + examples/mainwindows/macmainwindow/macmainwindow.h | 137 ++ .../mainwindows/macmainwindow/macmainwindow.mm | 347 +++++ .../mainwindows/macmainwindow/macmainwindow.pro | 23 + examples/mainwindows/macmainwindow/main.cpp | 66 + examples/mainwindows/mainwindow/colorswatch.cpp | 746 ++++++++++ examples/mainwindows/mainwindow/colorswatch.h | 136 ++ examples/mainwindows/mainwindow/main.cpp | 164 +++ examples/mainwindows/mainwindow/mainwindow.cpp | 514 +++++++ examples/mainwindows/mainwindow/mainwindow.h | 90 ++ examples/mainwindows/mainwindow/mainwindow.pro | 17 + examples/mainwindows/mainwindow/mainwindow.qrc | 8 + examples/mainwindows/mainwindow/qt.png | Bin 0 -> 2037 bytes examples/mainwindows/mainwindow/titlebarCenter.png | Bin 0 -> 146 bytes examples/mainwindows/mainwindow/titlebarLeft.png | Bin 0 -> 5148 bytes examples/mainwindows/mainwindow/titlebarRight.png | Bin 0 -> 2704 bytes examples/mainwindows/mainwindow/toolbar.cpp | 383 +++++ examples/mainwindows/mainwindow/toolbar.h | 118 ++ examples/painting/composition/composition.cpp | 544 ++++++++ examples/painting/composition/composition.h | 193 +++ examples/painting/composition/composition.html | 23 + examples/painting/composition/composition.pro | 29 + examples/painting/composition/composition.qrc | 8 + examples/painting/composition/flower.jpg | Bin 0 -> 49616 bytes examples/painting/composition/flower_alpha.jpg | Bin 0 -> 67326 bytes examples/painting/composition/main.cpp | 68 + examples/painting/deform/deform.pro | 24 + examples/painting/deform/deform.qrc | 6 + examples/painting/deform/main.cpp | 72 + examples/painting/deform/pathdeform.cpp | 647 +++++++++ examples/painting/deform/pathdeform.h | 153 ++ examples/painting/deform/pathdeform.html | 24 + examples/painting/gradients/gradients.cpp | 516 +++++++ examples/painting/gradients/gradients.h | 170 +++ examples/painting/gradients/gradients.html | 31 + examples/painting/gradients/gradients.pro | 20 + examples/painting/gradients/gradients.qrc | 6 + examples/painting/gradients/main.cpp | 63 + examples/painting/pathstroke/main.cpp | 71 + examples/painting/pathstroke/pathstroke.cpp | 686 +++++++++ examples/painting/pathstroke/pathstroke.h | 171 +++ examples/painting/pathstroke/pathstroke.html | 20 + examples/painting/pathstroke/pathstroke.pro | 24 + examples/painting/pathstroke/pathstroke.qrc | 6 + examples/painting/shared/arthurstyle.cpp | 452 ++++++ examples/painting/shared/arthurstyle.h | 79 ++ examples/painting/shared/arthurwidgets.cpp | 371 +++++ examples/painting/shared/arthurwidgets.h | 137 ++ examples/painting/shared/hoverpoints.cpp | 415 ++++++ examples/painting/shared/hoverpoints.h | 162 +++ examples/painting/shared/images/bg_pattern.png | Bin 0 -> 104 bytes .../shared/images/button_normal_cap_left.png | Bin 0 -> 654 bytes .../shared/images/button_normal_cap_right.png | Bin 0 -> 674 bytes .../shared/images/button_normal_stretch.png | Bin 0 -> 185 bytes .../shared/images/button_pressed_cap_left.png | Bin 0 -> 710 bytes .../shared/images/button_pressed_cap_right.png | Bin 0 -> 785 bytes .../shared/images/button_pressed_stretch.png | Bin 0 -> 217 bytes .../painting/shared/images/curve_thing_edit-6.png | Bin 0 -> 58097 bytes examples/painting/shared/images/frame_bottom.png | Bin 0 -> 166 bytes .../painting/shared/images/frame_bottomleft.png | Bin 0 -> 602 bytes .../painting/shared/images/frame_bottomright.png | Bin 0 -> 553 bytes examples/painting/shared/images/frame_left.png | Bin 0 -> 182 bytes examples/painting/shared/images/frame_right.png | Bin 0 -> 175 bytes examples/painting/shared/images/frame_top.png | Bin 0 -> 188 bytes examples/painting/shared/images/frame_topleft.png | Bin 0 -> 801 bytes examples/painting/shared/images/frame_topright.png | Bin 0 -> 851 bytes .../shared/images/groupframe_bottom_left.png | Bin 0 -> 397 bytes .../shared/images/groupframe_bottom_right.png | Bin 0 -> 383 bytes .../shared/images/groupframe_bottom_stretch.png | Bin 0 -> 141 bytes .../shared/images/groupframe_left_stretch.png | Bin 0 -> 132 bytes .../shared/images/groupframe_right_stretch.png | Bin 0 -> 113 bytes .../shared/images/groupframe_top_stretch.png | Bin 0 -> 115 bytes .../painting/shared/images/groupframe_topleft.png | Bin 0 -> 412 bytes .../painting/shared/images/groupframe_topright.png | Bin 0 -> 449 bytes examples/painting/shared/images/line_dash_dot.png | Bin 0 -> 151 bytes .../painting/shared/images/line_dash_dot_dot.png | Bin 0 -> 155 bytes examples/painting/shared/images/line_dashed.png | Bin 0 -> 121 bytes examples/painting/shared/images/line_dotted.png | Bin 0 -> 116 bytes examples/painting/shared/images/line_solid.png | Bin 0 -> 110 bytes .../painting/shared/images/radiobutton-off.png | Bin 0 -> 442 bytes examples/painting/shared/images/radiobutton-on.png | Bin 0 -> 474 bytes .../painting/shared/images/radiobutton_off.png | Bin 0 -> 442 bytes examples/painting/shared/images/radiobutton_on.png | Bin 0 -> 499 bytes examples/painting/shared/images/slider_bar.png | Bin 0 -> 748 bytes .../painting/shared/images/slider_thumb_off.png | Bin 0 -> 823 bytes .../painting/shared/images/slider_thumb_on.png | Bin 0 -> 798 bytes examples/painting/shared/images/title_cap_left.png | Bin 0 -> 179 bytes .../painting/shared/images/title_cap_right.png | Bin 0 -> 184 bytes examples/painting/shared/images/title_stretch.png | Bin 0 -> 106 bytes examples/painting/shared/shared.pri | 21 + examples/painting/shared/shared.pro | 39 + examples/painting/shared/shared.qrc | 39 + examples/richtext/textedit/example.html | 79 ++ examples/richtext/textedit/images/logo32.png | Bin 0 -> 1410 bytes examples/richtext/textedit/images/mac/editcopy.png | Bin 0 -> 1468 bytes examples/richtext/textedit/images/mac/editcut.png | Bin 0 -> 1512 bytes .../richtext/textedit/images/mac/editpaste.png | Bin 0 -> 1906 bytes examples/richtext/textedit/images/mac/editredo.png | Bin 0 -> 1752 bytes examples/richtext/textedit/images/mac/editundo.png | Bin 0 -> 1746 bytes .../richtext/textedit/images/mac/exportpdf.png | Bin 0 -> 1215 bytes examples/richtext/textedit/images/mac/filenew.png | Bin 0 -> 1172 bytes examples/richtext/textedit/images/mac/fileopen.png | Bin 0 -> 2168 bytes .../richtext/textedit/images/mac/fileprint.png | Bin 0 -> 2087 bytes examples/richtext/textedit/images/mac/filesave.png | Bin 0 -> 1206 bytes examples/richtext/textedit/images/mac/textbold.png | Bin 0 -> 1611 bytes .../richtext/textedit/images/mac/textcenter.png | Bin 0 -> 1404 bytes .../richtext/textedit/images/mac/textitalic.png | Bin 0 -> 1164 bytes .../richtext/textedit/images/mac/textjustify.png | Bin 0 -> 1257 bytes examples/richtext/textedit/images/mac/textleft.png | Bin 0 -> 1235 bytes .../richtext/textedit/images/mac/textright.png | Bin 0 -> 1406 bytes .../richtext/textedit/images/mac/textunder.png | Bin 0 -> 1183 bytes examples/richtext/textedit/images/mac/zoomin.png | Bin 0 -> 1696 bytes examples/richtext/textedit/images/mac/zoomout.png | Bin 0 -> 1662 bytes examples/richtext/textedit/images/win/editcopy.png | Bin 0 -> 1325 bytes examples/richtext/textedit/images/win/editcut.png | Bin 0 -> 1896 bytes .../richtext/textedit/images/win/editpaste.png | Bin 0 -> 1482 bytes examples/richtext/textedit/images/win/editredo.png | Bin 0 -> 1787 bytes examples/richtext/textedit/images/win/editundo.png | Bin 0 -> 1768 bytes .../richtext/textedit/images/win/exportpdf.png | Bin 0 -> 1059 bytes examples/richtext/textedit/images/win/filenew.png | Bin 0 -> 768 bytes examples/richtext/textedit/images/win/fileopen.png | Bin 0 -> 1662 bytes .../richtext/textedit/images/win/fileprint.png | Bin 0 -> 1456 bytes examples/richtext/textedit/images/win/filesave.png | Bin 0 -> 1205 bytes examples/richtext/textedit/images/win/textbold.png | Bin 0 -> 1134 bytes .../richtext/textedit/images/win/textcenter.png | Bin 0 -> 627 bytes .../richtext/textedit/images/win/textitalic.png | Bin 0 -> 829 bytes .../richtext/textedit/images/win/textjustify.png | Bin 0 -> 695 bytes examples/richtext/textedit/images/win/textleft.png | Bin 0 -> 673 bytes .../richtext/textedit/images/win/textright.png | Bin 0 -> 677 bytes .../richtext/textedit/images/win/textunder.png | Bin 0 -> 971 bytes examples/richtext/textedit/images/win/zoomin.png | Bin 0 -> 1208 bytes examples/richtext/textedit/images/win/zoomout.png | Bin 0 -> 1226 bytes examples/richtext/textedit/main.cpp | 54 + examples/richtext/textedit/textedit.cpp | 734 ++++++++++ examples/richtext/textedit/textedit.h | 129 ++ examples/richtext/textedit/textedit.pro | 22 + examples/richtext/textedit/textedit.qdoc | 45 + examples/richtext/textedit/textedit.qrc | 44 + examples/sql/books/bookdelegate.cpp | 126 ++ examples/sql/books/bookdelegate.h | 73 + examples/sql/books/books.pro | 23 + examples/sql/books/books.qrc | 5 + examples/sql/books/bookwindow.cpp | 121 ++ examples/sql/books/bookwindow.h | 64 + examples/sql/books/bookwindow.ui | 149 ++ examples/sql/books/images/star.png | Bin 0 -> 782 bytes examples/sql/books/initdb.h | 125 ++ examples/sql/books/main.cpp | 56 + examples/sql/sqlbrowser/browser.cpp | 247 ++++ examples/sql/sqlbrowser/browser.h | 99 ++ examples/sql/sqlbrowser/browserwidget.ui | 199 +++ examples/sql/sqlbrowser/connectionwidget.cpp | 165 +++ examples/sql/sqlbrowser/connectionwidget.h | 79 ++ examples/sql/sqlbrowser/main.cpp | 91 ++ examples/sql/sqlbrowser/qsqlconnectiondialog.cpp | 115 ++ examples/sql/sqlbrowser/qsqlconnectiondialog.h | 74 + examples/sql/sqlbrowser/qsqlconnectiondialog.ui | 224 +++ examples/sql/sqlbrowser/sqlbrowser.pro | 25 + examples/tools/undo/commands.cpp | 180 +++ examples/tools/undo/commands.h | 112 ++ examples/tools/undo/document.cpp | 445 ++++++ examples/tools/undo/document.h | 125 ++ examples/tools/undo/icons/background.png | Bin 0 -> 93 bytes examples/tools/undo/icons/blue.png | Bin 0 -> 1659 bytes examples/tools/undo/icons/circle.png | Bin 0 -> 1359 bytes examples/tools/undo/icons/exit.png | Bin 0 -> 1731 bytes examples/tools/undo/icons/fileclose.png | Bin 0 -> 1121 bytes examples/tools/undo/icons/filenew.png | Bin 0 -> 1266 bytes examples/tools/undo/icons/fileopen.png | Bin 0 -> 1771 bytes examples/tools/undo/icons/filesave.png | Bin 0 -> 1022 bytes examples/tools/undo/icons/green.png | Bin 0 -> 1766 bytes examples/tools/undo/icons/ok.png | Bin 0 -> 979 bytes examples/tools/undo/icons/rectangle.png | Bin 0 -> 690 bytes examples/tools/undo/icons/red.png | Bin 0 -> 1653 bytes examples/tools/undo/icons/redo.png | Bin 0 -> 985 bytes examples/tools/undo/icons/remove.png | Bin 0 -> 1833 bytes examples/tools/undo/icons/triangle.png | Bin 0 -> 850 bytes examples/tools/undo/icons/undo.png | Bin 0 -> 962 bytes examples/tools/undo/main.cpp | 56 + examples/tools/undo/mainwindow.cpp | 446 ++++++ examples/tools/undo/mainwindow.h | 87 ++ examples/tools/undo/mainwindow.ui | 322 +++++ examples/tools/undo/undo.pro | 18 + examples/tools/undo/undo.qrc | 20 + 754 files changed, 31388 insertions(+), 31525 deletions(-) delete mode 100644 demos/README delete mode 100644 demos/books/bookdelegate.cpp delete mode 100644 demos/books/bookdelegate.h delete mode 100644 demos/books/books.pro delete mode 100644 demos/books/books.qrc delete mode 100644 demos/books/bookwindow.cpp delete mode 100644 demos/books/bookwindow.h delete mode 100644 demos/books/bookwindow.ui delete mode 100644 demos/books/images/star.png delete mode 100644 demos/books/initdb.h delete mode 100644 demos/books/main.cpp delete mode 100644 demos/boxes/3rdparty/fbm.c delete mode 100644 demos/boxes/3rdparty/fbm.h delete mode 100644 demos/boxes/basic.fsh delete mode 100644 demos/boxes/basic.vsh delete mode 100644 demos/boxes/boxes.pro delete mode 100644 demos/boxes/boxes.qrc delete mode 100644 demos/boxes/cubemap_negx.jpg delete mode 100644 demos/boxes/cubemap_negy.jpg delete mode 100644 demos/boxes/cubemap_negz.jpg delete mode 100644 demos/boxes/cubemap_posx.jpg delete mode 100644 demos/boxes/cubemap_posy.jpg delete mode 100644 demos/boxes/cubemap_posz.jpg delete mode 100644 demos/boxes/dotted.fsh delete mode 100644 demos/boxes/fresnel.fsh delete mode 100644 demos/boxes/glass.fsh delete mode 100644 demos/boxes/glbuffers.cpp delete mode 100644 demos/boxes/glbuffers.h delete mode 100644 demos/boxes/glextensions.cpp delete mode 100644 demos/boxes/glextensions.h delete mode 100644 demos/boxes/gltrianglemesh.h delete mode 100644 demos/boxes/granite.fsh delete mode 100644 demos/boxes/main.cpp delete mode 100644 demos/boxes/marble.fsh delete mode 100644 demos/boxes/parameters.par delete mode 100644 demos/boxes/qt-logo.jpg delete mode 100644 demos/boxes/qt-logo.png delete mode 100644 demos/boxes/qtbox.cpp delete mode 100644 demos/boxes/qtbox.h delete mode 100644 demos/boxes/reflection.fsh delete mode 100644 demos/boxes/refraction.fsh delete mode 100644 demos/boxes/roundedbox.cpp delete mode 100644 demos/boxes/roundedbox.h delete mode 100644 demos/boxes/scene.cpp delete mode 100644 demos/boxes/scene.h delete mode 100644 demos/boxes/smiley.png delete mode 100644 demos/boxes/square.jpg delete mode 100644 demos/boxes/trackball.cpp delete mode 100644 demos/boxes/trackball.h delete mode 100644 demos/boxes/wood.fsh delete mode 100644 demos/chip/chip.cpp delete mode 100644 demos/chip/chip.h delete mode 100644 demos/chip/chip.pro delete mode 100644 demos/chip/fileprint.png delete mode 100644 demos/chip/images.qrc delete mode 100644 demos/chip/main.cpp delete mode 100644 demos/chip/mainwindow.cpp delete mode 100644 demos/chip/mainwindow.h delete mode 100644 demos/chip/qt4logo.png delete mode 100644 demos/chip/rotateleft.png delete mode 100644 demos/chip/rotateright.png delete mode 100644 demos/chip/view.cpp delete mode 100644 demos/chip/view.h delete mode 100644 demos/chip/zoomin.png delete mode 100644 demos/chip/zoomout.png delete mode 100644 demos/composition/composition.cpp delete mode 100644 demos/composition/composition.h delete mode 100644 demos/composition/composition.html delete mode 100644 demos/composition/composition.pro delete mode 100644 demos/composition/composition.qrc delete mode 100644 demos/composition/flower.jpg delete mode 100644 demos/composition/flower_alpha.jpg delete mode 100644 demos/composition/main.cpp delete mode 100644 demos/deform/deform.pro delete mode 100644 demos/deform/deform.qrc delete mode 100644 demos/deform/main.cpp delete mode 100644 demos/deform/pathdeform.cpp delete mode 100644 demos/deform/pathdeform.h delete mode 100644 demos/deform/pathdeform.html delete mode 100644 demos/demos.pro delete mode 100644 demos/embedded/digiflip/digiflip.cpp delete mode 100644 demos/embedded/digiflip/digiflip.pro delete mode 100644 demos/embedded/embedded.pro delete mode 100644 demos/embedded/flickable/flickable.cpp delete mode 100644 demos/embedded/flickable/flickable.h delete mode 100644 demos/embedded/flickable/flickable.pro delete mode 100644 demos/embedded/flickable/main.cpp delete mode 100644 demos/embedded/flightinfo/aircraft.png delete mode 100644 demos/embedded/flightinfo/flightinfo.cpp delete mode 100644 demos/embedded/flightinfo/flightinfo.pro delete mode 100644 demos/embedded/flightinfo/flightinfo.qrc delete mode 100644 demos/embedded/flightinfo/form.ui delete mode 100644 demos/embedded/lightmaps/lightmaps.cpp delete mode 100644 demos/embedded/lightmaps/lightmaps.h delete mode 100644 demos/embedded/lightmaps/lightmaps.pro delete mode 100644 demos/embedded/lightmaps/main.cpp delete mode 100644 demos/embedded/lightmaps/mapzoom.cpp delete mode 100644 demos/embedded/lightmaps/mapzoom.h delete mode 100644 demos/embedded/lightmaps/slippymap.cpp delete mode 100644 demos/embedded/lightmaps/slippymap.h delete mode 100644 demos/embedded/raycasting/raycasting.cpp delete mode 100644 demos/embedded/raycasting/raycasting.pro delete mode 100644 demos/embedded/raycasting/raycasting.qrc delete mode 100644 demos/embedded/raycasting/textures.png delete mode 100755 demos/embedded/styledemo/files/add.png delete mode 100644 demos/embedded/styledemo/files/application.qss delete mode 100644 demos/embedded/styledemo/files/blue.qss delete mode 100644 demos/embedded/styledemo/files/khaki.qss delete mode 100644 demos/embedded/styledemo/files/nature_1.jpg delete mode 100644 demos/embedded/styledemo/files/nostyle.qss delete mode 100755 demos/embedded/styledemo/files/remove.png delete mode 100644 demos/embedded/styledemo/files/transparent.qss delete mode 100644 demos/embedded/styledemo/main.cpp delete mode 100644 demos/embedded/styledemo/styledemo.pro delete mode 100644 demos/embedded/styledemo/styledemo.qrc delete mode 100644 demos/embedded/styledemo/stylewidget.cpp delete mode 100644 demos/embedded/styledemo/stylewidget.h delete mode 100644 demos/embedded/styledemo/stylewidget.ui delete mode 100644 demos/embeddeddialogs/No-Ones-Laughing-3.jpg delete mode 100644 demos/embeddeddialogs/customproxy.cpp delete mode 100644 demos/embeddeddialogs/customproxy.h delete mode 100644 demos/embeddeddialogs/embeddeddialog.cpp delete mode 100644 demos/embeddeddialogs/embeddeddialog.h delete mode 100644 demos/embeddeddialogs/embeddeddialog.ui delete mode 100644 demos/embeddeddialogs/embeddeddialogs.pro delete mode 100644 demos/embeddeddialogs/embeddeddialogs.qrc delete mode 100644 demos/embeddeddialogs/main.cpp delete mode 100644 demos/gradients/gradients.cpp delete mode 100644 demos/gradients/gradients.h delete mode 100644 demos/gradients/gradients.html delete mode 100644 demos/gradients/gradients.pro delete mode 100644 demos/gradients/gradients.qrc delete mode 100644 demos/gradients/main.cpp delete mode 100644 demos/interview/README delete mode 100644 demos/interview/images/folder.png delete mode 100644 demos/interview/images/interview.png delete mode 100644 demos/interview/images/services.png delete mode 100644 demos/interview/interview.pro delete mode 100644 demos/interview/interview.qrc delete mode 100644 demos/interview/main.cpp delete mode 100644 demos/interview/model.cpp delete mode 100644 demos/interview/model.h delete mode 100644 demos/macmainwindow/macmainwindow.h delete mode 100644 demos/macmainwindow/macmainwindow.mm delete mode 100644 demos/macmainwindow/macmainwindow.pro delete mode 100644 demos/macmainwindow/main.cpp delete mode 100644 demos/mainwindow/colorswatch.cpp delete mode 100644 demos/mainwindow/colorswatch.h delete mode 100644 demos/mainwindow/main.cpp delete mode 100644 demos/mainwindow/mainwindow.cpp delete mode 100644 demos/mainwindow/mainwindow.h delete mode 100644 demos/mainwindow/mainwindow.pro delete mode 100644 demos/mainwindow/mainwindow.qrc delete mode 100644 demos/mainwindow/qt.png delete mode 100644 demos/mainwindow/titlebarCenter.png delete mode 100644 demos/mainwindow/titlebarLeft.png delete mode 100644 demos/mainwindow/titlebarRight.png delete mode 100644 demos/mainwindow/toolbar.cpp delete mode 100644 demos/mainwindow/toolbar.h delete mode 100644 demos/pathstroke/main.cpp delete mode 100644 demos/pathstroke/pathstroke.cpp delete mode 100644 demos/pathstroke/pathstroke.h delete mode 100644 demos/pathstroke/pathstroke.html delete mode 100644 demos/pathstroke/pathstroke.pro delete mode 100644 demos/pathstroke/pathstroke.qrc delete mode 100644 demos/shared/arthurstyle.cpp delete mode 100644 demos/shared/arthurstyle.h delete mode 100644 demos/shared/arthurwidgets.cpp delete mode 100644 demos/shared/arthurwidgets.h delete mode 100644 demos/shared/hoverpoints.cpp delete mode 100644 demos/shared/hoverpoints.h delete mode 100644 demos/shared/images/bg_pattern.png delete mode 100644 demos/shared/images/button_normal_cap_left.png delete mode 100644 demos/shared/images/button_normal_cap_right.png delete mode 100644 demos/shared/images/button_normal_stretch.png delete mode 100644 demos/shared/images/button_pressed_cap_left.png delete mode 100644 demos/shared/images/button_pressed_cap_right.png delete mode 100644 demos/shared/images/button_pressed_stretch.png delete mode 100644 demos/shared/images/curve_thing_edit-6.png delete mode 100644 demos/shared/images/frame_bottom.png delete mode 100644 demos/shared/images/frame_bottomleft.png delete mode 100644 demos/shared/images/frame_bottomright.png delete mode 100644 demos/shared/images/frame_left.png delete mode 100644 demos/shared/images/frame_right.png delete mode 100644 demos/shared/images/frame_top.png delete mode 100644 demos/shared/images/frame_topleft.png delete mode 100644 demos/shared/images/frame_topright.png delete mode 100644 demos/shared/images/groupframe_bottom_left.png delete mode 100644 demos/shared/images/groupframe_bottom_right.png delete mode 100644 demos/shared/images/groupframe_bottom_stretch.png delete mode 100644 demos/shared/images/groupframe_left_stretch.png delete mode 100644 demos/shared/images/groupframe_right_stretch.png delete mode 100644 demos/shared/images/groupframe_top_stretch.png delete mode 100644 demos/shared/images/groupframe_topleft.png delete mode 100644 demos/shared/images/groupframe_topright.png delete mode 100644 demos/shared/images/line_dash_dot.png delete mode 100644 demos/shared/images/line_dash_dot_dot.png delete mode 100644 demos/shared/images/line_dashed.png delete mode 100644 demos/shared/images/line_dotted.png delete mode 100644 demos/shared/images/line_solid.png delete mode 100644 demos/shared/images/radiobutton-off.png delete mode 100644 demos/shared/images/radiobutton-on.png delete mode 100644 demos/shared/images/radiobutton_off.png delete mode 100644 demos/shared/images/radiobutton_on.png delete mode 100644 demos/shared/images/slider_bar.png delete mode 100644 demos/shared/images/slider_thumb_off.png delete mode 100644 demos/shared/images/slider_thumb_on.png delete mode 100644 demos/shared/images/title_cap_left.png delete mode 100644 demos/shared/images/title_cap_right.png delete mode 100644 demos/shared/images/title_stretch.png delete mode 100644 demos/shared/shared.pri delete mode 100644 demos/shared/shared.pro delete mode 100644 demos/shared/shared.qrc delete mode 100644 demos/spreadsheet/images/interview.png delete mode 100644 demos/spreadsheet/main.cpp delete mode 100644 demos/spreadsheet/printview.cpp delete mode 100644 demos/spreadsheet/printview.h delete mode 100644 demos/spreadsheet/spreadsheet.cpp delete mode 100644 demos/spreadsheet/spreadsheet.h delete mode 100644 demos/spreadsheet/spreadsheet.pro delete mode 100644 demos/spreadsheet/spreadsheet.qrc delete mode 100644 demos/spreadsheet/spreadsheetdelegate.cpp delete mode 100644 demos/spreadsheet/spreadsheetdelegate.h delete mode 100644 demos/spreadsheet/spreadsheetitem.cpp delete mode 100644 demos/spreadsheet/spreadsheetitem.h delete mode 100644 demos/sqlbrowser/browser.cpp delete mode 100644 demos/sqlbrowser/browser.h delete mode 100644 demos/sqlbrowser/browserwidget.ui delete mode 100644 demos/sqlbrowser/connectionwidget.cpp delete mode 100644 demos/sqlbrowser/connectionwidget.h delete mode 100644 demos/sqlbrowser/main.cpp delete mode 100644 demos/sqlbrowser/qsqlconnectiondialog.cpp delete mode 100644 demos/sqlbrowser/qsqlconnectiondialog.h delete mode 100644 demos/sqlbrowser/qsqlconnectiondialog.ui delete mode 100644 demos/sqlbrowser/sqlbrowser.pro delete mode 100644 demos/sub-attaq/animationmanager.cpp delete mode 100644 demos/sub-attaq/animationmanager.h delete mode 100644 demos/sub-attaq/boat.cpp delete mode 100644 demos/sub-attaq/boat.h delete mode 100644 demos/sub-attaq/boat_p.h delete mode 100644 demos/sub-attaq/bomb.cpp delete mode 100644 demos/sub-attaq/bomb.h delete mode 100644 demos/sub-attaq/data.xml delete mode 100644 demos/sub-attaq/graphicsscene.cpp delete mode 100644 demos/sub-attaq/graphicsscene.h delete mode 100644 demos/sub-attaq/main.cpp delete mode 100644 demos/sub-attaq/mainwindow.cpp delete mode 100644 demos/sub-attaq/mainwindow.h delete mode 100644 demos/sub-attaq/pics/big/background.png delete mode 100644 demos/sub-attaq/pics/big/boat.png delete mode 100644 demos/sub-attaq/pics/big/bomb.png delete mode 100644 demos/sub-attaq/pics/big/explosion/boat/step1.png delete mode 100644 demos/sub-attaq/pics/big/explosion/boat/step2.png delete mode 100644 demos/sub-attaq/pics/big/explosion/boat/step3.png delete mode 100644 demos/sub-attaq/pics/big/explosion/boat/step4.png delete mode 100644 demos/sub-attaq/pics/big/explosion/submarine/step1.png delete mode 100644 demos/sub-attaq/pics/big/explosion/submarine/step2.png delete mode 100644 demos/sub-attaq/pics/big/explosion/submarine/step3.png delete mode 100644 demos/sub-attaq/pics/big/explosion/submarine/step4.png delete mode 100644 demos/sub-attaq/pics/big/submarine.png delete mode 100644 demos/sub-attaq/pics/big/surface.png delete mode 100644 demos/sub-attaq/pics/big/torpedo.png delete mode 100644 demos/sub-attaq/pics/scalable/background-n810.svg delete mode 100644 demos/sub-attaq/pics/scalable/background.svg delete mode 100644 demos/sub-attaq/pics/scalable/boat.svg delete mode 100644 demos/sub-attaq/pics/scalable/bomb.svg delete mode 100644 demos/sub-attaq/pics/scalable/sand.svg delete mode 100644 demos/sub-attaq/pics/scalable/see.svg delete mode 100644 demos/sub-attaq/pics/scalable/sky.svg delete mode 100644 demos/sub-attaq/pics/scalable/sub-attaq.svg delete mode 100644 demos/sub-attaq/pics/scalable/submarine.svg delete mode 100644 demos/sub-attaq/pics/scalable/surface.svg delete mode 100644 demos/sub-attaq/pics/scalable/torpedo.svg delete mode 100644 demos/sub-attaq/pics/small/background.png delete mode 100644 demos/sub-attaq/pics/small/boat.png delete mode 100644 demos/sub-attaq/pics/small/bomb.png delete mode 100644 demos/sub-attaq/pics/small/submarine.png delete mode 100644 demos/sub-attaq/pics/small/surface.png delete mode 100644 demos/sub-attaq/pics/small/torpedo.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-a.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-a2.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-b.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-dash.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-excl.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-q.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-s.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-t.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-t2.png delete mode 100644 demos/sub-attaq/pics/welcome/logo-u.png delete mode 100644 demos/sub-attaq/pixmapitem.cpp delete mode 100644 demos/sub-attaq/pixmapitem.h delete mode 100644 demos/sub-attaq/progressitem.cpp delete mode 100644 demos/sub-attaq/progressitem.h delete mode 100644 demos/sub-attaq/qanimationstate.cpp delete mode 100644 demos/sub-attaq/qanimationstate.h delete mode 100644 demos/sub-attaq/states.cpp delete mode 100644 demos/sub-attaq/states.h delete mode 100644 demos/sub-attaq/sub-attaq.pro delete mode 100644 demos/sub-attaq/subattaq.qrc delete mode 100644 demos/sub-attaq/submarine.cpp delete mode 100644 demos/sub-attaq/submarine.h delete mode 100644 demos/sub-attaq/submarine_p.h delete mode 100644 demos/sub-attaq/textinformationitem.cpp delete mode 100644 demos/sub-attaq/textinformationitem.h delete mode 100644 demos/sub-attaq/torpedo.cpp delete mode 100644 demos/sub-attaq/torpedo.h delete mode 100644 demos/textedit/example.html delete mode 100644 demos/textedit/images/logo32.png delete mode 100644 demos/textedit/images/mac/editcopy.png delete mode 100644 demos/textedit/images/mac/editcut.png delete mode 100644 demos/textedit/images/mac/editpaste.png delete mode 100644 demos/textedit/images/mac/editredo.png delete mode 100644 demos/textedit/images/mac/editundo.png delete mode 100644 demos/textedit/images/mac/exportpdf.png delete mode 100644 demos/textedit/images/mac/filenew.png delete mode 100644 demos/textedit/images/mac/fileopen.png delete mode 100644 demos/textedit/images/mac/fileprint.png delete mode 100644 demos/textedit/images/mac/filesave.png delete mode 100644 demos/textedit/images/mac/textbold.png delete mode 100644 demos/textedit/images/mac/textcenter.png delete mode 100644 demos/textedit/images/mac/textitalic.png delete mode 100644 demos/textedit/images/mac/textjustify.png delete mode 100644 demos/textedit/images/mac/textleft.png delete mode 100644 demos/textedit/images/mac/textright.png delete mode 100644 demos/textedit/images/mac/textunder.png delete mode 100644 demos/textedit/images/mac/zoomin.png delete mode 100644 demos/textedit/images/mac/zoomout.png delete mode 100644 demos/textedit/images/win/editcopy.png delete mode 100644 demos/textedit/images/win/editcut.png delete mode 100644 demos/textedit/images/win/editpaste.png delete mode 100644 demos/textedit/images/win/editredo.png delete mode 100644 demos/textedit/images/win/editundo.png delete mode 100644 demos/textedit/images/win/exportpdf.png delete mode 100644 demos/textedit/images/win/filenew.png delete mode 100644 demos/textedit/images/win/fileopen.png delete mode 100644 demos/textedit/images/win/fileprint.png delete mode 100644 demos/textedit/images/win/filesave.png delete mode 100644 demos/textedit/images/win/textbold.png delete mode 100644 demos/textedit/images/win/textcenter.png delete mode 100644 demos/textedit/images/win/textitalic.png delete mode 100644 demos/textedit/images/win/textjustify.png delete mode 100644 demos/textedit/images/win/textleft.png delete mode 100644 demos/textedit/images/win/textright.png delete mode 100644 demos/textedit/images/win/textunder.png delete mode 100644 demos/textedit/images/win/zoomin.png delete mode 100644 demos/textedit/images/win/zoomout.png delete mode 100644 demos/textedit/main.cpp delete mode 100644 demos/textedit/textedit.cpp delete mode 100644 demos/textedit/textedit.h delete mode 100644 demos/textedit/textedit.pro delete mode 100644 demos/textedit/textedit.qdoc delete mode 100644 demos/textedit/textedit.qrc delete mode 100644 demos/undo/commands.cpp delete mode 100644 demos/undo/commands.h delete mode 100644 demos/undo/document.cpp delete mode 100644 demos/undo/document.h delete mode 100644 demos/undo/icons/background.png delete mode 100644 demos/undo/icons/blue.png delete mode 100644 demos/undo/icons/circle.png delete mode 100644 demos/undo/icons/exit.png delete mode 100644 demos/undo/icons/fileclose.png delete mode 100644 demos/undo/icons/filenew.png delete mode 100644 demos/undo/icons/fileopen.png delete mode 100644 demos/undo/icons/filesave.png delete mode 100644 demos/undo/icons/green.png delete mode 100644 demos/undo/icons/ok.png delete mode 100644 demos/undo/icons/rectangle.png delete mode 100644 demos/undo/icons/red.png delete mode 100644 demos/undo/icons/redo.png delete mode 100644 demos/undo/icons/remove.png delete mode 100644 demos/undo/icons/triangle.png delete mode 100644 demos/undo/icons/undo.png delete mode 100644 demos/undo/main.cpp delete mode 100644 demos/undo/mainwindow.cpp delete mode 100644 demos/undo/mainwindow.h delete mode 100644 demos/undo/mainwindow.ui delete mode 100644 demos/undo/undo.pro delete mode 100644 demos/undo/undo.qrc create mode 100644 examples/animation/sub-attaq/animationmanager.cpp create mode 100644 examples/animation/sub-attaq/animationmanager.h create mode 100644 examples/animation/sub-attaq/boat.cpp create mode 100644 examples/animation/sub-attaq/boat.h create mode 100644 examples/animation/sub-attaq/boat_p.h create mode 100644 examples/animation/sub-attaq/bomb.cpp create mode 100644 examples/animation/sub-attaq/bomb.h create mode 100644 examples/animation/sub-attaq/data.xml create mode 100644 examples/animation/sub-attaq/graphicsscene.cpp create mode 100644 examples/animation/sub-attaq/graphicsscene.h create mode 100644 examples/animation/sub-attaq/main.cpp create mode 100644 examples/animation/sub-attaq/mainwindow.cpp create mode 100644 examples/animation/sub-attaq/mainwindow.h create mode 100644 examples/animation/sub-attaq/pics/big/background.png create mode 100644 examples/animation/sub-attaq/pics/big/boat.png create mode 100644 examples/animation/sub-attaq/pics/big/bomb.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step1.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step2.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step3.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step4.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png create mode 100644 examples/animation/sub-attaq/pics/big/submarine.png create mode 100644 examples/animation/sub-attaq/pics/big/surface.png create mode 100644 examples/animation/sub-attaq/pics/big/torpedo.png create mode 100644 examples/animation/sub-attaq/pics/scalable/background-n810.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/background.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/boat.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/bomb.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/sand.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/see.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/sky.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/sub-attaq.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/submarine.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/surface.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/torpedo.svg create mode 100644 examples/animation/sub-attaq/pics/small/background.png create mode 100644 examples/animation/sub-attaq/pics/small/boat.png create mode 100644 examples/animation/sub-attaq/pics/small/bomb.png create mode 100644 examples/animation/sub-attaq/pics/small/submarine.png create mode 100644 examples/animation/sub-attaq/pics/small/surface.png create mode 100644 examples/animation/sub-attaq/pics/small/torpedo.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-a.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-a2.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-b.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-dash.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-excl.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-q.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-s.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-t.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-t2.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-u.png create mode 100644 examples/animation/sub-attaq/pixmapitem.cpp create mode 100644 examples/animation/sub-attaq/pixmapitem.h create mode 100644 examples/animation/sub-attaq/progressitem.cpp create mode 100644 examples/animation/sub-attaq/progressitem.h create mode 100644 examples/animation/sub-attaq/qanimationstate.cpp create mode 100644 examples/animation/sub-attaq/qanimationstate.h create mode 100644 examples/animation/sub-attaq/states.cpp create mode 100644 examples/animation/sub-attaq/states.h create mode 100644 examples/animation/sub-attaq/sub-attaq.pro create mode 100644 examples/animation/sub-attaq/subattaq.qrc create mode 100644 examples/animation/sub-attaq/submarine.cpp create mode 100644 examples/animation/sub-attaq/submarine.h create mode 100644 examples/animation/sub-attaq/submarine_p.h create mode 100644 examples/animation/sub-attaq/textinformationitem.cpp create mode 100644 examples/animation/sub-attaq/textinformationitem.h create mode 100644 examples/animation/sub-attaq/torpedo.cpp create mode 100644 examples/animation/sub-attaq/torpedo.h create mode 100644 examples/embedded/digiflip/digiflip.cpp create mode 100644 examples/embedded/digiflip/digiflip.pro create mode 100644 examples/embedded/embedded.pro create mode 100644 examples/embedded/flickable/flickable.cpp create mode 100644 examples/embedded/flickable/flickable.h create mode 100644 examples/embedded/flickable/flickable.pro create mode 100644 examples/embedded/flickable/main.cpp create mode 100644 examples/embedded/flightinfo/aircraft.png create mode 100644 examples/embedded/flightinfo/flightinfo.cpp create mode 100644 examples/embedded/flightinfo/flightinfo.pro create mode 100644 examples/embedded/flightinfo/flightinfo.qrc create mode 100644 examples/embedded/flightinfo/form.ui create mode 100644 examples/embedded/lightmaps/lightmaps.cpp create mode 100644 examples/embedded/lightmaps/lightmaps.h create mode 100644 examples/embedded/lightmaps/lightmaps.pro create mode 100644 examples/embedded/lightmaps/main.cpp create mode 100644 examples/embedded/lightmaps/mapzoom.cpp create mode 100644 examples/embedded/lightmaps/mapzoom.h create mode 100644 examples/embedded/lightmaps/slippymap.cpp create mode 100644 examples/embedded/lightmaps/slippymap.h create mode 100644 examples/embedded/raycasting/raycasting.cpp create mode 100644 examples/embedded/raycasting/raycasting.pro create mode 100644 examples/embedded/raycasting/raycasting.qrc create mode 100644 examples/embedded/raycasting/textures.png create mode 100755 examples/embedded/styledemo/files/add.png create mode 100644 examples/embedded/styledemo/files/application.qss create mode 100644 examples/embedded/styledemo/files/blue.qss create mode 100644 examples/embedded/styledemo/files/khaki.qss create mode 100644 examples/embedded/styledemo/files/nature_1.jpg create mode 100644 examples/embedded/styledemo/files/nostyle.qss create mode 100755 examples/embedded/styledemo/files/remove.png create mode 100644 examples/embedded/styledemo/files/transparent.qss create mode 100644 examples/embedded/styledemo/main.cpp create mode 100644 examples/embedded/styledemo/styledemo.pro create mode 100644 examples/embedded/styledemo/styledemo.qrc create mode 100644 examples/embedded/styledemo/stylewidget.cpp create mode 100644 examples/embedded/styledemo/stylewidget.h create mode 100644 examples/embedded/styledemo/stylewidget.ui create mode 100644 examples/graphicsview/boxes/3rdparty/fbm.c create mode 100644 examples/graphicsview/boxes/3rdparty/fbm.h create mode 100644 examples/graphicsview/boxes/basic.fsh create mode 100644 examples/graphicsview/boxes/basic.vsh create mode 100644 examples/graphicsview/boxes/boxes.pro create mode 100644 examples/graphicsview/boxes/boxes.qrc create mode 100644 examples/graphicsview/boxes/cubemap_negx.jpg create mode 100644 examples/graphicsview/boxes/cubemap_negy.jpg create mode 100644 examples/graphicsview/boxes/cubemap_negz.jpg create mode 100644 examples/graphicsview/boxes/cubemap_posx.jpg create mode 100644 examples/graphicsview/boxes/cubemap_posy.jpg create mode 100644 examples/graphicsview/boxes/cubemap_posz.jpg create mode 100644 examples/graphicsview/boxes/dotted.fsh create mode 100644 examples/graphicsview/boxes/fresnel.fsh create mode 100644 examples/graphicsview/boxes/glass.fsh create mode 100644 examples/graphicsview/boxes/glbuffers.cpp create mode 100644 examples/graphicsview/boxes/glbuffers.h create mode 100644 examples/graphicsview/boxes/glextensions.cpp create mode 100644 examples/graphicsview/boxes/glextensions.h create mode 100644 examples/graphicsview/boxes/gltrianglemesh.h create mode 100644 examples/graphicsview/boxes/granite.fsh create mode 100644 examples/graphicsview/boxes/main.cpp create mode 100644 examples/graphicsview/boxes/marble.fsh create mode 100644 examples/graphicsview/boxes/parameters.par create mode 100644 examples/graphicsview/boxes/qt-logo.jpg create mode 100644 examples/graphicsview/boxes/qt-logo.png create mode 100644 examples/graphicsview/boxes/qtbox.cpp create mode 100644 examples/graphicsview/boxes/qtbox.h create mode 100644 examples/graphicsview/boxes/reflection.fsh create mode 100644 examples/graphicsview/boxes/refraction.fsh create mode 100644 examples/graphicsview/boxes/roundedbox.cpp create mode 100644 examples/graphicsview/boxes/roundedbox.h create mode 100644 examples/graphicsview/boxes/scene.cpp create mode 100644 examples/graphicsview/boxes/scene.h create mode 100644 examples/graphicsview/boxes/smiley.png create mode 100644 examples/graphicsview/boxes/square.jpg create mode 100644 examples/graphicsview/boxes/trackball.cpp create mode 100644 examples/graphicsview/boxes/trackball.h create mode 100644 examples/graphicsview/boxes/wood.fsh create mode 100644 examples/graphicsview/chip/chip.cpp create mode 100644 examples/graphicsview/chip/chip.h create mode 100644 examples/graphicsview/chip/chip.pro create mode 100644 examples/graphicsview/chip/fileprint.png create mode 100644 examples/graphicsview/chip/images.qrc create mode 100644 examples/graphicsview/chip/main.cpp create mode 100644 examples/graphicsview/chip/mainwindow.cpp create mode 100644 examples/graphicsview/chip/mainwindow.h create mode 100644 examples/graphicsview/chip/qt4logo.png create mode 100644 examples/graphicsview/chip/rotateleft.png create mode 100644 examples/graphicsview/chip/rotateright.png create mode 100644 examples/graphicsview/chip/view.cpp create mode 100644 examples/graphicsview/chip/view.h create mode 100644 examples/graphicsview/chip/zoomin.png create mode 100644 examples/graphicsview/chip/zoomout.png create mode 100644 examples/graphicsview/embeddeddialogs/No-Ones-Laughing-3.jpg create mode 100644 examples/graphicsview/embeddeddialogs/customproxy.cpp create mode 100644 examples/graphicsview/embeddeddialogs/customproxy.h create mode 100644 examples/graphicsview/embeddeddialogs/embeddeddialog.cpp create mode 100644 examples/graphicsview/embeddeddialogs/embeddeddialog.h create mode 100644 examples/graphicsview/embeddeddialogs/embeddeddialog.ui create mode 100644 examples/graphicsview/embeddeddialogs/embeddeddialogs.pro create mode 100644 examples/graphicsview/embeddeddialogs/embeddeddialogs.qrc create mode 100644 examples/graphicsview/embeddeddialogs/main.cpp create mode 100644 examples/itemviews/interview/README create mode 100644 examples/itemviews/interview/images/folder.png create mode 100644 examples/itemviews/interview/images/interview.png create mode 100644 examples/itemviews/interview/images/services.png create mode 100644 examples/itemviews/interview/interview.pro create mode 100644 examples/itemviews/interview/interview.qrc create mode 100644 examples/itemviews/interview/main.cpp create mode 100644 examples/itemviews/interview/model.cpp create mode 100644 examples/itemviews/interview/model.h create mode 100644 examples/itemviews/spreadsheet/images/interview.png create mode 100644 examples/itemviews/spreadsheet/main.cpp create mode 100644 examples/itemviews/spreadsheet/printview.cpp create mode 100644 examples/itemviews/spreadsheet/printview.h create mode 100644 examples/itemviews/spreadsheet/spreadsheet.cpp create mode 100644 examples/itemviews/spreadsheet/spreadsheet.h create mode 100644 examples/itemviews/spreadsheet/spreadsheet.pro create mode 100644 examples/itemviews/spreadsheet/spreadsheet.qrc create mode 100644 examples/itemviews/spreadsheet/spreadsheetdelegate.cpp create mode 100644 examples/itemviews/spreadsheet/spreadsheetdelegate.h create mode 100644 examples/itemviews/spreadsheet/spreadsheetitem.cpp create mode 100644 examples/itemviews/spreadsheet/spreadsheetitem.h create mode 100644 examples/mainwindows/macmainwindow/macmainwindow.h create mode 100644 examples/mainwindows/macmainwindow/macmainwindow.mm create mode 100644 examples/mainwindows/macmainwindow/macmainwindow.pro create mode 100644 examples/mainwindows/macmainwindow/main.cpp create mode 100644 examples/mainwindows/mainwindow/colorswatch.cpp create mode 100644 examples/mainwindows/mainwindow/colorswatch.h create mode 100644 examples/mainwindows/mainwindow/main.cpp create mode 100644 examples/mainwindows/mainwindow/mainwindow.cpp create mode 100644 examples/mainwindows/mainwindow/mainwindow.h create mode 100644 examples/mainwindows/mainwindow/mainwindow.pro create mode 100644 examples/mainwindows/mainwindow/mainwindow.qrc create mode 100644 examples/mainwindows/mainwindow/qt.png create mode 100644 examples/mainwindows/mainwindow/titlebarCenter.png create mode 100644 examples/mainwindows/mainwindow/titlebarLeft.png create mode 100644 examples/mainwindows/mainwindow/titlebarRight.png create mode 100644 examples/mainwindows/mainwindow/toolbar.cpp create mode 100644 examples/mainwindows/mainwindow/toolbar.h create mode 100644 examples/painting/composition/composition.cpp create mode 100644 examples/painting/composition/composition.h create mode 100644 examples/painting/composition/composition.html create mode 100644 examples/painting/composition/composition.pro create mode 100644 examples/painting/composition/composition.qrc create mode 100644 examples/painting/composition/flower.jpg create mode 100644 examples/painting/composition/flower_alpha.jpg create mode 100644 examples/painting/composition/main.cpp create mode 100644 examples/painting/deform/deform.pro create mode 100644 examples/painting/deform/deform.qrc create mode 100644 examples/painting/deform/main.cpp create mode 100644 examples/painting/deform/pathdeform.cpp create mode 100644 examples/painting/deform/pathdeform.h create mode 100644 examples/painting/deform/pathdeform.html create mode 100644 examples/painting/gradients/gradients.cpp create mode 100644 examples/painting/gradients/gradients.h create mode 100644 examples/painting/gradients/gradients.html create mode 100644 examples/painting/gradients/gradients.pro create mode 100644 examples/painting/gradients/gradients.qrc create mode 100644 examples/painting/gradients/main.cpp create mode 100644 examples/painting/pathstroke/main.cpp create mode 100644 examples/painting/pathstroke/pathstroke.cpp create mode 100644 examples/painting/pathstroke/pathstroke.h create mode 100644 examples/painting/pathstroke/pathstroke.html create mode 100644 examples/painting/pathstroke/pathstroke.pro create mode 100644 examples/painting/pathstroke/pathstroke.qrc create mode 100644 examples/painting/shared/arthurstyle.cpp create mode 100644 examples/painting/shared/arthurstyle.h create mode 100644 examples/painting/shared/arthurwidgets.cpp create mode 100644 examples/painting/shared/arthurwidgets.h create mode 100644 examples/painting/shared/hoverpoints.cpp create mode 100644 examples/painting/shared/hoverpoints.h create mode 100644 examples/painting/shared/images/bg_pattern.png create mode 100644 examples/painting/shared/images/button_normal_cap_left.png create mode 100644 examples/painting/shared/images/button_normal_cap_right.png create mode 100644 examples/painting/shared/images/button_normal_stretch.png create mode 100644 examples/painting/shared/images/button_pressed_cap_left.png create mode 100644 examples/painting/shared/images/button_pressed_cap_right.png create mode 100644 examples/painting/shared/images/button_pressed_stretch.png create mode 100644 examples/painting/shared/images/curve_thing_edit-6.png create mode 100644 examples/painting/shared/images/frame_bottom.png create mode 100644 examples/painting/shared/images/frame_bottomleft.png create mode 100644 examples/painting/shared/images/frame_bottomright.png create mode 100644 examples/painting/shared/images/frame_left.png create mode 100644 examples/painting/shared/images/frame_right.png create mode 100644 examples/painting/shared/images/frame_top.png create mode 100644 examples/painting/shared/images/frame_topleft.png create mode 100644 examples/painting/shared/images/frame_topright.png create mode 100644 examples/painting/shared/images/groupframe_bottom_left.png create mode 100644 examples/painting/shared/images/groupframe_bottom_right.png create mode 100644 examples/painting/shared/images/groupframe_bottom_stretch.png create mode 100644 examples/painting/shared/images/groupframe_left_stretch.png create mode 100644 examples/painting/shared/images/groupframe_right_stretch.png create mode 100644 examples/painting/shared/images/groupframe_top_stretch.png create mode 100644 examples/painting/shared/images/groupframe_topleft.png create mode 100644 examples/painting/shared/images/groupframe_topright.png create mode 100644 examples/painting/shared/images/line_dash_dot.png create mode 100644 examples/painting/shared/images/line_dash_dot_dot.png create mode 100644 examples/painting/shared/images/line_dashed.png create mode 100644 examples/painting/shared/images/line_dotted.png create mode 100644 examples/painting/shared/images/line_solid.png create mode 100644 examples/painting/shared/images/radiobutton-off.png create mode 100644 examples/painting/shared/images/radiobutton-on.png create mode 100644 examples/painting/shared/images/radiobutton_off.png create mode 100644 examples/painting/shared/images/radiobutton_on.png create mode 100644 examples/painting/shared/images/slider_bar.png create mode 100644 examples/painting/shared/images/slider_thumb_off.png create mode 100644 examples/painting/shared/images/slider_thumb_on.png create mode 100644 examples/painting/shared/images/title_cap_left.png create mode 100644 examples/painting/shared/images/title_cap_right.png create mode 100644 examples/painting/shared/images/title_stretch.png create mode 100644 examples/painting/shared/shared.pri create mode 100644 examples/painting/shared/shared.pro create mode 100644 examples/painting/shared/shared.qrc create mode 100644 examples/richtext/textedit/example.html create mode 100644 examples/richtext/textedit/images/logo32.png create mode 100644 examples/richtext/textedit/images/mac/editcopy.png create mode 100644 examples/richtext/textedit/images/mac/editcut.png create mode 100644 examples/richtext/textedit/images/mac/editpaste.png create mode 100644 examples/richtext/textedit/images/mac/editredo.png create mode 100644 examples/richtext/textedit/images/mac/editundo.png create mode 100644 examples/richtext/textedit/images/mac/exportpdf.png create mode 100644 examples/richtext/textedit/images/mac/filenew.png create mode 100644 examples/richtext/textedit/images/mac/fileopen.png create mode 100644 examples/richtext/textedit/images/mac/fileprint.png create mode 100644 examples/richtext/textedit/images/mac/filesave.png create mode 100644 examples/richtext/textedit/images/mac/textbold.png create mode 100644 examples/richtext/textedit/images/mac/textcenter.png create mode 100644 examples/richtext/textedit/images/mac/textitalic.png create mode 100644 examples/richtext/textedit/images/mac/textjustify.png create mode 100644 examples/richtext/textedit/images/mac/textleft.png create mode 100644 examples/richtext/textedit/images/mac/textright.png create mode 100644 examples/richtext/textedit/images/mac/textunder.png create mode 100644 examples/richtext/textedit/images/mac/zoomin.png create mode 100644 examples/richtext/textedit/images/mac/zoomout.png create mode 100644 examples/richtext/textedit/images/win/editcopy.png create mode 100644 examples/richtext/textedit/images/win/editcut.png create mode 100644 examples/richtext/textedit/images/win/editpaste.png create mode 100644 examples/richtext/textedit/images/win/editredo.png create mode 100644 examples/richtext/textedit/images/win/editundo.png create mode 100644 examples/richtext/textedit/images/win/exportpdf.png create mode 100644 examples/richtext/textedit/images/win/filenew.png create mode 100644 examples/richtext/textedit/images/win/fileopen.png create mode 100644 examples/richtext/textedit/images/win/fileprint.png create mode 100644 examples/richtext/textedit/images/win/filesave.png create mode 100644 examples/richtext/textedit/images/win/textbold.png create mode 100644 examples/richtext/textedit/images/win/textcenter.png create mode 100644 examples/richtext/textedit/images/win/textitalic.png create mode 100644 examples/richtext/textedit/images/win/textjustify.png create mode 100644 examples/richtext/textedit/images/win/textleft.png create mode 100644 examples/richtext/textedit/images/win/textright.png create mode 100644 examples/richtext/textedit/images/win/textunder.png create mode 100644 examples/richtext/textedit/images/win/zoomin.png create mode 100644 examples/richtext/textedit/images/win/zoomout.png create mode 100644 examples/richtext/textedit/main.cpp create mode 100644 examples/richtext/textedit/textedit.cpp create mode 100644 examples/richtext/textedit/textedit.h create mode 100644 examples/richtext/textedit/textedit.pro create mode 100644 examples/richtext/textedit/textedit.qdoc create mode 100644 examples/richtext/textedit/textedit.qrc create mode 100644 examples/sql/books/bookdelegate.cpp create mode 100644 examples/sql/books/bookdelegate.h create mode 100644 examples/sql/books/books.pro create mode 100644 examples/sql/books/books.qrc create mode 100644 examples/sql/books/bookwindow.cpp create mode 100644 examples/sql/books/bookwindow.h create mode 100644 examples/sql/books/bookwindow.ui create mode 100644 examples/sql/books/images/star.png create mode 100644 examples/sql/books/initdb.h create mode 100644 examples/sql/books/main.cpp create mode 100644 examples/sql/sqlbrowser/browser.cpp create mode 100644 examples/sql/sqlbrowser/browser.h create mode 100644 examples/sql/sqlbrowser/browserwidget.ui create mode 100644 examples/sql/sqlbrowser/connectionwidget.cpp create mode 100644 examples/sql/sqlbrowser/connectionwidget.h create mode 100644 examples/sql/sqlbrowser/main.cpp create mode 100644 examples/sql/sqlbrowser/qsqlconnectiondialog.cpp create mode 100644 examples/sql/sqlbrowser/qsqlconnectiondialog.h create mode 100644 examples/sql/sqlbrowser/qsqlconnectiondialog.ui create mode 100644 examples/sql/sqlbrowser/sqlbrowser.pro create mode 100644 examples/tools/undo/commands.cpp create mode 100644 examples/tools/undo/commands.h create mode 100644 examples/tools/undo/document.cpp create mode 100644 examples/tools/undo/document.h create mode 100644 examples/tools/undo/icons/background.png create mode 100644 examples/tools/undo/icons/blue.png create mode 100644 examples/tools/undo/icons/circle.png create mode 100644 examples/tools/undo/icons/exit.png create mode 100644 examples/tools/undo/icons/fileclose.png create mode 100644 examples/tools/undo/icons/filenew.png create mode 100644 examples/tools/undo/icons/fileopen.png create mode 100644 examples/tools/undo/icons/filesave.png create mode 100644 examples/tools/undo/icons/green.png create mode 100644 examples/tools/undo/icons/ok.png create mode 100644 examples/tools/undo/icons/rectangle.png create mode 100644 examples/tools/undo/icons/red.png create mode 100644 examples/tools/undo/icons/redo.png create mode 100644 examples/tools/undo/icons/remove.png create mode 100644 examples/tools/undo/icons/triangle.png create mode 100644 examples/tools/undo/icons/undo.png create mode 100644 examples/tools/undo/main.cpp create mode 100644 examples/tools/undo/mainwindow.cpp create mode 100644 examples/tools/undo/mainwindow.h create mode 100644 examples/tools/undo/mainwindow.ui create mode 100644 examples/tools/undo/undo.pro create mode 100644 examples/tools/undo/undo.qrc diff --git a/demos/README b/demos/README deleted file mode 100644 index b1619908e2..0000000000 --- a/demos/README +++ /dev/null @@ -1,39 +0,0 @@ -These demonstrations are intended to highlight Qt's capabilities in different -application areas, and provide examples that are more advanced than those in -the examples directory. - -Beginners to Qt may wish to try out the Qt tutorial and some of the examples -before examining the demonstrations in detail. - - -The example launcher can be used to explore the different categories -available. It provides an overview of each example, lets you view the -documentation in Qt Assistant, and is able to launch examples. - - -Finding the Qt Examples and Demos launcher -========================================== - -On Windows: - -The launcher can be accessed via the Windows Start menu. Select the menu -entry entitled "Qt Examples and Demos" entry in the submenu containing -the Qt tools. - -On Mac OS X: - -For the binary distribution, the qtdemo executable is installed in the -/Developer/Applications/Qt directory. For the source distribution, it is -installed alongside the other Qt tools on the path specified when Qt is -configured. - -On Unix/Linux: - -The qtdemo executable is installed alongside the other Qt tools on the path -specified when Qt is configured. - -On all platforms: - -The source code for the launcher can be found in the demos/qtdemo directory -in the Qt package. This example is built at the same time as the Qt libraries, -tools, examples, and demonstrations. diff --git a/demos/books/bookdelegate.cpp b/demos/books/bookdelegate.cpp deleted file mode 100644 index 566dd81928..0000000000 --- a/demos/books/bookdelegate.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "bookdelegate.h" - -#include - -BookDelegate::BookDelegate(QObject *parent) - : QSqlRelationalDelegate(parent), star(QPixmap(":images/star.png")) -{ -} - -void BookDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const -{ - if (index.column() != 5) { - QStyleOptionViewItemV3 opt = option; - opt.rect.adjust(0, 0, -1, -1); // since we draw the grid ourselves - QSqlRelationalDelegate::paint(painter, opt, index); - } else { - const QAbstractItemModel *model = index.model(); - QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled) ? - (option.state & QStyle::State_Active) ? QPalette::Normal : QPalette::Inactive : QPalette::Disabled; - - if (option.state & QStyle::State_Selected) - painter->fillRect(option.rect, option.palette.color(cg, QPalette::Highlight)); - - int rating = model->data(index, Qt::DisplayRole).toInt(); - int width = star.width(); - int height = star.height(); - int x = option.rect.x(); - int y = option.rect.y() + (option.rect.height() / 2) - (height / 2); - for (int i = 0; i < rating; ++i) { - painter->drawPixmap(x, y, star); - x += width; - } - drawFocus(painter, option, option.rect.adjusted(0, 0, -1, -1)); // since we draw the grid ourselves - } - - QPen pen = painter->pen(); - painter->setPen(option.palette.color(QPalette::Mid)); - painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); - painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); - painter->setPen(pen); -} - -QSize BookDelegate::sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const -{ - if (index.column() == 5) - return QSize(5 * star.width(), star.height()) + QSize(1, 1); - - return QSqlRelationalDelegate::sizeHint(option, index) + QSize(1, 1); // since we draw the grid ourselves -} - -bool BookDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, - const QStyleOptionViewItem &option, - const QModelIndex &index) -{ - if (index.column() != 5) - return QSqlRelationalDelegate::editorEvent(event, model, option, index); - - if (event->type() == QEvent::MouseButtonPress) { - QMouseEvent *mouseEvent = static_cast(event); - int stars = qBound(0, int(0.7 + qreal(mouseEvent->pos().x() - - option.rect.x()) / star.width()), 5); - model->setData(index, QVariant(stars)); - return false; //so that the selection can change - } - - return true; -} - -QWidget *BookDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const -{ - if (index.column() != 4) - return QSqlRelationalDelegate::createEditor(parent, option, index); - - // for editing the year, return a spinbox with a range from -1000 to 2100. - QSpinBox *sb = new QSpinBox(parent); - sb->setFrame(false); - sb->setMaximum(2100); - sb->setMinimum(-1000); - - return sb; -} - diff --git a/demos/books/bookdelegate.h b/demos/books/bookdelegate.h deleted file mode 100644 index 5dc39c0223..0000000000 --- a/demos/books/bookdelegate.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef BOOKDELEGATE_H -#define BOOKDELEGATE_H - -#include -#include -#include -#include - -QT_FORWARD_DECLARE_CLASS(QPainter) - -class BookDelegate : public QSqlRelationalDelegate -{ -public: - BookDelegate(QObject *parent); - - void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const; - - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; - - bool editorEvent(QEvent *event, QAbstractItemModel *model, - const QStyleOptionViewItem &option, - const QModelIndex &index); - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const; - -private: - QPixmap star; -}; - -#endif diff --git a/demos/books/books.pro b/demos/books/books.pro deleted file mode 100644 index 1588288f3e..0000000000 --- a/demos/books/books.pro +++ /dev/null @@ -1,23 +0,0 @@ -TEMPLATE = app -INCLUDEPATH += . - -HEADERS = bookdelegate.h bookwindow.h initdb.h -RESOURCES = books.qrc -SOURCES = bookdelegate.cpp main.cpp bookwindow.cpp -FORMS = bookwindow.ui - -QT += sql - -target.path = $$[QT_INSTALL_DEMOS]/qtbase/books -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro images -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/books -INSTALLS += target sources - -symbian: CONFIG += qt_demo - -wince*: { - CONFIG(debug, debug|release):sqlPlugins.files = $$QT_BUILD_TREE/plugins/sqldrivers/*d4.dll - CONFIG(release, debug|release):sqlPlugins.files = $$QT_BUILD_TREE/plugins/sqldrivers/*[^d]4.dll - sqlPlugins.path = sqldrivers - DEPLOYMENT += sqlPlugins -} diff --git a/demos/books/books.qrc b/demos/books/books.qrc deleted file mode 100644 index 342638ecb0..0000000000 --- a/demos/books/books.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - images/star.png - - diff --git a/demos/books/bookwindow.cpp b/demos/books/bookwindow.cpp deleted file mode 100644 index 40d23d1761..0000000000 --- a/demos/books/bookwindow.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "bookwindow.h" -#include "bookdelegate.h" -#include "initdb.h" - -#include - -BookWindow::BookWindow() -{ - ui.setupUi(this); - - if (!QSqlDatabase::drivers().contains("QSQLITE")) - QMessageBox::critical(this, "Unable to load database", "This demo needs the SQLITE driver"); - - // initialize the database - QSqlError err = initDb(); - if (err.type() != QSqlError::NoError) { - showError(err); - return; - } - - // Create the data model - model = new QSqlRelationalTableModel(ui.bookTable); - model->setEditStrategy(QSqlTableModel::OnManualSubmit); - model->setTable("books"); - - // Remember the indexes of the columns - authorIdx = model->fieldIndex("author"); - genreIdx = model->fieldIndex("genre"); - - // Set the relations to the other database tables - model->setRelation(authorIdx, QSqlRelation("authors", "id", "name")); - model->setRelation(genreIdx, QSqlRelation("genres", "id", "name")); - - // Set the localized header captions - model->setHeaderData(authorIdx, Qt::Horizontal, tr("Author Name")); - model->setHeaderData(genreIdx, Qt::Horizontal, tr("Genre")); - model->setHeaderData(model->fieldIndex("title"), Qt::Horizontal, tr("Title")); - model->setHeaderData(model->fieldIndex("year"), Qt::Horizontal, tr("Year")); - model->setHeaderData(model->fieldIndex("rating"), Qt::Horizontal, tr("Rating")); - - // Populate the model - if (!model->select()) { - showError(model->lastError()); - return; - } - - // Set the model and hide the ID column - ui.bookTable->setModel(model); - ui.bookTable->setItemDelegate(new BookDelegate(ui.bookTable)); - ui.bookTable->setColumnHidden(model->fieldIndex("id"), true); - ui.bookTable->setSelectionMode(QAbstractItemView::SingleSelection); - - // Initialize the Author combo box - ui.authorEdit->setModel(model->relationModel(authorIdx)); - ui.authorEdit->setModelColumn(model->relationModel(authorIdx)->fieldIndex("name")); - - ui.genreEdit->setModel(model->relationModel(genreIdx)); - ui.genreEdit->setModelColumn(model->relationModel(genreIdx)->fieldIndex("name")); - - QDataWidgetMapper *mapper = new QDataWidgetMapper(this); - mapper->setModel(model); - mapper->setItemDelegate(new BookDelegate(this)); - mapper->addMapping(ui.titleEdit, model->fieldIndex("title")); - mapper->addMapping(ui.yearEdit, model->fieldIndex("year")); - mapper->addMapping(ui.authorEdit, authorIdx); - mapper->addMapping(ui.genreEdit, genreIdx); - mapper->addMapping(ui.ratingEdit, model->fieldIndex("rating")); - - connect(ui.bookTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), - mapper, SLOT(setCurrentModelIndex(QModelIndex))); - - ui.bookTable->setCurrentIndex(model->index(0, 0)); -} - -void BookWindow::showError(const QSqlError &err) -{ - QMessageBox::critical(this, "Unable to initialize Database", - "Error initializing database: " + err.text()); -} - diff --git a/demos/books/bookwindow.h b/demos/books/bookwindow.h deleted file mode 100644 index 4cd609650d..0000000000 --- a/demos/books/bookwindow.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef BOOKWINDOW_H -#define BOOKWINDOW_H - -#include -#include - -#include "ui_bookwindow.h" - - -class BookWindow: public QMainWindow -{ - Q_OBJECT -public: - BookWindow(); - -private: - void showError(const QSqlError &err); - Ui::BookWindow ui; - QSqlRelationalTableModel *model; - int authorIdx, genreIdx; -}; - -#endif diff --git a/demos/books/bookwindow.ui b/demos/books/bookwindow.ui deleted file mode 100644 index 659d324564..0000000000 --- a/demos/books/bookwindow.ui +++ /dev/null @@ -1,149 +0,0 @@ - - - - - BookWindow - - - - 0 - 0 - 601 - 420 - - - - Books - - - - - 9 - - - 6 - - - - - Books - - - - 9 - - - 6 - - - - - QAbstractItemView::SelectRows - - - - - - - Details - - - - - - <b>Title:</b> - - - - - - - true - - - - - - - <b>Author: </b> - - - - - - - true - - - - - - - <b>Genre:</b> - - - - - - - true - - - - - - - <b>Year:</b> - - - - - - - true - - - - - - 2100 - - - -1000 - - - - - - - <b>Rating:</b> - - - - - - - 5 - - - - - - - - - - - - - - - bookTable - titleEdit - authorEdit - genreEdit - yearEdit - - - - diff --git a/demos/books/images/star.png b/demos/books/images/star.png deleted file mode 100644 index 87f4464bd5..0000000000 Binary files a/demos/books/images/star.png and /dev/null differ diff --git a/demos/books/initdb.h b/demos/books/initdb.h deleted file mode 100644 index 9c9bebcba1..0000000000 --- a/demos/books/initdb.h +++ /dev/null @@ -1,125 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef INITDB_H -#define INITDB_H - -#include - -void addBook(QSqlQuery &q, const QString &title, int year, const QVariant &authorId, - const QVariant &genreId, int rating) -{ - q.addBindValue(title); - q.addBindValue(year); - q.addBindValue(authorId); - q.addBindValue(genreId); - q.addBindValue(rating); - q.exec(); -} - -QVariant addGenre(QSqlQuery &q, const QString &name) -{ - q.addBindValue(name); - q.exec(); - return q.lastInsertId(); -} - -QVariant addAuthor(QSqlQuery &q, const QString &name, const QDate &birthdate) -{ - q.addBindValue(name); - q.addBindValue(birthdate); - q.exec(); - return q.lastInsertId(); -} - -QSqlError initDb() -{ - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); - db.setDatabaseName(":memory:"); - - if (!db.open()) - return db.lastError(); - - QStringList tables = db.tables(); - if (tables.contains("books", Qt::CaseInsensitive) - && tables.contains("authors", Qt::CaseInsensitive)) - return QSqlError(); - - QSqlQuery q; - if (!q.exec(QLatin1String("create table books(id integer primary key, title varchar, author integer, genre integer, year integer, rating integer)"))) - return q.lastError(); - if (!q.exec(QLatin1String("create table authors(id integer primary key, name varchar, birthdate date)"))) - return q.lastError(); - if (!q.exec(QLatin1String("create table genres(id integer primary key, name varchar)"))) - return q.lastError(); - - if (!q.prepare(QLatin1String("insert into authors(name, birthdate) values(?, ?)"))) - return q.lastError(); - QVariant asimovId = addAuthor(q, QLatin1String("Isaac Asimov"), QDate(1920, 2, 1)); - QVariant greeneId = addAuthor(q, QLatin1String("Graham Greene"), QDate(1904, 10, 2)); - QVariant pratchettId = addAuthor(q, QLatin1String("Terry Pratchett"), QDate(1948, 4, 28)); - - if (!q.prepare(QLatin1String("insert into genres(name) values(?)"))) - return q.lastError(); - QVariant sfiction = addGenre(q, QLatin1String("Science Fiction")); - QVariant fiction = addGenre(q, QLatin1String("Fiction")); - QVariant fantasy = addGenre(q, QLatin1String("Fantasy")); - - if (!q.prepare(QLatin1String("insert into books(title, year, author, genre, rating) values(?, ?, ?, ?, ?)"))) - return q.lastError(); - addBook(q, QLatin1String("Foundation"), 1951, asimovId, sfiction, 3); - addBook(q, QLatin1String("Foundation and Empire"), 1952, asimovId, sfiction, 4); - addBook(q, QLatin1String("Second Foundation"), 1953, asimovId, sfiction, 3); - addBook(q, QLatin1String("Foundation's Edge"), 1982, asimovId, sfiction, 3); - addBook(q, QLatin1String("Foundation and Earth"), 1986, asimovId, sfiction, 4); - addBook(q, QLatin1String("Prelude to Foundation"), 1988, asimovId, sfiction, 3); - addBook(q, QLatin1String("Forward the Foundation"), 1993, asimovId, sfiction, 3); - addBook(q, QLatin1String("The Power and the Glory"), 1940, greeneId, fiction, 4); - addBook(q, QLatin1String("The Third Man"), 1950, greeneId, fiction, 5); - addBook(q, QLatin1String("Our Man in Havana"), 1958, greeneId, fiction, 4); - addBook(q, QLatin1String("Guards! Guards!"), 1989, pratchettId, fantasy, 3); - addBook(q, QLatin1String("Night Watch"), 2002, pratchettId, fantasy, 3); - addBook(q, QLatin1String("Going Postal"), 2004, pratchettId, fantasy, 3); - - return QSqlError(); -} - -#endif diff --git a/demos/books/main.cpp b/demos/books/main.cpp deleted file mode 100644 index 45aa8f87cf..0000000000 --- a/demos/books/main.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "bookwindow.h" - -#include - -int main(int argc, char * argv[]) -{ - Q_INIT_RESOURCE(books); - - QApplication app(argc, argv); - - BookWindow win; - win.show(); - - return app.exec(); -} diff --git a/demos/boxes/3rdparty/fbm.c b/demos/boxes/3rdparty/fbm.c deleted file mode 100644 index 98eb87a33b..0000000000 --- a/demos/boxes/3rdparty/fbm.c +++ /dev/null @@ -1,207 +0,0 @@ -/***************************************************************** - - Implementation of the fractional Brownian motion algorithm. These - functions were originally the work of F. Kenton Musgrave. - For documentation of the different functions please refer to the - book: - "Texturing and modeling: a procedural approach" - by David S. Ebert et. al. - -******************************************************************/ - -#if defined (_MSC_VER) -#include -#endif - -#include -#include -#include "fbm.h" - -#if defined(Q_CC_MSVC) -#pragma warning(disable:4244) -#endif - -/* Definitions used by the noise2() functions */ - -//#define B 0x100 -//#define BM 0xff -#define B 0x20 -#define BM 0x1f - -#define N 0x1000 -#define NP 12 /* 2^N */ -#define NM 0xfff - -static int p[B + B + 2]; -static float g3[B + B + 2][3]; -static float g2[B + B + 2][2]; -static float g1[B + B + 2]; -static int start = 1; - -static void init(void); - -#define s_curve(t) ( t * t * (3. - 2. * t) ) - -#define lerp(t, a, b) ( a + t * (b - a) ) - -#define setup(i,b0,b1,r0,r1)\ - t = vec[i] + N;\ - b0 = ((int)t) & BM;\ - b1 = (b0+1) & BM;\ - r0 = t - (int)t;\ - r1 = r0 - 1.; -#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) - -/* Fractional Brownian Motion function */ - -double fBm( Vector point, double H, double lacunarity, double octaves, - int init ) -{ - - double value, frequency, remainder; - int i; - static double exponent_array[10]; - float vec[3]; - - /* precompute and store spectral weights */ - if ( init ) { - start = 1; - srand( time(0) ); - /* seize required memory for exponent_array */ - frequency = 1.0; - for (i=0; i<=octaves; i++) { - /* compute weight for each frequency */ - exponent_array[i] = pow( frequency, -H ); - frequency *= lacunarity; - } - } - - value = 0.0; /* initialize vars to proper values */ - frequency = 1.0; - vec[0]=point.x; - vec[1]=point.y; - vec[2]=point.z; - - - /* inner loop of spectral construction */ - for (i=0; i - -#ifdef __cplusplus -extern "C" { -#endif - -//#define TRUE 1 -//#define FALSE 0 - -typedef struct { - double x; - double y; - double z; -} Vector; - -float noise3(float vec[]); -double fBm( Vector point, double H, double lacunarity, double octaves, - int init ); -#endif - -#ifdef __cplusplus -} -#endif - - - - diff --git a/demos/boxes/basic.fsh b/demos/boxes/basic.fsh deleted file mode 100644 index faf3601606..0000000000 --- a/demos/boxes/basic.fsh +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; -uniform vec4 basicColor; - -void main() -{ - vec3 N = normalize(normal); - // assume directional light - - gl_MaterialParameters M = gl_FrontMaterial; - - float NdotL = dot(N, lightDirection.xyz); - float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); - - vec3 absN = abs(gl_TexCoord[1].xyz); - vec3 texCoord; - if (absN.x > absN.y && absN.x > absN.z) - texCoord = gl_TexCoord[1].yzx; - else if (absN.y > absN.z) - texCoord = gl_TexCoord[1].zxy; - else - texCoord = gl_TexCoord[1].xyz; - texCoord.y *= -sign(texCoord.z); - texCoord += 0.5; - - vec4 texColor = texture2D(tex, texCoord.xy); - vec4 unlitColor = gl_Color * mix(basicColor, vec4(texColor.xyz, 1.0), texColor.w); - gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + - M.specular * specular * pow(max(RdotL, 0.0), M.shininess); -} diff --git a/demos/boxes/basic.vsh b/demos/boxes/basic.vsh deleted file mode 100644 index 31acc4224a..0000000000 --- a/demos/boxes/basic.vsh +++ /dev/null @@ -1,61 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform mat4 view; - -void main() -{ - gl_TexCoord[0] = gl_MultiTexCoord0; - gl_TexCoord[1] = gl_Vertex; - specular = gl_LightSource[0].specular; - ambient = gl_LightSource[0].ambient; - diffuse = gl_LightSource[0].diffuse; - lightDirection = view * gl_LightSource[0].position; - - normal = gl_NormalMatrix * gl_Normal; - position = (gl_ModelViewMatrix * gl_Vertex).xyz; - - gl_FrontColor = gl_Color; - gl_Position = ftransform(); -} diff --git a/demos/boxes/boxes.pro b/demos/boxes/boxes.pro deleted file mode 100644 index d599a3a0ac..0000000000 --- a/demos/boxes/boxes.pro +++ /dev/null @@ -1,49 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) ma 3. nov 17:33:30 2008 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -# Input -HEADERS += 3rdparty/fbm.h \ - glbuffers.h \ - glextensions.h \ - gltrianglemesh.h \ - qtbox.h \ - roundedbox.h \ - scene.h \ - trackball.h -SOURCES += 3rdparty/fbm.c \ - glbuffers.cpp \ - glextensions.cpp \ - main.cpp \ - qtbox.cpp \ - roundedbox.cpp \ - scene.cpp \ - trackball.cpp - -RESOURCES += boxes.qrc - -QT += opengl - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/boxes -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html *.jpg *.png *.fsh *.vsh *.par -sources.files -= 3rdparty/fbm.h 3rdparty/fbm.c -sources.files += 3rdparty -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/boxes -INSTALLS += target sources - -wince*: { - DEPLOYMENT_PLUGIN += qjpeg -} - -win32-msvc* { - QMAKE_CXXFLAGS -= -Zm200 - QMAKE_CFLAGS -= -Zm200 - QMAKE_CXXFLAGS += -Zm500 - QMAKE_CFLAGS += -Zm500 -} diff --git a/demos/boxes/boxes.qrc b/demos/boxes/boxes.qrc deleted file mode 100644 index d27506dc5a..0000000000 --- a/demos/boxes/boxes.qrc +++ /dev/null @@ -1,25 +0,0 @@ - - - cubemap_negx.jpg - cubemap_negy.jpg - cubemap_negz.jpg - cubemap_posx.jpg - cubemap_posy.jpg - cubemap_posz.jpg - square.jpg - basic.vsh - basic.fsh - dotted.fsh - fresnel.fsh - glass.fsh - granite.fsh - marble.fsh - reflection.fsh - refraction.fsh - wood.fsh - parameters.par - qt-logo.png - smiley.png - qt-logo.jpg - - diff --git a/demos/boxes/cubemap_negx.jpg b/demos/boxes/cubemap_negx.jpg deleted file mode 100644 index 07c282eab9..0000000000 Binary files a/demos/boxes/cubemap_negx.jpg and /dev/null differ diff --git a/demos/boxes/cubemap_negy.jpg b/demos/boxes/cubemap_negy.jpg deleted file mode 100644 index 46cd2f9cf3..0000000000 Binary files a/demos/boxes/cubemap_negy.jpg and /dev/null differ diff --git a/demos/boxes/cubemap_negz.jpg b/demos/boxes/cubemap_negz.jpg deleted file mode 100644 index 40c01ddff3..0000000000 Binary files a/demos/boxes/cubemap_negz.jpg and /dev/null differ diff --git a/demos/boxes/cubemap_posx.jpg b/demos/boxes/cubemap_posx.jpg deleted file mode 100644 index 0b42e8a1b1..0000000000 Binary files a/demos/boxes/cubemap_posx.jpg and /dev/null differ diff --git a/demos/boxes/cubemap_posy.jpg b/demos/boxes/cubemap_posy.jpg deleted file mode 100644 index 2aca9b1e98..0000000000 Binary files a/demos/boxes/cubemap_posy.jpg and /dev/null differ diff --git a/demos/boxes/cubemap_posz.jpg b/demos/boxes/cubemap_posz.jpg deleted file mode 100644 index 2e49173848..0000000000 Binary files a/demos/boxes/cubemap_posz.jpg and /dev/null differ diff --git a/demos/boxes/dotted.fsh b/demos/boxes/dotted.fsh deleted file mode 100644 index a9f1bcbefb..0000000000 --- a/demos/boxes/dotted.fsh +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; - -void main() -{ - vec3 N = normalize(normal); - - gl_MaterialParameters M = gl_FrontMaterial; - - // assume directional light - float NdotL = dot(N, lightDirection.xyz); - float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); - - float r1 = length(fract(7.0 * gl_TexCoord[1].xyz) - 0.5); - float r2 = length(fract(5.0 * gl_TexCoord[1].xyz + 0.2) - 0.5); - float r3 = length(fract(11.0 * gl_TexCoord[1].xyz + 0.7) - 0.5); - vec4 rs = vec4(r1, r2, r3, 0.0); - - vec4 unlitColor = gl_Color * (0.8 - clamp(10.0 * (0.4 - rs), 0.0, 0.2)); - unlitColor.w = 1.0; - gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + - M.specular * specular * pow(max(RdotL, 0.0), M.shininess); -} diff --git a/demos/boxes/fresnel.fsh b/demos/boxes/fresnel.fsh deleted file mode 100644 index 462f9674f4..0000000000 --- a/demos/boxes/fresnel.fsh +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; -uniform samplerCube env; -uniform mat4 view; -uniform vec4 basicColor; - -void main() -{ - vec3 N = normalize(normal); - // assume directional light - - gl_MaterialParameters M = gl_FrontMaterial; - - float NdotL = dot(N, lightDirection.xyz); - float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); - - vec3 absN = abs(gl_TexCoord[1].xyz); - vec3 texCoord; - if (absN.x > absN.y && absN.x > absN.z) - texCoord = gl_TexCoord[1].yzx; - else if (absN.y > absN.z) - texCoord = gl_TexCoord[1].zxy; - else - texCoord = gl_TexCoord[1].xyz; - texCoord.y *= -sign(texCoord.z); - texCoord += 0.5; - - vec4 texColor = texture2D(tex, texCoord.xy); - vec4 unlitColor = gl_Color * mix(basicColor, vec4(texColor.xyz, 1.0), texColor.w); - vec4 litColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + - M.specular * specular * pow(max(RdotL, 0.0), M.shininess); - - vec3 R = 2.0 * dot(-position, N) * N + position; - vec4 reflectedColor = textureCube(env, R * mat3(view[0].xyz, view[1].xyz, view[2].xyz)); - gl_FragColor = mix(litColor, reflectedColor, 0.2 + 0.8 * pow(1.0 + dot(N, normalize(position)), 2.0)); -} diff --git a/demos/boxes/glass.fsh b/demos/boxes/glass.fsh deleted file mode 100644 index aeac2c2fed..0000000000 --- a/demos/boxes/glass.fsh +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; -uniform samplerCube env; -uniform mat4 view; - -// Some arbitrary values -// Arrays don't work here on glsl < 120, apparently. -//const float coeffs[6] = float[6](1.0/4.0, 1.0/4.1, 1.0/4.2, 1.0/4.3, 1.0/4.4, 1.0/4.5); -float coeffs(int i) -{ - return 1.0 / (3.0 + 0.1 * float(i)); -} - -void main() -{ - vec3 N = normalize(normal); - vec3 I = -normalize(position); - mat3 V = mat3(view[0].xyz, view[1].xyz, view[2].xyz); - float IdotN = dot(I, N); - float scales[6]; - vec3 C[6]; - for (int i = 0; i < 6; ++i) { - scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN))); - C[i] = textureCube(env, (-I + coeffs(i) * N) * V).xyz; - } - vec4 refractedColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y, - C[3].z + 2.0*C[4].z + C[5].z, 4.0); - - vec3 R = 2.0 * dot(-position, N) * N + position; - vec4 reflectedColor = textureCube(env, R * V); - - gl_FragColor = mix(refractedColor, reflectedColor, 0.4 + 0.6 * pow(1.0 - IdotN, 2.0)); -} diff --git a/demos/boxes/glbuffers.cpp b/demos/boxes/glbuffers.cpp deleted file mode 100644 index e12132b4cd..0000000000 --- a/demos/boxes/glbuffers.cpp +++ /dev/null @@ -1,402 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "glbuffers.h" -#include - - -void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) -{ - const GLdouble ymax = zNear * tan(fovy * M_PI / 360.0); - const GLdouble ymin = -ymax; - const GLdouble xmin = ymin * aspect; - const GLdouble xmax = ymax * aspect; - glFrustum(xmin, xmax, ymin, ymax, zNear, zFar); -} - -//============================================================================// -// GLTexture // -//============================================================================// - -GLTexture::GLTexture() : m_texture(0), m_failed(false) -{ - glGenTextures(1, &m_texture); -} - -GLTexture::~GLTexture() -{ - glDeleteTextures(1, &m_texture); -} - -//============================================================================// -// GLTexture2D // -//============================================================================// - -GLTexture2D::GLTexture2D(int width, int height) -{ - glBindTexture(GL_TEXTURE_2D, m_texture); - glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, - GL_BGRA, GL_UNSIGNED_BYTE, 0); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); - glBindTexture(GL_TEXTURE_2D, 0); -} - - -GLTexture2D::GLTexture2D(const QString& fileName, int width, int height) -{ - // TODO: Add error handling. - QImage image(fileName); - - if (image.isNull()) { - m_failed = true; - return; - } - - image = image.convertToFormat(QImage::Format_ARGB32); - - //qDebug() << "Image size:" << image.width() << "x" << image.height(); - if (width <= 0) - width = image.width(); - if (height <= 0) - height = image.height(); - if (width != image.width() || height != image.height()) - image = image.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); - - glBindTexture(GL_TEXTURE_2D, m_texture); - - // Works on x86, so probably works on all little-endian systems. - // Does it work on big-endian systems? - glTexImage2D(GL_TEXTURE_2D, 0, 4, image.width(), image.height(), 0, - GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); - glBindTexture(GL_TEXTURE_2D, 0); -} - -void GLTexture2D::load(int width, int height, QRgb *data) -{ - glBindTexture(GL_TEXTURE_2D, m_texture); - glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, - GL_BGRA, GL_UNSIGNED_BYTE, data); - glBindTexture(GL_TEXTURE_2D, 0); -} - -void GLTexture2D::bind() -{ - glBindTexture(GL_TEXTURE_2D, m_texture); - glEnable(GL_TEXTURE_2D); -} - -void GLTexture2D::unbind() -{ - glBindTexture(GL_TEXTURE_2D, 0); - glDisable(GL_TEXTURE_2D); -} - - -//============================================================================// -// GLTexture3D // -//============================================================================// - -GLTexture3D::GLTexture3D(int width, int height, int depth) -{ - GLBUFFERS_ASSERT_OPENGL("GLTexture3D::GLTexture3D", glTexImage3D, return) - - glBindTexture(GL_TEXTURE_3D, m_texture); - glTexImage3D(GL_TEXTURE_3D, 0, 4, width, height, depth, 0, - GL_BGRA, GL_UNSIGNED_BYTE, 0); - - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - //glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - //glTexParameteri(GL_TEXTURE_3D, GL_GENERATE_MIPMAP, GL_TRUE); - glBindTexture(GL_TEXTURE_3D, 0); -} - -void GLTexture3D::load(int width, int height, int depth, QRgb *data) -{ - GLBUFFERS_ASSERT_OPENGL("GLTexture3D::load", glTexImage3D, return) - - glBindTexture(GL_TEXTURE_3D, m_texture); - glTexImage3D(GL_TEXTURE_3D, 0, 4, width, height, depth, 0, - GL_BGRA, GL_UNSIGNED_BYTE, data); - glBindTexture(GL_TEXTURE_3D, 0); -} - -void GLTexture3D::bind() -{ - glBindTexture(GL_TEXTURE_3D, m_texture); - glEnable(GL_TEXTURE_3D); -} - -void GLTexture3D::unbind() -{ - glBindTexture(GL_TEXTURE_3D, 0); - glDisable(GL_TEXTURE_3D); -} - -//============================================================================// -// GLTextureCube // -//============================================================================// - -GLTextureCube::GLTextureCube(int size) -{ - glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); - - for (int i = 0; i < 6; ++i) - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 4, size, size, 0, - GL_BGRA, GL_UNSIGNED_BYTE, 0); - - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE); - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -} - -GLTextureCube::GLTextureCube(const QStringList& fileNames, int size) -{ - // TODO: Add error handling. - - glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); - - int index = 0; - foreach (QString file, fileNames) { - QImage image(file); - if (image.isNull()) { - m_failed = true; - break; - } - - image = image.convertToFormat(QImage::Format_ARGB32); - - //qDebug() << "Image size:" << image.width() << "x" << image.height(); - if (size <= 0) - size = image.width(); - if (size != image.width() || size != image.height()) - image = image.scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); - - // Works on x86, so probably works on all little-endian systems. - // Does it work on big-endian systems? - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, 4, image.width(), image.height(), 0, - GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); - - if (++index == 6) - break; - } - - // Clear remaining faces. - while (index < 6) { - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, 4, size, size, 0, - GL_BGRA, GL_UNSIGNED_BYTE, 0); - ++index; - } - - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE); - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -} - -void GLTextureCube::load(int size, int face, QRgb *data) -{ - glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, 4, size, size, 0, - GL_BGRA, GL_UNSIGNED_BYTE, data); - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -} - -void GLTextureCube::bind() -{ - glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); - glEnable(GL_TEXTURE_CUBE_MAP); -} - -void GLTextureCube::unbind() -{ - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); - glDisable(GL_TEXTURE_CUBE_MAP); -} - -//============================================================================// -// GLFrameBufferObject // -//============================================================================// - -GLFrameBufferObject::GLFrameBufferObject(int width, int height) - : m_fbo(0) - , m_depthBuffer(0) - , m_width(width) - , m_height(height) - , m_failed(false) -{ - GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::GLFrameBufferObject", - glGenFramebuffersEXT && glGenRenderbuffersEXT && glBindRenderbufferEXT && glRenderbufferStorageEXT, return) - - // TODO: share depth buffers of same size - glGenFramebuffersEXT(1, &m_fbo); - //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); - glGenRenderbuffersEXT(1, &m_depthBuffer); - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthBuffer); - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, m_width, m_height); - //glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthBuffer); - //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); -} - -GLFrameBufferObject::~GLFrameBufferObject() -{ - GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::~GLFrameBufferObject", - glDeleteFramebuffersEXT && glDeleteRenderbuffersEXT, return) - - glDeleteFramebuffersEXT(1, &m_fbo); - glDeleteRenderbuffersEXT(1, &m_depthBuffer); -} - -void GLFrameBufferObject::setAsRenderTarget(bool state) -{ - GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::setAsRenderTarget", glBindFramebufferEXT, return) - - if (state) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); - glPushAttrib(GL_VIEWPORT_BIT); - glViewport(0, 0, m_width, m_height); - } else { - glPopAttrib(); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - } -} - -bool GLFrameBufferObject::isComplete() -{ - GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::isComplete", glCheckFramebufferStatusEXT, return false) - - return GL_FRAMEBUFFER_COMPLETE_EXT == glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); -} - -//============================================================================// -// GLRenderTargetCube // -//============================================================================// - -GLRenderTargetCube::GLRenderTargetCube(int size) - : GLTextureCube(size) - , m_fbo(size, size) -{ -} - -void GLRenderTargetCube::begin(int face) -{ - GLBUFFERS_ASSERT_OPENGL("GLRenderTargetCube::begin", - glFramebufferTexture2DEXT && glFramebufferRenderbufferEXT, return) - - m_fbo.setAsRenderTarget(true); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, - GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, m_texture, 0); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_fbo.m_depthBuffer); -} - -void GLRenderTargetCube::end() -{ - m_fbo.setAsRenderTarget(false); -} - -void GLRenderTargetCube::getViewMatrix(QMatrix4x4& mat, int face) -{ - if (face < 0 || face >= 6) { - qWarning("GLRenderTargetCube::getViewMatrix: 'face' must be in the range [0, 6). (face == %d)", face); - return; - } - - static int perm[6][3] = { - {2, 1, 0}, - {2, 1, 0}, - {0, 2, 1}, - {0, 2, 1}, - {0, 1, 2}, - {0, 1, 2}, - }; - - static float signs[6][3] = { - {-1.0f, -1.0f, -1.0f}, - {+1.0f, -1.0f, +1.0f}, - {+1.0f, +1.0f, -1.0f}, - {+1.0f, -1.0f, +1.0f}, - {+1.0f, -1.0f, -1.0f}, - {-1.0f, -1.0f, +1.0f}, - }; - - mat.fill(0.0f); - for (int i = 0; i < 3; ++i) - mat(i, perm[face][i]) = signs[face][i]; - mat(3, 3) = 1.0f; -} - -void GLRenderTargetCube::getProjectionMatrix(QMatrix4x4& mat, float nearZ, float farZ) -{ - static const QMatrix4x4 reference( - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, -1.0f, 0.0f); - - mat = reference; - mat(2, 2) = (nearZ+farZ)/(nearZ-farZ); - mat(2, 3) = 2.0f*nearZ*farZ/(nearZ-farZ); -} diff --git a/demos/boxes/glbuffers.h b/demos/boxes/glbuffers.h deleted file mode 100644 index 6b18d3f128..0000000000 --- a/demos/boxes/glbuffers.h +++ /dev/null @@ -1,366 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GLBUFFERS_H -#define GLBUFFERS_H - -//#include -#include "glextensions.h" - -#include -#include - -#define BUFFER_OFFSET(i) ((char*)0 + (i)) -#define SIZE_OF_MEMBER(cls, member) sizeof(static_cast(0)->member) - -#define GLBUFFERS_ASSERT_OPENGL(prefix, assertion, returnStatement) \ -if (m_failed || !(assertion)) { \ - if (!m_failed) qCritical(prefix ": The necessary OpenGL functions are not available."); \ - m_failed = true; \ - returnStatement; \ -} - -void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar); - -QT_BEGIN_NAMESPACE -class QMatrix4x4; -QT_END_NAMESPACE - -class GLTexture -{ -public: - GLTexture(); - virtual ~GLTexture(); - virtual void bind() = 0; - virtual void unbind() = 0; - virtual bool failed() const {return m_failed;} -protected: - GLuint m_texture; - bool m_failed; -}; - -class GLFrameBufferObject -{ -public: - friend class GLRenderTargetCube; - // friend class GLRenderTarget2D; - - GLFrameBufferObject(int width, int height); - virtual ~GLFrameBufferObject(); - bool isComplete(); - virtual bool failed() const {return m_failed;} -protected: - void setAsRenderTarget(bool state = true); - GLuint m_fbo; - GLuint m_depthBuffer; - int m_width, m_height; - bool m_failed; -}; - -class GLTexture2D : public GLTexture -{ -public: - GLTexture2D(int width, int height); - GLTexture2D(const QString& fileName, int width = 0, int height = 0); - void load(int width, int height, QRgb *data); - virtual void bind(); - virtual void unbind(); -}; - -class GLTexture3D : public GLTexture -{ -public: - GLTexture3D(int width, int height, int depth); - // TODO: Implement function below - //GLTexture3D(const QString& fileName, int width = 0, int height = 0); - void load(int width, int height, int depth, QRgb *data); - virtual void bind(); - virtual void unbind(); -}; - -class GLTextureCube : public GLTexture -{ -public: - GLTextureCube(int size); - GLTextureCube(const QStringList& fileNames, int size = 0); - void load(int size, int face, QRgb *data); - virtual void bind(); - virtual void unbind(); -}; - -// TODO: Define and implement class below -//class GLRenderTarget2D : public GLTexture2D - -class GLRenderTargetCube : public GLTextureCube -{ -public: - GLRenderTargetCube(int size); - // begin rendering to one of the cube's faces. 0 <= face < 6 - void begin(int face); - // end rendering - void end(); - virtual bool failed() {return m_failed || m_fbo.failed();} - - static void getViewMatrix(QMatrix4x4& mat, int face); - static void getProjectionMatrix(QMatrix4x4& mat, float nearZ, float farZ); -private: - GLFrameBufferObject m_fbo; -}; - -struct VertexDescription -{ - enum - { - Null = 0, // Terminates a VertexDescription array - Position, - TexCoord, - Normal, - Color, - }; - int field; // Position, TexCoord, Normal, Color - int type; // GL_FLOAT, GL_UNSIGNED_BYTE - int count; // number of elements - int offset; // field's offset into vertex struct - int index; // 0 (unused at the moment) -}; - -// Implementation of interleaved buffers. -// 'T' is a struct which must include a null-terminated static array -// 'VertexDescription* description'. -// Example: -/* -struct Vertex -{ - GLfloat position[3]; - GLfloat texCoord[2]; - GLfloat normal[3]; - GLbyte color[4]; - static VertexDescription description[]; -}; - -VertexDescription Vertex::description[] = { - {VertexDescription::Position, GL_FLOAT, SIZE_OF_MEMBER(Vertex, position) / sizeof(GLfloat), offsetof(Vertex, position), 0}, - {VertexDescription::TexCoord, GL_FLOAT, SIZE_OF_MEMBER(Vertex, texCoord) / sizeof(GLfloat), offsetof(Vertex, texCoord), 0}, - {VertexDescription::Normal, GL_FLOAT, SIZE_OF_MEMBER(Vertex, normal) / sizeof(GLfloat), offsetof(Vertex, normal), 0}, - {VertexDescription::Color, GL_BYTE, SIZE_OF_MEMBER(Vertex, color) / sizeof(GLbyte), offsetof(Vertex, color), 0}, - {VertexDescription::Null, 0, 0, 0, 0}, -}; -*/ -template -class GLVertexBuffer -{ -public: - GLVertexBuffer(int length, const T *data = 0, int mode = GL_STATIC_DRAW) - : m_length(0) - , m_mode(mode) - , m_buffer(0) - , m_failed(false) - { - GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::GLVertexBuffer", glGenBuffers && glBindBuffer && glBufferData, return) - - glGenBuffers(1, &m_buffer); - glBindBuffer(GL_ARRAY_BUFFER, m_buffer); - glBufferData(GL_ARRAY_BUFFER, (m_length = length) * sizeof(T), data, mode); - } - - ~GLVertexBuffer() - { - GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::~GLVertexBuffer", glDeleteBuffers, return) - - glDeleteBuffers(1, &m_buffer); - } - - void bind() - { - GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::bind", glBindBuffer, return) - - glBindBuffer(GL_ARRAY_BUFFER, m_buffer); - for (VertexDescription *desc = T::description; desc->field != VertexDescription::Null; ++desc) { - switch (desc->field) { - case VertexDescription::Position: - glVertexPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); - glEnableClientState(GL_VERTEX_ARRAY); - break; - case VertexDescription::TexCoord: - glTexCoordPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - break; - case VertexDescription::Normal: - glNormalPointer(desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); - glEnableClientState(GL_NORMAL_ARRAY); - break; - case VertexDescription::Color: - glColorPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); - glEnableClientState(GL_COLOR_ARRAY); - break; - default: - break; - } - } - } - - void unbind() - { - GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::unbind", glBindBuffer, return) - - glBindBuffer(GL_ARRAY_BUFFER, 0); - for (VertexDescription *desc = T::description; desc->field != VertexDescription::Null; ++desc) { - switch (desc->field) { - case VertexDescription::Position: - glDisableClientState(GL_VERTEX_ARRAY); - break; - case VertexDescription::TexCoord: - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - break; - case VertexDescription::Normal: - glDisableClientState(GL_NORMAL_ARRAY); - break; - case VertexDescription::Color: - glDisableClientState(GL_COLOR_ARRAY); - break; - default: - break; - } - } - } - - int length() const {return m_length;} - - T *lock() - { - GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::lock", glBindBuffer && glMapBuffer, return 0) - - glBindBuffer(GL_ARRAY_BUFFER, m_buffer); - //glBufferData(GL_ARRAY_BUFFER, m_length, NULL, m_mode); - GLvoid* buffer = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); - m_failed = (buffer == 0); - return reinterpret_cast(buffer); - } - - void unlock() - { - GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::unlock", glBindBuffer && glUnmapBuffer, return) - - glBindBuffer(GL_ARRAY_BUFFER, m_buffer); - glUnmapBuffer(GL_ARRAY_BUFFER); - } - - bool failed() - { - return m_failed; - } - -private: - int m_length, m_mode; - GLuint m_buffer; - bool m_failed; -}; - -template -class GLIndexBuffer -{ -public: - GLIndexBuffer(int length, const T *data = 0, int mode = GL_STATIC_DRAW) - : m_length(0) - , m_mode(mode) - , m_buffer(0) - , m_failed(false) - { - GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::GLIndexBuffer", glGenBuffers && glBindBuffer && glBufferData, return) - - glGenBuffers(1, &m_buffer); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, (m_length = length) * sizeof(T), data, mode); - } - - ~GLIndexBuffer() - { - GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::~GLIndexBuffer", glDeleteBuffers, return) - - glDeleteBuffers(1, &m_buffer); - } - - void bind() - { - GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::bind", glBindBuffer, return) - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); - } - - void unbind() - { - GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::unbind", glBindBuffer, return) - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } - - int length() const {return m_length;} - - T *lock() - { - GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::lock", glBindBuffer && glMapBuffer, return 0) - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); - GLvoid* buffer = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_WRITE); - m_failed = (buffer == 0); - return reinterpret_cast(buffer); - } - - void unlock() - { - GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::unlock", glBindBuffer && glUnmapBuffer, return) - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); - glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); - } - - bool failed() - { - return m_failed; - } - -private: - int m_length, m_mode; - GLuint m_buffer; - bool m_failed; -}; - -#endif diff --git a/demos/boxes/glextensions.cpp b/demos/boxes/glextensions.cpp deleted file mode 100644 index b712efe38b..0000000000 --- a/demos/boxes/glextensions.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "glextensions.h" - -#define RESOLVE_GL_FUNC(f) ok &= bool((f = (_gl##f) context->getProcAddress(QLatin1String("gl" #f)))); - -bool GLExtensionFunctions::resolve(const QGLContext *context) -{ - bool ok = true; - - RESOLVE_GL_FUNC(GenFramebuffersEXT) - RESOLVE_GL_FUNC(GenRenderbuffersEXT) - RESOLVE_GL_FUNC(BindRenderbufferEXT) - RESOLVE_GL_FUNC(RenderbufferStorageEXT) - RESOLVE_GL_FUNC(DeleteFramebuffersEXT) - RESOLVE_GL_FUNC(DeleteRenderbuffersEXT) - RESOLVE_GL_FUNC(BindFramebufferEXT) - RESOLVE_GL_FUNC(FramebufferTexture2DEXT) - RESOLVE_GL_FUNC(FramebufferRenderbufferEXT) - RESOLVE_GL_FUNC(CheckFramebufferStatusEXT) - - RESOLVE_GL_FUNC(ActiveTexture) - RESOLVE_GL_FUNC(TexImage3D) - - RESOLVE_GL_FUNC(GenBuffers) - RESOLVE_GL_FUNC(BindBuffer) - RESOLVE_GL_FUNC(BufferData) - RESOLVE_GL_FUNC(DeleteBuffers) - RESOLVE_GL_FUNC(MapBuffer) - RESOLVE_GL_FUNC(UnmapBuffer) - - return ok; -} - -bool GLExtensionFunctions::fboSupported() { - return GenFramebuffersEXT - && GenRenderbuffersEXT - && BindRenderbufferEXT - && RenderbufferStorageEXT - && DeleteFramebuffersEXT - && DeleteRenderbuffersEXT - && BindFramebufferEXT - && FramebufferTexture2DEXT - && FramebufferRenderbufferEXT - && CheckFramebufferStatusEXT; -} - -bool GLExtensionFunctions::openGL15Supported() { - return ActiveTexture - && TexImage3D - && GenBuffers - && BindBuffer - && BufferData - && DeleteBuffers - && MapBuffer - && UnmapBuffer; -} - -#undef RESOLVE_GL_FUNC diff --git a/demos/boxes/glextensions.h b/demos/boxes/glextensions.h deleted file mode 100644 index 54de548cd7..0000000000 --- a/demos/boxes/glextensions.h +++ /dev/null @@ -1,202 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GLEXTENSIONS_H -#define GLEXTENSIONS_H - -#include - -/* -Functions resolved: - -glGenFramebuffersEXT -glGenRenderbuffersEXT -glBindRenderbufferEXT -glRenderbufferStorageEXT -glDeleteFramebuffersEXT -glDeleteRenderbuffersEXT -glBindFramebufferEXT -glFramebufferTexture2DEXT -glFramebufferRenderbufferEXT -glCheckFramebufferStatusEXT - -glActiveTexture -glTexImage3D - -glGenBuffers -glBindBuffer -glBufferData -glDeleteBuffers -glMapBuffer -glUnmapBuffer -*/ - -#ifndef Q_WS_MAC -# ifndef APIENTRYP -# ifdef APIENTRY -# define APIENTRYP APIENTRY * -# else -# define APIENTRY -# define APIENTRYP * -# endif -# endif -#else -# define APIENTRY -# define APIENTRYP * -#endif - -#ifndef GL_VERSION_1_2 -#define GL_TEXTURE_3D 0x806F -#define GL_TEXTURE_WRAP_R 0x8072 -#define GL_CLAMP_TO_EDGE 0x812F -#define GL_BGRA 0x80E1 -#endif - -#ifndef GL_VERSION_1_3 -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE_CUBE_MAP 0x8513 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 -//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 -//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 -//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 -//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 -//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A -#endif - -#ifndef GL_ARB_vertex_buffer_object -typedef ptrdiff_t GLsizeiptrARB; -#endif - -#ifndef GL_VERSION_1_5 -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_READ_WRITE 0x88BA -#define GL_STATIC_DRAW 0x88E4 -#endif - -#ifndef GL_EXT_framebuffer_object -#define GL_RENDERBUFFER_EXT 0x8D41 -#define GL_FRAMEBUFFER_EXT 0x8D40 -#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 -#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 -#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 -#endif - -typedef void (APIENTRY *_glGenFramebuffersEXT) (GLsizei, GLuint *); -typedef void (APIENTRY *_glGenRenderbuffersEXT) (GLsizei, GLuint *); -typedef void (APIENTRY *_glBindRenderbufferEXT) (GLenum, GLuint); -typedef void (APIENTRY *_glRenderbufferStorageEXT) (GLenum, GLenum, GLsizei, GLsizei); -typedef void (APIENTRY *_glDeleteFramebuffersEXT) (GLsizei, const GLuint*); -typedef void (APIENTRY *_glDeleteRenderbuffersEXT) (GLsizei, const GLuint*); -typedef void (APIENTRY *_glBindFramebufferEXT) (GLenum, GLuint); -typedef void (APIENTRY *_glFramebufferTexture2DEXT) (GLenum, GLenum, GLenum, GLuint, GLint); -typedef void (APIENTRY *_glFramebufferRenderbufferEXT) (GLenum, GLenum, GLenum, GLuint); -typedef GLenum (APIENTRY *_glCheckFramebufferStatusEXT) (GLenum); - -typedef void (APIENTRY *_glActiveTexture) (GLenum); -typedef void (APIENTRY *_glTexImage3D) (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); - -typedef void (APIENTRY *_glGenBuffers) (GLsizei, GLuint *); -typedef void (APIENTRY *_glBindBuffer) (GLenum, GLuint); -typedef void (APIENTRY *_glBufferData) (GLenum, GLsizeiptrARB, const GLvoid *, GLenum); -typedef void (APIENTRY *_glDeleteBuffers) (GLsizei, const GLuint *); -typedef void *(APIENTRY *_glMapBuffer) (GLenum, GLenum); -typedef GLboolean (APIENTRY *_glUnmapBuffer) (GLenum); - -struct GLExtensionFunctions -{ - bool resolve(const QGLContext *context); - - bool fboSupported(); - bool openGL15Supported(); // the rest: multi-texture, 3D-texture, vertex buffer objects - - _glGenFramebuffersEXT GenFramebuffersEXT; - _glGenRenderbuffersEXT GenRenderbuffersEXT; - _glBindRenderbufferEXT BindRenderbufferEXT; - _glRenderbufferStorageEXT RenderbufferStorageEXT; - _glDeleteFramebuffersEXT DeleteFramebuffersEXT; - _glDeleteRenderbuffersEXT DeleteRenderbuffersEXT; - _glBindFramebufferEXT BindFramebufferEXT; - _glFramebufferTexture2DEXT FramebufferTexture2DEXT; - _glFramebufferRenderbufferEXT FramebufferRenderbufferEXT; - _glCheckFramebufferStatusEXT CheckFramebufferStatusEXT; - - _glActiveTexture ActiveTexture; - _glTexImage3D TexImage3D; - - _glGenBuffers GenBuffers; - _glBindBuffer BindBuffer; - _glBufferData BufferData; - _glDeleteBuffers DeleteBuffers; - _glMapBuffer MapBuffer; - _glUnmapBuffer UnmapBuffer; -}; - -inline GLExtensionFunctions &getGLExtensionFunctions() -{ - static GLExtensionFunctions funcs; - return funcs; -} - -#define glGenFramebuffersEXT getGLExtensionFunctions().GenFramebuffersEXT -#define glGenRenderbuffersEXT getGLExtensionFunctions().GenRenderbuffersEXT -#define glBindRenderbufferEXT getGLExtensionFunctions().BindRenderbufferEXT -#define glRenderbufferStorageEXT getGLExtensionFunctions().RenderbufferStorageEXT -#define glDeleteFramebuffersEXT getGLExtensionFunctions().DeleteFramebuffersEXT -#define glDeleteRenderbuffersEXT getGLExtensionFunctions().DeleteRenderbuffersEXT -#define glBindFramebufferEXT getGLExtensionFunctions().BindFramebufferEXT -#define glFramebufferTexture2DEXT getGLExtensionFunctions().FramebufferTexture2DEXT -#define glFramebufferRenderbufferEXT getGLExtensionFunctions().FramebufferRenderbufferEXT -#define glCheckFramebufferStatusEXT getGLExtensionFunctions().CheckFramebufferStatusEXT - -#define glActiveTexture getGLExtensionFunctions().ActiveTexture -#define glTexImage3D getGLExtensionFunctions().TexImage3D - -#define glGenBuffers getGLExtensionFunctions().GenBuffers -#define glBindBuffer getGLExtensionFunctions().BindBuffer -#define glBufferData getGLExtensionFunctions().BufferData -#define glDeleteBuffers getGLExtensionFunctions().DeleteBuffers -#define glMapBuffer getGLExtensionFunctions().MapBuffer -#define glUnmapBuffer getGLExtensionFunctions().UnmapBuffer - -#endif diff --git a/demos/boxes/gltrianglemesh.h b/demos/boxes/gltrianglemesh.h deleted file mode 100644 index ecf6531d85..0000000000 --- a/demos/boxes/gltrianglemesh.h +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GLTRIANGLEMESH_H -#define GLTRIANGLEMESH_H - -//#include -#include "glextensions.h" - -#include -#include - -#include "glbuffers.h" - -template -class GLTriangleMesh -{ -public: - GLTriangleMesh(int vertexCount, int indexCount) : m_vb(vertexCount), m_ib(indexCount) - { - } - - virtual ~GLTriangleMesh() - { - } - - virtual void draw() - { - if (failed()) - return; - - int type = GL_UNSIGNED_INT; - if (sizeof(TIndex) == sizeof(char)) type = GL_UNSIGNED_BYTE; - if (sizeof(TIndex) == sizeof(short)) type = GL_UNSIGNED_SHORT; - - m_vb.bind(); - m_ib.bind(); - glDrawElements(GL_TRIANGLES, m_ib.length(), type, BUFFER_OFFSET(0)); - m_vb.unbind(); - m_ib.unbind(); - } - - bool failed() - { - return m_vb.failed() || m_ib.failed(); - } -protected: - GLVertexBuffer m_vb; - GLIndexBuffer m_ib; -}; - - -#endif diff --git a/demos/boxes/granite.fsh b/demos/boxes/granite.fsh deleted file mode 100644 index abaeeb97bc..0000000000 --- a/demos/boxes/granite.fsh +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; -uniform sampler3D noise; - -//const vec4 graniteColors[3] = {vec4(0.0, 0.0, 0.0, 1), vec4(0.30, 0.15, 0.10, 1), vec4(0.80, 0.70, 0.75, 1)}; -uniform vec4 graniteColors[3]; - -float steep(float x) -{ - return clamp(5.0 * x - 2.0, 0.0, 1.0); -} - -void main() -{ - vec2 turbulence = vec2(0, 0); - float scale = 1.0; - for (int i = 0; i < 4; ++i) { - turbulence += scale * (texture3D(noise, gl_TexCoord[1].xyz / scale).xy - 0.5); - scale *= 0.5; - } - - vec3 N = normalize(normal); - // assume directional light - - gl_MaterialParameters M = gl_FrontMaterial; - - float NdotL = dot(N, lightDirection.xyz); - float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); - - vec4 unlitColor = mix(graniteColors[1], mix(graniteColors[0], graniteColors[2], steep(0.5 + turbulence.y)), 4.0 * abs(turbulence.x)); - gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + - M.specular * specular * pow(max(RdotL, 0.0), M.shininess); -} diff --git a/demos/boxes/main.cpp b/demos/boxes/main.cpp deleted file mode 100644 index 483170801f..0000000000 --- a/demos/boxes/main.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//#include -#include "glextensions.h" - -#include "scene.h" - -#include -#include - -class GraphicsView : public QGraphicsView -{ -public: - GraphicsView() - { - setWindowTitle(tr("Boxes")); - setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - //setRenderHints(QPainter::SmoothPixmapTransform); - } - -protected: - void resizeEvent(QResizeEvent *event) { - if (scene()) - scene()->setSceneRect(QRect(QPoint(0, 0), event->size())); - QGraphicsView::resizeEvent(event); - } -}; - -inline bool matchString(const char *extensionString, const char *subString) -{ - int subStringLength = strlen(subString); - return (strncmp(extensionString, subString, subStringLength) == 0) - && ((extensionString[subStringLength] == ' ') || (extensionString[subStringLength] == '\0')); -} - -bool necessaryExtensionsSupported() -{ - const char *extensionString = reinterpret_cast(glGetString(GL_EXTENSIONS)); - const char *p = extensionString; - - const int GL_EXT_FBO = 1; - const int GL_ARB_VS = 2; - const int GL_ARB_FS = 4; - const int GL_ARB_SO = 8; - int extensions = 0; - - while (*p) { - if (matchString(p, "GL_EXT_framebuffer_object")) - extensions |= GL_EXT_FBO; - else if (matchString(p, "GL_ARB_vertex_shader")) - extensions |= GL_ARB_VS; - else if (matchString(p, "GL_ARB_fragment_shader")) - extensions |= GL_ARB_FS; - else if (matchString(p, "GL_ARB_shader_objects")) - extensions |= GL_ARB_SO; - while ((*p != ' ') && (*p != '\0')) - ++p; - if (*p == ' ') - ++p; - } - return (extensions == 15); -} - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_5) == 0) { - QMessageBox::critical(0, "OpenGL features missing", - "OpenGL version 1.5 or higher is required to run this demo.\n" - "The program will now exit."); - return -1; - } - - int maxTextureSize = 1024; - QGLWidget *widget = new QGLWidget(QGLFormat(QGL::SampleBuffers)); - widget->makeCurrent(); - - if (!necessaryExtensionsSupported()) { - QMessageBox::critical(0, "OpenGL features missing", - "The OpenGL extensions required to run this demo are missing.\n" - "The program will now exit."); - delete widget; - return -2; - } - - // Check if all the necessary functions are resolved. - if (!getGLExtensionFunctions().resolve(widget->context())) { - QMessageBox::critical(0, "OpenGL features missing", - "Failed to resolve OpenGL functions required to run this demo.\n" - "The program will now exit."); - delete widget; - return -3; - } - - // TODO: Make conditional for final release - QMessageBox::information(0, "For your information", - "This demo can be GPU and CPU intensive and may\n" - "work poorly or not at all on your system."); - - widget->makeCurrent(); // The current context must be set before calling Scene's constructor - Scene scene(1024, 768, maxTextureSize); - GraphicsView view; - view.setViewport(widget); - view.setViewportUpdateMode(QGraphicsView::FullViewportUpdate); - view.setScene(&scene); - view.show(); - - return app.exec(); -} - diff --git a/demos/boxes/marble.fsh b/demos/boxes/marble.fsh deleted file mode 100644 index 170ec3abef..0000000000 --- a/demos/boxes/marble.fsh +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; -uniform sampler3D noise; - -//const vec4 marbleColors[2] = {vec4(0.9, 0.9, 0.9, 1), vec4(0.6, 0.5, 0.5, 1)}; -uniform vec4 marbleColors[2]; - -void main() -{ - float turbulence = 0.0; - float scale = 1.0; - for (int i = 0; i < 4; ++i) { - turbulence += scale * (texture3D(noise, 0.125 * gl_TexCoord[1].xyz / scale).x - 0.5); - scale *= 0.5; - } - - vec3 N = normalize(normal); - // assume directional light - - gl_MaterialParameters M = gl_FrontMaterial; - - float NdotL = dot(N, lightDirection.xyz); - float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); - - vec4 unlitColor = mix(marbleColors[0], marbleColors[1], exp(-4.0 * abs(turbulence))); - gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + - M.specular * specular * pow(max(RdotL, 0.0), M.shininess); -} diff --git a/demos/boxes/parameters.par b/demos/boxes/parameters.par deleted file mode 100644 index 50e20739b9..0000000000 --- a/demos/boxes/parameters.par +++ /dev/null @@ -1,5 +0,0 @@ -color basicColor ff0e3d0e -color woodColors ff5e3d33 ffcc9966 -float woodTubulence 0.1 -color graniteColors ff000000 ff4d261a ffccb3bf -color marbleColors ffe6e6e6 ff998080 diff --git a/demos/boxes/qt-logo.jpg b/demos/boxes/qt-logo.jpg deleted file mode 100644 index 4014b4659c..0000000000 Binary files a/demos/boxes/qt-logo.jpg and /dev/null differ diff --git a/demos/boxes/qt-logo.png b/demos/boxes/qt-logo.png deleted file mode 100644 index 7d3e97eb36..0000000000 Binary files a/demos/boxes/qt-logo.png and /dev/null differ diff --git a/demos/boxes/qtbox.cpp b/demos/boxes/qtbox.cpp deleted file mode 100644 index d24116578c..0000000000 --- a/demos/boxes/qtbox.cpp +++ /dev/null @@ -1,480 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qtbox.h" - -const qreal ROTATE_SPEED_X = 30.0 / 1000.0; -const qreal ROTATE_SPEED_Y = 20.0 / 1000.0; -const qreal ROTATE_SPEED_Z = 40.0 / 1000.0; -const int MAX_ITEM_SIZE = 512; -const int MIN_ITEM_SIZE = 16; - -//============================================================================// -// ItemBase // -//============================================================================// - -ItemBase::ItemBase(int size, int x, int y) : m_size(size), m_isResizing(false) -{ - setFlag(QGraphicsItem::ItemIsMovable, true); - setFlag(QGraphicsItem::ItemIsSelectable, true); - setFlag(QGraphicsItem::ItemIsFocusable, true); - setAcceptHoverEvents(true); - setPos(x, y); - m_startTime = QTime::currentTime(); -} - -ItemBase::~ItemBase() -{ -} - -QRectF ItemBase::boundingRect() const -{ - return QRectF(-m_size / 2, -m_size / 2, m_size, m_size); -} - -void ItemBase::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) -{ - if (option->state & QStyle::State_Selected) { - painter->setRenderHint(QPainter::Antialiasing, true); - if (option->state & QStyle::State_HasFocus) - painter->setPen(Qt::yellow); - else - painter->setPen(Qt::white); - painter->drawRect(boundingRect()); - - painter->drawLine(m_size / 2 - 9, m_size / 2, m_size / 2, m_size / 2 - 9); - painter->drawLine(m_size / 2 - 6, m_size / 2, m_size / 2, m_size / 2 - 6); - painter->drawLine(m_size / 2 - 3, m_size / 2, m_size / 2, m_size / 2 - 3); - - painter->setRenderHint(QPainter::Antialiasing, false); - } -} - -void ItemBase::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) -{ - if (!isSelected() && scene()) { - scene()->clearSelection(); - setSelected(true); - } - - QMenu menu; - QAction *delAction = menu.addAction("Delete"); - QAction *newAction = menu.addAction("New"); - QAction *growAction = menu.addAction("Grow"); - QAction *shrinkAction = menu.addAction("Shrink"); - - QAction *selectedAction = menu.exec(event->screenPos()); - - if (selectedAction == delAction) - deleteSelectedItems(scene()); - else if (selectedAction == newAction) - duplicateSelectedItems(scene()); - else if (selectedAction == growAction) - growSelectedItems(scene()); - else if (selectedAction == shrinkAction) - shrinkSelectedItems(scene()); -} - -void ItemBase::duplicateSelectedItems(QGraphicsScene *scene) -{ - if (!scene) - return; - - QList selected; - selected = scene->selectedItems(); - - foreach (QGraphicsItem *item, selected) { - ItemBase *itemBase = qgraphicsitem_cast(item); - if (itemBase) - scene->addItem(itemBase->createNew(itemBase->m_size, itemBase->pos().x() + itemBase->m_size, itemBase->pos().y())); - } -} - -void ItemBase::deleteSelectedItems(QGraphicsScene *scene) -{ - if (!scene) - return; - - QList selected; - selected = scene->selectedItems(); - - foreach (QGraphicsItem *item, selected) { - ItemBase *itemBase = qgraphicsitem_cast(item); - if (itemBase) - delete itemBase; - } -} - -void ItemBase::growSelectedItems(QGraphicsScene *scene) -{ - if (!scene) - return; - - QList selected; - selected = scene->selectedItems(); - - foreach (QGraphicsItem *item, selected) { - ItemBase *itemBase = qgraphicsitem_cast(item); - if (itemBase) { - itemBase->prepareGeometryChange(); - itemBase->m_size *= 2; - if (itemBase->m_size > MAX_ITEM_SIZE) - itemBase->m_size = MAX_ITEM_SIZE; - } - } -} - -void ItemBase::shrinkSelectedItems(QGraphicsScene *scene) -{ - if (!scene) - return; - - QList selected; - selected = scene->selectedItems(); - - foreach (QGraphicsItem *item, selected) { - ItemBase *itemBase = qgraphicsitem_cast(item); - if (itemBase) { - itemBase->prepareGeometryChange(); - itemBase->m_size /= 2; - if (itemBase->m_size < MIN_ITEM_SIZE) - itemBase->m_size = MIN_ITEM_SIZE; - } - } -} - -void ItemBase::mouseMoveEvent(QGraphicsSceneMouseEvent *event) -{ - if (m_isResizing) { - int dx = int(2.0 * event->pos().x()); - int dy = int(2.0 * event->pos().y()); - prepareGeometryChange(); - m_size = (dx > dy ? dx : dy); - if (m_size < MIN_ITEM_SIZE) - m_size = MIN_ITEM_SIZE; - else if (m_size > MAX_ITEM_SIZE) - m_size = MAX_ITEM_SIZE; - } else { - QGraphicsItem::mouseMoveEvent(event); - } -} - -void ItemBase::hoverMoveEvent(QGraphicsSceneHoverEvent *event) -{ - if (m_isResizing || (isInResizeArea(event->pos()) && isSelected())) - setCursor(Qt::SizeFDiagCursor); - else - setCursor(Qt::ArrowCursor); - QGraphicsItem::hoverMoveEvent(event); -} - -void ItemBase::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - static qreal z = 0.0; - setZValue(z += 1.0); - if (event->button() == Qt::LeftButton && isInResizeArea(event->pos())) { - m_isResizing = true; - } else { - QGraphicsItem::mousePressEvent(event); - } -} - -void ItemBase::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) -{ - if (event->button() == Qt::LeftButton && m_isResizing) { - m_isResizing = false; - } else { - QGraphicsItem::mouseReleaseEvent(event); - } -} - -void ItemBase::keyPressEvent(QKeyEvent *event) -{ - switch (event->key()) { - case Qt::Key_Delete: - deleteSelectedItems(scene()); - break; - case Qt::Key_Insert: - duplicateSelectedItems(scene()); - break; - case Qt::Key_Plus: - growSelectedItems(scene()); - break; - case Qt::Key_Minus: - shrinkSelectedItems(scene()); - break; - default: - QGraphicsItem::keyPressEvent(event); - break; - } -} - -void ItemBase::wheelEvent(QGraphicsSceneWheelEvent *event) -{ - prepareGeometryChange(); - m_size = int(m_size * exp(-event->delta() / 600.0)); - if (m_size > MAX_ITEM_SIZE) - m_size = MAX_ITEM_SIZE; - else if (m_size < MIN_ITEM_SIZE) - m_size = MIN_ITEM_SIZE; -} - -int ItemBase::type() const -{ - return Type; -} - - -bool ItemBase::isInResizeArea(const QPointF &pos) -{ - return (-pos.y() < pos.x() - m_size + 9); -} - -//============================================================================// -// QtBox // -//============================================================================// - -QtBox::QtBox(int size, int x, int y) : ItemBase(size, x, y), m_texture(0) -{ - for (int i = 0; i < 8; ++i) { - m_vertices[i].setX(i & 1 ? 0.5f : -0.5f); - m_vertices[i].setY(i & 2 ? 0.5f : -0.5f); - m_vertices[i].setZ(i & 4 ? 0.5f : -0.5f); - } - for (int i = 0; i < 4; ++i) { - m_texCoords[i].setX(i & 1 ? 1.0f : 0.0f); - m_texCoords[i].setY(i & 2 ? 1.0f : 0.0f); - } - m_normals[0] = QVector3D(-1.0f, 0.0f, 0.0f); - m_normals[1] = QVector3D(1.0f, 0.0f, 0.0f); - m_normals[2] = QVector3D(0.0f, -1.0f, 0.0f); - m_normals[3] = QVector3D(0.0f, 1.0f, 0.0f); - m_normals[4] = QVector3D(0.0f, 0.0f, -1.0f); - m_normals[5] = QVector3D(0.0f, 0.0f, 1.0f); -} - -QtBox::~QtBox() -{ - if (m_texture) - delete m_texture; -} - -ItemBase *QtBox::createNew(int size, int x, int y) -{ - return new QtBox(size, x, y); -} - -void QtBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) -{ - QRectF rect = boundingRect().translated(pos()); - float width = float(painter->device()->width()); - float height = float(painter->device()->height()); - - float left = 2.0f * float(rect.left()) / width - 1.0f; - float right = 2.0f * float(rect.right()) / width - 1.0f; - float top = 1.0f - 2.0f * float(rect.top()) / height; - float bottom = 1.0f - 2.0f * float(rect.bottom()) / height; - float moveToRectMatrix[] = { - 0.5f * (right - left), 0.0f, 0.0f, 0.0f, - 0.0f, 0.5f * (bottom - top), 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.5f * (right + left), 0.5f * (bottom + top), 0.0f, 1.0f - }; - - painter->beginNativePainting(); - - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadMatrixf(moveToRectMatrix); - qgluPerspective(60.0, 1.0, 0.01, 10.0); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - - //glEnable(GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - glEnable(GL_LIGHTING); - glEnable(GL_COLOR_MATERIAL); - glEnable(GL_NORMALIZE); - - if(m_texture == 0) - m_texture = new GLTexture2D(":/res/boxes/qt-logo.jpg", 64, 64); - m_texture->bind(); - glEnable(GL_TEXTURE_2D); - - glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); - float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f}; - float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f}; - glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour); - glLightfv(GL_LIGHT0, GL_POSITION, lightDir); - glEnable(GL_LIGHT0); - - glTranslatef(0.0f, 0.0f, -1.5f); - glRotatef(ROTATE_SPEED_X * m_startTime.msecsTo(QTime::currentTime()), 1.0f, 0.0f, 0.0f); - glRotatef(ROTATE_SPEED_Y * m_startTime.msecsTo(QTime::currentTime()), 0.0f, 1.0f, 0.0f); - glRotatef(ROTATE_SPEED_Z * m_startTime.msecsTo(QTime::currentTime()), 0.0f, 0.0f, 1.0f); - int dt = m_startTime.msecsTo(QTime::currentTime()); - if (dt < 500) - glScalef(dt / 500.0f, dt / 500.0f, dt / 500.0f); - - for (int dir = 0; dir < 3; ++dir) { - glColor4f(1.0f, 1.0f, 1.0f, 1.0); - - glBegin(GL_TRIANGLE_STRIP); - glNormal3fv(reinterpret_cast(&m_normals[2 * dir + 0])); - for (int i = 0; i < 2; ++i) { - for (int j = 0; j < 2; ++j) { - glTexCoord2fv(reinterpret_cast(&m_texCoords[(j << 1) | i])); - glVertex3fv(reinterpret_cast(&m_vertices[(i << ((dir + 2) % 3)) | (j << ((dir + 1) % 3))])); - } - } - glEnd(); - - glBegin(GL_TRIANGLE_STRIP); - glNormal3fv(reinterpret_cast(&m_normals[2 * dir + 1])); - for (int i = 0; i < 2; ++i) { - for (int j = 0; j < 2; ++j) { - glTexCoord2fv(reinterpret_cast(&m_texCoords[(j << 1) | i])); - glVertex3fv(reinterpret_cast(&m_vertices[(1 << dir) | (i << ((dir + 1) % 3)) | (j << ((dir + 2) % 3))])); - } - } - glEnd(); - } - m_texture->unbind(); - - //glDisable(GL_DEPTH_TEST); - glDisable(GL_CULL_FACE); - glDisable(GL_LIGHTING); - glDisable(GL_COLOR_MATERIAL); - glDisable(GL_TEXTURE_2D); - glDisable(GL_LIGHT0); - glDisable(GL_NORMALIZE); - - glPopMatrix(); - - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - - painter->endNativePainting(); - - ItemBase::paint(painter, option, widget); -} - -//============================================================================// -// CircleItem // -//============================================================================// - -CircleItem::CircleItem(int size, int x, int y) : ItemBase(size, x, y) -{ - m_color = QColor::fromHsv(rand() % 360, 255, 255); -} - -void CircleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) -{ - int dt = m_startTime.msecsTo(QTime::currentTime()); - - qreal r0 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 3800) % 4000))); - qreal r1 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 0) % 4000))); - qreal r2 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 1800) % 4000))); - qreal r3 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 2000) % 4000))); - - if (r0 > r1) - r0 = 0.0; - if (r2 > r3) - r2 = 0.0; - - QPainterPath path; - path.moveTo(r1, 0.0); - path.arcTo(-r1, -r1, 2 * r1, 2 * r1, 0.0, 360.0); - path.lineTo(r0, 0.0); - path.arcTo(-r0, -r0, 2 * r0, 2 * r0, 0.0, -360.0); - path.closeSubpath(); - path.moveTo(r3, 0.0); - path.arcTo(-r3, -r3, 2 * r3, 2 * r3, 0.0, 360.0); - path.lineTo(r0, 0.0); - path.arcTo(-r2, -r2, 2 * r2, 2 * r2, 0.0, -360.0); - path.closeSubpath(); - painter->setRenderHint(QPainter::Antialiasing, true); - painter->setBrush(QBrush(m_color)); - painter->setPen(Qt::NoPen); - painter->drawPath(path); - painter->setBrush(Qt::NoBrush); - painter->setPen(Qt::SolidLine); - painter->setRenderHint(QPainter::Antialiasing, false); - - ItemBase::paint(painter, option, widget); -} - -ItemBase *CircleItem::createNew(int size, int x, int y) -{ - return new CircleItem(size, x, y); -} - -//============================================================================// -// SquareItem // -//============================================================================// - -SquareItem::SquareItem(int size, int x, int y) : ItemBase(size, x, y) -{ - m_image = QPixmap(":/res/boxes/square.jpg"); -} - -void SquareItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) -{ - int dt = m_startTime.msecsTo(QTime::currentTime()); - QTransform oldTransform = painter->worldTransform(); - int dtMod = dt % 2000; - qreal amp = 0.002 * (dtMod < 1000 ? dtMod : 2000 - dtMod) - 1.0; - - qreal scale = 0.6 + 0.2 * amp * amp; - painter->setWorldTransform(QTransform().rotate(15.0 * amp).scale(scale, scale), true); - - painter->drawPixmap(-m_size / 2, -m_size / 2, m_size, m_size, m_image); - - painter->setWorldTransform(oldTransform, false); - ItemBase::paint(painter, option, widget); -} - -ItemBase *SquareItem::createNew(int size, int x, int y) -{ - return new SquareItem(size, x, y); -} diff --git a/demos/boxes/qtbox.h b/demos/boxes/qtbox.h deleted file mode 100644 index 56b86a55bb..0000000000 --- a/demos/boxes/qtbox.h +++ /dev/null @@ -1,118 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QTBOX_H -#define QTBOX_H - -#include - -#include -#include "glbuffers.h" - -class ItemBase : public QGraphicsItem -{ -public: - enum { Type = UserType + 1 }; - - ItemBase(int size, int x, int y); - virtual ~ItemBase(); - virtual QRectF boundingRect() const; - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); -protected: - virtual ItemBase *createNew(int size, int x, int y) = 0; - virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - virtual void hoverMoveEvent(QGraphicsSceneHoverEvent *event); - virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - virtual void keyPressEvent(QKeyEvent *event); - virtual void wheelEvent(QGraphicsSceneWheelEvent *event); - virtual int type() const; - bool isInResizeArea(const QPointF &pos); - - static void duplicateSelectedItems(QGraphicsScene *scene); - static void deleteSelectedItems(QGraphicsScene *scene); - static void growSelectedItems(QGraphicsScene *scene); - static void shrinkSelectedItems(QGraphicsScene *scene); - - int m_size; - QTime m_startTime; - bool m_isResizing; -}; - -class QtBox : public ItemBase -{ -public: - QtBox(int size, int x, int y); - virtual ~QtBox(); - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); -protected: - virtual ItemBase *createNew(int size, int x, int y); -private: - QVector3D m_vertices[8]; - QVector3D m_texCoords[4]; - QVector3D m_normals[6]; - GLTexture *m_texture; -}; - -class CircleItem : public ItemBase -{ -public: - CircleItem(int size, int x, int y); - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); -protected: - virtual ItemBase *createNew(int size, int x, int y); - - QColor m_color; -}; - -class SquareItem : public ItemBase -{ -public: - SquareItem(int size, int x, int y); - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); -protected: - virtual ItemBase *createNew(int size, int x, int y); - - QPixmap m_image; -}; - -#endif diff --git a/demos/boxes/reflection.fsh b/demos/boxes/reflection.fsh deleted file mode 100644 index 576c522bbb..0000000000 --- a/demos/boxes/reflection.fsh +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; -uniform samplerCube env; -uniform mat4 view; - -void main() -{ - vec3 N = normalize(normal); - vec3 R = 2.0 * dot(-position, N) * N + position; - gl_FragColor = textureCube(env, R * mat3(view[0].xyz, view[1].xyz, view[2].xyz)); -} diff --git a/demos/boxes/refraction.fsh b/demos/boxes/refraction.fsh deleted file mode 100644 index 10ab38a54c..0000000000 --- a/demos/boxes/refraction.fsh +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; -uniform samplerCube env; -uniform mat4 view; - -// Arrays don't work here on glsl < 120, apparently. -//const float coeffs[6] = float[6](1.0/2.0, 1.0/2.1, 1.0/2.2, 1.0/2.3, 1.0/2.4, 1.0/2.5); -float coeffs(int i) -{ - return 1.0 / (2.0 + 0.1 * float(i)); -} - -void main() -{ - vec3 N = normalize(normal); - vec3 I = -normalize(position); - float IdotN = dot(I, N); - float scales[6]; - vec3 C[6]; - for (int i = 0; i < 6; ++i) { - scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN))); - C[i] = textureCube(env, (-I + coeffs(i) * N) * mat3(view[0].xyz, view[1].xyz, view[2].xyz)).xyz; - } - - gl_FragColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y, - C[3].z + 2.0*C[4].z + C[5].z, 4.0); -} diff --git a/demos/boxes/roundedbox.cpp b/demos/boxes/roundedbox.cpp deleted file mode 100644 index 5058043707..0000000000 --- a/demos/boxes/roundedbox.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "roundedbox.h" - -//============================================================================// -// P3T2N3Vertex // -//============================================================================// - -VertexDescription P3T2N3Vertex::description[] = { - {VertexDescription::Position, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, position) / sizeof(float), 0, 0}, - {VertexDescription::TexCoord, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, texCoord) / sizeof(float), sizeof(QVector3D), 0}, - {VertexDescription::Normal, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, normal) / sizeof(float), sizeof(QVector3D) + sizeof(QVector2D), 0}, - - {VertexDescription::Null, 0, 0, 0, 0}, -}; - -//============================================================================// -// GLRoundedBox // -//============================================================================// - -float lerp(float a, float b, float t) -{ - return a * (1.0f - t) + b * t; -} - -GLRoundedBox::GLRoundedBox(float r, float scale, int n) - : GLTriangleMesh((n+2)*(n+3)*4, (n+1)*(n+1)*24+36+72*(n+1)) -{ - int vidx = 0, iidx = 0; - int vertexCountPerCorner = (n + 2) * (n + 3) / 2; - - P3T2N3Vertex *vp = m_vb.lock(); - unsigned short *ip = m_ib.lock(); - - if (!vp || !ip) { - qWarning("GLRoundedBox::GLRoundedBox: Failed to lock vertex buffer and/or index buffer."); - m_ib.unlock(); - m_vb.unlock(); - return; - } - - for (int corner = 0; corner < 8; ++corner) { - QVector3D centre(corner & 1 ? 1.0f : -1.0f, - corner & 2 ? 1.0f : -1.0f, - corner & 4 ? 1.0f : -1.0f); - int winding = (corner & 1) ^ ((corner >> 1) & 1) ^ (corner >> 2); - int offsX = ((corner ^ 1) - corner) * vertexCountPerCorner; - int offsY = ((corner ^ 2) - corner) * vertexCountPerCorner; - int offsZ = ((corner ^ 4) - corner) * vertexCountPerCorner; - - // Face polygons - if (winding) { - ip[iidx++] = vidx; - ip[iidx++] = vidx + offsX; - ip[iidx++] = vidx + offsY; - - ip[iidx++] = vidx + vertexCountPerCorner - n - 2; - ip[iidx++] = vidx + vertexCountPerCorner - n - 2 + offsY; - ip[iidx++] = vidx + vertexCountPerCorner - n - 2 + offsZ; - - ip[iidx++] = vidx + vertexCountPerCorner - 1; - ip[iidx++] = vidx + vertexCountPerCorner - 1 + offsZ; - ip[iidx++] = vidx + vertexCountPerCorner - 1 + offsX; - } - - for (int i = 0; i < n + 2; ++i) { - - // Edge polygons - if (winding && i < n + 1) { - ip[iidx++] = vidx + i + 1; - ip[iidx++] = vidx; - ip[iidx++] = vidx + offsY + i + 1; - ip[iidx++] = vidx + offsY; - ip[iidx++] = vidx + offsY + i + 1; - ip[iidx++] = vidx; - - ip[iidx++] = vidx + i; - ip[iidx++] = vidx + 2 * i + 2; - ip[iidx++] = vidx + i + offsX; - ip[iidx++] = vidx + 2 * i + offsX + 2; - ip[iidx++] = vidx + i + offsX; - ip[iidx++] = vidx + 2 * i + 2; - - ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i; - ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i; - ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i + offsZ; - ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i + offsZ; - ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i + offsZ; - ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i; - } - - for (int j = 0; j <= i; ++j) { - QVector3D normal = QVector3D(i - j, j, n + 1 - i).normalized(); - QVector3D offset(0.5f - r, 0.5f - r, 0.5f - r); - QVector3D pos = centre * (offset + r * normal); - - vp[vidx].position = scale * pos; - vp[vidx].normal = centre * normal; - vp[vidx].texCoord = QVector2D(pos.x() + 0.5f, pos.y() + 0.5f); - - // Corner polygons - if (i < n + 1) { - ip[iidx++] = vidx; - ip[iidx++] = vidx + i + 2 - winding; - ip[iidx++] = vidx + i + 1 + winding; - } - if (i < n) { - ip[iidx++] = vidx + i + 1 + winding; - ip[iidx++] = vidx + i + 2 - winding; - ip[iidx++] = vidx + 2 * i + 4; - } - - ++vidx; - } - } - - } - - m_ib.unlock(); - m_vb.unlock(); -} - diff --git a/demos/boxes/roundedbox.h b/demos/boxes/roundedbox.h deleted file mode 100644 index 54dda82000..0000000000 --- a/demos/boxes/roundedbox.h +++ /dev/null @@ -1,72 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ROUNDEDBOX_H -#define ROUNDEDBOX_H - -//#include -#include "glextensions.h" - -#include -#include - -#include "gltrianglemesh.h" -#include -#include -#include "glbuffers.h" - -struct P3T2N3Vertex -{ - QVector3D position; - QVector2D texCoord; - QVector3D normal; - static VertexDescription description[]; -}; - -class GLRoundedBox : public GLTriangleMesh -{ -public: - // 0 < r < 0.5, 0 <= n <= 125 - GLRoundedBox(float r = 0.25f, float scale = 1.0f, int n = 10); -}; - - -#endif diff --git a/demos/boxes/scene.cpp b/demos/boxes/scene.cpp deleted file mode 100644 index 39cd0fcafd..0000000000 --- a/demos/boxes/scene.cpp +++ /dev/null @@ -1,1085 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "scene.h" -#include -#include - -#include "3rdparty/fbm.h" - -void checkGLErrors(const QString& prefix) -{ - switch (glGetError()) { - case GL_NO_ERROR: - //qDebug() << prefix << tr("No error."); - break; - case GL_INVALID_ENUM: - qDebug() << prefix << QObject::tr("Invalid enum."); - break; - case GL_INVALID_VALUE: - qDebug() << prefix << QObject::tr("Invalid value."); - break; - case GL_INVALID_OPERATION: - qDebug() << prefix << QObject::tr("Invalid operation."); - break; - case GL_STACK_OVERFLOW: - qDebug() << prefix << QObject::tr("Stack overflow."); - break; - case GL_STACK_UNDERFLOW: - qDebug() << prefix << QObject::tr("Stack underflow."); - break; - case GL_OUT_OF_MEMORY: - qDebug() << prefix << QObject::tr("Out of memory."); - break; - default: - qDebug() << prefix << QObject::tr("Unknown error."); - break; - } -} - -//============================================================================// -// ColorEdit // -//============================================================================// - -ColorEdit::ColorEdit(QRgb initialColor, int id) - : m_color(initialColor), m_id(id) -{ - QHBoxLayout *layout = new QHBoxLayout; - setLayout(layout); - layout->setContentsMargins(0, 0, 0, 0); - - m_lineEdit = new QLineEdit(QString::number(m_color, 16)); - layout->addWidget(m_lineEdit); - - m_button = new QFrame; - QPalette palette = m_button->palette(); - palette.setColor(QPalette::Window, QColor(m_color)); - m_button->setPalette(palette); - m_button->setAutoFillBackground(true); - m_button->setMinimumSize(32, 0); - m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); - m_button->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); - layout->addWidget(m_button); - - connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone())); -} - -void ColorEdit::editDone() -{ - bool ok; - QRgb newColor = m_lineEdit->text().toUInt(&ok, 16); - if (ok) - setColor(newColor); -} - -void ColorEdit::mousePressEvent(QMouseEvent *event) -{ - if (event->button() == Qt::LeftButton) { - QColor color(m_color); - QColorDialog dialog(color, 0); - dialog.setOption(QColorDialog::ShowAlphaChannel, true); -// The ifdef block is a workaround for the beta, TODO: remove when bug 238525 is fixed -#ifdef Q_WS_MAC - dialog.setOption(QColorDialog::DontUseNativeDialog, true); -#endif - dialog.move(280, 120); - if (dialog.exec() == QDialog::Rejected) - return; - QRgb newColor = dialog.selectedColor().rgba(); - if (newColor == m_color) - return; - setColor(newColor); - } -} - -void ColorEdit::setColor(QRgb color) -{ - m_color = color; - m_lineEdit->setText(QString::number(m_color, 16)); // "Clean up" text - QPalette palette = m_button->palette(); - palette.setColor(QPalette::Window, QColor(m_color)); - m_button->setPalette(palette); - emit colorChanged(m_color, m_id); -} - -//============================================================================// -// FloatEdit // -//============================================================================// - -FloatEdit::FloatEdit(float initialValue, int id) - : m_value(initialValue), m_id(id) -{ - QHBoxLayout *layout = new QHBoxLayout; - setLayout(layout); - layout->setContentsMargins(0, 0, 0, 0); - - m_lineEdit = new QLineEdit(QString::number(m_value)); - layout->addWidget(m_lineEdit); - - connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone())); -} - -void FloatEdit::editDone() -{ - bool ok; - float newValue = m_lineEdit->text().toFloat(&ok); - if (ok) { - m_value = newValue; - m_lineEdit->setText(QString::number(m_value)); // "Clean up" text - emit valueChanged(m_value, m_id); - } -} - -//============================================================================// -// TwoSidedGraphicsWidget // -//============================================================================// - -TwoSidedGraphicsWidget::TwoSidedGraphicsWidget(QGraphicsScene *scene) - : QObject(scene) - , m_current(0) - , m_angle(0) - , m_delta(0) -{ - for (int i = 0; i < 2; ++i) - m_proxyWidgets[i] = 0; -} - -void TwoSidedGraphicsWidget::setWidget(int index, QWidget *widget) -{ - if (index < 0 || index >= 2) - { - qWarning("TwoSidedGraphicsWidget::setWidget: Index out of bounds, index == %d", index); - return; - } - - GraphicsWidget *proxy = new GraphicsWidget; - proxy->setWidget(widget); - - if (m_proxyWidgets[index]) - delete m_proxyWidgets[index]; - m_proxyWidgets[index] = proxy; - - proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache); - proxy->setZValue(1e30); // Make sure the dialog is drawn on top of all other (OpenGL) items - - if (index != m_current) - proxy->setVisible(false); - - qobject_cast(parent())->addItem(proxy); -} - -QWidget *TwoSidedGraphicsWidget::widget(int index) -{ - if (index < 0 || index >= 2) - { - qWarning("TwoSidedGraphicsWidget::widget: Index out of bounds, index == %d", index); - return 0; - } - return m_proxyWidgets[index]->widget(); -} - -void TwoSidedGraphicsWidget::flip() -{ - m_delta = (m_current == 0 ? 9 : -9); - animateFlip(); -} - -void TwoSidedGraphicsWidget::animateFlip() -{ - m_angle += m_delta; - if (m_angle == 90) { - int old = m_current; - m_current ^= 1; - m_proxyWidgets[old]->setVisible(false); - m_proxyWidgets[m_current]->setVisible(true); - m_proxyWidgets[m_current]->setGeometry(m_proxyWidgets[old]->geometry()); - } - - QRectF r = m_proxyWidgets[m_current]->boundingRect(); - m_proxyWidgets[m_current]->setTransform(QTransform() - .translate(r.width() / 2, r.height() / 2) - .rotate(m_angle - 180 * m_current, Qt::YAxis) - .translate(-r.width() / 2, -r.height() / 2)); - - if ((m_current == 0 && m_angle > 0) || (m_current == 1 && m_angle < 180)) - QTimer::singleShot(25, this, SLOT(animateFlip())); -} - -QVariant GraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value) -{ - if (change == ItemPositionChange && scene()) { - QRectF rect = boundingRect(); - QPointF pos = value.toPointF(); - QRectF sceneRect = scene()->sceneRect(); - if (pos.x() + rect.left() < sceneRect.left()) - pos.setX(sceneRect.left() - rect.left()); - else if (pos.x() + rect.right() >= sceneRect.right()) - pos.setX(sceneRect.right() - rect.right()); - if (pos.y() + rect.top() < sceneRect.top()) - pos.setY(sceneRect.top() - rect.top()); - else if (pos.y() + rect.bottom() >= sceneRect.bottom()) - pos.setY(sceneRect.bottom() - rect.bottom()); - return pos; - } - return QGraphicsProxyWidget::itemChange(change, value); -} - -void GraphicsWidget::resizeEvent(QGraphicsSceneResizeEvent *event) -{ - setCacheMode(QGraphicsItem::NoCache); - setCacheMode(QGraphicsItem::ItemCoordinateCache); - QGraphicsProxyWidget::resizeEvent(event); -} - -void GraphicsWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) -{ - painter->setRenderHint(QPainter::Antialiasing, false); - QGraphicsProxyWidget::paint(painter, option, widget); - //painter->setRenderHint(QPainter::Antialiasing, true); -} - -//============================================================================// -// RenderOptionsDialog // -//============================================================================// - -RenderOptionsDialog::RenderOptionsDialog() - : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint) -{ - setWindowOpacity(0.75); - setWindowTitle(tr("Options (double click to flip)")); - QGridLayout *layout = new QGridLayout; - setLayout(layout); - layout->setColumnStretch(1, 1); - - int row = 0; - - QCheckBox *check = new QCheckBox(tr("Dynamic cube map")); - check->setCheckState(Qt::Unchecked); - // Dynamic cube maps are only enabled when multi-texturing and render to texture are available. - check->setEnabled(glActiveTexture && glGenFramebuffersEXT); - connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int))); - layout->addWidget(check, 0, 0, 1, 2); - ++row; - - QPalette palette; - - // Load all .par files - // .par files have a simple syntax for specifying user adjustable uniform variables. - QSet uniforms; - QList filter = QStringList("*.par"); - QList files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); - - foreach (QFileInfo fileInfo, files) { - QFile file(fileInfo.absoluteFilePath()); - if (file.open(QIODevice::ReadOnly)) { - while (!file.atEnd()) { - QList tokens = file.readLine().simplified().split(' '); - QList::const_iterator it = tokens.begin(); - if (it == tokens.end()) - continue; - QByteArray type = *it; - if (++it == tokens.end()) - continue; - QByteArray name = *it; - bool singleElement = (tokens.size() == 3); // type, name and one value - char counter[10] = "000000000"; - int counterPos = 8; // position of last digit - while (++it != tokens.end()) { - m_parameterNames << name; - if (!singleElement) { - m_parameterNames.back() += "["; - m_parameterNames.back() += counter + counterPos; - m_parameterNames.back() += "]"; - int j = 8; // position of last digit - ++counter[j]; - while (j > 0 && counter[j] > '9') { - counter[j] = '0'; - ++counter[--j]; - } - if (j < counterPos) - counterPos = j; - } - - if (type == "color") { - layout->addWidget(new QLabel(m_parameterNames.back())); - bool ok; - ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1); - m_parameterEdits << colorEdit; - layout->addWidget(colorEdit); - connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int))); - ++row; - } else if (type == "float") { - layout->addWidget(new QLabel(m_parameterNames.back())); - bool ok; - FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1); - m_parameterEdits << floatEdit; - layout->addWidget(floatEdit); - connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int))); - ++row; - } - } - } - file.close(); - } - } - - layout->addWidget(new QLabel(tr("Texture:"))); - m_textureCombo = new QComboBox; - connect(m_textureCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(textureChanged(int))); - layout->addWidget(m_textureCombo); - ++row; - - layout->addWidget(new QLabel(tr("Shader:"))); - m_shaderCombo = new QComboBox; - connect(m_shaderCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(shaderChanged(int))); - layout->addWidget(m_shaderCombo); - ++row; - - layout->setRowStretch(row, 1); -} - -int RenderOptionsDialog::addTexture(const QString &name) -{ - m_textureCombo->addItem(name); - return m_textureCombo->count() - 1; -} - -int RenderOptionsDialog::addShader(const QString &name) -{ - m_shaderCombo->addItem(name); - return m_shaderCombo->count() - 1; -} - -void RenderOptionsDialog::emitParameterChanged() -{ - foreach (ParameterEdit *edit, m_parameterEdits) - edit->emitChange(); -} - -void RenderOptionsDialog::setColorParameter(QRgb color, int id) -{ - emit colorParameterChanged(m_parameterNames[id], color); -} - -void RenderOptionsDialog::setFloatParameter(float value, int id) -{ - emit floatParameterChanged(m_parameterNames[id], value); -} - -void RenderOptionsDialog::mouseDoubleClickEvent(QMouseEvent *event) -{ - if (event->button() == Qt::LeftButton) - emit doubleClicked(); -} - -//============================================================================// -// ItemDialog // -//============================================================================// - -ItemDialog::ItemDialog() - : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint) -{ - setWindowTitle(tr("Items (double click to flip)")); - setWindowOpacity(0.75); - resize(160, 100); - - QVBoxLayout *layout = new QVBoxLayout; - setLayout(layout); - QPushButton *button; - - button = new QPushButton(tr("Add Qt box")); - layout->addWidget(button); - connect(button, SIGNAL(clicked()), this, SLOT(triggerNewQtBox())); - - button = new QPushButton(tr("Add circle")); - layout->addWidget(button); - connect(button, SIGNAL(clicked()), this, SLOT(triggerNewCircleItem())); - - button = new QPushButton(tr("Add square")); - layout->addWidget(button); - connect(button, SIGNAL(clicked()), this, SLOT(triggerNewSquareItem())); - - layout->addStretch(1); -} - -void ItemDialog::triggerNewQtBox() -{ - emit newItemTriggered(QtBoxItem); -} - -void ItemDialog::triggerNewCircleItem() -{ - emit newItemTriggered(CircleItem); -} - -void ItemDialog::triggerNewSquareItem() -{ - emit newItemTriggered(SquareItem); -} - -void ItemDialog::mouseDoubleClickEvent(QMouseEvent *event) -{ - if (event->button() == Qt::LeftButton) - emit doubleClicked(); -} - -//============================================================================// -// Scene // -//============================================================================// - -const static char environmentShaderText[] = - "uniform samplerCube env;" - "void main() {" - "gl_FragColor = textureCube(env, gl_TexCoord[1].xyz);" - "}"; - -Scene::Scene(int width, int height, int maxTextureSize) - : m_distExp(600) - , m_frame(0) - , m_maxTextureSize(maxTextureSize) - , m_currentShader(0) - , m_currentTexture(0) - , m_dynamicCubemap(false) - , m_updateAllCubemaps(true) - , m_box(0) - , m_vertexShader(0) - , m_environmentShader(0) - , m_environmentProgram(0) -{ - setSceneRect(0, 0, width, height); - - m_trackBalls[0] = TrackBall(0.05f, QVector3D(0, 1, 0), TrackBall::Sphere); - m_trackBalls[1] = TrackBall(0.005f, QVector3D(0, 0, 1), TrackBall::Sphere); - m_trackBalls[2] = TrackBall(0.0f, QVector3D(0, 1, 0), TrackBall::Plane); - - m_renderOptions = new RenderOptionsDialog; - m_renderOptions->move(20, 120); - m_renderOptions->resize(m_renderOptions->sizeHint()); - - connect(m_renderOptions, SIGNAL(dynamicCubemapToggled(int)), this, SLOT(toggleDynamicCubemap(int))); - connect(m_renderOptions, SIGNAL(colorParameterChanged(QString,QRgb)), this, SLOT(setColorParameter(QString,QRgb))); - connect(m_renderOptions, SIGNAL(floatParameterChanged(QString,float)), this, SLOT(setFloatParameter(QString,float))); - connect(m_renderOptions, SIGNAL(textureChanged(int)), this, SLOT(setTexture(int))); - connect(m_renderOptions, SIGNAL(shaderChanged(int)), this, SLOT(setShader(int))); - - m_itemDialog = new ItemDialog; - connect(m_itemDialog, SIGNAL(newItemTriggered(ItemDialog::ItemType)), this, SLOT(newItem(ItemDialog::ItemType))); - - TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this); - twoSided->setWidget(0, m_renderOptions); - twoSided->setWidget(1, m_itemDialog); - - connect(m_renderOptions, SIGNAL(doubleClicked()), twoSided, SLOT(flip())); - connect(m_itemDialog, SIGNAL(doubleClicked()), twoSided, SLOT(flip())); - - addItem(new QtBox(64, width - 64, height - 64)); - addItem(new QtBox(64, width - 64, 64)); - addItem(new QtBox(64, 64, height - 64)); - addItem(new QtBox(64, 64, 64)); - - initGL(); - - m_timer = new QTimer(this); - m_timer->setInterval(20); - connect(m_timer, SIGNAL(timeout()), this, SLOT(update())); - m_timer->start(); - - m_time.start(); -} - -Scene::~Scene() -{ - if (m_box) - delete m_box; - foreach (GLTexture *texture, m_textures) - if (texture) delete texture; - if (m_mainCubemap) - delete m_mainCubemap; - foreach (QGLShaderProgram *program, m_programs) - if (program) delete program; - if (m_vertexShader) - delete m_vertexShader; - foreach (QGLShader *shader, m_fragmentShaders) - if (shader) delete shader; - foreach (GLRenderTargetCube *rt, m_cubemaps) - if (rt) delete rt; - if (m_environmentShader) - delete m_environmentShader; - if (m_environmentProgram) - delete m_environmentProgram; -} - -void Scene::initGL() -{ - m_box = new GLRoundedBox(0.25f, 1.0f, 10); - - m_vertexShader = new QGLShader(QGLShader::Vertex); - m_vertexShader->compileSourceFile(QLatin1String(":/res/boxes/basic.vsh")); - - QStringList list; - list << ":/res/boxes/cubemap_posx.jpg" << ":/res/boxes/cubemap_negx.jpg" << ":/res/boxes/cubemap_posy.jpg" - << ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg"; - m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize)); - m_environmentShader = new QGLShader(QGLShader::Fragment); - m_environmentShader->compileSourceCode(environmentShaderText); - m_environmentProgram = new QGLShaderProgram; - m_environmentProgram->addShader(m_vertexShader); - m_environmentProgram->addShader(m_environmentShader); - m_environmentProgram->link(); - - const int NOISE_SIZE = 128; // for a different size, B and BM in fbm.c must also be changed - m_noise = new GLTexture3D(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE); - QRgb *data = new QRgb[NOISE_SIZE * NOISE_SIZE * NOISE_SIZE]; - memset(data, 0, NOISE_SIZE * NOISE_SIZE * NOISE_SIZE * sizeof(QRgb)); - QRgb *p = data; - float pos[3]; - for (int k = 0; k < NOISE_SIZE; ++k) { - pos[2] = k * (0x20 / (float)NOISE_SIZE); - for (int j = 0; j < NOISE_SIZE; ++j) { - for (int i = 0; i < NOISE_SIZE; ++i) { - for (int byte = 0; byte < 4; ++byte) { - pos[0] = (i + (byte & 1) * 16) * (0x20 / (float)NOISE_SIZE); - pos[1] = (j + (byte & 2) * 8) * (0x20 / (float)NOISE_SIZE); - *p |= (int)(128.0f * (noise3(pos) + 1.0f)) << (byte * 8); - } - ++p; - } - } - } - m_noise->load(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, data); - delete[] data; - - m_mainCubemap = new GLRenderTargetCube(512); - - QStringList filter; - QList files; - - // Load all .png files as textures - m_currentTexture = 0; - filter = QStringList("*.png"); - files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); - - foreach (QFileInfo file, files) { - GLTexture *texture = new GLTexture2D(file.absoluteFilePath(), qMin(256, m_maxTextureSize), qMin(256, m_maxTextureSize)); - if (texture->failed()) { - delete texture; - continue; - } - m_textures << texture; - m_renderOptions->addTexture(file.baseName()); - } - - if (m_textures.size() == 0) - m_textures << new GLTexture2D(qMin(64, m_maxTextureSize), qMin(64, m_maxTextureSize)); - - // Load all .fsh files as fragment shaders - m_currentShader = 0; - filter = QStringList("*.fsh"); - files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); - foreach (QFileInfo file, files) { - QGLShaderProgram *program = new QGLShaderProgram; - QGLShader* shader = new QGLShader(QGLShader::Fragment); - shader->compileSourceFile(file.absoluteFilePath()); - // The program does not take ownership over the shaders, so store them in a vector so they can be deleted afterwards. - program->addShader(m_vertexShader); - program->addShader(shader); - if (!program->link()) { - qWarning("Failed to compile and link shader program"); - qWarning("Vertex shader log:"); - qWarning() << m_vertexShader->log(); - qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):"; - qWarning() << shader->log(); - qWarning("Shader program log:"); - qWarning() << program->log(); - - delete shader; - delete program; - continue; - } - - m_fragmentShaders << shader; - m_programs << program; - m_renderOptions->addShader(file.baseName()); - - program->bind(); - m_cubemaps << ((program->uniformLocation("env") != -1) ? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : 0); - program->release(); - } - - if (m_programs.size() == 0) - m_programs << new QGLShaderProgram; - - m_renderOptions->emitParameterChanged(); -} - -static void loadMatrix(const QMatrix4x4& m) -{ - // static to prevent glLoadMatrixf to fail on certain drivers - static GLfloat mat[16]; - const qreal *data = m.constData(); - for (int index = 0; index < 16; ++index) - mat[index] = data[index]; - glLoadMatrixf(mat); -} - -static void multMatrix(const QMatrix4x4& m) -{ - // static to prevent glMultMatrixf to fail on certain drivers - static GLfloat mat[16]; - const qreal *data = m.constData(); - for (int index = 0; index < 16; ++index) - mat[index] = data[index]; - glMultMatrixf(mat); -} - -// If one of the boxes should not be rendered, set excludeBox to its index. -// If the main box should not be rendered, set excludeBox to -1. -void Scene::renderBoxes(const QMatrix4x4 &view, int excludeBox) -{ - QMatrix4x4 invView = view.inverted(); - - // If multi-texturing is supported, use three saplers. - if (glActiveTexture) { - glActiveTexture(GL_TEXTURE0); - m_textures[m_currentTexture]->bind(); - glActiveTexture(GL_TEXTURE2); - m_noise->bind(); - glActiveTexture(GL_TEXTURE1); - } else { - m_textures[m_currentTexture]->bind(); - } - - glDisable(GL_LIGHTING); - glDisable(GL_CULL_FACE); - - QMatrix4x4 viewRotation(view); - viewRotation(3, 0) = viewRotation(3, 1) = viewRotation(3, 2) = 0.0f; - viewRotation(0, 3) = viewRotation(1, 3) = viewRotation(2, 3) = 0.0f; - viewRotation(3, 3) = 1.0f; - loadMatrix(viewRotation); - glScalef(20.0f, 20.0f, 20.0f); - - // Don't render the environment if the environment texture can't be set for the correct sampler. - if (glActiveTexture) { - m_environment->bind(); - m_environmentProgram->bind(); - m_environmentProgram->setUniformValue("tex", GLint(0)); - m_environmentProgram->setUniformValue("env", GLint(1)); - m_environmentProgram->setUniformValue("noise", GLint(2)); - m_box->draw(); - m_environmentProgram->release(); - m_environment->unbind(); - } - - loadMatrix(view); - - glEnable(GL_CULL_FACE); - glEnable(GL_LIGHTING); - - for (int i = 0; i < m_programs.size(); ++i) { - if (i == excludeBox) - continue; - - glPushMatrix(); - QMatrix4x4 m; - m.rotate(m_trackBalls[1].rotation()); - multMatrix(m); - - glRotatef(360.0f * i / m_programs.size(), 0.0f, 0.0f, 1.0f); - glTranslatef(2.0f, 0.0f, 0.0f); - glScalef(0.3f, 0.6f, 0.6f); - - if (glActiveTexture) { - if (m_dynamicCubemap && m_cubemaps[i]) - m_cubemaps[i]->bind(); - else - m_environment->bind(); - } - m_programs[i]->bind(); - m_programs[i]->setUniformValue("tex", GLint(0)); - m_programs[i]->setUniformValue("env", GLint(1)); - m_programs[i]->setUniformValue("noise", GLint(2)); - m_programs[i]->setUniformValue("view", view); - m_programs[i]->setUniformValue("invView", invView); - m_box->draw(); - m_programs[i]->release(); - - if (glActiveTexture) { - if (m_dynamicCubemap && m_cubemaps[i]) - m_cubemaps[i]->unbind(); - else - m_environment->unbind(); - } - glPopMatrix(); - } - - if (-1 != excludeBox) { - QMatrix4x4 m; - m.rotate(m_trackBalls[0].rotation()); - multMatrix(m); - - if (glActiveTexture) { - if (m_dynamicCubemap) - m_mainCubemap->bind(); - else - m_environment->bind(); - } - - m_programs[m_currentShader]->bind(); - m_programs[m_currentShader]->setUniformValue("tex", GLint(0)); - m_programs[m_currentShader]->setUniformValue("env", GLint(1)); - m_programs[m_currentShader]->setUniformValue("noise", GLint(2)); - m_programs[m_currentShader]->setUniformValue("view", view); - m_programs[m_currentShader]->setUniformValue("invView", invView); - m_box->draw(); - m_programs[m_currentShader]->release(); - - if (glActiveTexture) { - if (m_dynamicCubemap) - m_mainCubemap->unbind(); - else - m_environment->unbind(); - } - } - - if (glActiveTexture) { - glActiveTexture(GL_TEXTURE2); - m_noise->unbind(); - glActiveTexture(GL_TEXTURE0); - } - m_textures[m_currentTexture]->unbind(); -} - -void Scene::setStates() -{ - //glClearColor(0.25f, 0.25f, 0.5f, 1.0f); - - glEnable(GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - glEnable(GL_LIGHTING); - //glEnable(GL_COLOR_MATERIAL); - glEnable(GL_TEXTURE_2D); - glEnable(GL_NORMALIZE); - - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - - setLights(); - - float materialSpecular[] = {0.5f, 0.5f, 0.5f, 1.0f}; - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular); - glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 32.0f); -} - -void Scene::setLights() -{ - glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); - //float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f}; - float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f}; - //glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour); - //glLightfv(GL_LIGHT0, GL_SPECULAR, lightColour); - glLightfv(GL_LIGHT0, GL_POSITION, lightDir); - glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0f); - glEnable(GL_LIGHT0); -} - -void Scene::defaultStates() -{ - //glClearColor(0.0f, 0.0f, 0.0f, 0.0f); - - glDisable(GL_DEPTH_TEST); - glDisable(GL_CULL_FACE); - glDisable(GL_LIGHTING); - //glDisable(GL_COLOR_MATERIAL); - glDisable(GL_TEXTURE_2D); - glDisable(GL_LIGHT0); - glDisable(GL_NORMALIZE); - - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); - - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - - glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 0.0f); - float defaultMaterialSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f}; - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defaultMaterialSpecular); - glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f); -} - -void Scene::renderCubemaps() -{ - // To speed things up, only update the cubemaps for the small cubes every N frames. - const int N = (m_updateAllCubemaps ? 1 : 3); - - QMatrix4x4 mat; - GLRenderTargetCube::getProjectionMatrix(mat, 0.1f, 100.0f); - - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - loadMatrix(mat); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - - QVector3D center; - - for (int i = m_frame % N; i < m_cubemaps.size(); i += N) { - if (0 == m_cubemaps[i]) - continue; - - float angle = 2.0f * PI * i / m_cubemaps.size(); - - center = m_trackBalls[1].rotation().rotatedVector(QVector3D(cos(angle), sin(angle), 0.0f)); - - for (int face = 0; face < 6; ++face) { - m_cubemaps[i]->begin(face); - - GLRenderTargetCube::getViewMatrix(mat, face); - QVector4D v = QVector4D(-center.x(), -center.y(), -center.z(), 1.0); - mat.setColumn(3, mat * v); - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - renderBoxes(mat, i); - - m_cubemaps[i]->end(); - } - } - - for (int face = 0; face < 6; ++face) { - m_mainCubemap->begin(face); - GLRenderTargetCube::getViewMatrix(mat, face); - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - renderBoxes(mat, -1); - - m_mainCubemap->end(); - } - - glPopMatrix(); - - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - - m_updateAllCubemaps = false; -} - -void Scene::drawBackground(QPainter *painter, const QRectF &) -{ - float width = float(painter->device()->width()); - float height = float(painter->device()->height()); - - painter->beginNativePainting(); - setStates(); - - if (m_dynamicCubemap) - renderCubemaps(); - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - glMatrixMode(GL_PROJECTION); - qgluPerspective(60.0, width / height, 0.01, 15.0); - - glMatrixMode(GL_MODELVIEW); - - QMatrix4x4 view; - view.rotate(m_trackBalls[2].rotation()); - view(2, 3) -= 2.0f * exp(m_distExp / 1200.0f); - renderBoxes(view); - - defaultStates(); - ++m_frame; - - painter->endNativePainting(); -} - -QPointF Scene::pixelPosToViewPos(const QPointF& p) -{ - return QPointF(2.0 * float(p.x()) / width() - 1.0, - 1.0 - 2.0 * float(p.y()) / height()); -} - -void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) -{ - QGraphicsScene::mouseMoveEvent(event); - if (event->isAccepted()) - return; - - if (event->buttons() & Qt::LeftButton) { - m_trackBalls[0].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); - event->accept(); - } else { - m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); - } - - if (event->buttons() & Qt::RightButton) { - m_trackBalls[1].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); - event->accept(); - } else { - m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); - } - - if (event->buttons() & Qt::MidButton) { - m_trackBalls[2].move(pixelPosToViewPos(event->scenePos()), QQuaternion()); - event->accept(); - } else { - m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion()); - } -} - -void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - QGraphicsScene::mousePressEvent(event); - if (event->isAccepted()) - return; - - if (event->buttons() & Qt::LeftButton) { - m_trackBalls[0].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); - event->accept(); - } - - if (event->buttons() & Qt::RightButton) { - m_trackBalls[1].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); - event->accept(); - } - - if (event->buttons() & Qt::MidButton) { - m_trackBalls[2].push(pixelPosToViewPos(event->scenePos()), QQuaternion()); - event->accept(); - } -} - -void Scene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) -{ - QGraphicsScene::mouseReleaseEvent(event); - if (event->isAccepted()) - return; - - if (event->button() == Qt::LeftButton) { - m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); - event->accept(); - } - - if (event->button() == Qt::RightButton) { - m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); - event->accept(); - } - - if (event->button() == Qt::MidButton) { - m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion()); - event->accept(); - } -} - -void Scene::wheelEvent(QGraphicsSceneWheelEvent * event) -{ - QGraphicsScene::wheelEvent(event); - if (!event->isAccepted()) { - m_distExp += event->delta(); - if (m_distExp < -8 * 120) - m_distExp = -8 * 120; - if (m_distExp > 10 * 120) - m_distExp = 10 * 120; - event->accept(); - } -} - -void Scene::setShader(int index) -{ - if (index >= 0 && index < m_fragmentShaders.size()) - m_currentShader = index; -} - -void Scene::setTexture(int index) -{ - if (index >= 0 && index < m_textures.size()) - m_currentTexture = index; -} - -void Scene::toggleDynamicCubemap(int state) -{ - if ((m_dynamicCubemap = (state == Qt::Checked))) - m_updateAllCubemaps = true; -} - -void Scene::setColorParameter(const QString &name, QRgb color) -{ - // set the color in all programs - foreach (QGLShaderProgram *program, m_programs) { - program->bind(); - program->setUniformValue(program->uniformLocation(name), QColor(color)); - program->release(); - } -} - -void Scene::setFloatParameter(const QString &name, float value) -{ - // set the color in all programs - foreach (QGLShaderProgram *program, m_programs) { - program->bind(); - program->setUniformValue(program->uniformLocation(name), value); - program->release(); - } -} - -void Scene::newItem(ItemDialog::ItemType type) -{ - QSize size = sceneRect().size().toSize(); - switch (type) { - case ItemDialog::QtBoxItem: - addItem(new QtBox(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); - break; - case ItemDialog::CircleItem: - addItem(new CircleItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); - break; - case ItemDialog::SquareItem: - addItem(new SquareItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); - break; - default: - break; - } -} diff --git a/demos/boxes/scene.h b/demos/boxes/scene.h deleted file mode 100644 index 96ee908d58..0000000000 --- a/demos/boxes/scene.h +++ /dev/null @@ -1,245 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SCENE_H -#define SCENE_H - -//#include -#include "glextensions.h" - -#include -#include - -#include "roundedbox.h" -#include "gltrianglemesh.h" -#include "trackball.h" -#include "glbuffers.h" -#include "qtbox.h" - -#define PI 3.14159265358979 - -QT_BEGIN_NAMESPACE -class QMatrix4x4; -QT_END_NAMESPACE - -class ParameterEdit : public QWidget -{ -public: - virtual void emitChange() = 0; -}; - -class ColorEdit : public ParameterEdit -{ - Q_OBJECT -public: - ColorEdit(QRgb initialColor, int id); - QRgb color() const {return m_color;} - virtual void emitChange() {emit colorChanged(m_color, m_id);} -public slots: - void editDone(); -signals: - void colorChanged(QRgb color, int id); -protected: - virtual void mousePressEvent(QMouseEvent *event); - void setColor(QRgb color); // also emits colorChanged() -private: - QGraphicsScene *m_dialogParentScene; - QLineEdit *m_lineEdit; - QFrame *m_button; - QRgb m_color; - int m_id; -}; - -class FloatEdit : public ParameterEdit -{ - Q_OBJECT -public: - FloatEdit(float initialValue, int id); - float value() const {return m_value;} - virtual void emitChange() {emit valueChanged(m_value, m_id);} -public slots: - void editDone(); -signals: - void valueChanged(float value, int id); -private: - QGraphicsScene *m_dialogParentScene; - QLineEdit *m_lineEdit; - float m_value; - int m_id; -}; - -class GraphicsWidget : public QGraphicsProxyWidget -{ -public: - GraphicsWidget() : QGraphicsProxyWidget(0, Qt::Window) {} -protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); - virtual void resizeEvent(QGraphicsSceneResizeEvent *event); - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); -}; - -class TwoSidedGraphicsWidget : public QObject -{ - Q_OBJECT -public: - TwoSidedGraphicsWidget(QGraphicsScene *scene); - void setWidget(int index, QWidget *widget); - QWidget *widget(int index); -public slots: - void flip(); -protected slots: - void animateFlip(); -private: - GraphicsWidget *m_proxyWidgets[2]; - int m_current; - int m_angle; // angle in degrees - int m_delta; -}; - -class RenderOptionsDialog : public QDialog -{ - Q_OBJECT -public: - RenderOptionsDialog(); - int addTexture(const QString &name); - int addShader(const QString &name); - void emitParameterChanged(); -protected slots: - void setColorParameter(QRgb color, int id); - void setFloatParameter(float value, int id); -signals: - void dynamicCubemapToggled(int); - void colorParameterChanged(const QString &, QRgb); - void floatParameterChanged(const QString &, float); - void textureChanged(int); - void shaderChanged(int); - void doubleClicked(); -protected: - virtual void mouseDoubleClickEvent(QMouseEvent *event); - - QVector m_parameterNames; - QComboBox *m_textureCombo; - QComboBox *m_shaderCombo; - QVector m_parameterEdits; -}; - -class ItemDialog : public QDialog -{ - Q_OBJECT -public: - enum ItemType { - QtBoxItem, - CircleItem, - SquareItem, - }; - - ItemDialog(); -public slots: - void triggerNewQtBox(); - void triggerNewCircleItem(); - void triggerNewSquareItem(); -signals: - void doubleClicked(); - void newItemTriggered(ItemDialog::ItemType type); -protected: - virtual void mouseDoubleClickEvent(QMouseEvent *event); -}; - -class Scene : public QGraphicsScene -{ - Q_OBJECT -public: - Scene(int width, int height, int maxTextureSize); - ~Scene(); - virtual void drawBackground(QPainter *painter, const QRectF &rect); - -public slots: - void setShader(int index); - void setTexture(int index); - void toggleDynamicCubemap(int state); - void setColorParameter(const QString &name, QRgb color); - void setFloatParameter(const QString &name, float value); - void newItem(ItemDialog::ItemType type); -protected: - void renderBoxes(const QMatrix4x4 &view, int excludeBox = -2); - void setStates(); - void setLights(); - void defaultStates(); - void renderCubemaps(); - - virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - virtual void wheelEvent(QGraphicsSceneWheelEvent * event); -private: - void initGL(); - QPointF pixelPosToViewPos(const QPointF& p); - - QTime m_time; - int m_lastTime; - int m_mouseEventTime; - int m_distExp; - int m_frame; - int m_maxTextureSize; - - int m_currentShader; - int m_currentTexture; - bool m_dynamicCubemap; - bool m_updateAllCubemaps; - - RenderOptionsDialog *m_renderOptions; - ItemDialog *m_itemDialog; - QTimer *m_timer; - GLRoundedBox *m_box; - TrackBall m_trackBalls[3]; - QVector m_textures; - GLTextureCube *m_environment; - GLTexture3D *m_noise; - GLRenderTargetCube *m_mainCubemap; - QVector m_cubemaps; - QVector m_programs; - QGLShader *m_vertexShader; - QVector m_fragmentShaders; - QGLShader *m_environmentShader; - QGLShaderProgram *m_environmentProgram; -}; - -#endif diff --git a/demos/boxes/smiley.png b/demos/boxes/smiley.png deleted file mode 100644 index 41cfda6b23..0000000000 Binary files a/demos/boxes/smiley.png and /dev/null differ diff --git a/demos/boxes/square.jpg b/demos/boxes/square.jpg deleted file mode 100644 index 03f53bd530..0000000000 Binary files a/demos/boxes/square.jpg and /dev/null differ diff --git a/demos/boxes/trackball.cpp b/demos/boxes/trackball.cpp deleted file mode 100644 index 1bb864ce90..0000000000 --- a/demos/boxes/trackball.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "trackball.h" -#include "scene.h" - -//============================================================================// -// TrackBall // -//============================================================================// - -TrackBall::TrackBall(TrackMode mode) - : m_angularVelocity(0) - , m_paused(false) - , m_pressed(false) - , m_mode(mode) -{ - m_axis = QVector3D(0, 1, 0); - m_rotation = QQuaternion(); - m_lastTime = QTime::currentTime(); -} - -TrackBall::TrackBall(float angularVelocity, const QVector3D& axis, TrackMode mode) - : m_axis(axis) - , m_angularVelocity(angularVelocity) - , m_paused(false) - , m_pressed(false) - , m_mode(mode) -{ - m_rotation = QQuaternion(); - m_lastTime = QTime::currentTime(); -} - -void TrackBall::push(const QPointF& p, const QQuaternion &) -{ - m_rotation = rotation(); - m_pressed = true; - m_lastTime = QTime::currentTime(); - m_lastPos = p; - m_angularVelocity = 0.0f; -} - -void TrackBall::move(const QPointF& p, const QQuaternion &transformation) -{ - if (!m_pressed) - return; - - QTime currentTime = QTime::currentTime(); - int msecs = m_lastTime.msecsTo(currentTime); - if (msecs <= 20) - return; - - switch (m_mode) { - case Plane: - { - QLineF delta(m_lastPos, p); - m_angularVelocity = 180*delta.length() / (PI*msecs); - m_axis = QVector3D(-delta.dy(), delta.dx(), 0.0f).normalized(); - m_axis = transformation.rotatedVector(m_axis); - m_rotation = QQuaternion::fromAxisAndAngle(m_axis, 180 / PI * delta.length()) * m_rotation; - } - break; - case Sphere: - { - QVector3D lastPos3D = QVector3D(m_lastPos.x(), m_lastPos.y(), 0.0f); - float sqrZ = 1 - QVector3D::dotProduct(lastPos3D, lastPos3D); - if (sqrZ > 0) - lastPos3D.setZ(sqrt(sqrZ)); - else - lastPos3D.normalize(); - - QVector3D currentPos3D = QVector3D(p.x(), p.y(), 0.0f); - sqrZ = 1 - QVector3D::dotProduct(currentPos3D, currentPos3D); - if (sqrZ > 0) - currentPos3D.setZ(sqrt(sqrZ)); - else - currentPos3D.normalize(); - - m_axis = QVector3D::crossProduct(lastPos3D, currentPos3D); - float angle = 180 / PI * asin(sqrt(QVector3D::dotProduct(m_axis, m_axis))); - - m_angularVelocity = angle / msecs; - m_axis.normalize(); - m_axis = transformation.rotatedVector(m_axis); - m_rotation = QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation; - } - break; - } - - - m_lastPos = p; - m_lastTime = currentTime; -} - -void TrackBall::release(const QPointF& p, const QQuaternion &transformation) -{ - // Calling move() caused the rotation to stop if the framerate was too low. - move(p, transformation); - m_pressed = false; -} - -void TrackBall::start() -{ - m_lastTime = QTime::currentTime(); - m_paused = false; -} - -void TrackBall::stop() -{ - m_rotation = rotation(); - m_paused = true; -} - -QQuaternion TrackBall::rotation() const -{ - if (m_paused || m_pressed) - return m_rotation; - - QTime currentTime = QTime::currentTime(); - float angle = m_angularVelocity * m_lastTime.msecsTo(currentTime); - return QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation; -} - diff --git a/demos/boxes/trackball.h b/demos/boxes/trackball.h deleted file mode 100644 index 097851a42c..0000000000 --- a/demos/boxes/trackball.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef TRACKBALL_H -#define TRACKBALL_H - -#include - -#include -#include - -class TrackBall -{ -public: - enum TrackMode - { - Plane, - Sphere, - }; - TrackBall(TrackMode mode = Sphere); - TrackBall(float angularVelocity, const QVector3D& axis, TrackMode mode = Sphere); - // coordinates in [-1,1]x[-1,1] - void push(const QPointF& p, const QQuaternion &transformation); - void move(const QPointF& p, const QQuaternion &transformation); - void release(const QPointF& p, const QQuaternion &transformation); - void start(); // starts clock - void stop(); // stops clock - QQuaternion rotation() const; -private: - QQuaternion m_rotation; - QVector3D m_axis; - float m_angularVelocity; - - QPointF m_lastPos; - QTime m_lastTime; - bool m_paused; - bool m_pressed; - TrackMode m_mode; -}; - -#endif diff --git a/demos/boxes/wood.fsh b/demos/boxes/wood.fsh deleted file mode 100644 index 19950b252c..0000000000 --- a/demos/boxes/wood.fsh +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -varying vec3 position, normal; -varying vec4 specular, ambient, diffuse, lightDirection; - -uniform sampler2D tex; -uniform sampler3D noise; - -//const vec4 woodColors[2] = {vec4(0.37,0.24,0.20,1), vec4(0.8,0.6,0.4,1)}; -uniform vec4 woodColors[2]; -//const float woodTubulence = 0.1; -uniform float woodTubulence; - -void main() -{ - float r = length(gl_TexCoord[1].yz); - r += woodTubulence * texture3D(noise, 0.25 * gl_TexCoord[1].xyz).x; - - vec3 N = normalize(normal); - // assume directional light - - gl_MaterialParameters M = gl_FrontMaterial; - - float NdotL = dot(N, lightDirection.xyz); - float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); - - float f = fract(16.0 * r); - vec4 unlitColor = mix(woodColors[0], woodColors[1], min(1.25 * f, 5.0 - 5.0 * f)); - gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + - M.specular * specular * pow(max(RdotL, 0.0), M.shininess); -} diff --git a/demos/chip/chip.cpp b/demos/chip/chip.cpp deleted file mode 100644 index 21b63bae2c..0000000000 --- a/demos/chip/chip.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "chip.h" - -#include - -Chip::Chip(const QColor &color, int x, int y) -{ - this->x = x; - this->y = y; - this->color = color; - setZValue((x + y) % 2); - - setFlags(ItemIsSelectable | ItemIsMovable); - setAcceptsHoverEvents(true); -} - -QRectF Chip::boundingRect() const -{ - return QRectF(0, 0, 110, 70); -} - -QPainterPath Chip::shape() const -{ - QPainterPath path; - path.addRect(14, 14, 82, 42); - return path; -} - -void Chip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) -{ - Q_UNUSED(widget); - - QColor fillColor = (option->state & QStyle::State_Selected) ? color.dark(150) : color; - if (option->state & QStyle::State_MouseOver) - fillColor = fillColor.light(125); - - const qreal lod = option->levelOfDetailFromTransform(painter->worldTransform()); - if (lod < 0.2) { - if (lod < 0.125) { - painter->fillRect(QRectF(0, 0, 110, 70), fillColor); - return; - } - - QBrush b = painter->brush(); - painter->setBrush(fillColor); - painter->drawRect(13, 13, 97, 57); - painter->setBrush(b); - return; - } - - QPen oldPen = painter->pen(); - QPen pen = oldPen; - int width = 0; - if (option->state & QStyle::State_Selected) - width += 2; - - pen.setWidth(width); - QBrush b = painter->brush(); - painter->setBrush(QBrush(fillColor.dark(option->state & QStyle::State_Sunken ? 120 : 100))); - - painter->drawRect(QRect(14, 14, 79, 39)); - painter->setBrush(b); - - if (lod >= 1) { - painter->setPen(QPen(Qt::gray, 1)); - painter->drawLine(15, 54, 94, 54); - painter->drawLine(94, 53, 94, 15); - painter->setPen(QPen(Qt::black, 0)); - } - - // Draw text - if (lod >= 2) { - QFont font("Times", 10); - font.setStyleStrategy(QFont::ForceOutline); - painter->setFont(font); - painter->save(); - painter->scale(0.1, 0.1); - painter->drawText(170, 180, QString("Model: VSC-2000 (Very Small Chip) at %1x%2").arg(x).arg(y)); - painter->drawText(170, 200, QString("Serial number: DLWR-WEER-123L-ZZ33-SDSJ")); - painter->drawText(170, 220, QString("Manufacturer: Chip Manufacturer")); - painter->restore(); - } - - // Draw lines - QVarLengthArray lines; - if (lod >= 0.5) { - for (int i = 0; i <= 10; i += (lod > 0.5 ? 1 : 2)) { - lines.append(QLineF(18 + 7 * i, 13, 18 + 7 * i, 5)); - lines.append(QLineF(18 + 7 * i, 54, 18 + 7 * i, 62)); - } - for (int i = 0; i <= 6; i += (lod > 0.5 ? 1 : 2)) { - lines.append(QLineF(5, 18 + i * 5, 13, 18 + i * 5)); - lines.append(QLineF(94, 18 + i * 5, 102, 18 + i * 5)); - } - } - if (lod >= 0.4) { - const QLineF lineData[] = { - QLineF(25, 35, 35, 35), - QLineF(35, 30, 35, 40), - QLineF(35, 30, 45, 35), - QLineF(35, 40, 45, 35), - QLineF(45, 30, 45, 40), - QLineF(45, 35, 55, 35) - }; - lines.append(lineData, 6); - } - painter->drawLines(lines.data(), lines.size()); - - // Draw red ink - if (stuff.size() > 1) { - QPen p = painter->pen(); - painter->setPen(QPen(Qt::red, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - painter->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo(stuff.first()); - for (int i = 1; i < stuff.size(); ++i) - path.lineTo(stuff.at(i)); - painter->drawPath(path); - painter->setPen(p); - } -} - -void Chip::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - QGraphicsItem::mousePressEvent(event); - update(); -} - -void Chip::mouseMoveEvent(QGraphicsSceneMouseEvent *event) -{ - if (event->modifiers() & Qt::ShiftModifier) { - stuff << event->pos(); - update(); - return; - } - QGraphicsItem::mouseMoveEvent(event); -} - -void Chip::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) -{ - QGraphicsItem::mouseReleaseEvent(event); - update(); -} diff --git a/demos/chip/chip.h b/demos/chip/chip.h deleted file mode 100644 index ff9f636843..0000000000 --- a/demos/chip/chip.h +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef CHIP_H -#define CHIP_H - -#include -#include - -class Chip : public QGraphicsItem -{ -public: - Chip(const QColor &color, int x, int y); - - QRectF boundingRect() const; - QPainterPath shape() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget); - -protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - -private: - int x, y; - QColor color; - QList stuff; -}; - -#endif diff --git a/demos/chip/chip.pro b/demos/chip/chip.pro deleted file mode 100644 index 1e1a7de735..0000000000 --- a/demos/chip/chip.pro +++ /dev/null @@ -1,20 +0,0 @@ -RESOURCES += images.qrc - -HEADERS += mainwindow.h view.h chip.h -SOURCES += main.cpp -SOURCES += mainwindow.cpp view.cpp chip.cpp - -contains(QT_CONFIG, opengl):QT += opengl - -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/chip -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.png *.pro *.html *.doc images -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/chip -INSTALLS += target sources - -symbian: CONFIG += qt_demo diff --git a/demos/chip/fileprint.png b/demos/chip/fileprint.png deleted file mode 100644 index ba7c02dc18..0000000000 Binary files a/demos/chip/fileprint.png and /dev/null differ diff --git a/demos/chip/images.qrc b/demos/chip/images.qrc deleted file mode 100644 index c7cdf0c4c0..0000000000 --- a/demos/chip/images.qrc +++ /dev/null @@ -1,10 +0,0 @@ - - - qt4logo.png - zoomin.png - zoomout.png - rotateleft.png - rotateright.png - fileprint.png - - diff --git a/demos/chip/main.cpp b/demos/chip/main.cpp deleted file mode 100644 index e983e4cca6..0000000000 --- a/demos/chip/main.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "mainwindow.h" - -#include - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(images); - - QApplication app(argc, argv); - app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); - - MainWindow window; - window.show(); - - return app.exec(); -} diff --git a/demos/chip/mainwindow.cpp b/demos/chip/mainwindow.cpp deleted file mode 100644 index 7476c00ab1..0000000000 --- a/demos/chip/mainwindow.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "mainwindow.h" -#include "view.h" -#include "chip.h" - -#include - -MainWindow::MainWindow(QWidget *parent) - : QWidget(parent) -{ - populateScene(); - - h1Splitter = new QSplitter; - h2Splitter = new QSplitter; - - QSplitter *vSplitter = new QSplitter; - vSplitter->setOrientation(Qt::Vertical); - vSplitter->addWidget(h1Splitter); - vSplitter->addWidget(h2Splitter); - - View *view = new View("Top left view"); - view->view()->setScene(scene); - h1Splitter->addWidget(view); - - view = new View("Top right view"); - view->view()->setScene(scene); - h1Splitter->addWidget(view); - - view = new View("Bottom left view"); - view->view()->setScene(scene); - h2Splitter->addWidget(view); - - view = new View("Bottom right view"); - view->view()->setScene(scene); - h2Splitter->addWidget(view); - - QHBoxLayout *layout = new QHBoxLayout; - layout->addWidget(vSplitter); - setLayout(layout); - - setWindowTitle(tr("Chip Demo")); -} - -void MainWindow::populateScene() -{ - scene = new QGraphicsScene; - - QImage image(":/qt4logo.png"); - - // Populate scene - int xx = 0; - int nitems = 0; - for (int i = -11000; i < 11000; i += 110) { - ++xx; - int yy = 0; - for (int j = -7000; j < 7000; j += 70) { - ++yy; - qreal x = (i + 11000) / 22000.0; - qreal y = (j + 7000) / 14000.0; - - QColor color(image.pixel(int(image.width() * x), int(image.height() * y))); - QGraphicsItem *item = new Chip(color, xx, yy); - item->setPos(QPointF(i, j)); - scene->addItem(item); - - ++nitems; - } - } -} diff --git a/demos/chip/mainwindow.h b/demos/chip/mainwindow.h deleted file mode 100644 index 650e1f1f3c..0000000000 --- a/demos/chip/mainwindow.h +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include - -QT_FORWARD_DECLARE_CLASS(QGraphicsScene) -QT_FORWARD_DECLARE_CLASS(QGraphicsView) -QT_FORWARD_DECLARE_CLASS(QLabel) -QT_FORWARD_DECLARE_CLASS(QSlider) -QT_FORWARD_DECLARE_CLASS(QSplitter) - -class MainWindow : public QWidget -{ - Q_OBJECT -public: - MainWindow(QWidget *parent = 0); - -private: - void setupMatrix(); - void populateScene(); - - QGraphicsScene *scene; - QSplitter *h1Splitter; - QSplitter *h2Splitter; -}; - -#endif diff --git a/demos/chip/qt4logo.png b/demos/chip/qt4logo.png deleted file mode 100644 index 157e86ed64..0000000000 Binary files a/demos/chip/qt4logo.png and /dev/null differ diff --git a/demos/chip/rotateleft.png b/demos/chip/rotateleft.png deleted file mode 100644 index 8cfa931986..0000000000 Binary files a/demos/chip/rotateleft.png and /dev/null differ diff --git a/demos/chip/rotateright.png b/demos/chip/rotateright.png deleted file mode 100644 index ec5e8664a1..0000000000 Binary files a/demos/chip/rotateright.png and /dev/null differ diff --git a/demos/chip/view.cpp b/demos/chip/view.cpp deleted file mode 100644 index 5634f85d98..0000000000 --- a/demos/chip/view.cpp +++ /dev/null @@ -1,276 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "view.h" - -#include -#ifndef QT_NO_OPENGL -#include -#endif - -#include - -void GraphicsView::wheelEvent(QWheelEvent *e) -{ - if (e->modifiers() & Qt::ControlModifier) { - if (e->delta() > 0) - view->zoomIn(6); - else - view->zoomOut(6); - e->accept(); - } else { - QGraphicsView::wheelEvent(e); - } -} - -View::View(const QString &name, QWidget *parent) - : QFrame(parent) -{ - setFrameStyle(Sunken | StyledPanel); - graphicsView = new GraphicsView(this); - graphicsView->setRenderHint(QPainter::Antialiasing, false); - graphicsView->setDragMode(QGraphicsView::RubberBandDrag); - graphicsView->setOptimizationFlags(QGraphicsView::DontSavePainterState); - graphicsView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate); - graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse); - - int size = style()->pixelMetric(QStyle::PM_ToolBarIconSize); - QSize iconSize(size, size); - - QToolButton *zoomInIcon = new QToolButton; - zoomInIcon->setAutoRepeat(true); - zoomInIcon->setAutoRepeatInterval(33); - zoomInIcon->setAutoRepeatDelay(0); - zoomInIcon->setIcon(QPixmap(":/zoomin.png")); - zoomInIcon->setIconSize(iconSize); - QToolButton *zoomOutIcon = new QToolButton; - zoomOutIcon->setAutoRepeat(true); - zoomOutIcon->setAutoRepeatInterval(33); - zoomOutIcon->setAutoRepeatDelay(0); - zoomOutIcon->setIcon(QPixmap(":/zoomout.png")); - zoomOutIcon->setIconSize(iconSize); - zoomSlider = new QSlider; - zoomSlider->setMinimum(0); - zoomSlider->setMaximum(500); - zoomSlider->setValue(250); - zoomSlider->setTickPosition(QSlider::TicksRight); - - // Zoom slider layout - QVBoxLayout *zoomSliderLayout = new QVBoxLayout; - zoomSliderLayout->addWidget(zoomInIcon); - zoomSliderLayout->addWidget(zoomSlider); - zoomSliderLayout->addWidget(zoomOutIcon); - - QToolButton *rotateLeftIcon = new QToolButton; - rotateLeftIcon->setIcon(QPixmap(":/rotateleft.png")); - rotateLeftIcon->setIconSize(iconSize); - QToolButton *rotateRightIcon = new QToolButton; - rotateRightIcon->setIcon(QPixmap(":/rotateright.png")); - rotateRightIcon->setIconSize(iconSize); - rotateSlider = new QSlider; - rotateSlider->setOrientation(Qt::Horizontal); - rotateSlider->setMinimum(-360); - rotateSlider->setMaximum(360); - rotateSlider->setValue(0); - rotateSlider->setTickPosition(QSlider::TicksBelow); - - // Rotate slider layout - QHBoxLayout *rotateSliderLayout = new QHBoxLayout; - rotateSliderLayout->addWidget(rotateLeftIcon); - rotateSliderLayout->addWidget(rotateSlider); - rotateSliderLayout->addWidget(rotateRightIcon); - - resetButton = new QToolButton; - resetButton->setText(tr("0")); - resetButton->setEnabled(false); - - // Label layout - QHBoxLayout *labelLayout = new QHBoxLayout; - label = new QLabel(name); - label2 = new QLabel(tr("Pointer Mode")); - selectModeButton = new QToolButton; - selectModeButton->setText(tr("Select")); - selectModeButton->setCheckable(true); - selectModeButton->setChecked(true); - dragModeButton = new QToolButton; - dragModeButton->setText(tr("Drag")); - dragModeButton->setCheckable(true); - dragModeButton->setChecked(false); - antialiasButton = new QToolButton; - antialiasButton->setText(tr("Antialiasing")); - antialiasButton->setCheckable(true); - antialiasButton->setChecked(false); - openGlButton = new QToolButton; - openGlButton->setText(tr("OpenGL")); - openGlButton->setCheckable(true); -#ifndef QT_NO_OPENGL - openGlButton->setEnabled(QGLFormat::hasOpenGL()); -#else - openGlButton->setEnabled(false); -#endif - printButton = new QToolButton; - printButton->setIcon(QIcon(QPixmap(":/fileprint.png"))); - - QButtonGroup *pointerModeGroup = new QButtonGroup; - pointerModeGroup->setExclusive(true); - pointerModeGroup->addButton(selectModeButton); - pointerModeGroup->addButton(dragModeButton); - - labelLayout->addWidget(label); - labelLayout->addStretch(); - labelLayout->addWidget(label2); - labelLayout->addWidget(selectModeButton); - labelLayout->addWidget(dragModeButton); - labelLayout->addStretch(); - labelLayout->addWidget(antialiasButton); - labelLayout->addWidget(openGlButton); - labelLayout->addWidget(printButton); - - QGridLayout *topLayout = new QGridLayout; - topLayout->addLayout(labelLayout, 0, 0); - topLayout->addWidget(graphicsView, 1, 0); - topLayout->addLayout(zoomSliderLayout, 1, 1); - topLayout->addLayout(rotateSliderLayout, 2, 0); - topLayout->addWidget(resetButton, 2, 1); - setLayout(topLayout); - - connect(resetButton, SIGNAL(clicked()), this, SLOT(resetView())); - connect(zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); - connect(rotateSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); - connect(graphicsView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setResetButtonEnabled())); - connect(graphicsView->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setResetButtonEnabled())); - connect(selectModeButton, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); - connect(dragModeButton, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); - connect(antialiasButton, SIGNAL(toggled(bool)), this, SLOT(toggleAntialiasing())); - connect(openGlButton, SIGNAL(toggled(bool)), this, SLOT(toggleOpenGL())); - connect(rotateLeftIcon, SIGNAL(clicked()), this, SLOT(rotateLeft())); - connect(rotateRightIcon, SIGNAL(clicked()), this, SLOT(rotateRight())); - connect(zoomInIcon, SIGNAL(clicked()), this, SLOT(zoomIn())); - connect(zoomOutIcon, SIGNAL(clicked()), this, SLOT(zoomOut())); - connect(printButton, SIGNAL(clicked()), this, SLOT(print())); - - setupMatrix(); -} - -QGraphicsView *View::view() const -{ - return static_cast(graphicsView); -} - -void View::resetView() -{ - zoomSlider->setValue(250); - rotateSlider->setValue(0); - setupMatrix(); - graphicsView->ensureVisible(QRectF(0, 0, 0, 0)); - - resetButton->setEnabled(false); -} - -void View::setResetButtonEnabled() -{ - resetButton->setEnabled(true); -} - -void View::setupMatrix() -{ - qreal scale = qPow(qreal(2), (zoomSlider->value() - 250) / qreal(50)); - - QMatrix matrix; - matrix.scale(scale, scale); - matrix.rotate(rotateSlider->value()); - - graphicsView->setMatrix(matrix); - setResetButtonEnabled(); -} - -void View::togglePointerMode() -{ - graphicsView->setDragMode(selectModeButton->isChecked() - ? QGraphicsView::RubberBandDrag - : QGraphicsView::ScrollHandDrag); - graphicsView->setInteractive(selectModeButton->isChecked()); -} - -void View::toggleOpenGL() -{ -#ifndef QT_NO_OPENGL - graphicsView->setViewport(openGlButton->isChecked() ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget); -#endif -} - -void View::toggleAntialiasing() -{ - graphicsView->setRenderHint(QPainter::Antialiasing, antialiasButton->isChecked()); -} - -void View::print() -{ -#ifndef QT_NO_PRINTER - QPrinter printer; - QPrintDialog dialog(&printer, this); - if (dialog.exec() == QDialog::Accepted) { - QPainter painter(&printer); - graphicsView->render(&painter); - } -#endif -} - -void View::zoomIn(int level) -{ - zoomSlider->setValue(zoomSlider->value() + level); -} - -void View::zoomOut(int level) -{ - zoomSlider->setValue(zoomSlider->value() - level); -} - -void View::rotateLeft() -{ - rotateSlider->setValue(rotateSlider->value() - 10); -} - -void View::rotateRight() -{ - rotateSlider->setValue(rotateSlider->value() + 10); -} - diff --git a/demos/chip/view.h b/demos/chip/view.h deleted file mode 100644 index 7c587d4147..0000000000 --- a/demos/chip/view.h +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef VIEW_H -#define VIEW_H - -#include -#include - -QT_FORWARD_DECLARE_CLASS(QLabel) -QT_FORWARD_DECLARE_CLASS(QSlider) -QT_FORWARD_DECLARE_CLASS(QToolButton) - -class View; - -class GraphicsView : public QGraphicsView -{ - Q_OBJECT -public: - GraphicsView(View *v) : QGraphicsView(), view(v) { } - -protected: - void wheelEvent(QWheelEvent *); - -private: - View *view; -}; - -class View : public QFrame -{ - Q_OBJECT -public: - View(const QString &name, QWidget *parent = 0); - - QGraphicsView *view() const; - -public slots: - void zoomIn(int level = 1); - void zoomOut(int level = 1); - -private slots: - void resetView(); - void setResetButtonEnabled(); - void setupMatrix(); - void togglePointerMode(); - void toggleOpenGL(); - void toggleAntialiasing(); - void print(); - void rotateLeft(); - void rotateRight(); - -private: - GraphicsView *graphicsView; - QLabel *label; - QLabel *label2; - QToolButton *selectModeButton; - QToolButton *dragModeButton; - QToolButton *openGlButton; - QToolButton *antialiasButton; - QToolButton *printButton; - QToolButton *resetButton; - QSlider *zoomSlider; - QSlider *rotateSlider; -}; - -#endif diff --git a/demos/chip/zoomin.png b/demos/chip/zoomin.png deleted file mode 100644 index 8b0daeea48..0000000000 Binary files a/demos/chip/zoomin.png and /dev/null differ diff --git a/demos/chip/zoomout.png b/demos/chip/zoomout.png deleted file mode 100644 index 1575dd24f6..0000000000 Binary files a/demos/chip/zoomout.png and /dev/null differ diff --git a/demos/composition/composition.cpp b/demos/composition/composition.cpp deleted file mode 100644 index b3f810b26c..0000000000 --- a/demos/composition/composition.cpp +++ /dev/null @@ -1,544 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "composition.h" -#include -#include -#include -#include -#include -#include -#include - -const int animationInterval = 15; // update every 16 ms = ~60FPS - -CompositionWidget::CompositionWidget(QWidget *parent) - : QWidget(parent) -{ - CompositionRenderer *view = new CompositionRenderer(this); - - QGroupBox *mainGroup = new QGroupBox(parent); - mainGroup->setTitle(tr("Composition Modes")); - - QGroupBox *modesGroup = new QGroupBox(mainGroup); - modesGroup->setTitle(tr("Mode")); - - rbClear = new QRadioButton(tr("Clear"), modesGroup); - connect(rbClear, SIGNAL(clicked()), view, SLOT(setClearMode())); - rbSource = new QRadioButton(tr("Source"), modesGroup); - connect(rbSource, SIGNAL(clicked()), view, SLOT(setSourceMode())); - rbDest = new QRadioButton(tr("Destination"), modesGroup); - connect(rbDest, SIGNAL(clicked()), view, SLOT(setDestMode())); - rbSourceOver = new QRadioButton(tr("Source Over"), modesGroup); - connect(rbSourceOver, SIGNAL(clicked()), view, SLOT(setSourceOverMode())); - rbDestOver = new QRadioButton(tr("Destination Over"), modesGroup); - connect(rbDestOver, SIGNAL(clicked()), view, SLOT(setDestOverMode())); - rbSourceIn = new QRadioButton(tr("Source In"), modesGroup); - connect(rbSourceIn, SIGNAL(clicked()), view, SLOT(setSourceInMode())); - rbDestIn = new QRadioButton(tr("Dest In"), modesGroup); - connect(rbDestIn, SIGNAL(clicked()), view, SLOT(setDestInMode())); - rbSourceOut = new QRadioButton(tr("Source Out"), modesGroup); - connect(rbSourceOut, SIGNAL(clicked()), view, SLOT(setSourceOutMode())); - rbDestOut = new QRadioButton(tr("Dest Out"), modesGroup); - connect(rbDestOut, SIGNAL(clicked()), view, SLOT(setDestOutMode())); - rbSourceAtop = new QRadioButton(tr("Source Atop"), modesGroup); - connect(rbSourceAtop, SIGNAL(clicked()), view, SLOT(setSourceAtopMode())); - rbDestAtop = new QRadioButton(tr("Dest Atop"), modesGroup); - connect(rbDestAtop, SIGNAL(clicked()), view, SLOT(setDestAtopMode())); - rbXor = new QRadioButton(tr("Xor"), modesGroup); - connect(rbXor, SIGNAL(clicked()), view, SLOT(setXorMode())); - - rbPlus = new QRadioButton(tr("Plus"), modesGroup); - connect(rbPlus, SIGNAL(clicked()), view, SLOT(setPlusMode())); - rbMultiply = new QRadioButton(tr("Multiply"), modesGroup); - connect(rbMultiply, SIGNAL(clicked()), view, SLOT(setMultiplyMode())); - rbScreen = new QRadioButton(tr("Screen"), modesGroup); - connect(rbScreen, SIGNAL(clicked()), view, SLOT(setScreenMode())); - rbOverlay = new QRadioButton(tr("Overlay"), modesGroup); - connect(rbOverlay, SIGNAL(clicked()), view, SLOT(setOverlayMode())); - rbDarken = new QRadioButton(tr("Darken"), modesGroup); - connect(rbDarken, SIGNAL(clicked()), view, SLOT(setDarkenMode())); - rbLighten = new QRadioButton(tr("Lighten"), modesGroup); - connect(rbLighten, SIGNAL(clicked()), view, SLOT(setLightenMode())); - rbColorDodge = new QRadioButton(tr("Color Dodge"), modesGroup); - connect(rbColorDodge, SIGNAL(clicked()), view, SLOT(setColorDodgeMode())); - rbColorBurn = new QRadioButton(tr("Color Burn"), modesGroup); - connect(rbColorBurn, SIGNAL(clicked()), view, SLOT(setColorBurnMode())); - rbHardLight = new QRadioButton(tr("Hard Light"), modesGroup); - connect(rbHardLight, SIGNAL(clicked()), view, SLOT(setHardLightMode())); - rbSoftLight = new QRadioButton(tr("Soft Light"), modesGroup); - connect(rbSoftLight, SIGNAL(clicked()), view, SLOT(setSoftLightMode())); - rbDifference = new QRadioButton(tr("Difference"), modesGroup); - connect(rbDifference, SIGNAL(clicked()), view, SLOT(setDifferenceMode())); - rbExclusion = new QRadioButton(tr("Exclusion"), modesGroup); - connect(rbExclusion, SIGNAL(clicked()), view, SLOT(setExclusionMode())); - - QGroupBox *circleColorGroup = new QGroupBox(mainGroup); - circleColorGroup->setTitle(tr("Circle color")); - QSlider *circleColorSlider = new QSlider(Qt::Horizontal, circleColorGroup); - circleColorSlider->setRange(0, 359); - circleColorSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - connect(circleColorSlider, SIGNAL(valueChanged(int)), view, SLOT(setCircleColor(int))); - - QGroupBox *circleAlphaGroup = new QGroupBox(mainGroup); - circleAlphaGroup->setTitle(tr("Circle alpha")); - QSlider *circleAlphaSlider = new QSlider(Qt::Horizontal, circleAlphaGroup); - circleAlphaSlider->setRange(0, 255); - circleAlphaSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - connect(circleAlphaSlider, SIGNAL(valueChanged(int)), view, SLOT(setCircleAlpha(int))); - - QPushButton *showSourceButton = new QPushButton(mainGroup); - showSourceButton->setText(tr("Show Source")); -#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) - QPushButton *enableOpenGLButton = new QPushButton(mainGroup); - enableOpenGLButton->setText(tr("Use OpenGL")); - enableOpenGLButton->setCheckable(true); - enableOpenGLButton->setChecked(view->usesOpenGL()); - - if (!QGLFormat::hasOpenGL() || !QGLPixelBuffer::hasOpenGLPbuffers()) - enableOpenGLButton->hide(); -#endif - QPushButton *whatsThisButton = new QPushButton(mainGroup); - whatsThisButton->setText(tr("What's This?")); - whatsThisButton->setCheckable(true); - - QPushButton *animateButton = new QPushButton(mainGroup); - animateButton->setText(tr("Animated")); - animateButton->setCheckable(true); - animateButton->setChecked(true); - - QHBoxLayout *viewLayout = new QHBoxLayout(this); - viewLayout->addWidget(view); - viewLayout->addWidget(mainGroup); - - QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); - mainGroupLayout->addWidget(circleColorGroup); - mainGroupLayout->addWidget(circleAlphaGroup); - mainGroupLayout->addWidget(modesGroup); - mainGroupLayout->addStretch(); - mainGroupLayout->addWidget(animateButton); - mainGroupLayout->addWidget(whatsThisButton); - mainGroupLayout->addWidget(showSourceButton); -#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) - mainGroupLayout->addWidget(enableOpenGLButton); -#endif - - QGridLayout *modesLayout = new QGridLayout(modesGroup); - modesLayout->addWidget(rbClear, 0, 0); - modesLayout->addWidget(rbSource, 1, 0); - modesLayout->addWidget(rbDest, 2, 0); - modesLayout->addWidget(rbSourceOver, 3, 0); - modesLayout->addWidget(rbDestOver, 4, 0); - modesLayout->addWidget(rbSourceIn, 5, 0); - modesLayout->addWidget(rbDestIn, 6, 0); - modesLayout->addWidget(rbSourceOut, 7, 0); - modesLayout->addWidget(rbDestOut, 8, 0); - modesLayout->addWidget(rbSourceAtop, 9, 0); - modesLayout->addWidget(rbDestAtop, 10, 0); - modesLayout->addWidget(rbXor, 11, 0); - - modesLayout->addWidget(rbPlus, 0, 1); - modesLayout->addWidget(rbMultiply, 1, 1); - modesLayout->addWidget(rbScreen, 2, 1); - modesLayout->addWidget(rbOverlay, 3, 1); - modesLayout->addWidget(rbDarken, 4, 1); - modesLayout->addWidget(rbLighten, 5, 1); - modesLayout->addWidget(rbColorDodge, 6, 1); - modesLayout->addWidget(rbColorBurn, 7, 1); - modesLayout->addWidget(rbHardLight, 8, 1); - modesLayout->addWidget(rbSoftLight, 9, 1); - modesLayout->addWidget(rbDifference, 10, 1); - modesLayout->addWidget(rbExclusion, 11, 1); - - - QVBoxLayout *circleColorLayout = new QVBoxLayout(circleColorGroup); - circleColorLayout->addWidget(circleColorSlider); - - QVBoxLayout *circleAlphaLayout = new QVBoxLayout(circleAlphaGroup); - circleAlphaLayout->addWidget(circleAlphaSlider); - - view->loadDescription(":res/composition/composition.html"); - view->loadSourceFile(":res/composition/composition.cpp"); - - connect(whatsThisButton, SIGNAL(clicked(bool)), view, SLOT(setDescriptionEnabled(bool))); - connect(view, SIGNAL(descriptionEnabledChanged(bool)), whatsThisButton, SLOT(setChecked(bool))); - connect(showSourceButton, SIGNAL(clicked()), view, SLOT(showSource())); -#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) - connect(enableOpenGLButton, SIGNAL(clicked(bool)), view, SLOT(enableOpenGL(bool))); -#endif - connect(animateButton, SIGNAL(toggled(bool)), view, SLOT(setAnimationEnabled(bool))); - - circleColorSlider->setValue(270); - circleAlphaSlider->setValue(200); - rbSourceOut->animateClick(); - - setWindowTitle(tr("Composition Modes")); -} - - -void CompositionWidget::nextMode() -{ - /* - if (!m_animation_enabled) - return; - if (rbClear->isChecked()) rbSource->animateClick(); - if (rbSource->isChecked()) rbDest->animateClick(); - if (rbDest->isChecked()) rbSourceOver->animateClick(); - if (rbSourceOver->isChecked()) rbDestOver->animateClick(); - if (rbDestOver->isChecked()) rbSourceIn->animateClick(); - if (rbSourceIn->isChecked()) rbDestIn->animateClick(); - if (rbDestIn->isChecked()) rbSourceOut->animateClick(); - if (rbSourceOut->isChecked()) rbDestOut->animateClick(); - if (rbDestOut->isChecked()) rbSourceAtop->animateClick(); - if (rbSourceAtop->isChecked()) rbDestAtop->animateClick(); - if (rbDestAtop->isChecked()) rbXor->animateClick(); - if (rbXor->isChecked()) rbClear->animateClick(); - */ -} - -CompositionRenderer::CompositionRenderer(QWidget *parent) - : ArthurFrame(parent) -{ - m_animation_enabled = true; - m_animationTimer = startTimer(animationInterval); -#ifdef Q_WS_QWS - m_image = QPixmap(":res/composition/flower.jpg"); - m_image.setAlphaChannel(QPixmap(":res/composition/flower_alpha.jpg")); -#else - m_image = QImage(":res/composition/flower.jpg"); - m_image.setAlphaChannel(QImage(":res/composition/flower_alpha.jpg")); -#endif - m_circle_alpha = 127; - m_circle_hue = 255; - m_current_object = NoObject; - m_composition_mode = QPainter::CompositionMode_SourceOut; - - m_circle_pos = QPoint(200, 100); - - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); -#ifdef QT_OPENGL_SUPPORT - m_pbuffer = 0; - m_pbuffer_size = 1024; -#endif -} - -QRectF rectangle_around(const QPointF &p, const QSizeF &size = QSize(250, 200)) -{ - QRectF rect(p, size); - rect.translate(-size.width()/2, -size.height()/2); - return rect; -} - -void CompositionRenderer::setAnimationEnabled(bool enabled) -{ - if (m_animation_enabled == enabled) - return; - m_animation_enabled = enabled; - if (enabled) { - Q_ASSERT(!m_animationTimer); - m_animationTimer = startTimer(animationInterval); - } else { - killTimer(m_animationTimer); - m_animationTimer = 0; - } -} - -void CompositionRenderer::updateCirclePos() -{ - if (m_current_object != NoObject) - return; - QDateTime dt = QDateTime::currentDateTime(); - qreal t = (dt.toTime_t() * 1000 + dt.time().msec()) / 1000.0; - - qreal x = width() / qreal(2) + (qCos(t*8/11) + qSin(-t)) * width() / qreal(4); - qreal y = height() / qreal(2) + (qSin(t*6/7) + qCos(t * qreal(1.5))) * height() / qreal(4); - - setCirclePos(QLineF(m_circle_pos, QPointF(x, y)).pointAt(0.02)); -} - -void CompositionRenderer::drawBase(QPainter &p) -{ - p.setPen(Qt::NoPen); - - QLinearGradient rect_gradient(0, 0, 0, height()); - rect_gradient.setColorAt(0, Qt::red); - rect_gradient.setColorAt(.17, Qt::yellow); - rect_gradient.setColorAt(.33, Qt::green); - rect_gradient.setColorAt(.50, Qt::cyan); - rect_gradient.setColorAt(.66, Qt::blue); - rect_gradient.setColorAt(.81, Qt::magenta); - rect_gradient.setColorAt(1, Qt::red); - p.setBrush(rect_gradient); - p.drawRect(width() / 2, 0, width() / 2, height()); - - QLinearGradient alpha_gradient(0, 0, width(), 0); - alpha_gradient.setColorAt(0, Qt::white); - alpha_gradient.setColorAt(0.2, Qt::white); - alpha_gradient.setColorAt(0.5, Qt::transparent); - alpha_gradient.setColorAt(0.8, Qt::white); - alpha_gradient.setColorAt(1, Qt::white); - - p.setCompositionMode(QPainter::CompositionMode_DestinationIn); - p.setBrush(alpha_gradient); - p.drawRect(0, 0, width(), height()); - - p.setCompositionMode(QPainter::CompositionMode_DestinationOver); - - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::SmoothPixmapTransform); -#ifdef Q_WS_QWS - p.drawPixmap(rect(), m_image); -#else - p.drawImage(rect(), m_image); -#endif -} - -void CompositionRenderer::drawSource(QPainter &p) -{ - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing); - p.setCompositionMode(m_composition_mode); - - QRectF circle_rect = rectangle_around(m_circle_pos); - QColor color = QColor::fromHsvF(m_circle_hue / 360.0, 1, 1, m_circle_alpha / 255.0); - QLinearGradient circle_gradient(circle_rect.topLeft(), circle_rect.bottomRight()); - circle_gradient.setColorAt(0, color.light()); - circle_gradient.setColorAt(0.5, color); - circle_gradient.setColorAt(1, color.dark()); - p.setBrush(circle_gradient); - - p.drawEllipse(circle_rect); -} - -void CompositionRenderer::paint(QPainter *painter) -{ -#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) - if (usesOpenGL()) { - - int new_pbuf_size = m_pbuffer_size; - if (size().width() > m_pbuffer_size || - size().height() > m_pbuffer_size) - new_pbuf_size *= 2; - - if (size().width() < m_pbuffer_size/2 && - size().height() < m_pbuffer_size/2) - new_pbuf_size /= 2; - - if (!m_pbuffer || new_pbuf_size != m_pbuffer_size) { - if (m_pbuffer) { - m_pbuffer->deleteTexture(m_base_tex); - m_pbuffer->deleteTexture(m_compositing_tex); - delete m_pbuffer; - } - - m_pbuffer = new QGLPixelBuffer(QSize(new_pbuf_size, new_pbuf_size), QGLFormat::defaultFormat(), glWidget()); - m_pbuffer->makeCurrent(); - m_base_tex = m_pbuffer->generateDynamicTexture(); - m_compositing_tex = m_pbuffer->generateDynamicTexture(); - m_pbuffer_size = new_pbuf_size; - } - - if (size() != m_previous_size) { - m_previous_size = size(); - QPainter p(m_pbuffer); - p.setCompositionMode(QPainter::CompositionMode_Source); - p.fillRect(QRect(0, 0, m_pbuffer->width(), m_pbuffer->height()), Qt::transparent); - drawBase(p); - p.end(); - m_pbuffer->updateDynamicTexture(m_base_tex); - } - - qreal x_fraction = width()/float(m_pbuffer->width()); - qreal y_fraction = height()/float(m_pbuffer->height()); - - { - QPainter p(m_pbuffer); - p.setCompositionMode(QPainter::CompositionMode_Source); - p.fillRect(QRect(0, 0, m_pbuffer->width(), m_pbuffer->height()), Qt::transparent); - - p.save(); // Needed when using the GL1 engine - p.beginNativePainting(); // Needed when using the GL2 engine - - glBindTexture(GL_TEXTURE_2D, m_base_tex); - glEnable(GL_TEXTURE_2D); - glColor4f(1.,1.,1.,1.); - - glBegin(GL_QUADS); - { - glTexCoord2f(0, 1.0); - glVertex2f(0, 0); - - glTexCoord2f(x_fraction, 1.0); - glVertex2f(width(), 0); - - glTexCoord2f(x_fraction, 1.0-y_fraction); - glVertex2f(width(), height()); - - glTexCoord2f(0, 1.0-y_fraction); - glVertex2f(0, height()); - } - glEnd(); - - glDisable(GL_TEXTURE_2D); - - p.endNativePainting(); // Needed when using the GL2 engine - p.restore(); // Needed when using the GL1 engine - - drawSource(p); - p.end(); - m_pbuffer->updateDynamicTexture(m_compositing_tex); - } - - painter->beginNativePainting(); // Needed when using the GL2 engine - glWidget()->makeCurrent(); // Needed when using the GL1 engine - glBindTexture(GL_TEXTURE_2D, m_compositing_tex); - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(1.,1.,1.,1.); - glBegin(GL_QUADS); - { - glTexCoord2f(0, 1.0); - glVertex2f(0, 0); - - glTexCoord2f(x_fraction, 1.0); - glVertex2f(width(), 0); - - glTexCoord2f(x_fraction, 1.0-y_fraction); - glVertex2f(width(), height()); - - glTexCoord2f(0, 1.0-y_fraction); - glVertex2f(0, height()); - } - glEnd(); - glDisable(GL_TEXTURE_2D); - painter->endNativePainting(); // Needed when using the GL2 engine - } else -#endif - { - // using a QImage - if (m_buffer.size() != size()) { -#ifdef Q_WS_QWS - m_base_buffer = QPixmap(size()); - m_base_buffer.fill(Qt::transparent); -#else - m_buffer = QImage(size(), QImage::Format_ARGB32_Premultiplied); - m_base_buffer = QImage(size(), QImage::Format_ARGB32_Premultiplied); - - m_base_buffer.fill(0); -#endif - - QPainter p(&m_base_buffer); - - drawBase(p); - } - -#ifdef Q_WS_QWS - m_buffer = m_base_buffer; -#else - memcpy(m_buffer.bits(), m_base_buffer.bits(), m_buffer.byteCount()); -#endif - - { - QPainter p(&m_buffer); - drawSource(p); - } - -#ifdef Q_WS_QWS - painter->drawPixmap(0, 0, m_buffer); -#else - painter->drawImage(0, 0, m_buffer); -#endif - } -} - -void CompositionRenderer::mousePressEvent(QMouseEvent *e) -{ - setDescriptionEnabled(false); - - QRectF circle = rectangle_around(m_circle_pos); - - if (circle.contains(e->pos())) { - m_current_object = Circle; - m_offset = circle.center() - e->pos(); - } else { - m_current_object = NoObject; - } - if (m_animation_enabled) { - killTimer(m_animationTimer); - m_animationTimer = 0; - } -} - -void CompositionRenderer::mouseMoveEvent(QMouseEvent *e) -{ - if (m_current_object == Circle) setCirclePos(e->pos() + m_offset); -} - -void CompositionRenderer::mouseReleaseEvent(QMouseEvent *) -{ - m_current_object = NoObject; - - if (m_animation_enabled) { - Q_ASSERT(!m_animationTimer); - m_animationTimer = startTimer(animationInterval); - } -} - -void CompositionRenderer::timerEvent(QTimerEvent *event) -{ - if (event->timerId() == m_animationTimer) - updateCirclePos(); -} - -void CompositionRenderer::setCirclePos(const QPointF &pos) -{ - const QRect oldRect = rectangle_around(m_circle_pos).toAlignedRect(); - m_circle_pos = pos; - const QRect newRect = rectangle_around(m_circle_pos).toAlignedRect(); -#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) - if (usesOpenGL()) - update(); - else -#endif - update(oldRect | newRect); -} - diff --git a/demos/composition/composition.h b/demos/composition/composition.h deleted file mode 100644 index 86e8f5c0df..0000000000 --- a/demos/composition/composition.h +++ /dev/null @@ -1,193 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef COMPOSITION_H -#define COMPOSITION_H - -#include "arthurwidgets.h" - -#include -#include - -QT_FORWARD_DECLARE_CLASS(QPushButton) -QT_FORWARD_DECLARE_CLASS(QRadioButton) - -#ifdef QT_OPENGL_SUPPORT -#include -#endif - -class CompositionWidget : public QWidget -{ - Q_OBJECT - -public: - CompositionWidget(QWidget *parent); - -public slots: -void nextMode(); - -private: - bool m_cycle_enabled; - - QRadioButton *rbClear; - QRadioButton *rbSource; - QRadioButton *rbDest; - QRadioButton *rbSourceOver; - QRadioButton *rbDestOver; - QRadioButton *rbSourceIn; - QRadioButton *rbDestIn; - QRadioButton *rbSourceOut; - QRadioButton *rbDestOut; - QRadioButton *rbSourceAtop; - QRadioButton *rbDestAtop; - QRadioButton *rbXor; - - QRadioButton *rbPlus; - QRadioButton *rbMultiply; - QRadioButton *rbScreen; - QRadioButton *rbOverlay; - QRadioButton *rbDarken; - QRadioButton *rbLighten; - QRadioButton *rbColorDodge; - QRadioButton *rbColorBurn; - QRadioButton *rbHardLight; - QRadioButton *rbSoftLight; - QRadioButton *rbDifference; - QRadioButton *rbExclusion; -}; - -class CompositionRenderer : public ArthurFrame -{ - Q_OBJECT - - enum ObjectType { NoObject, Circle, Rectangle, Image }; - - Q_PROPERTY(int circleColor READ circleColor WRITE setCircleColor) - Q_PROPERTY(int circleAlpha READ circleAlpha WRITE setCircleAlpha) - Q_PROPERTY(bool animation READ animationEnabled WRITE setAnimationEnabled) - -public: - CompositionRenderer(QWidget *parent); - - void paint(QPainter *); - - void setCirclePos(const QPointF &pos); - - QSize sizeHint() const { return QSize(500, 400); } - - bool animationEnabled() const { return m_animation_enabled; } - int circleColor() const { return m_circle_hue; } - int circleAlpha() const { return m_circle_alpha; } - -protected: - void mousePressEvent(QMouseEvent *); - void mouseMoveEvent(QMouseEvent *); - void mouseReleaseEvent(QMouseEvent *); - void timerEvent(QTimerEvent *); - -public slots: - void setClearMode() { m_composition_mode = QPainter::CompositionMode_Clear; update(); } - void setSourceMode() { m_composition_mode = QPainter::CompositionMode_Source; update(); } - void setDestMode() { m_composition_mode = QPainter::CompositionMode_Destination; update(); } - void setSourceOverMode() { m_composition_mode = QPainter::CompositionMode_SourceOver; update(); } - void setDestOverMode() { m_composition_mode = QPainter::CompositionMode_DestinationOver; update(); } - void setSourceInMode() { m_composition_mode = QPainter::CompositionMode_SourceIn; update(); } - void setDestInMode() { m_composition_mode = QPainter::CompositionMode_DestinationIn; update(); } - void setSourceOutMode() { m_composition_mode = QPainter::CompositionMode_SourceOut; update(); } - void setDestOutMode() { m_composition_mode = QPainter::CompositionMode_DestinationOut; update(); } - void setSourceAtopMode() { m_composition_mode = QPainter::CompositionMode_SourceAtop; update(); } - void setDestAtopMode() { m_composition_mode = QPainter::CompositionMode_DestinationAtop; update(); } - void setXorMode() { m_composition_mode = QPainter::CompositionMode_Xor; update(); } - - void setPlusMode() { m_composition_mode = QPainter::CompositionMode_Plus; update(); } - void setMultiplyMode() { m_composition_mode = QPainter::CompositionMode_Multiply; update(); } - void setScreenMode() { m_composition_mode = QPainter::CompositionMode_Screen; update(); } - void setOverlayMode() { m_composition_mode = QPainter::CompositionMode_Overlay; update(); } - void setDarkenMode() { m_composition_mode = QPainter::CompositionMode_Darken; update(); } - void setLightenMode() { m_composition_mode = QPainter::CompositionMode_Lighten; update(); } - void setColorDodgeMode() { m_composition_mode = QPainter::CompositionMode_ColorDodge; update(); } - void setColorBurnMode() { m_composition_mode = QPainter::CompositionMode_ColorBurn; update(); } - void setHardLightMode() { m_composition_mode = QPainter::CompositionMode_HardLight; update(); } - void setSoftLightMode() { m_composition_mode = QPainter::CompositionMode_SoftLight; update(); } - void setDifferenceMode() { m_composition_mode = QPainter::CompositionMode_Difference; update(); } - void setExclusionMode() { m_composition_mode = QPainter::CompositionMode_Exclusion; update(); } - - void setCircleAlpha(int alpha) { m_circle_alpha = alpha; update(); } - void setCircleColor(int hue) { m_circle_hue = hue; update(); } - void setAnimationEnabled(bool enabled); - -private: - void updateCirclePos(); - void drawBase(QPainter &p); - void drawSource(QPainter &p); - - QPainter::CompositionMode m_composition_mode; - -#ifdef Q_WS_QWS - QPixmap m_image; - QPixmap m_buffer; - QPixmap m_base_buffer; -#else - QImage m_image; - QImage m_buffer; - QImage m_base_buffer; -#endif - - int m_circle_alpha; - int m_circle_hue; - - QPointF m_circle_pos; - QPointF m_offset; - - ObjectType m_current_object; - bool m_animation_enabled; - int m_animationTimer; - -#ifdef QT_OPENGL_SUPPORT - QGLPixelBuffer *m_pbuffer; - GLuint m_base_tex; - GLuint m_compositing_tex; - int m_pbuffer_size; // width==height==size of pbuffer - QSize m_previous_size; -#endif -}; - -#endif // COMPOSITION_H diff --git a/demos/composition/composition.html b/demos/composition/composition.html deleted file mode 100644 index 1848ad8bd1..0000000000 --- a/demos/composition/composition.html +++ /dev/null @@ -1,23 +0,0 @@ - - -

Demo for composition modes

- -

- This demo shows some of the more advanced composition modes supported by Qt. -

- -

- The two most common forms of composition are Source and SourceOver. - Source is used to draw opaque objects onto a paint device. In this mode, - each pixel in the source replaces the corresponding pixel in the destination. - In SourceOver composition mode, the source object is transparent and is - drawn on top of the destination. -

- -

- In addition to these standard modes, Qt defines the complete set of composition - modes as defined by Thomas Porter and Tom Duff. See the QPainter documentation - for details. -

- - diff --git a/demos/composition/composition.pro b/demos/composition/composition.pro deleted file mode 100644 index 59b91126b9..0000000000 --- a/demos/composition/composition.pro +++ /dev/null @@ -1,29 +0,0 @@ -SOURCES += main.cpp composition.cpp -HEADERS += composition.h - -SHARED_FOLDER = ../shared - -include($$SHARED_FOLDER/shared.pri) - -RESOURCES += composition.qrc -contains(QT_CONFIG, opengl) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/composition -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.png *.jpg *.pro *.html -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/composition -INSTALLS += target sources - -symbian: CONFIG += qt_demo - -win32-msvc* { - QMAKE_CXXFLAGS += /Zm500 - QMAKE_CFLAGS += /Zm500 -} - -wince* { - DEPLOYMENT_PLUGIN += qjpeg -} diff --git a/demos/composition/composition.qrc b/demos/composition/composition.qrc deleted file mode 100644 index d02c397ee8..0000000000 --- a/demos/composition/composition.qrc +++ /dev/null @@ -1,8 +0,0 @@ - - - composition.cpp - composition.html - flower.jpg - flower_alpha.jpg - - diff --git a/demos/composition/flower.jpg b/demos/composition/flower.jpg deleted file mode 100644 index f8e022c98c..0000000000 Binary files a/demos/composition/flower.jpg and /dev/null differ diff --git a/demos/composition/flower_alpha.jpg b/demos/composition/flower_alpha.jpg deleted file mode 100644 index 6a3c2a02ef..0000000000 Binary files a/demos/composition/flower_alpha.jpg and /dev/null differ diff --git a/demos/composition/main.cpp b/demos/composition/main.cpp deleted file mode 100644 index d6bc170a97..0000000000 --- a/demos/composition/main.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "composition.h" - -#include -#ifdef QT_OPENGL_SUPPORT -#include -#endif - -int main(int argc, char **argv) -{ - // Q_INIT_RESOURCE(deform); - -#ifdef QT_OPENGL_SUPPORT - QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); -#endif - QApplication app(argc, argv); - - CompositionWidget compWidget(0); - QStyle *arthurStyle = new ArthurStyle(); - compWidget.setStyle(arthurStyle); - - QList widgets = compWidget.findChildren(); - foreach (QWidget *w, widgets) - w->setStyle(arthurStyle); - compWidget.show(); - - return app.exec(); -} diff --git a/demos/deform/deform.pro b/demos/deform/deform.pro deleted file mode 100644 index 3393b8e83c..0000000000 --- a/demos/deform/deform.pro +++ /dev/null @@ -1,24 +0,0 @@ -SOURCES += main.cpp pathdeform.cpp -HEADERS += pathdeform.h - -SHARED_FOLDER = ../shared - -include($$SHARED_FOLDER/shared.pri) - -RESOURCES += deform.qrc - -contains(QT_CONFIG, opengl) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/deform -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/deform -INSTALLS += target sources - -symbian { - TARGET.UID3 = 0xA000A63D - CONFIG += qt_demo -} diff --git a/demos/deform/deform.qrc b/demos/deform/deform.qrc deleted file mode 100644 index 2e59ebcfc5..0000000000 --- a/demos/deform/deform.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - pathdeform.cpp - pathdeform.html - - diff --git a/demos/deform/main.cpp b/demos/deform/main.cpp deleted file mode 100644 index c49117a2f2..0000000000 --- a/demos/deform/main.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "pathdeform.h" - -#include -#include - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(deform); - - QApplication app(argc, argv); - - bool smallScreen = QApplication::arguments().contains("-small-screen"); - - PathDeformWidget deformWidget(0, smallScreen); - - QStyle *arthurStyle = new ArthurStyle(); - deformWidget.setStyle(arthurStyle); - QList widgets = deformWidget.findChildren(); - foreach (QWidget *w, widgets) - w->setStyle(arthurStyle); - - if (smallScreen) - deformWidget.showFullScreen(); - else - deformWidget.show(); - -#ifdef QT_KEYPAD_NAVIGATION - QApplication::setNavigationMode(Qt::NavigationModeCursorAuto); -#endif - return app.exec(); -} diff --git a/demos/deform/pathdeform.cpp b/demos/deform/pathdeform.cpp deleted file mode 100644 index f80ef2b8be..0000000000 --- a/demos/deform/pathdeform.cpp +++ /dev/null @@ -1,647 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "pathdeform.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -PathDeformControls::PathDeformControls(QWidget *parent, PathDeformRenderer* renderer, bool smallScreen) - : QWidget(parent) -{ - m_renderer = renderer; - - if (smallScreen) - layoutForSmallScreen(); - else - layoutForDesktop(); -} - - -void PathDeformControls::layoutForDesktop() -{ - QGroupBox* mainGroup = new QGroupBox(this); - mainGroup->setTitle(tr("Controls")); - - QGroupBox *radiusGroup = new QGroupBox(mainGroup); - radiusGroup->setTitle(tr("Lens Radius")); - QSlider *radiusSlider = new QSlider(Qt::Horizontal, radiusGroup); - radiusSlider->setRange(15, 150); - radiusSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - - QGroupBox *deformGroup = new QGroupBox(mainGroup); - deformGroup->setTitle(tr("Deformation")); - QSlider *deformSlider = new QSlider(Qt::Horizontal, deformGroup); - deformSlider->setRange(-100, 100); - deformSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - - QGroupBox *fontSizeGroup = new QGroupBox(mainGroup); - fontSizeGroup->setTitle(tr("Font Size")); - QSlider *fontSizeSlider = new QSlider(Qt::Horizontal, fontSizeGroup); - fontSizeSlider->setRange(16, 200); - fontSizeSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - - QGroupBox *textGroup = new QGroupBox(mainGroup); - textGroup->setTitle(tr("Text")); - QLineEdit *textInput = new QLineEdit(textGroup); - - QPushButton *animateButton = new QPushButton(mainGroup); - animateButton->setText(tr("Animated")); - animateButton->setCheckable(true); - - QPushButton *showSourceButton = new QPushButton(mainGroup); - showSourceButton->setText(tr("Show Source")); - -#ifdef QT_OPENGL_SUPPORT - QPushButton *enableOpenGLButton = new QPushButton(mainGroup); - enableOpenGLButton->setText(tr("Use OpenGL")); - enableOpenGLButton->setCheckable(true); - enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); -#endif - - QPushButton *whatsThisButton = new QPushButton(mainGroup); - whatsThisButton->setText(tr("What's This?")); - whatsThisButton->setCheckable(true); - - - mainGroup->setFixedWidth(180); - - QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); - mainGroupLayout->addWidget(radiusGroup); - mainGroupLayout->addWidget(deformGroup); - mainGroupLayout->addWidget(fontSizeGroup); - mainGroupLayout->addWidget(textGroup); - mainGroupLayout->addWidget(animateButton); - mainGroupLayout->addStretch(1); -#ifdef QT_OPENGL_SUPPORT - mainGroupLayout->addWidget(enableOpenGLButton); -#endif - mainGroupLayout->addWidget(showSourceButton); - mainGroupLayout->addWidget(whatsThisButton); - - QVBoxLayout *radiusGroupLayout = new QVBoxLayout(radiusGroup); - radiusGroupLayout->addWidget(radiusSlider); - - QVBoxLayout *deformGroupLayout = new QVBoxLayout(deformGroup); - deformGroupLayout->addWidget(deformSlider); - - QVBoxLayout *fontSizeGroupLayout = new QVBoxLayout(fontSizeGroup); - fontSizeGroupLayout->addWidget(fontSizeSlider); - - QVBoxLayout *textGroupLayout = new QVBoxLayout(textGroup); - textGroupLayout->addWidget(textInput); - - QVBoxLayout * mainLayout = new QVBoxLayout(this); - mainLayout->addWidget(mainGroup); - mainLayout->setMargin(0); - - connect(radiusSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setRadius(int))); - connect(deformSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setIntensity(int))); - connect(fontSizeSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setFontSize(int))); - connect(animateButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setAnimated(bool))); -#ifdef QT_OPENGL_SUPPORT - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); -#endif - - connect(textInput, SIGNAL(textChanged(QString)), m_renderer, SLOT(setText(QString))); - connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), - whatsThisButton, SLOT(setChecked(bool))); - connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); - connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); - - animateButton->animateClick(); - deformSlider->setValue(80); - fontSizeSlider->setValue(120); - radiusSlider->setValue(100); - textInput->setText(tr("Qt")); -} - -void PathDeformControls::layoutForSmallScreen() -{ - QGroupBox* mainGroup = new QGroupBox(this); - mainGroup->setTitle(tr("Controls")); - - QLabel *radiusLabel = new QLabel(mainGroup); - radiusLabel->setText(tr("Lens Radius:")); - QSlider *radiusSlider = new QSlider(Qt::Horizontal, mainGroup); - radiusSlider->setRange(15, 150); - radiusSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - - QLabel *deformLabel = new QLabel(mainGroup); - deformLabel->setText(tr("Deformation:")); - QSlider *deformSlider = new QSlider(Qt::Horizontal, mainGroup); - deformSlider->setRange(-100, 100); - deformSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - - QLabel *fontSizeLabel = new QLabel(mainGroup); - fontSizeLabel->setText(tr("Font Size:")); - QSlider *fontSizeSlider = new QSlider(Qt::Horizontal, mainGroup); - fontSizeSlider->setRange(16, 200); - fontSizeSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - - QPushButton *animateButton = new QPushButton(tr("Animated"), mainGroup); - animateButton->setCheckable(true); - -#ifdef QT_OPENGL_SUPPORT - QPushButton *enableOpenGLButton = new QPushButton(mainGroup); - enableOpenGLButton->setText(tr("Use OpenGL")); - enableOpenGLButton->setCheckable(mainGroup); - enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); -#endif - - QPushButton *quitButton = new QPushButton(tr("Quit"), mainGroup); - QPushButton *okButton = new QPushButton(tr("OK"), mainGroup); - - - QGridLayout *mainGroupLayout = new QGridLayout(mainGroup); - mainGroupLayout->setMargin(0); - mainGroupLayout->addWidget(radiusLabel, 0, 0, Qt::AlignRight); - mainGroupLayout->addWidget(radiusSlider, 0, 1); - mainGroupLayout->addWidget(deformLabel, 1, 0, Qt::AlignRight); - mainGroupLayout->addWidget(deformSlider, 1, 1); - mainGroupLayout->addWidget(fontSizeLabel, 2, 0, Qt::AlignRight); - mainGroupLayout->addWidget(fontSizeSlider, 2, 1); - mainGroupLayout->addWidget(animateButton, 3,0, 1,2); -#ifdef QT_OPENGL_SUPPORT - mainGroupLayout->addWidget(enableOpenGLButton, 4,0, 1,2); -#endif - - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->addWidget(mainGroup); - mainLayout->addStretch(1); - mainLayout->addWidget(okButton); - mainLayout->addWidget(quitButton); - - connect(quitButton, SIGNAL(clicked()), this, SLOT(emitQuitSignal())); - connect(okButton, SIGNAL(clicked()), this, SLOT(emitOkSignal())); - connect(radiusSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setRadius(int))); - connect(deformSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setIntensity(int))); - connect(fontSizeSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setFontSize(int))); - connect(animateButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setAnimated(bool))); -#ifdef QT_OPENGL_SUPPORT - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); -#endif - - - animateButton->animateClick(); - deformSlider->setValue(80); - fontSizeSlider->setValue(120); - - QRect screen_size = QApplication::desktop()->screenGeometry(); - radiusSlider->setValue(qMin(screen_size.width(), screen_size.height())/5); - - m_renderer->setText(tr("Qt")); -} - - -void PathDeformControls::emitQuitSignal() -{ emit quitPressed(); } - -void PathDeformControls::emitOkSignal() -{ emit okPressed(); } - - -PathDeformWidget::PathDeformWidget(QWidget *parent, bool smallScreen) - : QWidget(parent) -{ - setWindowTitle(tr("Vector Deformation")); - - m_renderer = new PathDeformRenderer(this, smallScreen); - m_renderer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - - // Layouts - QHBoxLayout *mainLayout = new QHBoxLayout(this); - mainLayout->addWidget(m_renderer); - - m_controls = new PathDeformControls(0, m_renderer, smallScreen); - m_controls->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum); - - if (!smallScreen) - mainLayout->addWidget(m_controls); - - m_renderer->loadSourceFile(":res/deform/pathdeform.cpp"); - m_renderer->loadDescription(":res/deform/pathdeform.html"); - m_renderer->setDescriptionEnabled(false); - - connect(m_renderer, SIGNAL(clicked()), this, SLOT(showControls())); - connect(m_controls, SIGNAL(okPressed()), this, SLOT(hideControls())); - connect(m_controls, SIGNAL(quitPressed()), QApplication::instance(), SLOT(quit())); -} - - -void PathDeformWidget::showControls() -{ - m_controls->showFullScreen(); -} - -void PathDeformWidget::hideControls() -{ - m_controls->hide(); -} - -void PathDeformWidget::setStyle( QStyle * style ) -{ - QWidget::setStyle(style); - if (m_controls != 0) - { - m_controls->setStyle(style); - - QList widgets = m_controls->findChildren(); - foreach (QWidget *w, widgets) - w->setStyle(style); - } -} - -static inline QRect circle_bounds(const QPointF ¢er, qreal radius, qreal compensation) -{ - return QRect(qRound(center.x() - radius - compensation), - qRound(center.y() - radius - compensation), - qRound((radius + compensation) * 2), - qRound((radius + compensation) * 2)); - -} - -const int LENS_EXTENT = 10; - -PathDeformRenderer::PathDeformRenderer(QWidget *widget, bool smallScreen) - : ArthurFrame(widget) -{ - m_radius = 100; - m_pos = QPointF(m_radius, m_radius); - m_direction = QPointF(1, 1); - m_fontSize = 24; - m_animated = true; - m_repaintTimer.start(25, this); - m_repaintTracker.start(); - m_intensity = 100; - m_smallScreen = smallScreen; - -// m_fpsTimer.start(1000, this); -// m_fpsCounter = 0; - - generateLensPixmap(); -} - -void PathDeformRenderer::setText(const QString &text) -{ - m_text = text; - - QFont f("times new roman,utopia"); - f.setStyleStrategy(QFont::ForceOutline); - f.setPointSize(m_fontSize); - f.setStyleHint(QFont::Times); - - QFontMetrics fm(f); - - m_paths.clear(); - m_pathBounds = QRect(); - - QPointF advance(0, 0); - - bool do_quick = true; - for (int i=0; i= 0x4ff && text.at(i).unicode() <= 0x1e00) { - do_quick = false; - break; - } - } - - if (do_quick) { - for (int i=0; itimerId() == m_repaintTimer.timerId()) { - - if (QLineF(QPointF(0,0), m_direction).length() > 1) - m_direction *= 0.995; - qreal time = m_repaintTracker.restart(); - - QRect rectBefore = circle_bounds(m_pos, m_radius, m_fontSize); - - qreal dx = m_direction.x(); - qreal dy = m_direction.y(); - if (time > 0) { - dx = dx * time * .1; - dy = dy * time * .1; - } - - m_pos += QPointF(dx, dy); - - - - if (m_pos.x() - m_radius < 0) { - m_direction.setX(-m_direction.x()); - m_pos.setX(m_radius); - } else if (m_pos.x() + m_radius > width()) { - m_direction.setX(-m_direction.x()); - m_pos.setX(width() - m_radius); - } - - if (m_pos.y() - m_radius < 0) { - m_direction.setY(-m_direction.y()); - m_pos.setY(m_radius); - } else if (m_pos.y() + m_radius > height()) { - m_direction.setY(-m_direction.y()); - m_pos.setY(height() - m_radius); - } - -#ifdef QT_OPENGL_SUPPORT - if (usesOpenGL()) { - update(); - } else -#endif - { - QRect rectAfter = circle_bounds(m_pos, m_radius, m_fontSize); - update(rectAfter | rectBefore); - QApplication::syncX(); - } - } -// else if (e->timerId() == m_fpsTimer.timerId()) { -// printf("fps: %d\n", m_fpsCounter); -// emit frameRate(m_fpsCounter); -// m_fpsCounter = 0; - -// } -} - -void PathDeformRenderer::mousePressEvent(QMouseEvent *e) -{ - setDescriptionEnabled(false); - - m_repaintTimer.stop(); - m_offset = QPointF(); - if (QLineF(m_pos, e->pos()).length() <= m_radius) - m_offset = m_pos - e->pos(); - - m_mousePress = e->pos(); - - // If we're not running in small screen mode, always assume we're dragging - m_mouseDrag = !m_smallScreen; - - mouseMoveEvent(e); -} - -void PathDeformRenderer::mouseReleaseEvent(QMouseEvent *e) -{ - if (e->buttons() == Qt::NoButton && m_animated) { - m_repaintTimer.start(10, this); - m_repaintTracker.start(); - } - - if (!m_mouseDrag && m_smallScreen) - emit clicked(); -} - -void PathDeformRenderer::mouseMoveEvent(QMouseEvent *e) -{ - if (!m_mouseDrag && (QLineF(m_mousePress, e->pos()).length() > 25.0) ) - m_mouseDrag = true; - - if (m_mouseDrag) { - QRect rectBefore = circle_bounds(m_pos, m_radius, m_fontSize); - if (e->type() == QEvent::MouseMove) { - QLineF line(m_pos, e->pos() + m_offset); - line.setLength(line.length() * .1); - QPointF dir(line.dx(), line.dy()); - m_direction = (m_direction + dir) / 2; - } - m_pos = e->pos() + m_offset; -#ifdef QT_OPENGL_SUPPORT - if (usesOpenGL()) { - update(); - } else -#endif - { - QRect rectAfter = circle_bounds(m_pos, m_radius, m_fontSize); - update(rectBefore | rectAfter); - } - } -} - -QPainterPath PathDeformRenderer::lensDeform(const QPainterPath &source, const QPointF &offset) -{ - QPainterPath path; - path.addPath(source); - - qreal flip = m_intensity / qreal(100); - - for (int i=0; i 0) { - path.setElementPositionAt(i, - x + flip * dx * len / m_radius, - y + flip * dy * len / m_radius); - } else { - path.setElementPositionAt(i, x, y); - } - - } - - return path; -} - - -void PathDeformRenderer::paint(QPainter *painter) -{ - int pad_x = 5; - int pad_y = 5; - - int skip_x = qRound(m_pathBounds.width() + pad_x + m_fontSize/2); - int skip_y = qRound(m_pathBounds.height() + pad_y); - - painter->setPen(Qt::NoPen); - painter->setBrush(Qt::black); - - QRectF clip(painter->clipPath().boundingRect()); - - int overlap = pad_x / 2; - - for (int start_y=0; start_y < height(); start_y += skip_y) { - - if (start_y > clip.bottom()) - break; - - int start_x = -overlap; - for (; start_x < width(); start_x += skip_x) { - - if (start_y + skip_y >= clip.top() && - start_x + skip_x >= clip.left() && - start_x <= clip.right()) { - for (int i=0; idrawPath(path); - } - } - } - overlap = skip_x - (start_x - width()); - - } - - if (preferImage()) { - painter->drawImage(m_pos - QPointF(m_radius + LENS_EXTENT, m_radius + LENS_EXTENT), - m_lens_image); - } else { - painter->drawPixmap(m_pos - QPointF(m_radius + LENS_EXTENT, m_radius + LENS_EXTENT), - m_lens_pixmap); - } -} - - - -void PathDeformRenderer::setRadius(int radius) -{ - qreal max = qMax(m_radius, (qreal)radius); - m_radius = radius; - generateLensPixmap(); - if (!m_animated || m_radius < max) { -#ifdef QT_OPENGL_SUPPORT - if (usesOpenGL()) { - update(); - } else -#endif - { - update(circle_bounds(m_pos, max, m_fontSize)); - } - } -} - -void PathDeformRenderer::setIntensity(int intensity) -{ - m_intensity = intensity; - if (!m_animated) { -#ifdef QT_OPENGL_SUPPORT - if (usesOpenGL()) { - update(); - } else -#endif - { - update(circle_bounds(m_pos, m_radius, m_fontSize)); - } - } -} diff --git a/demos/deform/pathdeform.h b/demos/deform/pathdeform.h deleted file mode 100644 index 73a1955082..0000000000 --- a/demos/deform/pathdeform.h +++ /dev/null @@ -1,153 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef PATHDEFORM_H -#define PATHDEFORM_H - -#include "arthurwidgets.h" - -#include -#include -#include - -class PathDeformRenderer : public ArthurFrame -{ - Q_OBJECT - Q_PROPERTY(bool animated READ animated WRITE setAnimated) - Q_PROPERTY(int radius READ radius WRITE setRadius) - Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize) - Q_PROPERTY(int intensity READ intensity WRITE setIntensity) - Q_PROPERTY(QString text READ text WRITE setText) - -public: - PathDeformRenderer(QWidget *widget, bool smallScreen = false); - - void paint(QPainter *painter); - - void mousePressEvent(QMouseEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void mouseMoveEvent(QMouseEvent *e); - void timerEvent(QTimerEvent *e); - - QSize sizeHint() const { return QSize(600, 500); } - - bool animated() const { return m_animated; } - int radius() const { return int(m_radius); } - int fontSize() const { return m_fontSize; } - int intensity() const { return int(m_intensity); } - QString text() const { return m_text; } - -public slots: - void setRadius(int radius); - void setFontSize(int fontSize) { m_fontSize = fontSize; setText(m_text); } - void setText(const QString &text); - void setIntensity(int intensity); - - void setAnimated(bool animated); - -signals: - void clicked(); -// void frameRate(double fps); - -private: - void generateLensPixmap(); - QPainterPath lensDeform(const QPainterPath &source, const QPointF &offset); - - QBasicTimer m_repaintTimer; -// QBasicTimer m_fpsTimer; -// int m_fpsCounter; - QTime m_repaintTracker; - - QVector m_paths; - QVector m_advances; - QRectF m_pathBounds; - QString m_text; - - QPixmap m_lens_pixmap; - QImage m_lens_image; - - int m_fontSize; - bool m_animated; - - qreal m_intensity; - qreal m_radius; - QPointF m_pos; - QPointF m_offset; - QPointF m_direction; - QPointF m_mousePress; - bool m_mouseDrag; - bool m_smallScreen; -}; - -class PathDeformControls : public QWidget -{ - Q_OBJECT -public: - PathDeformControls(QWidget *parent, PathDeformRenderer* renderer, bool smallScreen); -signals: - void okPressed(); - void quitPressed(); -private: - PathDeformRenderer* m_renderer; - void layoutForDesktop(); - void layoutForSmallScreen(); -private slots: - void emitQuitSignal(); - void emitOkSignal(); -}; - -class PathDeformWidget : public QWidget -{ - Q_OBJECT -public: - PathDeformWidget(QWidget *parent, bool smallScreen); - void setStyle ( QStyle * style ); - -private: - PathDeformRenderer *m_renderer; - PathDeformControls *m_controls; - -private slots: - void showControls(); - void hideControls(); -}; - -#endif // PATHDEFORM_H diff --git a/demos/deform/pathdeform.html b/demos/deform/pathdeform.html deleted file mode 100644 index b3f63a8e0a..0000000000 --- a/demos/deform/pathdeform.html +++ /dev/null @@ -1,24 +0,0 @@ - -
-

Vector deformation

-
- -

This demo shows how to use advanced vector techniques to draw text -using a QPainterPath.

- -

We define a vector deformation field in the shape of a lens and apply -this to all points in a path. This means that what is rendered on -screen is not pixel manipulation, but modified vector representations of -the glyphs themselves. This is visible from the high quality of the -antialiased edges for the deformed glyphs.

- -

To get a fairly complex path we allow the user to type in text and -convert the text to paths. This is done using the -QPainterPath::addText() function.

- -

The lens is drawn using a single call to drawEllipse(), using -a QRadialGradient to fill it with a specialized color table, -giving the effect of the Sun's reflection and a drop shadow. The lens -is cached as a pixmap for better performance.

- - diff --git a/demos/demos.pro b/demos/demos.pro deleted file mode 100644 index 81968fd61d..0000000000 --- a/demos/demos.pro +++ /dev/null @@ -1,98 +0,0 @@ -TEMPLATE = subdirs - -!contains(QT_CONFIG, no-gui) { -SUBDIRS = \ - demos_shared \ - demos_deform \ - demos_gradients \ - demos_pathstroke \ - demos_affine \ - demos_composition \ - demos_books \ - demos_interview \ - demos_mainwindow \ - demos_spreadsheet \ - demos_textedit \ - demos_chip \ - demos_embeddeddialogs \ - demos_undo \ - demos_sub-attaq - -symbian: SUBDIRS = \ - demos_shared \ - demos_deform \ - demos_pathstroke - - -wince*: SUBDIRS = \ - demos_shared \ - demos_deform \ - demos_gradients \ - demos_pathstroke \ - demos_affine \ - demos_composition \ - demos_books \ - demos_interview \ - demos_mainwindow \ - demos_spreadsheet \ - demos_textedit \ - # demos_chip \ - demos_embeddeddialogs \ - demos_undo \ - demos_sub-attaq - -contains(QT_CONFIG, opengl):!contains(QT_CONFIG, opengles1):!contains(QT_CONFIG, opengles2):{ -SUBDIRS += demos_boxes -} - -mac* && !qpa: SUBDIRS += demos_macmainwindow -wince*|symbian|embedded|x11: SUBDIRS += demos_embedded - -!cross_compile:{ -contains(QT_BUILD_PARTS, tools):{ -SUBDIRS += demos_sqlbrowser -} -} - -# install -sources.files = README *.pro -sources.path = $$[QT_INSTALL_DEMOS] -INSTALLS += sources - -symbian: CONFIG += qt_demo - -demos_chip.subdir = chip -demos_embeddeddialogs.subdir = embeddeddialogs -demos_embedded.subdir = embedded -# Because of fluidlauncher -demos_embedded.depends = demos_deform demos_pathstroke -demos_shared.subdir = shared -demos_deform.subdir = deform -demos_gradients.subdir = gradients -demos_pathstroke.subdir = pathstroke -demos_affine.subdir = affine -demos_composition.subdir = composition -demos_books.subdir = books -demos_interview.subdir = interview -demos_macmainwindow.subdir = macmainwindow -demos_mainwindow.subdir = mainwindow -demos_spreadsheet.subdir = spreadsheet -demos_textedit.subdir = textedit -demos_arthurplugin.subdir = arthurplugin -demos_sqlbrowser.subdir = sqlbrowser -demos_undo.subdir = undo -demos_qtdemo.subdir = qtdemo - -demos_boxes.subdir = boxes -demos_sub-attaq.subdir = sub-attaq - -#CONFIG += ordered -!ordered { - demos_affine.depends = demos_shared - demos_deform.depends = demos_shared - demos_gradients.depends = demos_shared - demos_composition.depends = demos_shared - demos_arthurplugin.depends = demos_shared - demos_pathstroke.depends = demos_shared -} -} diff --git a/demos/embedded/digiflip/digiflip.cpp b/demos/embedded/digiflip/digiflip.cpp deleted file mode 100644 index 895524355e..0000000000 --- a/demos/embedded/digiflip/digiflip.cpp +++ /dev/null @@ -1,425 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include - -class Digits: public QWidget -{ - Q_OBJECT - -public: - - enum { - Slide, - Flip, - Rotate - }; - - Digits(QWidget *parent) - : QWidget(parent) - , m_number(0) - , m_transition(Slide) - { - setAttribute(Qt::WA_OpaquePaintEvent, true); - setAttribute(Qt::WA_NoSystemBackground, true); - connect(&m_animator, SIGNAL(frameChanged(int)), SLOT(update())); - m_animator.setFrameRange(0, 100); - m_animator.setDuration(600); - m_animator.setCurveShape(QTimeLine::EaseInOutCurve); - } - - void setTransition(int tr) { - m_transition = tr; - } - - int transition() const { - return m_transition; - } - - void setNumber(int n) { - if (m_number != n) { - m_number = qBound(0, n, 99); - preparePixmap(); - update(); - } - } - - void flipTo(int n) { - if (m_number != n) { - m_number = qBound(0, n, 99); - m_lastPixmap = m_pixmap; - preparePixmap(); - m_animator.stop(); - m_animator.start(); - } - } - -protected: - - void drawFrame(QPainter *p, const QRect &rect) { - p->setPen(Qt::NoPen); - QLinearGradient gradient(rect.topLeft(), rect.bottomLeft()); - gradient.setColorAt(0.00, QColor(245, 245, 245)); - gradient.setColorAt(0.49, QColor(192, 192, 192)); - gradient.setColorAt(0.51, QColor(245, 245, 245)); - gradient.setColorAt(1.00, QColor(192, 192, 192)); - p->setBrush(gradient); - QRect r = rect; - p->drawRoundedRect(r, 15, 15, Qt::RelativeSize); - r.adjust(1, 4, -1, -4); - p->setPen(QColor(181, 181, 181)); - p->setBrush(Qt::NoBrush); - p->drawRoundedRect(r, 15, 15, Qt::RelativeSize); - p->setPen(QColor(159, 159, 159)); - int y = rect.top() + rect.height() / 2 - 1; - p->drawLine(rect.left(), y, rect.right(), y); - } - - QPixmap drawDigits(int n, const QRect &rect) { - - int scaleFactor = 2; -#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) - if (rect.height() > 240) - scaleFactor = 1; -#endif - - QString str = QString::number(n); - if (str.length() == 1) - str.prepend("0"); - - QFont font; - font.setFamily("Helvetica"); - int fontHeight = scaleFactor * 0.55 * rect.height(); - font.setPixelSize(fontHeight); - font.setBold(true); - - QPixmap pixmap(rect.size() * scaleFactor); - pixmap.fill(Qt::transparent); - - QLinearGradient gradient(QPoint(0, 0), QPoint(0, pixmap.height())); - gradient.setColorAt(0.00, QColor(128, 128, 128)); - gradient.setColorAt(0.49, QColor(64, 64, 64)); - gradient.setColorAt(0.51, QColor(128, 128, 128)); - gradient.setColorAt(1.00, QColor(16, 16, 16)); - - QPainter p; - p.begin(&pixmap); - p.setFont(font); - QPen pen; - pen.setBrush(QBrush(gradient)); - p.setPen(pen); - p.drawText(pixmap.rect(), Qt::AlignCenter, str); - p.end(); - - return pixmap.scaledToWidth(width(), Qt::SmoothTransformation); - } - - void preparePixmap() { - m_pixmap = QPixmap(size()); - m_pixmap.fill(Qt::transparent); - QPainter p; - p.begin(&m_pixmap); - p.drawPixmap(0, 0, drawDigits(m_number, rect())); - p.end(); - } - - void resizeEvent(QResizeEvent*) { - preparePixmap(); - update(); - } - - void paintStatic() { - QPainter p(this); - p.fillRect(rect(), Qt::black); - - int pad = width() / 10; - drawFrame(&p, rect().adjusted(pad, pad, -pad, -pad)); - p.drawPixmap(0, 0, m_pixmap); - } - - void paintSlide() { - QPainter p(this); - p.fillRect(rect(), Qt::black); - - int pad = width() / 10; - QRect fr = rect().adjusted(pad, pad, -pad, -pad); - drawFrame(&p, fr); - p.setClipRect(fr); - - int y = height() * m_animator.currentFrame() / 100; - p.drawPixmap(0, y, m_lastPixmap); - p.drawPixmap(0, y - height(), m_pixmap); - } - - void paintFlip() { - QPainter p(this); -#if !defined(Q_OS_SYMBIAN) && !defined(Q_OS_WINCE_WM) - p.setRenderHint(QPainter::SmoothPixmapTransform, true); - p.setRenderHint(QPainter::Antialiasing, true); -#endif - p.fillRect(rect(), Qt::black); - - int hw = width() / 2; - int hh = height() / 2; - - // behind is the new pixmap - int pad = width() / 10; - QRect fr = rect().adjusted(pad, pad, -pad, -pad); - drawFrame(&p, fr); - p.drawPixmap(0, 0, m_pixmap); - - int index = m_animator.currentFrame(); - - if (index <= 50) { - - // the top part of the old pixmap is flipping - int angle = -180 * index / 100; - QTransform transform; - transform.translate(hw, hh); - transform.rotate(angle, Qt::XAxis); - p.setTransform(transform); - drawFrame(&p, fr.adjusted(-hw, -hh, -hw, -hh)); - p.drawPixmap(-hw, -hh, m_lastPixmap); - - // the bottom part is still the old pixmap - p.resetTransform(); - p.setClipRect(0, hh, width(), hh); - drawFrame(&p, fr); - p.drawPixmap(0, 0, m_lastPixmap); - } else { - - p.setClipRect(0, hh, width(), hh); - - // the bottom part is still the old pixmap - drawFrame(&p, fr); - p.drawPixmap(0, 0, m_lastPixmap); - - // the bottom part of the new pixmap is flipping - int angle = 180 - 180 * m_animator.currentFrame() / 100; - QTransform transform; - transform.translate(hw, hh); - transform.rotate(angle, Qt::XAxis); - p.setTransform(transform); - drawFrame(&p, fr.adjusted(-hw, -hh, -hw, -hh)); - p.drawPixmap(-hw, -hh, m_pixmap); - - } - - } - - void paintRotate() { - QPainter p(this); - - int pad = width() / 10; - QRect fr = rect().adjusted(pad, pad, -pad, -pad); - drawFrame(&p, fr); - p.setClipRect(fr); - - int angle1 = -180 * m_animator.currentFrame() / 100; - int angle2 = 180 - 180 * m_animator.currentFrame() / 100; - int angle = (m_animator.currentFrame() <= 50) ? angle1 : angle2; - QPixmap pix = (m_animator.currentFrame() <= 50) ? m_lastPixmap : m_pixmap; - - QTransform transform; - transform.translate(width() / 2, height() / 2); - transform.rotate(angle, Qt::XAxis); - - p.setTransform(transform); - p.setRenderHint(QPainter::SmoothPixmapTransform, true); - p.drawPixmap(-width() / 2, -height() / 2, pix); - } - - void paintEvent(QPaintEvent *event) { - Q_UNUSED(event); - if (m_animator.state() == QTimeLine::Running) { - if (m_transition == Slide) - paintSlide(); - if (m_transition == Flip) - paintFlip(); - if (m_transition == Rotate) - paintRotate(); - } else { - paintStatic(); - } - } - -private: - int m_number; - int m_transition; - QPixmap m_pixmap; - QPixmap m_lastPixmap; - QTimeLine m_animator; -}; - -class DigiFlip : public QMainWindow -{ - Q_OBJECT - -public: - DigiFlip(QWidget *parent = 0) - : QMainWindow(parent) - { - m_hour = new Digits(this); - m_hour->show(); - m_minute = new Digits(this); - m_minute->show(); - - QPalette pal = palette(); - pal.setColor(QPalette::Window, Qt::black); - setPalette(pal); - - m_ticker.start(1000, this); - QTime t = QTime::currentTime(); - m_hour->setNumber(t.hour()); - m_minute->setNumber(t.minute()); - updateTime(); - - QAction *slideAction = new QAction("&Slide", this); - QAction *flipAction = new QAction("&Flip", this); - QAction *rotateAction = new QAction("&Rotate", this); - connect(slideAction, SIGNAL(triggered()), SLOT(chooseSlide())); - connect(flipAction, SIGNAL(triggered()), SLOT(chooseFlip())); - connect(rotateAction, SIGNAL(triggered()), SLOT(chooseRotate())); -#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) - menuBar()->addAction(slideAction); - menuBar()->addAction(flipAction); - menuBar()->addAction(rotateAction); -#else - addAction(slideAction); - addAction(flipAction); - addAction(rotateAction); - setContextMenuPolicy(Qt::ActionsContextMenu); -#endif - } - - void updateTime() { - QTime t = QTime::currentTime(); - m_hour->flipTo(t.hour()); - m_minute->flipTo(t.minute()); - QString str = t.toString("hh:mm:ss"); - str.prepend(": "); - if (m_hour->transition() == Digits::Slide) - str.prepend("Slide"); - if (m_hour->transition() == Digits::Flip) - str.prepend("Flip"); - if (m_hour->transition() == Digits::Rotate) - str.prepend("Rotate"); - setWindowTitle(str); - } - - void switchTransition(int delta) { - int i = (m_hour->transition() + delta + 3) % 3; - m_hour->setTransition(i); - m_minute->setTransition(i); - updateTime(); - } - -protected: - void resizeEvent(QResizeEvent*) { - int digitsWidth = width() / 2; - int digitsHeight = digitsWidth * 1.2; - - int y = (height() - digitsHeight) / 3; - - m_hour->resize(digitsWidth, digitsHeight); - m_hour->move(0, y); - - m_minute->resize(digitsWidth, digitsHeight); - m_minute->move(width() / 2, y); - } - - void timerEvent(QTimerEvent*) { - updateTime(); - } - - void keyPressEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_Right) { - switchTransition(1); - event->accept(); - } - if (event->key() == Qt::Key_Left) { - switchTransition(-1); - event->accept(); - } - } - -private slots: - void chooseSlide() { - m_hour->setTransition(0); - m_minute->setTransition(0); - updateTime(); - } - - void chooseFlip() { - m_hour->setTransition(1); - m_minute->setTransition(1); - updateTime(); - } - - void chooseRotate() { - m_hour->setTransition(2); - m_minute->setTransition(2); - updateTime(); - } - -private: - QBasicTimer m_ticker; - Digits *m_hour; - Digits *m_minute; -}; - -#include "digiflip.moc" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - DigiFlip time; -#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) - time.showMaximized(); -#else - time.resize(320, 240); - time.show(); -#endif - - return app.exec(); -} diff --git a/demos/embedded/digiflip/digiflip.pro b/demos/embedded/digiflip/digiflip.pro deleted file mode 100644 index 7fa06fa90a..0000000000 --- a/demos/embedded/digiflip/digiflip.pro +++ /dev/null @@ -1,11 +0,0 @@ -SOURCES = digiflip.cpp - -symbian { - TARGET.UID3 = 0xA000CF72 - CONFIG += qt_demo -} - -target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/digiflip -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/digiflip -INSTALLS += target sources diff --git a/demos/embedded/embedded.pro b/demos/embedded/embedded.pro deleted file mode 100644 index e9a448b1e3..0000000000 --- a/demos/embedded/embedded.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = styledemo raycasting flickable digiflip - -SUBDIRS += lightmaps -SUBDIRS += flightinfo - -# install -sources.files = README *.pro -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded -INSTALLS += sources - -symbian: CONFIG += qt_demo diff --git a/demos/embedded/flickable/flickable.cpp b/demos/embedded/flickable/flickable.cpp deleted file mode 100644 index edcc1a7396..0000000000 --- a/demos/embedded/flickable/flickable.cpp +++ /dev/null @@ -1,284 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "flickable.h" - -#include -#include - -class FlickableTicker: QObject -{ -public: - FlickableTicker(Flickable *scroller) { - m_scroller = scroller; - } - - void start(int interval) { - if (!m_timer.isActive()) - m_timer.start(interval, this); - } - - void stop() { - m_timer.stop(); - } - -protected: - void timerEvent(QTimerEvent *event) { - Q_UNUSED(event); - m_scroller->tick(); - } - -private: - Flickable *m_scroller; - QBasicTimer m_timer; -}; - -class FlickablePrivate -{ -public: - typedef enum { - Steady, - Pressed, - ManualScroll, - AutoScroll, - Stop - } State; - - State state; - int threshold; - QPoint pressPos; - QPoint offset; - QPoint delta; - QPoint speed; - FlickableTicker *ticker; - QTime timeStamp; - QWidget *target; - QList ignoreList; -}; - -Flickable::Flickable() -{ - d = new FlickablePrivate; - d->state = FlickablePrivate::Steady; - d->threshold = 10; - d->ticker = new FlickableTicker(this); - d->timeStamp = QTime::currentTime(); - d->target = 0; -} - -Flickable::~Flickable() -{ - delete d; -} - -void Flickable::setThreshold(int th) -{ - if (th >= 0) - d->threshold = th; -} - -int Flickable::threshold() const -{ - return d->threshold; -} - -void Flickable::setAcceptMouseClick(QWidget *target) -{ - d->target = target; -} - -static QPoint deaccelerate(const QPoint &speed, int a = 1, int max = 64) -{ - int x = qBound(-max, speed.x(), max); - int y = qBound(-max, speed.y(), max); - x = (x == 0) ? x : (x > 0) ? qMax(0, x - a) : qMin(0, x + a); - y = (y == 0) ? y : (y > 0) ? qMax(0, y - a) : qMin(0, y + a); - return QPoint(x, y); -} - -void Flickable::handleMousePress(QMouseEvent *event) -{ - event->ignore(); - - if (event->button() != Qt::LeftButton) - return; - - if (d->ignoreList.removeAll(event)) - return; - - switch (d->state) { - - case FlickablePrivate::Steady: - event->accept(); - d->state = FlickablePrivate::Pressed; - d->pressPos = event->pos(); - break; - - case FlickablePrivate::AutoScroll: - event->accept(); - d->state = FlickablePrivate::Stop; - d->speed = QPoint(0, 0); - d->pressPos = event->pos(); - d->offset = scrollOffset(); - d->ticker->stop(); - break; - - default: - break; - } -} - -void Flickable::handleMouseRelease(QMouseEvent *event) -{ - event->ignore(); - - if (event->button() != Qt::LeftButton) - return; - - if (d->ignoreList.removeAll(event)) - return; - - QPoint delta; - - switch (d->state) { - - case FlickablePrivate::Pressed: - event->accept(); - d->state = FlickablePrivate::Steady; - if (d->target) { - QMouseEvent *event1 = new QMouseEvent(QEvent::MouseButtonPress, - d->pressPos, Qt::LeftButton, - Qt::LeftButton, Qt::NoModifier); - QMouseEvent *event2 = new QMouseEvent(*event); - d->ignoreList << event1; - d->ignoreList << event2; - QApplication::postEvent(d->target, event1); - QApplication::postEvent(d->target, event2); - } - break; - - case FlickablePrivate::ManualScroll: - event->accept(); - delta = event->pos() - d->pressPos; - if (d->timeStamp.elapsed() > 100) { - d->timeStamp = QTime::currentTime(); - d->speed = delta - d->delta; - d->delta = delta; - } - d->offset = scrollOffset(); - d->pressPos = event->pos(); - if (d->speed == QPoint(0, 0)) { - d->state = FlickablePrivate::Steady; - } else { - d->speed /= 4; - d->state = FlickablePrivate::AutoScroll; - d->ticker->start(20); - } - break; - - case FlickablePrivate::Stop: - event->accept(); - d->state = FlickablePrivate::Steady; - d->offset = scrollOffset(); - break; - - default: - break; - } -} - -void Flickable::handleMouseMove(QMouseEvent *event) -{ - event->ignore(); - - if (!(event->buttons() & Qt::LeftButton)) - return; - - if (d->ignoreList.removeAll(event)) - return; - - QPoint delta; - - switch (d->state) { - - case FlickablePrivate::Pressed: - case FlickablePrivate::Stop: - delta = event->pos() - d->pressPos; - if (delta.x() > d->threshold || delta.x() < -d->threshold || - delta.y() > d->threshold || delta.y() < -d->threshold) { - d->timeStamp = QTime::currentTime(); - d->state = FlickablePrivate::ManualScroll; - d->delta = QPoint(0, 0); - d->pressPos = event->pos(); - event->accept(); - } - break; - - case FlickablePrivate::ManualScroll: - event->accept(); - delta = event->pos() - d->pressPos; - setScrollOffset(d->offset - delta); - if (d->timeStamp.elapsed() > 100) { - d->timeStamp = QTime::currentTime(); - d->speed = delta - d->delta; - d->delta = delta; - } - break; - - default: - break; - } -} - -void Flickable::tick() -{ - if (d->state == FlickablePrivate:: AutoScroll) { - d->speed = deaccelerate(d->speed); - setScrollOffset(d->offset - d->speed); - d->offset = scrollOffset(); - if (d->speed == QPoint(0, 0)) { - d->state = FlickablePrivate::Steady; - d->ticker->stop(); - } - } else { - d->ticker->stop(); - } -} diff --git a/demos/embedded/flickable/flickable.h b/demos/embedded/flickable/flickable.h deleted file mode 100644 index 3195d3297c..0000000000 --- a/demos/embedded/flickable/flickable.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef FLICKABLE_H -#define FLICKABLE_H - -class QMouseEvent; -class QPoint; -class QWidget; - -class FlickableTicker; -class FlickablePrivate; - -class Flickable -{ -public: - - Flickable(); - virtual ~Flickable(); - - void setThreshold(int threshold); - int threshold() const; - - void setAcceptMouseClick(QWidget *target); - - void handleMousePress(QMouseEvent *event); - void handleMouseMove(QMouseEvent *event); - void handleMouseRelease(QMouseEvent *event); - -protected: - virtual QPoint scrollOffset() const = 0; - virtual void setScrollOffset(const QPoint &offset) = 0; - -private: - void tick(); - -private: - FlickablePrivate *d; - friend class FlickableTicker; -}; - -#endif // FLICKABLE_H diff --git a/demos/embedded/flickable/flickable.pro b/demos/embedded/flickable/flickable.pro deleted file mode 100644 index 6ee744bc63..0000000000 --- a/demos/embedded/flickable/flickable.pro +++ /dev/null @@ -1,12 +0,0 @@ -SOURCES = flickable.cpp main.cpp -HEADERS = flickable.h - -symbian { - TARGET.UID3 = 0xA000CF73 - CONFIG += qt_demo -} - -target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/flickable -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/flickable -INSTALLS += target sources diff --git a/demos/embedded/flickable/main.cpp b/demos/embedded/flickable/main.cpp deleted file mode 100644 index 3711a6dc57..0000000000 --- a/demos/embedded/flickable/main.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include - -#include "flickable.h" - -// Returns a list of two-word color names -static QStringList colorPairs(int max) -{ - // capitalize the first letter - QStringList colors = QColor::colorNames(); - colors.removeAll("transparent"); - int num = colors.count(); - for (int c = 0; c < num; ++c) - colors[c] = colors[c][0].toUpper() + colors[c].mid(1); - - // combine two colors, e.g. "lime skyblue" - QStringList combinedColors; - for (int i = 0; i < num; ++i) - for (int j = 0; j < num; ++j) - combinedColors << QString("%1 %2").arg(colors[i]).arg(colors[j]); - - // randomize it - colors.clear(); - while (combinedColors.count()) { - int i = qrand() % combinedColors.count(); - colors << combinedColors[i]; - combinedColors.removeAt(i); - if (colors.count() == max) - break; - } - - return colors; -} - -class ColorList : public QWidget, public Flickable -{ - Q_OBJECT - -public: - ColorList(QWidget *parent = 0) - : QWidget(parent) { - m_offset = 0; - m_height = QFontMetrics(font()).height() + 5; - m_highlight = -1; - m_selected = -1; - - QStringList colors = colorPairs(999); - for (int i = 0; i < colors.count(); ++i) { - QString c = colors[i]; - QString str; - str.sprintf("%4d", i + 1); - m_colorNames << (str + " " + c); - - QStringList duet = c.split(' '); - m_firstColor << duet[0]; - m_secondColor << duet[1]; - } - - setAttribute(Qt::WA_OpaquePaintEvent, true); - setAttribute(Qt::WA_NoSystemBackground, true); - - setMouseTracking(true); - Flickable::setAcceptMouseClick(this); - } - -protected: - // reimplement from Flickable - virtual QPoint scrollOffset() const { - return QPoint(0, m_offset); - } - - // reimplement from Flickable - virtual void setScrollOffset(const QPoint &offset) { - int yy = offset.y(); - if (yy != m_offset) { - m_offset = qBound(0, yy, m_height * m_colorNames.count() - height()); - update(); - } - } - -protected: - void paintEvent(QPaintEvent *event) { - QPainter p(this); - p.fillRect(event->rect(), Qt::white); - int start = m_offset / m_height; - int y = start * m_height - m_offset; - if (m_offset <= 0) { - start = 0; - y = -m_offset; - } - int end = start + height() / m_height + 1; - if (end > m_colorNames.count() - 1) - end = m_colorNames.count() - 1; - for (int i = start; i <= end; ++i, y += m_height) { - - p.setBrush(Qt::NoBrush); - p.setPen(Qt::black); - if (i == m_highlight) { - p.fillRect(0, y, width(), m_height, QColor(0, 64, 128)); - p.setPen(Qt::white); - } - if (i == m_selected) { - p.fillRect(0, y, width(), m_height, QColor(0, 128, 240)); - p.setPen(Qt::white); - } - - p.drawText(m_height + 2, y, width(), m_height, Qt::AlignVCenter, m_colorNames[i]); - - p.setPen(Qt::NoPen); - p.setBrush(m_firstColor[i]); - p.drawRect(1, y + 1, m_height - 2, m_height - 2); - p.setBrush(m_secondColor[i]); - p.drawRect(5, y + 5, m_height - 11, m_height - 11); - } - p.end(); - } - - void keyReleaseEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_Down) { - m_offset += 20; - event->accept(); - update(); - return; - } - if (event->key() == Qt::Key_Up) { - m_offset -= 20; - event->accept(); - update(); - return; - } - } - - void mousePressEvent(QMouseEvent *event) { - Flickable::handleMousePress(event); - if (event->isAccepted()) - return; - - if (event->button() == Qt::LeftButton) { - int y = event->pos().y() + m_offset; - int i = y / m_height; - if (i != m_highlight) { - m_highlight = i; - m_selected = -1; - update(); - } - event->accept(); - } - } - - void mouseMoveEvent(QMouseEvent *event) { - Flickable::handleMouseMove(event); - } - - void mouseReleaseEvent(QMouseEvent *event) { - Flickable::handleMouseRelease(event); - if (event->isAccepted()) - return; - - if (event->button() == Qt::LeftButton) { - m_selected = m_highlight; - event->accept(); - update(); - } - } - -private: - int m_offset; - int m_height; - int m_highlight; - int m_selected; - QStringList m_colorNames; - QList m_firstColor; - QList m_secondColor; -}; - -#include "main.moc" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - ColorList list; - list.setWindowTitle("Kinetic Scrolling"); -#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) - list.showMaximized(); -#else - list.resize(320, 320); - list.show(); -#endif - - return app.exec(); -} diff --git a/demos/embedded/flightinfo/aircraft.png b/demos/embedded/flightinfo/aircraft.png deleted file mode 100644 index 2312bcc9f0..0000000000 Binary files a/demos/embedded/flightinfo/aircraft.png and /dev/null differ diff --git a/demos/embedded/flightinfo/flightinfo.cpp b/demos/embedded/flightinfo/flightinfo.cpp deleted file mode 100644 index 58e71c8376..0000000000 --- a/demos/embedded/flightinfo/flightinfo.cpp +++ /dev/null @@ -1,399 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include - -#include "ui_form.h" - -#define FLIGHTVIEW_URL "http://mobile.flightview.com/TrackByFlight.aspx" -#define FLIGHTVIEW_RANDOM "http://mobile.flightview.com/TrackSampleFlight.aspx" - -// strips all invalid constructs that might trip QXmlStreamReader -static QString sanitized(const QString &xml) -{ - QString data = xml; - - // anything up to the html tag - int i = data.indexOf(" 0) - data.remove(0, i - 1); - - // everything inside the head tag - i = data.indexOf(" 0) - data.remove(i, data.indexOf("") - i + 7); - - // invalid link for JavaScript code - while (true) { - i = data.indexOf("onclick=\"gotoUrl("); - if (i < 0) - break; - data.remove(i, data.indexOf('\"', i + 9) - i + 1); - } - - // all inline frames - while (true) { - i = data.indexOf("") - i + 8); - } - - // entities - data.remove(" "); - data.remove("©"); - - return data; -} - -class FlightInfo : public QMainWindow -{ - Q_OBJECT - -private: - - Ui_Form ui; - QUrl m_url; - QDate m_searchDate; - QPixmap m_map; - QNetworkAccessManager m_manager; - QList mapReplies; - -public: - - FlightInfo(QMainWindow *parent = 0): QMainWindow(parent) { - - QWidget *w = new QWidget(this); - ui.setupUi(w); - setCentralWidget(w); - - ui.searchBar->hide(); - ui.infoBox->hide(); - connect(ui.searchButton, SIGNAL(clicked()), SLOT(startSearch())); - connect(ui.flightEdit, SIGNAL(returnPressed()), SLOT(startSearch())); - - setWindowTitle("Flight Info"); - - // Rendered from the public-domain vectorized aircraft - // http://openclipart.org/media/people/Jarno - m_map = QPixmap(":/aircraft.png"); - - QAction *searchTodayAction = new QAction("Today's Flight", this); - QAction *searchYesterdayAction = new QAction("Yesterday's Flight", this); - QAction *randomAction = new QAction("Random Flight", this); - connect(searchTodayAction, SIGNAL(triggered()), SLOT(today())); - connect(searchYesterdayAction, SIGNAL(triggered()), SLOT(yesterday())); - connect(randomAction, SIGNAL(triggered()), SLOT(randomFlight())); - connect(&m_manager, SIGNAL(finished(QNetworkReply*)), - this, SLOT(handleNetworkData(QNetworkReply*))); -#if defined(Q_OS_SYMBIAN) - menuBar()->addAction(searchTodayAction); - menuBar()->addAction(searchYesterdayAction); - menuBar()->addAction(randomAction); -#else - addAction(searchTodayAction); - addAction(searchYesterdayAction); - addAction(randomAction); - setContextMenuPolicy(Qt::ActionsContextMenu); -#endif - } - -private slots: - - void handleNetworkData(QNetworkReply *networkReply) { - if (!networkReply->error()) { - if (!mapReplies.contains(networkReply)) { - // Assume UTF-8 encoded - QByteArray data = networkReply->readAll(); - QString xml = QString::fromUtf8(data); - digest(xml); - } else { - mapReplies.removeOne(networkReply); - m_map.loadFromData(networkReply->readAll()); - update(); - } - } - networkReply->deleteLater(); - } - - void today() { - QDateTime timestamp = QDateTime::currentDateTime(); - m_searchDate = timestamp.date(); - searchFlight(); - } - - void yesterday() { - QDateTime timestamp = QDateTime::currentDateTime(); - timestamp = timestamp.addDays(-1); - m_searchDate = timestamp.date(); - searchFlight(); - } - - void searchFlight() { - ui.searchBar->show(); - ui.infoBox->hide(); - ui.flightStatus->hide(); - ui.flightName->setText("Enter flight number"); - ui.flightEdit->setFocus(); -#ifdef QT_KEYPAD_NAVIGATION - ui.flightEdit->setEditFocus(true); -#endif - m_map = QPixmap(); - update(); - } - - void startSearch() { - ui.searchBar->hide(); - QString flight = ui.flightEdit->text().simplified(); - if (!flight.isEmpty()) - request(flight, m_searchDate); - } - - void randomFlight() { - request(QString(), QDate::currentDate()); - } - -public slots: - - void request(const QString &flightCode, const QDate &date) { - - setWindowTitle("Loading..."); - - QString code = flightCode.simplified(); - QString airlineCode = code.left(2).toUpper(); - QString flightNumber = code.mid(2, code.length()); - - ui.flightName->setText("Searching for " + code); - - m_url = QUrl(FLIGHTVIEW_URL); - m_url.addEncodedQueryItem("view", "detail"); - m_url.addEncodedQueryItem("al", QUrl::toPercentEncoding(airlineCode)); - m_url.addEncodedQueryItem("fn", QUrl::toPercentEncoding(flightNumber)); - m_url.addEncodedQueryItem("dpdat", QUrl::toPercentEncoding(date.toString("yyyyMMdd"))); - - if (code.isEmpty()) { - // random flight as sample - m_url = QUrl(FLIGHTVIEW_RANDOM); - ui.flightName->setText("Getting a random flight..."); - } - - m_manager.get(QNetworkRequest(m_url)); - } - - -private: - - void digest(const QString &content) { - - setWindowTitle("Flight Info"); - QString data = sanitized(content); - - // do we only get the flight list? - // we grab the first leg in the flight list - // then fetch another URL for the real flight info - int i = data.indexOf("a href=\"?view=detail"); - if (i > 0) { - QString href = data.mid(i, data.indexOf('\"', i + 8) - i + 1); - QRegExp regex("dpap=([A-Za-z0-9]+)"); - regex.indexIn(href); - QString airport = regex.cap(1); - m_url.addEncodedQueryItem("dpap", QUrl::toPercentEncoding(airport)); - m_manager.get(QNetworkRequest(m_url)); - return; - } - - QXmlStreamReader xml(data); - bool inFlightName = false; - bool inFlightStatus = false; - bool inFlightMap = false; - bool inFieldName = false; - bool inFieldValue = false; - - QString flightName; - QString flightStatus; - QStringList fieldNames; - QStringList fieldValues; - - while (!xml.atEnd()) { - xml.readNext(); - - if (xml.tokenType() == QXmlStreamReader::StartElement) { - QStringRef className = xml.attributes().value("class"); - inFlightName |= xml.name() == "h1"; - inFlightStatus |= className == "FlightDetailHeaderStatus"; - inFlightMap |= className == "flightMap"; - if (xml.name() == "td" && !className.isEmpty()) { - QString cn = className.toString(); - if (cn.contains("fieldTitle")) { - inFieldName = true; - fieldNames += QString(); - fieldValues += QString(); - } - if (cn.contains("fieldValue")) - inFieldValue = true; - } - if (xml.name() == "img" && inFlightMap) { - QString src = xml.attributes().value("src").toString(); - src.prepend("http://mobile.flightview.com/"); - QUrl url = QUrl::fromPercentEncoding(src.toAscii()); - mapReplies.append(m_manager.get(QNetworkRequest(url))); - } - } - - if (xml.tokenType() == QXmlStreamReader::EndElement) { - inFlightName &= xml.name() != "h1"; - inFlightStatus &= xml.name() != "div"; - inFlightMap &= xml.name() != "div"; - inFieldName &= xml.name() != "td"; - inFieldValue &= xml.name() != "td"; - } - - if (xml.tokenType() == QXmlStreamReader::Characters) { - if (inFlightName) - flightName += xml.text(); - if (inFlightStatus) - flightStatus += xml.text(); - if (inFieldName) - fieldNames.last() += xml.text(); - if (inFieldValue) - fieldValues.last() += xml.text(); - } - } - - if (fieldNames.isEmpty()) { - QString code = ui.flightEdit->text().simplified().left(10); - QString msg = QString("Flight %1 is not found").arg(code); - ui.flightName->setText(msg); - return; - } - - ui.flightName->setText(flightName); - flightStatus.remove("Status: "); - ui.flightStatus->setText(flightStatus); - ui.flightStatus->show(); - - QStringList whiteList; - whiteList << "Departure"; - whiteList << "Arrival"; - whiteList << "Scheduled"; - whiteList << "Takeoff"; - whiteList << "Estimated"; - whiteList << "Term-Gate"; - - QString text; - text = QString("").arg(width() - 25); - for (int i = 0; i < fieldNames.count(); i++) { - QString fn = fieldNames[i].simplified(); - if (fn.endsWith(':')) - fn = fn.left(fn.length() - 1); - if (!whiteList.contains(fn)) - continue; - - QString fv = fieldValues[i].simplified(); - bool special = false; - special |= fn.startsWith("Departure"); - special |= fn.startsWith("Arrival"); - text += ""; - if (special) { - text += ""; - } else { - text += ""; - text += ""; - } - text += ""; - } - text += "
"; - text += "" + fv + ""; - text += ""; - text += fn; - text += " : "; - text += " "; - text += ""; - text += fv; - text += "
"; - ui.detailedInfo->setText(text); - ui.infoBox->show(); - } - - void resizeEvent(QResizeEvent *event) { - Q_UNUSED(event); - ui.detailedInfo->setMaximumWidth(width() - 25); - } - - void paintEvent(QPaintEvent *event) { - QMainWindow::paintEvent(event); - QPainter p(this); - p.fillRect(rect(), QColor(131, 171, 210)); - if (!m_map.isNull()) { - int x = (width() - m_map.width()) / 2; - int space = ui.infoBox->pos().y(); - if (!ui.infoBox->isVisible()) - space = height(); - int top = ui.titleBox->height(); - int y = qMax(top, (space - m_map.height()) / 2); - p.drawPixmap(x, y, m_map); - } - p.end(); - } - -}; - - -#include "flightinfo.moc" - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(flightinfo); - - QApplication app(argc, argv); - - FlightInfo w; -#if defined(Q_OS_SYMBIAN) - w.showMaximized(); -#else - w.resize(360, 504); - w.show(); -#endif - - return app.exec(); -} diff --git a/demos/embedded/flightinfo/flightinfo.pro b/demos/embedded/flightinfo/flightinfo.pro deleted file mode 100644 index a33423f543..0000000000 --- a/demos/embedded/flightinfo/flightinfo.pro +++ /dev/null @@ -1,17 +0,0 @@ -TEMPLATE = app -TARGET = flightinfo -SOURCES = flightinfo.cpp -FORMS += form.ui -RESOURCES = flightinfo.qrc -QT += network - -symbian { - TARGET.UID3 = 0xA000CF74 - CONFIG += qt_demo - TARGET.CAPABILITY = NetworkServices -} - -target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/flightinfo -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/flightinfo -INSTALLS += target sources diff --git a/demos/embedded/flightinfo/flightinfo.qrc b/demos/embedded/flightinfo/flightinfo.qrc deleted file mode 100644 index babea7e0cb..0000000000 --- a/demos/embedded/flightinfo/flightinfo.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - aircraft.png - - diff --git a/demos/embedded/flightinfo/form.ui b/demos/embedded/flightinfo/form.ui deleted file mode 100644 index 3a24c758a6..0000000000 --- a/demos/embedded/flightinfo/form.ui +++ /dev/null @@ -1,226 +0,0 @@ - - - Form - - - - 0 - 0 - 220 - 171 - - - - Form - - - - 0 - - - 0 - - - - - QFrame { -background-color: #45629a; -} - -QLabel { -color: white; -} - - - QFrame::NoFrame - - - QFrame::Raised - - - 0 - - - - 0 - - - 4 - - - - - - 0 - 0 - - - - Powered by FlightView - - - - - - - - 0 - 0 - - - - - 75 - true - - - - background-color: white; -color: #45629a; - - - 0 - - - Ready - - - Qt::AlignCenter - - - 4 - - - - - - - - - - QFrame::NoFrame - - - QFrame::Raised - - - - 5 - - - - - color: black; -border: 1px solid black; -background: white; -selection-background-color: lightgray; - - - - - - - color: rgb(255, 255, 255); -background-color: rgb(85, 85, 255); -padding: 2px; -border: 2px solid rgb(0, 0, 127); - - - Search - - - Qt::ToolButtonTextBesideIcon - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - Qt::Vertical - - - - 20 - 58 - - - - - - - - - 0 - 0 - - - - QFrame { border: 2px solid white; -border-radius: 10px; -margin: 5px; -background-color: rgba(69, 98, 154, 192); } - - - QFrame::NoFrame - - - QFrame::Raised - - - - 0 - - - 5 - - - - - - 0 - 0 - - - - color: white; -border: none; -background-color: none; - - - - - - Qt::RichText - - - true - - - Qt::NoTextInteraction - - - - - - - - - - - diff --git a/demos/embedded/lightmaps/lightmaps.cpp b/demos/embedded/lightmaps/lightmaps.cpp deleted file mode 100644 index d672530e19..0000000000 --- a/demos/embedded/lightmaps/lightmaps.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include - -#include - -#include "lightmaps.h" -#include "slippymap.h" - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -// how long (milliseconds) the user need to hold (after a tap on the screen) -// before triggering the magnifying glass feature -// 701, a prime number, is the sum of 229, 233, 239 -// (all three are also prime numbers, consecutive!) -#define HOLD_TIME 701 - -// maximum size of the magnifier -// Hint: see above to find why I picked this one :) -#define MAX_MAGNIFIER 229 - -LightMaps::LightMaps(QWidget *parent) - : QWidget(parent), pressed(false), snapped(false), zoomed(false), - invert(false) -{ - m_normalMap = new SlippyMap(this); - m_largeMap = new SlippyMap(this); - connect(m_normalMap, SIGNAL(updated(QRect)), SLOT(updateMap(QRect))); - connect(m_largeMap, SIGNAL(updated(QRect)), SLOT(update())); -} - -void LightMaps::setCenter(qreal lat, qreal lng) -{ - m_normalMap->latitude = lat; - m_normalMap->longitude = lng; - m_normalMap->invalidate(); - m_largeMap->latitude = lat; - m_largeMap->longitude = lng; - m_largeMap->invalidate(); -} - -void LightMaps::toggleNightMode() -{ - invert = !invert; - update(); -} - -void LightMaps::updateMap(const QRect &r) -{ - update(r); -} - -void LightMaps::activateZoom() -{ - zoomed = true; - tapTimer.stop(); - m_largeMap->zoom = m_normalMap->zoom + 1; - m_largeMap->width = m_normalMap->width * 2; - m_largeMap->height = m_normalMap->height * 2; - m_largeMap->latitude = m_normalMap->latitude; - m_largeMap->longitude = m_normalMap->longitude; - m_largeMap->invalidate(); - update(); -} - -void LightMaps::resizeEvent(QResizeEvent *) -{ - m_normalMap->width = width(); - m_normalMap->height = height(); - m_normalMap->invalidate(); - m_largeMap->width = m_normalMap->width * 2; - m_largeMap->height = m_normalMap->height * 2; - m_largeMap->invalidate(); -} - -void LightMaps::paintEvent(QPaintEvent *event) -{ - QPainter p; - p.begin(this); - m_normalMap->render(&p, event->rect()); - p.setPen(Qt::black); -#if defined(Q_OS_SYMBIAN) - QFont font = p.font(); - font.setPixelSize(13); - p.setFont(font); -#endif - p.drawText(rect(), Qt::AlignBottom | Qt::TextWordWrap, - "Map data CCBYSA 2009 OpenStreetMap.org contributors"); - p.end(); - - if (zoomed) { - int dim = qMin(width(), height()); - int magnifierSize = qMin(MAX_MAGNIFIER, dim * 2 / 3); - int radius = magnifierSize / 2; - int ring = radius - 15; - QSize box = QSize(magnifierSize, magnifierSize); - - // reupdate our mask - if (maskPixmap.size() != box) { - maskPixmap = QPixmap(box); - maskPixmap.fill(Qt::transparent); - - QRadialGradient g; - g.setCenter(radius, radius); - g.setFocalPoint(radius, radius); - g.setRadius(radius); - g.setColorAt(1.0, QColor(255, 255, 255, 0)); - g.setColorAt(0.5, QColor(128, 128, 128, 255)); - - QPainter mask(&maskPixmap); - mask.setRenderHint(QPainter::Antialiasing); - mask.setCompositionMode(QPainter::CompositionMode_Source); - mask.setBrush(g); - mask.setPen(Qt::NoPen); - mask.drawRect(maskPixmap.rect()); - mask.setBrush(QColor(Qt::transparent)); - mask.drawEllipse(g.center(), ring, ring); - mask.end(); - } - - QPoint center = dragPos - QPoint(0, radius); - center = center + QPoint(0, radius / 2); - QPoint corner = center - QPoint(radius, radius); - - QPoint xy = center * 2 - QPoint(radius, radius); - - // only set the dimension to the magnified portion - if (zoomPixmap.size() != box) { - zoomPixmap = QPixmap(box); - zoomPixmap.fill(Qt::lightGray); - } - if (true) { - QPainter p(&zoomPixmap); - p.translate(-xy); - m_largeMap->render(&p, QRect(xy, box)); - p.end(); - } - - QPainterPath clipPath; - clipPath.addEllipse(center, ring, ring); - - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - p.setClipPath(clipPath); - p.drawPixmap(corner, zoomPixmap); - p.setClipping(false); - p.drawPixmap(corner, maskPixmap); - p.setPen(Qt::gray); - p.drawPath(clipPath); - } - if (invert) { - QPainter p(this); - p.setCompositionMode(QPainter::CompositionMode_Difference); - p.fillRect(event->rect(), Qt::white); - p.end(); - } -} - -void LightMaps::timerEvent(QTimerEvent *) -{ - if (!zoomed) - activateZoom(); - update(); -} - -void LightMaps::mousePressEvent(QMouseEvent *event) -{ - if (event->buttons() != Qt::LeftButton) - return; - pressed = snapped = true; - pressPos = dragPos = event->pos(); - tapTimer.stop(); - tapTimer.start(HOLD_TIME, this); -} - -void LightMaps::mouseMoveEvent(QMouseEvent *event) -{ - if (!event->buttons()) - return; - if (!zoomed) { - if (!pressed || !snapped) { - QPoint delta = event->pos() - pressPos; - pressPos = event->pos(); - m_normalMap->pan(delta); - return; - } else { - const int threshold = 10; - QPoint delta = event->pos() - pressPos; - if (snapped) { - snapped &= delta.x() < threshold; - snapped &= delta.y() < threshold; - snapped &= delta.x() > -threshold; - snapped &= delta.y() > -threshold; - } - if (!snapped) - tapTimer.stop(); - } - } else { - dragPos = event->pos(); - update(); - } -} - -void LightMaps::mouseReleaseEvent(QMouseEvent *) -{ - zoomed = false; - update(); -} - -void LightMaps::keyPressEvent(QKeyEvent *event) -{ - if (!zoomed) { - if (event->key() == Qt::Key_Left) - m_normalMap->pan(QPoint(20, 0)); - if (event->key() == Qt::Key_Right) - m_normalMap->pan(QPoint(-20, 0)); - if (event->key() == Qt::Key_Up) - m_normalMap->pan(QPoint(0, 20)); - if (event->key() == Qt::Key_Down) - m_normalMap->pan(QPoint(0, -20)); - if (event->key() == Qt::Key_Z || event->key() == Qt::Key_Select) { - dragPos = QPoint(width() / 2, height() / 2); - activateZoom(); - } - } else { - if (event->key() == Qt::Key_Z || event->key() == Qt::Key_Select) { - zoomed = false; - update(); - } - QPoint delta(0, 0); - if (event->key() == Qt::Key_Left) - delta = QPoint(-15, 0); - if (event->key() == Qt::Key_Right) - delta = QPoint(15, 0); - if (event->key() == Qt::Key_Up) - delta = QPoint(0, -15); - if (event->key() == Qt::Key_Down) - delta = QPoint(0, 15); - if (delta != QPoint(0, 0)) { - dragPos += delta; - update(); - } - } -} diff --git a/demos/embedded/lightmaps/lightmaps.h b/demos/embedded/lightmaps/lightmaps.h deleted file mode 100644 index 45b5c188a2..0000000000 --- a/demos/embedded/lightmaps/lightmaps.h +++ /dev/null @@ -1,88 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef LIGHTMAPS_H -#define LIGHTMAPS_H - -#include -#include - -class SlippyMap; - -class LightMaps: public QWidget -{ - Q_OBJECT - -public: - LightMaps(QWidget *parent = 0); - void setCenter(qreal lat, qreal lng); - -public slots: - void toggleNightMode(); - -protected: - void activateZoom(); - void resizeEvent(QResizeEvent *); - void paintEvent(QPaintEvent *event); - void timerEvent(QTimerEvent *); - void mousePressEvent(QMouseEvent *event); - void mouseMoveEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *); - void keyPressEvent(QKeyEvent *event); - -private slots: - void updateMap(const QRect &r); - -private: - SlippyMap *m_normalMap; - SlippyMap *m_largeMap; - bool pressed; - bool snapped; - QPoint pressPos; - QPoint dragPos; - QBasicTimer tapTimer; - bool zoomed; - QPixmap zoomPixmap; - QPixmap maskPixmap; - bool invert; -}; - -#endif \ No newline at end of file diff --git a/demos/embedded/lightmaps/lightmaps.pro b/demos/embedded/lightmaps/lightmaps.pro deleted file mode 100644 index 2751c3a647..0000000000 --- a/demos/embedded/lightmaps/lightmaps.pro +++ /dev/null @@ -1,21 +0,0 @@ -TEMPLATE = app -HEADERS = lightmaps.h \ - mapzoom.h \ - slippymap.h -SOURCES = lightmaps.cpp \ - main.cpp \ - mapzoom.cpp \ - slippymap.cpp -QT += network - -symbian { - TARGET.UID3 = 0xA000CF75 - CONFIG += qt_demo - TARGET.CAPABILITY = NetworkServices - TARGET.EPOCHEAPSIZE = 0x20000 0x2000000 -} - -target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/lightmaps -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/lightmaps -INSTALLS += target sources diff --git a/demos/embedded/lightmaps/main.cpp b/demos/embedded/lightmaps/main.cpp deleted file mode 100644 index 85f74e638e..0000000000 --- a/demos/embedded/lightmaps/main.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "mapzoom.h" - -int main(int argc, char **argv) -{ -#if defined(Q_WS_X11) - QApplication::setGraphicsSystem("raster"); -#endif - - QApplication app(argc, argv); - app.setApplicationName("LightMaps"); - - MapZoom w; -#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) - w.showMaximized(); -#else - w.resize(600, 450); - w.show(); -#endif - - return app.exec(); -} diff --git a/demos/embedded/lightmaps/mapzoom.cpp b/demos/embedded/lightmaps/mapzoom.cpp deleted file mode 100644 index d01457e3f4..0000000000 --- a/demos/embedded/lightmaps/mapzoom.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include "lightmaps.h" -#include "mapzoom.h" - -MapZoom::MapZoom() - : QMainWindow(0) -{ - map = new LightMaps(this); - setCentralWidget(map); - map->setFocus(); - - QAction *osloAction = new QAction(tr("&Oslo"), this); - QAction *berlinAction = new QAction(tr("&Berlin"), this); - QAction *jakartaAction = new QAction(tr("&Jakarta"), this); - QAction *nightModeAction = new QAction(tr("Night Mode"), this); - nightModeAction->setCheckable(true); - nightModeAction->setChecked(false); - QAction *osmAction = new QAction(tr("About OpenStreetMap"), this); - connect(osloAction, SIGNAL(triggered()), SLOT(chooseOslo())); - connect(berlinAction, SIGNAL(triggered()), SLOT(chooseBerlin())); - connect(jakartaAction, SIGNAL(triggered()), SLOT(chooseJakarta())); - connect(nightModeAction, SIGNAL(triggered()), map, SLOT(toggleNightMode())); - connect(osmAction, SIGNAL(triggered()), SLOT(aboutOsm())); - -#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) - menuBar()->addAction(osloAction); - menuBar()->addAction(berlinAction); - menuBar()->addAction(jakartaAction); - menuBar()->addAction(nightModeAction); - menuBar()->addAction(osmAction); -#else - QMenu *menu = menuBar()->addMenu(tr("&Options")); - menu->addAction(osloAction); - menu->addAction(berlinAction); - menu->addAction(jakartaAction); - menu->addSeparator(); - menu->addAction(nightModeAction); - menu->addAction(osmAction); -#endif - - QNetworkConfigurationManager manager; - if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) { - // Get saved network configuration - QSettings settings(QSettings::UserScope, QLatin1String("Trolltech")); - settings.beginGroup(QLatin1String("QtNetwork")); - const QString id = - settings.value(QLatin1String("DefaultNetworkConfiguration")).toString(); - settings.endGroup(); - - // If the saved network configuration is not currently discovered use the system - // default - QNetworkConfiguration config = manager.configurationFromIdentifier(id); - if ((config.state() & QNetworkConfiguration::Discovered) != - QNetworkConfiguration::Discovered) { - config = manager.defaultConfiguration(); - } - - networkSession = new QNetworkSession(config, this); - connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened())); - - networkSession->open(); - } else { - networkSession = 0; - } - - setWindowTitle(tr("Light Maps")); -} - -void MapZoom::sessionOpened() -{ - // Save the used configuration - QNetworkConfiguration config = networkSession->configuration(); - QString id; - if (config.type() == QNetworkConfiguration::UserChoice) { - id = networkSession->sessionProperty( - QLatin1String("UserChoiceConfiguration")).toString(); - } else { - id = config.identifier(); - } - - QSettings settings(QSettings::UserScope, QLatin1String("Trolltech")); - settings.beginGroup(QLatin1String("QtNetwork")); - settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id); - settings.endGroup(); -} - -void MapZoom::chooseOslo() -{ - map->setCenter(59.9138204, 10.7387413); -} - -void MapZoom::chooseBerlin() -{ - map->setCenter(52.52958999943302, 13.383053541183472); -} - -void MapZoom::chooseJakarta() -{ - map->setCenter(-6.211544, 106.845172); -} - -void MapZoom::aboutOsm() -{ - QDesktopServices::openUrl(QUrl("http://www.openstreetmap.org")); -} diff --git a/demos/embedded/lightmaps/mapzoom.h b/demos/embedded/lightmaps/mapzoom.h deleted file mode 100644 index ac70a23316..0000000000 --- a/demos/embedded/lightmaps/mapzoom.h +++ /dev/null @@ -1,69 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MAPZOOM_H -#define MAPZOOM_H - -#include - -class QNetworkSession; -class LightMaps; - -class MapZoom : public QMainWindow -{ - Q_OBJECT - -public: - MapZoom(); - -private slots: - void sessionOpened(); - void chooseOslo(); - void chooseBerlin(); - void chooseJakarta(); - void aboutOsm(); - -private: - LightMaps *map; - QNetworkSession *networkSession; -}; - -#endif \ No newline at end of file diff --git a/demos/embedded/lightmaps/slippymap.cpp b/demos/embedded/lightmaps/slippymap.cpp deleted file mode 100644 index 8c71f2946a..0000000000 --- a/demos/embedded/lightmaps/slippymap.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include -#include -#include "slippymap.h" - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -uint qHash(const QPoint& p) -{ - return p.x() * 17 ^ p.y(); -} - -// tile size in pixels -const int tdim = 256; - -QPointF tileForCoordinate(qreal lat, qreal lng, int zoom) -{ - qreal zn = static_cast(1 << zoom); - qreal tx = (lng + 180.0) / 360.0; - qreal ty = (1.0 - log(tan(lat * M_PI / 180.0) + - 1.0 / cos(lat * M_PI / 180.0)) / M_PI) / 2.0; - return QPointF(tx * zn, ty * zn); -} - -qreal longitudeFromTile(qreal tx, int zoom) -{ - qreal zn = static_cast(1 << zoom); - qreal lat = tx / zn * 360.0 - 180.0; - return lat; -} - -qreal latitudeFromTile(qreal ty, int zoom) -{ - qreal zn = static_cast(1 << zoom); - qreal n = M_PI - 2 * M_PI * ty / zn; - qreal lng = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n))); - return lng; -} - - -SlippyMap::SlippyMap(QObject *parent) - : QObject(parent), width(400), height(300), zoom(15), - latitude(59.9138204), longitude(10.7387413) -{ - m_emptyTile = QPixmap(tdim, tdim); - m_emptyTile.fill(Qt::lightGray); - - QNetworkDiskCache *cache = new QNetworkDiskCache; - cache->setCacheDirectory(QDesktopServices::storageLocation - (QDesktopServices::CacheLocation)); - m_manager.setCache(cache); - connect(&m_manager, SIGNAL(finished(QNetworkReply*)), - this, SLOT(handleNetworkData(QNetworkReply*))); -} - -void SlippyMap::invalidate() -{ - if (width <= 0 || height <= 0) - return; - - QPointF ct = tileForCoordinate(latitude, longitude, zoom); - qreal tx = ct.x(); - qreal ty = ct.y(); - - // top-left corner of the center tile - int xp = width / 2 - (tx - floor(tx)) * tdim; - int yp = height / 2 - (ty - floor(ty)) * tdim; - - // first tile vertical and horizontal - int xa = (xp + tdim - 1) / tdim; - int ya = (yp + tdim - 1) / tdim; - int xs = static_cast(tx) - xa; - int ys = static_cast(ty) - ya; - - // offset for top-left tile - m_offset = QPoint(xp - xa * tdim, yp - ya * tdim); - - // last tile vertical and horizontal - int xe = static_cast(tx) + (width - xp - 1) / tdim; - int ye = static_cast(ty) + (height - yp - 1) / tdim; - - // build a rect - m_tilesRect = QRect(xs, ys, xe - xs + 1, ye - ys + 1); - - if (m_url.isEmpty()) - download(); - - emit updated(QRect(0, 0, width, height)); -} - -void SlippyMap::render(QPainter *p, const QRect &rect) -{ - for (int x = 0; x <= m_tilesRect.width(); ++x) - for (int y = 0; y <= m_tilesRect.height(); ++y) { - QPoint tp(x + m_tilesRect.left(), y + m_tilesRect.top()); - QRect box = tileRect(tp); - if (rect.intersects(box)) { - if (m_tilePixmaps.contains(tp)) - p->drawPixmap(box, m_tilePixmaps.value(tp)); - else - p->drawPixmap(box, m_emptyTile); - } - } -} - -void SlippyMap::pan(const QPoint &delta) -{ - QPointF dx = QPointF(delta) / qreal(tdim); - QPointF center = tileForCoordinate(latitude, longitude, zoom) - dx; - latitude = latitudeFromTile(center.y(), zoom); - longitude = longitudeFromTile(center.x(), zoom); - invalidate(); -} - -void SlippyMap::handleNetworkData(QNetworkReply *reply) -{ - QImage img; - QPoint tp = reply->request().attribute(QNetworkRequest::User).toPoint(); - QUrl url = reply->url(); - if (!reply->error()) - if (!img.load(reply, 0)) - img = QImage(); - reply->deleteLater(); - m_tilePixmaps[tp] = QPixmap::fromImage(img); - if (img.isNull()) - m_tilePixmaps[tp] = m_emptyTile; - emit updated(tileRect(tp)); - - // purge unused spaces - QRect bound = m_tilesRect.adjusted(-2, -2, 2, 2); - foreach(QPoint tp, m_tilePixmaps.keys()) - if (!bound.contains(tp)) - m_tilePixmaps.remove(tp); - - download(); -} - -void SlippyMap::download() -{ - QPoint grab(0, 0); - for (int x = 0; x <= m_tilesRect.width(); ++x) - for (int y = 0; y <= m_tilesRect.height(); ++y) { - QPoint tp = m_tilesRect.topLeft() + QPoint(x, y); - if (!m_tilePixmaps.contains(tp)) { - grab = tp; - break; - } - } - if (grab == QPoint(0, 0)) { - m_url = QUrl(); - return; - } - - QString path = "http://tile.openstreetmap.org/%1/%2/%3.png"; - m_url = QUrl(path.arg(zoom).arg(grab.x()).arg(grab.y())); - QNetworkRequest request; - request.setUrl(m_url); - request.setRawHeader("User-Agent", "Nokia (Qt) Graphics Dojo 1.0"); - request.setAttribute(QNetworkRequest::User, QVariant(grab)); - m_manager.get(request); -} - -QRect SlippyMap::tileRect(const QPoint &tp) -{ - QPoint t = tp - m_tilesRect.topLeft(); - int x = t.x() * tdim + m_offset.x(); - int y = t.y() * tdim + m_offset.y(); - return QRect(x, y, tdim, tdim); -} diff --git a/demos/embedded/lightmaps/slippymap.h b/demos/embedded/lightmaps/slippymap.h deleted file mode 100644 index 64ba5c3e59..0000000000 --- a/demos/embedded/lightmaps/slippymap.h +++ /dev/null @@ -1,87 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SLIPPYMAP_H -#define SLIPPYMAP_H - -#include -#include -#include - -class QNetworkReply; -class QPainter; - -class SlippyMap: public QObject -{ - Q_OBJECT - -public: - SlippyMap(QObject *parent = 0); - void invalidate(); - void render(QPainter *p, const QRect &rect); - void pan(const QPoint &delta); - - int width; - int height; - int zoom; - qreal latitude; - qreal longitude; - -signals: - void updated(const QRect &rect); - -private slots: - void handleNetworkData(QNetworkReply *reply); - void download(); - -protected: - QRect tileRect(const QPoint &tp); - -private: - QPoint m_offset; - QRect m_tilesRect; - QPixmap m_emptyTile; - QHash m_tilePixmaps; - QNetworkAccessManager m_manager; - QUrl m_url; -}; - -#endif \ No newline at end of file diff --git a/demos/embedded/raycasting/raycasting.cpp b/demos/embedded/raycasting/raycasting.cpp deleted file mode 100644 index d404044a9a..0000000000 --- a/demos/embedded/raycasting/raycasting.cpp +++ /dev/null @@ -1,391 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include - -#include - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -#define WORLD_SIZE 8 -int world_map[WORLD_SIZE][WORLD_SIZE] = { - { 1, 1, 1, 1, 6, 1, 1, 1 }, - { 1, 0, 0, 1, 0, 0, 0, 7 }, - { 1, 1, 0, 1, 0, 1, 1, 1 }, - { 6, 0, 0, 0, 0, 0, 0, 3 }, - { 1, 8, 8, 0, 8, 0, 8, 1 }, - { 2, 2, 0, 0, 8, 8, 7, 1 }, - { 3, 0, 0, 0, 0, 0, 0, 5 }, - { 2, 2, 2, 2, 7, 4, 4, 4 }, -}; - -#define TEXTURE_SIZE 64 -#define TEXTURE_BLOCK (TEXTURE_SIZE * TEXTURE_SIZE) - -class Raycasting: public QWidget -{ -public: - Raycasting(QWidget *parent = 0) - : QWidget(parent) - , angle(0.5) - , playerPos(1.5, 1.5) - , angleDelta(0) - , moveDelta(0) - , touchDevice(false) { - - // http://www.areyep.com/RIPandMCS-TextureLibrary.html - textureImg.load(":/textures.png"); - textureImg = textureImg.convertToFormat(QImage::Format_ARGB32); - Q_ASSERT(textureImg.width() == TEXTURE_SIZE * 2); - Q_ASSERT(textureImg.bytesPerLine() == 4 * TEXTURE_SIZE * 2); - textureCount = textureImg.height() / TEXTURE_SIZE; - - watch.start(); - ticker.start(25, this); - setAttribute(Qt::WA_OpaquePaintEvent, true); - setMouseTracking(false); - } - - void updatePlayer() { - int interval = qBound(20, watch.elapsed(), 250); - watch.start(); - angle += angleDelta * interval / 1000; - qreal step = moveDelta * interval / 1000; - qreal dx = cos(angle) * step; - qreal dy = sin(angle) * step; - QPointF pos = playerPos + 3 * QPointF(dx, dy); - int xi = static_cast(pos.x()); - int yi = static_cast(pos.y()); - if (world_map[yi][xi] == 0) - playerPos = playerPos + QPointF(dx, dy); - } - - void showFps() { - static QTime frameTick; - static int totalFrame = 0; - if (!(totalFrame & 31)) { - int elapsed = frameTick.elapsed(); - frameTick.start(); - int fps = 32 * 1000 / (1 + elapsed); - setWindowTitle(QString("Raycasting (%1 FPS)").arg(fps)); - } - totalFrame++; - } - - void render() { - - // setup the screen surface - if (buffer.size() != bufferSize) - buffer = QImage(bufferSize, QImage::Format_ARGB32); - int bufw = buffer.width(); - int bufh = buffer.height(); - if (bufw <= 0 || bufh <= 0) - return; - - // we intentionally cheat here, to avoid detach - const uchar *ptr = buffer.bits(); - QRgb *start = (QRgb*)(ptr); - QRgb stride = buffer.bytesPerLine() / 4; - QRgb *finish = start + stride * bufh; - - // prepare the texture pointer - const uchar *src = textureImg.bits(); - const QRgb *texsrc = reinterpret_cast(src); - - // cast all rays here - qreal sina = sin(angle); - qreal cosa = cos(angle); - qreal u = cosa - sina; - qreal v = sina + cosa; - qreal du = 2 * sina / bufw; - qreal dv = -2 * cosa / bufw; - - for (int ray = 0; ray < bufw; ++ray, u += du, v += dv) { - // every time this ray advances 'u' units in x direction, - // it also advanced 'v' units in y direction - qreal uu = (u < 0) ? -u : u; - qreal vv = (v < 0) ? -v : v; - qreal duu = 1 / uu; - qreal dvv = 1 / vv; - int stepx = (u < 0) ? -1 : 1; - int stepy = (v < 0) ? -1 : 1; - - // the cell in the map that we need to check - qreal px = playerPos.x(); - qreal py = playerPos.y(); - int mapx = static_cast(px); - int mapy = static_cast(py); - - // the position and texture for the hit - int texture = 0; - qreal hitdist = 0.1; - qreal texofs = 0; - bool dark = false; - - // first hit at constant x and constant y lines - qreal distx = (u > 0) ? (mapx + 1 - px) * duu : (px - mapx) * duu; - qreal disty = (v > 0) ? (mapy + 1 - py) * dvv : (py - mapy) * dvv; - - // loop until we hit something - while (texture <= 0) { - if (distx > disty) { - // shorter distance to a hit in constant y line - hitdist = disty; - disty += dvv; - mapy += stepy; - texture = world_map[mapy][mapx]; - if (texture > 0) { - dark = true; - if (stepy > 0) { - qreal ofs = px + u * (mapy - py) / v; - texofs = ofs - floor(ofs); - } else { - qreal ofs = px + u * (mapy + 1 - py) / v; - texofs = ofs - floor(ofs); - } - } - } else { - // shorter distance to a hit in constant x line - hitdist = distx; - distx += duu; - mapx += stepx; - texture = world_map[mapy][mapx]; - if (texture > 0) { - if (stepx > 0) { - qreal ofs = py + v * (mapx - px) / u; - texofs = ofs - floor(ofs); - } else { - qreal ofs = py + v * (mapx + 1 - px) / u; - texofs = ceil(ofs) - ofs; - } - } - } - } - - // get the texture, note that the texture image - // has two textures horizontally, "normal" vs "dark" - int col = static_cast(texofs * TEXTURE_SIZE); - col = qBound(0, col, TEXTURE_SIZE - 1); - texture = (texture - 1) % textureCount; - const QRgb *tex = texsrc + TEXTURE_BLOCK * texture * 2 + - (TEXTURE_SIZE * 2 * col); - if (dark) - tex += TEXTURE_SIZE; - - // start from the texture center (horizontally) - int h = static_cast(bufw / hitdist / 2); - int dy = (TEXTURE_SIZE << 12) / h; - int p1 = ((TEXTURE_SIZE / 2) << 12) - dy; - int p2 = p1 + dy; - - // start from the screen center (vertically) - // y1 will go up (decrease), y2 will go down (increase) - int y1 = bufh / 2; - int y2 = y1 + 1; - QRgb *pixel1 = start + y1 * stride + ray; - QRgb *pixel2 = pixel1 + stride; - - // map the texture to the sliver - while (y1 >= 0 && y2 < bufh && p1 >= 0) { - *pixel1 = tex[p1 >> 12]; - *pixel2 = tex[p2 >> 12]; - p1 -= dy; - p2 += dy; - --y1; - ++y2; - pixel1 -= stride; - pixel2 += stride; - } - - // ceiling and floor - for (; pixel1 > start; pixel1 -= stride) - *pixel1 = qRgb(0, 0, 0); - for (; pixel2 < finish; pixel2 += stride) - *pixel2 = qRgb(96, 96, 96); - } - - update(QRect(QPoint(0, 0), bufferSize)); - } - -protected: - - void resizeEvent(QResizeEvent*) { -#if defined(Q_OS_WINCE_WM) - touchDevice = true; -#elif defined(Q_OS_SYMBIAN) - // FIXME: use HAL - if (width() > 480 || height() > 480) - touchDevice = true; -#else - touchDevice = false; -#endif - if (touchDevice) { - if (width() < height()) { - trackPad = QRect(0, height() / 2, width(), height() / 2); - centerPad = QPoint(width() / 2, height() * 3 / 4); - bufferSize = QSize(width(), height() / 2); - } else { - trackPad = QRect(width() / 2, 0, width() / 2, height()); - centerPad = QPoint(width() * 3 / 4, height() / 2); - bufferSize = QSize(width() / 2, height()); - } - } else { - trackPad = QRect(); - bufferSize = size(); - } - update(); - } - - void timerEvent(QTimerEvent*) { - updatePlayer(); - render(); - showFps(); - } - - void paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setCompositionMode(QPainter::CompositionMode_Source); - - p.drawImage(event->rect(), buffer, event->rect()); - - if (touchDevice && event->rect().intersects(trackPad)) { - p.fillRect(trackPad, Qt::white); - p.setPen(QPen(QColor(224, 224, 224), 6)); - int rad = qMin(trackPad.width(), trackPad.height()) * 0.3; - p.drawEllipse(centerPad, rad, rad); - - p.setPen(Qt::NoPen); - p.setBrush(Qt::gray); - - QPolygon poly; - poly << QPoint(-30, 0); - poly << QPoint(0, -40); - poly << QPoint(30, 0); - - p.translate(centerPad); - for (int i = 0; i < 4; ++i) { - p.rotate(90); - p.translate(0, 20 - rad); - p.drawPolygon(poly); - p.translate(0, rad - 20); - } - } - - p.end(); - } - - void keyPressEvent(QKeyEvent *event) { - event->accept(); - if (event->key() == Qt::Key_Left) - angleDelta = 1.3 * M_PI; - if (event->key() == Qt::Key_Right) - angleDelta = -1.3 * M_PI; - if (event->key() == Qt::Key_Up) - moveDelta = 2.5; - if (event->key() == Qt::Key_Down) - moveDelta = -2.5; - } - - void keyReleaseEvent(QKeyEvent *event) { - event->accept(); - if (event->key() == Qt::Key_Left) - angleDelta = (angleDelta > 0) ? 0 : angleDelta; - if (event->key() == Qt::Key_Right) - angleDelta = (angleDelta < 0) ? 0 : angleDelta; - if (event->key() == Qt::Key_Up) - moveDelta = (moveDelta > 0) ? 0 : moveDelta; - if (event->key() == Qt::Key_Down) - moveDelta = (moveDelta < 0) ? 0 : moveDelta; - } - - void mousePressEvent(QMouseEvent *event) { - qreal dx = centerPad.x() - event->pos().x(); - qreal dy = centerPad.y() - event->pos().y(); - angleDelta = dx * 2 * M_PI / width(); - moveDelta = dy * 10 / height(); - } - - void mouseMoveEvent(QMouseEvent *event) { - qreal dx = centerPad.x() - event->pos().x(); - qreal dy = centerPad.y() - event->pos().y(); - angleDelta = dx * 2 * M_PI / width(); - moveDelta = dy * 10 / height(); - } - - void mouseReleaseEvent(QMouseEvent*) { - angleDelta = 0; - moveDelta = 0; - } - -private: - QTime watch; - QBasicTimer ticker; - QImage buffer; - qreal angle; - QPointF playerPos; - qreal angleDelta; - qreal moveDelta; - QImage textureImg; - int textureCount; - bool touchDevice; - QRect trackPad; - QPoint centerPad; - QSize bufferSize; -}; - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - Raycasting w; - w.setWindowTitle("Raycasting"); -#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) - w.showMaximized(); -#else - w.resize(640, 480); - w.show(); -#endif - - return app.exec(); -} diff --git a/demos/embedded/raycasting/raycasting.pro b/demos/embedded/raycasting/raycasting.pro deleted file mode 100644 index a4bb1826b9..0000000000 --- a/demos/embedded/raycasting/raycasting.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = app -SOURCES = raycasting.cpp -RESOURCES += raycasting.qrc - -symbian { - TARGET.UID3 = 0xA000CF76 - CONFIG += qt_demo -} - -target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/raycasting -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/raycasting -INSTALLS += target sources diff --git a/demos/embedded/raycasting/raycasting.qrc b/demos/embedded/raycasting/raycasting.qrc deleted file mode 100644 index 974a06093c..0000000000 --- a/demos/embedded/raycasting/raycasting.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - textures.png - - diff --git a/demos/embedded/raycasting/textures.png b/demos/embedded/raycasting/textures.png deleted file mode 100644 index 2eb1ba7ff6..0000000000 Binary files a/demos/embedded/raycasting/textures.png and /dev/null differ diff --git a/demos/embedded/styledemo/files/add.png b/demos/embedded/styledemo/files/add.png deleted file mode 100755 index fc5c16d4c8..0000000000 Binary files a/demos/embedded/styledemo/files/add.png and /dev/null differ diff --git a/demos/embedded/styledemo/files/application.qss b/demos/embedded/styledemo/files/application.qss deleted file mode 100644 index 432fe6bc76..0000000000 --- a/demos/embedded/styledemo/files/application.qss +++ /dev/null @@ -1,125 +0,0 @@ -QWidget#StyleWidget -{ - background-color: none; - background-image: url(icons:nature_1.jpg); -} - -QLabel, QAbstractButton -{ - font: bold; - color: beige; -} - -QAbstractButton -{ - background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(173,216,230,60%), stop:1 rgba(0,0,139,60%) ); - border-color: black; - border-style: solid; - border-width: 3px; - border-radius: 6px; -} - -QAbstractButton:pressed, QAbstractButton:checked -{ - background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0,0,139,60%), stop:1 rgba(173,216,230,60%) ); -} - -QSpinBox { - padding-left: 24px; - padding-right: 24px; - border-color: darkkhaki; - border-style: solid; - border-radius: 5; - border-width: 3; -} - -QSpinBox::up-button -{ - subcontrol-origin: padding; - subcontrol-position: right; /* position at the top right corner */ - width: 24px; - height: 24px; - border-width: 3px; - -} - -QSpinBox::up-arrow -{ - image: url(icons:add.png); - width: 18px; - height: 18px; -} - - -QSpinBox::down-button -{ - subcontrol-origin: border; - subcontrol-position: left; - width: 24px; - height: 24px; - border-width: 3px; -} - -QSpinBox::down-arrow -{ - image: url(icons:remove.png); - width: 18px; - height: 18px; -} - - -QScrollBar:horizontal -{ - border: 1px solid black; - background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0,0,139,60%), stop:1 rgba(173,216,230,60%) ); - height: 15px; - margin: 0px 20px 0 20px; -} - -QScrollBar::handle:horizontal -{ - border: 1px solid black; - background: rgba(0,0,139,60%); - min-width: 20px; -} - -QScrollBar::add-line:horizontal -{ - border: 1px solid black; - background: rgba(0,0,139,60%); - width: 20px; - subcontrol-position: right; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:horizontal -{ - border: 1px solid black; - background: rgba(0,0,139,60%); - width: 20px; - subcontrol-position: left; - subcontrol-origin: margin; -} - -QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal -{ - border: none; - width: 16px; - height: 16px; -} - -QScrollBar:left-arrow:horizontal -{ - image: url(icons:add.png) -} - -QScrollBar::right-arrow:horizontal -{ - image: url(icons:remove.png) -} - -QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal -{ - background: none; -} - diff --git a/demos/embedded/styledemo/files/blue.qss b/demos/embedded/styledemo/files/blue.qss deleted file mode 100644 index ac8671b5e4..0000000000 --- a/demos/embedded/styledemo/files/blue.qss +++ /dev/null @@ -1,38 +0,0 @@ -* -{ - color: beige; -} - -QLabel, QAbstractButton -{ - font: bold; - color: yellow; -} - -QFrame -{ - background-color: rgba(96,96,255,60%); - border-color: rgb(32,32,196); - border-width: 3px; - border-style: solid; - border-radius: 5; - padding: 3px; -} - -QAbstractButton -{ - background: qlineargradient(x1:0, y1:0, x2:0, y2:1, - stop:0 lightblue, stop:0.5 darkblue); - border-width: 3px; - border-color: darkblue; - border-style: solid; - border-radius: 5; - padding: 3px; -} - -QAbstractButton:pressed -{ - background: qlineargradient(x1:0, y1:0, x2:0, y2:1, - stop:0.5 darkblue, stop:1 lightblue); - border-color: beige; -} diff --git a/demos/embedded/styledemo/files/khaki.qss b/demos/embedded/styledemo/files/khaki.qss deleted file mode 100644 index b0d4a0fa6f..0000000000 --- a/demos/embedded/styledemo/files/khaki.qss +++ /dev/null @@ -1,99 +0,0 @@ - -QWidget#StartScreen, QWidget#MainWidget { - border: none; -} - -QWidget#StartScreen, .QFrame { - background-color: beige; -} - -QPushButton, QToolButton { - background-color: palegoldenrod; - border-width: 2px; - border-color: darkkhaki; - border-style: solid; - border-radius: 5; - padding: 3px; - /* min-width: 96px; */ - /* min-height: 48px; */ -} - -QPushButton:hover, QToolButton:hover { - background-color: khaki; -} - -QPushButton:pressed, QToolButton:pressed { - padding-left: 5px; - padding-top: 5px; - background-color: #d0d67c; -} - -QLabel, QAbstractButton { - font: italic "Times New Roman"; -} - -QFrame, QLabel#title { - border-width: 2px; - padding: 1px; - border-style: solid; - border-color: darkkhaki; - border-radius: 5px; -} - -QFrame:focus { - border-width: 3px; - padding: 0px; -} - - -QLabel { - border: none; - padding: 0; - background: none; -} - -QLabel#title { - font: 32px bold; -} - -QSpinBox { - padding-left: 24px; - padding-right: 24px; - border-color: darkkhaki; - border-style: solid; - border-radius: 5; - border-width: 3; -} - -QSpinBox::up-button -{ - subcontrol-origin: padding; - subcontrol-position: right; /* position at the top right corner */ - width: 24px; - height: 24px; - border-width: 3px; - border-image: url(:/files/spindownpng) 1; -} - -QSpinBox::up-arrow { - image: url(:/files/add.png); - width: 12px; - height: 12px; - } - - -QSpinBox::down-button -{ - subcontrol-origin: border; - subcontrol-position: left; - width: 24px; - height: 24px; - border-width: 3px; - border-image: url(:/files/spindownpng) 1; -} - -QSpinBox::down-arrow { - image: url(:/files/remove.png); - width: 12px; - height: 12px; - } diff --git a/demos/embedded/styledemo/files/nature_1.jpg b/demos/embedded/styledemo/files/nature_1.jpg deleted file mode 100644 index 3a04edb96a..0000000000 Binary files a/demos/embedded/styledemo/files/nature_1.jpg and /dev/null differ diff --git a/demos/embedded/styledemo/files/nostyle.qss b/demos/embedded/styledemo/files/nostyle.qss deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/demos/embedded/styledemo/files/remove.png b/demos/embedded/styledemo/files/remove.png deleted file mode 100755 index a0ab1fa21a..0000000000 Binary files a/demos/embedded/styledemo/files/remove.png and /dev/null differ diff --git a/demos/embedded/styledemo/files/transparent.qss b/demos/embedded/styledemo/files/transparent.qss deleted file mode 100644 index b38eb366f4..0000000000 --- a/demos/embedded/styledemo/files/transparent.qss +++ /dev/null @@ -1,139 +0,0 @@ -QWidget#StyleWidget -{ - background-color: none; - background-image: url(:/files/nature_1.jpg); -} - -QLabel, QAbstractButton -{ - color: beige; -} - -QFrame, QLabel#title { - border-width: 2px; - padding: 1px; - border-style: solid; - border-color: black; - border-radius: 5px; -} - -QFrame:focus { - border-width: 3px; - padding: 0px; -} - - - -QAbstractButton -{ - background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(173,216,230,60%), stop:1 rgba(0,0,139,60%) ); - border-color: black; - border-style: solid; - border-width: 3px; - border-radius: 6px; -} - -QAbstractButton:pressed, QAbstractButton:checked -{ - background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0,0,139,60%), stop:1 rgba(173,216,230,60%) ); -} - -QSpinBox { - padding-left: 24px; - padding-right: 24px; - border-color: darkkhaki; - border-style: solid; - border-radius: 5; - border-width: 3; -} - -QSpinBox::up-button -{ - subcontrol-origin: padding; - subcontrol-position: right; /* position at the top right corner */ - width: 24px; - height: 24px; - border-width: 3px; - -} - -QSpinBox::up-arrow -{ - image: url(:/files/add.png); - width: 18px; - height: 18px; -} - - -QSpinBox::down-button -{ - subcontrol-origin: border; - subcontrol-position: left; - width: 24px; - height: 24px; - border-width: 3px; -} - -QSpinBox::down-arrow -{ - image: url(:/files/remove.png); - width: 18px; - height: 18px; -} - - -QScrollBar:horizontal -{ - border: 1px solid black; - background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0,0,139,60%), stop:1 rgba(173,216,230,60%) ); - height: 15px; - margin: 0px 20px 0 20px; -} - -QScrollBar::handle:horizontal -{ - border: 1px solid black; - background: rgba(0,0,139,60%); - min-width: 20px; -} - -QScrollBar::add-line:horizontal -{ - border: 1px solid black; - background: rgba(0,0,139,60%); - width: 20px; - subcontrol-position: right; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:horizontal -{ - border: 1px solid black; - background: rgba(0,0,139,60%); - width: 20px; - subcontrol-position: left; - subcontrol-origin: margin; -} - -QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal -{ - border: none; - width: 16px; - height: 16px; -} - -QScrollBar:left-arrow:horizontal -{ - image: url(:/files/add.png) -} - -QScrollBar::right-arrow:horizontal -{ - image: url(:/files/remove.png) -} - -QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal -{ - background: none; -} - diff --git a/demos/embedded/styledemo/main.cpp b/demos/embedded/styledemo/main.cpp deleted file mode 100644 index 7a484b0365..0000000000 --- a/demos/embedded/styledemo/main.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#include - -#include "stylewidget.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - Q_INIT_RESOURCE(styledemo); - - app.setApplicationName("style"); - app.setOrganizationName("Nokia"); - app.setOrganizationDomain("com.nokia.qt"); - - StyleWidget widget; - widget.showFullScreen(); - - return app.exec(); -} - diff --git a/demos/embedded/styledemo/styledemo.pro b/demos/embedded/styledemo/styledemo.pro deleted file mode 100644 index 60700dd1df..0000000000 --- a/demos/embedded/styledemo/styledemo.pro +++ /dev/null @@ -1,17 +0,0 @@ -TEMPLATE = app - -# Input -HEADERS += stylewidget.h -FORMS += stylewidget.ui -SOURCES += main.cpp stylewidget.cpp -RESOURCES += styledemo.qrc - -target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/styledemo -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro *.html -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/styledemo -INSTALLS += target sources - -symbian { - TARGET.UID3 = 0xA000A63F - CONFIG += qt_demo -} diff --git a/demos/embedded/styledemo/styledemo.qrc b/demos/embedded/styledemo/styledemo.qrc deleted file mode 100644 index 96237d4203..0000000000 --- a/demos/embedded/styledemo/styledemo.qrc +++ /dev/null @@ -1,13 +0,0 @@ - - - files/add.png - files/blue.qss - files/khaki.qss - files/nostyle.qss - files/transparent.qss - files/application.qss - files/nature_1.jpg - files/remove.png - - - diff --git a/demos/embedded/styledemo/stylewidget.cpp b/demos/embedded/styledemo/stylewidget.cpp deleted file mode 100644 index 7bac8a84d7..0000000000 --- a/demos/embedded/styledemo/stylewidget.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#include -#include -#include - -#include "stylewidget.h" - - - -StyleWidget::StyleWidget(QWidget *parent) - : QFrame(parent) -{ - m_ui.setupUi(this); -} - - -void StyleWidget::on_close_clicked() -{ - close(); -} - -void StyleWidget::on_blueStyle_clicked() -{ - QFile styleSheet(":/files/blue.qss"); - - if (!styleSheet.open(QIODevice::ReadOnly)) { - qWarning("Unable to open :/files/blue.qss"); - return; - } - - qApp->setStyleSheet(styleSheet.readAll()); -} - -void StyleWidget::on_khakiStyle_clicked() -{ - QFile styleSheet(":/files/khaki.qss"); - - if (!styleSheet.open(QIODevice::ReadOnly)) { - qWarning("Unable to open :/files/khaki.qss"); - return; - } - - qApp->setStyleSheet(styleSheet.readAll()); -} - - -void StyleWidget::on_noStyle_clicked() -{ - QFile styleSheet(":/files/nostyle.qss"); - - if (!styleSheet.open(QIODevice::ReadOnly)) { - qWarning("Unable to open :/files/nostyle.qss"); - return; - } - - qApp->setStyleSheet(styleSheet.readAll()); -} - - -void StyleWidget::on_transparentStyle_clicked() -{ - QFile styleSheet(":/files/transparent.qss"); - - if (!styleSheet.open(QIODevice::ReadOnly)) { - qWarning("Unable to open :/files/transparent.qss"); - return; - } - - qApp->setStyleSheet(styleSheet.readAll()); -} - - - diff --git a/demos/embedded/styledemo/stylewidget.h b/demos/embedded/styledemo/stylewidget.h deleted file mode 100644 index 11fa5348de..0000000000 --- a/demos/embedded/styledemo/stylewidget.h +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#ifndef STYLEWIDGET_H -#define STYLEWIDGET_H - -#include - -#include "ui_stylewidget.h" - -class StyleWidget : public QFrame -{ - Q_OBJECT -public: - StyleWidget(QWidget *parent = 0); - -private: - Ui_StyleWidget m_ui; - -private slots: - void on_close_clicked(); - void on_blueStyle_clicked(); - void on_khakiStyle_clicked(); - void on_noStyle_clicked(); - void on_transparentStyle_clicked(); -}; - -#endif diff --git a/demos/embedded/styledemo/stylewidget.ui b/demos/embedded/styledemo/stylewidget.ui deleted file mode 100644 index 767f44aead..0000000000 --- a/demos/embedded/styledemo/stylewidget.ui +++ /dev/null @@ -1,417 +0,0 @@ - - - StyleWidget - - - - 0 - 0 - 184 - 245 - - - - Form - - - - - - Styles - - - - 4 - - - 4 - - - - - - 0 - 0 - - - - Qt::StrongFocus - - - Transp. - - - true - - - false - - - true - - - - - - - - 0 - 0 - - - - Qt::StrongFocus - - - Blue - - - true - - - false - - - true - - - - - - - - 0 - 0 - - - - Qt::StrongFocus - - - Khaki - - - true - - - false - - - true - - - - - - - - 0 - 0 - - - - Qt::StrongFocus - - - None - - - true - - - true - - - true - - - - - - - - - - Qt::Vertical - - - - 0 - 0 - - - - - - - - 4 - - - - - - 0 - 0 - - - - Value: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::WheelFocus - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - false - - - - - - - - - - 0 - 0 - - - - - 0 - 24 - - - - Qt::TabFocus - - - Qt::Horizontal - - - - - - - - 0 - 0 - - - - - 0 - 24 - - - - Qt::TabFocus - - - Qt::Horizontal - - - - - - - - 0 - 0 - - - - Qt::StrongFocus - - - Show - - - true - - - true - - - false - - - - - - - - 0 - 0 - - - - Qt::StrongFocus - - - Enable - - - true - - - true - - - false - - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 0 - 0 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::StrongFocus - - - Close - - - - - - - - - - - horizontalScrollBar - valueChanged(int) - horizontalScrollBar_2 - setValue(int) - - - 84 - 147 - - - 166 - 147 - - - - - horizontalScrollBar_2 - valueChanged(int) - horizontalScrollBar - setValue(int) - - - 166 - 147 - - - 84 - 147 - - - - - pushButton - clicked(bool) - horizontalScrollBar_2 - setEnabled(bool) - - - 166 - 175 - - - 166 - 147 - - - - - pushButton_2 - clicked(bool) - horizontalScrollBar - setVisible(bool) - - - 84 - 175 - - - 84 - 147 - - - - - spinBox - valueChanged(int) - horizontalScrollBar_2 - setValue(int) - - - 166 - 115 - - - 166 - 147 - - - - - horizontalScrollBar_2 - valueChanged(int) - spinBox - setValue(int) - - - 132 - 132 - - - 135 - 110 - - - - - diff --git a/demos/embeddeddialogs/No-Ones-Laughing-3.jpg b/demos/embeddeddialogs/No-Ones-Laughing-3.jpg deleted file mode 100644 index 445567fbda..0000000000 Binary files a/demos/embeddeddialogs/No-Ones-Laughing-3.jpg and /dev/null differ diff --git a/demos/embeddeddialogs/customproxy.cpp b/demos/embeddeddialogs/customproxy.cpp deleted file mode 100644 index cbc622a34f..0000000000 --- a/demos/embeddeddialogs/customproxy.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "customproxy.h" - -#include - -CustomProxy::CustomProxy(QGraphicsItem *parent, Qt::WindowFlags wFlags) - : QGraphicsProxyWidget(parent, wFlags), popupShown(false), currentPopup(0) -{ - timeLine = new QTimeLine(250, this); - connect(timeLine, SIGNAL(valueChanged(qreal)), - this, SLOT(updateStep(qreal))); - connect(timeLine, SIGNAL(stateChanged(QTimeLine::State)), - this, SLOT(stateChanged(QTimeLine::State))); -} - -QRectF CustomProxy::boundingRect() const -{ - return QGraphicsProxyWidget::boundingRect().adjusted(0, 0, 10, 10); -} - -void CustomProxy::paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, - QWidget *widget) -{ - const QColor color(0, 0, 0, 64); - - QRectF r = windowFrameRect(); - QRectF right(r.right(), r.top() + 10, 10, r.height() - 10); - QRectF bottom(r.left() + 10, r.bottom(), r.width(), 10); - bool intersectsRight = right.intersects(option->exposedRect); - bool intersectsBottom = bottom.intersects(option->exposedRect); - if (intersectsRight && intersectsBottom) { - QPainterPath path; - path.addRect(right); - path.addRect(bottom); - painter->setPen(Qt::NoPen); - painter->setBrush(color); - painter->drawPath(path); - } else if (intersectsBottom) { - painter->fillRect(bottom, color); - } else if (intersectsRight) { - painter->fillRect(right, color); - } - - QGraphicsProxyWidget::paintWindowFrame(painter, option, widget); -} - -void CustomProxy::hoverEnterEvent(QGraphicsSceneHoverEvent *event) -{ - QGraphicsProxyWidget::hoverEnterEvent(event); - scene()->setActiveWindow(this); - if (timeLine->currentValue() != 1) - zoomIn(); -} - -void CustomProxy::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) -{ - QGraphicsProxyWidget::hoverLeaveEvent(event); - if (!popupShown && (timeLine->direction() != QTimeLine::Backward || timeLine->currentValue() != 0)) - zoomOut(); -} - -bool CustomProxy::sceneEventFilter(QGraphicsItem *watched, QEvent *event) -{ - if (watched->isWindow() && (event->type() == QEvent::UngrabMouse || event->type() == QEvent::GrabMouse)) { - popupShown = watched->isVisible(); - if (!popupShown && !isUnderMouse()) - zoomOut(); - } - return QGraphicsProxyWidget::sceneEventFilter(watched, event); -} - -QVariant CustomProxy::itemChange(GraphicsItemChange change, const QVariant &value) -{ - if (change == ItemChildAddedChange || change == ItemChildRemovedChange) { - if (change == ItemChildAddedChange) { - currentPopup = qvariant_cast(value); - currentPopup->setCacheMode(ItemCoordinateCache); - if (scene()) - currentPopup->installSceneEventFilter(this); - } else if (scene()) { - currentPopup->removeSceneEventFilter(this); - currentPopup = 0; - } - } else if (currentPopup && change == ItemSceneHasChanged) { - currentPopup->installSceneEventFilter(this); - } - return QGraphicsProxyWidget::itemChange(change, value); -} - -void CustomProxy::updateStep(qreal step) -{ - QRectF r = boundingRect(); - setTransform(QTransform() - .translate(r.width() / 2, r.height() / 2) - .rotate(step * 30, Qt::XAxis) - .rotate(step * 10, Qt::YAxis) - .rotate(step * 5, Qt::ZAxis) - .scale(1 + 1.5 * step, 1 + 1.5 * step) - .translate(-r.width() / 2, -r.height() / 2)); -} - -void CustomProxy::stateChanged(QTimeLine::State state) -{ - if (state == QTimeLine::Running) { - if (timeLine->direction() == QTimeLine::Forward) - setCacheMode(ItemCoordinateCache); - } else if (state == QTimeLine::NotRunning) { - if (timeLine->direction() == QTimeLine::Backward) - setCacheMode(DeviceCoordinateCache); - } -} - -void CustomProxy::zoomIn() -{ - if (timeLine->direction() != QTimeLine::Forward) - timeLine->setDirection(QTimeLine::Forward); - if (timeLine->state() == QTimeLine::NotRunning) - timeLine->start(); -} - -void CustomProxy::zoomOut() -{ - if (timeLine->direction() != QTimeLine::Backward) - timeLine->setDirection(QTimeLine::Backward); - if (timeLine->state() == QTimeLine::NotRunning) - timeLine->start(); -} diff --git a/demos/embeddeddialogs/customproxy.h b/demos/embeddeddialogs/customproxy.h deleted file mode 100644 index 1ceaa06bb3..0000000000 --- a/demos/embeddeddialogs/customproxy.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef CUSTOMPROXY_H -#define CUSTOMPROXY_H - -#include -#include - -class CustomProxy : public QGraphicsProxyWidget -{ - Q_OBJECT -public: - CustomProxy(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); - - QRectF boundingRect() const; - void paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, - QWidget *widget); - -protected: - void hoverEnterEvent(QGraphicsSceneHoverEvent *event); - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); - bool sceneEventFilter(QGraphicsItem *watched, QEvent *event); - QVariant itemChange(GraphicsItemChange change, const QVariant &value); - -private slots: - void updateStep(qreal step); - void stateChanged(QTimeLine::State); - void zoomIn(); - void zoomOut(); - -private: - QTimeLine *timeLine; - bool popupShown; - QGraphicsItem *currentPopup; -}; - -#endif diff --git a/demos/embeddeddialogs/embeddeddialog.cpp b/demos/embeddeddialogs/embeddeddialog.cpp deleted file mode 100644 index f932307925..0000000000 --- a/demos/embeddeddialogs/embeddeddialog.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "embeddeddialog.h" -#include "ui_embeddeddialog.h" - -#include - -EmbeddedDialog::EmbeddedDialog(QWidget *parent) - : QDialog(parent) -{ - ui = new Ui_embeddedDialog; - ui->setupUi(this); - ui->layoutDirection->setCurrentIndex(layoutDirection() != Qt::LeftToRight); - - foreach (QString styleName, QStyleFactory::keys()) { - ui->style->addItem(styleName); - if (style()->objectName().toLower() == styleName.toLower()) - ui->style->setCurrentIndex(ui->style->count() - 1); - } - - connect(ui->layoutDirection, SIGNAL(activated(int)), - this, SLOT(layoutDirectionChanged(int))); - connect(ui->spacing, SIGNAL(valueChanged(int)), - this, SLOT(spacingChanged(int))); - connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), - this, SLOT(fontChanged(QFont))); - connect(ui->style, SIGNAL(activated(QString)), - this, SLOT(styleChanged(QString))); -} - -EmbeddedDialog::~EmbeddedDialog() -{ - delete ui; -} - -void EmbeddedDialog::layoutDirectionChanged(int index) -{ - setLayoutDirection(index == 0 ? Qt::LeftToRight : Qt::RightToLeft); -} - -void EmbeddedDialog::spacingChanged(int spacing) -{ - layout()->setSpacing(spacing); - adjustSize(); -} - -void EmbeddedDialog::fontChanged(const QFont &font) -{ - setFont(font); -} - -static void setStyleHelper(QWidget *widget, QStyle *style) -{ - widget->setStyle(style); - widget->setPalette(style->standardPalette()); - foreach (QObject *child, widget->children()) { - if (QWidget *childWidget = qobject_cast(child)) - setStyleHelper(childWidget, style); - } -} - -void EmbeddedDialog::styleChanged(const QString &styleName) -{ - QStyle *style = QStyleFactory::create(styleName); - if (style) - setStyleHelper(this, style); -} diff --git a/demos/embeddeddialogs/embeddeddialog.h b/demos/embeddeddialogs/embeddeddialog.h deleted file mode 100644 index b7f8da085e..0000000000 --- a/demos/embeddeddialogs/embeddeddialog.h +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef EMBEDDEDDIALOG_H -#define EMBEDDEDDIALOG_H - -#include - -QT_FORWARD_DECLARE_CLASS(Ui_embeddedDialog); - -class EmbeddedDialog : public QDialog -{ - Q_OBJECT -public: - EmbeddedDialog(QWidget *parent = 0); - ~EmbeddedDialog(); - -private slots: - void layoutDirectionChanged(int index); - void spacingChanged(int spacing); - void fontChanged(const QFont &font); - void styleChanged(const QString &styleName); - -private: - Ui_embeddedDialog *ui; -}; - -#endif diff --git a/demos/embeddeddialogs/embeddeddialog.ui b/demos/embeddeddialogs/embeddeddialog.ui deleted file mode 100644 index f967b10085..0000000000 --- a/demos/embeddeddialogs/embeddeddialog.ui +++ /dev/null @@ -1,87 +0,0 @@ - - embeddedDialog - - - - 0 - 0 - 407 - 134 - - - - Embedded Dialog - - - - - - Layout Direction: - - - layoutDirection - - - - - - - - Left to Right - - - - - Right to Left - - - - - - - - Select Font: - - - fontComboBox - - - - - - - - - - Style: - - - style - - - - - - - - - - Layout spacing: - - - spacing - - - - - - - Qt::Horizontal - - - - - - - - diff --git a/demos/embeddeddialogs/embeddeddialogs.pro b/demos/embeddeddialogs/embeddeddialogs.pro deleted file mode 100644 index 675a9889a2..0000000000 --- a/demos/embeddeddialogs/embeddeddialogs.pro +++ /dev/null @@ -1,19 +0,0 @@ -SOURCES += main.cpp -SOURCES += customproxy.cpp embeddeddialog.cpp -HEADERS += customproxy.h embeddeddialog.h - -FORMS += embeddeddialog.ui -RESOURCES += embeddeddialogs.qrc - -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/embeddeddialogs -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.png *.jpg *.plist *.icns *.ico *.rc *.pro *.html *.doc images -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embeddeddialogs -INSTALLS += target sources - -symbian: CONFIG += qt_demo diff --git a/demos/embeddeddialogs/embeddeddialogs.qrc b/demos/embeddeddialogs/embeddeddialogs.qrc deleted file mode 100644 index 33be5038da..0000000000 --- a/demos/embeddeddialogs/embeddeddialogs.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - No-Ones-Laughing-3.jpg - - diff --git a/demos/embeddeddialogs/main.cpp b/demos/embeddeddialogs/main.cpp deleted file mode 100644 index bca81b8c79..0000000000 --- a/demos/embeddeddialogs/main.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "customproxy.h" -#include "embeddeddialog.h" - -#include - -int main(int argc, char *argv[]) -{ - Q_INIT_RESOURCE(embeddeddialogs); - QApplication app(argc, argv); - - QGraphicsScene scene; - scene.setStickyFocus(true); -#ifndef Q_OS_WINCE - const int gridSize = 10; -#else - const int gridSize = 5; -#endif - - for (int y = 0; y < gridSize; ++y) { - for (int x = 0; x < gridSize; ++x) { - CustomProxy *proxy = new CustomProxy(0, Qt::Window); - proxy->setWidget(new EmbeddedDialog); - - QRectF rect = proxy->boundingRect(); - - proxy->setPos(x * rect.width() * 1.05, y * rect.height() * 1.05); - proxy->setCacheMode(QGraphicsItem::DeviceCoordinateCache); - - scene.addItem(proxy); - } - } - scene.setSceneRect(scene.itemsBoundingRect()); - - QGraphicsView view(&scene); - view.scale(0.5, 0.5); - view.setRenderHints(view.renderHints() | QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - view.setBackgroundBrush(QPixmap(":/No-Ones-Laughing-3.jpg")); - view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); - view.show(); - view.setWindowTitle("Embedded Dialogs Demo"); - return app.exec(); -} diff --git a/demos/gradients/gradients.cpp b/demos/gradients/gradients.cpp deleted file mode 100644 index d8b739b3b0..0000000000 --- a/demos/gradients/gradients.cpp +++ /dev/null @@ -1,516 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "gradients.h" -#include "hoverpoints.h" - -ShadeWidget::ShadeWidget(ShadeType type, QWidget *parent) - : QWidget(parent), m_shade_type(type), m_alpha_gradient(QLinearGradient(0, 0, 0, 0)) -{ - - // Checkers background - if (m_shade_type == ARGBShade) { - QPixmap pm(20, 20); - QPainter pmp(&pm); - pmp.fillRect(0, 0, 10, 10, Qt::lightGray); - pmp.fillRect(10, 10, 10, 10, Qt::lightGray); - pmp.fillRect(0, 10, 10, 10, Qt::darkGray); - pmp.fillRect(10, 0, 10, 10, Qt::darkGray); - pmp.end(); - QPalette pal = palette(); - pal.setBrush(backgroundRole(), QBrush(pm)); - setAutoFillBackground(true); - setPalette(pal); - - } else { - setAttribute(Qt::WA_NoBackground); - - } - - QPolygonF points; - points << QPointF(0, sizeHint().height()) - << QPointF(sizeHint().width(), 0); - - m_hoverPoints = new HoverPoints(this, HoverPoints::CircleShape); -// m_hoverPoints->setConnectionType(HoverPoints::LineConnection); - m_hoverPoints->setPoints(points); - m_hoverPoints->setPointLock(0, HoverPoints::LockToLeft); - m_hoverPoints->setPointLock(1, HoverPoints::LockToRight); - m_hoverPoints->setSortType(HoverPoints::XSort); - - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - - connect(m_hoverPoints, SIGNAL(pointsChanged(QPolygonF)), this, SIGNAL(colorsChanged())); -} - - -QPolygonF ShadeWidget::points() const -{ - return m_hoverPoints->points(); -} - - -uint ShadeWidget::colorAt(int x) -{ - generateShade(); - - QPolygonF pts = m_hoverPoints->points(); - for (int i=1; i < pts.size(); ++i) { - if (pts.at(i-1).x() <= x && pts.at(i).x() >= x) { - QLineF l(pts.at(i-1), pts.at(i)); - l.setLength(l.length() * ((x - l.x1()) / l.dx())); - return m_shade.pixel(qRound(qMin(l.x2(), (qreal(m_shade.width() - 1)))), - qRound(qMin(l.y2(), qreal(m_shade.height() - 1)))); - } - } - return 0; -} - - -void ShadeWidget::setGradientStops(const QGradientStops &stops) -{ - if (m_shade_type == ARGBShade) { - m_alpha_gradient = QLinearGradient(0, 0, width(), 0); - - for (int i=0; isetSpacing(1); - vbox->setMargin(1); - - m_red_shade = new ShadeWidget(ShadeWidget::RedShade, this); - m_green_shade = new ShadeWidget(ShadeWidget::GreenShade, this); - m_blue_shade = new ShadeWidget(ShadeWidget::BlueShade, this); - m_alpha_shade = new ShadeWidget(ShadeWidget::ARGBShade, this); - - vbox->addWidget(m_red_shade); - vbox->addWidget(m_green_shade); - vbox->addWidget(m_blue_shade); - vbox->addWidget(m_alpha_shade); - - connect(m_red_shade, SIGNAL(colorsChanged()), this, SLOT(pointsUpdated())); - connect(m_green_shade, SIGNAL(colorsChanged()), this, SLOT(pointsUpdated())); - connect(m_blue_shade, SIGNAL(colorsChanged()), this, SLOT(pointsUpdated())); - connect(m_alpha_shade, SIGNAL(colorsChanged()), this, SLOT(pointsUpdated())); -} - - -inline static bool x_less_than(const QPointF &p1, const QPointF &p2) -{ - return p1.x() < p2.x(); -} - - -void GradientEditor::pointsUpdated() -{ - qreal w = m_alpha_shade->width(); - - QGradientStops stops; - - QPolygonF points; - - points += m_red_shade->points(); - points += m_green_shade->points(); - points += m_blue_shade->points(); - points += m_alpha_shade->points(); - - qSort(points.begin(), points.end(), x_less_than); - - for (int i=0; icolorAt(int(x))) >> 16, - (0x0000ff00 & m_green_shade->colorAt(int(x))) >> 8, - (0x000000ff & m_blue_shade->colorAt(int(x))), - (0xff000000 & m_alpha_shade->colorAt(int(x))) >> 24); - - if (x / w > 1) - return; - - stops << QGradientStop(x / w, color); - } - - m_alpha_shade->setGradientStops(stops); - - emit gradientStopsChanged(stops); -} - - -static void set_shade_points(const QPolygonF &points, ShadeWidget *shade) -{ - shade->hoverPoints()->setPoints(points); - shade->hoverPoints()->setPointLock(0, HoverPoints::LockToLeft); - shade->hoverPoints()->setPointLock(points.size() - 1, HoverPoints::LockToRight); - shade->update(); -} - -void GradientEditor::setGradientStops(const QGradientStops &stops) -{ - QPolygonF pts_red, pts_green, pts_blue, pts_alpha; - - qreal h_red = m_red_shade->height(); - qreal h_green = m_green_shade->height(); - qreal h_blue = m_blue_shade->height(); - qreal h_alpha = m_alpha_shade->height(); - - for (int i=0; iwidth(), h_red - qRed(color) * h_red / 255); - pts_green << QPointF(pos * m_green_shade->width(), h_green - qGreen(color) * h_green / 255); - pts_blue << QPointF(pos * m_blue_shade->width(), h_blue - qBlue(color) * h_blue / 255); - pts_alpha << QPointF(pos * m_alpha_shade->width(), h_alpha - qAlpha(color) * h_alpha / 255); - } - - set_shade_points(pts_red, m_red_shade); - set_shade_points(pts_green, m_green_shade); - set_shade_points(pts_blue, m_blue_shade); - set_shade_points(pts_alpha, m_alpha_shade); - -} - -GradientWidget::GradientWidget(QWidget *parent) - : QWidget(parent) -{ - setWindowTitle(tr("Gradients")); - - m_renderer = new GradientRenderer(this); - - QGroupBox *mainGroup = new QGroupBox(this); - mainGroup->setTitle(tr("Gradients")); - - QGroupBox *editorGroup = new QGroupBox(mainGroup); - editorGroup->setTitle(tr("Color Editor")); - m_editor = new GradientEditor(editorGroup); - - QGroupBox *typeGroup = new QGroupBox(mainGroup); - typeGroup->setTitle(tr("Gradient Type")); - m_linearButton = new QRadioButton(tr("Linear Gradient"), typeGroup); - m_radialButton = new QRadioButton(tr("Radial Gradient"), typeGroup); - m_conicalButton = new QRadioButton(tr("Conical Gradient"), typeGroup); - - QGroupBox *spreadGroup = new QGroupBox(mainGroup); - spreadGroup->setTitle(tr("Spread Method")); - m_padSpreadButton = new QRadioButton(tr("Pad Spread"), spreadGroup); - m_reflectSpreadButton = new QRadioButton(tr("Reflect Spread"), spreadGroup); - m_repeatSpreadButton = new QRadioButton(tr("Repeat Spread"), spreadGroup); - - QGroupBox *defaultsGroup = new QGroupBox(mainGroup); - defaultsGroup->setTitle(tr("Defaults")); - QPushButton *default1Button = new QPushButton(tr("1"), defaultsGroup); - QPushButton *default2Button = new QPushButton(tr("2"), defaultsGroup); - QPushButton *default3Button = new QPushButton(tr("3"), defaultsGroup); - QPushButton *default4Button = new QPushButton(tr("Reset"), editorGroup); - - QPushButton *showSourceButton = new QPushButton(mainGroup); - showSourceButton->setText(tr("Show Source")); -#ifdef QT_OPENGL_SUPPORT - QPushButton *enableOpenGLButton = new QPushButton(mainGroup); - enableOpenGLButton->setText(tr("Use OpenGL")); - enableOpenGLButton->setCheckable(true); - enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); -#endif - QPushButton *whatsThisButton = new QPushButton(mainGroup); - whatsThisButton->setText(tr("What's This?")); - whatsThisButton->setCheckable(true); - - // Layouts - QHBoxLayout *mainLayout = new QHBoxLayout(this); - mainLayout->addWidget(m_renderer); - mainLayout->addWidget(mainGroup); - - mainGroup->setFixedWidth(180); - QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); - mainGroupLayout->addWidget(editorGroup); - mainGroupLayout->addWidget(typeGroup); - mainGroupLayout->addWidget(spreadGroup); - mainGroupLayout->addWidget(defaultsGroup); - mainGroupLayout->addStretch(1); - mainGroupLayout->addWidget(showSourceButton); -#ifdef QT_OPENGL_SUPPORT - mainGroupLayout->addWidget(enableOpenGLButton); -#endif - mainGroupLayout->addWidget(whatsThisButton); - - QVBoxLayout *editorGroupLayout = new QVBoxLayout(editorGroup); - editorGroupLayout->addWidget(m_editor); - - QVBoxLayout *typeGroupLayout = new QVBoxLayout(typeGroup); - typeGroupLayout->addWidget(m_linearButton); - typeGroupLayout->addWidget(m_radialButton); - typeGroupLayout->addWidget(m_conicalButton); - - QVBoxLayout *spreadGroupLayout = new QVBoxLayout(spreadGroup); - spreadGroupLayout->addWidget(m_padSpreadButton); - spreadGroupLayout->addWidget(m_repeatSpreadButton); - spreadGroupLayout->addWidget(m_reflectSpreadButton); - - QHBoxLayout *defaultsGroupLayout = new QHBoxLayout(defaultsGroup); - defaultsGroupLayout->addWidget(default1Button); - defaultsGroupLayout->addWidget(default2Button); - defaultsGroupLayout->addWidget(default3Button); - editorGroupLayout->addWidget(default4Button); - - connect(m_editor, SIGNAL(gradientStopsChanged(QGradientStops)), - m_renderer, SLOT(setGradientStops(QGradientStops))); - - connect(m_linearButton, SIGNAL(clicked()), m_renderer, SLOT(setLinearGradient())); - connect(m_radialButton, SIGNAL(clicked()), m_renderer, SLOT(setRadialGradient())); - connect(m_conicalButton, SIGNAL(clicked()), m_renderer, SLOT(setConicalGradient())); - - connect(m_padSpreadButton, SIGNAL(clicked()), m_renderer, SLOT(setPadSpread())); - connect(m_reflectSpreadButton, SIGNAL(clicked()), m_renderer, SLOT(setReflectSpread())); - connect(m_repeatSpreadButton, SIGNAL(clicked()), m_renderer, SLOT(setRepeatSpread())); - - connect(default1Button, SIGNAL(clicked()), this, SLOT(setDefault1())); - connect(default2Button, SIGNAL(clicked()), this, SLOT(setDefault2())); - connect(default3Button, SIGNAL(clicked()), this, SLOT(setDefault3())); - connect(default4Button, SIGNAL(clicked()), this, SLOT(setDefault4())); - - connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); -#ifdef QT_OPENGL_SUPPORT - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); -#endif - connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); - connect(whatsThisButton, SIGNAL(clicked(bool)), - m_renderer->hoverPoints(), SLOT(setDisabled(bool))); - connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), - whatsThisButton, SLOT(setChecked(bool))); - connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), - m_renderer->hoverPoints(), SLOT(setDisabled(bool))); - - m_renderer->loadSourceFile(":res/gradients/gradients.cpp"); - m_renderer->loadDescription(":res/gradients/gradients.html"); - - QTimer::singleShot(50, this, SLOT(setDefault1())); -} - -void GradientWidget::setDefault(int config) -{ - QGradientStops stops; - QPolygonF points; - switch (config) { - case 1: - stops << QGradientStop(0.00, QColor::fromRgba(0)); - stops << QGradientStop(0.04, QColor::fromRgba(0xff131360)); - stops << QGradientStop(0.08, QColor::fromRgba(0xff202ccc)); - stops << QGradientStop(0.42, QColor::fromRgba(0xff93d3f9)); - stops << QGradientStop(0.51, QColor::fromRgba(0xffb3e6ff)); - stops << QGradientStop(0.73, QColor::fromRgba(0xffffffec)); - stops << QGradientStop(0.92, QColor::fromRgba(0xff5353d9)); - stops << QGradientStop(0.96, QColor::fromRgba(0xff262666)); - stops << QGradientStop(1.00, QColor::fromRgba(0)); - m_linearButton->animateClick(); - m_repeatSpreadButton->animateClick(); - break; - - case 2: - stops << QGradientStop(0.00, QColor::fromRgba(0xffffffff)); - stops << QGradientStop(0.11, QColor::fromRgba(0xfff9ffa0)); - stops << QGradientStop(0.13, QColor::fromRgba(0xfff9ff99)); - stops << QGradientStop(0.14, QColor::fromRgba(0xfff3ff86)); - stops << QGradientStop(0.49, QColor::fromRgba(0xff93b353)); - stops << QGradientStop(0.87, QColor::fromRgba(0xff264619)); - stops << QGradientStop(0.96, QColor::fromRgba(0xff0c1306)); - stops << QGradientStop(1.00, QColor::fromRgba(0)); - m_radialButton->animateClick(); - m_padSpreadButton->animateClick(); - break; - - case 3: - stops << QGradientStop(0.00, QColor::fromRgba(0)); - stops << QGradientStop(0.10, QColor::fromRgba(0xffe0cc73)); - stops << QGradientStop(0.17, QColor::fromRgba(0xffc6a006)); - stops << QGradientStop(0.46, QColor::fromRgba(0xff600659)); - stops << QGradientStop(0.72, QColor::fromRgba(0xff0680ac)); - stops << QGradientStop(0.92, QColor::fromRgba(0xffb9d9e6)); - stops << QGradientStop(1.00, QColor::fromRgba(0)); - m_conicalButton->animateClick(); - m_padSpreadButton->animateClick(); - break; - - case 4: - stops << QGradientStop(0.00, QColor::fromRgba(0xff000000)); - stops << QGradientStop(1.00, QColor::fromRgba(0xffffffff)); - break; - - default: - qWarning("bad default: %d\n", config); - break; - } - - QPolygonF pts; - int h_off = m_renderer->width() / 10; - int v_off = m_renderer->height() / 8; - pts << QPointF(m_renderer->width() / 2, m_renderer->height() / 2) - << QPointF(m_renderer->width() / 2 - h_off, m_renderer->height() / 2 - v_off); - - m_editor->setGradientStops(stops); - m_renderer->hoverPoints()->setPoints(pts); - m_renderer->setGradientStops(stops); -} - - -GradientRenderer::GradientRenderer(QWidget *parent) - : ArthurFrame(parent) -{ - m_hoverPoints = new HoverPoints(this, HoverPoints::CircleShape); - m_hoverPoints->setPointSize(QSize(20, 20)); - m_hoverPoints->setConnectionType(HoverPoints::NoConnection); - m_hoverPoints->setEditable(false); - - QVector points; - points << QPointF(100, 100) << QPointF(200, 200); - m_hoverPoints->setPoints(points); - - m_spread = QGradient::PadSpread; - m_gradientType = Qt::LinearGradientPattern; -} - -void GradientRenderer::setGradientStops(const QGradientStops &stops) -{ - m_stops = stops; - update(); -} - - -void GradientRenderer::mousePressEvent(QMouseEvent *) -{ - setDescriptionEnabled(false); -} - -void GradientRenderer::paint(QPainter *p) -{ - QPolygonF pts = m_hoverPoints->points(); - - QGradient g; - - if (m_gradientType == Qt::LinearGradientPattern) { - g = QLinearGradient(pts.at(0), pts.at(1)); - - } else if (m_gradientType == Qt::RadialGradientPattern) { - g = QRadialGradient(pts.at(0), qMin(width(), height()) / 3.0, pts.at(1)); - - } else { - QLineF l(pts.at(0), pts.at(1)); - qreal angle = l.angle(QLineF(0, 0, 1, 0)); - if (l.dy() > 0) - angle = 360 - angle; - g = QConicalGradient(pts.at(0), angle); - } - - for (int i=0; isetBrush(g); - p->setPen(Qt::NoPen); - - p->drawRect(rect()); - -} diff --git a/demos/gradients/gradients.h b/demos/gradients/gradients.h deleted file mode 100644 index e1a2bcb41e..0000000000 --- a/demos/gradients/gradients.h +++ /dev/null @@ -1,170 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GRADIENTS_H -#define GRADIENTS_H - -#include "arthurwidgets.h" - -#include - -class HoverPoints; - - -class ShadeWidget : public QWidget -{ - Q_OBJECT -public: - enum ShadeType { - RedShade, - GreenShade, - BlueShade, - ARGBShade - }; - - ShadeWidget(ShadeType type, QWidget *parent); - - void setGradientStops(const QGradientStops &stops); - - void paintEvent(QPaintEvent *e); - - QSize sizeHint() const { return QSize(150, 40); } - QPolygonF points() const; - - HoverPoints *hoverPoints() const { return m_hoverPoints; } - - uint colorAt(int x); - -signals: - void colorsChanged(); - -private: - void generateShade(); - - ShadeType m_shade_type; - QImage m_shade; - HoverPoints *m_hoverPoints; - QLinearGradient m_alpha_gradient; -}; - -class GradientEditor : public QWidget -{ - Q_OBJECT -public: - GradientEditor(QWidget *parent); - - void setGradientStops(const QGradientStops &stops); - -public slots: - void pointsUpdated(); - -signals: - void gradientStopsChanged(const QGradientStops &stops); - -private: - ShadeWidget *m_red_shade; - ShadeWidget *m_green_shade; - ShadeWidget *m_blue_shade; - ShadeWidget *m_alpha_shade; -}; - - -class GradientRenderer : public ArthurFrame -{ - Q_OBJECT -public: - GradientRenderer(QWidget *parent); - void paint(QPainter *p); - - QSize sizeHint() const { return QSize(400, 400); } - - HoverPoints *hoverPoints() const { return m_hoverPoints; } - void mousePressEvent(QMouseEvent *e); - -public slots: - void setGradientStops(const QGradientStops &stops); - - void setPadSpread() { m_spread = QGradient::PadSpread; update(); } - void setRepeatSpread() { m_spread = QGradient::RepeatSpread; update(); } - void setReflectSpread() { m_spread = QGradient::ReflectSpread; update(); } - - void setLinearGradient() { m_gradientType = Qt::LinearGradientPattern; update(); } - void setRadialGradient() { m_gradientType = Qt::RadialGradientPattern; update(); } - void setConicalGradient() { m_gradientType = Qt::ConicalGradientPattern; update(); } - - -private: - QGradientStops m_stops; - HoverPoints *m_hoverPoints; - - QGradient::Spread m_spread; - Qt::BrushStyle m_gradientType; -}; - - -class GradientWidget : public QWidget -{ - Q_OBJECT -public: - GradientWidget(QWidget *parent); - -public slots: - void setDefault1() { setDefault(1); } - void setDefault2() { setDefault(2); } - void setDefault3() { setDefault(3); } - void setDefault4() { setDefault(4); } - -private: - void setDefault(int i); - - GradientRenderer *m_renderer; - GradientEditor *m_editor; - - QRadioButton *m_linearButton; - QRadioButton *m_radialButton; - QRadioButton *m_conicalButton; - QRadioButton *m_padSpreadButton; - QRadioButton *m_reflectSpreadButton; - QRadioButton *m_repeatSpreadButton; - -}; - -#endif // GRADIENTS_H diff --git a/demos/gradients/gradients.html b/demos/gradients/gradients.html deleted file mode 100644 index 1ea2c0ed6c..0000000000 --- a/demos/gradients/gradients.html +++ /dev/null @@ -1,31 +0,0 @@ - -
-

Gradients

-
- -

In this demo we show the various types of gradients that can -be used in Qt.

- -

There are three types of gradients: - -

    -
  • Linear gradients interpolate colors between start and end - points.
  • -
  • Radial gradients interpolate colors between a focal point and the - points on a circle surrounding it.
  • -
  • Conical gradients interpolate colors around a center point.
  • -
- -

- -

The panel on the right contains a color table editor that defines -the colors in the gradient. The three topmost controls determine the red, -green and blue components while the last defines the alpha of the -gradient. You can move points, and add new ones, by clicking with the left -mouse button, and remove points by clicking with the right button.

- -

There are three default configurations available at the bottom of -the page that are provided as suggestions on how a color table could be -configured.

- - diff --git a/demos/gradients/gradients.pro b/demos/gradients/gradients.pro deleted file mode 100644 index ed4120e01c..0000000000 --- a/demos/gradients/gradients.pro +++ /dev/null @@ -1,20 +0,0 @@ -SOURCES += main.cpp gradients.cpp -HEADERS += gradients.h - -SHARED_FOLDER = ../shared - -include($$SHARED_FOLDER/shared.pri) - -RESOURCES += gradients.qrc -contains(QT_CONFIG, opengl) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/gradients -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/gradients -INSTALLS += target sources - -symbian: CONFIG += qt_demo diff --git a/demos/gradients/gradients.qrc b/demos/gradients/gradients.qrc deleted file mode 100644 index fb971eb17b..0000000000 --- a/demos/gradients/gradients.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - gradients.cpp - gradients.html - - diff --git a/demos/gradients/main.cpp b/demos/gradients/main.cpp deleted file mode 100644 index 1d2f0d5775..0000000000 --- a/demos/gradients/main.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "gradients.h" - -#include - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(gradients); - - QApplication app(argc, argv); - - GradientWidget gradientWidget(0); - QStyle *arthurStyle = new ArthurStyle(); - gradientWidget.setStyle(arthurStyle); - QList widgets = gradientWidget.findChildren(); - foreach (QWidget *w, widgets) { - w->setStyle(arthurStyle); - w->setAttribute(Qt::WA_AcceptTouchEvents); - } - gradientWidget.show(); - - return app.exec(); -} diff --git a/demos/interview/README b/demos/interview/README deleted file mode 100644 index 50894428f6..0000000000 --- a/demos/interview/README +++ /dev/null @@ -1,2 +0,0 @@ -The interview example shows the same model and selection being shared -between three different views. diff --git a/demos/interview/images/folder.png b/demos/interview/images/folder.png deleted file mode 100644 index 589fd2df59..0000000000 Binary files a/demos/interview/images/folder.png and /dev/null differ diff --git a/demos/interview/images/interview.png b/demos/interview/images/interview.png deleted file mode 100644 index 0c3d690258..0000000000 Binary files a/demos/interview/images/interview.png and /dev/null differ diff --git a/demos/interview/images/services.png b/demos/interview/images/services.png deleted file mode 100644 index 6b2ad969d4..0000000000 Binary files a/demos/interview/images/services.png and /dev/null differ diff --git a/demos/interview/interview.pro b/demos/interview/interview.pro deleted file mode 100644 index a497fbc407..0000000000 --- a/demos/interview/interview.pro +++ /dev/null @@ -1,19 +0,0 @@ -TEMPLATE = app - -CONFIG += qt warn_on -HEADERS += model.h -SOURCES += model.cpp main.cpp -RESOURCES += interview.qrc - -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/interview -sources.files = $$SOURCES $$HEADERS $$RESOURCES README *.pro images -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/interview -INSTALLS += target sources - -symbian: CONFIG += qt_demo diff --git a/demos/interview/interview.qrc b/demos/interview/interview.qrc deleted file mode 100644 index b28ea34d8a..0000000000 --- a/demos/interview/interview.qrc +++ /dev/null @@ -1,7 +0,0 @@ - - - images/folder.png - images/services.png - images/interview.png - - diff --git a/demos/interview/main.cpp b/demos/interview/main.cpp deleted file mode 100644 index b9656c6185..0000000000 --- a/demos/interview/main.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "model.h" - -#include -#include -#include -#include -#include -#include - -int main(int argc, char *argv[]) -{ - Q_INIT_RESOURCE(interview); - - QApplication app(argc, argv); - QSplitter page; - - QAbstractItemModel *data = new Model(1000, 10, &page); - QItemSelectionModel *selections = new QItemSelectionModel(data); - - QTableView *table = new QTableView; - table->setModel(data); - table->setSelectionModel(selections); - table->horizontalHeader()->setMovable(true); - table->verticalHeader()->setMovable(true); - // Set StaticContents to enable minimal repaints on resizes. - table->viewport()->setAttribute(Qt::WA_StaticContents); - page.addWidget(table); - - QTreeView *tree = new QTreeView; - tree->setModel(data); - tree->setSelectionModel(selections); - tree->setUniformRowHeights(true); - tree->header()->setStretchLastSection(false); - tree->viewport()->setAttribute(Qt::WA_StaticContents); - // Disable the focus rect to get minimal repaints when scrolling on Mac. - tree->setAttribute(Qt::WA_MacShowFocusRect, false); - page.addWidget(tree); - - QListView *list = new QListView; - list->setModel(data); - list->setSelectionModel(selections); - list->setViewMode(QListView::IconMode); - list->setSelectionMode(QAbstractItemView::ExtendedSelection); - list->setAlternatingRowColors(false); - list->viewport()->setAttribute(Qt::WA_StaticContents); - list->setAttribute(Qt::WA_MacShowFocusRect, false); - page.addWidget(list); - - page.setWindowIcon(QPixmap(":/images/interview.png")); - page.setWindowTitle("Interview"); - page.show(); - - return app.exec(); -} diff --git a/demos/interview/model.cpp b/demos/interview/model.cpp deleted file mode 100644 index 6031615711..0000000000 --- a/demos/interview/model.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "model.h" -#include -#include - -Model::Model(int rows, int columns, QObject *parent) - : QAbstractItemModel(parent), - services(QPixmap(":/images/services.png")), - rc(rows), cc(columns), - tree(new QVector(rows, Node(0))) -{ - -} - -Model::~Model() -{ - delete tree; -} - -QModelIndex Model::index(int row, int column, const QModelIndex &parent) const -{ - if (row < rc && row >= 0 && column < cc && column >= 0) { - Node *p = static_cast(parent.internalPointer()); - Node *n = node(row, p); - if (n) - return createIndex(row, column, n); - } - return QModelIndex(); -} - -QModelIndex Model::parent(const QModelIndex &child) const -{ - if (child.isValid()) { - Node *n = static_cast(child.internalPointer()); - Node *p = parent(n); - if (p) - return createIndex(row(p), 0, p); - } - return QModelIndex(); -} - -int Model::rowCount(const QModelIndex &parent) const -{ - return (parent.isValid() && parent.column() != 0) ? 0 : rc; -} - -int Model::columnCount(const QModelIndex &parent) const -{ - Q_UNUSED(parent); - return cc; -} - -QVariant Model::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - return QVariant(); - if (role == Qt::DisplayRole) - return "Item " + QString::number(index.row()) + ":" + QString::number(index.column()); - if (role == Qt::DecorationRole) { - if (index.column() == 0) - return iconProvider.icon(QFileIconProvider::Folder); - return iconProvider.icon(QFileIconProvider::File); - } - return QVariant(); -} - -QVariant Model::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (role == Qt::DisplayRole) - return QString::number(section); - if (role == Qt::DecorationRole) - return QVariant::fromValue(services); - return QAbstractItemModel::headerData(section, orientation, role); -} - -bool Model::hasChildren(const QModelIndex &parent) const -{ - if (parent.isValid() && parent.column() != 0) - return false; - return rc > 0 && cc > 0; -} - -Qt::ItemFlags Model::flags(const QModelIndex &index) const -{ - if (!index.isValid()) - return 0; - return (Qt::ItemIsDragEnabled|Qt::ItemIsSelectable|Qt::ItemIsEnabled); -} - -Model::Node *Model::node(int row, Node *parent) const -{ - if (parent && !parent->children) - parent->children = new QVector(rc, Node(parent)); - QVector *v = parent ? parent->children : tree; - return const_cast(&(v->at(row))); -} - -Model::Node *Model::parent(Node *child) const -{ - return child ? child->parent : 0; -} - -int Model::row(Node *node) const -{ - const Node *first = node->parent ? &(node->parent->children->at(0)) : &(tree->at(0)); - return (node - first); -} diff --git a/demos/interview/model.h b/demos/interview/model.h deleted file mode 100644 index f0ae556ce3..0000000000 --- a/demos/interview/model.h +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MODEL_H -#define MODEL_H - -#include -#include -#include -#include - -class Model : public QAbstractItemModel -{ - Q_OBJECT - -public: - Model(int rows, int columns, QObject *parent = 0); - ~Model(); - - QModelIndex index(int row, int column, const QModelIndex &parent) const; - QModelIndex parent(const QModelIndex &child) const; - - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - - bool hasChildren(const QModelIndex &parent) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - -private: - - struct Node - { - Node(Node *parent = 0) : parent(parent), children(0) {} - ~Node() { delete children; } - Node *parent; - QVector *children; - }; - - Node *node(int row, Node *parent) const; - Node *parent(Node *child) const; - int row(Node *node) const; - - QIcon services; - int rc, cc; - QVector *tree; - QFileIconProvider iconProvider; -}; - -#endif diff --git a/demos/macmainwindow/macmainwindow.h b/demos/macmainwindow/macmainwindow.h deleted file mode 100644 index 10ff3b5147..0000000000 --- a/demos/macmainwindow/macmainwindow.h +++ /dev/null @@ -1,137 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#ifndef MACMAINWINDOW_H -#define MACMAINWINDOW_H - -#include - -#ifdef Q_WS_MAC - -#import - -#ifdef QT_MAC_USE_COCOA -class SearchWidget : public QMacCocoaViewContainer -{ - Q_OBJECT -public: - SearchWidget(QWidget *parent = 0); - ~SearchWidget(); - - QSize sizeHint() const; -private: -}; - -#else -#include - -// The SearchWidget class wraps a native HISearchField. -class SearchWidget : public QWidget -{ - Q_OBJECT -private: - HIViewRef searchField; - CFStringRef searchFieldText; - -public: - QSize sizeHint() const; - SearchWidget(QWidget *parent = 0); - ~SearchWidget(); -}; - -#endif - -QMenu *createMenu(QWidget *parent); - -class SearchWrapper : public QWidget -{ -Q_OBJECT -public: - SearchWrapper(QWidget *parent = 0); - QSize sizeHint() const; - QWidget *s; -}; - -class Spacer : public QWidget -{ -Q_OBJECT -public: - Spacer(QWidget *parent = 0); - QSize sizeHint() const; -}; - -class MacSplitterHandle : public QSplitterHandle -{ -Q_OBJECT -public: - MacSplitterHandle(Qt::Orientation orientation, QSplitter *parent); - void paintEvent(QPaintEvent *); - QSize sizeHint() const; -}; - -class MacSplitter : public QSplitter -{ -public: - QSplitterHandle *createHandle(); -}; - -class MacMainWindow : public QMainWindow -{ -Q_OBJECT -public: - MacMainWindow(); - ~MacMainWindow(); - QAbstractItemModel *createItemModel(); - void resizeEvent(QResizeEvent *e); - QAbstractItemModel *createDocumentModel(); -public: - QSplitter *splitter; - QSplitter *horizontalSplitter; - QTreeView *sidebar; - QListView *documents; - QTextEdit *textedit; - QVBoxLayout *layout; - SearchWidget *searchWidget; - QToolBar * toolBar; -}; - -#endif // Q_WS_MAC - -#endif //MACMAINWINDOW_H diff --git a/demos/macmainwindow/macmainwindow.mm b/demos/macmainwindow/macmainwindow.mm deleted file mode 100644 index 3b0ba6f02a..0000000000 --- a/demos/macmainwindow/macmainwindow.mm +++ /dev/null @@ -1,347 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#include "macmainwindow.h" -#import -#include - - -#ifdef Q_WS_MAC - -#include - -#ifdef QT_MAC_USE_COCOA - -//![0] -SearchWidget::SearchWidget(QWidget *parent) - : QMacCocoaViewContainer(0, parent) -{ - // Many Cocoa objects create temporary autorelease objects, - // so create a pool to catch them. - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - // Create the NSSearchField, set it on the QCocoaViewContainer. - NSSearchField *search = [[NSSearchField alloc] init]; - setCocoaView(search); - - // Use a Qt menu for the search field menu. - QMenu *qtMenu = createMenu(this); - NSMenu *nsMenu = qtMenu->macMenu(0); - [[search cell] setSearchMenuTemplate:nsMenu]; - - // Release our reference, since our super class takes ownership and we - // don't need it anymore. - [search release]; - - // Clean up our pool as we no longer need it. - [pool release]; -} -//![0] - -SearchWidget::~SearchWidget() -{ -} - -QSize SearchWidget::sizeHint() const -{ - return QSize(150, 40); -} - -#else - -// The SearchWidget class wraps a native HISearchField. -SearchWidget::SearchWidget(QWidget *parent) - :QWidget(parent) -{ - - // Create a native search field and pass its window id to QWidget::create. - searchFieldText = CFStringCreateWithCString(0, "search", 0); - HISearchFieldCreate(NULL/*bounds*/, kHISearchFieldAttributesSearchIcon | kHISearchFieldAttributesCancel, - NULL/*menu ref*/, searchFieldText, &searchField); - create(reinterpret_cast(searchField)); - - // Use a Qt menu for the search field menu. - QMenu *searchMenu = createMenu(this); - MenuRef menuRef = searchMenu->macMenu(0); - HISearchFieldSetSearchMenu(searchField, menuRef); - setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); -} - -SearchWidget::~SearchWidget() -{ - CFRelease(searchField); - CFRelease(searchFieldText); -} - -// Get the size hint from the search field. -QSize SearchWidget::sizeHint() const -{ - EventRef event; - HIRect optimalBounds; - CreateEvent(0, kEventClassControl, - kEventControlGetOptimalBounds, - GetCurrentEventTime(), - kEventAttributeUserEvent, &event); - - SendEventToEventTargetWithOptions(event, - HIObjectGetEventTarget(HIObjectRef(winId())), - kEventTargetDontPropagate); - - GetEventParameter(event, - kEventParamControlOptimalBounds, typeHIRect, - 0, sizeof(HIRect), 0, &optimalBounds); - - ReleaseEvent(event); - return QSize(optimalBounds.size.width + 100, // make it a bit wider. - optimalBounds.size.height); -} - -#endif - -QMenu *createMenu(QWidget *parent) -{ - QMenu *searchMenu = new QMenu(parent); - - QAction * indexAction = searchMenu->addAction("Index Search"); - indexAction->setCheckable(true); - indexAction->setChecked(true); - - QAction * fulltextAction = searchMenu->addAction("Full Text Search"); - fulltextAction->setCheckable(true); - - QActionGroup *searchActionGroup = new QActionGroup(parent); - searchActionGroup->addAction(indexAction); - searchActionGroup->addAction(fulltextAction); - searchActionGroup->setExclusive(true); - - return searchMenu; -} - -SearchWrapper::SearchWrapper(QWidget *parent) -:QWidget(parent) -{ - s = new SearchWidget(this); - s->move(2,2); - setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); -} - -QSize SearchWrapper::sizeHint() const -{ - return s->sizeHint() + QSize(6, 2); -} - -Spacer::Spacer(QWidget *parent) -:QWidget(parent) -{ - QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - setSizePolicy(sizePolicy); -} - -QSize Spacer::sizeHint() const -{ - return QSize(1, 1); -} - -MacSplitterHandle::MacSplitterHandle(Qt::Orientation orientation, QSplitter *parent) -: QSplitterHandle(orientation, parent) { } - -// Paint the horizontal handle as a gradient, paint -// the vertical handle as a line. -void MacSplitterHandle::paintEvent(QPaintEvent *) -{ - QPainter painter(this); - - QColor topColor(145, 145, 145); - QColor bottomColor(142, 142, 142); - QColor gradientStart(252, 252, 252); - QColor gradientStop(223, 223, 223); - - if (orientation() == Qt::Vertical) { - painter.setPen(topColor); - painter.drawLine(0, 0, width(), 0); - painter.setPen(bottomColor); - painter.drawLine(0, height() - 1, width(), height() - 1); - - QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, height() -3)); - linearGrad.setColorAt(0, gradientStart); - linearGrad.setColorAt(1, gradientStop); - painter.fillRect(QRect(QPoint(0,1), size() - QSize(0, 2)), QBrush(linearGrad)); - } else { - painter.setPen(topColor); - painter.drawLine(0, 0, 0, height()); - } -} - -QSize MacSplitterHandle::sizeHint() const -{ - QSize parent = QSplitterHandle::sizeHint(); - if (orientation() == Qt::Vertical) { - return parent + QSize(0, 3); - } else { - return QSize(1, parent.height()); - } -} - -QSplitterHandle *MacSplitter::createHandle() -{ - return new MacSplitterHandle(orientation(), this); -} - -MacMainWindow::MacMainWindow() -{ - QSettings settings; - restoreGeometry(settings.value("Geometry").toByteArray()); - - setWindowTitle("Mac Main Window"); - - splitter = new MacSplitter(); - - // Set up the left-hand side blue side bar. - sidebar = new QTreeView(); - sidebar->setFrameStyle(QFrame::NoFrame); - sidebar->setAttribute(Qt::WA_MacShowFocusRect, false); - sidebar->setAutoFillBackground(true); - - // Set the palette. - QPalette palette = sidebar->palette(); - QColor macSidebarColor(231, 237, 246); - QColor macSidebarHighlightColor(168, 183, 205); - palette.setColor(QPalette::Base, macSidebarColor); - palette.setColor(QPalette::Highlight, macSidebarHighlightColor); - sidebar->setPalette(palette); - - sidebar->setModel(createItemModel()); - sidebar->header()->hide(); - sidebar->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - sidebar->setTextElideMode(Qt::ElideMiddle); - - splitter->addWidget(sidebar); - - horizontalSplitter = new MacSplitter(); - horizontalSplitter->setOrientation(Qt::Vertical); - splitter->addWidget(horizontalSplitter); - - splitter->setStretchFactor(0, 0); - splitter->setStretchFactor(1, 1); - - // Set up the top document list view. - documents = new QListView(); - documents->setFrameStyle(QFrame::NoFrame); - documents->setAttribute(Qt::WA_MacShowFocusRect, false); - documents->setModel(createDocumentModel()); - documents->setAlternatingRowColors(true); - documents->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); - horizontalSplitter->addWidget(documents); - horizontalSplitter->setStretchFactor(0, 0); - - // Set up the text view. - textedit = new QTextEdit(); - textedit->setFrameStyle(QFrame::NoFrame); - textedit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); - textedit->setText("





This demo shows how to create a \ - Qt main window application that has the same appearance as other \ - Mac OS X applications such as Mail or iTunes. This includes \ - customizing the item views and QSplitter and wrapping native widgets \ - such as the search field.
"); - - horizontalSplitter->addWidget(textedit); - - setCentralWidget(splitter); - - toolBar = addToolBar(tr("Search")); - toolBar->addWidget(new Spacer()); - toolBar->addWidget(new SearchWrapper()); - - setUnifiedTitleAndToolBarOnMac(true); -} - -MacMainWindow::~MacMainWindow() -{ - QSettings settings; - settings.setValue("Geometry", saveGeometry()); -} - -QAbstractItemModel *MacMainWindow::createItemModel() -{ - QStandardItemModel *model = new QStandardItemModel(); - QStandardItem *parentItem = model->invisibleRootItem(); - - QStandardItem *documentationItem = new QStandardItem("Documentation"); - parentItem->appendRow(documentationItem); - - QStandardItem *assistantItem = new QStandardItem("Qt MainWindow Manual"); - documentationItem->appendRow(assistantItem); - - QStandardItem *designerItem = new QStandardItem("Qt Designer Manual"); - documentationItem->appendRow(designerItem); - - QStandardItem *qtItem = new QStandardItem("Qt Reference Documentation"); - qtItem->appendRow(new QStandardItem("Classes")); - qtItem->appendRow(new QStandardItem("Overviews")); - qtItem->appendRow(new QStandardItem("Tutorial & Examples")); - documentationItem->appendRow(qtItem); - - QStandardItem *bookmarksItem = new QStandardItem("Bookmarks"); - parentItem->appendRow(bookmarksItem); - bookmarksItem->appendRow(new QStandardItem("QWidget")); - bookmarksItem->appendRow(new QStandardItem("QObject")); - bookmarksItem->appendRow(new QStandardItem("QWizard")); - - return model; -} - -void MacMainWindow::resizeEvent(QResizeEvent *) -{ - if (toolBar) - toolBar->updateGeometry(); -} - -QAbstractItemModel *MacMainWindow::createDocumentModel() -{ - QStandardItemModel *model = new QStandardItemModel(); - QStandardItem *parentItem = model->invisibleRootItem(); - parentItem->appendRow(new QStandardItem("QWidget Class Reference")); - parentItem->appendRow(new QStandardItem("QObject Class Reference")); - parentItem->appendRow(new QStandardItem("QListView Class Reference")); - - return model; -} - -#endif // Q_WS_MAC diff --git a/demos/macmainwindow/macmainwindow.pro b/demos/macmainwindow/macmainwindow.pro deleted file mode 100644 index 435905612a..0000000000 --- a/demos/macmainwindow/macmainwindow.pro +++ /dev/null @@ -1,23 +0,0 @@ -TEMPLATE = app -TARGET = macmainwindow - -CONFIG += qt warn_on console - -OBJECTIVE_SOURCES += macmainwindow.mm -SOURCES += main.cpp -HEADERS += macmainwindow.h - -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -LIBS += -framework Cocoa -framework Carbon - -# install -mac { -target.path = $$[QT_INSTALL_DEMOS]/qtbase/macmainwindow -sources.files = $$SOURCES *.pro *.html -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/macmainwindow -INSTALLS += target sources -} diff --git a/demos/macmainwindow/main.cpp b/demos/macmainwindow/main.cpp deleted file mode 100644 index 34e4847068..0000000000 --- a/demos/macmainwindow/main.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "macmainwindow.h" - -#ifdef Q_WS_MAC - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - MacMainWindow mainWindow; - mainWindow.show(); - return app.exec(); -} - -#else -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - QLabel label; - label.resize(300, 200); - label.setText(" This demo requires Mac OS X."); - label.show(); - return app.exec(); -} - -#endif diff --git a/demos/mainwindow/colorswatch.cpp b/demos/mainwindow/colorswatch.cpp deleted file mode 100644 index dd16fddbe7..0000000000 --- a/demos/mainwindow/colorswatch.cpp +++ /dev/null @@ -1,746 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "colorswatch.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#undef DEBUG_SIZEHINTS - -QColor bgColorForName(const QString &name) -{ - if (name == "Black") - return QColor("#D8D8D8"); - else if (name == "White") - return QColor("#F1F1F1"); - else if (name == "Red") - return QColor("#F1D8D8"); - else if (name == "Green") - return QColor("#D8E4D8"); - else if (name == "Blue") - return QColor("#D8D8F1"); - else if (name == "Yellow") - return QColor("#F1F0D8"); - return QColor(name).light(110); -} - -QColor fgColorForName(const QString &name) -{ - if (name == "Black") - return QColor("#6C6C6C"); - else if (name == "White") - return QColor("#F8F8F8"); - else if (name == "Red") - return QColor("#F86C6C"); - else if (name == "Green") - return QColor("#6CB26C"); - else if (name == "Blue") - return QColor("#6C6CF8"); - else if (name == "Yellow") - return QColor("#F8F76C"); - return QColor(name); -} - -class ColorDock : public QFrame -{ - Q_OBJECT -public: - ColorDock(const QString &c, QWidget *parent); - - virtual QSize sizeHint() const; - virtual QSize minimumSizeHint() const; - - void setCustomSizeHint(const QSize &size); - -public slots: - void changeSizeHints(); - -protected: - void paintEvent(QPaintEvent *); - QString color; - QSize szHint, minSzHint; -}; - -ColorDock::ColorDock(const QString &c, QWidget *parent) - : QFrame(parent) , color(c) -{ - QFont font = this->font(); - font.setPointSize(8); - setFont(font); - szHint = QSize(-1, -1); - minSzHint = QSize(125, 75); -} - -QSize ColorDock::sizeHint() const -{ - return szHint; -} - -QSize ColorDock::minimumSizeHint() const -{ - return minSzHint; -} - -void ColorDock::paintEvent(QPaintEvent *) -{ - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - p.fillRect(rect(), bgColorForName(color)); - - p.save(); - - extern void render_qt_text(QPainter *, int, int, const QColor &); - render_qt_text(&p, width(), height(), fgColorForName(color)); - - p.restore(); - -#ifdef DEBUG_SIZEHINTS - p.setRenderHint(QPainter::Antialiasing, false); - - QSize sz = size(); - QSize szHint = sizeHint(); - QSize minSzHint = minimumSizeHint(); - QSize maxSz = maximumSize(); - QString text = QString::fromLatin1("sz: %1x%2\nszHint: %3x%4\nminSzHint: %5x%6\n" - "maxSz: %8x%9") - .arg(sz.width()).arg(sz.height()) - .arg(szHint.width()).arg(szHint.height()) - .arg(minSzHint.width()).arg(minSzHint.height()) - .arg(maxSz.width()).arg(maxSz.height()); - - QRect r = fontMetrics().boundingRect(rect(), Qt::AlignLeft|Qt::AlignTop, text); - r.adjust(-2, -2, 1, 1); - p.translate(4, 4); - QColor bg = Qt::yellow; - bg.setAlpha(120); - p.setBrush(bg); - p.setPen(Qt::black); - p.drawRect(r); - p.drawText(rect(), Qt::AlignLeft|Qt::AlignTop, text); -#endif // DEBUG_SIZEHINTS -} - -static QSpinBox *createSpinBox(int value, QWidget *parent, int max = 1000) -{ - QSpinBox *result = new QSpinBox(parent); - result->setMinimum(-1); - result->setMaximum(max); - result->setValue(value); - return result; -} - -void ColorDock::changeSizeHints() -{ - QDialog dialog(this); - dialog.setWindowTitle(color); - - QVBoxLayout *topLayout = new QVBoxLayout(&dialog); - - QGridLayout *inputLayout = new QGridLayout(); - topLayout->addLayout(inputLayout); - - inputLayout->addWidget(new QLabel(tr("Size Hint:"), &dialog), 0, 0); - inputLayout->addWidget(new QLabel(tr("Min Size Hint:"), &dialog), 1, 0); - inputLayout->addWidget(new QLabel(tr("Max Size:"), &dialog), 2, 0); - inputLayout->addWidget(new QLabel(tr("Dockwgt Max Size:"), &dialog), 3, 0); - - QSpinBox *szHintW = createSpinBox(szHint.width(), &dialog); - inputLayout->addWidget(szHintW, 0, 1); - QSpinBox *szHintH = createSpinBox(szHint.height(), &dialog); - inputLayout->addWidget(szHintH, 0, 2); - - QSpinBox *minSzHintW = createSpinBox(minSzHint.width(), &dialog); - inputLayout->addWidget(minSzHintW, 1, 1); - QSpinBox *minSzHintH = createSpinBox(minSzHint.height(), &dialog); - inputLayout->addWidget(minSzHintH, 1, 2); - - QSize maxSz = maximumSize(); - QSpinBox *maxSzW = createSpinBox(maxSz.width(), &dialog, QWIDGETSIZE_MAX); - inputLayout->addWidget(maxSzW, 2, 1); - QSpinBox *maxSzH = createSpinBox(maxSz.height(), &dialog, QWIDGETSIZE_MAX); - inputLayout->addWidget(maxSzH, 2, 2); - - QSize dwMaxSz = parentWidget()->maximumSize(); - QSpinBox *dwMaxSzW = createSpinBox(dwMaxSz.width(), &dialog, QWIDGETSIZE_MAX); - inputLayout->addWidget(dwMaxSzW, 3, 1); - QSpinBox *dwMaxSzH = createSpinBox(dwMaxSz.height(), &dialog, QWIDGETSIZE_MAX); - inputLayout->addWidget(dwMaxSzH, 3, 2); - - inputLayout->setColumnStretch(1, 1); - inputLayout->setColumnStretch(2, 1); - - topLayout->addStretch(); - - QHBoxLayout *buttonBox = new QHBoxLayout(); - topLayout->addLayout(buttonBox); - - QPushButton *okButton = new QPushButton(tr("Ok"), &dialog); - QPushButton *cancelButton = new QPushButton(tr("Cancel"), &dialog); - connect(okButton, SIGNAL(clicked()), &dialog, SLOT(accept())); - connect(cancelButton, SIGNAL(clicked()), &dialog, SLOT(reject())); - buttonBox->addStretch(); - buttonBox->addWidget(cancelButton); - buttonBox->addWidget(okButton); - - - if (!dialog.exec()) - return; - - szHint = QSize(szHintW->value(), szHintH->value()); - minSzHint = QSize(minSzHintW->value(), minSzHintH->value()); - maxSz = QSize(maxSzW->value(), maxSzH->value()); - setMaximumSize(maxSz); - dwMaxSz = QSize(dwMaxSzW->value(), dwMaxSzH->value()); - parentWidget()->setMaximumSize(dwMaxSz); - updateGeometry(); - update(); -} - -void ColorDock::setCustomSizeHint(const QSize &size) -{ - szHint = size; - updateGeometry(); -} - -ColorSwatch::ColorSwatch(const QString &colorName, QWidget *parent, Qt::WindowFlags flags) - : QDockWidget(parent, flags) -{ - setObjectName(colorName + QLatin1String(" Dock Widget")); - setWindowTitle(objectName() + QLatin1String(" [*]")); - - QFrame *swatch = new ColorDock(colorName, this); - swatch->setFrameStyle(QFrame::Box | QFrame::Sunken); - - setWidget(swatch); - - changeSizeHintsAction = new QAction(tr("Change Size Hints"), this); - connect(changeSizeHintsAction, SIGNAL(triggered()), swatch, SLOT(changeSizeHints())); - - closableAction = new QAction(tr("Closable"), this); - closableAction->setCheckable(true); - connect(closableAction, SIGNAL(triggered(bool)), SLOT(changeClosable(bool))); - - movableAction = new QAction(tr("Movable"), this); - movableAction->setCheckable(true); - connect(movableAction, SIGNAL(triggered(bool)), SLOT(changeMovable(bool))); - - floatableAction = new QAction(tr("Floatable"), this); - floatableAction->setCheckable(true); - connect(floatableAction, SIGNAL(triggered(bool)), SLOT(changeFloatable(bool))); - - verticalTitleBarAction = new QAction(tr("Vertical title bar"), this); - verticalTitleBarAction->setCheckable(true); - connect(verticalTitleBarAction, SIGNAL(triggered(bool)), - SLOT(changeVerticalTitleBar(bool))); - - floatingAction = new QAction(tr("Floating"), this); - floatingAction->setCheckable(true); - connect(floatingAction, SIGNAL(triggered(bool)), SLOT(changeFloating(bool))); - - allowedAreasActions = new QActionGroup(this); - allowedAreasActions->setExclusive(false); - - allowLeftAction = new QAction(tr("Allow on Left"), this); - allowLeftAction->setCheckable(true); - connect(allowLeftAction, SIGNAL(triggered(bool)), SLOT(allowLeft(bool))); - - allowRightAction = new QAction(tr("Allow on Right"), this); - allowRightAction->setCheckable(true); - connect(allowRightAction, SIGNAL(triggered(bool)), SLOT(allowRight(bool))); - - allowTopAction = new QAction(tr("Allow on Top"), this); - allowTopAction->setCheckable(true); - connect(allowTopAction, SIGNAL(triggered(bool)), SLOT(allowTop(bool))); - - allowBottomAction = new QAction(tr("Allow on Bottom"), this); - allowBottomAction->setCheckable(true); - connect(allowBottomAction, SIGNAL(triggered(bool)), SLOT(allowBottom(bool))); - - allowedAreasActions->addAction(allowLeftAction); - allowedAreasActions->addAction(allowRightAction); - allowedAreasActions->addAction(allowTopAction); - allowedAreasActions->addAction(allowBottomAction); - - areaActions = new QActionGroup(this); - areaActions->setExclusive(true); - - leftAction = new QAction(tr("Place on Left") , this); - leftAction->setCheckable(true); - connect(leftAction, SIGNAL(triggered(bool)), SLOT(placeLeft(bool))); - - rightAction = new QAction(tr("Place on Right") , this); - rightAction->setCheckable(true); - connect(rightAction, SIGNAL(triggered(bool)), SLOT(placeRight(bool))); - - topAction = new QAction(tr("Place on Top") , this); - topAction->setCheckable(true); - connect(topAction, SIGNAL(triggered(bool)), SLOT(placeTop(bool))); - - bottomAction = new QAction(tr("Place on Bottom") , this); - bottomAction->setCheckable(true); - connect(bottomAction, SIGNAL(triggered(bool)), SLOT(placeBottom(bool))); - - areaActions->addAction(leftAction); - areaActions->addAction(rightAction); - areaActions->addAction(topAction); - areaActions->addAction(bottomAction); - - connect(movableAction, SIGNAL(triggered(bool)), areaActions, SLOT(setEnabled(bool))); - - connect(movableAction, SIGNAL(triggered(bool)), allowedAreasActions, SLOT(setEnabled(bool))); - - connect(floatableAction, SIGNAL(triggered(bool)), floatingAction, SLOT(setEnabled(bool))); - - connect(floatingAction, SIGNAL(triggered(bool)), floatableAction, SLOT(setDisabled(bool))); - connect(movableAction, SIGNAL(triggered(bool)), floatableAction, SLOT(setEnabled(bool))); - - tabMenu = new QMenu(this); - tabMenu->setTitle(tr("Tab into")); - connect(tabMenu, SIGNAL(triggered(QAction*)), this, SLOT(tabInto(QAction*))); - - splitHMenu = new QMenu(this); - splitHMenu->setTitle(tr("Split horizontally into")); - connect(splitHMenu, SIGNAL(triggered(QAction*)), this, SLOT(splitInto(QAction*))); - - splitVMenu = new QMenu(this); - splitVMenu->setTitle(tr("Split vertically into")); - connect(splitVMenu, SIGNAL(triggered(QAction*)), this, SLOT(splitInto(QAction*))); - - windowModifiedAction = new QAction(tr("Modified"), this); - windowModifiedAction->setCheckable(true); - windowModifiedAction->setChecked(false); - connect(windowModifiedAction, SIGNAL(toggled(bool)), this, SLOT(setWindowModified(bool))); - - menu = new QMenu(colorName, this); - menu->addAction(toggleViewAction()); - QAction *action = menu->addAction(tr("Raise")); - connect(action, SIGNAL(triggered()), this, SLOT(raise())); - menu->addAction(changeSizeHintsAction); - menu->addSeparator(); - menu->addAction(closableAction); - menu->addAction(movableAction); - menu->addAction(floatableAction); - menu->addAction(floatingAction); - menu->addAction(verticalTitleBarAction); - menu->addSeparator(); - menu->addActions(allowedAreasActions->actions()); - menu->addSeparator(); - menu->addActions(areaActions->actions()); - menu->addSeparator(); - menu->addMenu(splitHMenu); - menu->addMenu(splitVMenu); - menu->addMenu(tabMenu); - menu->addSeparator(); - menu->addAction(windowModifiedAction); - - connect(menu, SIGNAL(aboutToShow()), this, SLOT(updateContextMenu())); - - if(colorName == "Black") { - leftAction->setShortcut(Qt::CTRL|Qt::Key_W); - rightAction->setShortcut(Qt::CTRL|Qt::Key_E); - toggleViewAction()->setShortcut(Qt::CTRL|Qt::Key_R); - } -} - -void ColorSwatch::updateContextMenu() -{ - QMainWindow *mainWindow = qobject_cast(parentWidget()); - const Qt::DockWidgetArea area = mainWindow->dockWidgetArea(this); - const Qt::DockWidgetAreas areas = allowedAreas(); - - closableAction->setChecked(features() & QDockWidget::DockWidgetClosable); - if (windowType() == Qt::Drawer) { - floatableAction->setEnabled(false); - floatingAction->setEnabled(false); - movableAction->setEnabled(false); - verticalTitleBarAction->setChecked(false); - } else { - floatableAction->setChecked(features() & QDockWidget::DockWidgetFloatable); - floatingAction->setChecked(isWindow()); - // done after floating, to get 'floatable' correctly initialized - movableAction->setChecked(features() & QDockWidget::DockWidgetMovable); - verticalTitleBarAction - ->setChecked(features() & QDockWidget::DockWidgetVerticalTitleBar); - } - - allowLeftAction->setChecked(isAreaAllowed(Qt::LeftDockWidgetArea)); - allowRightAction->setChecked(isAreaAllowed(Qt::RightDockWidgetArea)); - allowTopAction->setChecked(isAreaAllowed(Qt::TopDockWidgetArea)); - allowBottomAction->setChecked(isAreaAllowed(Qt::BottomDockWidgetArea)); - - if (allowedAreasActions->isEnabled()) { - allowLeftAction->setEnabled(area != Qt::LeftDockWidgetArea); - allowRightAction->setEnabled(area != Qt::RightDockWidgetArea); - allowTopAction->setEnabled(area != Qt::TopDockWidgetArea); - allowBottomAction->setEnabled(area != Qt::BottomDockWidgetArea); - } - - leftAction->blockSignals(true); - rightAction->blockSignals(true); - topAction->blockSignals(true); - bottomAction->blockSignals(true); - - leftAction->setChecked(area == Qt::LeftDockWidgetArea); - rightAction->setChecked(area == Qt::RightDockWidgetArea); - topAction->setChecked(area == Qt::TopDockWidgetArea); - bottomAction->setChecked(area == Qt::BottomDockWidgetArea); - - leftAction->blockSignals(false); - rightAction->blockSignals(false); - topAction->blockSignals(false); - bottomAction->blockSignals(false); - - if (areaActions->isEnabled()) { - leftAction->setEnabled(areas & Qt::LeftDockWidgetArea); - rightAction->setEnabled(areas & Qt::RightDockWidgetArea); - topAction->setEnabled(areas & Qt::TopDockWidgetArea); - bottomAction->setEnabled(areas & Qt::BottomDockWidgetArea); - } - - tabMenu->clear(); - splitHMenu->clear(); - splitVMenu->clear(); - QList dock_list = mainWindow->findChildren(); - foreach (ColorSwatch *dock, dock_list) { -// if (!dock->isVisible() || dock->isFloating()) -// continue; - tabMenu->addAction(dock->objectName()); - splitHMenu->addAction(dock->objectName()); - splitVMenu->addAction(dock->objectName()); - } -} - -void ColorSwatch::splitInto(QAction *action) -{ - QMainWindow *mainWindow = qobject_cast(parentWidget()); - QList dock_list = mainWindow->findChildren(); - ColorSwatch *target = 0; - foreach (ColorSwatch *dock, dock_list) { - if (action->text() == dock->objectName()) { - target = dock; - break; - } - } - if (target == 0) - return; - - Qt::Orientation o = action->parent() == splitHMenu - ? Qt::Horizontal : Qt::Vertical; - mainWindow->splitDockWidget(target, this, o); -} - -void ColorSwatch::tabInto(QAction *action) -{ - QMainWindow *mainWindow = qobject_cast(parentWidget()); - QList dock_list = mainWindow->findChildren(); - ColorSwatch *target = 0; - foreach (ColorSwatch *dock, dock_list) { - if (action->text() == dock->objectName()) { - target = dock; - break; - } - } - if (target == 0) - return; - - mainWindow->tabifyDockWidget(target, this); -} - -void ColorSwatch::contextMenuEvent(QContextMenuEvent *event) -{ - event->accept(); - menu->exec(event->globalPos()); -} - -void ColorSwatch::resizeEvent(QResizeEvent *e) -{ - if (BlueTitleBar *btb = qobject_cast(titleBarWidget())) - btb->updateMask(); - - QDockWidget::resizeEvent(e); -} - - -void ColorSwatch::allow(Qt::DockWidgetArea area, bool a) -{ - Qt::DockWidgetAreas areas = allowedAreas(); - areas = a ? areas | area : areas & ~area; - setAllowedAreas(areas); - - if (areaActions->isEnabled()) { - leftAction->setEnabled(areas & Qt::LeftDockWidgetArea); - rightAction->setEnabled(areas & Qt::RightDockWidgetArea); - topAction->setEnabled(areas & Qt::TopDockWidgetArea); - bottomAction->setEnabled(areas & Qt::BottomDockWidgetArea); - } -} - -void ColorSwatch::place(Qt::DockWidgetArea area, bool p) -{ - if (!p) return; - - QMainWindow *mainWindow = qobject_cast(parentWidget()); - mainWindow->addDockWidget(area, this); - - if (allowedAreasActions->isEnabled()) { - allowLeftAction->setEnabled(area != Qt::LeftDockWidgetArea); - allowRightAction->setEnabled(area != Qt::RightDockWidgetArea); - allowTopAction->setEnabled(area != Qt::TopDockWidgetArea); - allowBottomAction->setEnabled(area != Qt::BottomDockWidgetArea); - } -} - -void ColorSwatch::setCustomSizeHint(const QSize &size) -{ - if (ColorDock *dock = qobject_cast(widget())) - dock->setCustomSizeHint(size); -} - -void ColorSwatch::changeClosable(bool on) -{ setFeatures(on ? features() | DockWidgetClosable : features() & ~DockWidgetClosable); } - -void ColorSwatch::changeMovable(bool on) -{ setFeatures(on ? features() | DockWidgetMovable : features() & ~DockWidgetMovable); } - -void ColorSwatch::changeFloatable(bool on) -{ setFeatures(on ? features() | DockWidgetFloatable : features() & ~DockWidgetFloatable); } - -void ColorSwatch::changeFloating(bool floating) -{ setFloating(floating); } - -void ColorSwatch::allowLeft(bool a) -{ allow(Qt::LeftDockWidgetArea, a); } - -void ColorSwatch::allowRight(bool a) -{ allow(Qt::RightDockWidgetArea, a); } - -void ColorSwatch::allowTop(bool a) -{ allow(Qt::TopDockWidgetArea, a); } - -void ColorSwatch::allowBottom(bool a) -{ allow(Qt::BottomDockWidgetArea, a); } - -void ColorSwatch::placeLeft(bool p) -{ place(Qt::LeftDockWidgetArea, p); } - -void ColorSwatch::placeRight(bool p) -{ place(Qt::RightDockWidgetArea, p); } - -void ColorSwatch::placeTop(bool p) -{ place(Qt::TopDockWidgetArea, p); } - -void ColorSwatch::placeBottom(bool p) -{ place(Qt::BottomDockWidgetArea, p); } - -void ColorSwatch::changeVerticalTitleBar(bool on) -{ - setFeatures(on ? features() | DockWidgetVerticalTitleBar - : features() & ~DockWidgetVerticalTitleBar); -} - -QSize BlueTitleBar::minimumSizeHint() const -{ - QDockWidget *dw = qobject_cast(parentWidget()); - Q_ASSERT(dw != 0); - QSize result(leftPm.width() + rightPm.width(), centerPm.height()); - if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) - result.transpose(); - return result; -} - -BlueTitleBar::BlueTitleBar(QWidget *parent) - : QWidget(parent) -{ - leftPm = QPixmap(":/res/titlebarLeft.png"); - centerPm = QPixmap(":/res/titlebarCenter.png"); - rightPm = QPixmap(":/res/titlebarRight.png"); -} - -void BlueTitleBar::paintEvent(QPaintEvent*) -{ - QPainter painter(this); - QRect rect = this->rect(); - - QDockWidget *dw = qobject_cast(parentWidget()); - Q_ASSERT(dw != 0); - - if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) { - QSize s = rect.size(); - s.transpose(); - rect.setSize(s); - - painter.translate(rect.left(), rect.top() + rect.width()); - painter.rotate(-90); - painter.translate(-rect.left(), -rect.top()); - } - - painter.drawPixmap(rect.topLeft(), leftPm); - painter.drawPixmap(rect.topRight() - QPoint(rightPm.width() - 1, 0), rightPm); - QBrush brush(centerPm); - painter.fillRect(rect.left() + leftPm.width(), rect.top(), - rect.width() - leftPm.width() - rightPm.width(), - centerPm.height(), centerPm); -} - -void BlueTitleBar::mousePressEvent(QMouseEvent *event) -{ - QPoint pos = event->pos(); - - QRect rect = this->rect(); - - QDockWidget *dw = qobject_cast(parentWidget()); - Q_ASSERT(dw != 0); - - if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) { - QPoint p = pos; - pos.setX(rect.left() + rect.bottom() - p.y()); - pos.setY(rect.top() + p.x() - rect.left()); - - QSize s = rect.size(); - s.transpose(); - rect.setSize(s); - } - - const int buttonRight = 7; - const int buttonWidth = 20; - int right = rect.right() - pos.x(); - int button = (right - buttonRight)/buttonWidth; - switch (button) { - case 0: - event->accept(); - dw->close(); - break; - case 1: - event->accept(); - dw->setFloating(!dw->isFloating()); - break; - case 2: { - event->accept(); - QDockWidget::DockWidgetFeatures features = dw->features(); - if (features & QDockWidget::DockWidgetVerticalTitleBar) - features &= ~QDockWidget::DockWidgetVerticalTitleBar; - else - features |= QDockWidget::DockWidgetVerticalTitleBar; - dw->setFeatures(features); - break; - } - default: - event->ignore(); - break; - } -} - -void BlueTitleBar::updateMask() -{ - QDockWidget *dw = qobject_cast(parent()); - Q_ASSERT(dw != 0); - - QRect rect = dw->rect(); - QPixmap bitmap(dw->size()); - - { - QPainter painter(&bitmap); - - ///initialize to transparent - painter.fillRect(rect, Qt::color0); - - QRect contents = rect; - contents.setTopLeft(geometry().bottomLeft()); - contents.setRight(geometry().right()); - contents.setBottom(contents.bottom()-y()); - painter.fillRect(contents, Qt::color1); - - - - //let's pait the titlebar - - QRect titleRect = this->geometry(); - - if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) { - QSize s = rect.size(); - s.transpose(); - rect.setSize(s); - - QSize s2 = size(); - s2.transpose(); - titleRect.setSize(s2); - - painter.translate(rect.left(), rect.top() + rect.width()); - painter.rotate(-90); - painter.translate(-rect.left(), -rect.top()); - } - - contents.setTopLeft(titleRect.bottomLeft()); - contents.setRight(titleRect.right()); - contents.setBottom(rect.bottom()-y()); - - QRect rect = titleRect; - - - painter.drawPixmap(rect.topLeft(), leftPm.mask()); - painter.fillRect(rect.left() + leftPm.width(), rect.top(), - rect.width() - leftPm.width() - rightPm.width(), - centerPm.height(), Qt::color1); - painter.drawPixmap(rect.topRight() - QPoint(rightPm.width() - 1, 0), rightPm.mask()); - - painter.fillRect(contents, Qt::color1); - } - - dw->setMask(bitmap); -} - -#include "colorswatch.moc" diff --git a/demos/mainwindow/colorswatch.h b/demos/mainwindow/colorswatch.h deleted file mode 100644 index 555f1c6cd4..0000000000 --- a/demos/mainwindow/colorswatch.h +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef COLORSWATCH_H -#define COLORSWATCH_H - -#include - -QT_FORWARD_DECLARE_CLASS(QAction) -QT_FORWARD_DECLARE_CLASS(QActionGroup) -QT_FORWARD_DECLARE_CLASS(QMenu) - -class ColorSwatch : public QDockWidget -{ - Q_OBJECT - - QAction *closableAction; - QAction *movableAction; - QAction *floatableAction; - QAction *floatingAction; - QAction *verticalTitleBarAction; - - QActionGroup *allowedAreasActions; - QAction *allowLeftAction; - QAction *allowRightAction; - QAction *allowTopAction; - QAction *allowBottomAction; - - QActionGroup *areaActions; - QAction *leftAction; - QAction *rightAction; - QAction *topAction; - QAction *bottomAction; - - QAction *changeSizeHintsAction; - - QMenu *tabMenu; - QMenu *splitHMenu; - QMenu *splitVMenu; - - QAction *windowModifiedAction; - -public: - ColorSwatch(const QString &colorName, QWidget *parent = 0, Qt::WindowFlags flags = 0); - - QMenu *menu; - void setCustomSizeHint(const QSize &size); - -protected: - virtual void contextMenuEvent(QContextMenuEvent *event); - virtual void resizeEvent(QResizeEvent *e); - -private: - void allow(Qt::DockWidgetArea area, bool allow); - void place(Qt::DockWidgetArea area, bool place); - -private slots: - void changeClosable(bool on); - void changeMovable(bool on); - void changeFloatable(bool on); - void changeFloating(bool on); - void changeVerticalTitleBar(bool on); - void updateContextMenu(); - - void allowLeft(bool a); - void allowRight(bool a); - void allowTop(bool a); - void allowBottom(bool a); - - void placeLeft(bool p); - void placeRight(bool p); - void placeTop(bool p); - void placeBottom(bool p); - - void splitInto(QAction *action); - void tabInto(QAction *action); -}; - -class BlueTitleBar : public QWidget -{ - Q_OBJECT -public: - BlueTitleBar(QWidget *parent = 0); - - QSize sizeHint() const { return minimumSizeHint(); } - QSize minimumSizeHint() const; -protected: - void paintEvent(QPaintEvent *event); - void mousePressEvent(QMouseEvent *event); -public slots: - void updateMask(); - -private: - QPixmap leftPm, centerPm, rightPm; -}; - - -#endif diff --git a/demos/mainwindow/main.cpp b/demos/mainwindow/main.cpp deleted file mode 100644 index 71cff13cb8..0000000000 --- a/demos/mainwindow/main.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "mainwindow.h" - -#include -#include -#include -#include -#include - -void render_qt_text(QPainter *painter, int w, int h, const QColor &color) { - QPainterPath path; - path.moveTo(-0.083695, 0.283849); - path.cubicTo(-0.049581, 0.349613, -0.012720, 0.397969, 0.026886, 0.428917); - path.cubicTo(0.066493, 0.459865, 0.111593, 0.477595, 0.162186, 0.482108); - path.lineTo(0.162186, 0.500000); - path.cubicTo(0.115929, 0.498066, 0.066565, 0.487669, 0.014094, 0.468810); - path.cubicTo(-0.038378, 0.449952, -0.088103, 0.423839, -0.135082, 0.390474); - path.cubicTo(-0.182061, 0.357108, -0.222608, 0.321567, -0.256722, 0.283849); - path.cubicTo(-0.304712, 0.262250, -0.342874, 0.239362, -0.371206, 0.215184); - path.cubicTo(-0.411969, 0.179078, -0.443625, 0.134671, -0.466175, 0.081963); - path.cubicTo(-0.488725, 0.029255, -0.500000, -0.033043, -0.500000, -0.104932); - path.cubicTo(-0.500000, -0.218407, -0.467042, -0.312621, -0.401127, -0.387573); - path.cubicTo(-0.335212, -0.462524, -0.255421, -0.500000, -0.161752, -0.500000); - path.cubicTo(-0.072998, -0.500000, 0.003903, -0.462444, 0.068951, -0.387331); - path.cubicTo(0.133998, -0.312218, 0.166522, -0.217440, 0.166522, -0.102998); - path.cubicTo(0.166522, -0.010155, 0.143394, 0.071325, 0.097138, 0.141441); - path.cubicTo(0.050882, 0.211557, -0.009396, 0.259026, -0.083695, 0.283849); - path.moveTo(-0.167823, -0.456963); - path.cubicTo(-0.228823, -0.456963, -0.277826, -0.432624, -0.314831, -0.383946); - path.cubicTo(-0.361665, -0.323340, -0.385082, -0.230335, -0.385082, -0.104932); - path.cubicTo(-0.385082, 0.017569, -0.361376, 0.112025, -0.313964, 0.178433); - path.cubicTo(-0.277248, 0.229368, -0.228534, 0.254836, -0.167823, 0.254836); - path.cubicTo(-0.105088, 0.254836, -0.054496, 0.229368, -0.016045, 0.178433); - path.cubicTo(0.029055, 0.117827, 0.051605, 0.028691, 0.051605, -0.088975); - path.cubicTo(0.051605, -0.179562, 0.039318, -0.255803, 0.014744, -0.317698); - path.cubicTo(-0.004337, -0.365409, -0.029705, -0.400548, -0.061362, -0.423114); - path.cubicTo(-0.093018, -0.445680, -0.128505, -0.456963, -0.167823, -0.456963); - path.moveTo(0.379011, -0.404739); - path.lineTo(0.379011, -0.236460); - path.lineTo(0.486123, -0.236460); - path.lineTo(0.486123, -0.197292); - path.lineTo(0.379011, -0.197292); - path.lineTo(0.379011, 0.134913); - path.cubicTo(0.379011, 0.168117, 0.383276, 0.190442, 0.391804, 0.201886); - path.cubicTo(0.400332, 0.213330, 0.411246, 0.219052, 0.424545, 0.219052); - path.cubicTo(0.435531, 0.219052, 0.446227, 0.215264, 0.456635, 0.207689); - path.cubicTo(0.467042, 0.200113, 0.474993, 0.188910, 0.480486, 0.174081); - path.lineTo(0.500000, 0.174081); - path.cubicTo(0.488436, 0.210509, 0.471957, 0.237911, 0.450564, 0.256286); - path.cubicTo(0.429170, 0.274662, 0.407054, 0.283849, 0.384215, 0.283849); - path.cubicTo(0.368893, 0.283849, 0.353859, 0.279094, 0.339115, 0.269584); - path.cubicTo(0.324371, 0.260074, 0.313530, 0.246534, 0.306592, 0.228965); - path.cubicTo(0.299653, 0.211396, 0.296184, 0.184075, 0.296184, 0.147002); - path.lineTo(0.296184, -0.197292); - path.lineTo(0.223330, -0.197292); - path.lineTo(0.223330, -0.215667); - path.cubicTo(0.241833, -0.224049, 0.260697, -0.237992, 0.279922, -0.257495); - path.cubicTo(0.299147, -0.276999, 0.316276, -0.300129, 0.331310, -0.326886); - path.cubicTo(0.338826, -0.341070, 0.349523, -0.367021, 0.363400, -0.404739); - path.lineTo(0.379011, -0.404739); - path.moveTo(-0.535993, 0.275629); - - painter->translate(w / 2, h / 2); - double scale = qMin(w, h) * 8 / 10.0; - painter->scale(scale, scale); - - painter->setRenderHint(QPainter::Antialiasing); - - painter->save(); - painter->translate(.1, .1); - painter->fillPath(path, QColor(0, 0, 0, 63)); - painter->restore(); - - painter->setBrush(color); - painter->setPen(QPen(Qt::black, 0.02, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); - painter->drawPath(path); -} - -void usage() -{ - qWarning() << "Usage: mainwindow [-SizeHint x] ..."; - exit(1); -} - -QMap parseCustomSizeHints(int argc, char **argv) -{ - QMap result; - - for (int i = 1; i < argc; ++i) { - QString arg = QString::fromLocal8Bit(argv[i]); - - if (arg.startsWith(QLatin1String("-SizeHint"))) { - QString name = arg.mid(9); - if (name.isEmpty()) - usage(); - if (++i == argc) - usage(); - QString sizeStr = QString::fromLocal8Bit(argv[i]); - int idx = sizeStr.indexOf(QLatin1Char('x')); - if (idx == -1) - usage(); - bool ok; - int w = sizeStr.left(idx).toInt(&ok); - if (!ok) - usage(); - int h = sizeStr.mid(idx + 1).toInt(&ok); - if (!ok) - usage(); - result[name] = QSize(w, h); - } - } - - return result; -} - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - QMap customSizeHints = parseCustomSizeHints(argc, argv); - MainWindow mainWin(customSizeHints); - mainWin.resize(800, 600); - mainWin.show(); - return app.exec(); -} diff --git a/demos/mainwindow/mainwindow.cpp b/demos/mainwindow/mainwindow.cpp deleted file mode 100644 index a58a713c0b..0000000000 --- a/demos/mainwindow/mainwindow.cpp +++ /dev/null @@ -1,514 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "mainwindow.h" -#include "colorswatch.h" -#include "toolbar.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static const char * const message = - "

Qt Main Window Demo

" - - "

This is a demonstration of the QMainWindow, QToolBar and " - "QDockWidget classes.

" - - "

The tool bar and dock widgets can be dragged around and rearranged " - "using the mouse or via the menu.

" - - "

Each dock widget contains a colored frame and a context " - "(right-click) menu.

" - -#ifdef Q_WS_MAC - "

On Mac OS X, the \"Black\" dock widget has been created as a " - "Drawer, which is a special kind of QDockWidget.

" -#endif - ; - -Q_DECLARE_METATYPE(QDockWidget::DockWidgetFeatures) - -MainWindow::MainWindow(const QMap &customSizeHints, - QWidget *parent, Qt::WindowFlags flags) - : QMainWindow(parent, flags) -{ - setObjectName("MainWindow"); - setWindowTitle("Qt Main Window Demo"); - - center = new QTextEdit(this); - center->setReadOnly(true); - center->setMinimumSize(400, 205); - setCentralWidget(center); - - setupToolBar(); - setupMenuBar(); - setupDockWidgets(customSizeHints); - - statusBar()->showMessage(tr("Status Bar")); -} - -void MainWindow::actionTriggered(QAction *action) -{ - qDebug("action '%s' triggered", action->text().toLocal8Bit().data()); -} - -void MainWindow::setupToolBar() -{ - for (int i = 0; i < 3; ++i) { - ToolBar *tb = new ToolBar(QString::fromLatin1("Tool Bar %1").arg(i + 1), this); - toolBars.append(tb); - addToolBar(tb); - } -} - -void MainWindow::setupMenuBar() -{ - QMenu *menu = menuBar()->addMenu(tr("&File")); - - QAction *action = menu->addAction(tr("Save layout...")); - connect(action, SIGNAL(triggered()), this, SLOT(saveLayout())); - - action = menu->addAction(tr("Load layout...")); - connect(action, SIGNAL(triggered()), this, SLOT(loadLayout())); - - action = menu->addAction(tr("Switch layout direction")); - connect(action, SIGNAL(triggered()), this, SLOT(switchLayoutDirection())); - - menu->addSeparator(); - - menu->addAction(tr("&Quit"), this, SLOT(close())); - - mainWindowMenu = menuBar()->addMenu(tr("Main window")); - - action = mainWindowMenu->addAction(tr("Animated docks")); - action->setCheckable(true); - action->setChecked(dockOptions() & AnimatedDocks); - connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); - - action = mainWindowMenu->addAction(tr("Allow nested docks")); - action->setCheckable(true); - action->setChecked(dockOptions() & AllowNestedDocks); - connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); - - action = mainWindowMenu->addAction(tr("Allow tabbed docks")); - action->setCheckable(true); - action->setChecked(dockOptions() & AllowTabbedDocks); - connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); - - action = mainWindowMenu->addAction(tr("Force tabbed docks")); - action->setCheckable(true); - action->setChecked(dockOptions() & ForceTabbedDocks); - connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); - - action = mainWindowMenu->addAction(tr("Vertical tabs")); - action->setCheckable(true); - action->setChecked(dockOptions() & VerticalTabs); - connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); - - QMenu *toolBarMenu = menuBar()->addMenu(tr("Tool bars")); - for (int i = 0; i < toolBars.count(); ++i) - toolBarMenu->addMenu(toolBars.at(i)->menu); - - dockWidgetMenu = menuBar()->addMenu(tr("&Dock Widgets")); -} - -void MainWindow::setDockOptions() -{ - DockOptions opts; - QList actions = mainWindowMenu->actions(); - - if (actions.at(0)->isChecked()) - opts |= AnimatedDocks; - if (actions.at(1)->isChecked()) - opts |= AllowNestedDocks; - if (actions.at(2)->isChecked()) - opts |= AllowTabbedDocks; - if (actions.at(3)->isChecked()) - opts |= ForceTabbedDocks; - if (actions.at(4)->isChecked()) - opts |= VerticalTabs; - - QMainWindow::setDockOptions(opts); -} - -void MainWindow::saveLayout() -{ - QString fileName - = QFileDialog::getSaveFileName(this, tr("Save layout")); - if (fileName.isEmpty()) - return; - QFile file(fileName); - if (!file.open(QFile::WriteOnly)) { - QString msg = tr("Failed to open %1\n%2") - .arg(fileName) - .arg(file.errorString()); - QMessageBox::warning(this, tr("Error"), msg); - return; - } - - QByteArray geo_data = saveGeometry(); - QByteArray layout_data = saveState(); - - bool ok = file.putChar((uchar)geo_data.size()); - if (ok) - ok = file.write(geo_data) == geo_data.size(); - if (ok) - ok = file.write(layout_data) == layout_data.size(); - - if (!ok) { - QString msg = tr("Error writing to %1\n%2") - .arg(fileName) - .arg(file.errorString()); - QMessageBox::warning(this, tr("Error"), msg); - return; - } -} - -void MainWindow::loadLayout() -{ - QString fileName - = QFileDialog::getOpenFileName(this, tr("Load layout")); - if (fileName.isEmpty()) - return; - QFile file(fileName); - if (!file.open(QFile::ReadOnly)) { - QString msg = tr("Failed to open %1\n%2") - .arg(fileName) - .arg(file.errorString()); - QMessageBox::warning(this, tr("Error"), msg); - return; - } - - uchar geo_size; - QByteArray geo_data; - QByteArray layout_data; - - bool ok = file.getChar((char*)&geo_size); - if (ok) { - geo_data = file.read(geo_size); - ok = geo_data.size() == geo_size; - } - if (ok) { - layout_data = file.readAll(); - ok = layout_data.size() > 0; - } - - if (ok) - ok = restoreGeometry(geo_data); - if (ok) - ok = restoreState(layout_data); - - if (!ok) { - QString msg = tr("Error reading %1") - .arg(fileName); - QMessageBox::warning(this, tr("Error"), msg); - return; - } -} - -QAction *addAction(QMenu *menu, const QString &text, QActionGroup *group, QSignalMapper *mapper, - int id) -{ - bool first = group->actions().isEmpty(); - QAction *result = menu->addAction(text); - result->setCheckable(true); - result->setChecked(first); - group->addAction(result); - QObject::connect(result, SIGNAL(triggered()), mapper, SLOT(map())); - mapper->setMapping(result, id); - return result; -} - -void MainWindow::setupDockWidgets(const QMap &customSizeHints) -{ - qRegisterMetaType(); - - mapper = new QSignalMapper(this); - connect(mapper, SIGNAL(mapped(int)), this, SLOT(setCorner(int))); - - QMenu *corner_menu = dockWidgetMenu->addMenu(tr("Top left corner")); - QActionGroup *group = new QActionGroup(this); - group->setExclusive(true); - ::addAction(corner_menu, tr("Top dock area"), group, mapper, 0); - ::addAction(corner_menu, tr("Left dock area"), group, mapper, 1); - - corner_menu = dockWidgetMenu->addMenu(tr("Top right corner")); - group = new QActionGroup(this); - group->setExclusive(true); - ::addAction(corner_menu, tr("Top dock area"), group, mapper, 2); - ::addAction(corner_menu, tr("Right dock area"), group, mapper, 3); - - corner_menu = dockWidgetMenu->addMenu(tr("Bottom left corner")); - group = new QActionGroup(this); - group->setExclusive(true); - ::addAction(corner_menu, tr("Bottom dock area"), group, mapper, 4); - ::addAction(corner_menu, tr("Left dock area"), group, mapper, 5); - - corner_menu = dockWidgetMenu->addMenu(tr("Bottom right corner")); - group = new QActionGroup(this); - group->setExclusive(true); - ::addAction(corner_menu, tr("Bottom dock area"), group, mapper, 6); - ::addAction(corner_menu, tr("Right dock area"), group, mapper, 7); - - dockWidgetMenu->addSeparator(); - - static const struct Set { - const char * name; - uint flags; - Qt::DockWidgetArea area; - } sets [] = { -#ifndef Q_WS_MAC - { "Black", 0, Qt::LeftDockWidgetArea }, -#else - { "Black", Qt::Drawer, Qt::LeftDockWidgetArea }, -#endif - { "White", 0, Qt::RightDockWidgetArea }, - { "Red", 0, Qt::TopDockWidgetArea }, - { "Green", 0, Qt::TopDockWidgetArea }, - { "Blue", 0, Qt::BottomDockWidgetArea }, - { "Yellow", 0, Qt::BottomDockWidgetArea } - }; - const int setCount = sizeof(sets) / sizeof(Set); - - for (int i = 0; i < setCount; ++i) { - ColorSwatch *swatch = new ColorSwatch(tr(sets[i].name), this, Qt::WindowFlags(sets[i].flags)); - if (i%2) - swatch->setWindowIcon(QIcon(QPixmap(":/res/qt.png"))); - if (qstrcmp(sets[i].name, "Blue") == 0) { - BlueTitleBar *titlebar = new BlueTitleBar(swatch); - swatch->setTitleBarWidget(titlebar); - connect(swatch, SIGNAL(topLevelChanged(bool)), titlebar, SLOT(updateMask())); - connect(swatch, SIGNAL(featuresChanged(QDockWidget::DockWidgetFeatures)), titlebar, SLOT(updateMask()), Qt::QueuedConnection); - -#ifdef Q_WS_QWS - QPalette pal = palette(); - pal.setBrush(backgroundRole(), QColor(0,0,0,0)); - swatch->setPalette(pal); -#endif - } - - QString name = QString::fromLatin1(sets[i].name); - if (customSizeHints.contains(name)) - swatch->setCustomSizeHint(customSizeHints.value(name)); - - addDockWidget(sets[i].area, swatch); - dockWidgetMenu->addMenu(swatch->menu); - } - - createDockWidgetAction = new QAction(tr("Add dock widget..."), this); - connect(createDockWidgetAction, SIGNAL(triggered()), this, SLOT(createDockWidget())); - destroyDockWidgetMenu = new QMenu(tr("Destroy dock widget"), this); - destroyDockWidgetMenu->setEnabled(false); - connect(destroyDockWidgetMenu, SIGNAL(triggered(QAction*)), this, SLOT(destroyDockWidget(QAction*))); - - dockWidgetMenu->addSeparator(); - dockWidgetMenu->addAction(createDockWidgetAction); - dockWidgetMenu->addMenu(destroyDockWidgetMenu); -} - -void MainWindow::setCorner(int id) -{ - switch (id) { - case 0: - QMainWindow::setCorner(Qt::TopLeftCorner, Qt::TopDockWidgetArea); - break; - case 1: - QMainWindow::setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); - break; - case 2: - QMainWindow::setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea); - break; - case 3: - QMainWindow::setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); - break; - case 4: - QMainWindow::setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); - break; - case 5: - QMainWindow::setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); - break; - case 6: - QMainWindow::setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea); - break; - case 7: - QMainWindow::setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); - break; - } -} - -void MainWindow::showEvent(QShowEvent *event) -{ - QMainWindow::showEvent(event); -} - -void MainWindow::switchLayoutDirection() -{ - if (layoutDirection() == Qt::LeftToRight) - qApp->setLayoutDirection(Qt::RightToLeft); - else - qApp->setLayoutDirection(Qt::LeftToRight); -} - -class CreateDockWidgetDialog : public QDialog -{ -public: - CreateDockWidgetDialog(QWidget *parent = 0); - - QString objectName() const; - Qt::DockWidgetArea location() const; - -private: - QLineEdit *m_objectName; - QComboBox *m_location; -}; - -CreateDockWidgetDialog::CreateDockWidgetDialog(QWidget *parent) - : QDialog(parent) -{ - QGridLayout *layout = new QGridLayout(this); - - layout->addWidget(new QLabel(tr("Object name:")), 0, 0); - m_objectName = new QLineEdit; - layout->addWidget(m_objectName, 0, 1); - - layout->addWidget(new QLabel(tr("Location:")), 1, 0); - m_location = new QComboBox; - m_location->setEditable(false); - m_location->addItem(tr("Top")); - m_location->addItem(tr("Left")); - m_location->addItem(tr("Right")); - m_location->addItem(tr("Bottom")); - m_location->addItem(tr("Restore")); - layout->addWidget(m_location, 1, 1); - - QHBoxLayout *buttonLayout = new QHBoxLayout; - layout->addLayout(buttonLayout, 2, 0, 1, 2); - buttonLayout->addStretch(); - - QPushButton *cancelButton = new QPushButton(tr("Cancel")); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); - buttonLayout->addWidget(cancelButton); - QPushButton *okButton = new QPushButton(tr("Ok")); - connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); - buttonLayout->addWidget(okButton); - - okButton->setDefault(true); -} - -QString CreateDockWidgetDialog::objectName() const -{ - return m_objectName->text(); -} - -Qt::DockWidgetArea CreateDockWidgetDialog::location() const -{ - switch (m_location->currentIndex()) { - case 0: return Qt::TopDockWidgetArea; - case 1: return Qt::LeftDockWidgetArea; - case 2: return Qt::RightDockWidgetArea; - case 3: return Qt::BottomDockWidgetArea; - default: - break; - } - return Qt::NoDockWidgetArea; -} - -void MainWindow::createDockWidget() -{ - CreateDockWidgetDialog dialog(this); - int ret = dialog.exec(); - if (ret == QDialog::Rejected) - return; - - QDockWidget *dw = new QDockWidget; - dw->setObjectName(dialog.objectName()); - dw->setWindowTitle(dialog.objectName()); - dw->setWidget(new QTextEdit); - - Qt::DockWidgetArea area = dialog.location(); - switch (area) { - case Qt::LeftDockWidgetArea: - case Qt::RightDockWidgetArea: - case Qt::TopDockWidgetArea: - case Qt::BottomDockWidgetArea: - addDockWidget(area, dw); - break; - default: - if (!restoreDockWidget(dw)) { - QMessageBox::warning(this, QString(), tr("Failed to restore dock widget")); - delete dw; - return; - } - break; - } - - extraDockWidgets.append(dw); - destroyDockWidgetMenu->setEnabled(true); - destroyDockWidgetMenu->addAction(new QAction(dialog.objectName(), this)); -} - -void MainWindow::destroyDockWidget(QAction *action) -{ - int index = destroyDockWidgetMenu->actions().indexOf(action); - delete extraDockWidgets.takeAt(index); - destroyDockWidgetMenu->removeAction(action); - action->deleteLater(); - - if (destroyDockWidgetMenu->isEmpty()) - destroyDockWidgetMenu->setEnabled(false); -} diff --git a/demos/mainwindow/mainwindow.h b/demos/mainwindow/mainwindow.h deleted file mode 100644 index aa01ffa131..0000000000 --- a/demos/mainwindow/mainwindow.h +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include -#include - -class ToolBar; -QT_FORWARD_DECLARE_CLASS(QMenu) -QT_FORWARD_DECLARE_CLASS(QSignalMapper) - -class MainWindow : public QMainWindow -{ - Q_OBJECT - - QTextEdit *center; - QList toolBars; - QMenu *dockWidgetMenu; - QMenu *mainWindowMenu; - QSignalMapper *mapper; - QList extraDockWidgets; - QAction *createDockWidgetAction; - QMenu *destroyDockWidgetMenu; - -public: - MainWindow(const QMap &customSizeHints, - QWidget *parent = 0, Qt::WindowFlags flags = 0); - -protected: - void showEvent(QShowEvent *event); - -public slots: - void actionTriggered(QAction *action); - void saveLayout(); - void loadLayout(); - void setCorner(int id); - void switchLayoutDirection(); - void setDockOptions(); - - void createDockWidget(); - void destroyDockWidget(QAction *action); - -private: - void setupToolBar(); - void setupMenuBar(); - void setupDockWidgets(const QMap &customSizeHints); -}; - - -#endif diff --git a/demos/mainwindow/mainwindow.pro b/demos/mainwindow/mainwindow.pro deleted file mode 100644 index 6da113d722..0000000000 --- a/demos/mainwindow/mainwindow.pro +++ /dev/null @@ -1,17 +0,0 @@ -TEMPLATE = app -HEADERS += colorswatch.h mainwindow.h toolbar.h -SOURCES += colorswatch.cpp mainwindow.cpp toolbar.cpp main.cpp -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -RESOURCES += mainwindow.qrc - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/mainwindow -sources.files = $$SOURCES $$HEADERS $$FORMS $$RESOURCES *.png *.jpg *.pro -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/mainwindow -INSTALLS += target sources - -symbian: CONFIG += qt_demo diff --git a/demos/mainwindow/mainwindow.qrc b/demos/mainwindow/mainwindow.qrc deleted file mode 100644 index 47ff22a3e4..0000000000 --- a/demos/mainwindow/mainwindow.qrc +++ /dev/null @@ -1,8 +0,0 @@ - - - qt.png - titlebarLeft.png - titlebarCenter.png - titlebarRight.png - - diff --git a/demos/mainwindow/qt.png b/demos/mainwindow/qt.png deleted file mode 100644 index 48fa9fc2ef..0000000000 Binary files a/demos/mainwindow/qt.png and /dev/null differ diff --git a/demos/mainwindow/titlebarCenter.png b/demos/mainwindow/titlebarCenter.png deleted file mode 100644 index 5cc141355c..0000000000 Binary files a/demos/mainwindow/titlebarCenter.png and /dev/null differ diff --git a/demos/mainwindow/titlebarLeft.png b/demos/mainwindow/titlebarLeft.png deleted file mode 100644 index 315166202b..0000000000 Binary files a/demos/mainwindow/titlebarLeft.png and /dev/null differ diff --git a/demos/mainwindow/titlebarRight.png b/demos/mainwindow/titlebarRight.png deleted file mode 100644 index a4505268ec..0000000000 Binary files a/demos/mainwindow/titlebarRight.png and /dev/null differ diff --git a/demos/mainwindow/toolbar.cpp b/demos/mainwindow/toolbar.cpp deleted file mode 100644 index 1176ee5480..0000000000 --- a/demos/mainwindow/toolbar.cpp +++ /dev/null @@ -1,383 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "toolbar.h" - -#include -#include -#include -#include -#include -#include -#include - -#include - -static QPixmap genIcon(const QSize &iconSize, const QString &, const QColor &color) -{ - int w = iconSize.width(); - int h = iconSize.height(); - - QImage image(w, h, QImage::Format_ARGB32_Premultiplied); - image.fill(0); - - QPainter p(&image); - - extern void render_qt_text(QPainter *, int, int, const QColor &); - render_qt_text(&p, w, h, color); - - return QPixmap::fromImage(image, Qt::DiffuseDither | Qt::DiffuseAlphaDither); -} - -static QPixmap genIcon(const QSize &iconSize, int number, const QColor &color) -{ return genIcon(iconSize, QString::number(number), color); } - -ToolBar::ToolBar(const QString &title, QWidget *parent) - : QToolBar(parent), spinbox(0), spinboxAction(0) -{ - tip = 0; - setWindowTitle(title); - setObjectName(title); - - setIconSize(QSize(32, 32)); - - QColor bg(palette().background().color()); - menu = new QMenu("One", this); - menu->setIcon(genIcon(iconSize(), 1, Qt::black)); - menu->addAction(genIcon(iconSize(), "A", Qt::blue), "A"); - menu->addAction(genIcon(iconSize(), "B", Qt::blue), "B"); - menu->addAction(genIcon(iconSize(), "C", Qt::blue), "C"); - addAction(menu->menuAction()); - - QAction *two = addAction(genIcon(iconSize(), 2, Qt::white), "Two"); - QFont boldFont; - boldFont.setBold(true); - two->setFont(boldFont); - - addAction(genIcon(iconSize(), 3, Qt::red), "Three"); - addAction(genIcon(iconSize(), 4, Qt::green), "Four"); - addAction(genIcon(iconSize(), 5, Qt::blue), "Five"); - addAction(genIcon(iconSize(), 6, Qt::yellow), "Six"); - orderAction = new QAction(this); - orderAction->setText(tr("Order Items in Tool Bar")); - connect(orderAction, SIGNAL(triggered()), SLOT(order())); - - randomizeAction = new QAction(this); - randomizeAction->setText(tr("Randomize Items in Tool Bar")); - connect(randomizeAction, SIGNAL(triggered()), SLOT(randomize())); - - addSpinBoxAction = new QAction(this); - addSpinBoxAction->setText(tr("Add Spin Box")); - connect(addSpinBoxAction, SIGNAL(triggered()), SLOT(addSpinBox())); - - removeSpinBoxAction = new QAction(this); - removeSpinBoxAction->setText(tr("Remove Spin Box")); - removeSpinBoxAction->setEnabled(false); - connect(removeSpinBoxAction, SIGNAL(triggered()), SLOT(removeSpinBox())); - - movableAction = new QAction(tr("Movable"), this); - movableAction->setCheckable(true); - connect(movableAction, SIGNAL(triggered(bool)), SLOT(changeMovable(bool))); - - allowedAreasActions = new QActionGroup(this); - allowedAreasActions->setExclusive(false); - - allowLeftAction = new QAction(tr("Allow on Left"), this); - allowLeftAction->setCheckable(true); - connect(allowLeftAction, SIGNAL(triggered(bool)), SLOT(allowLeft(bool))); - - allowRightAction = new QAction(tr("Allow on Right"), this); - allowRightAction->setCheckable(true); - connect(allowRightAction, SIGNAL(triggered(bool)), SLOT(allowRight(bool))); - - allowTopAction = new QAction(tr("Allow on Top"), this); - allowTopAction->setCheckable(true); - connect(allowTopAction, SIGNAL(triggered(bool)), SLOT(allowTop(bool))); - - allowBottomAction = new QAction(tr("Allow on Bottom"), this); - allowBottomAction->setCheckable(true); - connect(allowBottomAction, SIGNAL(triggered(bool)), SLOT(allowBottom(bool))); - - allowedAreasActions->addAction(allowLeftAction); - allowedAreasActions->addAction(allowRightAction); - allowedAreasActions->addAction(allowTopAction); - allowedAreasActions->addAction(allowBottomAction); - - areaActions = new QActionGroup(this); - areaActions->setExclusive(true); - - leftAction = new QAction(tr("Place on Left") , this); - leftAction->setCheckable(true); - connect(leftAction, SIGNAL(triggered(bool)), SLOT(placeLeft(bool))); - - rightAction = new QAction(tr("Place on Right") , this); - rightAction->setCheckable(true); - connect(rightAction, SIGNAL(triggered(bool)), SLOT(placeRight(bool))); - - topAction = new QAction(tr("Place on Top") , this); - topAction->setCheckable(true); - connect(topAction, SIGNAL(triggered(bool)), SLOT(placeTop(bool))); - - bottomAction = new QAction(tr("Place on Bottom") , this); - bottomAction->setCheckable(true); - connect(bottomAction, SIGNAL(triggered(bool)), SLOT(placeBottom(bool))); - - areaActions->addAction(leftAction); - areaActions->addAction(rightAction); - areaActions->addAction(topAction); - areaActions->addAction(bottomAction); - - toolBarBreakAction = new QAction(tr("Insert break"), this); - connect(toolBarBreakAction, SIGNAL(triggered(bool)), this, SLOT(insertToolBarBreak())); - - connect(movableAction, SIGNAL(triggered(bool)), areaActions, SLOT(setEnabled(bool))); - - connect(movableAction, SIGNAL(triggered(bool)), allowedAreasActions, SLOT(setEnabled(bool))); - - menu = new QMenu(title, this); - menu->addAction(toggleViewAction()); - menu->addSeparator(); - menu->addAction(orderAction); - menu->addAction(randomizeAction); - menu->addSeparator(); - menu->addAction(addSpinBoxAction); - menu->addAction(removeSpinBoxAction); - menu->addSeparator(); - menu->addAction(movableAction); - menu->addSeparator(); - menu->addActions(allowedAreasActions->actions()); - menu->addSeparator(); - menu->addActions(areaActions->actions()); - menu->addSeparator(); - menu->addAction(toolBarBreakAction); - - connect(menu, SIGNAL(aboutToShow()), this, SLOT(updateMenu())); - - randomize(); -} - -void ToolBar::updateMenu() -{ - QMainWindow *mainWindow = qobject_cast(parentWidget()); - Q_ASSERT(mainWindow != 0); - - const Qt::ToolBarArea area = mainWindow->toolBarArea(this); - const Qt::ToolBarAreas areas = allowedAreas(); - - movableAction->setChecked(isMovable()); - - allowLeftAction->setChecked(isAreaAllowed(Qt::LeftToolBarArea)); - allowRightAction->setChecked(isAreaAllowed(Qt::RightToolBarArea)); - allowTopAction->setChecked(isAreaAllowed(Qt::TopToolBarArea)); - allowBottomAction->setChecked(isAreaAllowed(Qt::BottomToolBarArea)); - - if (allowedAreasActions->isEnabled()) { - allowLeftAction->setEnabled(area != Qt::LeftToolBarArea); - allowRightAction->setEnabled(area != Qt::RightToolBarArea); - allowTopAction->setEnabled(area != Qt::TopToolBarArea); - allowBottomAction->setEnabled(area != Qt::BottomToolBarArea); - } - - leftAction->setChecked(area == Qt::LeftToolBarArea); - rightAction->setChecked(area == Qt::RightToolBarArea); - topAction->setChecked(area == Qt::TopToolBarArea); - bottomAction->setChecked(area == Qt::BottomToolBarArea); - - if (areaActions->isEnabled()) { - leftAction->setEnabled(areas & Qt::LeftToolBarArea); - rightAction->setEnabled(areas & Qt::RightToolBarArea); - topAction->setEnabled(areas & Qt::TopToolBarArea); - bottomAction->setEnabled(areas & Qt::BottomToolBarArea); - } -} - -void ToolBar::order() -{ - QList ordered, actions1 = actions(), - actions2 = findChildren(); - while (!actions2.isEmpty()) { - QAction *action = actions2.takeFirst(); - if (!actions1.contains(action)) - continue; - actions1.removeAll(action); - ordered.append(action); - } - - clear(); - addActions(ordered); - - orderAction->setEnabled(false); -} - -void ToolBar::randomize() -{ - QList randomized, actions = this->actions(); - while (!actions.isEmpty()) { - QAction *action = actions.takeAt(rand() % actions.size()); - randomized.append(action); - } - clear(); - addActions(randomized); - - orderAction->setEnabled(true); -} - -void ToolBar::addSpinBox() -{ - if (!spinbox) { - spinbox = new QSpinBox(this); - } - if (!spinboxAction) - spinboxAction = addWidget(spinbox); - else - addAction(spinboxAction); - - addSpinBoxAction->setEnabled(false); - removeSpinBoxAction->setEnabled(true); -} - -void ToolBar::removeSpinBox() -{ - if (spinboxAction) - removeAction(spinboxAction); - - addSpinBoxAction->setEnabled(true); - removeSpinBoxAction->setEnabled(false); -} - -void ToolBar::allow(Qt::ToolBarArea area, bool a) -{ - Qt::ToolBarAreas areas = allowedAreas(); - areas = a ? areas | area : areas & ~area; - setAllowedAreas(areas); - - if (areaActions->isEnabled()) { - leftAction->setEnabled(areas & Qt::LeftToolBarArea); - rightAction->setEnabled(areas & Qt::RightToolBarArea); - topAction->setEnabled(areas & Qt::TopToolBarArea); - bottomAction->setEnabled(areas & Qt::BottomToolBarArea); - } -} - -void ToolBar::place(Qt::ToolBarArea area, bool p) -{ - if (!p) - return; - - QMainWindow *mainWindow = qobject_cast(parentWidget()); - Q_ASSERT(mainWindow != 0); - - mainWindow->addToolBar(area, this); - - if (allowedAreasActions->isEnabled()) { - allowLeftAction->setEnabled(area != Qt::LeftToolBarArea); - allowRightAction->setEnabled(area != Qt::RightToolBarArea); - allowTopAction->setEnabled(area != Qt::TopToolBarArea); - allowBottomAction->setEnabled(area != Qt::BottomToolBarArea); - } -} - -void ToolBar::changeMovable(bool movable) -{ setMovable(movable); } - -void ToolBar::allowLeft(bool a) -{ allow(Qt::LeftToolBarArea, a); } - -void ToolBar::allowRight(bool a) -{ allow(Qt::RightToolBarArea, a); } - -void ToolBar::allowTop(bool a) -{ allow(Qt::TopToolBarArea, a); } - -void ToolBar::allowBottom(bool a) -{ allow(Qt::BottomToolBarArea, a); } - -void ToolBar::placeLeft(bool p) -{ place(Qt::LeftToolBarArea, p); } - -void ToolBar::placeRight(bool p) -{ place(Qt::RightToolBarArea, p); } - -void ToolBar::placeTop(bool p) -{ place(Qt::TopToolBarArea, p); } - -void ToolBar::placeBottom(bool p) -{ place(Qt::BottomToolBarArea, p); } - -void ToolBar::insertToolBarBreak() -{ - QMainWindow *mainWindow = qobject_cast(parentWidget()); - Q_ASSERT(mainWindow != 0); - - mainWindow->insertToolBarBreak(this); -} - -void ToolBar::enterEvent(QEvent*) -{ -/* - These labels on top of toolbars look darn ugly - - if (tip == 0) { - tip = new QLabel(windowTitle(), this); - QPalette pal = tip->palette(); - QColor c = Qt::black; - c.setAlpha(100); - pal.setColor(QPalette::Window, c); - pal.setColor(QPalette::Foreground, Qt::white); - tip->setPalette(pal); - tip->setAutoFillBackground(true); - tip->setMargin(3); - tip->setText(windowTitle()); - } - QPoint c = rect().center(); - QSize hint = tip->sizeHint(); - tip->setGeometry(c.x() - hint.width()/2, c.y() - hint.height()/2, - hint.width(), hint.height()); - - tip->show(); -*/ -} - -void ToolBar::leaveEvent(QEvent*) -{ - if (tip != 0) - tip->hide(); -} diff --git a/demos/mainwindow/toolbar.h b/demos/mainwindow/toolbar.h deleted file mode 100644 index 5b982ee73b..0000000000 --- a/demos/mainwindow/toolbar.h +++ /dev/null @@ -1,118 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef TOOLBAR_H -#define TOOLBAR_H - -#include - -QT_FORWARD_DECLARE_CLASS(QAction) -QT_FORWARD_DECLARE_CLASS(QActionGroup) -QT_FORWARD_DECLARE_CLASS(QMenu) -QT_FORWARD_DECLARE_CLASS(QSpinBox) -QT_FORWARD_DECLARE_CLASS(QLabel) - -class ToolBar : public QToolBar -{ - Q_OBJECT - - QSpinBox *spinbox; - QAction *spinboxAction; - - QAction *orderAction; - QAction *randomizeAction; - QAction *addSpinBoxAction; - QAction *removeSpinBoxAction; - - QAction *movableAction; - - QActionGroup *allowedAreasActions; - QAction *allowLeftAction; - QAction *allowRightAction; - QAction *allowTopAction; - QAction *allowBottomAction; - - QActionGroup *areaActions; - QAction *leftAction; - QAction *rightAction; - QAction *topAction; - QAction *bottomAction; - - QAction *toolBarBreakAction; - -public: - ToolBar(const QString &title, QWidget *parent); - - QMenu *menu; - -protected: - void enterEvent(QEvent*); - void leaveEvent(QEvent*); - -private: - void allow(Qt::ToolBarArea area, bool allow); - void place(Qt::ToolBarArea area, bool place); - QLabel *tip; - -private slots: - void order(); - void randomize(); - void addSpinBox(); - void removeSpinBox(); - - void changeMovable(bool movable); - - void allowLeft(bool a); - void allowRight(bool a); - void allowTop(bool a); - void allowBottom(bool a); - - void placeLeft(bool p); - void placeRight(bool p); - void placeTop(bool p); - void placeBottom(bool p); - - void updateMenu(); - void insertToolBarBreak(); - -}; - -#endif diff --git a/demos/pathstroke/main.cpp b/demos/pathstroke/main.cpp deleted file mode 100644 index b357f99336..0000000000 --- a/demos/pathstroke/main.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "pathstroke.h" -#include - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(pathstroke); - - QApplication app(argc, argv); - - bool smallScreen = QApplication::arguments().contains("-small-screen"); - - PathStrokeWidget pathStrokeWidget(smallScreen); - QStyle *arthurStyle = new ArthurStyle(); - pathStrokeWidget.setStyle(arthurStyle); - QList widgets = pathStrokeWidget.findChildren(); - foreach (QWidget *w, widgets) { - w->setStyle(arthurStyle); - w->setAttribute(Qt::WA_AcceptTouchEvents); - } - - if (smallScreen) - pathStrokeWidget.showFullScreen(); - else - pathStrokeWidget.show(); - -#ifdef QT_KEYPAD_NAVIGATION - QApplication::setNavigationMode(Qt::NavigationModeCursorAuto); -#endif - return app.exec(); -} diff --git a/demos/pathstroke/pathstroke.cpp b/demos/pathstroke/pathstroke.cpp deleted file mode 100644 index 02c35f7721..0000000000 --- a/demos/pathstroke/pathstroke.cpp +++ /dev/null @@ -1,686 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "pathstroke.h" -#include "arthurstyle.h" -#include "arthurwidgets.h" - -#include - -extern void draw_round_rect(QPainter *p, const QRect &bounds, int radius); - - -PathStrokeControls::PathStrokeControls(QWidget* parent, PathStrokeRenderer* renderer, bool smallScreen) - : QWidget(parent) -{ - m_renderer = renderer; - - if (smallScreen) - layoutForSmallScreens(); - else - layoutForDesktop(); -} - -void PathStrokeControls::createCommonControls(QWidget* parent) -{ - m_capGroup = new QGroupBox(parent); - m_capGroup->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - QRadioButton *flatCap = new QRadioButton(m_capGroup); - QRadioButton *squareCap = new QRadioButton(m_capGroup); - QRadioButton *roundCap = new QRadioButton(m_capGroup); - m_capGroup->setTitle(tr("Cap Style")); - flatCap->setText(tr("Flat")); - squareCap->setText(tr("Square")); - roundCap->setText(tr("Round")); - flatCap->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - squareCap->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - roundCap->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - - m_joinGroup = new QGroupBox(parent); - m_joinGroup->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - QRadioButton *bevelJoin = new QRadioButton(m_joinGroup); - QRadioButton *miterJoin = new QRadioButton(m_joinGroup); - QRadioButton *roundJoin = new QRadioButton(m_joinGroup); - m_joinGroup->setTitle(tr("Join Style")); - bevelJoin->setText(tr("Bevel")); - miterJoin->setText(tr("Miter")); - roundJoin->setText(tr("Round")); - - m_styleGroup = new QGroupBox(parent); - m_styleGroup->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - QRadioButton *solidLine = new QRadioButton(m_styleGroup); - QRadioButton *dashLine = new QRadioButton(m_styleGroup); - QRadioButton *dotLine = new QRadioButton(m_styleGroup); - QRadioButton *dashDotLine = new QRadioButton(m_styleGroup); - QRadioButton *dashDotDotLine = new QRadioButton(m_styleGroup); - QRadioButton *customDashLine = new QRadioButton(m_styleGroup); - m_styleGroup->setTitle(tr("Pen Style")); - - QPixmap line_solid(":res/images/line_solid.png"); - solidLine->setIcon(line_solid); - solidLine->setIconSize(line_solid.size()); - QPixmap line_dashed(":res/images/line_dashed.png"); - dashLine->setIcon(line_dashed); - dashLine->setIconSize(line_dashed.size()); - QPixmap line_dotted(":res/images/line_dotted.png"); - dotLine->setIcon(line_dotted); - dotLine->setIconSize(line_dotted.size()); - QPixmap line_dash_dot(":res/images/line_dash_dot.png"); - dashDotLine->setIcon(line_dash_dot); - dashDotLine->setIconSize(line_dash_dot.size()); - QPixmap line_dash_dot_dot(":res/images/line_dash_dot_dot.png"); - dashDotDotLine->setIcon(line_dash_dot_dot); - dashDotDotLine->setIconSize(line_dash_dot_dot.size()); - customDashLine->setText(tr("Custom")); - - int fixedHeight = bevelJoin->sizeHint().height(); - solidLine->setFixedHeight(fixedHeight); - dashLine->setFixedHeight(fixedHeight); - dotLine->setFixedHeight(fixedHeight); - dashDotLine->setFixedHeight(fixedHeight); - dashDotDotLine->setFixedHeight(fixedHeight); - - m_pathModeGroup = new QGroupBox(parent); - m_pathModeGroup->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - QRadioButton *curveMode = new QRadioButton(m_pathModeGroup); - QRadioButton *lineMode = new QRadioButton(m_pathModeGroup); - m_pathModeGroup->setTitle(tr("Line Style")); - curveMode->setText(tr("Curves")); - lineMode->setText(tr("Lines")); - - - // Layouts - QVBoxLayout *capGroupLayout = new QVBoxLayout(m_capGroup); - capGroupLayout->addWidget(flatCap); - capGroupLayout->addWidget(squareCap); - capGroupLayout->addWidget(roundCap); - - QVBoxLayout *joinGroupLayout = new QVBoxLayout(m_joinGroup); - joinGroupLayout->addWidget(bevelJoin); - joinGroupLayout->addWidget(miterJoin); - joinGroupLayout->addWidget(roundJoin); - - QVBoxLayout *styleGroupLayout = new QVBoxLayout(m_styleGroup); - styleGroupLayout->addWidget(solidLine); - styleGroupLayout->addWidget(dashLine); - styleGroupLayout->addWidget(dotLine); - styleGroupLayout->addWidget(dashDotLine); - styleGroupLayout->addWidget(dashDotDotLine); - styleGroupLayout->addWidget(customDashLine); - - QVBoxLayout *pathModeGroupLayout = new QVBoxLayout(m_pathModeGroup); - pathModeGroupLayout->addWidget(curveMode); - pathModeGroupLayout->addWidget(lineMode); - - - // Connections - connect(flatCap, SIGNAL(clicked()), m_renderer, SLOT(setFlatCap())); - connect(squareCap, SIGNAL(clicked()), m_renderer, SLOT(setSquareCap())); - connect(roundCap, SIGNAL(clicked()), m_renderer, SLOT(setRoundCap())); - - connect(bevelJoin, SIGNAL(clicked()), m_renderer, SLOT(setBevelJoin())); - connect(miterJoin, SIGNAL(clicked()), m_renderer, SLOT(setMiterJoin())); - connect(roundJoin, SIGNAL(clicked()), m_renderer, SLOT(setRoundJoin())); - - connect(curveMode, SIGNAL(clicked()), m_renderer, SLOT(setCurveMode())); - connect(lineMode, SIGNAL(clicked()), m_renderer, SLOT(setLineMode())); - - connect(solidLine, SIGNAL(clicked()), m_renderer, SLOT(setSolidLine())); - connect(dashLine, SIGNAL(clicked()), m_renderer, SLOT(setDashLine())); - connect(dotLine, SIGNAL(clicked()), m_renderer, SLOT(setDotLine())); - connect(dashDotLine, SIGNAL(clicked()), m_renderer, SLOT(setDashDotLine())); - connect(dashDotDotLine, SIGNAL(clicked()), m_renderer, SLOT(setDashDotDotLine())); - connect(customDashLine, SIGNAL(clicked()), m_renderer, SLOT(setCustomDashLine())); - - // Set the defaults: - flatCap->setChecked(true); - bevelJoin->setChecked(true); - curveMode->setChecked(true); - solidLine->setChecked(true); -} - - -void PathStrokeControls::layoutForDesktop() -{ - QGroupBox *mainGroup = new QGroupBox(this); - mainGroup->setFixedWidth(180); - mainGroup->setTitle(tr("Path Stroking")); - - createCommonControls(mainGroup); - - QGroupBox* penWidthGroup = new QGroupBox(mainGroup); - QSlider *penWidth = new QSlider(Qt::Horizontal, penWidthGroup); - penWidth->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - penWidthGroup->setTitle(tr("Pen Width")); - penWidth->setRange(0, 500); - - QPushButton *animated = new QPushButton(mainGroup); - animated->setText(tr("Animate")); - animated->setCheckable(true); - - QPushButton *showSourceButton = new QPushButton(mainGroup); - showSourceButton->setText(tr("Show Source")); -#ifdef QT_OPENGL_SUPPORT - QPushButton *enableOpenGLButton = new QPushButton(mainGroup); - enableOpenGLButton->setText(tr("Use OpenGL")); - enableOpenGLButton->setCheckable(true); - enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); -#endif - QPushButton *whatsThisButton = new QPushButton(mainGroup); - whatsThisButton->setText(tr("What's This?")); - whatsThisButton->setCheckable(true); - - - // Layouts: - QVBoxLayout *penWidthLayout = new QVBoxLayout(penWidthGroup); - penWidthLayout->addWidget(penWidth); - - QVBoxLayout * mainLayout = new QVBoxLayout(this); - mainLayout->setMargin(0); - mainLayout->addWidget(mainGroup); - - QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); - mainGroupLayout->setMargin(3); - mainGroupLayout->addWidget(m_capGroup); - mainGroupLayout->addWidget(m_joinGroup); - mainGroupLayout->addWidget(m_styleGroup); - mainGroupLayout->addWidget(penWidthGroup); - mainGroupLayout->addWidget(m_pathModeGroup); - mainGroupLayout->addWidget(animated); - mainGroupLayout->addStretch(1); - mainGroupLayout->addWidget(showSourceButton); -#ifdef QT_OPENGL_SUPPORT - mainGroupLayout->addWidget(enableOpenGLButton); -#endif - mainGroupLayout->addWidget(whatsThisButton); - - - // Set up connections - connect(animated, SIGNAL(toggled(bool)), - m_renderer, SLOT(setAnimation(bool))); - - connect(penWidth, SIGNAL(valueChanged(int)), - m_renderer, SLOT(setPenWidth(int))); - - connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); -#ifdef QT_OPENGL_SUPPORT - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); -#endif - connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); - connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), - whatsThisButton, SLOT(setChecked(bool))); - - - // Set the defaults - animated->setChecked(true); - penWidth->setValue(50); - -} - -void PathStrokeControls::layoutForSmallScreens() -{ - createCommonControls(this); - - m_capGroup->layout()->setMargin(0); - m_joinGroup->layout()->setMargin(0); - m_styleGroup->layout()->setMargin(0); - m_pathModeGroup->layout()->setMargin(0); - - QPushButton* okBtn = new QPushButton(tr("OK"), this); - okBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - okBtn->setMinimumSize(100,okBtn->minimumSize().height()); - - QPushButton* quitBtn = new QPushButton(tr("Quit"), this); - quitBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - quitBtn->setMinimumSize(100, okBtn->minimumSize().height()); - - QLabel *penWidthLabel = new QLabel(tr(" Width:")); - QSlider *penWidth = new QSlider(Qt::Horizontal, this); - penWidth->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - penWidth->setRange(0, 500); - -#ifdef QT_OPENGL_SUPPORT - QPushButton *enableOpenGLButton = new QPushButton(this); - enableOpenGLButton->setText(tr("Use OpenGL")); - enableOpenGLButton->setCheckable(true); - enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); -#endif - - // Layouts: - QHBoxLayout *penWidthLayout = new QHBoxLayout(0); - penWidthLayout->addWidget(penWidthLabel, 0, Qt::AlignRight); - penWidthLayout->addWidget(penWidth); - - QVBoxLayout *leftLayout = new QVBoxLayout(0); - leftLayout->addWidget(m_capGroup); - leftLayout->addWidget(m_joinGroup); -#ifdef QT_OPENGL_SUPPORT - leftLayout->addWidget(enableOpenGLButton); -#endif - leftLayout->addLayout(penWidthLayout); - - QVBoxLayout *rightLayout = new QVBoxLayout(0); - rightLayout->addWidget(m_styleGroup); - rightLayout->addWidget(m_pathModeGroup); - - QGridLayout *mainLayout = new QGridLayout(this); - mainLayout->setMargin(0); - - // Add spacers around the form items so we don't look stupid at higher resolutions - mainLayout->addItem(new QSpacerItem(0,0), 0, 0, 1, 4); - mainLayout->addItem(new QSpacerItem(0,0), 1, 0, 2, 1); - mainLayout->addItem(new QSpacerItem(0,0), 1, 3, 2, 1); - mainLayout->addItem(new QSpacerItem(0,0), 3, 0, 1, 4); - - mainLayout->addLayout(leftLayout, 1, 1); - mainLayout->addLayout(rightLayout, 1, 2); - mainLayout->addWidget(quitBtn, 2, 1, Qt::AlignHCenter | Qt::AlignTop); - mainLayout->addWidget(okBtn, 2, 2, Qt::AlignHCenter | Qt::AlignTop); - -#ifdef QT_OPENGL_SUPPORT - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); -#endif - - connect(penWidth, SIGNAL(valueChanged(int)), m_renderer, SLOT(setPenWidth(int))); - connect(quitBtn, SIGNAL(clicked()), this, SLOT(emitQuitSignal())); - connect(okBtn, SIGNAL(clicked()), this, SLOT(emitOkSignal())); - - m_renderer->setAnimation(true); - penWidth->setValue(50); -} - -void PathStrokeControls::emitQuitSignal() -{ emit quitPressed(); } - -void PathStrokeControls::emitOkSignal() -{ emit okPressed(); } - - -PathStrokeWidget::PathStrokeWidget(bool smallScreen) -{ - setWindowTitle(tr("Path Stroking")); - - // Widget construction and property setting - m_renderer = new PathStrokeRenderer(this, smallScreen); - - m_controls = new PathStrokeControls(0, m_renderer, smallScreen); - - // Layouting - QHBoxLayout *viewLayout = new QHBoxLayout(this); - viewLayout->addWidget(m_renderer); - - if (!smallScreen) - viewLayout->addWidget(m_controls); - - m_renderer->loadSourceFile(":res/pathstroke/pathstroke.cpp"); - m_renderer->loadDescription(":res/pathstroke/pathstroke.html"); - - connect(m_renderer, SIGNAL(clicked()), this, SLOT(showControls())); - connect(m_controls, SIGNAL(okPressed()), this, SLOT(hideControls())); - connect(m_controls, SIGNAL(quitPressed()), QApplication::instance(), SLOT(quit())); -} - - -void PathStrokeWidget::showControls() -{ - m_controls->showFullScreen(); -} - - -void PathStrokeWidget::hideControls() -{ - m_controls->hide(); -} - - -void PathStrokeWidget::setStyle( QStyle * style ) -{ - QWidget::setStyle(style); - if (m_controls != 0) - { - m_controls->setStyle(style); - - QList widgets = m_controls->findChildren(); - foreach (QWidget *w, widgets) - w->setStyle(style); - } -} - - -PathStrokeRenderer::PathStrokeRenderer(QWidget *parent, bool smallScreen) - : ArthurFrame(parent) -{ - m_smallScreen = smallScreen; - m_pointSize = 10; - m_activePoint = -1; - m_capStyle = Qt::FlatCap; - m_joinStyle = Qt::BevelJoin; - m_pathMode = CurveMode; - m_penWidth = 1; - m_penStyle = Qt::SolidLine; - m_wasAnimated = true; - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - setAttribute(Qt::WA_AcceptTouchEvents); -} - -void PathStrokeRenderer::paint(QPainter *painter) -{ - if (m_points.isEmpty()) - initializePoints(); - - painter->setRenderHint(QPainter::Antialiasing); - - QPalette pal = palette(); - painter->setPen(Qt::NoPen); - - // Construct the path - QPainterPath path; - path.moveTo(m_points.at(0)); - - if (m_pathMode == LineMode) { - for (int i=1; i dashes; - qreal space = 4; - dashes << 1 << space - << 3 << space - << 9 << space - << 27 << space - << 9 << space - << 3 << space; - stroker.setDashPattern(dashes); - QPainterPath stroke = stroker.createStroke(path); - painter->fillPath(stroke, lg); - - } else { - QPen pen(lg, m_penWidth, m_penStyle, m_capStyle, m_joinStyle); - painter->strokePath(path, pen); - } - } - - if (1) { - // Draw the control points - painter->setPen(QColor(50, 100, 120, 200)); - painter->setBrush(QColor(200, 200, 210, 120)); - for (int i=0; idrawEllipse(QRectF(pos.x() - m_pointSize, - pos.y() - m_pointSize, - m_pointSize*2, m_pointSize*2)); - } - painter->setPen(QPen(Qt::lightGray, 0, Qt::SolidLine)); - painter->setBrush(Qt::NoBrush); - painter->drawPolyline(m_points); - } - -} - -void PathStrokeRenderer::initializePoints() -{ - const int count = 7; - m_points.clear(); - m_vectors.clear(); - - QMatrix m; - qreal rot = 360 / count; - QPointF center(width() / 2, height() / 2); - QMatrix vm; - vm.shear(2, -1); - vm.scale(3, 3); - - for (int i=0; i right) { - vec.setX(-vec.x()); - pos.setX(pos.x() < left ? left : right); - } if (pos.y() < top || pos.y() > bottom) { - vec.setY(-vec.y()); - pos.setY(pos.y() < top ? top : bottom); - } - m_points[i] = pos; - m_vectors[i] = vec; - } - update(); -} - -void PathStrokeRenderer::mousePressEvent(QMouseEvent *e) -{ - if (!m_fingerPointMapping.isEmpty()) - return; - setDescriptionEnabled(false); - m_activePoint = -1; - qreal distance = -1; - for (int i=0; ipos(), m_points.at(i)).length(); - if ((distance < 0 && d < 8 * m_pointSize) || d < distance) { - distance = d; - m_activePoint = i; - } - } - - if (m_activePoint != -1) { - m_wasAnimated = m_timer.isActive(); - setAnimation(false); - mouseMoveEvent(e); - } - - // If we're not running in small screen mode, always assume we're dragging - m_mouseDrag = !m_smallScreen; - m_mousePress = e->pos(); -} - -void PathStrokeRenderer::mouseMoveEvent(QMouseEvent *e) -{ - if (!m_fingerPointMapping.isEmpty()) - return; - // If we've moved more then 25 pixels, assume user is dragging - if (!m_mouseDrag && QPoint(m_mousePress - e->pos()).manhattanLength() > 25) - m_mouseDrag = true; - - if (m_mouseDrag && m_activePoint >= 0 && m_activePoint < m_points.size()) { - m_points[m_activePoint] = e->pos(); - update(); - } -} - -void PathStrokeRenderer::mouseReleaseEvent(QMouseEvent *) -{ - if (!m_fingerPointMapping.isEmpty()) - return; - m_activePoint = -1; - setAnimation(m_wasAnimated); - - if (!m_mouseDrag && m_smallScreen) - emit clicked(); -} - -void PathStrokeRenderer::timerEvent(QTimerEvent *e) -{ - if (e->timerId() == m_timer.timerId()) { - updatePoints(); - QApplication::syncX(); - } // else if (e->timerId() == m_fpsTimer.timerId()) { -// emit frameRate(m_frameCount); -// m_frameCount = 0; -// } -} - -bool PathStrokeRenderer::event(QEvent *e) -{ - bool touchBegin = false; - switch (e->type()) { - case QEvent::TouchBegin: - touchBegin = true; - case QEvent::TouchUpdate: - { - const QTouchEvent *const event = static_cast(e); - const QList points = event->touchPoints(); - foreach (const QTouchEvent::TouchPoint &touchPoint, points) { - const int id = touchPoint.id(); - switch (touchPoint.state()) { - case Qt::TouchPointPressed: - { - // find the point, move it - QSet activePoints = QSet::fromList(m_fingerPointMapping.values()); - int activePoint = -1; - qreal distance = -1; - const int pointsCount = m_points.size(); - for (int i=0; i::iterator it = m_fingerPointMapping.find(id); - m_points[it.value()] = touchPoint.pos(); - m_fingerPointMapping.erase(it); - } - break; - case Qt::TouchPointMoved: - { - // move the point - const int pointIdx = m_fingerPointMapping.value(id, -1); - if (pointIdx >= 0) - m_points[pointIdx] = touchPoint.pos(); - } - break; - default: - break; - } - } - if (m_fingerPointMapping.isEmpty()) { - e->ignore(); - return false; - } else { - if (touchBegin) { - m_wasAnimated = m_timer.isActive(); - setAnimation(false); - } - update(); - return true; - } - } - break; - case QEvent::TouchEnd: - if (m_fingerPointMapping.isEmpty()) { - e->ignore(); - return false; - } - m_fingerPointMapping.clear(); - setAnimation(m_wasAnimated); - return true; - break; - default: - break; - } - return QWidget::event(e); -} - -void PathStrokeRenderer::setAnimation(bool animation) -{ - m_timer.stop(); -// m_fpsTimer.stop(); - - if (animation) { - m_timer.start(25, this); -// m_fpsTimer.start(1000, this); -// m_frameCount = 0; - } -} diff --git a/demos/pathstroke/pathstroke.h b/demos/pathstroke/pathstroke.h deleted file mode 100644 index f0360b6648..0000000000 --- a/demos/pathstroke/pathstroke.h +++ /dev/null @@ -1,171 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef PATHSTROKE_H -#define PATHSTROKE_H - -#include "arthurwidgets.h" -#include - -class PathStrokeRenderer : public ArthurFrame -{ - Q_OBJECT - Q_PROPERTY(bool animation READ animation WRITE setAnimation) - Q_PROPERTY(qreal penWidth READ realPenWidth WRITE setRealPenWidth) -public: - enum PathMode { CurveMode, LineMode }; - - PathStrokeRenderer(QWidget *parent, bool smallScreen = false); - - void paint(QPainter *); - void mousePressEvent(QMouseEvent *e); - void mouseMoveEvent(QMouseEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void timerEvent(QTimerEvent *e); - bool event(QEvent *e); - - QSize sizeHint() const { return QSize(500, 500); } - - bool animation() const { return m_timer.isActive(); } - - qreal realPenWidth() const { return m_penWidth; } - void setRealPenWidth(qreal penWidth) { m_penWidth = penWidth; update(); } - -signals: - void clicked(); - -public slots: - void setPenWidth(int penWidth) { m_penWidth = penWidth / 10.0; update(); } - void setAnimation(bool animation); - - void setFlatCap() { m_capStyle = Qt::FlatCap; update(); } - void setSquareCap() { m_capStyle = Qt::SquareCap; update(); } - void setRoundCap() { m_capStyle = Qt::RoundCap; update(); } - - void setBevelJoin() { m_joinStyle = Qt::BevelJoin; update(); } - void setMiterJoin() { m_joinStyle = Qt::MiterJoin; update(); } - void setRoundJoin() { m_joinStyle = Qt::RoundJoin; update(); } - - void setCurveMode() { m_pathMode = CurveMode; update(); } - void setLineMode() { m_pathMode = LineMode; update(); } - - void setSolidLine() { m_penStyle = Qt::SolidLine; update(); } - void setDashLine() { m_penStyle = Qt::DashLine; update(); } - void setDotLine() { m_penStyle = Qt::DotLine; update(); } - void setDashDotLine() { m_penStyle = Qt::DashDotLine; update(); } - void setDashDotDotLine() { m_penStyle = Qt::DashDotDotLine; update(); } - void setCustomDashLine() { m_penStyle = Qt::NoPen; update(); } - -private: - void initializePoints(); - void updatePoints(); - - QBasicTimer m_timer; - - PathMode m_pathMode; - - bool m_wasAnimated; - - qreal m_penWidth; - int m_pointCount; - int m_pointSize; - int m_activePoint; - QVector m_points; - QVector m_vectors; - - Qt::PenJoinStyle m_joinStyle; - Qt::PenCapStyle m_capStyle; - - Qt::PenStyle m_penStyle; - - bool m_smallScreen; - QPoint m_mousePress; - bool m_mouseDrag; - - QHash m_fingerPointMapping; -}; - -class PathStrokeControls : public QWidget -{ - Q_OBJECT -public: - PathStrokeControls(QWidget* parent, PathStrokeRenderer* renderer, bool smallScreen); - -signals: - void okPressed(); - void quitPressed(); - -private: - PathStrokeRenderer* m_renderer; - - QGroupBox *m_capGroup; - QGroupBox *m_joinGroup; - QGroupBox *m_styleGroup; - QGroupBox *m_pathModeGroup; - - void createCommonControls(QWidget* parent); - void layoutForDesktop(); - void layoutForSmallScreens(); - -private slots: - void emitQuitSignal(); - void emitOkSignal(); - -}; - -class PathStrokeWidget : public QWidget -{ - Q_OBJECT -public: - PathStrokeWidget(bool smallScreen); - void setStyle ( QStyle * style ); - -private: - PathStrokeRenderer *m_renderer; - PathStrokeControls *m_controls; - -private slots: - void showControls(); - void hideControls(); - -}; - -#endif // PATHSTROKE_H diff --git a/demos/pathstroke/pathstroke.html b/demos/pathstroke/pathstroke.html deleted file mode 100644 index 9e7e50de76..0000000000 --- a/demos/pathstroke/pathstroke.html +++ /dev/null @@ -1,20 +0,0 @@ - -
-

Primitive Stroking

-
- -

In this demo we show some of the various types of pens that can be -used in Qt.

- -

Qt defines cap styles for how the end points are treated and join -styles for how path segments are joined together. A standard set of -predefined dash patterns are also included that can be used with -QPen.

- -

In addition to the predefined patterns available in -QPen we also demonstrate direct use of the -QPainterPathStroker class which can be used to define -custom dash patterns. You can see this by enabling the -Custom Pattern option.

- - diff --git a/demos/pathstroke/pathstroke.pro b/demos/pathstroke/pathstroke.pro deleted file mode 100644 index 9bbf8a6f77..0000000000 --- a/demos/pathstroke/pathstroke.pro +++ /dev/null @@ -1,24 +0,0 @@ -SOURCES += main.cpp pathstroke.cpp -HEADERS += pathstroke.h - -SHARED_FOLDER = ../shared - -include($$SHARED_FOLDER/shared.pri) - -RESOURCES += pathstroke.qrc - -contains(QT_CONFIG, opengl) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/pathstroke -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/pathstroke -INSTALLS += target sources - -symbian { - TARGET.UID3 = 0xA000A63E - CONFIG += qt_demo -} diff --git a/demos/pathstroke/pathstroke.qrc b/demos/pathstroke/pathstroke.qrc deleted file mode 100644 index a9a723409e..0000000000 --- a/demos/pathstroke/pathstroke.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - pathstroke.cpp - pathstroke.html - - diff --git a/demos/shared/arthurstyle.cpp b/demos/shared/arthurstyle.cpp deleted file mode 100644 index 432b8b34e5..0000000000 --- a/demos/shared/arthurstyle.cpp +++ /dev/null @@ -1,452 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "arthurstyle.h" -#include "arthurwidgets.h" -#include -#include -#include -#include -#include -#include -#include -#include - -QPixmap cached(const QString &img) -{ - if (QPixmap *p = QPixmapCache::find(img)) - return *p; - - QPixmap pm; - pm = QPixmap::fromImage(QImage(img), Qt::OrderedDither | Qt::OrderedAlphaDither); - if (pm.isNull()) - return QPixmap(); - - QPixmapCache::insert(img, pm); - return pm; -} - - -ArthurStyle::ArthurStyle() - : QWindowsStyle() -{ - Q_INIT_RESOURCE(shared); -} - - -void ArthurStyle::drawHoverRect(QPainter *painter, const QRect &r) const -{ - qreal h = r.height(); - qreal h2 = r.height() / qreal(2); - QPainterPath path; - path.addRect(r.x() + h2, r.y() + 0, r.width() - h2 * 2, r.height()); - path.addEllipse(r.x(), r.y(), h, h); - path.addEllipse(r.x() + r.width() - h, r.y(), h, h); - path.setFillRule(Qt::WindingFill); - painter->setPen(Qt::NoPen); - painter->setBrush(QColor(191, 215, 191)); - painter->setRenderHint(QPainter::Antialiasing); - painter->drawPath(path); -} - - -void ArthurStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget) const -{ - - Q_ASSERT(option); - switch (element) { - case PE_FrameFocusRect: - break; - - case PE_IndicatorRadioButton: - if (const QStyleOptionButton *button = qstyleoption_cast(option)) { - bool hover = (button->state & State_Enabled) && (button->state & State_MouseOver); - painter->save(); - QPixmap radio; - if (hover) - drawHoverRect(painter, widget->rect()); - - if (button->state & State_Sunken) - radio = cached(":res/images/radiobutton-on.png"); - else if (button->state & State_On) - radio = cached(":res/images/radiobutton_on.png"); - else - radio = cached(":res/images/radiobutton_off.png"); - painter->drawPixmap(button->rect.topLeft(), radio); - - painter->restore(); - } - break; - - case PE_PanelButtonCommand: - if (const QStyleOptionButton *button = qstyleoption_cast(option)) { - bool hover = (button->state & State_Enabled) && (button->state & State_MouseOver); - - painter->save(); - const QPushButton *pushButton = qobject_cast(widget); - Q_ASSERT(pushButton); - QWidget *parent = pushButton->parentWidget(); - if (parent && qobject_cast(parent)) { - QLinearGradient lg(0, 0, 0, parent->height()); - lg.setColorAt(0, QColor(224,224,224)); - lg.setColorAt(1, QColor(255,255,255)); - painter->setPen(Qt::NoPen); - painter->setBrush(lg); - painter->setBrushOrigin(-widget->mapToParent(QPoint(0,0))); - painter->drawRect(button->rect); - painter->setBrushOrigin(0,0); - } - - bool down = (button->state & State_Sunken) || (button->state & State_On); - - QPixmap left, right, mid; - if (down) { - left = cached(":res/images/button_pressed_cap_left.png"); - right = cached(":res/images/button_pressed_cap_right.png"); - mid = cached(":res/images/button_pressed_stretch.png"); - } else { - left = cached(":res/images/button_normal_cap_left.png"); - right = cached(":res/images/button_normal_cap_right.png"); - mid = cached(":res/images/button_normal_stretch.png"); - } - painter->drawPixmap(button->rect.topLeft(), left); - painter->drawTiledPixmap(QRect(button->rect.x() + left.width(), - button->rect.y(), - button->rect.width() - left.width() - right.width(), - left.height()), - mid); - painter->drawPixmap(button->rect.x() + button->rect.width() - right.width(), - button->rect.y(), - right); - if (hover) - painter->fillRect(widget->rect().adjusted(3,5,-3,-5), QColor(31,127,31,63)); - painter->restore(); - } - break; - - case PE_FrameGroupBox: - if (const QStyleOptionFrameV2 *group - = qstyleoption_cast(option)) { - const QRect &r = group->rect; - - painter->save(); - int radius = 14; - int radius2 = radius*2; - QPainterPath clipPath; - clipPath.moveTo(radius, 0); - clipPath.arcTo(r.right() - radius2, 0, radius2, radius2, 90, -90); - clipPath.arcTo(r.right() - radius2, r.bottom() - radius2, radius2, radius2, 0, -90); - clipPath.arcTo(r.left(), r.bottom() - radius2, radius2, radius2, 270, -90); - clipPath.arcTo(r.left(), r.top(), radius2, radius2, 180, -90); - painter->setClipPath(clipPath); - QPixmap titleStretch = cached(":res/images/title_stretch.png"); - QPixmap topLeft = cached(":res/images/groupframe_topleft.png"); - QPixmap topRight = cached(":res/images/groupframe_topright.png"); - QPixmap bottomLeft = cached(":res/images/groupframe_bottom_left.png"); - QPixmap bottomRight = cached(":res/images/groupframe_bottom_right.png"); - QPixmap leftStretch = cached(":res/images/groupframe_left_stretch.png"); - QPixmap topStretch = cached(":res/images/groupframe_top_stretch.png"); - QPixmap rightStretch = cached(":res/images/groupframe_right_stretch.png"); - QPixmap bottomStretch = cached(":res/images/groupframe_bottom_stretch.png"); - QLinearGradient lg(0, 0, 0, r.height()); - lg.setColorAt(0, QColor(224,224,224)); - lg.setColorAt(1, QColor(255,255,255)); - painter->setPen(Qt::NoPen); - painter->setBrush(lg); - painter->drawRect(r.adjusted(0, titleStretch.height()/2, 0, 0)); - painter->setClipping(false); - - int topFrameOffset = titleStretch.height()/2 - 2; - painter->drawPixmap(r.topLeft() + QPoint(0, topFrameOffset), topLeft); - painter->drawPixmap(r.topRight() - QPoint(topRight.width()-1, 0) - + QPoint(0, topFrameOffset), topRight); - painter->drawPixmap(r.bottomLeft() - QPoint(0, bottomLeft.height()-1), bottomLeft); - painter->drawPixmap(r.bottomRight() - QPoint(bottomRight.width()-1, - bottomRight.height()-1), bottomRight); - - QRect left = r; - left.setY(r.y() + topLeft.height() + topFrameOffset); - left.setWidth(leftStretch.width()); - left.setHeight(r.height() - topLeft.height() - bottomLeft.height() - topFrameOffset); - painter->drawTiledPixmap(left, leftStretch); - - QRect top = r; - top.setX(r.x() + topLeft.width()); - top.setY(r.y() + topFrameOffset); - top.setWidth(r.width() - topLeft.width() - topRight.width()); - top.setHeight(topLeft.height()); - painter->drawTiledPixmap(top, topStretch); - - QRect right = r; - right.setX(r.right() - rightStretch.width()+1); - right.setY(r.y() + topRight.height() + topFrameOffset); - right.setWidth(rightStretch.width()); - right.setHeight(r.height() - topRight.height() - - bottomRight.height() - topFrameOffset); - painter->drawTiledPixmap(right, rightStretch); - - QRect bottom = r; - bottom.setX(r.x() + bottomLeft.width()); - bottom.setY(r.bottom() - bottomStretch.height()+1); - bottom.setWidth(r.width() - bottomLeft.width() - bottomRight.width()); - bottom.setHeight(bottomLeft.height()); - painter->drawTiledPixmap(bottom, bottomStretch); - painter->restore(); - } - break; - - default: - QWindowsStyle::drawPrimitive(element, option, painter, widget); - break; - } - return; -} - - -void ArthurStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, - QPainter *painter, const QWidget *widget) const -{ - switch (control) { - case CC_Slider: - if (const QStyleOptionSlider *slider = qstyleoption_cast(option)) { - QRect groove = subControlRect(CC_Slider, option, SC_SliderGroove, widget); - QRect handle = subControlRect(CC_Slider, option, SC_SliderHandle, widget); - - painter->save(); - - bool hover = (slider->state & State_Enabled) && (slider->state & State_MouseOver); - if (hover) { - QRect moderated = widget->rect().adjusted(0, 4, 0, -4); - drawHoverRect(painter, moderated); - } - - if ((option->subControls & SC_SliderGroove) && groove.isValid()) { - QPixmap grv = cached(":res/images/slider_bar.png"); - painter->drawPixmap(QRect(groove.x() + 5, groove.y(), - groove.width() - 10, grv.height()), - grv); - } - if ((option->subControls & SC_SliderHandle) && handle.isValid()) { - QPixmap hndl = cached(":res/images/slider_thumb_on.png"); - painter->drawPixmap(handle.topLeft(), hndl); - } - - painter->restore(); - } - break; - case CC_GroupBox: - if (const QStyleOptionGroupBox *groupBox - = qstyleoption_cast(option)) { - QStyleOptionGroupBox groupBoxCopy(*groupBox); - groupBoxCopy.subControls &= ~SC_GroupBoxLabel; - QWindowsStyle::drawComplexControl(control, &groupBoxCopy, painter, widget); - - if (groupBox->subControls & SC_GroupBoxLabel) { - const QRect &r = groupBox->rect; - QPixmap titleLeft = cached(":res/images/title_cap_left.png"); - QPixmap titleRight = cached(":res/images/title_cap_right.png"); - QPixmap titleStretch = cached(":res/images/title_stretch.png"); - int txt_width = groupBox->fontMetrics.width(groupBox->text) + 20; - painter->drawPixmap(r.center().x() - txt_width/2, 0, titleLeft); - QRect tileRect = subControlRect(control, groupBox, SC_GroupBoxLabel, widget); - painter->drawTiledPixmap(tileRect, titleStretch); - painter->drawPixmap(tileRect.x() + tileRect.width(), 0, titleRight); - int opacity = 31; - painter->setPen(QColor(0, 0, 0, opacity)); - painter->drawText(tileRect.translated(0, 1), - Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text); - painter->drawText(tileRect.translated(2, 1), - Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text); - painter->setPen(QColor(0, 0, 0, opacity * 2)); - painter->drawText(tileRect.translated(1, 1), - Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text); - painter->setPen(Qt::white); - painter->drawText(tileRect, Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text); - } - } - break; - default: - QWindowsStyle::drawComplexControl(control, option, painter, widget); - break; - } - return; -} - -QRect ArthurStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option, - SubControl subControl, const QWidget *widget) const -{ - QRect rect; - - switch (control) { - default: - rect = QWindowsStyle::subControlRect(control, option, subControl, widget); - break; - case CC_GroupBox: - if (const QStyleOptionGroupBox *group - = qstyleoption_cast(option)) { - switch (subControl) { - default: - rect = QWindowsStyle::subControlRect(control, option, subControl, widget); - break; - case SC_GroupBoxContents: - rect = QWindowsStyle::subControlRect(control, option, subControl, widget); - rect.adjust(0, -8, 0, 0); - break; - case SC_GroupBoxFrame: - rect = group->rect; - break; - case SC_GroupBoxLabel: - QPixmap titleLeft = cached(":res/images/title_cap_left.png"); - QPixmap titleRight = cached(":res/images/title_cap_right.png"); - QPixmap titleStretch = cached(":res/images/title_stretch.png"); - int txt_width = group->fontMetrics.width(group->text) + 20; - rect = QRect(group->rect.center().x() - txt_width/2 + titleLeft.width(), 0, - txt_width - titleLeft.width() - titleRight.width(), - titleStretch.height()); - break; - } - } - break; - } - - if (control == CC_Slider && subControl == SC_SliderHandle) { - rect.setWidth(13); - rect.setHeight(27); - } else if (control == CC_Slider && subControl == SC_SliderGroove) { - rect.setHeight(9); - rect.moveTop(27/2 - 9/2); - } - return rect; -} - -QSize ArthurStyle::sizeFromContents(ContentsType type, const QStyleOption *option, - const QSize &size, const QWidget *widget) const -{ - QSize newSize = QWindowsStyle::sizeFromContents(type, option, size, widget); - - - switch (type) { - case CT_RadioButton: - newSize += QSize(20, 0); - break; - - case CT_PushButton: - newSize.setHeight(26); - break; - - case CT_Slider: - newSize.setHeight(27); - break; - - default: - break; - } - - return newSize; -} - -int ArthurStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QWidget *widget) const -{ - if (pm == PM_SliderLength) - return 13; - return QWindowsStyle::pixelMetric(pm, opt, widget); -} - -void ArthurStyle::polish(QWidget *widget) -{ - if (widget->layout() && qobject_cast(widget)) { - if (widget->findChildren().size() == 0) { - widget->layout()->setSpacing(0); - widget->layout()->setMargin(12); - } else { - widget->layout()->setMargin(13); - } - } - - if (qobject_cast(widget) - || qobject_cast(widget) - || qobject_cast(widget)) { - widget->setAttribute(Qt::WA_Hover); - } - - QPalette pal = widget->palette(); - if (widget->isWindow()) { - pal.setColor(QPalette::Background, QColor(241, 241, 241)); - widget->setPalette(pal); - } - -} - -void ArthurStyle::unpolish(QWidget *widget) -{ - if (qobject_cast(widget) - || qobject_cast(widget) - || qobject_cast(widget)) { - widget->setAttribute(Qt::WA_Hover, false); - } -} - -void ArthurStyle::polish(QPalette &palette) -{ - palette.setColor(QPalette::Background, QColor(241, 241, 241)); -} - -QRect ArthurStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const -{ - QRect r; - switch(element) { - case SE_RadioButtonClickRect: - r = widget->rect(); - break; - case SE_RadioButtonContents: - r = widget->rect().adjusted(20, 0, 0, 0); - break; - default: - r = QWindowsStyle::subElementRect(element, option, widget); - break; - } - - if (qobject_cast(widget)) - r = r.adjusted(5, 0, -5, 0); - - return r; -} diff --git a/demos/shared/arthurstyle.h b/demos/shared/arthurstyle.h deleted file mode 100644 index 32c7fad970..0000000000 --- a/demos/shared/arthurstyle.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ARTHURSTYLE_H -#define ARTHURSTYLE_H - -#include - -QT_USE_NAMESPACE - -class ArthurStyle : public QWindowsStyle -{ -public: - ArthurStyle(); - - void drawHoverRect(QPainter *painter, const QRect &rect) const; - - void drawPrimitive(PrimitiveElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget = 0) const; -// void drawControl(ControlElement element, const QStyleOption *option, -// QPainter *painter, const QWidget *widget) const; - void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, - QPainter *painter, const QWidget *widget) const; - QSize sizeFromContents(ContentsType type, const QStyleOption *option, - const QSize &size, const QWidget *widget) const; - - QRect subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const; - QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, - SubControl sc, const QWidget *widget) const; - -// SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, -// const QPoint &pos, const QWidget *widget = 0) const; - - int pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const; - - void polish(QPalette &palette); - void polish(QWidget *widget); - void unpolish(QWidget *widget); -}; - -#endif diff --git a/demos/shared/arthurwidgets.cpp b/demos/shared/arthurwidgets.cpp deleted file mode 100644 index b3c75f0fc4..0000000000 --- a/demos/shared/arthurwidgets.cpp +++ /dev/null @@ -1,371 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "arthurwidgets.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -extern QPixmap cached(const QString &img); - -ArthurFrame::ArthurFrame(QWidget *parent) - : QWidget(parent) - , m_prefer_image(false) -{ -#ifdef QT_OPENGL_SUPPORT - glw = 0; - m_use_opengl = false; - QGLFormat f = QGLFormat::defaultFormat(); - f.setSampleBuffers(true); - f.setStencil(true); - f.setAlpha(true); - f.setAlphaBufferSize(8); - QGLFormat::setDefaultFormat(f); -#endif - m_document = 0; - m_show_doc = false; - - m_tile = QPixmap(128, 128); - m_tile.fill(Qt::white); - QPainter pt(&m_tile); - QColor color(230, 230, 230); - pt.fillRect(0, 0, 64, 64, color); - pt.fillRect(64, 64, 64, 64, color); - pt.end(); - -// QPalette pal = palette(); -// pal.setBrush(backgroundRole(), m_tile); -// setPalette(pal); - -#ifdef Q_WS_X11 - QPixmap xRenderPixmap(1, 1); - m_prefer_image = xRenderPixmap.pixmapData()->classId() == QPixmapData::X11Class && !xRenderPixmap.x11PictureHandle(); -#endif -} - - -#ifdef QT_OPENGL_SUPPORT -void ArthurFrame::enableOpenGL(bool use_opengl) -{ - m_use_opengl = use_opengl; - - if (!glw) { - glw = new GLWidget(this); - glw->setAutoFillBackground(false); - glw->disableAutoBufferSwap(); - QApplication::postEvent(this, new QResizeEvent(size(), size())); - } - - if (use_opengl) { - glw->show(); - } else { - glw->hide(); - } - - update(); -} -#endif - -void ArthurFrame::paintEvent(QPaintEvent *e) -{ -#ifdef Q_WS_QWS - static QPixmap *static_image = 0; -#else - static QImage *static_image = 0; -#endif - QPainter painter; - if (preferImage() -#ifdef QT_OPENGL_SUPPORT - && !m_use_opengl -#endif - ) { - if (!static_image || static_image->size() != size()) { - delete static_image; -#ifdef Q_WS_QWS - static_image = new QPixmap(size()); -#else - static_image = new QImage(size(), QImage::Format_RGB32); -#endif - } - painter.begin(static_image); - - int o = 10; - - QBrush bg = palette().brush(QPalette::Background); - painter.fillRect(0, 0, o, o, bg); - painter.fillRect(width() - o, 0, o, o, bg); - painter.fillRect(0, height() - o, o, o, bg); - painter.fillRect(width() - o, height() - o, o, o, bg); - } else { -#ifdef QT_OPENGL_SUPPORT - if (m_use_opengl) { - painter.begin(glw); - painter.fillRect(QRectF(0, 0, glw->width(), glw->height()), palette().color(backgroundRole())); - } else { - painter.begin(this); - } -#else - painter.begin(this); -#endif - } - - painter.setClipRect(e->rect()); - - painter.setRenderHint(QPainter::Antialiasing); - - QPainterPath clipPath; - - QRect r = rect(); - qreal left = r.x() + 1; - qreal top = r.y() + 1; - qreal right = r.right(); - qreal bottom = r.bottom(); - qreal radius2 = 8 * 2; - - clipPath.moveTo(right - radius2, top); - clipPath.arcTo(right - radius2, top, radius2, radius2, 90, -90); - clipPath.arcTo(right - radius2, bottom - radius2, radius2, radius2, 0, -90); - clipPath.arcTo(left, bottom - radius2, radius2, radius2, 270, -90); - clipPath.arcTo(left, top, radius2, radius2, 180, -90); - clipPath.closeSubpath(); - - painter.save(); - painter.setClipPath(clipPath, Qt::IntersectClip); - - painter.drawTiledPixmap(rect(), m_tile); - - // client painting - - paint(&painter); - - painter.restore(); - - painter.save(); - if (m_show_doc) - paintDescription(&painter); - painter.restore(); - - int level = 180; - painter.setPen(QPen(QColor(level, level, level), 2)); - painter.setBrush(Qt::NoBrush); - painter.drawPath(clipPath); - - if (preferImage() -#ifdef QT_OPENGL_SUPPORT - && !m_use_opengl -#endif - ) { - painter.end(); - painter.begin(this); -#ifdef Q_WS_QWS - painter.drawPixmap(e->rect(), *static_image, e->rect()); -#else - painter.drawImage(e->rect(), *static_image, e->rect()); -#endif - } - -#ifdef QT_OPENGL_SUPPORT - if (m_use_opengl && (inherits("PathDeformRenderer") || inherits("PathStrokeRenderer") || inherits("CompositionRenderer") || m_show_doc)) - glw->swapBuffers(); -#endif -} - -void ArthurFrame::resizeEvent(QResizeEvent *e) -{ -#ifdef QT_OPENGL_SUPPORT - if (glw) - glw->setGeometry(0, 0, e->size().width()-1, e->size().height()-1); -#endif - QWidget::resizeEvent(e); -} - -void ArthurFrame::setDescriptionEnabled(bool enabled) -{ - if (m_show_doc != enabled) { - m_show_doc = enabled; - emit descriptionEnabledChanged(m_show_doc); - update(); - } -} - -void ArthurFrame::loadDescription(const QString &fileName) -{ - QFile textFile(fileName); - QString text; - if (!textFile.open(QFile::ReadOnly)) - text = QString("Unable to load resource file: '%1'").arg(fileName); - else - text = textFile.readAll(); - setDescription(text); -} - - -void ArthurFrame::setDescription(const QString &text) -{ - m_document = new QTextDocument(this); - m_document->setHtml(text); -} - -void ArthurFrame::paintDescription(QPainter *painter) -{ - if (!m_document) - return; - - int pageWidth = qMax(width() - 100, 100); - int pageHeight = qMax(height() - 100, 100); - if (pageWidth != m_document->pageSize().width()) { - m_document->setPageSize(QSize(pageWidth, pageHeight)); - } - - QRect textRect(width() / 2 - pageWidth / 2, - height() / 2 - pageHeight / 2, - pageWidth, - pageHeight); - int pad = 10; - QRect clearRect = textRect.adjusted(-pad, -pad, pad, pad); - painter->setPen(Qt::NoPen); - painter->setBrush(QColor(0, 0, 0, 63)); - int shade = 10; - painter->drawRect(clearRect.x() + clearRect.width() + 1, - clearRect.y() + shade, - shade, - clearRect.height() + 1); - painter->drawRect(clearRect.x() + shade, - clearRect.y() + clearRect.height() + 1, - clearRect.width() - shade + 1, - shade); - - painter->setRenderHint(QPainter::Antialiasing, false); - painter->setBrush(QColor(255, 255, 255, 220)); - painter->setPen(Qt::black); - painter->drawRect(clearRect); - - painter->setClipRegion(textRect, Qt::IntersectClip); - painter->translate(textRect.topLeft()); - - QAbstractTextDocumentLayout::PaintContext ctx; - - QLinearGradient g(0, 0, 0, textRect.height()); - g.setColorAt(0, Qt::black); - g.setColorAt(0.9, Qt::black); - g.setColorAt(1, Qt::transparent); - - QPalette pal = palette(); - pal.setBrush(QPalette::Text, g); - - ctx.palette = pal; - ctx.clip = QRect(0, 0, textRect.width(), textRect.height()); - m_document->documentLayout()->draw(painter, ctx); -} - -void ArthurFrame::loadSourceFile(const QString &sourceFile) -{ - m_sourceFileName = sourceFile; -} - -void ArthurFrame::showSource() -{ - // Check for existing source - if (findChild()) - return; - - QString contents; - if (m_sourceFileName.isEmpty()) { - contents = QString("No source for widget: '%1'").arg(objectName()); - } else { - QFile f(m_sourceFileName); - if (!f.open(QFile::ReadOnly)) - contents = QString("Could not open file: '%1'").arg(m_sourceFileName); - else - contents = f.readAll(); - } - - contents.replace('&', "&"); - contents.replace('<', "<"); - contents.replace('>', ">"); - - QStringList keywords; - keywords << "for " << "if " << "switch " << " int " << "#include " << "const" - << "void " << "uint " << "case " << "double " << "#define " << "static" - << "new" << "this"; - - foreach (QString keyword, keywords) - contents.replace(keyword, QLatin1String("") + keyword + QLatin1String("")); - contents.replace("(int ", "(int "); - - QStringList ppKeywords; - ppKeywords << "#ifdef" << "#ifndef" << "#if" << "#endif" << "#else"; - - foreach (QString keyword, ppKeywords) - contents.replace(keyword, QLatin1String("") + keyword + QLatin1String("")); - - contents.replace(QRegExp("(\\d\\d?)"), QLatin1String("\\1")); - - QRegExp commentRe("(//.+)\\n"); - commentRe.setMinimal(true); - contents.replace(commentRe, QLatin1String("\\1\n")); - - QRegExp stringLiteralRe("(\".+\")"); - stringLiteralRe.setMinimal(true); - contents.replace(stringLiteralRe, QLatin1String("\\1")); - - QString html = contents; - html.prepend("
");
-    html.append("
"); - - QTextBrowser *sourceViewer = new QTextBrowser(0); - sourceViewer->setWindowTitle("Source: " + m_sourceFileName.mid(5)); - sourceViewer->setParent(this, Qt::Dialog); - sourceViewer->setAttribute(Qt::WA_DeleteOnClose); - sourceViewer->setLineWrapMode(QTextEdit::NoWrap); - sourceViewer->setHtml(html); - sourceViewer->resize(600, 600); - sourceViewer->show(); -} diff --git a/demos/shared/arthurwidgets.h b/demos/shared/arthurwidgets.h deleted file mode 100644 index dc8f92505d..0000000000 --- a/demos/shared/arthurwidgets.h +++ /dev/null @@ -1,137 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ARTHURWIDGETS_H -#define ARTHURWIDGETS_H - -#include "arthurstyle.h" -#include -#include -#include - -#if defined(QT_OPENGL_SUPPORT) -#include -#include -class GLWidget : public QGLWidget -{ -public: - GLWidget(QWidget *parent) - : QGLWidget(QGLFormat(QGL::SampleBuffers), parent) - { - setAttribute(Qt::WA_AcceptTouchEvents); - } - void disableAutoBufferSwap() { setAutoBufferSwap(false); } - void paintEvent(QPaintEvent *) { parentWidget()->update(); } -protected: - bool event(QEvent *event) - { - switch (event->type()) { - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - case QEvent::TouchEnd: - event->ignore(); - return false; - break; - default: - break; - } - return QGLWidget::event(event); - } -}; -#endif - -QT_FORWARD_DECLARE_CLASS(QTextDocument) -QT_FORWARD_DECLARE_CLASS(QTextEdit) -QT_FORWARD_DECLARE_CLASS(QVBoxLayout) - -class ArthurFrame : public QWidget -{ - Q_OBJECT -public: - ArthurFrame(QWidget *parent); - virtual void paint(QPainter *) {} - - - void paintDescription(QPainter *p); - - void loadDescription(const QString &filename); - void setDescription(const QString &htmlDesc); - - void loadSourceFile(const QString &fileName); - - bool preferImage() const { return m_prefer_image; } - -#if defined(QT_OPENGL_SUPPORT) - QGLWidget *glWidget() const { return glw; } -#endif - -public slots: - void setPreferImage(bool pi) { m_prefer_image = pi; } - void setDescriptionEnabled(bool enabled); - void showSource(); - -#if defined(QT_OPENGL_SUPPORT) - void enableOpenGL(bool use_opengl); - bool usesOpenGL() { return m_use_opengl; } -#endif - -signals: - void descriptionEnabledChanged(bool); - -protected: - void paintEvent(QPaintEvent *); - void resizeEvent(QResizeEvent *); - -#if defined(QT_OPENGL_SUPPORT) - GLWidget *glw; - bool m_use_opengl; -#endif - QPixmap m_tile; - - bool m_show_doc; - bool m_prefer_image; - QTextDocument *m_document; - - QString m_sourceFileName; - -}; - -#endif diff --git a/demos/shared/hoverpoints.cpp b/demos/shared/hoverpoints.cpp deleted file mode 100644 index 36c24186d3..0000000000 --- a/demos/shared/hoverpoints.cpp +++ /dev/null @@ -1,415 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifdef QT_OPENGL_SUPPORT -#include -#endif - -#include "arthurwidgets.h" -#include "hoverpoints.h" - -#define printf - -HoverPoints::HoverPoints(QWidget *widget, PointShape shape) - : QObject(widget) -{ - m_widget = widget; - widget->installEventFilter(this); - widget->setAttribute(Qt::WA_AcceptTouchEvents); - - m_connectionType = CurveConnection; - m_sortType = NoSort; - m_shape = shape; - m_pointPen = QPen(QColor(255, 255, 255, 191), 1); - m_connectionPen = QPen(QColor(255, 255, 255, 127), 2); - m_pointBrush = QBrush(QColor(191, 191, 191, 127)); - m_pointSize = QSize(11, 11); - m_currentIndex = -1; - m_editable = true; - m_enabled = true; - - connect(this, SIGNAL(pointsChanged(QPolygonF)), - m_widget, SLOT(update())); -} - - -void HoverPoints::setEnabled(bool enabled) -{ - if (m_enabled != enabled) { - m_enabled = enabled; - m_widget->update(); - } -} - - -bool HoverPoints::eventFilter(QObject *object, QEvent *event) -{ - if (object == m_widget && m_enabled) { - switch (event->type()) { - - case QEvent::MouseButtonPress: - { - if (!m_fingerPointMapping.isEmpty()) - return true; - QMouseEvent *me = (QMouseEvent *) event; - - QPointF clickPos = me->pos(); - int index = -1; - for (int i=0; ibutton() == Qt::LeftButton) { - if (index == -1) { - if (!m_editable) - return false; - int pos = 0; - // Insert sort for x or y - if (m_sortType == XSort) { - for (int i=0; i clickPos.x()) { - pos = i; - break; - } - } else if (m_sortType == YSort) { - for (int i=0; i clickPos.y()) { - pos = i; - break; - } - } - - m_points.insert(pos, clickPos); - m_locks.insert(pos, 0); - m_currentIndex = pos; - firePointChange(); - } else { - m_currentIndex = index; - } - return true; - - } else if (me->button() == Qt::RightButton) { - if (index >= 0 && m_editable) { - if (m_locks[index] == 0) { - m_locks.remove(index); - m_points.remove(index); - } - firePointChange(); - return true; - } - } - - } - break; - - case QEvent::MouseButtonRelease: - if (!m_fingerPointMapping.isEmpty()) - return true; - m_currentIndex = -1; - break; - - case QEvent::MouseMove: - if (!m_fingerPointMapping.isEmpty()) - return true; - if (m_currentIndex >= 0) - movePoint(m_currentIndex, ((QMouseEvent *)event)->pos()); - break; - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - { - const QTouchEvent *const touchEvent = static_cast(event); - const QList points = touchEvent->touchPoints(); - const qreal pointSize = qMax(m_pointSize.width(), m_pointSize.height()); - foreach (const QTouchEvent::TouchPoint &touchPoint, points) { - const int id = touchPoint.id(); - switch (touchPoint.state()) { - case Qt::TouchPointPressed: - { - // find the point, move it - QSet activePoints = QSet::fromList(m_fingerPointMapping.values()); - int activePoint = -1; - qreal distance = -1; - const int pointsCount = m_points.size(); - const int activePointCount = activePoints.size(); - if (pointsCount == 2 && activePointCount == 1) { // only two points - activePoint = activePoints.contains(0) ? 1 : 0; - } else { - for (int i=0; i::iterator it = m_fingerPointMapping.find(id); - movePoint(it.value(), touchPoint.pos()); - m_fingerPointMapping.erase(it); - } - break; - case Qt::TouchPointMoved: - { - // move the point - const int pointIdx = m_fingerPointMapping.value(id, -1); - if (pointIdx >= 0) // do we track this point? - movePoint(pointIdx, touchPoint.pos()); - } - break; - default: - break; - } - } - if (m_fingerPointMapping.isEmpty()) { - event->ignore(); - return false; - } else { - return true; - } - } - break; - case QEvent::TouchEnd: - if (m_fingerPointMapping.isEmpty()) { - event->ignore(); - return false; - } - return true; - break; - - case QEvent::Resize: - { - QResizeEvent *e = (QResizeEvent *) event; - if (e->oldSize().width() == 0 || e->oldSize().height() == 0) - break; - qreal stretch_x = e->size().width() / qreal(e->oldSize().width()); - qreal stretch_y = e->size().height() / qreal(e->oldSize().height()); - for (int i=0; i(that_widget); - if (af && af->usesOpenGL()) - af->glWidget()->swapBuffers(); -#endif - return true; - } - default: - break; - } - } - - return false; -} - - -void HoverPoints::paintPoints() -{ - QPainter p; -#ifdef QT_OPENGL_SUPPORT - ArthurFrame *af = qobject_cast(m_widget); - if (af && af->usesOpenGL()) - p.begin(af->glWidget()); - else - p.begin(m_widget); -#else - p.begin(m_widget); -#endif - - p.setRenderHint(QPainter::Antialiasing); - - if (m_connectionPen.style() != Qt::NoPen && m_connectionType != NoConnection) { - p.setPen(m_connectionPen); - - if (m_connectionType == CurveConnection) { - QPainterPath path; - path.moveTo(m_points.at(0)); - for (int i=1; i right || (lock & HoverPoints::LockToRight)) p.setX(right); - - if (p.y() < top || (lock & HoverPoints::LockToTop)) p.setY(top); - else if (p.y() > bottom || (lock & HoverPoints::LockToBottom)) p.setY(bottom); - - return p; -} - -void HoverPoints::setPoints(const QPolygonF &points) -{ - if (points.size() != m_points.size()) - m_fingerPointMapping.clear(); - m_points.clear(); - for (int i=0; i 0) { - m_locks.resize(m_points.size()); - - m_locks.fill(0); - } -} - - -void HoverPoints::movePoint(int index, const QPointF &point, bool emitUpdate) -{ - m_points[index] = bound_point(point, boundingRect(), m_locks.at(index)); - if (emitUpdate) - firePointChange(); -} - - -inline static bool x_less_than(const QPointF &p1, const QPointF &p2) -{ - return p1.x() < p2.x(); -} - - -inline static bool y_less_than(const QPointF &p1, const QPointF &p2) -{ - return p1.y() < p2.y(); -} - -void HoverPoints::firePointChange() -{ -// printf("HoverPoints::firePointChange(), current=%d\n", m_currentIndex); - - if (m_sortType != NoSort) { - - QPointF oldCurrent; - if (m_currentIndex != -1) { - oldCurrent = m_points[m_currentIndex]; - } - - if (m_sortType == XSort) - qSort(m_points.begin(), m_points.end(), x_less_than); - else if (m_sortType == YSort) - qSort(m_points.begin(), m_points.end(), y_less_than); - - // Compensate for changed order... - if (m_currentIndex != -1) { - for (int i=0; i - -QT_FORWARD_DECLARE_CLASS(QBypassWidget) - -class HoverPoints : public QObject -{ - Q_OBJECT -public: - enum PointShape { - CircleShape, - RectangleShape - }; - - enum LockType { - LockToLeft = 0x01, - LockToRight = 0x02, - LockToTop = 0x04, - LockToBottom = 0x08 - }; - - enum SortType { - NoSort, - XSort, - YSort - }; - - enum ConnectionType { - NoConnection, - LineConnection, - CurveConnection - }; - - HoverPoints(QWidget *widget, PointShape shape); - - bool eventFilter(QObject *object, QEvent *event); - - void paintPoints(); - - inline QRectF boundingRect() const; - void setBoundingRect(const QRectF &boundingRect) { m_bounds = boundingRect; } - - QPolygonF points() const { return m_points; } - void setPoints(const QPolygonF &points); - - QSizeF pointSize() const { return m_pointSize; } - void setPointSize(const QSizeF &size) { m_pointSize = size; } - - SortType sortType() const { return m_sortType; } - void setSortType(SortType sortType) { m_sortType = sortType; } - - ConnectionType connectionType() const { return m_connectionType; } - void setConnectionType(ConnectionType connectionType) { m_connectionType = connectionType; } - - void setConnectionPen(const QPen &pen) { m_connectionPen = pen; } - void setShapePen(const QPen &pen) { m_pointPen = pen; } - void setShapeBrush(const QBrush &brush) { m_pointBrush = brush; } - - void setPointLock(int pos, LockType lock) { m_locks[pos] = lock; } - - void setEditable(bool editable) { m_editable = editable; } - bool editable() const { return m_editable; } - -public slots: - void setEnabled(bool enabled); - void setDisabled(bool disabled) { setEnabled(!disabled); } - -signals: - void pointsChanged(const QPolygonF &points); - -public: - void firePointChange(); - -private: - inline QRectF pointBoundingRect(int i) const; - void movePoint(int i, const QPointF &newPos, bool emitChange = true); - - QWidget *m_widget; - - QPolygonF m_points; - QRectF m_bounds; - PointShape m_shape; - SortType m_sortType; - ConnectionType m_connectionType; - - QVector m_locks; - - QSizeF m_pointSize; - int m_currentIndex; - bool m_editable; - bool m_enabled; - - QHash m_fingerPointMapping; - - QPen m_pointPen; - QBrush m_pointBrush; - QPen m_connectionPen; -}; - - -inline QRectF HoverPoints::pointBoundingRect(int i) const -{ - QPointF p = m_points.at(i); - qreal w = m_pointSize.width(); - qreal h = m_pointSize.height(); - qreal x = p.x() - w / 2; - qreal y = p.y() - h / 2; - return QRectF(x, y, w, h); -} - -inline QRectF HoverPoints::boundingRect() const -{ - if (m_bounds.isEmpty()) - return m_widget->rect(); - else - return m_bounds; -} - -#endif // HOVERPOINTS_H diff --git a/demos/shared/images/bg_pattern.png b/demos/shared/images/bg_pattern.png deleted file mode 100644 index ee670266f0..0000000000 Binary files a/demos/shared/images/bg_pattern.png and /dev/null differ diff --git a/demos/shared/images/button_normal_cap_left.png b/demos/shared/images/button_normal_cap_left.png deleted file mode 100644 index db31dd971d..0000000000 Binary files a/demos/shared/images/button_normal_cap_left.png and /dev/null differ diff --git a/demos/shared/images/button_normal_cap_right.png b/demos/shared/images/button_normal_cap_right.png deleted file mode 100644 index 38ead1c719..0000000000 Binary files a/demos/shared/images/button_normal_cap_right.png and /dev/null differ diff --git a/demos/shared/images/button_normal_stretch.png b/demos/shared/images/button_normal_stretch.png deleted file mode 100644 index 87abe67ac9..0000000000 Binary files a/demos/shared/images/button_normal_stretch.png and /dev/null differ diff --git a/demos/shared/images/button_pressed_cap_left.png b/demos/shared/images/button_pressed_cap_left.png deleted file mode 100644 index 66bfc13cb4..0000000000 Binary files a/demos/shared/images/button_pressed_cap_left.png and /dev/null differ diff --git a/demos/shared/images/button_pressed_cap_right.png b/demos/shared/images/button_pressed_cap_right.png deleted file mode 100644 index 3d4cfe25b1..0000000000 Binary files a/demos/shared/images/button_pressed_cap_right.png and /dev/null differ diff --git a/demos/shared/images/button_pressed_stretch.png b/demos/shared/images/button_pressed_stretch.png deleted file mode 100644 index 4dd4ad11e6..0000000000 Binary files a/demos/shared/images/button_pressed_stretch.png and /dev/null differ diff --git a/demos/shared/images/curve_thing_edit-6.png b/demos/shared/images/curve_thing_edit-6.png deleted file mode 100644 index 034b474d02..0000000000 Binary files a/demos/shared/images/curve_thing_edit-6.png and /dev/null differ diff --git a/demos/shared/images/frame_bottom.png b/demos/shared/images/frame_bottom.png deleted file mode 100644 index 889b40d304..0000000000 Binary files a/demos/shared/images/frame_bottom.png and /dev/null differ diff --git a/demos/shared/images/frame_bottomleft.png b/demos/shared/images/frame_bottomleft.png deleted file mode 100644 index 0b3023f397..0000000000 Binary files a/demos/shared/images/frame_bottomleft.png and /dev/null differ diff --git a/demos/shared/images/frame_bottomright.png b/demos/shared/images/frame_bottomright.png deleted file mode 100644 index 0021e35864..0000000000 Binary files a/demos/shared/images/frame_bottomright.png and /dev/null differ diff --git a/demos/shared/images/frame_left.png b/demos/shared/images/frame_left.png deleted file mode 100644 index 40f331c293..0000000000 Binary files a/demos/shared/images/frame_left.png and /dev/null differ diff --git a/demos/shared/images/frame_right.png b/demos/shared/images/frame_right.png deleted file mode 100644 index 023af8c700..0000000000 Binary files a/demos/shared/images/frame_right.png and /dev/null differ diff --git a/demos/shared/images/frame_top.png b/demos/shared/images/frame_top.png deleted file mode 100644 index 001f3a7144..0000000000 Binary files a/demos/shared/images/frame_top.png and /dev/null differ diff --git a/demos/shared/images/frame_topleft.png b/demos/shared/images/frame_topleft.png deleted file mode 100644 index 58c68d407a..0000000000 Binary files a/demos/shared/images/frame_topleft.png and /dev/null differ diff --git a/demos/shared/images/frame_topright.png b/demos/shared/images/frame_topright.png deleted file mode 100644 index 6a7e8d3eb3..0000000000 Binary files a/demos/shared/images/frame_topright.png and /dev/null differ diff --git a/demos/shared/images/groupframe_bottom_left.png b/demos/shared/images/groupframe_bottom_left.png deleted file mode 100644 index af2fe061e3..0000000000 Binary files a/demos/shared/images/groupframe_bottom_left.png and /dev/null differ diff --git a/demos/shared/images/groupframe_bottom_right.png b/demos/shared/images/groupframe_bottom_right.png deleted file mode 100644 index fdf2e97b13..0000000000 Binary files a/demos/shared/images/groupframe_bottom_right.png and /dev/null differ diff --git a/demos/shared/images/groupframe_bottom_stretch.png b/demos/shared/images/groupframe_bottom_stretch.png deleted file mode 100644 index f47b67d7c0..0000000000 Binary files a/demos/shared/images/groupframe_bottom_stretch.png and /dev/null differ diff --git a/demos/shared/images/groupframe_left_stretch.png b/demos/shared/images/groupframe_left_stretch.png deleted file mode 100644 index c122f462ed..0000000000 Binary files a/demos/shared/images/groupframe_left_stretch.png and /dev/null differ diff --git a/demos/shared/images/groupframe_right_stretch.png b/demos/shared/images/groupframe_right_stretch.png deleted file mode 100644 index 1056b7812a..0000000000 Binary files a/demos/shared/images/groupframe_right_stretch.png and /dev/null differ diff --git a/demos/shared/images/groupframe_top_stretch.png b/demos/shared/images/groupframe_top_stretch.png deleted file mode 100644 index 5746ef96fc..0000000000 Binary files a/demos/shared/images/groupframe_top_stretch.png and /dev/null differ diff --git a/demos/shared/images/groupframe_topleft.png b/demos/shared/images/groupframe_topleft.png deleted file mode 100644 index 98d9cd96b4..0000000000 Binary files a/demos/shared/images/groupframe_topleft.png and /dev/null differ diff --git a/demos/shared/images/groupframe_topright.png b/demos/shared/images/groupframe_topright.png deleted file mode 100644 index 1a0a328c20..0000000000 Binary files a/demos/shared/images/groupframe_topright.png and /dev/null differ diff --git a/demos/shared/images/line_dash_dot.png b/demos/shared/images/line_dash_dot.png deleted file mode 100644 index 1c61442d9f..0000000000 Binary files a/demos/shared/images/line_dash_dot.png and /dev/null differ diff --git a/demos/shared/images/line_dash_dot_dot.png b/demos/shared/images/line_dash_dot_dot.png deleted file mode 100644 index 0d9bb972f9..0000000000 Binary files a/demos/shared/images/line_dash_dot_dot.png and /dev/null differ diff --git a/demos/shared/images/line_dashed.png b/demos/shared/images/line_dashed.png deleted file mode 100644 index d5bc7ea5fe..0000000000 Binary files a/demos/shared/images/line_dashed.png and /dev/null differ diff --git a/demos/shared/images/line_dotted.png b/demos/shared/images/line_dotted.png deleted file mode 100644 index a2f9a35925..0000000000 Binary files a/demos/shared/images/line_dotted.png and /dev/null differ diff --git a/demos/shared/images/line_solid.png b/demos/shared/images/line_solid.png deleted file mode 100644 index 60ef3f9485..0000000000 Binary files a/demos/shared/images/line_solid.png and /dev/null differ diff --git a/demos/shared/images/radiobutton-off.png b/demos/shared/images/radiobutton-off.png deleted file mode 100644 index af1753a3e7..0000000000 Binary files a/demos/shared/images/radiobutton-off.png and /dev/null differ diff --git a/demos/shared/images/radiobutton-on.png b/demos/shared/images/radiobutton-on.png deleted file mode 100644 index f875838bb5..0000000000 Binary files a/demos/shared/images/radiobutton-on.png and /dev/null differ diff --git a/demos/shared/images/radiobutton_off.png b/demos/shared/images/radiobutton_off.png deleted file mode 100644 index 400906ebfa..0000000000 Binary files a/demos/shared/images/radiobutton_off.png and /dev/null differ diff --git a/demos/shared/images/radiobutton_on.png b/demos/shared/images/radiobutton_on.png deleted file mode 100644 index 50a049ec56..0000000000 Binary files a/demos/shared/images/radiobutton_on.png and /dev/null differ diff --git a/demos/shared/images/slider_bar.png b/demos/shared/images/slider_bar.png deleted file mode 100644 index 1b3d62c007..0000000000 Binary files a/demos/shared/images/slider_bar.png and /dev/null differ diff --git a/demos/shared/images/slider_thumb_off.png b/demos/shared/images/slider_thumb_off.png deleted file mode 100644 index d7f141daef..0000000000 Binary files a/demos/shared/images/slider_thumb_off.png and /dev/null differ diff --git a/demos/shared/images/slider_thumb_on.png b/demos/shared/images/slider_thumb_on.png deleted file mode 100644 index 8e1f510813..0000000000 Binary files a/demos/shared/images/slider_thumb_on.png and /dev/null differ diff --git a/demos/shared/images/title_cap_left.png b/demos/shared/images/title_cap_left.png deleted file mode 100644 index 2d475070c8..0000000000 Binary files a/demos/shared/images/title_cap_left.png and /dev/null differ diff --git a/demos/shared/images/title_cap_right.png b/demos/shared/images/title_cap_right.png deleted file mode 100644 index dc3ff8536c..0000000000 Binary files a/demos/shared/images/title_cap_right.png and /dev/null differ diff --git a/demos/shared/images/title_stretch.png b/demos/shared/images/title_stretch.png deleted file mode 100644 index 11043345d0..0000000000 Binary files a/demos/shared/images/title_stretch.png and /dev/null differ diff --git a/demos/shared/shared.pri b/demos/shared/shared.pri deleted file mode 100644 index fb7b04c0be..0000000000 --- a/demos/shared/shared.pri +++ /dev/null @@ -1,21 +0,0 @@ -INCLUDEPATH += $$SHARED_FOLDER - -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} -contains(CONFIG, debug_and_release_target) { - CONFIG(debug, debug|release) { - QMAKE_LIBDIR += $$SHARED_FOLDER/debug - } else { - QMAKE_LIBDIR += $$SHARED_FOLDER/release - } -} else { - QMAKE_LIBDIR += $$SHARED_FOLDER -} - -hpux-acc*:LIBS += $$SHARED_FOLDER/libdemo_shared.a -hpuxi-acc*:LIBS += $$SHARED_FOLDER/libdemo_shared.a -symbian:LIBS += -ldemo_shared.lib -!hpuxi-acc*:!hpux-acc*:!symbian:LIBS += -ldemo_shared - diff --git a/demos/shared/shared.pro b/demos/shared/shared.pro deleted file mode 100644 index 88d7fbedab..0000000000 --- a/demos/shared/shared.pro +++ /dev/null @@ -1,39 +0,0 @@ -TEMPLATE = lib -CONFIG += static - -contains(QT_CONFIG, opengl)|contains(QT_CONFIG, opengles1)|contains(QT_CONFIG, opengles2) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} - -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} -TARGET = demo_shared -QT += gui-private - -SOURCES += \ - arthurstyle.cpp\ - arthurwidgets.cpp \ - hoverpoints.cpp - -HEADERS += \ - arthurstyle.h \ - arthurwidgets.h \ - hoverpoints.h - -RESOURCES += shared.qrc - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/shared -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.pri images -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/shared -INSTALLS += sources - -!cross_compile:INSTALLS += target - -symbian { - TARGET.UID3 = 0xA000A63C - CONFIG += qt_demo -} diff --git a/demos/shared/shared.qrc b/demos/shared/shared.qrc deleted file mode 100644 index 17336ecf80..0000000000 --- a/demos/shared/shared.qrc +++ /dev/null @@ -1,39 +0,0 @@ - - - images/button_normal_cap_left.png - images/button_normal_cap_right.png - images/button_normal_stretch.png - images/button_pressed_cap_left.png - images/button_pressed_cap_right.png - images/button_pressed_stretch.png - images/radiobutton-on.png - images/radiobutton_on.png - images/radiobutton_off.png - images/slider_bar.png - images/slider_thumb_on.png - images/groupframe_topleft.png - images/groupframe_topright.png - images/groupframe_bottom_left.png - images/groupframe_bottom_right.png - images/groupframe_top_stretch.png - images/groupframe_bottom_stretch.png - images/groupframe_left_stretch.png - images/groupframe_right_stretch.png - images/frame_topleft.png - images/frame_topright.png - images/frame_bottomleft.png - images/frame_bottomright.png - images/frame_left.png - images/frame_top.png - images/frame_right.png - images/frame_bottom.png - images/title_cap_left.png - images/title_cap_right.png - images/title_stretch.png - images/line_dash_dot.png - images/line_dotted.png - images/line_dashed.png - images/line_solid.png - images/line_dash_dot_dot.png - - diff --git a/demos/spreadsheet/images/interview.png b/demos/spreadsheet/images/interview.png deleted file mode 100644 index 0c3d690258..0000000000 Binary files a/demos/spreadsheet/images/interview.png and /dev/null differ diff --git a/demos/spreadsheet/main.cpp b/demos/spreadsheet/main.cpp deleted file mode 100644 index 4c20646f9c..0000000000 --- a/demos/spreadsheet/main.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "spreadsheet.h" - -int main(int argc, char** argv) { - Q_INIT_RESOURCE(spreadsheet); - QApplication app(argc, argv); - SpreadSheet sheet(10, 6); - sheet.setWindowIcon(QPixmap(":/images/interview.png")); - sheet.resize(640, 420); - sheet.show(); - return app.exec(); -} - - diff --git a/demos/spreadsheet/printview.cpp b/demos/spreadsheet/printview.cpp deleted file mode 100644 index 0962e28844..0000000000 --- a/demos/spreadsheet/printview.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "printview.h" -#include -#include - -PrintView::PrintView() -{ - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); -} - -void PrintView::print(QPrinter *printer) -{ -#ifndef QT_NO_PRINTER - resize(printer->width(), printer->height()); - render(printer); -#endif -} - diff --git a/demos/spreadsheet/printview.h b/demos/spreadsheet/printview.h deleted file mode 100644 index 7c74844483..0000000000 --- a/demos/spreadsheet/printview.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef PRINTVIEW_H -#define PRINTVIEW_H - -#include - -class PrintView : public QTableView -{ - Q_OBJECT - -public: - PrintView(); - -public Q_SLOTS: - void print(QPrinter *printer); -}; - -#endif // PRINTVIEW_H - - diff --git a/demos/spreadsheet/spreadsheet.cpp b/demos/spreadsheet/spreadsheet.cpp deleted file mode 100644 index 6b99521b7b..0000000000 --- a/demos/spreadsheet/spreadsheet.cpp +++ /dev/null @@ -1,633 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "spreadsheet.h" -#include "spreadsheetdelegate.h" -#include "spreadsheetitem.h" -#include "printview.h" - -SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent) - : QMainWindow(parent) -{ - addToolBar(toolBar = new QToolBar()); - formulaInput = new QLineEdit(); - - cellLabel = new QLabel(toolBar); - cellLabel->setMinimumSize(80, 0); - - toolBar->addWidget(cellLabel); - toolBar->addWidget(formulaInput); - - table = new QTableWidget(rows, cols, this); - for (int c = 0; c < cols; ++c) { - QString character(QChar('A' + c)); - table->setHorizontalHeaderItem(c, new QTableWidgetItem(character)); - } - - table->setItemPrototype(table->item(rows -1, cols - 1)); - table->setItemDelegate(new SpreadSheetDelegate()); - - createActions(); - updateColor(0); - setupMenuBar(); - setupContents(); - setupContextMenu(); - setCentralWidget(table); - - statusBar(); - connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), - this, SLOT(updateStatus(QTableWidgetItem*))); - connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), - this, SLOT(updateColor(QTableWidgetItem*))); - connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), - this, SLOT(updateLineEdit(QTableWidgetItem*))); - connect(table, SIGNAL(itemChanged(QTableWidgetItem*)), - this, SLOT(updateStatus(QTableWidgetItem*))); - connect(formulaInput, SIGNAL(returnPressed()), this, SLOT(returnPressed())); - connect(table, SIGNAL(itemChanged(QTableWidgetItem*)), - this, SLOT(updateLineEdit(QTableWidgetItem*))); - - setWindowTitle(tr("Spreadsheet")); -} - -void SpreadSheet::createActions() -{ - cell_sumAction = new QAction(tr("Sum"), this); - connect(cell_sumAction, SIGNAL(triggered()), this, SLOT(actionSum())); - - cell_addAction = new QAction(tr("&Add"), this); - cell_addAction->setShortcut(Qt::CTRL | Qt::Key_Plus); - connect(cell_addAction, SIGNAL(triggered()), this, SLOT(actionAdd())); - - cell_subAction = new QAction(tr("&Subtract"), this); - cell_subAction->setShortcut(Qt::CTRL | Qt::Key_Minus); - connect(cell_subAction, SIGNAL(triggered()), this, SLOT(actionSubtract())); - - cell_mulAction = new QAction(tr("&Multiply"), this); - cell_mulAction->setShortcut(Qt::CTRL | Qt::Key_multiply); - connect(cell_mulAction, SIGNAL(triggered()), this, SLOT(actionMultiply())); - - cell_divAction = new QAction(tr("&Divide"), this); - cell_divAction->setShortcut(Qt::CTRL | Qt::Key_division); - connect(cell_divAction, SIGNAL(triggered()), this, SLOT(actionDivide())); - - fontAction = new QAction(tr("Font..."), this); - fontAction->setShortcut(Qt::CTRL | Qt::Key_F); - connect(fontAction, SIGNAL(triggered()), this, SLOT(selectFont())); - - colorAction = new QAction(QPixmap(16, 16), tr("Background &Color..."), this); - connect(colorAction, SIGNAL(triggered()), this, SLOT(selectColor())); - - clearAction = new QAction(tr("Clear"), this); - clearAction->setShortcut(Qt::Key_Delete); - connect(clearAction, SIGNAL(triggered()), this, SLOT(clear())); - - aboutSpreadSheet = new QAction(tr("About Spreadsheet"), this); - connect(aboutSpreadSheet, SIGNAL(triggered()), this, SLOT(showAbout())); - - exitAction = new QAction(tr("E&xit"), this); - connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); - - printAction = new QAction(tr("&Print"), this); - connect(printAction, SIGNAL(triggered()), this, SLOT(print())); - - firstSeparator = new QAction(this); - firstSeparator->setSeparator(true); - - secondSeparator = new QAction(this); - secondSeparator->setSeparator(true); -} - -void SpreadSheet::setupMenuBar() -{ - QMenu *fileMenu = menuBar()->addMenu(tr("&File")); - fileMenu->addAction(printAction); - fileMenu->addAction(exitAction); - - QMenu *cellMenu = menuBar()->addMenu(tr("&Cell")); - cellMenu->addAction(cell_addAction); - cellMenu->addAction(cell_subAction); - cellMenu->addAction(cell_mulAction); - cellMenu->addAction(cell_divAction); - cellMenu->addAction(cell_sumAction); - cellMenu->addSeparator(); - cellMenu->addAction(colorAction); - cellMenu->addAction(fontAction); - - menuBar()->addSeparator(); - - QMenu *aboutMenu = menuBar()->addMenu(tr("&Help")); - aboutMenu->addAction(aboutSpreadSheet); -} - -void SpreadSheet::updateStatus(QTableWidgetItem *item) -{ - if (item && item == table->currentItem()) { - statusBar()->showMessage(item->data(Qt::StatusTipRole).toString(), - 1000); - cellLabel->setText(tr("Cell: (%1)").arg(encode_pos(table->row(item), - table->column(item)))); - } -} - -void SpreadSheet::updateColor(QTableWidgetItem *item) -{ - QPixmap pix(16, 16); - QColor col; - if (item) - col = item->backgroundColor(); - if (!col.isValid()) - col = palette().base().color(); - - QPainter pt(&pix); - pt.fillRect(0, 0, 16, 16, col); - - QColor lighter = col.light(); - pt.setPen(lighter); - QPoint lightFrame[] = { QPoint(0, 15), QPoint(0, 0), QPoint(15, 0) }; - pt.drawPolyline(lightFrame, 3); - - pt.setPen(col.dark()); - QPoint darkFrame[] = { QPoint(1, 15), QPoint(15, 15), QPoint(15, 1) }; - pt.drawPolyline(darkFrame, 3); - - pt.end(); - - colorAction->setIcon(pix); -} - -void SpreadSheet::updateLineEdit(QTableWidgetItem *item) -{ - if (item != table->currentItem()) - return; - if (item) - formulaInput->setText(item->data(Qt::EditRole).toString()); - else - formulaInput->clear(); -} - -void SpreadSheet::returnPressed() -{ - QString text = formulaInput->text(); - int row = table->currentRow(); - int col = table->currentColumn(); - QTableWidgetItem *item = table->item(row, col); - if (!item) - table->setItem(row, col, new SpreadSheetItem(text)); - else - item->setData(Qt::EditRole, text); - table->viewport()->update(); -} - -void SpreadSheet::selectColor() -{ - QTableWidgetItem *item = table->currentItem(); - QColor col = item ? item->backgroundColor() : table->palette().base().color(); - col = QColorDialog::getColor(col, this); - if (!col.isValid()) - return; - - QList selected = table->selectedItems(); - if (selected.count() == 0) - return; - - foreach(QTableWidgetItem *i, selected) - if (i) - i->setBackgroundColor(col); - - updateColor(table->currentItem()); -} - -void SpreadSheet::selectFont() -{ - QList selected = table->selectedItems(); - if (selected.count() == 0) - return; - - bool ok = false; - QFont fnt = QFontDialog::getFont(&ok, font(), this); - - if (!ok) - return; - foreach(QTableWidgetItem *i, selected) - if (i) - i->setFont(fnt); -} - -bool SpreadSheet::runInputDialog(const QString &title, - const QString &c1Text, - const QString &c2Text, - const QString &opText, - const QString &outText, - QString *cell1, QString *cell2, QString *outCell) -{ - QStringList rows, cols; - for (int c = 0; c < table->columnCount(); ++c) - cols << QChar('A' + c); - for (int r = 0; r < table->rowCount(); ++r) - rows << QString::number(1 + r); - - QDialog addDialog(this); - addDialog.setWindowTitle(title); - - QGroupBox group(title, &addDialog); - group.setMinimumSize(250, 100); - - QLabel cell1Label(c1Text, &group); - QComboBox cell1RowInput(&group); - int c1Row, c1Col; - decode_pos(*cell1, &c1Row, &c1Col); - cell1RowInput.addItems(rows); - cell1RowInput.setCurrentIndex(c1Row); - - QComboBox cell1ColInput(&group); - cell1ColInput.addItems(cols); - cell1ColInput.setCurrentIndex(c1Col); - - QLabel operatorLabel(opText, &group); - operatorLabel.setAlignment(Qt::AlignHCenter); - - QLabel cell2Label(c2Text, &group); - QComboBox cell2RowInput(&group); - int c2Row, c2Col; - decode_pos(*cell2, &c2Row, &c2Col); - cell2RowInput.addItems(rows); - cell2RowInput.setCurrentIndex(c2Row); - QComboBox cell2ColInput(&group); - cell2ColInput.addItems(cols); - cell2ColInput.setCurrentIndex(c2Col); - - QLabel equalsLabel("=", &group); - equalsLabel.setAlignment(Qt::AlignHCenter); - - QLabel outLabel(outText, &group); - QComboBox outRowInput(&group); - int outRow, outCol; - decode_pos(*outCell, &outRow, &outCol); - outRowInput.addItems(rows); - outRowInput.setCurrentIndex(outRow); - QComboBox outColInput(&group); - outColInput.addItems(cols); - outColInput.setCurrentIndex(outCol); - - QPushButton cancelButton(tr("Cancel"), &addDialog); - connect(&cancelButton, SIGNAL(clicked()), &addDialog, SLOT(reject())); - - QPushButton okButton(tr("OK"), &addDialog); - okButton.setDefault(true); - connect(&okButton, SIGNAL(clicked()), &addDialog, SLOT(accept())); - - QHBoxLayout *buttonsLayout = new QHBoxLayout; - buttonsLayout->addStretch(1); - buttonsLayout->addWidget(&okButton); - buttonsLayout->addSpacing(10); - buttonsLayout->addWidget(&cancelButton); - - QVBoxLayout *dialogLayout = new QVBoxLayout(&addDialog); - dialogLayout->addWidget(&group); - dialogLayout->addStretch(1); - dialogLayout->addItem(buttonsLayout); - - QHBoxLayout *cell1Layout = new QHBoxLayout; - cell1Layout->addWidget(&cell1Label); - cell1Layout->addSpacing(10); - cell1Layout->addWidget(&cell1ColInput); - cell1Layout->addSpacing(10); - cell1Layout->addWidget(&cell1RowInput); - - QHBoxLayout *cell2Layout = new QHBoxLayout; - cell2Layout->addWidget(&cell2Label); - cell2Layout->addSpacing(10); - cell2Layout->addWidget(&cell2ColInput); - cell2Layout->addSpacing(10); - cell2Layout->addWidget(&cell2RowInput); - - QHBoxLayout *outLayout = new QHBoxLayout; - outLayout->addWidget(&outLabel); - outLayout->addSpacing(10); - outLayout->addWidget(&outColInput); - outLayout->addSpacing(10); - outLayout->addWidget(&outRowInput); - - QVBoxLayout *vLayout = new QVBoxLayout(&group); - vLayout->addItem(cell1Layout); - vLayout->addWidget(&operatorLabel); - vLayout->addItem(cell2Layout); - vLayout->addWidget(&equalsLabel); - vLayout->addStretch(1); - vLayout->addItem(outLayout); - - if (addDialog.exec()) { - *cell1 = cell1ColInput.currentText() + cell1RowInput.currentText(); - *cell2 = cell2ColInput.currentText() + cell2RowInput.currentText(); - *outCell = outColInput.currentText() + outRowInput.currentText(); - return true; - } - - return false; -} - -void SpreadSheet::actionSum() -{ - int row_first = 0; - int row_last = 0; - int row_cur = 0; - - int col_first = 0; - int col_last = 0; - int col_cur = 0; - - QList selected = table->selectedItems(); - - if (!selected.isEmpty()) { - QTableWidgetItem *first = selected.first(); - QTableWidgetItem *last = selected.last(); - row_first = table->row(first); - row_last = table->row(last); - col_first = table->column(first); - col_last = table->column(last); - } - - QTableWidgetItem *current = table->currentItem(); - - if (current) { - row_cur = table->row(current); - col_cur = table->column(current); - } - - QString cell1 = encode_pos(row_first, col_first); - QString cell2 = encode_pos(row_last, col_last); - QString out = encode_pos(row_cur, col_cur); - - if (runInputDialog(tr("Sum cells"), tr("First cell:"), tr("Last cell:"), - QString("%1").arg(QChar(0x03a3)), tr("Output to:"), - &cell1, &cell2, &out)) { - int row, col; - decode_pos(out, &row, &col); - table->item(row, col)->setText(tr("sum %1 %2").arg(cell1, cell2)); - } -} - -void SpreadSheet::actionMath_helper(const QString &title, const QString &op) -{ - QString cell1 = "C1"; - QString cell2 = "C2"; - QString out = "C3"; - - QTableWidgetItem *current = table->currentItem(); - if (current) - out = encode_pos(table->currentRow(), table->currentColumn()); - - if (runInputDialog(title, tr("Cell 1"), tr("Cell 2"), op, tr("Output to:"), - &cell1, &cell2, &out)) { - int row, col; - decode_pos(out, &row, &col); - table->item(row, col)->setText(tr("%1 %2 %3").arg(op, cell1, cell2)); - } -} - -void SpreadSheet::actionAdd() -{ - actionMath_helper(tr("Addition"), "+"); -} - -void SpreadSheet::actionSubtract() -{ - actionMath_helper(tr("Subtraction"), "-"); -} - -void SpreadSheet::actionMultiply() -{ - actionMath_helper(tr("Multiplication"), "*"); -} -void SpreadSheet::actionDivide() -{ - actionMath_helper(tr("Division"), "/"); -} - -void SpreadSheet::clear() -{ - foreach (QTableWidgetItem *i, table->selectedItems()) - i->setText(""); -} - -void SpreadSheet::setupContextMenu() -{ - addAction(cell_addAction); - addAction(cell_subAction); - addAction(cell_mulAction); - addAction(cell_divAction); - addAction(cell_sumAction); - addAction(firstSeparator); - addAction(colorAction); - addAction(fontAction); - addAction(secondSeparator); - addAction(clearAction); - setContextMenuPolicy(Qt::ActionsContextMenu); -} - -void SpreadSheet::setupContents() -{ - QColor titleBackground(Qt::lightGray); - QFont titleFont = table->font(); - titleFont.setBold(true); - - // column 0 - table->setItem(0, 0, new SpreadSheetItem("Item")); - table->item(0, 0)->setBackgroundColor(titleBackground); - table->item(0, 0)->setToolTip("This column shows the purchased item/service"); - table->item(0, 0)->setFont(titleFont); - - table->setItem(1, 0, new SpreadSheetItem("AirportBus")); - table->setItem(2, 0, new SpreadSheetItem("Flight (Munich)")); - table->setItem(3, 0, new SpreadSheetItem("Lunch")); - table->setItem(4, 0, new SpreadSheetItem("Flight (LA)")); - table->setItem(5, 0, new SpreadSheetItem("Taxi")); - table->setItem(6, 0, new SpreadSheetItem("Dinner")); - table->setItem(7, 0, new SpreadSheetItem("Hotel")); - table->setItem(8, 0, new SpreadSheetItem("Flight (Oslo)")); - table->setItem(9, 0, new SpreadSheetItem("Total:")); - - table->item(9, 0)->setFont(titleFont); - table->item(9, 0)->setBackgroundColor(Qt::lightGray); - - // column 1 - table->setItem(0, 1, new SpreadSheetItem("Date")); - table->item(0, 1)->setBackgroundColor(titleBackground); - table->item(0, 1)->setToolTip("This column shows the purchase date, double click to change"); - table->item(0, 1)->setFont(titleFont); - - table->setItem(1, 1, new SpreadSheetItem("15/6/2006")); - table->setItem(2, 1, new SpreadSheetItem("15/6/2006")); - table->setItem(3, 1, new SpreadSheetItem("15/6/2006")); - table->setItem(4, 1, new SpreadSheetItem("21/5/2006")); - table->setItem(5, 1, new SpreadSheetItem("16/6/2006")); - table->setItem(6, 1, new SpreadSheetItem("16/6/2006")); - table->setItem(7, 1, new SpreadSheetItem("16/6/2006")); - table->setItem(8, 1, new SpreadSheetItem("18/6/2006")); - - table->setItem(9, 1, new SpreadSheetItem()); - table->item(9, 1)->setBackgroundColor(Qt::lightGray); - - // column 2 - table->setItem(0, 2, new SpreadSheetItem("Price")); - table->item(0, 2)->setBackgroundColor(titleBackground); - table->item(0, 2)->setToolTip("This column shows the price of the purchase"); - table->item(0, 2)->setFont(titleFont); - - table->setItem(1, 2, new SpreadSheetItem("150")); - table->setItem(2, 2, new SpreadSheetItem("2350")); - table->setItem(3, 2, new SpreadSheetItem("-14")); - table->setItem(4, 2, new SpreadSheetItem("980")); - table->setItem(5, 2, new SpreadSheetItem("5")); - table->setItem(6, 2, new SpreadSheetItem("120")); - table->setItem(7, 2, new SpreadSheetItem("300")); - table->setItem(8, 2, new SpreadSheetItem("1240")); - - table->setItem(9, 2, new SpreadSheetItem()); - table->item(9, 2)->setBackgroundColor(Qt::lightGray); - - // column 3 - table->setItem(0, 3, new SpreadSheetItem("Currency")); - table->item(0, 3)->setBackgroundColor(titleBackground); - table->item(0, 3)->setToolTip("This column shows the currency"); - table->item(0, 3)->setFont(titleFont); - - table->setItem(1, 3, new SpreadSheetItem("NOK")); - table->setItem(2, 3, new SpreadSheetItem("NOK")); - table->setItem(3, 3, new SpreadSheetItem("EUR")); - table->setItem(4, 3, new SpreadSheetItem("EUR")); - table->setItem(5, 3, new SpreadSheetItem("USD")); - table->setItem(6, 3, new SpreadSheetItem("USD")); - table->setItem(7, 3, new SpreadSheetItem("USD")); - table->setItem(8, 3, new SpreadSheetItem("USD")); - - table->setItem(9, 3, new SpreadSheetItem()); - table->item(9,3)->setBackgroundColor(Qt::lightGray); - - // column 4 - table->setItem(0, 4, new SpreadSheetItem("Ex. Rate")); - table->item(0, 4)->setBackgroundColor(titleBackground); - table->item(0, 4)->setToolTip("This column shows the exchange rate to NOK"); - table->item(0, 4)->setFont(titleFont); - - table->setItem(1, 4, new SpreadSheetItem("1")); - table->setItem(2, 4, new SpreadSheetItem("1")); - table->setItem(3, 4, new SpreadSheetItem("8")); - table->setItem(4, 4, new SpreadSheetItem("8")); - table->setItem(5, 4, new SpreadSheetItem("7")); - table->setItem(6, 4, new SpreadSheetItem("7")); - table->setItem(7, 4, new SpreadSheetItem("7")); - table->setItem(8, 4, new SpreadSheetItem("7")); - - table->setItem(9, 4, new SpreadSheetItem()); - table->item(9,4)->setBackgroundColor(Qt::lightGray); - - // column 5 - table->setItem(0, 5, new SpreadSheetItem("NOK")); - table->item(0, 5)->setBackgroundColor(titleBackground); - table->item(0, 5)->setToolTip("This column shows the expenses in NOK"); - table->item(0, 5)->setFont(titleFont); - - table->setItem(1, 5, new SpreadSheetItem("* C2 E2")); - table->setItem(2, 5, new SpreadSheetItem("* C3 E3")); - table->setItem(3, 5, new SpreadSheetItem("* C4 E4")); - table->setItem(4, 5, new SpreadSheetItem("* C5 E5")); - table->setItem(5, 5, new SpreadSheetItem("* C6 E6")); - table->setItem(6, 5, new SpreadSheetItem("* C7 E7")); - table->setItem(7, 5, new SpreadSheetItem("* C8 E8")); - table->setItem(8, 5, new SpreadSheetItem("* C9 E9")); - - table->setItem(9, 5, new SpreadSheetItem("sum F2 F9")); - table->item(9,5)->setBackgroundColor(Qt::lightGray); -} - -const char *htmlText = -"" -"

This demo shows use of QTableWidget with custom handling for" -" individual cells.

" -"

Using a customized table item we make it possible to have dynamic" -" output in different cells. The content that is implemented for this" -" particular demo is:" -"

    " -"
  • Adding two cells.
  • " -"
  • Subtracting one cell from another.
  • " -"
  • Multiplying two cells.
  • " -"
  • Dividing one cell with another.
  • " -"
  • Summing the contents of an arbitrary number of cells.
  • " -""; - -void SpreadSheet::showAbout() -{ - QMessageBox::about(this, "About Spreadsheet", htmlText); -} - -void decode_pos(const QString &pos, int *row, int *col) -{ - if (pos.isEmpty()) { - *col = -1; - *row = -1; - } else { - *col = pos.at(0).toLatin1() - 'A'; - *row = pos.right(pos.size() - 1).toInt() - 1; - } -} - -QString encode_pos(int row, int col) -{ - return QString(col + 'A') + QString::number(row + 1); -} - - -void SpreadSheet::print() -{ -#ifndef QT_NO_PRINTER - QPrinter printer(QPrinter::ScreenResolution); - QPrintPreviewDialog dlg(&printer); - PrintView view; - view.setModel(table->model()); - connect(&dlg, SIGNAL(paintRequested(QPrinter*)), - &view, SLOT(print(QPrinter*))); - dlg.exec(); -#endif -} - diff --git a/demos/spreadsheet/spreadsheet.h b/demos/spreadsheet/spreadsheet.h deleted file mode 100644 index 386a469c99..0000000000 --- a/demos/spreadsheet/spreadsheet.h +++ /dev/null @@ -1,124 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SPREADSHEET_H -#define SPREADSHEET_H - -#include - -QT_BEGIN_NAMESPACE -class QAction; -class QLabel; -class QLineEdit; -class QToolBar; -class QTableWidgetItem; -class QTableWidget; -QT_END_NAMESPACE - -class SpreadSheet : public QMainWindow -{ - Q_OBJECT - -public: - - SpreadSheet(int rows, int cols, QWidget *parent = 0); - -public slots: - void updateStatus(QTableWidgetItem *item); - void updateColor(QTableWidgetItem *item); - void updateLineEdit(QTableWidgetItem *item); - void returnPressed(); - void selectColor(); - void selectFont(); - void clear(); - void showAbout(); - - void print(); - - void actionSum(); - void actionSubtract(); - void actionAdd(); - void actionMultiply(); - void actionDivide(); - -protected: - void setupContextMenu(); - void setupContents(); - - void setupMenuBar(); - void createActions(); - - void actionMath_helper(const QString &title, const QString &op); - bool runInputDialog(const QString &title, - const QString &c1Text, - const QString &c2Text, - const QString &opText, - const QString &outText, - QString *cell1, QString *cell2, QString *outCell); -private: - QToolBar *toolBar; - QAction *colorAction; - QAction *fontAction; - QAction *firstSeparator; - QAction *cell_sumAction; - QAction *cell_addAction; - QAction *cell_subAction; - QAction *cell_mulAction; - QAction *cell_divAction; - QAction *secondSeparator; - QAction *clearAction; - QAction *aboutSpreadSheet; - QAction *exitAction; - - QAction *printAction; - - QLabel *cellLabel; - QTableWidget *table; - QLineEdit *formulaInput; - -}; - -void decode_pos(const QString &pos, int *row, int *col); -QString encode_pos(int row, int col); - - -#endif // SPREADSHEET_H - diff --git a/demos/spreadsheet/spreadsheet.pro b/demos/spreadsheet/spreadsheet.pro deleted file mode 100644 index 7179d98eba..0000000000 --- a/demos/spreadsheet/spreadsheet.pro +++ /dev/null @@ -1,34 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) Thu Mar 5 14:39:33 2009 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -CONFIG += qt warn_on -#unix:contains(QT_CONFIG, dbus):QT += dbus - -# Input -HEADERS += printview.h spreadsheet.h spreadsheetdelegate.h spreadsheetitem.h -SOURCES += main.cpp \ - printview.cpp \ - spreadsheet.cpp \ - spreadsheetdelegate.cpp \ - spreadsheetitem.cpp -RESOURCES += spreadsheet.qrc - - -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/spreadsheet -sources.files = $$SOURCES $$RESOURCES *.pro images $$HEADERS -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/spreadsheet -INSTALLS += target sources - -symbian: CONFIG += qt_demo diff --git a/demos/spreadsheet/spreadsheet.qrc b/demos/spreadsheet/spreadsheet.qrc deleted file mode 100644 index 13f496d8e3..0000000000 --- a/demos/spreadsheet/spreadsheet.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - images/interview.png - - diff --git a/demos/spreadsheet/spreadsheetdelegate.cpp b/demos/spreadsheet/spreadsheetdelegate.cpp deleted file mode 100644 index 6f2f2dd071..0000000000 --- a/demos/spreadsheet/spreadsheetdelegate.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "spreadsheetdelegate.h" -#include - -SpreadSheetDelegate::SpreadSheetDelegate(QObject *parent) - : QItemDelegate(parent) {} - -QWidget *SpreadSheetDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &, - const QModelIndex &index) const -{ - if (index.column() == 1) { - QDateTimeEdit *editor = new QDateTimeEdit(parent); - editor->setDisplayFormat("dd/M/yyyy"); - editor->setCalendarPopup(true); - return editor; - } - - QLineEdit *editor = new QLineEdit(parent); - - // create a completer with the strings in the column as model - QStringList allStrings; - for (int i = 1; irowCount(); i++) { - QString strItem(index.model()->data(index.sibling(i, index.column()), - Qt::EditRole).toString()); - - if (!allStrings.contains(strItem)) - allStrings.append(strItem); - } - - QCompleter *autoComplete = new QCompleter(allStrings); - editor->setCompleter(autoComplete); - connect(editor, SIGNAL(editingFinished()), - this, SLOT(commitAndCloseEditor())); - return editor; -} - -void SpreadSheetDelegate::commitAndCloseEditor() -{ - QLineEdit *editor = qobject_cast(sender()); - emit commitData(editor); - emit closeEditor(editor); -} - -void SpreadSheetDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const -{ - QLineEdit *edit = qobject_cast(editor); - if (edit) { - edit->setText(index.model()->data(index, Qt::EditRole).toString()); - } else { - QDateTimeEdit *dateEditor = qobject_cast(editor); - if (dateEditor) { - dateEditor->setDate(QDate::fromString( - index.model()->data(index, Qt::EditRole).toString(), - "d/M/yyyy")); - } - } -} - -void SpreadSheetDelegate::setModelData(QWidget *editor, - QAbstractItemModel *model, const QModelIndex &index) const -{ - QLineEdit *edit = qobject_cast(editor); - if (edit) { - model->setData(index, edit->text()); - } else { - QDateTimeEdit *dateEditor = qobject_cast(editor); - if (dateEditor) { - model->setData(index, dateEditor->date().toString("dd/M/yyyy")); - } - } -} - diff --git a/demos/spreadsheet/spreadsheetdelegate.h b/demos/spreadsheet/spreadsheetdelegate.h deleted file mode 100644 index 7987f35499..0000000000 --- a/demos/spreadsheet/spreadsheetdelegate.h +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SPREADSHEETDELEGATE_H -#define SPREADSHEETDELEGATE_H - -#include -#include "spreadsheet.h" - -class SpreadSheetDelegate : public QItemDelegate -{ - Q_OBJECT - -public: - SpreadSheetDelegate(QObject *parent = 0); - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &, - const QModelIndex &index) const; - void setEditorData(QWidget *editor, const QModelIndex &index) const; - void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const; - -private slots: - void commitAndCloseEditor(); -}; - -#endif // SPREADSHEETDELEGATE_H - diff --git a/demos/spreadsheet/spreadsheetitem.cpp b/demos/spreadsheet/spreadsheetitem.cpp deleted file mode 100644 index 74a1967a8a..0000000000 --- a/demos/spreadsheet/spreadsheetitem.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "spreadsheetitem.h" - -SpreadSheetItem::SpreadSheetItem() - : QTableWidgetItem(), isResolving(false) -{ -} - -SpreadSheetItem::SpreadSheetItem(const QString &text) - : QTableWidgetItem(text), isResolving(false) -{ -} - -QTableWidgetItem *SpreadSheetItem::clone() const -{ - SpreadSheetItem *item = new SpreadSheetItem(); - *item = *this; - return item; -} - -QVariant SpreadSheetItem::data(int role) const -{ - if (role == Qt::EditRole || role == Qt::StatusTipRole) - return formula(); - - if (role == Qt::DisplayRole) - return display(); - - QString t = display().toString(); - bool isNumber = false; - int number = t.toInt(&isNumber); - - if (role == Qt::TextColorRole) { - if (!isNumber) - return QVariant::fromValue(QColor(Qt::black)); - else if (number < 0) - return QVariant::fromValue(QColor(Qt::red)); - return QVariant::fromValue(QColor(Qt::blue)); - } - - if (role == Qt::TextAlignmentRole) - if (!t.isEmpty() && (t.at(0).isNumber() || t.at(0) == '-')) - return (int)(Qt::AlignRight | Qt::AlignVCenter); - - return QTableWidgetItem::data(role); - } - -void SpreadSheetItem::setData(int role, const QVariant &value) -{ - QTableWidgetItem::setData(role, value); - if (tableWidget()) - tableWidget()->viewport()->update(); -} - -QVariant SpreadSheetItem::display() const -{ - // avoid circular dependencies - if (isResolving) - return QVariant(); - - isResolving = true; - QVariant result = computeFormula(formula(), tableWidget(), this); - isResolving = false; - return result; -} - -QVariant SpreadSheetItem::computeFormula(const QString &formula, - const QTableWidget *widget, - const QTableWidgetItem *self) -{ - // check if the s tring is actually a formula or not - QStringList list = formula.split(' '); - if (list.isEmpty() || !widget) - return formula; // it is a normal string - - QString op = list.value(0).toLower(); - - int firstRow = -1; - int firstCol = -1; - int secondRow = -1; - int secondCol = -1; - - if (list.count() > 1) - decode_pos(list.value(1), &firstRow, &firstCol); - - if (list.count() > 2) - decode_pos(list.value(2), &secondRow, &secondCol); - - const QTableWidgetItem *start = widget->item(firstRow, firstCol); - const QTableWidgetItem *end = widget->item(secondRow, secondCol); - - int firstVal = start ? start->text().toInt() : 0; - int secondVal = end ? end->text().toInt() : 0; - - QVariant result; - if (op == "sum") { - int sum = 0; - for (int r = firstRow; r <= secondRow; ++r) { - for (int c = firstCol; c <= secondCol; ++c) { - const QTableWidgetItem *tableItem = widget->item(r, c); - if (tableItem && tableItem != self) - sum += tableItem->text().toInt(); - } - } - - result = sum; - } else if (op == "+") { - result = (firstVal + secondVal); - } else if (op == "-") { - result = (firstVal - secondVal); - } else if (op == "*") { - result = (firstVal * secondVal); - } else if (op == "/") { - if (secondVal == 0) - result = QString("nan"); - else - result = (firstVal / secondVal); - } else if (op == "=") { - if (start) - result = start->text(); - } else { - result = formula; - } - - return result; -} - diff --git a/demos/spreadsheet/spreadsheetitem.h b/demos/spreadsheet/spreadsheetitem.h deleted file mode 100644 index b0e7e337ed..0000000000 --- a/demos/spreadsheet/spreadsheetitem.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SPREADSHEETITEM_H -#define SPREADSHEETITEM_H - -#include -#include -#include "spreadsheet.h" - -class SpreadSheetItem : public QTableWidgetItem -{ -public: - SpreadSheetItem(); - SpreadSheetItem(const QString &text); - - QTableWidgetItem *clone() const; - - QVariant data(int role) const; - void setData(int role, const QVariant &value); - QVariant display() const; - - inline QString formula() const - { return QTableWidgetItem::data(Qt::DisplayRole).toString(); } - - static QVariant computeFormula(const QString &formula, - const QTableWidget *widget, - const QTableWidgetItem *self = 0); - -private: - mutable bool isResolving; -}; - -#endif // SPREADSHEETITEM_H - diff --git a/demos/sqlbrowser/browser.cpp b/demos/sqlbrowser/browser.cpp deleted file mode 100644 index 1c53743059..0000000000 --- a/demos/sqlbrowser/browser.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "browser.h" -#include "qsqlconnectiondialog.h" - -#include -#include - -Browser::Browser(QWidget *parent) - : QWidget(parent) -{ - setupUi(this); - - table->addAction(insertRowAction); - table->addAction(deleteRowAction); - - if (QSqlDatabase::drivers().isEmpty()) - QMessageBox::information(this, tr("No database drivers found"), - tr("This demo requires at least one Qt database driver. " - "Please check the documentation how to build the " - "Qt SQL plugins.")); - - emit statusMessage(tr("Ready.")); -} - -Browser::~Browser() -{ -} - -void Browser::exec() -{ - QSqlQueryModel *model = new QSqlQueryModel(table); - model->setQuery(QSqlQuery(sqlEdit->toPlainText(), connectionWidget->currentDatabase())); - table->setModel(model); - - if (model->lastError().type() != QSqlError::NoError) - emit statusMessage(model->lastError().text()); - else if (model->query().isSelect()) - emit statusMessage(tr("Query OK.")); - else - emit statusMessage(tr("Query OK, number of affected rows: %1").arg( - model->query().numRowsAffected())); - - updateActions(); -} - -QSqlError Browser::addConnection(const QString &driver, const QString &dbName, const QString &host, - const QString &user, const QString &passwd, int port) -{ - static int cCount = 0; - - QSqlError err; - QSqlDatabase db = QSqlDatabase::addDatabase(driver, QString("Browser%1").arg(++cCount)); - db.setDatabaseName(dbName); - db.setHostName(host); - db.setPort(port); - if (!db.open(user, passwd)) { - err = db.lastError(); - db = QSqlDatabase(); - QSqlDatabase::removeDatabase(QString("Browser%1").arg(cCount)); - } - connectionWidget->refresh(); - - return err; -} - -void Browser::addConnection() -{ - QSqlConnectionDialog dialog(this); - if (dialog.exec() != QDialog::Accepted) - return; - - if (dialog.useInMemoryDatabase()) { - QSqlDatabase::database("in_mem_db", false).close(); - QSqlDatabase::removeDatabase("in_mem_db"); - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "in_mem_db"); - db.setDatabaseName(":memory:"); - if (!db.open()) - QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while " - "opening the connection: ") + db.lastError().text()); - QSqlQuery q("", db); - q.exec("drop table Movies"); - q.exec("drop table Names"); - q.exec("create table Movies (id integer primary key, Title varchar, Director varchar, Rating number)"); - q.exec("insert into Movies values (0, 'Metropolis', 'Fritz Lang', '8.4')"); - q.exec("insert into Movies values (1, 'Nosferatu, eine Symphonie des Grauens', 'F.W. Murnau', '8.1')"); - q.exec("insert into Movies values (2, 'Bis ans Ende der Welt', 'Wim Wenders', '6.5')"); - q.exec("insert into Movies values (3, 'Hardware', 'Richard Stanley', '5.2')"); - q.exec("insert into Movies values (4, 'Mitchell', 'Andrew V. McLaglen', '2.1')"); - q.exec("create table Names (id integer primary key, Firstname varchar, Lastname varchar, City varchar)"); - q.exec("insert into Names values (0, 'Sala', 'Palmer', 'Morristown')"); - q.exec("insert into Names values (1, 'Christopher', 'Walker', 'Morristown')"); - q.exec("insert into Names values (2, 'Donald', 'Duck', 'Andeby')"); - q.exec("insert into Names values (3, 'Buck', 'Rogers', 'Paris')"); - q.exec("insert into Names values (4, 'Sherlock', 'Holmes', 'London')"); - connectionWidget->refresh(); - } else { - QSqlError err = addConnection(dialog.driverName(), dialog.databaseName(), dialog.hostName(), - dialog.userName(), dialog.password(), dialog.port()); - if (err.type() != QSqlError::NoError) - QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while " - "opening the connection: ") + err.text()); - } -} - -void Browser::showTable(const QString &t) -{ - QSqlTableModel *model = new QSqlTableModel(table, connectionWidget->currentDatabase()); - model->setEditStrategy(QSqlTableModel::OnRowChange); - model->setTable(connectionWidget->currentDatabase().driver()->escapeIdentifier(t, QSqlDriver::TableName)); - model->select(); - if (model->lastError().type() != QSqlError::NoError) - emit statusMessage(model->lastError().text()); - table->setModel(model); - table->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed); - - connect(table->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), - this, SLOT(currentChanged())); - updateActions(); -} - -void Browser::showMetaData(const QString &t) -{ - QSqlRecord rec = connectionWidget->currentDatabase().record(t); - QStandardItemModel *model = new QStandardItemModel(table); - - model->insertRows(0, rec.count()); - model->insertColumns(0, 7); - - model->setHeaderData(0, Qt::Horizontal, "Fieldname"); - model->setHeaderData(1, Qt::Horizontal, "Type"); - model->setHeaderData(2, Qt::Horizontal, "Length"); - model->setHeaderData(3, Qt::Horizontal, "Precision"); - model->setHeaderData(4, Qt::Horizontal, "Required"); - model->setHeaderData(5, Qt::Horizontal, "AutoValue"); - model->setHeaderData(6, Qt::Horizontal, "DefaultValue"); - - - for (int i = 0; i < rec.count(); ++i) { - QSqlField fld = rec.field(i); - model->setData(model->index(i, 0), fld.name()); - model->setData(model->index(i, 1), fld.typeID() == -1 - ? QString(QVariant::typeToName(fld.type())) - : QString("%1 (%2)").arg(QVariant::typeToName(fld.type())).arg(fld.typeID())); - model->setData(model->index(i, 2), fld.length()); - model->setData(model->index(i, 3), fld.precision()); - model->setData(model->index(i, 4), fld.requiredStatus() == -1 ? QVariant("?") - : QVariant(bool(fld.requiredStatus()))); - model->setData(model->index(i, 5), fld.isAutoValue()); - model->setData(model->index(i, 6), fld.defaultValue()); - } - - table->setModel(model); - table->setEditTriggers(QAbstractItemView::NoEditTriggers); - - updateActions(); -} - -void Browser::insertRow() -{ - QSqlTableModel *model = qobject_cast(table->model()); - if (!model) - return; - - QModelIndex insertIndex = table->currentIndex(); - int row = insertIndex.row() == -1 ? 0 : insertIndex.row(); - model->insertRow(row); - insertIndex = model->index(row, 0); - table->setCurrentIndex(insertIndex); - table->edit(insertIndex); -} - -void Browser::deleteRow() -{ - QSqlTableModel *model = qobject_cast(table->model()); - if (!model) - return; - - model->setEditStrategy(QSqlTableModel::OnManualSubmit); - - QModelIndexList currentSelection = table->selectionModel()->selectedIndexes(); - for (int i = 0; i < currentSelection.count(); ++i) { - if (currentSelection.at(i).column() != 0) - continue; - model->removeRow(currentSelection.at(i).row()); - } - - model->submitAll(); - model->setEditStrategy(QSqlTableModel::OnRowChange); - - updateActions(); -} - -void Browser::updateActions() -{ - bool enableIns = qobject_cast(table->model()); - bool enableDel = enableIns && table->currentIndex().isValid(); - - insertRowAction->setEnabled(enableIns); - deleteRowAction->setEnabled(enableDel); -} - -void Browser::about() -{ - QMessageBox::about(this, tr("About"), tr("The SQL Browser demonstration " - "shows how a data browser can be used to visualize the results of SQL" - "statements on a live database")); -} diff --git a/demos/sqlbrowser/browser.h b/demos/sqlbrowser/browser.h deleted file mode 100644 index 11f9e36211..0000000000 --- a/demos/sqlbrowser/browser.h +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef BROWSER_H -#define BROWSER_H - -#include -#include "ui_browserwidget.h" - -class ConnectionWidget; -QT_FORWARD_DECLARE_CLASS(QTableView) -QT_FORWARD_DECLARE_CLASS(QPushButton) -QT_FORWARD_DECLARE_CLASS(QTextEdit) -QT_FORWARD_DECLARE_CLASS(QSqlError) - -class Browser: public QWidget, private Ui::Browser -{ - Q_OBJECT -public: - Browser(QWidget *parent = 0); - virtual ~Browser(); - - QSqlError addConnection(const QString &driver, const QString &dbName, const QString &host, - const QString &user, const QString &passwd, int port = -1); - - void insertRow(); - void deleteRow(); - void updateActions(); - -public slots: - void exec(); - void showTable(const QString &table); - void showMetaData(const QString &table); - void addConnection(); - void currentChanged() { updateActions(); } - void about(); - - void on_insertRowAction_triggered() - { insertRow(); } - void on_deleteRowAction_triggered() - { deleteRow(); } - void on_connectionWidget_tableActivated(const QString &table) - { showTable(table); } - void on_connectionWidget_metaDataRequested(const QString &table) - { showMetaData(table); } - void on_submitButton_clicked() - { - exec(); - sqlEdit->setFocus(); - } - void on_clearButton_clicked() - { - sqlEdit->clear(); - sqlEdit->setFocus(); - } - -signals: - void statusMessage(const QString &message); -}; - -#endif diff --git a/demos/sqlbrowser/browserwidget.ui b/demos/sqlbrowser/browserwidget.ui deleted file mode 100644 index 20946f0ede..0000000000 --- a/demos/sqlbrowser/browserwidget.ui +++ /dev/null @@ -1,199 +0,0 @@ - - - - - Browser - - - - 0 - 0 - 765 - 515 - - - - Qt SQL Browser - - - - 8 - - - 6 - - - - - - 7 - 7 - 0 - 0 - - - - Qt::Horizontal - - - - - 13 - 7 - 1 - 0 - - - - - - - 7 - 7 - 2 - 0 - - - - Qt::ActionsContextMenu - - - QAbstractItemView::SelectRows - - - - - - - - - 5 - 3 - 0 - 0 - - - - - 16777215 - 180 - - - - SQL Query - - - - 9 - - - 6 - - - - - - 7 - 3 - 0 - 0 - - - - - 0 - 18 - - - - - 0 - 120 - - - - - - - - 1 - - - 6 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - &Clear - - - - - - - &Submit - - - - - - - - - - - - false - - - &Insert Row - - - Inserts a new Row - - - - - false - - - &Delete Row - - - Deletes the current Row - - - - - - - ConnectionWidget - QTreeView -
    connectionwidget.h
    - 0 - -
    -
    - - sqlEdit - clearButton - submitButton - connectionWidget - table - - - -
    diff --git a/demos/sqlbrowser/connectionwidget.cpp b/demos/sqlbrowser/connectionwidget.cpp deleted file mode 100644 index 936f32f29f..0000000000 --- a/demos/sqlbrowser/connectionwidget.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "connectionwidget.h" - -#include -#include - -ConnectionWidget::ConnectionWidget(QWidget *parent) - : QWidget(parent) -{ - QVBoxLayout *layout = new QVBoxLayout(this); - tree = new QTreeWidget(this); - tree->setObjectName(QLatin1String("tree")); - tree->setHeaderLabels(QStringList(tr("database"))); - tree->header()->setResizeMode(QHeaderView::Stretch); - QAction *refreshAction = new QAction(tr("Refresh"), tree); - metaDataAction = new QAction(tr("Show Schema"), tree); - connect(refreshAction, SIGNAL(triggered()), SLOT(refresh())); - connect(metaDataAction, SIGNAL(triggered()), SLOT(showMetaData())); - tree->addAction(refreshAction); - tree->addAction(metaDataAction); - tree->setContextMenuPolicy(Qt::ActionsContextMenu); - - layout->addWidget(tree); - - QMetaObject::connectSlotsByName(this); -} - -ConnectionWidget::~ConnectionWidget() -{ -} - -static QString qDBCaption(const QSqlDatabase &db) -{ - QString nm = db.driverName(); - nm.append(QLatin1Char(':')); - if (!db.userName().isEmpty()) - nm.append(db.userName()).append(QLatin1Char('@')); - nm.append(db.databaseName()); - return nm; -} - -void ConnectionWidget::refresh() -{ - tree->clear(); - QStringList connectionNames = QSqlDatabase::connectionNames(); - - bool gotActiveDb = false; - for (int i = 0; i < connectionNames.count(); ++i) { - QTreeWidgetItem *root = new QTreeWidgetItem(tree); - QSqlDatabase db = QSqlDatabase::database(connectionNames.at(i), false); - root->setText(0, qDBCaption(db)); - if (connectionNames.at(i) == activeDb) { - gotActiveDb = true; - setActive(root); - } - if (db.isOpen()) { - QStringList tables = db.tables(); - for (int t = 0; t < tables.count(); ++t) { - QTreeWidgetItem *table = new QTreeWidgetItem(root); - table->setText(0, tables.at(t)); - } - } - } - if (!gotActiveDb) { - activeDb = connectionNames.value(0); - setActive(tree->topLevelItem(0)); - } - - tree->doItemsLayout(); // HACK -} - -QSqlDatabase ConnectionWidget::currentDatabase() const -{ - return QSqlDatabase::database(activeDb); -} - -static void qSetBold(QTreeWidgetItem *item, bool bold) -{ - QFont font = item->font(0); - font.setBold(bold); - item->setFont(0, font); -} - -void ConnectionWidget::setActive(QTreeWidgetItem *item) -{ - for (int i = 0; i < tree->topLevelItemCount(); ++i) { - if (tree->topLevelItem(i)->font(0).bold()) - qSetBold(tree->topLevelItem(i), false); - } - - if (!item) - return; - - qSetBold(item, true); - activeDb = QSqlDatabase::connectionNames().value(tree->indexOfTopLevelItem(item)); -} - -void ConnectionWidget::on_tree_itemActivated(QTreeWidgetItem *item, int /* column */) -{ - - if (!item) - return; - - if (!item->parent()) { - setActive(item); - } else { - setActive(item->parent()); - emit tableActivated(item->text(0)); - } -} - -void ConnectionWidget::showMetaData() -{ - QTreeWidgetItem *cItem = tree->currentItem(); - if (!cItem || !cItem->parent()) - return; - setActive(cItem->parent()); - emit metaDataRequested(cItem->text(0)); -} - -void ConnectionWidget::on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *) -{ - metaDataAction->setEnabled(current && current->parent()); -} - diff --git a/demos/sqlbrowser/connectionwidget.h b/demos/sqlbrowser/connectionwidget.h deleted file mode 100644 index aa04fc25bf..0000000000 --- a/demos/sqlbrowser/connectionwidget.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef CONNECTIONWIDGET_H -#define CONNECTIONWIDGET_H - -#include - -QT_FORWARD_DECLARE_CLASS(QTreeWidget) -QT_FORWARD_DECLARE_CLASS(QTreeWidgetItem) -QT_FORWARD_DECLARE_CLASS(QSqlDatabase) -QT_FORWARD_DECLARE_CLASS(QMenu) - -class ConnectionWidget: public QWidget -{ - Q_OBJECT -public: - ConnectionWidget(QWidget *parent = 0); - virtual ~ConnectionWidget(); - - QSqlDatabase currentDatabase() const; - -signals: - void tableActivated(const QString &table); - void metaDataRequested(const QString &tableName); - -public slots: - void refresh(); - void showMetaData(); - void on_tree_itemActivated(QTreeWidgetItem *item, int column); - void on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); - -private: - void setActive(QTreeWidgetItem *); - - QTreeWidget *tree; - QAction *metaDataAction; - QString activeDb; -}; - -#endif diff --git a/demos/sqlbrowser/main.cpp b/demos/sqlbrowser/main.cpp deleted file mode 100644 index dc006176b7..0000000000 --- a/demos/sqlbrowser/main.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "browser.h" - -#include -#include -#include - -void addConnectionsFromCommandline(const QStringList &args, Browser *browser) -{ - for (int i = 1; i < args.count(); ++i) { - QUrl url(args.at(i), QUrl::TolerantMode); - if (!url.isValid()) { - qWarning("Invalid URL: %s", qPrintable(args.at(i))); - continue; - } - QSqlError err = browser->addConnection(url.scheme(), url.path().mid(1), url.host(), - url.userName(), url.password(), url.port(-1)); - if (err.type() != QSqlError::NoError) - qDebug() << "Unable to open connection:" << err; - } -} - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - QMainWindow mainWin; - mainWin.setWindowTitle(QObject::tr("Qt SQL Browser")); - - Browser browser(&mainWin); - mainWin.setCentralWidget(&browser); - - QMenu *fileMenu = mainWin.menuBar()->addMenu(QObject::tr("&File")); - fileMenu->addAction(QObject::tr("Add &Connection..."), &browser, SLOT(addConnection())); - fileMenu->addSeparator(); - fileMenu->addAction(QObject::tr("&Quit"), &app, SLOT(quit())); - - QMenu *helpMenu = mainWin.menuBar()->addMenu(QObject::tr("&Help")); - helpMenu->addAction(QObject::tr("About"), &browser, SLOT(about())); - helpMenu->addAction(QObject::tr("About Qt"), qApp, SLOT(aboutQt())); - - QObject::connect(&browser, SIGNAL(statusMessage(QString)), - mainWin.statusBar(), SLOT(showMessage(QString))); - - addConnectionsFromCommandline(app.arguments(), &browser); - mainWin.show(); - if (QSqlDatabase::connectionNames().isEmpty()) - QMetaObject::invokeMethod(&browser, "addConnection", Qt::QueuedConnection); - - return app.exec(); -} diff --git a/demos/sqlbrowser/qsqlconnectiondialog.cpp b/demos/sqlbrowser/qsqlconnectiondialog.cpp deleted file mode 100644 index 56b6c031db..0000000000 --- a/demos/sqlbrowser/qsqlconnectiondialog.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qsqlconnectiondialog.h" -#include "ui_qsqlconnectiondialog.h" - -#include - -QSqlConnectionDialog::QSqlConnectionDialog(QWidget *parent) - : QDialog(parent) -{ - ui.setupUi(this); - - QStringList drivers = QSqlDatabase::drivers(); - - // remove compat names - drivers.removeAll("QMYSQL3"); - drivers.removeAll("QOCI8"); - drivers.removeAll("QODBC3"); - drivers.removeAll("QPSQL7"); - drivers.removeAll("QTDS7"); - - if (!drivers.contains("QSQLITE")) - ui.dbCheckBox->setEnabled(false); - - ui.comboDriver->addItems(drivers); -} - -QSqlConnectionDialog::~QSqlConnectionDialog() -{ -} - -QString QSqlConnectionDialog::driverName() const -{ - return ui.comboDriver->currentText(); -} - -QString QSqlConnectionDialog::databaseName() const -{ - return ui.editDatabase->text(); -} - -QString QSqlConnectionDialog::userName() const -{ - return ui.editUsername->text(); -} - -QString QSqlConnectionDialog::password() const -{ - return ui.editPassword->text(); -} - -QString QSqlConnectionDialog::hostName() const -{ - return ui.editHostname->text(); -} - -int QSqlConnectionDialog::port() const -{ - return ui.portSpinBox->value(); -} - -bool QSqlConnectionDialog::useInMemoryDatabase() const -{ - return ui.dbCheckBox->isChecked(); -} - -void QSqlConnectionDialog::on_okButton_clicked() -{ - if (ui.comboDriver->currentText().isEmpty()) { - QMessageBox::information(this, tr("No database driver selected"), - tr("Please select a database driver")); - ui.comboDriver->setFocus(); - } else { - accept(); - } -} diff --git a/demos/sqlbrowser/qsqlconnectiondialog.h b/demos/sqlbrowser/qsqlconnectiondialog.h deleted file mode 100644 index 8c4519a195..0000000000 --- a/demos/sqlbrowser/qsqlconnectiondialog.h +++ /dev/null @@ -1,74 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSQLCONNECTIONDIALOG_H -#define QSQLCONNECTIONDIALOG_H - -#include -#include - -#include "ui_qsqlconnectiondialog.h" - -class QSqlConnectionDialog: public QDialog -{ - Q_OBJECT -public: - QSqlConnectionDialog(QWidget *parent = 0); - ~QSqlConnectionDialog(); - - QString driverName() const; - QString databaseName() const; - QString userName() const; - QString password() const; - QString hostName() const; - int port() const; - bool useInMemoryDatabase() const; - -private slots: - void on_okButton_clicked(); - void on_cancelButton_clicked() { reject(); } - void on_dbCheckBox_clicked() { ui.connGroupBox->setEnabled(!ui.dbCheckBox->isChecked()); } - -private: - Ui::QSqlConnectionDialogUi ui; -}; - -#endif diff --git a/demos/sqlbrowser/qsqlconnectiondialog.ui b/demos/sqlbrowser/qsqlconnectiondialog.ui deleted file mode 100644 index 91a8700579..0000000000 --- a/demos/sqlbrowser/qsqlconnectiondialog.ui +++ /dev/null @@ -1,224 +0,0 @@ - - - - - QSqlConnectionDialogUi - - - - 0 - 0 - 315 - 302 - - - - Connect... - - - - 8 - - - 6 - - - - - Connection settings - - - - 8 - - - 6 - - - - - - - - &Username: - - - editUsername - - - - - - - D&river - - - comboDriver - - - - - - - - - - Default - - - 65535 - - - -1 - - - -1 - - - - - - - Database Name: - - - editDatabase - - - - - - - QLineEdit::Password - - - - - - - - - - - - - &Hostname: - - - editHostname - - - - - - - P&ort: - - - portSpinBox - - - - - - - &Password: - - - editPassword - - - - - - - - - - 0 - - - 6 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Us&e predefined in-memory database - - - - - - - - - 0 - - - 6 - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 20 - 20 - - - - - - - - &OK - - - true - - - - - - - &Cancel - - - - - - - - - - comboDriver - editDatabase - editUsername - editPassword - editHostname - portSpinBox - dbCheckBox - okButton - cancelButton - - - - diff --git a/demos/sqlbrowser/sqlbrowser.pro b/demos/sqlbrowser/sqlbrowser.pro deleted file mode 100644 index dc6214622c..0000000000 --- a/demos/sqlbrowser/sqlbrowser.pro +++ /dev/null @@ -1,25 +0,0 @@ -TEMPLATE = app -TARGET = sqlbrowser - -QT += sql - -HEADERS = browser.h connectionwidget.h qsqlconnectiondialog.h -SOURCES = main.cpp browser.cpp connectionwidget.cpp qsqlconnectiondialog.cpp - -FORMS = browserwidget.ui qsqlconnectiondialog.ui -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/sqlbrowser -sources.files = $$SOURCES $$HEADERS $$FORMS *.pro -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/sqlbrowser -INSTALLS += target sources - -symbian: CONFIG += qt_demo - -wince*: { - DEPLOYMENT_PLUGIN += qsqlite -} diff --git a/demos/sub-attaq/animationmanager.cpp b/demos/sub-attaq/animationmanager.cpp deleted file mode 100644 index c7e230e3d2..0000000000 --- a/demos/sub-attaq/animationmanager.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "animationmanager.h" - -//Qt -#include -#include - -// the universe's only animation manager -AnimationManager *AnimationManager::instance = 0; - -AnimationManager::AnimationManager() -{ -} - -AnimationManager *AnimationManager::self() -{ - if (!instance) - instance = new AnimationManager; - return instance; -} - -void AnimationManager::registerAnimation(QAbstractAnimation *anim) -{ - QObject::connect(anim, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterAnimation_helper(QObject*))); - animations.append(anim); -} - -void AnimationManager::unregisterAnimation_helper(QObject *obj) -{ - unregisterAnimation(static_cast(obj)); -} - -void AnimationManager::unregisterAnimation(QAbstractAnimation *anim) -{ - QObject::disconnect(anim, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterAnimation_helper(QObject*))); - animations.removeAll(anim); -} - -void AnimationManager::unregisterAllAnimations() -{ - animations.clear(); -} - -void AnimationManager::pauseAll() -{ - foreach (QAbstractAnimation* animation, animations) { - if (animation->state() == QAbstractAnimation::Running) - animation->pause(); - } -} -void AnimationManager::resumeAll() -{ - foreach (QAbstractAnimation* animation, animations) { - if (animation->state() == QAbstractAnimation::Paused) - animation->resume(); - } -} diff --git a/demos/sub-attaq/animationmanager.h b/demos/sub-attaq/animationmanager.h deleted file mode 100644 index 429d656485..0000000000 --- a/demos/sub-attaq/animationmanager.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ANIMATIONMANAGER_H -#define ANIMATIONMANAGER_H - -#include - -QT_BEGIN_NAMESPACE -class QAbstractAnimation; -QT_END_NAMESPACE - -class AnimationManager : public QObject -{ -Q_OBJECT -public: - AnimationManager(); - void registerAnimation(QAbstractAnimation *anim); - void unregisterAnimation(QAbstractAnimation *anim); - void unregisterAllAnimations(); - static AnimationManager *self(); - -public slots: - void pauseAll(); - void resumeAll(); - -private slots: - void unregisterAnimation_helper(QObject *obj); - -private: - static AnimationManager *instance; - QList animations; -}; - -#endif // ANIMATIONMANAGER_H diff --git a/demos/sub-attaq/boat.cpp b/demos/sub-attaq/boat.cpp deleted file mode 100644 index 4ddf59e6a0..0000000000 --- a/demos/sub-attaq/boat.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "boat.h" -#include "boat_p.h" -#include "bomb.h" -#include "pixmapitem.h" -#include "graphicsscene.h" -#include "animationmanager.h" -#include "qanimationstate.h" - -//Qt -#include -#include -#include -#include -#include -#include - -static QAbstractAnimation *setupDestroyAnimation(Boat *boat) -{ - QSequentialAnimationGroup *group = new QSequentialAnimationGroup(boat); - for (int i = 1; i <= 4; i++) { - PixmapItem *step = new PixmapItem(QString("explosion/boat/step%1").arg(i),GraphicsScene::Big, boat); - step->setZValue(6); - step->setOpacity(0); - - //fade-in - QPropertyAnimation *anim = new QPropertyAnimation(step, "opacity"); - anim->setEndValue(1); - anim->setDuration(100); - group->insertAnimation(i-1, anim); - - //and then fade-out - QPropertyAnimation *anim2 = new QPropertyAnimation(step, "opacity"); - anim2->setEndValue(0); - anim2->setDuration(100); - group->addAnimation(anim2); - } - - AnimationManager::self()->registerAnimation(group); - return group; -} - - - -Boat::Boat() : PixmapItem(QString("boat"), GraphicsScene::Big), - speed(0), bombsAlreadyLaunched(0), direction(Boat::None), movementAnimation(0) -{ - setZValue(4); - setFlags(QGraphicsItem::ItemIsFocusable); - - //The movement animation used to animate the boat - movementAnimation = new QPropertyAnimation(this, "pos"); - - //The destroy animation used to explode the boat - destroyAnimation = setupDestroyAnimation(this); - - //We setup the state machine of the boat - machine = new QStateMachine(this); - QState *moving = new QState(machine); - StopState *stopState = new StopState(this, moving); - machine->setInitialState(moving); - moving->setInitialState(stopState); - MoveStateRight *moveStateRight = new MoveStateRight(this, moving); - MoveStateLeft *moveStateLeft = new MoveStateLeft(this, moving); - LaunchStateRight *launchStateRight = new LaunchStateRight(this, machine); - LaunchStateLeft *launchStateLeft = new LaunchStateLeft(this, machine); - - //then setup the transitions for the rightMove state - KeyStopTransition *leftStopRight = new KeyStopTransition(this, QEvent::KeyPress, Qt::Key_Left); - leftStopRight->setTargetState(stopState); - KeyMoveTransition *leftMoveRight = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Left); - leftMoveRight->setTargetState(moveStateRight); - KeyMoveTransition *rightMoveRight = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); - rightMoveRight->setTargetState(moveStateRight); - KeyMoveTransition *rightMoveStop = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); - rightMoveStop->setTargetState(moveStateRight); - - //then setup the transitions for the leftMove state - KeyStopTransition *rightStopLeft = new KeyStopTransition(this, QEvent::KeyPress, Qt::Key_Right); - rightStopLeft->setTargetState(stopState); - KeyMoveTransition *rightMoveLeft = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); - rightMoveLeft->setTargetState(moveStateLeft); - KeyMoveTransition *leftMoveLeft = new KeyMoveTransition(this, QEvent::KeyPress,Qt::Key_Left); - leftMoveLeft->setTargetState(moveStateLeft); - KeyMoveTransition *leftMoveStop = new KeyMoveTransition(this, QEvent::KeyPress,Qt::Key_Left); - leftMoveStop->setTargetState(moveStateLeft); - - //We set up the right move state - moveStateRight->addTransition(leftStopRight); - moveStateRight->addTransition(leftMoveRight); - moveStateRight->addTransition(rightMoveRight); - stopState->addTransition(rightMoveStop); - - //We set up the left move state - moveStateLeft->addTransition(rightStopLeft); - moveStateLeft->addTransition(leftMoveLeft); - moveStateLeft->addTransition(rightMoveLeft); - stopState->addTransition(leftMoveStop); - - //The animation is finished, it means we reached the border of the screen, the boat is stopped so we move to the stop state - moveStateLeft->addTransition(movementAnimation, SIGNAL(finished()), stopState); - moveStateRight->addTransition(movementAnimation, SIGNAL(finished()), stopState); - - //We set up the keys for dropping bombs - KeyLaunchTransition *upFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); - upFireLeft->setTargetState(launchStateRight); - KeyLaunchTransition *upFireRight = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); - upFireRight->setTargetState(launchStateRight); - KeyLaunchTransition *upFireStop = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); - upFireStop->setTargetState(launchStateRight); - KeyLaunchTransition *downFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); - downFireLeft->setTargetState(launchStateLeft); - KeyLaunchTransition *downFireRight = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); - downFireRight->setTargetState(launchStateLeft); - KeyLaunchTransition *downFireMove = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); - downFireMove->setTargetState(launchStateLeft); - - //We set up transitions for fire up - moveStateRight->addTransition(upFireRight); - moveStateLeft->addTransition(upFireLeft); - stopState->addTransition(upFireStop); - - //We set up transitions for fire down - moveStateRight->addTransition(downFireRight); - moveStateLeft->addTransition(downFireLeft); - stopState->addTransition(downFireMove); - - //Finally the launch state should come back to its original state - QHistoryState *historyState = new QHistoryState(moving); - launchStateLeft->addTransition(historyState); - launchStateRight->addTransition(historyState); - - QFinalState *final = new QFinalState(machine); - - //This state play the destroyed animation - QAnimationState *destroyedState = new QAnimationState(machine); - destroyedState->setAnimation(destroyAnimation); - - //Play a nice animation when the boat is destroyed - moving->addTransition(this, SIGNAL(boatDestroyed()), destroyedState); - - //Transition to final state when the destroyed animation is finished - destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); - - //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()), this, SIGNAL(boatExecutionFinished())); - -} - -void Boat::run() -{ - //We register animations - AnimationManager::self()->registerAnimation(movementAnimation); - AnimationManager::self()->registerAnimation(destroyAnimation); - machine->start(); -} - -void Boat::stop() -{ - movementAnimation->stop(); - machine->stop(); -} - -void Boat::updateBoatMovement() -{ - if (speed == 0 || direction == Boat::None) { - movementAnimation->stop(); - return; - } - - movementAnimation->stop(); - - if (direction == Boat::Left) { - movementAnimation->setEndValue(QPointF(0,y())); - movementAnimation->setDuration(x()/speed*15); - } - else /*if (direction == Boat::Right)*/ { - movementAnimation->setEndValue(QPointF(scene()->width()-size().width(),y())); - movementAnimation->setDuration((scene()->width()-size().width()-x())/speed*15); - } - movementAnimation->start(); -} - -void Boat::destroy() -{ - movementAnimation->stop(); - emit boatDestroyed(); -} - -int Boat::bombsLaunched() const -{ - return bombsAlreadyLaunched; -} - -void Boat::setBombsLaunched(int number) -{ - if (number > MAX_BOMB) { - qWarning("Boat::setBombsLaunched : It impossible to launch that number of bombs"); - return; - } - bombsAlreadyLaunched = number; -} - -int Boat::currentSpeed() const -{ - return speed; -} - -void Boat::setCurrentSpeed(int speed) -{ - if (speed > 3 || speed < 0) { - qWarning("Boat::setCurrentSpeed: The boat can't run on that speed"); - return; - } - this->speed = speed; -} - -enum Boat::Movement Boat::currentDirection() const -{ - return direction; -} - -void Boat::setCurrentDirection(Movement direction) -{ - this->direction = direction; -} - -int Boat::type() const -{ - return Type; -} diff --git a/demos/sub-attaq/boat.h b/demos/sub-attaq/boat.h deleted file mode 100644 index 71e3512fc3..0000000000 --- a/demos/sub-attaq/boat.h +++ /dev/null @@ -1,95 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __BOAT__H__ -#define __BOAT__H__ - -#include "pixmapitem.h" - -class Bomb; -QT_BEGIN_NAMESPACE -class QVariantAnimation; -class QAbstractAnimation; -class QStateMachine; -QT_END_NAMESPACE - -class Boat : public PixmapItem -{ -Q_OBJECT -public: - enum Movement { - None = 0, - Left, - Right - }; - enum { Type = UserType + 2 }; - Boat(); - void destroy(); - void run(); - void stop(); - - int bombsLaunched() const; - void setBombsLaunched(int number); - - int currentSpeed() const; - void setCurrentSpeed(int speed); - - enum Movement currentDirection() const; - void setCurrentDirection(Movement direction); - - void updateBoatMovement(); - - virtual int type() const; - -signals: - void boatDestroyed(); - void boatExecutionFinished(); - -private: - int speed; - int bombsAlreadyLaunched; - Movement direction; - QVariantAnimation *movementAnimation; - QAbstractAnimation *destroyAnimation; - QStateMachine *machine; -}; - -#endif //__BOAT__H__ diff --git a/demos/sub-attaq/boat_p.h b/demos/sub-attaq/boat_p.h deleted file mode 100644 index 9022a4ca51..0000000000 --- a/demos/sub-attaq/boat_p.h +++ /dev/null @@ -1,232 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef BOAT_P_H -#define BOAT_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -//Own -#include "bomb.h" -#include "graphicsscene.h" - -// Qt -#include - -static const int MAX_BOMB = 5; - - -//These transtion test if we have to stop the boat (i.e current speed is 1) -class KeyStopTransition : public QKeyEventTransition -{ -public: - KeyStopTransition(Boat *b, QEvent::Type t, int k) - : QKeyEventTransition(b, t, k), boat(b), key(k) - { - } -protected: - virtual bool eventTest(QEvent *event) - { - if (!QKeyEventTransition::eventTest(event)) - return false; - return (boat->currentSpeed() == 1); - } -private: - Boat * boat; - int key; -}; - -//These transtion test if we have to move the boat (i.e current speed was 0 or another value) - class KeyMoveTransition : public QKeyEventTransition -{ -public: - KeyMoveTransition(Boat *b, QEvent::Type t, int k) - : QKeyEventTransition(b, t, k), boat(b), key(k) - { - } -protected: - virtual bool eventTest(QEvent *event) - { - if (!QKeyEventTransition::eventTest(event)) - return false; - return (boat->currentSpeed() >= 0); - } - void onTransition(QEvent *) - { - //We decrease the speed if needed - if (key == Qt::Key_Left && boat->currentDirection() == Boat::Right) - boat->setCurrentSpeed(boat->currentSpeed() - 1); - else if (key == Qt::Key_Right && boat->currentDirection() == Boat::Left) - boat->setCurrentSpeed(boat->currentSpeed() - 1); - else if (boat->currentSpeed() < 3) - boat->setCurrentSpeed(boat->currentSpeed() + 1); - boat->updateBoatMovement(); - } -private: - Boat * boat; - int key; -}; - -//This transition trigger the bombs launch - class KeyLaunchTransition : public QKeyEventTransition -{ -public: - KeyLaunchTransition(Boat *boat, QEvent::Type type, int key) - : QKeyEventTransition(boat, type, key), boat(boat), key(key) - { - } -protected: - virtual bool eventTest(QEvent *event) - { - if (!QKeyEventTransition::eventTest(event)) - return false; - //We have enough bomb? - return (boat->bombsLaunched() < MAX_BOMB); - } -private: - Boat * boat; - int key; -}; - -//This state is describing when the boat is moving right -class MoveStateRight : public QState -{ -public: - MoveStateRight(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) - { - } -protected: - void onEntry(QEvent *) - { - boat->setCurrentDirection(Boat::Right); - boat->updateBoatMovement(); - } -private: - Boat * boat; -}; - - //This state is describing when the boat is moving left -class MoveStateLeft : public QState -{ -public: - MoveStateLeft(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) - { - } -protected: - void onEntry(QEvent *) - { - boat->setCurrentDirection(Boat::Left); - boat->updateBoatMovement(); - } -private: - Boat * boat; -}; - -//This state is describing when the boat is in a stand by position -class StopState : public QState -{ -public: - StopState(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) - { - } -protected: - void onEntry(QEvent *) - { - boat->setCurrentSpeed(0); - boat->setCurrentDirection(Boat::None); - boat->updateBoatMovement(); - } -private: - Boat * boat; -}; - -//This state is describing the launch of the torpedo on the right -class LaunchStateRight : public QState -{ -public: - LaunchStateRight(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) - { - } -protected: - void onEntry(QEvent *) - { - Bomb *b = new Bomb(); - b->setPos(boat->x()+boat->size().width(),boat->y()); - GraphicsScene *scene = static_cast(boat->scene()); - scene->addItem(b); - b->launch(Bomb::Right); - boat->setBombsLaunched(boat->bombsLaunched() + 1); - } -private: - Boat * boat; -}; - -//This state is describing the launch of the torpedo on the left -class LaunchStateLeft : public QState -{ -public: - LaunchStateLeft(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) - { - } -protected: - void onEntry(QEvent *) - { - Bomb *b = new Bomb(); - b->setPos(boat->x() - b->size().width(), boat->y()); - GraphicsScene *scene = static_cast(boat->scene()); - scene->addItem(b); - b->launch(Bomb::Left); - boat->setBombsLaunched(boat->bombsLaunched() + 1); - } -private: - Boat * boat; -}; - -#endif // BOAT_P_H diff --git a/demos/sub-attaq/bomb.cpp b/demos/sub-attaq/bomb.cpp deleted file mode 100644 index 6811a27e88..0000000000 --- a/demos/sub-attaq/bomb.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "bomb.h" -#include "submarine.h" -#include "pixmapitem.h" -#include "animationmanager.h" -#include "qanimationstate.h" - -//Qt -#include -#include -#include -#include - -Bomb::Bomb() : PixmapItem(QString("bomb"), GraphicsScene::Big) -{ - setZValue(2); -} - -void Bomb::launch(Bomb::Direction direction) -{ - QSequentialAnimationGroup *launchAnimation = new QSequentialAnimationGroup; - AnimationManager::self()->registerAnimation(launchAnimation); - qreal delta = direction == Right ? 20 : - 20; - QPropertyAnimation *anim = new QPropertyAnimation(this, "pos"); - anim->setEndValue(QPointF(x() + delta,y() - 20)); - anim->setDuration(150); - launchAnimation->addAnimation(anim); - anim = new QPropertyAnimation(this, "pos"); - anim->setEndValue(QPointF(x() + delta*2, y() )); - anim->setDuration(150); - launchAnimation->addAnimation(anim); - anim = new QPropertyAnimation(this, "pos"); - anim->setEndValue(QPointF(x() + delta*2,scene()->height())); - anim->setDuration(y()/2*60); - launchAnimation->addAnimation(anim); - connect(anim,SIGNAL(valueChanged(QVariant)),this,SLOT(onAnimationLaunchValueChanged(QVariant))); - connect(this, SIGNAL(bombExploded()), launchAnimation, SLOT(stop())); - //We setup the state machine of the bomb - QStateMachine *machine = new QStateMachine(this); - - //This state is when the launch animation is playing - QAnimationState *launched = new QAnimationState(machine); - launched->setAnimation(launchAnimation); - - //End - QFinalState *final = new QFinalState(machine); - - machine->setInitialState(launched); - - //### Add a nice animation when the bomb is destroyed - launched->addTransition(this, SIGNAL(bombExploded()),final); - - //If the animation is finished, then we move to the final state - launched->addTransition(launched, SIGNAL(animationFinished()), final); - - //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(bombExecutionFinished())); - - machine->start(); - -} - -void Bomb::onAnimationLaunchValueChanged(const QVariant &) -{ - foreach (QGraphicsItem * item , collidingItems(Qt::IntersectsItemBoundingRect)) { - if (item->type() == SubMarine::Type) { - SubMarine *s = static_cast(item); - destroy(); - s->destroy(); - } - } -} - -void Bomb::destroy() -{ - emit bombExploded(); -} diff --git a/demos/sub-attaq/bomb.h b/demos/sub-attaq/bomb.h deleted file mode 100644 index 222c3d029f..0000000000 --- a/demos/sub-attaq/bomb.h +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __BOMB__H__ -#define __BOMB__H__ - -#include "pixmapitem.h" - -class Bomb : public PixmapItem -{ -Q_OBJECT -public: - enum Direction { - Left = 0, - Right - }; - Bomb(); - void launch(Direction direction); - void destroy(); - -signals: - void bombExploded(); - void bombExecutionFinished(); - -private slots: - void onAnimationLaunchValueChanged(const QVariant &); -}; - -#endif //__BOMB__H__ diff --git a/demos/sub-attaq/data.xml b/demos/sub-attaq/data.xml deleted file mode 100644 index 0f30515ddf..0000000000 --- a/demos/sub-attaq/data.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/graphicsscene.cpp b/demos/sub-attaq/graphicsscene.cpp deleted file mode 100644 index f82d441068..0000000000 --- a/demos/sub-attaq/graphicsscene.cpp +++ /dev/null @@ -1,282 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "graphicsscene.h" -#include "states.h" -#include "boat.h" -#include "submarine.h" -#include "torpedo.h" -#include "bomb.h" -#include "pixmapitem.h" -#include "animationmanager.h" -#include "qanimationstate.h" -#include "progressitem.h" -#include "textinformationitem.h" - -//Qt -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -GraphicsScene::GraphicsScene(int x, int y, int width, int height, Mode mode) - : QGraphicsScene(x , y, width, height), mode(mode), boat(new Boat) -{ - PixmapItem *backgroundItem = new PixmapItem(QString("background"),mode); - backgroundItem->setZValue(1); - backgroundItem->setPos(0,0); - addItem(backgroundItem); - - PixmapItem *surfaceItem = new PixmapItem(QString("surface"),mode); - surfaceItem->setZValue(3); - surfaceItem->setPos(0,sealLevel() - surfaceItem->boundingRect().height()/2); - addItem(surfaceItem); - - //The item that display score and level - progressItem = new ProgressItem(backgroundItem); - - textInformationItem = new TextInformationItem(backgroundItem); - textInformationItem->hide(); - //We create the boat - addItem(boat); - boat->setPos(this->width()/2, sealLevel() - boat->size().height()); - boat->hide(); - - //parse the xml that contain all data of the game - QXmlStreamReader reader; - QFile file(":data.xml"); - file.open(QIODevice::ReadOnly); - reader.setDevice(&file); - LevelDescription currentLevel; - while (!reader.atEnd()) { - reader.readNext(); - if (reader.tokenType() == QXmlStreamReader::StartElement) { - if (reader.name() == "submarine") { - SubmarineDescription desc; - desc.name = reader.attributes().value("name").toString(); - desc.points = reader.attributes().value("points").toString().toInt(); - desc.type = reader.attributes().value("type").toString().toInt(); - submarinesData.append(desc); - } else if (reader.name() == "level") { - currentLevel.id = reader.attributes().value("id").toString().toInt(); - currentLevel.name = reader.attributes().value("name").toString(); - } else if (reader.name() == "subinstance") { - currentLevel.submarines.append(qMakePair(reader.attributes().value("type").toString().toInt(), reader.attributes().value("nb").toString().toInt())); - } - } else if (reader.tokenType() == QXmlStreamReader::EndElement) { - if (reader.name() == "level") { - levelsData.insert(currentLevel.id, currentLevel); - currentLevel.submarines.clear(); - } - } - } -} - -qreal GraphicsScene::sealLevel() const -{ - return (mode == Big) ? 220 : 160; -} - -void GraphicsScene::setupScene(QAction *newAction, QAction *quitAction) -{ - static const int nLetters = 10; - static struct { - char const *pix; - qreal initX, initY; - qreal destX, destY; - } logoData[nLetters] = { - {"s", -1000, -1000, 300, 150 }, - {"u", -800, -1000, 350, 150 }, - {"b", -600, -1000, 400, 120 }, - {"dash", -400, -1000, 460, 150 }, - {"a", 1000, 2000, 350, 250 }, - {"t", 800, 2000, 400, 250 }, - {"t2", 600, 2000, 430, 250 }, - {"a2", 400, 2000, 465, 250 }, - {"q", 200, 2000, 510, 250 }, - {"excl", 0, 2000, 570, 220 } }; - - QSequentialAnimationGroup * lettersGroupMoving = new QSequentialAnimationGroup(this); - QParallelAnimationGroup * lettersGroupFading = new QParallelAnimationGroup(this); - - for (int i = 0; i < nLetters; ++i) { - PixmapItem *logo = new PixmapItem(QLatin1String(":/logo-") + logoData[i].pix, this); - logo->setPos(logoData[i].initX, logoData[i].initY); - logo->setZValue(i + 3); - //creation of the animations for moving letters - QPropertyAnimation *moveAnim = new QPropertyAnimation(logo, "pos", lettersGroupMoving); - moveAnim->setEndValue(QPointF(logoData[i].destX, logoData[i].destY)); - moveAnim->setDuration(200); - moveAnim->setEasingCurve(QEasingCurve::OutElastic); - lettersGroupMoving->addPause(50); - //creation of the animations for fading out the letters - QPropertyAnimation *fadeAnim = new QPropertyAnimation(logo, "opacity", lettersGroupFading); - fadeAnim->setDuration(800); - fadeAnim->setEndValue(0); - fadeAnim->setEasingCurve(QEasingCurve::OutQuad); - } - - QStateMachine *machine = new QStateMachine(this); - - //This state is when the player is playing - PlayState *gameState = new PlayState(this, machine); - - //Final state - QFinalState *final = new QFinalState(machine); - - //Animation when the player enter in the game - QAnimationState *lettersMovingState = new QAnimationState(machine); - lettersMovingState->setAnimation(lettersGroupMoving); - - //Animation when the welcome screen disappear - QAnimationState *lettersFadingState = new QAnimationState(machine); - lettersFadingState->setAnimation(lettersGroupFading); - - //if new game then we fade out the welcome screen and start playing - lettersMovingState->addTransition(newAction, SIGNAL(triggered()), lettersFadingState); - lettersFadingState->addTransition(lettersFadingState, SIGNAL(animationFinished()), gameState); - - //New Game is triggered then player start playing - gameState->addTransition(newAction, SIGNAL(triggered()), gameState); - - //Wanna quit, then connect to CTRL+Q - gameState->addTransition(quitAction, SIGNAL(triggered()), final); - lettersMovingState->addTransition(quitAction, SIGNAL(triggered()), final); - - //Welcome screen is the initial state - machine->setInitialState(lettersMovingState); - - machine->start(); - - //We reach the final state, then we quit - connect(machine, SIGNAL(finished()), qApp, SLOT(quit())); -} - -void GraphicsScene::addItem(Bomb *bomb) -{ - bombs.insert(bomb); - connect(bomb,SIGNAL(bombExecutionFinished()),this, SLOT(onBombExecutionFinished())); - QGraphicsScene::addItem(bomb); -} - -void GraphicsScene::addItem(Torpedo *torpedo) -{ - torpedos.insert(torpedo); - connect(torpedo,SIGNAL(torpedoExecutionFinished()),this, SLOT(onTorpedoExecutionFinished())); - QGraphicsScene::addItem(torpedo); -} - -void GraphicsScene::addItem(SubMarine *submarine) -{ - submarines.insert(submarine); - connect(submarine,SIGNAL(subMarineExecutionFinished()),this, SLOT(onSubMarineExecutionFinished())); - QGraphicsScene::addItem(submarine); -} - -void GraphicsScene::addItem(QGraphicsItem *item) -{ - QGraphicsScene::addItem(item); -} - -void GraphicsScene::onBombExecutionFinished() -{ - Bomb *bomb = qobject_cast(sender()); - bombs.remove(bomb); - bomb->deleteLater(); - if (boat) - boat->setBombsLaunched(boat->bombsLaunched() - 1); -} - -void GraphicsScene::onTorpedoExecutionFinished() -{ - Torpedo *torpedo = qobject_cast(sender()); - torpedos.remove(torpedo); - torpedo->deleteLater(); -} - -void GraphicsScene::onSubMarineExecutionFinished() -{ - SubMarine *submarine = qobject_cast(sender()); - submarines.remove(submarine); - if (submarines.count() == 0) - emit allSubMarineDestroyed(submarine->points()); - else - emit subMarineDestroyed(submarine->points()); - submarine->deleteLater(); -} - -void GraphicsScene::clearScene() -{ - foreach (SubMarine *sub, submarines) { - sub->destroy(); - sub->deleteLater(); - } - - foreach (Torpedo *torpedo, torpedos) { - torpedo->destroy(); - torpedo->deleteLater(); - } - - foreach (Bomb *bomb, bombs) { - bomb->destroy(); - bomb->deleteLater(); - } - - submarines.clear(); - bombs.clear(); - torpedos.clear(); - - AnimationManager::self()->unregisterAllAnimations(); - - boat->stop(); - boat->hide(); - boat->setEnabled(true); -} diff --git a/demos/sub-attaq/graphicsscene.h b/demos/sub-attaq/graphicsscene.h deleted file mode 100644 index e1220a5eb8..0000000000 --- a/demos/sub-attaq/graphicsscene.h +++ /dev/null @@ -1,122 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __GRAPHICSSCENE__H__ -#define __GRAPHICSSCENE__H__ - -//Qt -#include -#include -#include - - -class Boat; -class SubMarine; -class Torpedo; -class Bomb; -class PixmapItem; -class ProgressItem; -class TextInformationItem; -QT_BEGIN_NAMESPACE -class QAction; -QT_END_NAMESPACE - -class GraphicsScene : public QGraphicsScene -{ -Q_OBJECT -public: - enum Mode { - Big = 0, - Small - }; - - struct SubmarineDescription { - int type; - int points; - QString name; - }; - - struct LevelDescription { - int id; - QString name; - QList > submarines; - }; - - GraphicsScene(int x, int y, int width, int height, Mode mode = Big); - qreal sealLevel() const; - void setupScene(QAction *newAction, QAction *quitAction); - void addItem(Bomb *bomb); - void addItem(Torpedo *torpedo); - void addItem(SubMarine *submarine); - void addItem(QGraphicsItem *item); - void clearScene(); - -signals: - void subMarineDestroyed(int); - void allSubMarineDestroyed(int); - -private slots: - void onBombExecutionFinished(); - void onTorpedoExecutionFinished(); - void onSubMarineExecutionFinished(); - -private: - Mode mode; - ProgressItem *progressItem; - TextInformationItem *textInformationItem; - Boat *boat; - QSet submarines; - QSet bombs; - QSet torpedos; - QVector submarinesData; - QHash levelsData; - - friend class PauseState; - friend class PlayState; - friend class LevelState; - friend class LostState; - friend class WinState; - friend class WinTransition; - friend class UpdateScoreTransition; -}; - -#endif //__GRAPHICSSCENE__H__ - diff --git a/demos/sub-attaq/main.cpp b/demos/sub-attaq/main.cpp deleted file mode 100644 index c8e534e7e7..0000000000 --- a/demos/sub-attaq/main.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include "mainwindow.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - Q_INIT_RESOURCE(subattaq); - - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); - - MainWindow w; - w.show(); - - return app.exec(); -} diff --git a/demos/sub-attaq/mainwindow.cpp b/demos/sub-attaq/mainwindow.cpp deleted file mode 100644 index 81632a50a0..0000000000 --- a/demos/sub-attaq/mainwindow.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "mainwindow.h" -#include "graphicsscene.h" - -//Qt -#include - -#ifdef QT_NO_OPENGL - #include - #include - #include -#else - #include -#endif - -MainWindow::MainWindow() : QMainWindow(0) -{ - QMenu *file = menuBar()->addMenu(tr("&File")); - - QAction *newAction = file->addAction(tr("New Game")); - newAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_N)); - QAction *quitAction = file->addAction(tr("Quit")); - quitAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q)); - - if (QApplication::arguments().contains("-fullscreen")) { - scene = new GraphicsScene(0, 0, 750, 400, GraphicsScene::Small); - setWindowState(Qt::WindowFullScreen); - } else { - scene = new GraphicsScene(0, 0, 880, 630); - layout()->setSizeConstraint(QLayout::SetFixedSize); - } - - view = new QGraphicsView(scene, this); - view->setAlignment(Qt::AlignLeft | Qt::AlignTop); - scene->setupScene(newAction, quitAction); -#ifndef QT_NO_OPENGL - view->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); -#endif - - setCentralWidget(view); -} diff --git a/demos/sub-attaq/mainwindow.h b/demos/sub-attaq/mainwindow.h deleted file mode 100644 index 933587a262..0000000000 --- a/demos/sub-attaq/mainwindow.h +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __MAINWINDOW__H__ -#define __MAINWINDOW__H__ - -//Qt -#include -class GraphicsScene; -QT_BEGIN_NAMESPACE -class QGraphicsView; -QT_END_NAMESPACE - -class MainWindow : public QMainWindow -{ -Q_OBJECT -public: - MainWindow(); - -private: - GraphicsScene *scene; - QGraphicsView *view; -}; - -#endif //__MAINWINDOW__H__ diff --git a/demos/sub-attaq/pics/big/background.png b/demos/sub-attaq/pics/big/background.png deleted file mode 100644 index 9f581571fa..0000000000 Binary files a/demos/sub-attaq/pics/big/background.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/boat.png b/demos/sub-attaq/pics/big/boat.png deleted file mode 100644 index be82dff62a..0000000000 Binary files a/demos/sub-attaq/pics/big/boat.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/bomb.png b/demos/sub-attaq/pics/big/bomb.png deleted file mode 100644 index 3af5f2f29c..0000000000 Binary files a/demos/sub-attaq/pics/big/bomb.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/explosion/boat/step1.png b/demos/sub-attaq/pics/big/explosion/boat/step1.png deleted file mode 100644 index c9fd8b0984..0000000000 Binary files a/demos/sub-attaq/pics/big/explosion/boat/step1.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/explosion/boat/step2.png b/demos/sub-attaq/pics/big/explosion/boat/step2.png deleted file mode 100644 index 7528f2d2da..0000000000 Binary files a/demos/sub-attaq/pics/big/explosion/boat/step2.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/explosion/boat/step3.png b/demos/sub-attaq/pics/big/explosion/boat/step3.png deleted file mode 100644 index aae9c9c184..0000000000 Binary files a/demos/sub-attaq/pics/big/explosion/boat/step3.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/explosion/boat/step4.png b/demos/sub-attaq/pics/big/explosion/boat/step4.png deleted file mode 100644 index d697c1bae8..0000000000 Binary files a/demos/sub-attaq/pics/big/explosion/boat/step4.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/explosion/submarine/step1.png b/demos/sub-attaq/pics/big/explosion/submarine/step1.png deleted file mode 100644 index 88ca5144b7..0000000000 Binary files a/demos/sub-attaq/pics/big/explosion/submarine/step1.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/explosion/submarine/step2.png b/demos/sub-attaq/pics/big/explosion/submarine/step2.png deleted file mode 100644 index 524f5890ee..0000000000 Binary files a/demos/sub-attaq/pics/big/explosion/submarine/step2.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/explosion/submarine/step3.png b/demos/sub-attaq/pics/big/explosion/submarine/step3.png deleted file mode 100644 index 2cca1e80fe..0000000000 Binary files a/demos/sub-attaq/pics/big/explosion/submarine/step3.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/explosion/submarine/step4.png b/demos/sub-attaq/pics/big/explosion/submarine/step4.png deleted file mode 100644 index 82100a8260..0000000000 Binary files a/demos/sub-attaq/pics/big/explosion/submarine/step4.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/submarine.png b/demos/sub-attaq/pics/big/submarine.png deleted file mode 100644 index df435dc47d..0000000000 Binary files a/demos/sub-attaq/pics/big/submarine.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/surface.png b/demos/sub-attaq/pics/big/surface.png deleted file mode 100644 index 4eba29e9cd..0000000000 Binary files a/demos/sub-attaq/pics/big/surface.png and /dev/null differ diff --git a/demos/sub-attaq/pics/big/torpedo.png b/demos/sub-attaq/pics/big/torpedo.png deleted file mode 100644 index f9c26873f1..0000000000 Binary files a/demos/sub-attaq/pics/big/torpedo.png and /dev/null differ diff --git a/demos/sub-attaq/pics/scalable/background-n810.svg b/demos/sub-attaq/pics/scalable/background-n810.svg deleted file mode 100644 index ece9f7aaf1..0000000000 --- a/demos/sub-attaq/pics/scalable/background-n810.svg +++ /dev/null @@ -1,171 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/background.svg b/demos/sub-attaq/pics/scalable/background.svg deleted file mode 100644 index 0be268010e..0000000000 --- a/demos/sub-attaq/pics/scalable/background.svg +++ /dev/null @@ -1,171 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/boat.svg b/demos/sub-attaq/pics/scalable/boat.svg deleted file mode 100644 index 5298821ba8..0000000000 --- a/demos/sub-attaq/pics/scalable/boat.svg +++ /dev/null @@ -1,279 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/bomb.svg b/demos/sub-attaq/pics/scalable/bomb.svg deleted file mode 100644 index 294771a6dd..0000000000 --- a/demos/sub-attaq/pics/scalable/bomb.svg +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/sand.svg b/demos/sub-attaq/pics/scalable/sand.svg deleted file mode 100644 index 8af11b7a66..0000000000 --- a/demos/sub-attaq/pics/scalable/sand.svg +++ /dev/null @@ -1,103 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/see.svg b/demos/sub-attaq/pics/scalable/see.svg deleted file mode 100644 index 0666691215..0000000000 --- a/demos/sub-attaq/pics/scalable/see.svg +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/sky.svg b/demos/sub-attaq/pics/scalable/sky.svg deleted file mode 100644 index 1546c087a7..0000000000 --- a/demos/sub-attaq/pics/scalable/sky.svg +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/sub-attaq.svg b/demos/sub-attaq/pics/scalable/sub-attaq.svg deleted file mode 100644 index b075179b46..0000000000 --- a/demos/sub-attaq/pics/scalable/sub-attaq.svg +++ /dev/null @@ -1,1473 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/submarine.svg b/demos/sub-attaq/pics/scalable/submarine.svg deleted file mode 100644 index 8a0ffddbca..0000000000 --- a/demos/sub-attaq/pics/scalable/submarine.svg +++ /dev/null @@ -1,214 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/surface.svg b/demos/sub-attaq/pics/scalable/surface.svg deleted file mode 100644 index 40ed239638..0000000000 --- a/demos/sub-attaq/pics/scalable/surface.svg +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/scalable/torpedo.svg b/demos/sub-attaq/pics/scalable/torpedo.svg deleted file mode 100644 index 48e429d2bf..0000000000 --- a/demos/sub-attaq/pics/scalable/torpedo.svg +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/sub-attaq/pics/small/background.png b/demos/sub-attaq/pics/small/background.png deleted file mode 100644 index 5ad3db660a..0000000000 Binary files a/demos/sub-attaq/pics/small/background.png and /dev/null differ diff --git a/demos/sub-attaq/pics/small/boat.png b/demos/sub-attaq/pics/small/boat.png deleted file mode 100644 index 114ccc310e..0000000000 Binary files a/demos/sub-attaq/pics/small/boat.png and /dev/null differ diff --git a/demos/sub-attaq/pics/small/bomb.png b/demos/sub-attaq/pics/small/bomb.png deleted file mode 100644 index 3af5f2f29c..0000000000 Binary files a/demos/sub-attaq/pics/small/bomb.png and /dev/null differ diff --git a/demos/sub-attaq/pics/small/submarine.png b/demos/sub-attaq/pics/small/submarine.png deleted file mode 100644 index 0c0c350600..0000000000 Binary files a/demos/sub-attaq/pics/small/submarine.png and /dev/null differ diff --git a/demos/sub-attaq/pics/small/surface.png b/demos/sub-attaq/pics/small/surface.png deleted file mode 100644 index 06d0e47a5c..0000000000 Binary files a/demos/sub-attaq/pics/small/surface.png and /dev/null differ diff --git a/demos/sub-attaq/pics/small/torpedo.png b/demos/sub-attaq/pics/small/torpedo.png deleted file mode 100644 index f9c26873f1..0000000000 Binary files a/demos/sub-attaq/pics/small/torpedo.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-a.png b/demos/sub-attaq/pics/welcome/logo-a.png deleted file mode 100644 index 67dd76dac0..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-a.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-a2.png b/demos/sub-attaq/pics/welcome/logo-a2.png deleted file mode 100644 index 17668b07de..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-a2.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-b.png b/demos/sub-attaq/pics/welcome/logo-b.png deleted file mode 100644 index cf6c04560b..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-b.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-dash.png b/demos/sub-attaq/pics/welcome/logo-dash.png deleted file mode 100644 index 219233ce6b..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-dash.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-excl.png b/demos/sub-attaq/pics/welcome/logo-excl.png deleted file mode 100644 index 8dd0a2eb86..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-excl.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-q.png b/demos/sub-attaq/pics/welcome/logo-q.png deleted file mode 100644 index 86e588d4d8..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-q.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-s.png b/demos/sub-attaq/pics/welcome/logo-s.png deleted file mode 100644 index 7b6a36e93a..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-s.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-t.png b/demos/sub-attaq/pics/welcome/logo-t.png deleted file mode 100644 index b2e3526bea..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-t.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-t2.png b/demos/sub-attaq/pics/welcome/logo-t2.png deleted file mode 100644 index b11a77886e..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-t2.png and /dev/null differ diff --git a/demos/sub-attaq/pics/welcome/logo-u.png b/demos/sub-attaq/pics/welcome/logo-u.png deleted file mode 100644 index 24eede887a..0000000000 Binary files a/demos/sub-attaq/pics/welcome/logo-u.png and /dev/null differ diff --git a/demos/sub-attaq/pixmapitem.cpp b/demos/sub-attaq/pixmapitem.cpp deleted file mode 100644 index be75bd1995..0000000000 --- a/demos/sub-attaq/pixmapitem.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "pixmapitem.h" - -//Qt -#include - -PixmapItem::PixmapItem(const QString &fileName,GraphicsScene::Mode mode, QGraphicsItem * parent) : QGraphicsObject(parent) -{ - if (mode == GraphicsScene::Big) - pix = ":/big/" + fileName; - else - pix = ":/small/" + fileName; -} - -PixmapItem::PixmapItem(const QString &fileName, QGraphicsScene *scene) : QGraphicsObject(), pix(fileName) -{ - scene->addItem(this); -} - -QSizeF PixmapItem::size() const -{ - return pix.size(); -} - -QRectF PixmapItem::boundingRect() const -{ - return QRectF(QPointF(0, 0), pix.size()); -} - -void PixmapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - painter->drawPixmap(0, 0, pix); -} - - diff --git a/demos/sub-attaq/pixmapitem.h b/demos/sub-attaq/pixmapitem.h deleted file mode 100644 index 0a94aab7eb..0000000000 --- a/demos/sub-attaq/pixmapitem.h +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __PIXMAPITEM__H__ -#define __PIXMAPITEM__H__ - -//Own -#include "graphicsscene.h" - -//Qt -#include - -class PixmapItem : public QGraphicsObject -{ -public: - PixmapItem(const QString &fileName, GraphicsScene::Mode mode, QGraphicsItem * parent = 0); - PixmapItem(const QString &fileName, QGraphicsScene *scene); - QSizeF size() const; - QRectF boundingRect() const; - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *); -private: - QPixmap pix; -}; - -#endif //__PIXMAPITEM__H__ diff --git a/demos/sub-attaq/progressitem.cpp b/demos/sub-attaq/progressitem.cpp deleted file mode 100644 index 426dedfbd4..0000000000 --- a/demos/sub-attaq/progressitem.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "progressitem.h" -#include "pixmapitem.h" - -ProgressItem::ProgressItem (QGraphicsItem * parent) - : QGraphicsTextItem(parent), currentLevel(1), currentScore(0) -{ - setFont(QFont("Comic Sans MS")); - setPos(parentItem()->boundingRect().topRight() - QPointF(180, -5)); -} - -void ProgressItem::setLevel(int level) -{ - currentLevel = level; - updateProgress(); -} - -void ProgressItem::setScore(int score) -{ - currentScore = score; - updateProgress(); -} - -void ProgressItem::updateProgress() -{ - setHtml(QString("Level : %1 Score : %2").arg(currentLevel).arg(currentScore)); -} diff --git a/demos/sub-attaq/progressitem.h b/demos/sub-attaq/progressitem.h deleted file mode 100644 index bcf708c512..0000000000 --- a/demos/sub-attaq/progressitem.h +++ /dev/null @@ -1,61 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef PROGRESSITEM_H -#define PROGRESSITEM_H - -//Qt -#include - -class ProgressItem : public QGraphicsTextItem -{ -public: - ProgressItem(QGraphicsItem * parent = 0); - void setLevel(int level); - void setScore(int score); - -private: - void updateProgress(); - int currentLevel; - int currentScore; -}; - -#endif // PROGRESSITEM_H diff --git a/demos/sub-attaq/qanimationstate.cpp b/demos/sub-attaq/qanimationstate.cpp deleted file mode 100644 index 593c8dfe8d..0000000000 --- a/demos/sub-attaq/qanimationstate.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qanimationstate.h" - -#include - -QT_BEGIN_NAMESPACE - -/*! -\class QAnimationState - -\brief The QAnimationState class provides state that handle an animation and emit -a signal when this animation is finished. - -\ingroup statemachine - -QAnimationState provides a state that handle an animation. It will start this animation -when the state is entered and stop it when it is leaved. When the animation has finished the -state emit animationFinished signal. -QAnimationState is part of \l{The State Machine Framework}. - -\code -QStateMachine machine; -QAnimationState *s = new QAnimationState(machine->rootState()); -QPropertyAnimation *animation = new QPropertyAnimation(obj, "pos"); -s->setAnimation(animation); -QState *s2 = new QState(machine->rootState()); -s->addTransition(s, SIGNAL(animationFinished()), s2); -machine.start(); -\endcode - -\sa QState, {The Animation Framework} -*/ - - -#ifndef QT_NO_ANIMATION - -/*! - Constructs a new state with the given \a parent state. -*/ -QAnimationState::QAnimationState(QState *parent) - : QState(parent), m_animation(0) -{ -} - -/*! - Destroys the animation state. -*/ -QAnimationState::~QAnimationState() -{ -} - -/*! - Set an \a animation for this QAnimationState. If an animation was previously handle by this - state then it won't emit animationFinished for the old animation. The QAnimationState doesn't - take the ownership of the animation. -*/ -void QAnimationState::setAnimation(QAbstractAnimation *animation) -{ - if (animation == m_animation) - return; - - //Disconnect from the previous animation if exist - if(m_animation) - disconnect(m_animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); - - m_animation = animation; - - if (m_animation) { - //connect the new animation - connect(m_animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); - } -} - -/*! - Returns the animation handle by this animation state, or 0 if there is no animation. -*/ -QAbstractAnimation* QAnimationState::animation() const -{ - return m_animation; -} - -/*! - \reimp -*/ -void QAnimationState::onEntry(QEvent *) -{ - if (m_animation) - m_animation->start(); -} - -/*! - \reimp -*/ -void QAnimationState::onExit(QEvent *) -{ - if (m_animation) - m_animation->stop(); -} - -/*! - \reimp -*/ -bool QAnimationState::event(QEvent *e) -{ - return QState::event(e); -} - -QT_END_NAMESPACE - -#endif diff --git a/demos/sub-attaq/qanimationstate.h b/demos/sub-attaq/qanimationstate.h deleted file mode 100644 index aace3b502b..0000000000 --- a/demos/sub-attaq/qanimationstate.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QANIMATIONSTATE_H -#define QANIMATIONSTATE_H - -#ifndef QT_STATEMACHINE_SOLUTION -# include -# include -#else -# include "qstate.h" -# include "qabstractanimation.h" -#endif - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -#ifndef QT_NO_ANIMATION - -class QAbstractAnimation; - -class QAnimationState : public QState -{ - Q_OBJECT -public: - QAnimationState(QState *parent = 0); - ~QAnimationState(); - - void setAnimation(QAbstractAnimation *animation); - QAbstractAnimation* animation() const; - -signals: - void animationFinished(); - -protected: - void onEntry(QEvent *); - void onExit(QEvent *); - bool event(QEvent *e); - -private: - Q_DISABLE_COPY(QAnimationState) - QAbstractAnimation *m_animation; -}; - -#endif - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QANIMATIONSTATE_H diff --git a/demos/sub-attaq/states.cpp b/demos/sub-attaq/states.cpp deleted file mode 100644 index 462e13b90e..0000000000 --- a/demos/sub-attaq/states.cpp +++ /dev/null @@ -1,330 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "states.h" -#include "graphicsscene.h" -#include "boat.h" -#include "submarine.h" -#include "torpedo.h" -#include "animationmanager.h" -#include "progressitem.h" -#include "textinformationitem.h" - -//Qt -#include -#include -#include -#include -#include - -PlayState::PlayState(GraphicsScene *scene, QState *parent) - : QState(parent), - scene(scene), - machine(0), - currentLevel(0), - score(0) -{ -} - -PlayState::~PlayState() -{ - delete machine; -} - -void PlayState::onEntry(QEvent *) -{ - //We are now playing? - if (machine) { - machine->stop(); - //we hide the information - scene->textInformationItem->hide(); - scene->clearScene(); - currentLevel = 0; - score = 0; - delete machine; - } - - machine = new QStateMachine; - - //This state is when player is playing - LevelState *levelState = new LevelState(scene, this, machine); - - //This state is when the player is actually playing but the game is not paused - QState *playingState = new QState(levelState); - levelState->setInitialState(playingState); - - //This state is when the game is paused - PauseState *pauseState = new PauseState(scene, levelState); - - //We have one view, it receive the key press event - QKeyEventTransition *pressPplay = new QKeyEventTransition(scene->views().at(0), QEvent::KeyPress, Qt::Key_P); - pressPplay->setTargetState(pauseState); - QKeyEventTransition *pressPpause = new QKeyEventTransition(scene->views().at(0), QEvent::KeyPress, Qt::Key_P); - pressPpause->setTargetState(playingState); - - //Pause "P" is triggered, the player pause the game - playingState->addTransition(pressPplay); - - //To get back playing when the game has been paused - pauseState->addTransition(pressPpause); - - //This state is when player have lost - LostState *lostState = new LostState(scene, this, machine); - - //This state is when player have won - WinState *winState = new WinState(scene, this, machine); - - //The boat has been destroyed then the game is finished - levelState->addTransition(scene->boat, SIGNAL(boatExecutionFinished()),lostState); - - //This transition check if we won or not - WinTransition *winTransition = new WinTransition(scene, this, winState); - - //The boat has been destroyed then the game is finished - levelState->addTransition(winTransition); - - //This state is an animation when the score changed - UpdateScoreState *scoreState = new UpdateScoreState(this, levelState); - - //This transition update the score when a submarine die - UpdateScoreTransition *scoreTransition = new UpdateScoreTransition(scene, this, levelState); - scoreTransition->setTargetState(scoreState); - - //The boat has been destroyed then the game is finished - playingState->addTransition(scoreTransition); - - //We go back to play state - scoreState->addTransition(playingState); - - //We start playing!!! - machine->setInitialState(levelState); - - //Final state - QFinalState *final = new QFinalState(machine); - - //This transition is triggered when the player press space after completing a level - CustomSpaceTransition *spaceTransition = new CustomSpaceTransition(scene->views().at(0), this, QEvent::KeyPress, Qt::Key_Space); - spaceTransition->setTargetState(levelState); - winState->addTransition(spaceTransition); - - //We lost we should reach the final state - lostState->addTransition(lostState, SIGNAL(finished()), final); - - machine->start(); -} - -LevelState::LevelState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) -{ -} -void LevelState::onEntry(QEvent *) -{ - initializeLevel(); -} - -void LevelState::initializeLevel() -{ - //we re-init the boat - scene->boat->setPos(scene->width()/2, scene->sealLevel() - scene->boat->size().height()); - scene->boat->setCurrentSpeed(0); - scene->boat->setCurrentDirection(Boat::None); - scene->boat->setBombsLaunched(0); - scene->boat->show(); - scene->setFocusItem(scene->boat, Qt::OtherFocusReason); - scene->boat->run(); - - scene->progressItem->setScore(game->score); - scene->progressItem->setLevel(game->currentLevel + 1); - - GraphicsScene::LevelDescription currentLevelDescription = scene->levelsData.value(game->currentLevel); - - for (int i = 0; i < currentLevelDescription.submarines.size(); ++i ) { - - QPair subContent = currentLevelDescription.submarines.at(i); - GraphicsScene::SubmarineDescription submarineDesc = scene->submarinesData.at(subContent.first); - - for (int j = 0; j < subContent.second; ++j ) { - SubMarine *sub = new SubMarine(submarineDesc.type, submarineDesc.name, submarineDesc.points); - scene->addItem(sub); - int random = (qrand() % 15 + 1); - qreal x = random == 13 || random == 5 ? 0 : scene->width() - sub->size().width(); - qreal y = scene->height() -(qrand() % 150 + 1) - sub->size().height(); - sub->setPos(x,y); - sub->setCurrentDirection(x == 0 ? SubMarine::Right : SubMarine::Left); - sub->setCurrentSpeed(qrand() % 3 + 1); - } - } -} - -/** Pause State */ -PauseState::PauseState(GraphicsScene *scene, QState *parent) : QState(parent),scene(scene) -{ -} -void PauseState::onEntry(QEvent *) -{ - AnimationManager::self()->pauseAll(); - scene->boat->setEnabled(false); -} -void PauseState::onExit(QEvent *) -{ - AnimationManager::self()->resumeAll(); - scene->boat->setEnabled(true); - scene->boat->setFocus(); -} - -/** Lost State */ -LostState::LostState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) -{ -} - -void LostState::onEntry(QEvent *) -{ - //The message to display - QString message = QString("You lose on level %1. Your score is %2.").arg(game->currentLevel+1).arg(game->score); - - //We set the level back to 0 - game->currentLevel = 0; - - //We set the score back to 0 - game->score = 0; - - //We clear the scene - scene->clearScene(); - - //We inform the player - scene->textInformationItem->setMessage(message); - scene->textInformationItem->show(); -} - -void LostState::onExit(QEvent *) -{ - //we hide the information - scene->textInformationItem->hide(); -} - -/** Win State */ -WinState::WinState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) -{ -} - -void WinState::onEntry(QEvent *) -{ - //We clear the scene - scene->clearScene(); - - QString message; - if (scene->levelsData.size() - 1 != game->currentLevel) { - message = QString("You win the level %1. Your score is %2.\nPress Space to continue.").arg(game->currentLevel+1).arg(game->score); - //We increment the level number - game->currentLevel++; - } else { - message = QString("You finish the game on level %1. Your score is %2.").arg(game->currentLevel+1).arg(game->score); - //We set the level back to 0 - game->currentLevel = 0; - //We set the score back to 0 - game->score = 0; - } - - //We inform the player - scene->textInformationItem->setMessage(message); - scene->textInformationItem->show(); -} - -void WinState::onExit(QEvent *) -{ - //we hide the information - scene->textInformationItem->hide(); -} - -/** UpdateScore State */ -UpdateScoreState::UpdateScoreState(PlayState *g, QState *parent) : QState(parent), game(g) -{ -} - -/** Win transition */ -UpdateScoreTransition::UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) - : QSignalTransition(scene,SIGNAL(subMarineDestroyed(int))), - game(game), scene(scene) -{ - setTargetState(target); -} - -bool UpdateScoreTransition::eventTest(QEvent *event) -{ - if (!QSignalTransition::eventTest(event)) - return false; - QStateMachine::SignalEvent *se = static_cast(event); - game->score += se->arguments().at(0).toInt(); - scene->progressItem->setScore(game->score); - return true; -} - -/** Win transition */ -WinTransition::WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) - : QSignalTransition(scene,SIGNAL(allSubMarineDestroyed(int))), - game(game), scene(scene) -{ - setTargetState(target); -} - -bool WinTransition::eventTest(QEvent *event) -{ - if (!QSignalTransition::eventTest(event)) - return false; - QStateMachine::SignalEvent *se = static_cast(event); - game->score += se->arguments().at(0).toInt(); - scene->progressItem->setScore(game->score); - return true; -} - -/** Space transition */ -CustomSpaceTransition::CustomSpaceTransition(QWidget *widget, PlayState *game, QEvent::Type type, int key) - : QKeyEventTransition(widget, type, key), - game(game) -{ -} - -bool CustomSpaceTransition::eventTest(QEvent *event) -{ - if (!QKeyEventTransition::eventTest(event)) - return false; - return (game->currentLevel != 0); -} diff --git a/demos/sub-attaq/states.h b/demos/sub-attaq/states.h deleted file mode 100644 index cda9603196..0000000000 --- a/demos/sub-attaq/states.h +++ /dev/null @@ -1,180 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef STATES_H -#define STATES_H - -//Qt -#include -#include -#include -#include -#include - -class GraphicsScene; -class Boat; -class SubMarine; -QT_BEGIN_NAMESPACE -class QStateMachine; -QT_END_NAMESPACE - -class PlayState : public QState -{ -public: - PlayState(GraphicsScene *scene, QState *parent = 0); - ~PlayState(); - - protected: - void onEntry(QEvent *); - -private : - GraphicsScene *scene; - QStateMachine *machine; - int currentLevel; - int score; - QState *parallelChild; - - friend class UpdateScoreState; - friend class UpdateScoreTransition; - friend class WinTransition; - friend class CustomSpaceTransition; - friend class WinState; - friend class LostState; - friend class LevelState; -}; - -class LevelState : public QState -{ -public: - LevelState(GraphicsScene *scene, PlayState *game, QState *parent = 0); -protected: - void onEntry(QEvent *); -private : - void initializeLevel(); - GraphicsScene *scene; - PlayState *game; -}; - -class PauseState : public QState -{ -public: - PauseState(GraphicsScene *scene, QState *parent = 0); - -protected: - void onEntry(QEvent *); - void onExit(QEvent *); -private : - GraphicsScene *scene; - Boat *boat; -}; - -class LostState : public QState -{ -public: - LostState(GraphicsScene *scene, PlayState *game, QState *parent = 0); - -protected: - void onEntry(QEvent *); - void onExit(QEvent *); -private : - GraphicsScene *scene; - PlayState *game; -}; - -class WinState : public QState -{ -public: - WinState(GraphicsScene *scene, PlayState *game, QState *parent = 0); - -protected: - void onEntry(QEvent *); - void onExit(QEvent *); -private : - GraphicsScene *scene; - PlayState *game; -}; - -class UpdateScoreState : public QState -{ -public: - UpdateScoreState(PlayState *game, QState *parent); -private: - QPropertyAnimation *scoreAnimation; - PlayState *game; -}; - -//These transtion is used to update the score -class UpdateScoreTransition : public QSignalTransition -{ -public: - UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target); -protected: - virtual bool eventTest(QEvent *event); -private: - PlayState * game; - GraphicsScene *scene; -}; - -//These transtion test if we have won the game -class WinTransition : public QSignalTransition -{ -public: - WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target); -protected: - virtual bool eventTest(QEvent *event); -private: - PlayState * game; - GraphicsScene *scene; -}; - -//These transtion is true if one level has been completed and the player want to continue - class CustomSpaceTransition : public QKeyEventTransition -{ -public: - CustomSpaceTransition(QWidget *widget, PlayState *game, QEvent::Type type, int key); -protected: - virtual bool eventTest(QEvent *event); -private: - PlayState *game; - int key; -}; - -#endif // STATES_H diff --git a/demos/sub-attaq/sub-attaq.pro b/demos/sub-attaq/sub-attaq.pro deleted file mode 100644 index 5575f5e65f..0000000000 --- a/demos/sub-attaq/sub-attaq.pro +++ /dev/null @@ -1,41 +0,0 @@ -contains(QT_CONFIG, opengl):QT += opengl -HEADERS += boat.h \ - bomb.h \ - mainwindow.h \ - submarine.h \ - torpedo.h \ - pixmapitem.h \ - graphicsscene.h \ - animationmanager.h \ - states.h \ - boat_p.h \ - submarine_p.h \ - qanimationstate.h \ - progressitem.h \ - textinformationitem.h -SOURCES += boat.cpp \ - bomb.cpp \ - main.cpp \ - mainwindow.cpp \ - submarine.cpp \ - torpedo.cpp \ - pixmapitem.cpp \ - graphicsscene.cpp \ - animationmanager.cpp \ - states.cpp \ - qanimationstate.cpp \ - progressitem.cpp \ - textinformationitem.cpp -RESOURCES += subattaq.qrc - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/sub-attaq -sources.files = $$SOURCES \ - $$HEADERS \ - $$RESOURCES \ - $$FORMS \ - sub-attaq.pro \ - pics -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/sub-attaq -INSTALLS += target \ - sources diff --git a/demos/sub-attaq/subattaq.qrc b/demos/sub-attaq/subattaq.qrc deleted file mode 100644 index 80a3af11cc..0000000000 --- a/demos/sub-attaq/subattaq.qrc +++ /dev/null @@ -1,39 +0,0 @@ - - - pics/scalable/sub-attaq.svg - pics/scalable/submarine.svg - pics/scalable/boat.svg - pics/scalable/torpedo.svg - pics/welcome/logo-s.png - pics/welcome/logo-u.png - pics/welcome/logo-b.png - pics/welcome/logo-dash.png - pics/welcome/logo-a.png - pics/welcome/logo-t.png - pics/welcome/logo-t2.png - pics/welcome/logo-a2.png - pics/welcome/logo-q.png - pics/welcome/logo-excl.png - pics/big/background.png - pics/big/boat.png - pics/big/bomb.png - pics/big/submarine.png - pics/big/surface.png - pics/big/torpedo.png - pics/small/background.png - pics/small/boat.png - pics/small/bomb.png - pics/small/submarine.png - pics/small/surface.png - pics/small/torpedo.png - pics/big/explosion/boat/step1.png - pics/big/explosion/boat/step2.png - pics/big/explosion/boat/step3.png - pics/big/explosion/boat/step4.png - pics/big/explosion/submarine/step1.png - pics/big/explosion/submarine/step2.png - pics/big/explosion/submarine/step3.png - pics/big/explosion/submarine/step4.png - data.xml - - diff --git a/demos/sub-attaq/submarine.cpp b/demos/sub-attaq/submarine.cpp deleted file mode 100644 index 2c8a5a2884..0000000000 --- a/demos/sub-attaq/submarine.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "submarine.h" -#include "submarine_p.h" -#include "torpedo.h" -#include "pixmapitem.h" -#include "graphicsscene.h" -#include "animationmanager.h" -#include "qanimationstate.h" - -#include -#include -#include -#include - -static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub) -{ - QSequentialAnimationGroup *group = new QSequentialAnimationGroup(sub); - for (int i = 1; i <= 4; ++i) { - PixmapItem *step = new PixmapItem(QString::fromLatin1("explosion/submarine/step%1").arg(i), GraphicsScene::Big, sub); - step->setZValue(6); - step->setOpacity(0); - QPropertyAnimation *anim = new QPropertyAnimation(step, "opacity", group); - anim->setDuration(100); - anim->setEndValue(1); - } - AnimationManager::self()->registerAnimation(group); - return group; -} - - -SubMarine::SubMarine(int type, const QString &name, int points) : PixmapItem(QString("submarine"), GraphicsScene::Big), - subType(type), subName(name), subPoints(points), speed(0), direction(SubMarine::None) -{ - setZValue(5); - setTransformOriginPoint(boundingRect().center()); - - graphicsRotation = new QGraphicsRotation(this); - graphicsRotation->setAxis(Qt::YAxis); - graphicsRotation->setOrigin(QVector3D(size().width()/2, size().height()/2, 0)); - QList r; - r.append(graphicsRotation); - setTransformations(r); - - //We setup the state machine of the submarine - QStateMachine *machine = new QStateMachine(this); - - //This state is when the boat is moving/rotating - QState *moving = new QState(machine); - - //This state is when the boat is moving from left to right - MovementState *movement = new MovementState(this, moving); - - //This state is when the boat is moving from left to right - ReturnState *rotation = new ReturnState(this, moving); - - //This is the initial state of the moving root state - moving->setInitialState(movement); - - movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving); - - //This is the initial state of the machine - machine->setInitialState(moving); - - //End - QFinalState *final = new QFinalState(machine); - - //If the moving animation is finished we move to the return state - movement->addTransition(movement, SIGNAL(animationFinished()), rotation); - - //If the return animation is finished we move to the moving state - rotation->addTransition(rotation, SIGNAL(animationFinished()), movement); - - //This state play the destroyed animation - QAnimationState *destroyedState = new QAnimationState(machine); - destroyedState->setAnimation(setupDestroyAnimation(this)); - - //Play a nice animation when the submarine is destroyed - moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState); - - //Transition to final state when the destroyed animation is finished - destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); - - //The machine has finished to be executed, then the submarine is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished())); - - machine->start(); -} - -int SubMarine::points() const -{ - return subPoints; -} - -void SubMarine::setCurrentDirection(SubMarine::Movement direction) -{ - if (this->direction == direction) - return; - if (direction == SubMarine::Right && this->direction == SubMarine::None) { - graphicsRotation->setAngle(180); - } - this->direction = direction; -} - -enum SubMarine::Movement SubMarine::currentDirection() const -{ - return direction; -} - -void SubMarine::setCurrentSpeed(int speed) -{ - if (speed < 0 || speed > 3) { - qWarning("SubMarine::setCurrentSpeed : The speed is invalid"); - } - this->speed = speed; - emit subMarineStateChanged(); -} - -int SubMarine::currentSpeed() const -{ - return speed; -} - -void SubMarine::launchTorpedo(int speed) -{ - Torpedo * torp = new Torpedo(); - GraphicsScene *scene = static_cast(this->scene()); - scene->addItem(torp); - torp->setPos(pos()); - torp->setCurrentSpeed(speed); - torp->launch(); -} - -void SubMarine::destroy() -{ - emit subMarineDestroyed(); -} - -int SubMarine::type() const -{ - return Type; -} diff --git a/demos/sub-attaq/submarine.h b/demos/sub-attaq/submarine.h deleted file mode 100644 index 0d6087dc26..0000000000 --- a/demos/sub-attaq/submarine.h +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __SUBMARINE__H__ -#define __SUBMARINE__H__ - -//Qt -#include - -#include "pixmapitem.h" - -class Torpedo; - -class SubMarine : public PixmapItem -{ -Q_OBJECT -public: - enum Movement { - None = 0, - Left, - Right - }; - enum { Type = UserType + 1 }; - SubMarine(int type, const QString &name, int points); - - int points() const; - - void setCurrentDirection(Movement direction); - enum Movement currentDirection() const; - - void setCurrentSpeed(int speed); - int currentSpeed() const; - - void launchTorpedo(int speed); - void destroy(); - - virtual int type() const; - - QGraphicsRotation *rotation() const { return graphicsRotation; } - -signals: - void subMarineDestroyed(); - void subMarineExecutionFinished(); - void subMarineStateChanged(); - -private: - int subType; - QString subName; - int subPoints; - int speed; - Movement direction; - QGraphicsRotation *graphicsRotation; -}; - -#endif //__SUBMARINE__H__ diff --git a/demos/sub-attaq/submarine_p.h b/demos/sub-attaq/submarine_p.h deleted file mode 100644 index f0b370d878..0000000000 --- a/demos/sub-attaq/submarine_p.h +++ /dev/null @@ -1,137 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SUBMARINE_P_H -#define SUBMARINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -//Own -#include "animationmanager.h" -#include "submarine.h" -#include "qanimationstate.h" - -//Qt -#include -#include - -//This state is describing when the boat is moving right -class MovementState : public QAnimationState -{ -Q_OBJECT -public: - MovementState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) - { - movementAnimation = new QPropertyAnimation(submarine, "pos"); - connect(movementAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationMovementValueChanged(const QVariant &))); - setAnimation(movementAnimation); - AnimationManager::self()->registerAnimation(movementAnimation); - this->submarine = submarine; - } - -protected slots: - void onAnimationMovementValueChanged(const QVariant &) - { - if (qrand() % 200 + 1 == 3) - submarine->launchTorpedo(qrand() % 3 + 1); - } - -protected: - void onEntry(QEvent *e) - { - if (submarine->currentDirection() == SubMarine::Left) { - movementAnimation->setEndValue(QPointF(0,submarine->y())); - movementAnimation->setDuration(submarine->x()/submarine->currentSpeed()*12); - } - else /*if (submarine->currentDirection() == SubMarine::Right)*/ { - movementAnimation->setEndValue(QPointF(submarine->scene()->width()-submarine->size().width(),submarine->y())); - movementAnimation->setDuration((submarine->scene()->width()-submarine->size().width()-submarine->x())/submarine->currentSpeed()*12); - } - QAnimationState::onEntry(e); - } - -private: - SubMarine *submarine; - QPropertyAnimation *movementAnimation; -}; - -//This state is describing when the boat is moving right -class ReturnState : public QAnimationState -{ -public: - ReturnState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) - { - returnAnimation = new QPropertyAnimation(submarine->rotation(), "angle"); - returnAnimation->setDuration(500); - AnimationManager::self()->registerAnimation(returnAnimation); - setAnimation(returnAnimation); - this->submarine = submarine; - } - -protected: - void onEntry(QEvent *e) - { - returnAnimation->stop(); - returnAnimation->setEndValue(submarine->currentDirection() == SubMarine::Right ? 360. : 180.); - QAnimationState::onEntry(e); - } - - void onExit(QEvent *e) - { - submarine->currentDirection() == SubMarine::Right ? submarine->setCurrentDirection(SubMarine::Left) : submarine->setCurrentDirection(SubMarine::Right); - QAnimationState::onExit(e); - } - -private: - SubMarine *submarine; - QPropertyAnimation *returnAnimation; -}; - -#endif // SUBMARINE_P_H diff --git a/demos/sub-attaq/textinformationitem.cpp b/demos/sub-attaq/textinformationitem.cpp deleted file mode 100644 index e2653361a1..0000000000 --- a/demos/sub-attaq/textinformationitem.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#include "textinformationitem.h" -#include "pixmapitem.h" - -TextInformationItem::TextInformationItem (QGraphicsItem * parent) - : QGraphicsTextItem(parent) -{ - setFont(QFont("Comic Sans MS", 15)); -} -#include -void TextInformationItem::setMessage(const QString& text) -{ - setHtml(text); - setPos(parentItem()->boundingRect().center().x() - boundingRect().size().width()/2 , parentItem()->boundingRect().center().y()); -} diff --git a/demos/sub-attaq/textinformationitem.h b/demos/sub-attaq/textinformationitem.h deleted file mode 100644 index 4b5f71969f..0000000000 --- a/demos/sub-attaq/textinformationitem.h +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef TEXTINFORMATIONITEM_H -#define TEXTINFORMATIONITEM_H - -//Qt -#include - -class TextInformationItem : public QGraphicsTextItem -{ -public: - TextInformationItem(QGraphicsItem * parent = 0); - void setMessage(const QString& text); -}; - -#endif // TEXTINFORMATIONITEM_H diff --git a/demos/sub-attaq/torpedo.cpp b/demos/sub-attaq/torpedo.cpp deleted file mode 100644 index 8c9bacfa38..0000000000 --- a/demos/sub-attaq/torpedo.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "torpedo.h" -#include "pixmapitem.h" -#include "boat.h" -#include "graphicsscene.h" -#include "animationmanager.h" -#include "qanimationstate.h" - -#include -#include -#include - -Torpedo::Torpedo() : PixmapItem(QString::fromLatin1("torpedo"),GraphicsScene::Big), - currentSpeed(0) -{ - setZValue(2); -} - -void Torpedo::launch() -{ - QPropertyAnimation *launchAnimation = new QPropertyAnimation(this, "pos"); - AnimationManager::self()->registerAnimation(launchAnimation); - launchAnimation->setEndValue(QPointF(x(),qobject_cast(scene())->sealLevel() - 15)); - launchAnimation->setEasingCurve(QEasingCurve::InQuad); - launchAnimation->setDuration(y()/currentSpeed*10); - connect(launchAnimation,SIGNAL(valueChanged(QVariant)),this,SLOT(onAnimationLaunchValueChanged(QVariant))); - connect(this,SIGNAL(torpedoExploded()), launchAnimation, SLOT(stop())); - - //We setup the state machine of the torpedo - QStateMachine *machine = new QStateMachine(this); - - //This state is when the launch animation is playing - QAnimationState *launched = new QAnimationState(machine); - launched->setAnimation(launchAnimation); - - //End - QFinalState *final = new QFinalState(machine); - - machine->setInitialState(launched); - - //### Add a nice animation when the torpedo is destroyed - launched->addTransition(this, SIGNAL(torpedoExploded()),final); - - //If the animation is finished, then we move to the final state - launched->addTransition(launched, SIGNAL(animationFinished()), final); - - //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(torpedoExecutionFinished())); - - machine->start(); -} - -void Torpedo::setCurrentSpeed(int speed) -{ - if (speed < 0) { - qWarning("Torpedo::setCurrentSpeed : The speed is invalid"); - return; - } - currentSpeed = speed; -} - -void Torpedo::onAnimationLaunchValueChanged(const QVariant &) -{ - foreach (QGraphicsItem *item , collidingItems(Qt::IntersectsItemBoundingRect)) { - if (Boat *b = qgraphicsitem_cast(item)) - b->destroy(); - } -} - -void Torpedo::destroy() -{ - emit torpedoExploded(); -} diff --git a/demos/sub-attaq/torpedo.h b/demos/sub-attaq/torpedo.h deleted file mode 100644 index a5ec24dabf..0000000000 --- a/demos/sub-attaq/torpedo.h +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __TORPEDO__H__ -#define __TORPEDO__H__ - -#include "pixmapitem.h" - -class Torpedo : public PixmapItem -{ -Q_OBJECT -public: - Torpedo(); - void launch(); - void setCurrentSpeed(int speed); - void destroy(); - -signals: - void torpedoExploded(); - void torpedoExecutionFinished(); - -private slots: - void onAnimationLaunchValueChanged(const QVariant &); - -private: - int currentSpeed; -}; - -#endif //__TORPEDO__H__ diff --git a/demos/textedit/example.html b/demos/textedit/example.html deleted file mode 100644 index 6327b5f8fc..0000000000 --- a/demos/textedit/example.html +++ /dev/null @@ -1,79 +0,0 @@ -QTextEdit Demonstration -

    QTextEdit

    -

    The QTextEdit widget is an advanced editor that supports formatted rich text. It can be used to display HTML and other rich document formats. Internally, QTextEdit uses the QTextDocument class to describe both the high-level structure of each document and the low-level formatting of paragraphs.

    -

    If you are viewing this document in the textedit demo, you can edit this document to explore Qt's rich text editing features. We have included some comments in each of the following sections to encourage you to experiment.

    -

    Font and Paragraph Styles

    -

    QTextEdit supports bold, italic, and underlined font styles, and can display multicolored text. Font families such as Times New Roman and Courier can also be used directly. If you place the cursor in a region of styled text, the controls in the tool bars will change to reflect the current style.

    -

    Paragraphs can be formatted so that the text is left-aligned, right-aligned, centered, or fully justified.

    -

    Try changing the alignment of some text and resize the editor to see how the text layout changes.

    -

    Lists

    -

    Different kinds of lists can be included in rich text documents. Standard bullet lists can be nested, using different symbols for each level of the list:

    -
    • Disc symbols are typically used for top-level list items.
    -
    • Circle symbols can be used to distinguish between items in lower-level lists.
    -
    • Square symbols provide a reasonable alternative to discs and circles.
    -

    Ordered lists can be created that can be used for tables of contents. Different characters can be used to enumerate items, and we can use both Roman and Arabic numerals in the same list structure:

    -
    1. Introduction
    2. -
    3. Qt Tools
    -
    1. Qt Assistant
    2. -
    3. Qt Designer
    4. -
      1. Form Editor
      2. -
      3. Component Architecture
      -
    5. Qt Linguist
    -

    -

    The list will automatically be renumbered if you add or remove items. Try adding new sections to the above list or removing existing item to see the numbers change.

    -

    -

    Images

    -

    Inline images are treated like ordinary ranges of characters in the text editor, so they flow with the surrounding text. Images can also be selected in the same way as text, making it easy to cut, copy, and paste them.

    -

    Try to select this image by clicking and dragging over it with the mouse, or use the text cursor to select it by holding down Shift and using the arrow keys. You can then cut or copy it, and paste it into different parts of this document.

    -

    Tables

    -

    QTextEdit can arrange and format tables, supporting features such as row and column spans, text formatting within cells, and size constraints for columns.

    -

    -

    - - - - - - - - - - - - - - - - - - - - - - -
    -

    -

    Development Tools

    -

    Programming Techniques

    -

    Graphical User Interfaces

    -

    9:00 - 11:00

    -

    Introduction to Qt

    -

    11:00 - 13:00

    -

    Using qmake

    -

    Object-oriented Programming

    -

    Layouts in Qt

    -

    13:00 - 15:00

    -

    Qt Designer Tutorial

    -

    Extreme Programming

    -

    Writing Custom Styles

    -

    15:00 - 17:00

    -

    Qt Linguist and Internationalization

    -

    -

    Try adding text to the cells in the table and experiment with the alignment of the paragraphs.

    -

    Hyperlinks

    -

    QTextEdit is designed to support hyperlinks between documents, and this feature is used extensively in Qt Assistant. Hyperlinks are automatically created when an HTML file is imported into an editor. Since the rich text framework supports hyperlinks natively, they can also be created programatically.

    -

    Undo and Redo

    -

    Full support for undo and redo operations is built into QTextEdit and the underlying rich text framework. Operations on a document can be packaged together to make editing a more comfortable experience for the user.

    -

    Try making changes to this document and press Ctrl+Z to undo them. You can always recover the original contents of the document.

    diff --git a/demos/textedit/images/logo32.png b/demos/textedit/images/logo32.png deleted file mode 100644 index 5f91e9873b..0000000000 Binary files a/demos/textedit/images/logo32.png and /dev/null differ diff --git a/demos/textedit/images/mac/editcopy.png b/demos/textedit/images/mac/editcopy.png deleted file mode 100644 index f551364464..0000000000 Binary files a/demos/textedit/images/mac/editcopy.png and /dev/null differ diff --git a/demos/textedit/images/mac/editcut.png b/demos/textedit/images/mac/editcut.png deleted file mode 100644 index a784fd5709..0000000000 Binary files a/demos/textedit/images/mac/editcut.png and /dev/null differ diff --git a/demos/textedit/images/mac/editpaste.png b/demos/textedit/images/mac/editpaste.png deleted file mode 100644 index 64c0b2d6ab..0000000000 Binary files a/demos/textedit/images/mac/editpaste.png and /dev/null differ diff --git a/demos/textedit/images/mac/editredo.png b/demos/textedit/images/mac/editredo.png deleted file mode 100644 index 8875bf246c..0000000000 Binary files a/demos/textedit/images/mac/editredo.png and /dev/null differ diff --git a/demos/textedit/images/mac/editundo.png b/demos/textedit/images/mac/editundo.png deleted file mode 100644 index a3bd5e0bf2..0000000000 Binary files a/demos/textedit/images/mac/editundo.png and /dev/null differ diff --git a/demos/textedit/images/mac/exportpdf.png b/demos/textedit/images/mac/exportpdf.png deleted file mode 100644 index ebb44e6b88..0000000000 Binary files a/demos/textedit/images/mac/exportpdf.png and /dev/null differ diff --git a/demos/textedit/images/mac/filenew.png b/demos/textedit/images/mac/filenew.png deleted file mode 100644 index d3882c7b3f..0000000000 Binary files a/demos/textedit/images/mac/filenew.png and /dev/null differ diff --git a/demos/textedit/images/mac/fileopen.png b/demos/textedit/images/mac/fileopen.png deleted file mode 100644 index fc06c5ec63..0000000000 Binary files a/demos/textedit/images/mac/fileopen.png and /dev/null differ diff --git a/demos/textedit/images/mac/fileprint.png b/demos/textedit/images/mac/fileprint.png deleted file mode 100644 index 10ca56c82a..0000000000 Binary files a/demos/textedit/images/mac/fileprint.png and /dev/null differ diff --git a/demos/textedit/images/mac/filesave.png b/demos/textedit/images/mac/filesave.png deleted file mode 100644 index b41ecf5319..0000000000 Binary files a/demos/textedit/images/mac/filesave.png and /dev/null differ diff --git a/demos/textedit/images/mac/textbold.png b/demos/textedit/images/mac/textbold.png deleted file mode 100644 index 38400bd1f6..0000000000 Binary files a/demos/textedit/images/mac/textbold.png and /dev/null differ diff --git a/demos/textedit/images/mac/textcenter.png b/demos/textedit/images/mac/textcenter.png deleted file mode 100644 index 2ef5b2ee6f..0000000000 Binary files a/demos/textedit/images/mac/textcenter.png and /dev/null differ diff --git a/demos/textedit/images/mac/textitalic.png b/demos/textedit/images/mac/textitalic.png deleted file mode 100644 index 0170ee26a6..0000000000 Binary files a/demos/textedit/images/mac/textitalic.png and /dev/null differ diff --git a/demos/textedit/images/mac/textjustify.png b/demos/textedit/images/mac/textjustify.png deleted file mode 100644 index 39cd6c1a9d..0000000000 Binary files a/demos/textedit/images/mac/textjustify.png and /dev/null differ diff --git a/demos/textedit/images/mac/textleft.png b/demos/textedit/images/mac/textleft.png deleted file mode 100644 index 83a66d5535..0000000000 Binary files a/demos/textedit/images/mac/textleft.png and /dev/null differ diff --git a/demos/textedit/images/mac/textright.png b/demos/textedit/images/mac/textright.png deleted file mode 100644 index e7c04645cf..0000000000 Binary files a/demos/textedit/images/mac/textright.png and /dev/null differ diff --git a/demos/textedit/images/mac/textunder.png b/demos/textedit/images/mac/textunder.png deleted file mode 100644 index 968bac5e90..0000000000 Binary files a/demos/textedit/images/mac/textunder.png and /dev/null differ diff --git a/demos/textedit/images/mac/zoomin.png b/demos/textedit/images/mac/zoomin.png deleted file mode 100644 index d46f5aff0d..0000000000 Binary files a/demos/textedit/images/mac/zoomin.png and /dev/null differ diff --git a/demos/textedit/images/mac/zoomout.png b/demos/textedit/images/mac/zoomout.png deleted file mode 100644 index 46326566d1..0000000000 Binary files a/demos/textedit/images/mac/zoomout.png and /dev/null differ diff --git a/demos/textedit/images/win/editcopy.png b/demos/textedit/images/win/editcopy.png deleted file mode 100644 index 1121b47d8b..0000000000 Binary files a/demos/textedit/images/win/editcopy.png and /dev/null differ diff --git a/demos/textedit/images/win/editcut.png b/demos/textedit/images/win/editcut.png deleted file mode 100644 index 38e55f7420..0000000000 Binary files a/demos/textedit/images/win/editcut.png and /dev/null differ diff --git a/demos/textedit/images/win/editpaste.png b/demos/textedit/images/win/editpaste.png deleted file mode 100644 index ffab15aaf8..0000000000 Binary files a/demos/textedit/images/win/editpaste.png and /dev/null differ diff --git a/demos/textedit/images/win/editredo.png b/demos/textedit/images/win/editredo.png deleted file mode 100644 index 9d679fe6fc..0000000000 Binary files a/demos/textedit/images/win/editredo.png and /dev/null differ diff --git a/demos/textedit/images/win/editundo.png b/demos/textedit/images/win/editundo.png deleted file mode 100644 index eee23d24a3..0000000000 Binary files a/demos/textedit/images/win/editundo.png and /dev/null differ diff --git a/demos/textedit/images/win/exportpdf.png b/demos/textedit/images/win/exportpdf.png deleted file mode 100644 index eef5132928..0000000000 Binary files a/demos/textedit/images/win/exportpdf.png and /dev/null differ diff --git a/demos/textedit/images/win/filenew.png b/demos/textedit/images/win/filenew.png deleted file mode 100644 index af5d122141..0000000000 Binary files a/demos/textedit/images/win/filenew.png and /dev/null differ diff --git a/demos/textedit/images/win/fileopen.png b/demos/textedit/images/win/fileopen.png deleted file mode 100644 index fc6f17e977..0000000000 Binary files a/demos/textedit/images/win/fileopen.png and /dev/null differ diff --git a/demos/textedit/images/win/fileprint.png b/demos/textedit/images/win/fileprint.png deleted file mode 100644 index ba7c02dc18..0000000000 Binary files a/demos/textedit/images/win/fileprint.png and /dev/null differ diff --git a/demos/textedit/images/win/filesave.png b/demos/textedit/images/win/filesave.png deleted file mode 100644 index 8feec99bee..0000000000 Binary files a/demos/textedit/images/win/filesave.png and /dev/null differ diff --git a/demos/textedit/images/win/textbold.png b/demos/textedit/images/win/textbold.png deleted file mode 100644 index 9cbc7138b9..0000000000 Binary files a/demos/textedit/images/win/textbold.png and /dev/null differ diff --git a/demos/textedit/images/win/textcenter.png b/demos/textedit/images/win/textcenter.png deleted file mode 100644 index 11efb4b852..0000000000 Binary files a/demos/textedit/images/win/textcenter.png and /dev/null differ diff --git a/demos/textedit/images/win/textitalic.png b/demos/textedit/images/win/textitalic.png deleted file mode 100644 index b30ce14c14..0000000000 Binary files a/demos/textedit/images/win/textitalic.png and /dev/null differ diff --git a/demos/textedit/images/win/textjustify.png b/demos/textedit/images/win/textjustify.png deleted file mode 100644 index 9de0c88085..0000000000 Binary files a/demos/textedit/images/win/textjustify.png and /dev/null differ diff --git a/demos/textedit/images/win/textleft.png b/demos/textedit/images/win/textleft.png deleted file mode 100644 index 16f80bc325..0000000000 Binary files a/demos/textedit/images/win/textleft.png and /dev/null differ diff --git a/demos/textedit/images/win/textright.png b/demos/textedit/images/win/textright.png deleted file mode 100644 index 16872df62a..0000000000 Binary files a/demos/textedit/images/win/textright.png and /dev/null differ diff --git a/demos/textedit/images/win/textunder.png b/demos/textedit/images/win/textunder.png deleted file mode 100644 index c72eff53fb..0000000000 Binary files a/demos/textedit/images/win/textunder.png and /dev/null differ diff --git a/demos/textedit/images/win/zoomin.png b/demos/textedit/images/win/zoomin.png deleted file mode 100644 index 2e586fc7bf..0000000000 Binary files a/demos/textedit/images/win/zoomin.png and /dev/null differ diff --git a/demos/textedit/images/win/zoomout.png b/demos/textedit/images/win/zoomout.png deleted file mode 100644 index a736d39343..0000000000 Binary files a/demos/textedit/images/win/zoomout.png and /dev/null differ diff --git a/demos/textedit/main.cpp b/demos/textedit/main.cpp deleted file mode 100644 index 036fa80ba7..0000000000 --- a/demos/textedit/main.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "textedit.h" -#include - -int main( int argc, char ** argv ) -{ - Q_INIT_RESOURCE(textedit); - - QApplication a( argc, argv ); - TextEdit mw; - mw.resize( 700, 800 ); - mw.show(); - return a.exec(); -} diff --git a/demos/textedit/textedit.cpp b/demos/textedit/textedit.cpp deleted file mode 100644 index c8373262c9..0000000000 --- a/demos/textedit/textedit.cpp +++ /dev/null @@ -1,734 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "textedit.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef Q_WS_MAC -const QString rsrcPath = ":/images/mac"; -#else -const QString rsrcPath = ":/images/win"; -#endif - -TextEdit::TextEdit(QWidget *parent) - : QMainWindow(parent) -{ - setToolButtonStyle(Qt::ToolButtonFollowStyle); - setupFileActions(); - setupEditActions(); - setupTextActions(); - - { - QMenu *helpMenu = new QMenu(tr("Help"), this); - menuBar()->addMenu(helpMenu); - helpMenu->addAction(tr("About"), this, SLOT(about())); - helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt())); - } - - textEdit = new QTextEdit(this); - connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)), - this, SLOT(currentCharFormatChanged(QTextCharFormat))); - connect(textEdit, SIGNAL(cursorPositionChanged()), - this, SLOT(cursorPositionChanged())); - - setCentralWidget(textEdit); - textEdit->setFocus(); - setCurrentFileName(QString()); - - fontChanged(textEdit->font()); - colorChanged(textEdit->textColor()); - alignmentChanged(textEdit->alignment()); - - connect(textEdit->document(), SIGNAL(modificationChanged(bool)), - actionSave, SLOT(setEnabled(bool))); - connect(textEdit->document(), SIGNAL(modificationChanged(bool)), - this, SLOT(setWindowModified(bool))); - connect(textEdit->document(), SIGNAL(undoAvailable(bool)), - actionUndo, SLOT(setEnabled(bool))); - connect(textEdit->document(), SIGNAL(redoAvailable(bool)), - actionRedo, SLOT(setEnabled(bool))); - - setWindowModified(textEdit->document()->isModified()); - actionSave->setEnabled(textEdit->document()->isModified()); - actionUndo->setEnabled(textEdit->document()->isUndoAvailable()); - actionRedo->setEnabled(textEdit->document()->isRedoAvailable()); - - connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo())); - connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo())); - - actionCut->setEnabled(false); - actionCopy->setEnabled(false); - - connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut())); - connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy())); - connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste())); - - connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool))); - connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool))); - -#ifndef QT_NO_CLIPBOARD - connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged())); -#endif - - QString initialFile = ":/example.html"; - const QStringList args = QCoreApplication::arguments(); - if (args.count() == 2) - initialFile = args.at(1); - - if (!load(initialFile)) - fileNew(); -} - -void TextEdit::closeEvent(QCloseEvent *e) -{ - if (maybeSave()) - e->accept(); - else - e->ignore(); -} - -void TextEdit::setupFileActions() -{ - QToolBar *tb = new QToolBar(this); - tb->setWindowTitle(tr("File Actions")); - addToolBar(tb); - - QMenu *menu = new QMenu(tr("&File"), this); - menuBar()->addMenu(menu); - - QAction *a; - - QIcon newIcon = QIcon::fromTheme("document-new", QIcon(rsrcPath + "/filenew.png")); - a = new QAction( newIcon, tr("&New"), this); - a->setPriority(QAction::LowPriority); - a->setShortcut(QKeySequence::New); - connect(a, SIGNAL(triggered()), this, SLOT(fileNew())); - tb->addAction(a); - menu->addAction(a); - - a = new QAction(QIcon::fromTheme("document-open", QIcon(rsrcPath + "/fileopen.png")), - tr("&Open..."), this); - a->setShortcut(QKeySequence::Open); - connect(a, SIGNAL(triggered()), this, SLOT(fileOpen())); - tb->addAction(a); - menu->addAction(a); - - menu->addSeparator(); - - actionSave = a = new QAction(QIcon::fromTheme("document-save", QIcon(rsrcPath + "/filesave.png")), - tr("&Save"), this); - a->setShortcut(QKeySequence::Save); - connect(a, SIGNAL(triggered()), this, SLOT(fileSave())); - a->setEnabled(false); - tb->addAction(a); - menu->addAction(a); - - a = new QAction(tr("Save &As..."), this); - a->setPriority(QAction::LowPriority); - connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs())); - menu->addAction(a); - menu->addSeparator(); - -#ifndef QT_NO_PRINTER - a = new QAction(QIcon::fromTheme("document-print", QIcon(rsrcPath + "/fileprint.png")), - tr("&Print..."), this); - a->setPriority(QAction::LowPriority); - a->setShortcut(QKeySequence::Print); - connect(a, SIGNAL(triggered()), this, SLOT(filePrint())); - tb->addAction(a); - menu->addAction(a); - - a = new QAction(QIcon::fromTheme("fileprint", QIcon(rsrcPath + "/fileprint.png")), - tr("Print Preview..."), this); - connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview())); - menu->addAction(a); - - a = new QAction(QIcon::fromTheme("exportpdf", QIcon(rsrcPath + "/exportpdf.png")), - tr("&Export PDF..."), this); - a->setPriority(QAction::LowPriority); - a->setShortcut(Qt::CTRL + Qt::Key_D); - connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf())); - tb->addAction(a); - menu->addAction(a); - - menu->addSeparator(); -#endif - - a = new QAction(tr("&Quit"), this); - a->setShortcut(Qt::CTRL + Qt::Key_Q); - connect(a, SIGNAL(triggered()), this, SLOT(close())); - menu->addAction(a); -} - -void TextEdit::setupEditActions() -{ - QToolBar *tb = new QToolBar(this); - tb->setWindowTitle(tr("Edit Actions")); - addToolBar(tb); - QMenu *menu = new QMenu(tr("&Edit"), this); - menuBar()->addMenu(menu); - - QAction *a; - a = actionUndo = new QAction(QIcon::fromTheme("edit-undo", QIcon(rsrcPath + "/editundo.png")), - tr("&Undo"), this); - a->setShortcut(QKeySequence::Undo); - tb->addAction(a); - menu->addAction(a); - a = actionRedo = new QAction(QIcon::fromTheme("edit-redo", QIcon(rsrcPath + "/editredo.png")), - tr("&Redo"), this); - a->setPriority(QAction::LowPriority); - a->setShortcut(QKeySequence::Redo); - tb->addAction(a); - menu->addAction(a); - menu->addSeparator(); - a = actionCut = new QAction(QIcon::fromTheme("edit-cut", QIcon(rsrcPath + "/editcut.png")), - tr("Cu&t"), this); - a->setPriority(QAction::LowPriority); - a->setShortcut(QKeySequence::Cut); - tb->addAction(a); - menu->addAction(a); - a = actionCopy = new QAction(QIcon::fromTheme("edit-copy", QIcon(rsrcPath + "/editcopy.png")), - tr("&Copy"), this); - a->setPriority(QAction::LowPriority); - a->setShortcut(QKeySequence::Copy); - tb->addAction(a); - menu->addAction(a); - a = actionPaste = new QAction(QIcon::fromTheme("edit-paste", QIcon(rsrcPath + "/editpaste.png")), - tr("&Paste"), this); - a->setPriority(QAction::LowPriority); - a->setShortcut(QKeySequence::Paste); - tb->addAction(a); - menu->addAction(a); -#ifndef QT_NO_CLIPBOARD - if (const QMimeData *md = QApplication::clipboard()->mimeData()) - actionPaste->setEnabled(md->hasText()); -#endif -} - -void TextEdit::setupTextActions() -{ - QToolBar *tb = new QToolBar(this); - tb->setWindowTitle(tr("Format Actions")); - addToolBar(tb); - - QMenu *menu = new QMenu(tr("F&ormat"), this); - menuBar()->addMenu(menu); - - actionTextBold = new QAction(QIcon::fromTheme("format-text-bold", QIcon(rsrcPath + "/textbold.png")), - tr("&Bold"), this); - actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); - actionTextBold->setPriority(QAction::LowPriority); - QFont bold; - bold.setBold(true); - actionTextBold->setFont(bold); - connect(actionTextBold, SIGNAL(triggered()), this, SLOT(textBold())); - tb->addAction(actionTextBold); - menu->addAction(actionTextBold); - actionTextBold->setCheckable(true); - - actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic", QIcon(rsrcPath + "/textitalic.png")), - tr("&Italic"), this); - actionTextItalic->setPriority(QAction::LowPriority); - actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); - QFont italic; - italic.setItalic(true); - actionTextItalic->setFont(italic); - connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic())); - tb->addAction(actionTextItalic); - menu->addAction(actionTextItalic); - actionTextItalic->setCheckable(true); - - actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline", QIcon(rsrcPath + "/textunder.png")), - tr("&Underline"), this); - actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); - actionTextUnderline->setPriority(QAction::LowPriority); - QFont underline; - underline.setUnderline(true); - actionTextUnderline->setFont(underline); - connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline())); - tb->addAction(actionTextUnderline); - menu->addAction(actionTextUnderline); - actionTextUnderline->setCheckable(true); - - menu->addSeparator(); - - QActionGroup *grp = new QActionGroup(this); - connect(grp, SIGNAL(triggered(QAction*)), this, SLOT(textAlign(QAction*))); - - // Make sure the alignLeft is always left of the alignRight - if (QApplication::isLeftToRight()) { - actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")), - tr("&Left"), grp); - actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp); - actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp); - } else { - actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp); - actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp); - actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")), tr("&Left"), grp); - } - actionAlignJustify = new QAction(QIcon::fromTheme("format-justify-fill", QIcon(rsrcPath + "/textjustify.png")), tr("&Justify"), grp); - - actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); - actionAlignLeft->setCheckable(true); - actionAlignLeft->setPriority(QAction::LowPriority); - actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); - actionAlignCenter->setCheckable(true); - actionAlignCenter->setPriority(QAction::LowPriority); - actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); - actionAlignRight->setCheckable(true); - actionAlignRight->setPriority(QAction::LowPriority); - actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); - actionAlignJustify->setCheckable(true); - actionAlignJustify->setPriority(QAction::LowPriority); - - tb->addActions(grp->actions()); - menu->addActions(grp->actions()); - - menu->addSeparator(); - - QPixmap pix(16, 16); - pix.fill(Qt::black); - actionTextColor = new QAction(pix, tr("&Color..."), this); - connect(actionTextColor, SIGNAL(triggered()), this, SLOT(textColor())); - tb->addAction(actionTextColor); - menu->addAction(actionTextColor); - - - tb = new QToolBar(this); - tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea); - tb->setWindowTitle(tr("Format Actions")); - addToolBarBreak(Qt::TopToolBarArea); - addToolBar(tb); - - comboStyle = new QComboBox(tb); - tb->addWidget(comboStyle); - comboStyle->addItem("Standard"); - comboStyle->addItem("Bullet List (Disc)"); - comboStyle->addItem("Bullet List (Circle)"); - comboStyle->addItem("Bullet List (Square)"); - comboStyle->addItem("Ordered List (Decimal)"); - comboStyle->addItem("Ordered List (Alpha lower)"); - comboStyle->addItem("Ordered List (Alpha upper)"); - comboStyle->addItem("Ordered List (Roman lower)"); - comboStyle->addItem("Ordered List (Roman upper)"); - connect(comboStyle, SIGNAL(activated(int)), - this, SLOT(textStyle(int))); - - comboFont = new QFontComboBox(tb); - tb->addWidget(comboFont); - connect(comboFont, SIGNAL(activated(QString)), - this, SLOT(textFamily(QString))); - - comboSize = new QComboBox(tb); - comboSize->setObjectName("comboSize"); - tb->addWidget(comboSize); - comboSize->setEditable(true); - - QFontDatabase db; - foreach(int size, db.standardSizes()) - comboSize->addItem(QString::number(size)); - - connect(comboSize, SIGNAL(activated(QString)), - this, SLOT(textSize(QString))); - comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font() - .pointSize()))); -} - -bool TextEdit::load(const QString &f) -{ - if (!QFile::exists(f)) - return false; - QFile file(f); - if (!file.open(QFile::ReadOnly)) - return false; - - QByteArray data = file.readAll(); - QTextCodec *codec = Qt::codecForHtml(data); - QString str = codec->toUnicode(data); - if (Qt::mightBeRichText(str)) { - textEdit->setHtml(str); - } else { - str = QString::fromLocal8Bit(data); - textEdit->setPlainText(str); - } - - setCurrentFileName(f); - return true; -} - -bool TextEdit::maybeSave() -{ - if (!textEdit->document()->isModified()) - return true; - if (fileName.startsWith(QLatin1String(":/"))) - return true; - QMessageBox::StandardButton ret; - ret = QMessageBox::warning(this, 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 fileSave(); - else if (ret == QMessageBox::Cancel) - return false; - return true; -} - -void TextEdit::setCurrentFileName(const QString &fileName) -{ - this->fileName = fileName; - textEdit->document()->setModified(false); - - QString shownName; - if (fileName.isEmpty()) - shownName = "untitled.txt"; - else - shownName = QFileInfo(fileName).fileName(); - - setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text"))); - setWindowModified(false); -} - -void TextEdit::fileNew() -{ - if (maybeSave()) { - textEdit->clear(); - setCurrentFileName(QString()); - } -} - -void TextEdit::fileOpen() -{ - QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."), - QString(), tr("HTML-Files (*.htm *.html);;All Files (*)")); - if (!fn.isEmpty()) - load(fn); -} - -bool TextEdit::fileSave() -{ - if (fileName.isEmpty()) - return fileSaveAs(); - - QTextDocumentWriter writer(fileName); - bool success = writer.write(textEdit->document()); - if (success) - textEdit->document()->setModified(false); - return success; -} - -bool TextEdit::fileSaveAs() -{ - QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."), - QString(), tr("ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)")); - if (fn.isEmpty()) - return false; - if (! (fn.endsWith(".odt", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive)) ) - fn += ".odt"; // default - setCurrentFileName(fn); - return fileSave(); -} - -void TextEdit::filePrint() -{ -#ifndef QT_NO_PRINTER - QPrinter printer(QPrinter::HighResolution); - QPrintDialog *dlg = new QPrintDialog(&printer, this); - if (textEdit->textCursor().hasSelection()) - dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); - dlg->setWindowTitle(tr("Print Document")); - if (dlg->exec() == QDialog::Accepted) { - textEdit->print(&printer); - } - delete dlg; -#endif -} - -void TextEdit::filePrintPreview() -{ -#ifndef QT_NO_PRINTER - QPrinter printer(QPrinter::HighResolution); - QPrintPreviewDialog preview(&printer, this); - connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*))); - preview.exec(); -#endif -} - -void TextEdit::printPreview(QPrinter *printer) -{ -#ifdef QT_NO_PRINTER - Q_UNUSED(printer); -#else - textEdit->print(printer); -#endif -} - - -void TextEdit::filePrintPdf() -{ -#ifndef QT_NO_PRINTER -//! [0] - QString fileName = QFileDialog::getSaveFileName(this, "Export PDF", - QString(), "*.pdf"); - if (!fileName.isEmpty()) { - if (QFileInfo(fileName).suffix().isEmpty()) - fileName.append(".pdf"); - QPrinter printer(QPrinter::HighResolution); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setOutputFileName(fileName); - textEdit->document()->print(&printer); - } -//! [0] -#endif -} - -void TextEdit::textBold() -{ - QTextCharFormat fmt; - fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); - mergeFormatOnWordOrSelection(fmt); -} - -void TextEdit::textUnderline() -{ - QTextCharFormat fmt; - fmt.setFontUnderline(actionTextUnderline->isChecked()); - mergeFormatOnWordOrSelection(fmt); -} - -void TextEdit::textItalic() -{ - QTextCharFormat fmt; - fmt.setFontItalic(actionTextItalic->isChecked()); - mergeFormatOnWordOrSelection(fmt); -} - -void TextEdit::textFamily(const QString &f) -{ - QTextCharFormat fmt; - fmt.setFontFamily(f); - mergeFormatOnWordOrSelection(fmt); -} - -void TextEdit::textSize(const QString &p) -{ - qreal pointSize = p.toFloat(); - if (p.toFloat() > 0) { - QTextCharFormat fmt; - fmt.setFontPointSize(pointSize); - mergeFormatOnWordOrSelection(fmt); - } -} - -void TextEdit::textStyle(int styleIndex) -{ - QTextCursor cursor = textEdit->textCursor(); - - if (styleIndex != 0) { - QTextListFormat::Style style = QTextListFormat::ListDisc; - - switch (styleIndex) { - default: - case 1: - style = QTextListFormat::ListDisc; - break; - case 2: - style = QTextListFormat::ListCircle; - break; - case 3: - style = QTextListFormat::ListSquare; - break; - case 4: - style = QTextListFormat::ListDecimal; - break; - case 5: - style = QTextListFormat::ListLowerAlpha; - break; - case 6: - style = QTextListFormat::ListUpperAlpha; - break; - case 7: - style = QTextListFormat::ListLowerRoman; - break; - case 8: - style = QTextListFormat::ListUpperRoman; - break; - } - - cursor.beginEditBlock(); - - QTextBlockFormat blockFmt = cursor.blockFormat(); - - QTextListFormat listFmt; - - if (cursor.currentList()) { - listFmt = cursor.currentList()->format(); - } else { - listFmt.setIndent(blockFmt.indent() + 1); - blockFmt.setIndent(0); - cursor.setBlockFormat(blockFmt); - } - - listFmt.setStyle(style); - - cursor.createList(listFmt); - - cursor.endEditBlock(); - } else { - // #### - QTextBlockFormat bfmt; - bfmt.setObjectIndex(-1); - cursor.mergeBlockFormat(bfmt); - } -} - -void TextEdit::textColor() -{ - QColor col = QColorDialog::getColor(textEdit->textColor(), this); - if (!col.isValid()) - return; - QTextCharFormat fmt; - fmt.setForeground(col); - mergeFormatOnWordOrSelection(fmt); - colorChanged(col); -} - -void TextEdit::textAlign(QAction *a) -{ - if (a == actionAlignLeft) - textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); - else if (a == actionAlignCenter) - textEdit->setAlignment(Qt::AlignHCenter); - else if (a == actionAlignRight) - textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); - else if (a == actionAlignJustify) - textEdit->setAlignment(Qt::AlignJustify); -} - -void TextEdit::currentCharFormatChanged(const QTextCharFormat &format) -{ - fontChanged(format.font()); - colorChanged(format.foreground().color()); -} - -void TextEdit::cursorPositionChanged() -{ - alignmentChanged(textEdit->alignment()); -} - -void TextEdit::clipboardDataChanged() -{ -#ifndef QT_NO_CLIPBOARD - if (const QMimeData *md = QApplication::clipboard()->mimeData()) - actionPaste->setEnabled(md->hasText()); -#endif -} - -void TextEdit::about() -{ - QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's " - "rich text editing facilities in action, providing an example " - "document for you to experiment with.")); -} - -void TextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format) -{ - QTextCursor cursor = textEdit->textCursor(); - if (!cursor.hasSelection()) - cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(format); - textEdit->mergeCurrentCharFormat(format); -} - -void TextEdit::fontChanged(const QFont &f) -{ - comboFont->setCurrentIndex(comboFont->findText(QFontInfo(f).family())); - comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize()))); - actionTextBold->setChecked(f.bold()); - actionTextItalic->setChecked(f.italic()); - actionTextUnderline->setChecked(f.underline()); -} - -void TextEdit::colorChanged(const QColor &c) -{ - QPixmap pix(16, 16); - pix.fill(c); - actionTextColor->setIcon(pix); -} - -void TextEdit::alignmentChanged(Qt::Alignment a) -{ - if (a & Qt::AlignLeft) { - actionAlignLeft->setChecked(true); - } else if (a & Qt::AlignHCenter) { - actionAlignCenter->setChecked(true); - } else if (a & Qt::AlignRight) { - actionAlignRight->setChecked(true); - } else if (a & Qt::AlignJustify) { - actionAlignJustify->setChecked(true); - } -} - diff --git a/demos/textedit/textedit.h b/demos/textedit/textedit.h deleted file mode 100644 index 6436178ab5..0000000000 --- a/demos/textedit/textedit.h +++ /dev/null @@ -1,129 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef TEXTEDIT_H -#define TEXTEDIT_H - -#include -#include -#include - -QT_FORWARD_DECLARE_CLASS(QAction) -QT_FORWARD_DECLARE_CLASS(QComboBox) -QT_FORWARD_DECLARE_CLASS(QFontComboBox) -QT_FORWARD_DECLARE_CLASS(QTextEdit) -QT_FORWARD_DECLARE_CLASS(QTextCharFormat) -QT_FORWARD_DECLARE_CLASS(QMenu) - -class TextEdit : public QMainWindow -{ - Q_OBJECT - -public: - TextEdit(QWidget *parent = 0); - -protected: - virtual void closeEvent(QCloseEvent *e); - -private: - void setupFileActions(); - void setupEditActions(); - void setupTextActions(); - bool load(const QString &f); - bool maybeSave(); - void setCurrentFileName(const QString &fileName); - -private slots: - void fileNew(); - void fileOpen(); - bool fileSave(); - bool fileSaveAs(); - void filePrint(); - void filePrintPreview(); - void filePrintPdf(); - - void textBold(); - void textUnderline(); - void textItalic(); - void textFamily(const QString &f); - void textSize(const QString &p); - void textStyle(int styleIndex); - void textColor(); - void textAlign(QAction *a); - - void currentCharFormatChanged(const QTextCharFormat &format); - void cursorPositionChanged(); - - void clipboardDataChanged(); - void about(); - void printPreview(QPrinter *); - -private: - void mergeFormatOnWordOrSelection(const QTextCharFormat &format); - void fontChanged(const QFont &f); - void colorChanged(const QColor &c); - void alignmentChanged(Qt::Alignment a); - - QAction *actionSave, - *actionTextBold, - *actionTextUnderline, - *actionTextItalic, - *actionTextColor, - *actionAlignLeft, - *actionAlignCenter, - *actionAlignRight, - *actionAlignJustify, - *actionUndo, - *actionRedo, - *actionCut, - *actionCopy, - *actionPaste; - - QComboBox *comboStyle; - QFontComboBox *comboFont; - QComboBox *comboSize; - - QToolBar *tb; - QString fileName; - QTextEdit *textEdit; -}; - -#endif diff --git a/demos/textedit/textedit.pro b/demos/textedit/textedit.pro deleted file mode 100644 index b37ac3036a..0000000000 --- a/demos/textedit/textedit.pro +++ /dev/null @@ -1,22 +0,0 @@ -TEMPLATE = app -TARGET = textedit - -CONFIG += qt warn_on - -HEADERS = textedit.h -SOURCES = textedit.cpp \ - main.cpp - -RESOURCES += textedit.qrc -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/textedit -sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html *.doc images -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/textedit -INSTALLS += target sources - -symbian: CONFIG += qt_demo diff --git a/demos/textedit/textedit.qdoc b/demos/textedit/textedit.qdoc deleted file mode 100644 index 8fc9609407..0000000000 --- a/demos/textedit/textedit.qdoc +++ /dev/null @@ -1,45 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:FDL$ -** GNU Free Documentation License -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms -** and conditions contained in a signed written agreement between you -** and Nokia. -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! \page textedit-example.html - - \ingroup examples - \title Text Edit Example - - This example displays a text editor with the user interface written - in pure C++. - - A similar example which uses \link designer-manual.book Qt - Designer\endlink to produce the user interface is in the \link - designer-manual.book Qt Designer manual\endlink. - - - See \c{$QTDIR/examples/textedit} for the source code. - -*/ - - diff --git a/demos/textedit/textedit.qrc b/demos/textedit/textedit.qrc deleted file mode 100644 index 7d6efd7d67..0000000000 --- a/demos/textedit/textedit.qrc +++ /dev/null @@ -1,44 +0,0 @@ - - - images/logo32.png - images/mac/editcopy.png - images/mac/editcut.png - images/mac/editpaste.png - images/mac/editredo.png - images/mac/editundo.png - images/mac/exportpdf.png - images/mac/filenew.png - images/mac/fileopen.png - images/mac/fileprint.png - images/mac/filesave.png - images/mac/textbold.png - images/mac/textcenter.png - images/mac/textitalic.png - images/mac/textjustify.png - images/mac/textleft.png - images/mac/textright.png - images/mac/textunder.png - images/mac/zoomin.png - images/mac/zoomout.png - images/win/editcopy.png - images/win/editcut.png - images/win/editpaste.png - images/win/editredo.png - images/win/editundo.png - images/win/exportpdf.png - images/win/filenew.png - images/win/fileopen.png - images/win/fileprint.png - images/win/filesave.png - images/win/textbold.png - images/win/textcenter.png - images/win/textitalic.png - images/win/textjustify.png - images/win/textleft.png - images/win/textright.png - images/win/textunder.png - images/win/zoomin.png - images/win/zoomout.png - example.html - - diff --git a/demos/undo/commands.cpp b/demos/undo/commands.cpp deleted file mode 100644 index e688cad602..0000000000 --- a/demos/undo/commands.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "commands.h" - -static const int setShapeRectCommandId = 1; -static const int setShapeColorCommandId = 2; - -/****************************************************************************** -** AddShapeCommand -*/ - -AddShapeCommand::AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent) - : QUndoCommand(parent) -{ - m_doc = doc; - m_shape = shape; -} - -void AddShapeCommand::undo() -{ - m_doc->deleteShape(m_shapeName); -} - -void AddShapeCommand::redo() -{ - // A shape only gets a name when it is inserted into a document - m_shapeName = m_doc->addShape(m_shape); - setText(QObject::tr("Add %1").arg(m_shapeName)); -} - -/****************************************************************************** -** RemoveShapeCommand -*/ - -RemoveShapeCommand::RemoveShapeCommand(Document *doc, const QString &shapeName, - QUndoCommand *parent) - : QUndoCommand(parent) -{ - setText(QObject::tr("Remove %1").arg(shapeName)); - m_doc = doc; - m_shape = doc->shape(shapeName); - m_shapeName = shapeName; -} - -void RemoveShapeCommand::undo() -{ - m_shapeName = m_doc->addShape(m_shape); -} - -void RemoveShapeCommand::redo() -{ - m_doc->deleteShape(m_shapeName); -} - -/****************************************************************************** -** SetShapeColorCommand -*/ - -SetShapeColorCommand::SetShapeColorCommand(Document *doc, const QString &shapeName, - const QColor &color, QUndoCommand *parent) - : QUndoCommand(parent) -{ - setText(QObject::tr("Set %1's color").arg(shapeName)); - - m_doc = doc; - m_shapeName = shapeName; - m_oldColor = doc->shape(shapeName).color(); - m_newColor = color; -} - -void SetShapeColorCommand::undo() -{ - m_doc->setShapeColor(m_shapeName, m_oldColor); -} - -void SetShapeColorCommand::redo() -{ - m_doc->setShapeColor(m_shapeName, m_newColor); -} - -bool SetShapeColorCommand::mergeWith(const QUndoCommand *command) -{ - if (command->id() != setShapeColorCommandId) - return false; - - const SetShapeColorCommand *other = static_cast(command); - if (m_shapeName != other->m_shapeName) - return false; - - m_newColor = other->m_newColor; - return true; -} - -int SetShapeColorCommand::id() const -{ - return setShapeColorCommandId; -} - -/****************************************************************************** -** SetShapeRectCommand -*/ - -SetShapeRectCommand::SetShapeRectCommand(Document *doc, const QString &shapeName, - const QRect &rect, QUndoCommand *parent) - : QUndoCommand(parent) -{ - setText(QObject::tr("Change %1's geometry").arg(shapeName)); - - m_doc = doc; - m_shapeName = shapeName; - m_oldRect = doc->shape(shapeName).rect(); - m_newRect = rect; -} - -void SetShapeRectCommand::undo() -{ - m_doc->setShapeRect(m_shapeName, m_oldRect); -} - -void SetShapeRectCommand::redo() -{ - m_doc->setShapeRect(m_shapeName, m_newRect); -} - -bool SetShapeRectCommand::mergeWith(const QUndoCommand *command) -{ - if (command->id() != setShapeRectCommandId) - return false; - - const SetShapeRectCommand *other = static_cast(command); - if (m_shapeName != other->m_shapeName) - return false; - - m_newRect = other->m_newRect; - return true; -} - -int SetShapeRectCommand::id() const -{ - return setShapeRectCommandId; -} diff --git a/demos/undo/commands.h b/demos/undo/commands.h deleted file mode 100644 index ca7bd2b307..0000000000 --- a/demos/undo/commands.h +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef COMMANDS_H -#define COMMANDS_H - -#include -#include "document.h" - -class AddShapeCommand : public QUndoCommand -{ -public: - AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent = 0); - void undo(); - void redo(); - -private: - Document *m_doc; - Shape m_shape; - QString m_shapeName; -}; - -class RemoveShapeCommand : public QUndoCommand -{ -public: - RemoveShapeCommand(Document *doc, const QString &shapeName, QUndoCommand *parent = 0); - void undo(); - void redo(); - -private: - Document *m_doc; - Shape m_shape; - QString m_shapeName; -}; - -class SetShapeColorCommand : public QUndoCommand -{ -public: - SetShapeColorCommand(Document *doc, const QString &shapeName, const QColor &color, - QUndoCommand *parent = 0); - - void undo(); - void redo(); - - bool mergeWith(const QUndoCommand *command); - int id() const; - -private: - Document *m_doc; - QString m_shapeName; - QColor m_oldColor; - QColor m_newColor; -}; - -class SetShapeRectCommand : public QUndoCommand -{ -public: - SetShapeRectCommand(Document *doc, const QString &shapeName, const QRect &rect, - QUndoCommand *parent = 0); - - void undo(); - void redo(); - - bool mergeWith(const QUndoCommand *command); - int id() const; - -private: - Document *m_doc; - QString m_shapeName; - QRect m_oldRect; - QRect m_newRect; -}; - -#endif // COMMANDS_H diff --git a/demos/undo/document.cpp b/demos/undo/document.cpp deleted file mode 100644 index e143f98061..0000000000 --- a/demos/undo/document.cpp +++ /dev/null @@ -1,445 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include "document.h" -#include "commands.h" - -static const int resizeHandleWidth = 6; - -/****************************************************************************** -** Shape -*/ - -const QSize Shape::minSize(80, 50); - -Shape::Shape(Type type, const QColor &color, const QRect &rect) - : m_type(type), m_rect(rect), m_color(color) -{ -} - -Shape::Type Shape::type() const -{ - return m_type; -} - -QRect Shape::rect() const -{ - return m_rect; -} - -QColor Shape::color() const -{ - return m_color; -} - -QString Shape::name() const -{ - return m_name; -} - -QRect Shape::resizeHandle() const -{ - QPoint br = m_rect.bottomRight(); - return QRect(br - QPoint(resizeHandleWidth, resizeHandleWidth), br); -} - -QString Shape::typeToString(Type type) -{ - QString result; - - switch (type) { - case Rectangle: - result = QLatin1String("Rectangle"); - break; - case Circle: - result = QLatin1String("Circle"); - break; - case Triangle: - result = QLatin1String("Triangle"); - break; - } - - return result; -} - -Shape::Type Shape::stringToType(const QString &s, bool *ok) -{ - if (ok != 0) - *ok = true; - - if (s == QLatin1String("Rectangle")) - return Rectangle; - if (s == QLatin1String("Circle")) - return Circle; - if (s == QLatin1String("Triangle")) - return Triangle; - - if (ok != 0) - *ok = false; - return Rectangle; -} - -/****************************************************************************** -** Document -*/ - -Document::Document(QWidget *parent) - : QWidget(parent), m_currentIndex(-1), m_mousePressIndex(-1), m_resizeHandlePressed(false) -{ - m_undoStack = new QUndoStack(this); - - setAutoFillBackground(true); - setBackgroundRole(QPalette::Base); - - QPalette pal = palette(); - pal.setBrush(QPalette::Base, QPixmap(":/icons/background.png")); - pal.setColor(QPalette::HighlightedText, Qt::red); - setPalette(pal); -} - -QString Document::addShape(const Shape &shape) -{ - QString name = Shape::typeToString(shape.type()); - name = uniqueName(name); - - m_shapeList.append(shape); - m_shapeList[m_shapeList.count() - 1].m_name = name; - setCurrentShape(m_shapeList.count() - 1); - - return name; -} - -void Document::deleteShape(const QString &shapeName) -{ - int index = indexOf(shapeName); - if (index == -1) - return; - - update(m_shapeList.at(index).rect()); - - m_shapeList.removeAt(index); - - if (index <= m_currentIndex) { - m_currentIndex = -1; - if (index == m_shapeList.count()) - --index; - setCurrentShape(index); - } -} - -Shape Document::shape(const QString &shapeName) const -{ - int index = indexOf(shapeName); - if (index == -1) - return Shape(); - return m_shapeList.at(index); -} - -void Document::setShapeRect(const QString &shapeName, const QRect &rect) -{ - int index = indexOf(shapeName); - if (index == -1) - return; - - Shape &shape = m_shapeList[index]; - - update(shape.rect()); - update(rect); - - shape.m_rect = rect; -} - -void Document::setShapeColor(const QString &shapeName, const QColor &color) -{ - - int index = indexOf(shapeName); - if (index == -1) - return; - - Shape &shape = m_shapeList[index]; - shape.m_color = color; - - update(shape.rect()); -} - -QUndoStack *Document::undoStack() const -{ - return m_undoStack; -} - -bool Document::load(QTextStream &stream) -{ - m_shapeList.clear(); - - while (!stream.atEnd()) { - QString shapeType, shapeName, colorName; - int left, top, width, height; - stream >> shapeType >> shapeName >> colorName >> left >> top >> width >> height; - if (stream.status() != QTextStream::Ok) - return false; - bool ok; - Shape::Type type = Shape::stringToType(shapeType, &ok); - if (!ok) - return false; - QColor color(colorName); - if (!color.isValid()) - return false; - - Shape shape(type); - shape.m_name = shapeName; - shape.m_color = color; - shape.m_rect = QRect(left, top, width, height); - - m_shapeList.append(shape); - } - - m_currentIndex = m_shapeList.isEmpty() ? -1 : 0; - - return true; -} - -void Document::save(QTextStream &stream) -{ - for (int i = 0; i < m_shapeList.count(); ++i) { - const Shape &shape = m_shapeList.at(i); - QRect r = shape.rect(); - stream << Shape::typeToString(shape.type()) << QLatin1Char(' ') - << shape.name() << QLatin1Char(' ') - << shape.color().name() << QLatin1Char(' ') - << r.left() << QLatin1Char(' ') - << r.top() << QLatin1Char(' ') - << r.width() << QLatin1Char(' ') - << r.height(); - if (i != m_shapeList.count() - 1) - stream << QLatin1Char('\n'); - } - m_undoStack->setClean(); -} - -QString Document::fileName() const -{ - return m_fileName; -} - -void Document::setFileName(const QString &fileName) -{ - m_fileName = fileName; -} - -int Document::indexAt(const QPoint &pos) const -{ - for (int i = m_shapeList.count() - 1; i >= 0; --i) { - if (m_shapeList.at(i).rect().contains(pos)) - return i; - } - return -1; -} - -void Document::mousePressEvent(QMouseEvent *event) -{ - event->accept(); - int index = indexAt(event->pos());; - if (index != -1) { - setCurrentShape(index); - - const Shape &shape = m_shapeList.at(index); - m_resizeHandlePressed = shape.resizeHandle().contains(event->pos()); - - if (m_resizeHandlePressed) - m_mousePressOffset = shape.rect().bottomRight() - event->pos(); - else - m_mousePressOffset = event->pos() - shape.rect().topLeft(); - } - m_mousePressIndex = index; -} - -void Document::mouseReleaseEvent(QMouseEvent *event) -{ - event->accept(); - m_mousePressIndex = -1; -} - -void Document::mouseMoveEvent(QMouseEvent *event) -{ - event->accept(); - - if (m_mousePressIndex == -1) - return; - - const Shape &shape = m_shapeList.at(m_mousePressIndex); - - QRect rect; - if (m_resizeHandlePressed) { - rect = QRect(shape.rect().topLeft(), event->pos() + m_mousePressOffset); - } else { - rect = shape.rect(); - rect.moveTopLeft(event->pos() - m_mousePressOffset); - } - - QSize size = rect.size().expandedTo(Shape::minSize); - rect.setSize(size); - - m_undoStack->push(new SetShapeRectCommand(this, shape.name(), rect)); -} - -static QGradient gradient(const QColor &color, const QRect &rect) -{ - QColor c = color; - c.setAlpha(160); - QLinearGradient result(rect.topLeft(), rect.bottomRight()); - result.setColorAt(0, c.dark(150)); - result.setColorAt(0.5, c.light(200)); - result.setColorAt(1, c.dark(150)); - return result; -} - -static QPolygon triangle(const QRect &rect) -{ - QPolygon result(3); - result.setPoint(0, rect.center().x(), rect.top()); - result.setPoint(1, rect.right(), rect.bottom()); - result.setPoint(2, rect.left(), rect.bottom()); - return result; -} - -void Document::paintEvent(QPaintEvent *event) -{ - QRegion paintRegion = event->region(); - QPainter painter(this); - QPalette pal = palette(); - - for (int i = 0; i < m_shapeList.count(); ++i) { - const Shape &shape = m_shapeList.at(i); - - if (!paintRegion.contains(shape.rect())) - continue; - - QPen pen = pal.text().color(); - pen.setWidth(i == m_currentIndex ? 2 : 1); - painter.setPen(pen); - painter.setBrush(gradient(shape.color(), shape.rect())); - - QRect rect = shape.rect(); - rect.adjust(1, 1, -resizeHandleWidth/2, -resizeHandleWidth/2); - - // paint the shape - switch (shape.type()) { - case Shape::Rectangle: - painter.drawRect(rect); - break; - case Shape::Circle: - painter.setRenderHint(QPainter::Antialiasing); - painter.drawEllipse(rect); - painter.setRenderHint(QPainter::Antialiasing, false); - break; - case Shape::Triangle: - painter.setRenderHint(QPainter::Antialiasing); - painter.drawPolygon(triangle(rect)); - painter.setRenderHint(QPainter::Antialiasing, false); - break; - } - - // paint the resize handle - painter.setPen(pal.text().color()); - painter.setBrush(Qt::white); - painter.drawRect(shape.resizeHandle().adjusted(0, 0, -1, -1)); - - // paint the shape name - painter.setBrush(pal.text()); - if (shape.type() == Shape::Triangle) - rect.adjust(0, rect.height()/2, 0, 0); - painter.drawText(rect, Qt::AlignCenter, shape.name()); - } -} - -void Document::setCurrentShape(int index) -{ - QString currentName; - - if (m_currentIndex != -1) - update(m_shapeList.at(m_currentIndex).rect()); - - m_currentIndex = index; - - if (m_currentIndex != -1) { - const Shape ¤t = m_shapeList.at(m_currentIndex); - update(current.rect()); - currentName = current.name(); - } - - emit currentShapeChanged(currentName); -} - -int Document::indexOf(const QString &shapeName) const -{ - for (int i = 0; i < m_shapeList.count(); ++i) { - if (m_shapeList.at(i).name() == shapeName) - return i; - } - return -1; -} - -QString Document::uniqueName(const QString &name) const -{ - QString unique; - - for (int i = 0; ; ++i) { - unique = name; - if (i > 0) - unique += QString::number(i); - if (indexOf(unique) == -1) - break; - } - - return unique; -} - -QString Document::currentShapeName() const -{ - if (m_currentIndex == -1) - return QString(); - return m_shapeList.at(m_currentIndex).name(); -} - diff --git a/demos/undo/document.h b/demos/undo/document.h deleted file mode 100644 index b0eda92d41..0000000000 --- a/demos/undo/document.h +++ /dev/null @@ -1,125 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef DOCUMENT_H -#define DOCUMENT_H - -#include - -QT_FORWARD_DECLARE_CLASS(QUndoStack) -QT_FORWARD_DECLARE_CLASS(QTextStream) - -class Shape -{ -public: - enum Type { Rectangle, Circle, Triangle }; - - Shape(Type type = Rectangle, const QColor &color = Qt::red, const QRect &rect = QRect()); - - Type type() const; - QString name() const; - QRect rect() const; - QRect resizeHandle() const; - QColor color() const; - - static QString typeToString(Type type); - static Type stringToType(const QString &s, bool *ok = 0); - - static const QSize minSize; - -private: - Type m_type; - QRect m_rect; - QColor m_color; - QString m_name; - - friend class Document; -}; - -class Document : public QWidget -{ - Q_OBJECT - -public: - Document(QWidget *parent = 0); - - QString addShape(const Shape &shape); - void deleteShape(const QString &shapeName); - Shape shape(const QString &shapeName) const; - QString currentShapeName() const; - - void setShapeRect(const QString &shapeName, const QRect &rect); - void setShapeColor(const QString &shapeName, const QColor &color); - - bool load(QTextStream &stream); - void save(QTextStream &stream); - - QString fileName() const; - void setFileName(const QString &fileName); - - QUndoStack *undoStack() const; - -signals: - void currentShapeChanged(const QString &shapeName); - -protected: - void paintEvent(QPaintEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); - void mouseMoveEvent(QMouseEvent *event); - -private: - void setCurrentShape(int index); - int indexOf(const QString &shapeName) const; - int indexAt(const QPoint &pos) const; - QString uniqueName(const QString &name) const; - - QList m_shapeList; - int m_currentIndex; - int m_mousePressIndex; - QPoint m_mousePressOffset; - bool m_resizeHandlePressed; - QString m_fileName; - - QUndoStack *m_undoStack; -}; - -#endif // DOCUMENT_H diff --git a/demos/undo/icons/background.png b/demos/undo/icons/background.png deleted file mode 100644 index 3bc5ed8cf0..0000000000 Binary files a/demos/undo/icons/background.png and /dev/null differ diff --git a/demos/undo/icons/blue.png b/demos/undo/icons/blue.png deleted file mode 100644 index 4e181bb61a..0000000000 Binary files a/demos/undo/icons/blue.png and /dev/null differ diff --git a/demos/undo/icons/circle.png b/demos/undo/icons/circle.png deleted file mode 100644 index ed16c6e144..0000000000 Binary files a/demos/undo/icons/circle.png and /dev/null differ diff --git a/demos/undo/icons/exit.png b/demos/undo/icons/exit.png deleted file mode 100644 index 539cb2ead9..0000000000 Binary files a/demos/undo/icons/exit.png and /dev/null differ diff --git a/demos/undo/icons/fileclose.png b/demos/undo/icons/fileclose.png deleted file mode 100644 index c5483d14ab..0000000000 Binary files a/demos/undo/icons/fileclose.png and /dev/null differ diff --git a/demos/undo/icons/filenew.png b/demos/undo/icons/filenew.png deleted file mode 100644 index 57e57e343b..0000000000 Binary files a/demos/undo/icons/filenew.png and /dev/null differ diff --git a/demos/undo/icons/fileopen.png b/demos/undo/icons/fileopen.png deleted file mode 100644 index 33e0d6394c..0000000000 Binary files a/demos/undo/icons/fileopen.png and /dev/null differ diff --git a/demos/undo/icons/filesave.png b/demos/undo/icons/filesave.png deleted file mode 100644 index 57fd5e2f34..0000000000 Binary files a/demos/undo/icons/filesave.png and /dev/null differ diff --git a/demos/undo/icons/green.png b/demos/undo/icons/green.png deleted file mode 100644 index e2e7cc9e50..0000000000 Binary files a/demos/undo/icons/green.png and /dev/null differ diff --git a/demos/undo/icons/ok.png b/demos/undo/icons/ok.png deleted file mode 100644 index e355ea91bc..0000000000 Binary files a/demos/undo/icons/ok.png and /dev/null differ diff --git a/demos/undo/icons/rectangle.png b/demos/undo/icons/rectangle.png deleted file mode 100644 index 3a7d9795fd..0000000000 Binary files a/demos/undo/icons/rectangle.png and /dev/null differ diff --git a/demos/undo/icons/red.png b/demos/undo/icons/red.png deleted file mode 100644 index 58c3e7253b..0000000000 Binary files a/demos/undo/icons/red.png and /dev/null differ diff --git a/demos/undo/icons/redo.png b/demos/undo/icons/redo.png deleted file mode 100644 index 5591517e1c..0000000000 Binary files a/demos/undo/icons/redo.png and /dev/null differ diff --git a/demos/undo/icons/remove.png b/demos/undo/icons/remove.png deleted file mode 100644 index 7a7b048c0a..0000000000 Binary files a/demos/undo/icons/remove.png and /dev/null differ diff --git a/demos/undo/icons/triangle.png b/demos/undo/icons/triangle.png deleted file mode 100644 index 2969131c31..0000000000 Binary files a/demos/undo/icons/triangle.png and /dev/null differ diff --git a/demos/undo/icons/undo.png b/demos/undo/icons/undo.png deleted file mode 100644 index 8cf63a8ec9..0000000000 Binary files a/demos/undo/icons/undo.png and /dev/null differ diff --git a/demos/undo/main.cpp b/demos/undo/main.cpp deleted file mode 100644 index a1bb49533a..0000000000 --- a/demos/undo/main.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "mainwindow.h" - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(undo); - - QApplication app(argc, argv); - - MainWindow win; - win.resize(800, 600); - win.show(); - - return app.exec(); -}; diff --git a/demos/undo/mainwindow.cpp b/demos/undo/mainwindow.cpp deleted file mode 100644 index fb16606686..0000000000 --- a/demos/undo/mainwindow.cpp +++ /dev/null @@ -1,446 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include "document.h" -#include "mainwindow.h" -#include "commands.h" - -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent) -{ - setupUi(this); - - QWidget *w = documentTabs->widget(0); - documentTabs->removeTab(0); - delete w; - - connect(actionOpen, SIGNAL(triggered()), this, SLOT(openDocument())); - connect(actionClose, SIGNAL(triggered()), this, SLOT(closeDocument())); - connect(actionNew, SIGNAL(triggered()), this, SLOT(newDocument())); - connect(actionSave, SIGNAL(triggered()), this, SLOT(saveDocument())); - connect(actionExit, SIGNAL(triggered()), this, SLOT(close())); - connect(actionRed, SIGNAL(triggered()), this, SLOT(setShapeColor())); - connect(actionGreen, SIGNAL(triggered()), this, SLOT(setShapeColor())); - connect(actionBlue, SIGNAL(triggered()), this, SLOT(setShapeColor())); - connect(actionAddCircle, SIGNAL(triggered()), this, SLOT(addShape())); - connect(actionAddRectangle, SIGNAL(triggered()), this, SLOT(addShape())); - connect(actionAddTriangle, SIGNAL(triggered()), this, SLOT(addShape())); - connect(actionRemoveShape, SIGNAL(triggered()), this, SLOT(removeShape())); - connect(actionAddRobot, SIGNAL(triggered()), this, SLOT(addRobot())); - connect(actionAddSnowman, SIGNAL(triggered()), this, SLOT(addSnowman())); - connect(actionAbout, SIGNAL(triggered()), this, SLOT(about())); - connect(actionAboutQt, SIGNAL(triggered()), this, SLOT(aboutQt())); - - connect(undoLimit, SIGNAL(valueChanged(int)), this, SLOT(updateActions())); - connect(documentTabs, SIGNAL(currentChanged(int)), this, SLOT(updateActions())); - - actionOpen->setShortcut(QString("Ctrl+O")); - actionClose->setShortcut(QString("Ctrl+W")); - actionNew->setShortcut(QString("Ctrl+N")); - actionSave->setShortcut(QString("Ctrl+S")); - actionExit->setShortcut(QString("Ctrl+Q")); - actionRemoveShape->setShortcut(QString("Del")); - actionRed->setShortcut(QString("Alt+R")); - actionGreen->setShortcut(QString("Alt+G")); - actionBlue->setShortcut(QString("Alt+B")); - actionAddCircle->setShortcut(QString("Alt+C")); - actionAddRectangle->setShortcut(QString("Alt+L")); - actionAddTriangle->setShortcut(QString("Alt+T")); - - m_undoGroup = new QUndoGroup(this); - undoView->setGroup(m_undoGroup); - undoView->setCleanIcon(QIcon(":/icons/ok.png")); - - QAction *undoAction = m_undoGroup->createUndoAction(this); - QAction *redoAction = m_undoGroup->createRedoAction(this); - undoAction->setIcon(QIcon(":/icons/undo.png")); - redoAction->setIcon(QIcon(":/icons/redo.png")); - menuShape->insertAction(menuShape->actions().at(0), undoAction); - menuShape->insertAction(undoAction, redoAction); - - toolBar->addAction(undoAction); - toolBar->addAction(redoAction); - - newDocument(); - updateActions(); -}; - -void MainWindow::updateActions() -{ - Document *doc = currentDocument(); - m_undoGroup->setActiveStack(doc == 0 ? 0 : doc->undoStack()); - QString shapeName = doc == 0 ? QString() : doc->currentShapeName(); - - actionAddRobot->setEnabled(doc != 0); - actionAddSnowman->setEnabled(doc != 0); - actionAddCircle->setEnabled(doc != 0); - actionAddRectangle->setEnabled(doc != 0); - actionAddTriangle->setEnabled(doc != 0); - actionClose->setEnabled(doc != 0); - actionSave->setEnabled(doc != 0 && !doc->undoStack()->isClean()); - undoLimit->setEnabled(doc != 0 && doc->undoStack()->count() == 0); - - if (shapeName.isEmpty()) { - actionRed->setEnabled(false); - actionGreen->setEnabled(false); - actionBlue->setEnabled(false); - actionRemoveShape->setEnabled(false); - } else { - Shape shape = doc->shape(shapeName); - actionRed->setEnabled(shape.color() != Qt::red); - actionGreen->setEnabled(shape.color() != Qt::green); - actionBlue->setEnabled(shape.color() != Qt::blue); - actionRemoveShape->setEnabled(true); - } - - if (doc != 0) { - int index = documentTabs->indexOf(doc); - Q_ASSERT(index != -1); - static const QIcon unsavedIcon(":/icons/filesave.png"); - documentTabs->setTabIcon(index, doc->undoStack()->isClean() ? QIcon() : unsavedIcon); - - if (doc->undoStack()->count() == 0) - doc->undoStack()->setUndoLimit(undoLimit->value()); - } -} - -void MainWindow::openDocument() -{ - QString fileName = QFileDialog::getOpenFileName(this); - if (fileName.isEmpty()) - return; - - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly)) { - QMessageBox::warning(this, - tr("File error"), - tr("Failed to open\n%1").arg(fileName)); - return; - } - QTextStream stream(&file); - - Document *doc = new Document(); - if (!doc->load(stream)) { - QMessageBox::warning(this, - tr("Parse error"), - tr("Failed to parse\n%1").arg(fileName)); - delete doc; - return; - } - - doc->setFileName(fileName); - addDocument(doc); -} - -QString MainWindow::fixedWindowTitle(const Document *doc) const -{ - QString title = doc->fileName(); - - if (title.isEmpty()) - title = tr("Unnamed"); - else - title = QFileInfo(title).fileName(); - - QString result; - - for (int i = 0; ; ++i) { - result = title; - if (i > 0) - result += QString::number(i); - - bool unique = true; - for (int j = 0; j < documentTabs->count(); ++j) { - const QWidget *widget = documentTabs->widget(j); - if (widget == doc) - continue; - if (result == documentTabs->tabText(j)) { - unique = false; - break; - } - } - - if (unique) - break; - } - - return result; -} - -void MainWindow::addDocument(Document *doc) -{ - if (documentTabs->indexOf(doc) != -1) - return; - m_undoGroup->addStack(doc->undoStack()); - documentTabs->addTab(doc, fixedWindowTitle(doc)); - connect(doc, SIGNAL(currentShapeChanged(QString)), this, SLOT(updateActions())); - connect(doc->undoStack(), SIGNAL(indexChanged(int)), this, SLOT(updateActions())); - connect(doc->undoStack(), SIGNAL(cleanChanged(bool)), this, SLOT(updateActions())); - - setCurrentDocument(doc); -} - -void MainWindow::setCurrentDocument(Document *doc) -{ - documentTabs->setCurrentWidget(doc); -} - -Document *MainWindow::currentDocument() const -{ - return qobject_cast(documentTabs->currentWidget()); -} - -void MainWindow::removeDocument(Document *doc) -{ - int index = documentTabs->indexOf(doc); - if (index == -1) - return; - - documentTabs->removeTab(index); - m_undoGroup->removeStack(doc->undoStack()); - disconnect(doc, SIGNAL(currentShapeChanged(QString)), this, SLOT(updateActions())); - disconnect(doc->undoStack(), SIGNAL(indexChanged(int)), this, SLOT(updateActions())); - disconnect(doc->undoStack(), SIGNAL(cleanChanged(bool)), this, SLOT(updateActions())); - - if (documentTabs->count() == 0) { - newDocument(); - updateActions(); - } -} - -void MainWindow::saveDocument() -{ - Document *doc = currentDocument(); - if (doc == 0) - return; - - for (;;) { - QString fileName = doc->fileName(); - - if (fileName.isEmpty()) - fileName = QFileDialog::getSaveFileName(this); - if (fileName.isEmpty()) - break; - - QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::warning(this, - tr("File error"), - tr("Failed to open\n%1").arg(fileName)); - doc->setFileName(QString()); - } else { - QTextStream stream(&file); - doc->save(stream); - doc->setFileName(fileName); - - int index = documentTabs->indexOf(doc); - Q_ASSERT(index != -1); - documentTabs->setTabText(index, fixedWindowTitle(doc)); - - break; - } - } -} - -void MainWindow::closeDocument() -{ - Document *doc = currentDocument(); - if (doc == 0) - return; - - if (!doc->undoStack()->isClean()) { - int button - = QMessageBox::warning(this, - tr("Unsaved changes"), - tr("Would you like to save this document?"), - QMessageBox::Yes, QMessageBox::No); - if (button == QMessageBox::Yes) - saveDocument(); - } - - removeDocument(doc); - delete doc; -} - -void MainWindow::newDocument() -{ - addDocument(new Document()); -} - -static QColor randomColor() -{ - int r = (int) (3.0*(rand()/(RAND_MAX + 1.0))); - switch (r) { - case 0: - return Qt::red; - case 1: - return Qt::green; - default: - break; - } - return Qt::blue; -} - -static QRect randomRect(const QSize &s) -{ - QSize min = Shape::minSize; - - int left = (int) ((0.0 + s.width() - min.width())*(rand()/(RAND_MAX + 1.0))); - int top = (int) ((0.0 + s.height() - min.height())*(rand()/(RAND_MAX + 1.0))); - int width = (int) ((0.0 + s.width() - left - min.width())*(rand()/(RAND_MAX + 1.0))) + min.width(); - int height = (int) ((0.0 + s.height() - top - min.height())*(rand()/(RAND_MAX + 1.0))) + min.height(); - - return QRect(left, top, width, height); -} - -void MainWindow::addShape() -{ - Document *doc = currentDocument(); - if (doc == 0) - return; - - Shape::Type type; - - if (sender() == actionAddCircle) - type = Shape::Circle; - else if (sender() == actionAddRectangle) - type = Shape::Rectangle; - else if (sender() == actionAddTriangle) - type = Shape::Triangle; - else return; - - Shape newShape(type, randomColor(), randomRect(doc->size())); - doc->undoStack()->push(new AddShapeCommand(doc, newShape)); -} - -void MainWindow::removeShape() -{ - Document *doc = currentDocument(); - if (doc == 0) - return; - - QString shapeName = doc->currentShapeName(); - if (shapeName.isEmpty()) - return; - - doc->undoStack()->push(new RemoveShapeCommand(doc, shapeName)); -} - -void MainWindow::setShapeColor() -{ - Document *doc = currentDocument(); - if (doc == 0) - return; - - QString shapeName = doc->currentShapeName(); - if (shapeName.isEmpty()) - return; - - QColor color; - - if (sender() == actionRed) - color = Qt::red; - else if (sender() == actionGreen) - color = Qt::green; - else if (sender() == actionBlue) - color = Qt::blue; - else - return; - - if (color == doc->shape(shapeName).color()) - return; - - doc->undoStack()->push(new SetShapeColorCommand(doc, shapeName, color)); -} - -void MainWindow::addSnowman() -{ - Document *doc = currentDocument(); - if (doc == 0) - return; - - // Create a macro command using beginMacro() and endMacro() - - doc->undoStack()->beginMacro(tr("Add snowman")); - doc->undoStack()->push(new AddShapeCommand(doc, - Shape(Shape::Circle, Qt::blue, QRect(51, 30, 97, 95)))); - doc->undoStack()->push(new AddShapeCommand(doc, - Shape(Shape::Circle, Qt::blue, QRect(27, 123, 150, 133)))); - doc->undoStack()->push(new AddShapeCommand(doc, - Shape(Shape::Circle, Qt::blue, QRect(11, 253, 188, 146)))); - doc->undoStack()->endMacro(); -} - -void MainWindow::addRobot() -{ - Document *doc = currentDocument(); - if (doc == 0) - return; - - // Compose a macro command by explicitly adding children to a parent command - - QUndoCommand *parent = new QUndoCommand(tr("Add robot")); - - new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(115, 15, 81, 70)), parent); - new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(82, 89, 148, 188)), parent); - new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(76, 280, 80, 165)), parent); - new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(163, 280, 80, 164)), parent); - new AddShapeCommand(doc, Shape(Shape::Circle, Qt::blue, QRect(116, 25, 80, 50)), parent); - new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(232, 92, 80, 127)), parent); - new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(2, 92, 80, 125)), parent); - - doc->undoStack()->push(parent); -} - -void MainWindow::about() -{ - QMessageBox::about(this, tr("About Undo"), tr("The Undo demonstration shows how to use the Qt Undo framework.")); -} - -void MainWindow::aboutQt() -{ - QMessageBox::aboutQt(this, tr("About Qt")); -} diff --git a/demos/undo/mainwindow.h b/demos/undo/mainwindow.h deleted file mode 100644 index 4500c6d68d..0000000000 --- a/demos/undo/mainwindow.h +++ /dev/null @@ -1,87 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include -#include "ui_mainwindow.h" - -class Document; - -class MainWindow : public QMainWindow, public Ui::MainWindow -{ - Q_OBJECT - -public: - MainWindow(QWidget *parent = 0); - - void addDocument(Document *doc); - void removeDocument(Document *doc); - void setCurrentDocument(Document *doc); - Document *currentDocument() const; - -public slots: - void openDocument(); - void saveDocument(); - void closeDocument(); - void newDocument(); - - void addShape(); - void removeShape(); - void setShapeColor(); - - void addSnowman(); - void addRobot(); - - void about(); - void aboutQt(); - -private slots: - void updateActions(); - -private: - QUndoGroup *m_undoGroup; - - QString fixedWindowTitle(const Document *doc) const; -}; - -#endif // MAINWINDOW_H diff --git a/demos/undo/mainwindow.ui b/demos/undo/mainwindow.ui deleted file mode 100644 index 91a0b437e5..0000000000 --- a/demos/undo/mainwindow.ui +++ /dev/null @@ -1,322 +0,0 @@ - - MainWindow - - - - 0 - 0 - 567 - 600 - - - - - 32 - 32 - - - - - - 0 - - - 0 - - - - - 0 - - - - Tab 1 - - - - - - - - - - 0 - 0 - 567 - 27 - - - - - File - - - - - - - - - - - Edit - - - - Macros - - - - - - - - - - - - - - - - - - - Help - - - - - - - - - - - - File actions - - - Qt::Horizontal - - - TopToolBarArea - - - false - - - - - - - - - - Shape actions - - - Qt::Vertical - - - LeftToolBarArea - - - false - - - - - - - - - - - - - Undo Stack - - - 2 - - - - - 0 - - - 4 - - - - - 0 - - - 6 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Undo limit - - - - - - - - - - - - false - - - - - - - - - :/icons/fileopen.png - - - &Open - - - - - :/icons/fileclose.png - - - &Close - - - - - :/icons/filenew.png - - - &New - - - - - :/icons/filesave.png - - - &Save - - - - - :/icons/exit.png - - - E&xit - - - - - :/icons/red.png - - - Red - - - - - :/icons/green.png - - - Green - - - - - :/icons/blue.png - - - Blue - - - - - :/icons/rectangle.png - - - Add Rectangle - - - - - :/icons/circle.png - - - Add Circle - - - - - :/icons/remove.png - - - Remove Shape - - - - - Add robot - - - - - Add snowan - - - - - :/icons/triangle.png - - - addTriangle - - - - - About - - - - - About Qt - - - - - - QUndoView - QListView -
    qundoview.h
    -
    -
    - - - - -
    diff --git a/demos/undo/undo.pro b/demos/undo/undo.pro deleted file mode 100644 index 84f1d7b326..0000000000 --- a/demos/undo/undo.pro +++ /dev/null @@ -1,18 +0,0 @@ -SOURCES += main.cpp mainwindow.cpp commands.cpp document.cpp -HEADERS += mainwindow.h commands.h document.h -FORMS += mainwindow.ui - -build_all:!build_pass { - CONFIG -= build_all - CONFIG += release -} - -RESOURCES += undo.qrc - -# install -target.path = $$[QT_INSTALL_DEMOS]/qtbase/undo -sources.files = $$SOURCES $$HEADERS *.pro icons $$RESOURCES $$FORMS -sources.path = $$[QT_INSTALL_DEMOS]/qtbase/undo -INSTALLS += target sources - -symbian: CONFIG += qt_demo diff --git a/demos/undo/undo.qrc b/demos/undo/undo.qrc deleted file mode 100644 index 65619b8f1a..0000000000 --- a/demos/undo/undo.qrc +++ /dev/null @@ -1,20 +0,0 @@ - - - icons/background.png - icons/blue.png - icons/circle.png - icons/exit.png - icons/fileclose.png - icons/filenew.png - icons/fileopen.png - icons/filesave.png - icons/green.png - icons/ok.png - icons/rectangle.png - icons/red.png - icons/redo.png - icons/remove.png - icons/triangle.png - icons/undo.png - - diff --git a/examples/animation/sub-attaq/animationmanager.cpp b/examples/animation/sub-attaq/animationmanager.cpp new file mode 100644 index 0000000000..c7e230e3d2 --- /dev/null +++ b/examples/animation/sub-attaq/animationmanager.cpp @@ -0,0 +1,98 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "animationmanager.h" + +//Qt +#include +#include + +// the universe's only animation manager +AnimationManager *AnimationManager::instance = 0; + +AnimationManager::AnimationManager() +{ +} + +AnimationManager *AnimationManager::self() +{ + if (!instance) + instance = new AnimationManager; + return instance; +} + +void AnimationManager::registerAnimation(QAbstractAnimation *anim) +{ + QObject::connect(anim, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterAnimation_helper(QObject*))); + animations.append(anim); +} + +void AnimationManager::unregisterAnimation_helper(QObject *obj) +{ + unregisterAnimation(static_cast(obj)); +} + +void AnimationManager::unregisterAnimation(QAbstractAnimation *anim) +{ + QObject::disconnect(anim, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterAnimation_helper(QObject*))); + animations.removeAll(anim); +} + +void AnimationManager::unregisterAllAnimations() +{ + animations.clear(); +} + +void AnimationManager::pauseAll() +{ + foreach (QAbstractAnimation* animation, animations) { + if (animation->state() == QAbstractAnimation::Running) + animation->pause(); + } +} +void AnimationManager::resumeAll() +{ + foreach (QAbstractAnimation* animation, animations) { + if (animation->state() == QAbstractAnimation::Paused) + animation->resume(); + } +} diff --git a/examples/animation/sub-attaq/animationmanager.h b/examples/animation/sub-attaq/animationmanager.h new file mode 100644 index 0000000000..429d656485 --- /dev/null +++ b/examples/animation/sub-attaq/animationmanager.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ANIMATIONMANAGER_H +#define ANIMATIONMANAGER_H + +#include + +QT_BEGIN_NAMESPACE +class QAbstractAnimation; +QT_END_NAMESPACE + +class AnimationManager : public QObject +{ +Q_OBJECT +public: + AnimationManager(); + void registerAnimation(QAbstractAnimation *anim); + void unregisterAnimation(QAbstractAnimation *anim); + void unregisterAllAnimations(); + static AnimationManager *self(); + +public slots: + void pauseAll(); + void resumeAll(); + +private slots: + void unregisterAnimation_helper(QObject *obj); + +private: + static AnimationManager *instance; + QList animations; +}; + +#endif // ANIMATIONMANAGER_H diff --git a/examples/animation/sub-attaq/boat.cpp b/examples/animation/sub-attaq/boat.cpp new file mode 100644 index 0000000000..4ddf59e6a0 --- /dev/null +++ b/examples/animation/sub-attaq/boat.cpp @@ -0,0 +1,272 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "boat.h" +#include "boat_p.h" +#include "bomb.h" +#include "pixmapitem.h" +#include "graphicsscene.h" +#include "animationmanager.h" +#include "qanimationstate.h" + +//Qt +#include +#include +#include +#include +#include +#include + +static QAbstractAnimation *setupDestroyAnimation(Boat *boat) +{ + QSequentialAnimationGroup *group = new QSequentialAnimationGroup(boat); + for (int i = 1; i <= 4; i++) { + PixmapItem *step = new PixmapItem(QString("explosion/boat/step%1").arg(i),GraphicsScene::Big, boat); + step->setZValue(6); + step->setOpacity(0); + + //fade-in + QPropertyAnimation *anim = new QPropertyAnimation(step, "opacity"); + anim->setEndValue(1); + anim->setDuration(100); + group->insertAnimation(i-1, anim); + + //and then fade-out + QPropertyAnimation *anim2 = new QPropertyAnimation(step, "opacity"); + anim2->setEndValue(0); + anim2->setDuration(100); + group->addAnimation(anim2); + } + + AnimationManager::self()->registerAnimation(group); + return group; +} + + + +Boat::Boat() : PixmapItem(QString("boat"), GraphicsScene::Big), + speed(0), bombsAlreadyLaunched(0), direction(Boat::None), movementAnimation(0) +{ + setZValue(4); + setFlags(QGraphicsItem::ItemIsFocusable); + + //The movement animation used to animate the boat + movementAnimation = new QPropertyAnimation(this, "pos"); + + //The destroy animation used to explode the boat + destroyAnimation = setupDestroyAnimation(this); + + //We setup the state machine of the boat + machine = new QStateMachine(this); + QState *moving = new QState(machine); + StopState *stopState = new StopState(this, moving); + machine->setInitialState(moving); + moving->setInitialState(stopState); + MoveStateRight *moveStateRight = new MoveStateRight(this, moving); + MoveStateLeft *moveStateLeft = new MoveStateLeft(this, moving); + LaunchStateRight *launchStateRight = new LaunchStateRight(this, machine); + LaunchStateLeft *launchStateLeft = new LaunchStateLeft(this, machine); + + //then setup the transitions for the rightMove state + KeyStopTransition *leftStopRight = new KeyStopTransition(this, QEvent::KeyPress, Qt::Key_Left); + leftStopRight->setTargetState(stopState); + KeyMoveTransition *leftMoveRight = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Left); + leftMoveRight->setTargetState(moveStateRight); + KeyMoveTransition *rightMoveRight = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); + rightMoveRight->setTargetState(moveStateRight); + KeyMoveTransition *rightMoveStop = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); + rightMoveStop->setTargetState(moveStateRight); + + //then setup the transitions for the leftMove state + KeyStopTransition *rightStopLeft = new KeyStopTransition(this, QEvent::KeyPress, Qt::Key_Right); + rightStopLeft->setTargetState(stopState); + KeyMoveTransition *rightMoveLeft = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); + rightMoveLeft->setTargetState(moveStateLeft); + KeyMoveTransition *leftMoveLeft = new KeyMoveTransition(this, QEvent::KeyPress,Qt::Key_Left); + leftMoveLeft->setTargetState(moveStateLeft); + KeyMoveTransition *leftMoveStop = new KeyMoveTransition(this, QEvent::KeyPress,Qt::Key_Left); + leftMoveStop->setTargetState(moveStateLeft); + + //We set up the right move state + moveStateRight->addTransition(leftStopRight); + moveStateRight->addTransition(leftMoveRight); + moveStateRight->addTransition(rightMoveRight); + stopState->addTransition(rightMoveStop); + + //We set up the left move state + moveStateLeft->addTransition(rightStopLeft); + moveStateLeft->addTransition(leftMoveLeft); + moveStateLeft->addTransition(rightMoveLeft); + stopState->addTransition(leftMoveStop); + + //The animation is finished, it means we reached the border of the screen, the boat is stopped so we move to the stop state + moveStateLeft->addTransition(movementAnimation, SIGNAL(finished()), stopState); + moveStateRight->addTransition(movementAnimation, SIGNAL(finished()), stopState); + + //We set up the keys for dropping bombs + KeyLaunchTransition *upFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); + upFireLeft->setTargetState(launchStateRight); + KeyLaunchTransition *upFireRight = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); + upFireRight->setTargetState(launchStateRight); + KeyLaunchTransition *upFireStop = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); + upFireStop->setTargetState(launchStateRight); + KeyLaunchTransition *downFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); + downFireLeft->setTargetState(launchStateLeft); + KeyLaunchTransition *downFireRight = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); + downFireRight->setTargetState(launchStateLeft); + KeyLaunchTransition *downFireMove = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); + downFireMove->setTargetState(launchStateLeft); + + //We set up transitions for fire up + moveStateRight->addTransition(upFireRight); + moveStateLeft->addTransition(upFireLeft); + stopState->addTransition(upFireStop); + + //We set up transitions for fire down + moveStateRight->addTransition(downFireRight); + moveStateLeft->addTransition(downFireLeft); + stopState->addTransition(downFireMove); + + //Finally the launch state should come back to its original state + QHistoryState *historyState = new QHistoryState(moving); + launchStateLeft->addTransition(historyState); + launchStateRight->addTransition(historyState); + + QFinalState *final = new QFinalState(machine); + + //This state play the destroyed animation + QAnimationState *destroyedState = new QAnimationState(machine); + destroyedState->setAnimation(destroyAnimation); + + //Play a nice animation when the boat is destroyed + moving->addTransition(this, SIGNAL(boatDestroyed()), destroyedState); + + //Transition to final state when the destroyed animation is finished + destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); + + //The machine has finished to be executed, then the boat is dead + connect(machine,SIGNAL(finished()), this, SIGNAL(boatExecutionFinished())); + +} + +void Boat::run() +{ + //We register animations + AnimationManager::self()->registerAnimation(movementAnimation); + AnimationManager::self()->registerAnimation(destroyAnimation); + machine->start(); +} + +void Boat::stop() +{ + movementAnimation->stop(); + machine->stop(); +} + +void Boat::updateBoatMovement() +{ + if (speed == 0 || direction == Boat::None) { + movementAnimation->stop(); + return; + } + + movementAnimation->stop(); + + if (direction == Boat::Left) { + movementAnimation->setEndValue(QPointF(0,y())); + movementAnimation->setDuration(x()/speed*15); + } + else /*if (direction == Boat::Right)*/ { + movementAnimation->setEndValue(QPointF(scene()->width()-size().width(),y())); + movementAnimation->setDuration((scene()->width()-size().width()-x())/speed*15); + } + movementAnimation->start(); +} + +void Boat::destroy() +{ + movementAnimation->stop(); + emit boatDestroyed(); +} + +int Boat::bombsLaunched() const +{ + return bombsAlreadyLaunched; +} + +void Boat::setBombsLaunched(int number) +{ + if (number > MAX_BOMB) { + qWarning("Boat::setBombsLaunched : It impossible to launch that number of bombs"); + return; + } + bombsAlreadyLaunched = number; +} + +int Boat::currentSpeed() const +{ + return speed; +} + +void Boat::setCurrentSpeed(int speed) +{ + if (speed > 3 || speed < 0) { + qWarning("Boat::setCurrentSpeed: The boat can't run on that speed"); + return; + } + this->speed = speed; +} + +enum Boat::Movement Boat::currentDirection() const +{ + return direction; +} + +void Boat::setCurrentDirection(Movement direction) +{ + this->direction = direction; +} + +int Boat::type() const +{ + return Type; +} diff --git a/examples/animation/sub-attaq/boat.h b/examples/animation/sub-attaq/boat.h new file mode 100644 index 0000000000..71e3512fc3 --- /dev/null +++ b/examples/animation/sub-attaq/boat.h @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __BOAT__H__ +#define __BOAT__H__ + +#include "pixmapitem.h" + +class Bomb; +QT_BEGIN_NAMESPACE +class QVariantAnimation; +class QAbstractAnimation; +class QStateMachine; +QT_END_NAMESPACE + +class Boat : public PixmapItem +{ +Q_OBJECT +public: + enum Movement { + None = 0, + Left, + Right + }; + enum { Type = UserType + 2 }; + Boat(); + void destroy(); + void run(); + void stop(); + + int bombsLaunched() const; + void setBombsLaunched(int number); + + int currentSpeed() const; + void setCurrentSpeed(int speed); + + enum Movement currentDirection() const; + void setCurrentDirection(Movement direction); + + void updateBoatMovement(); + + virtual int type() const; + +signals: + void boatDestroyed(); + void boatExecutionFinished(); + +private: + int speed; + int bombsAlreadyLaunched; + Movement direction; + QVariantAnimation *movementAnimation; + QAbstractAnimation *destroyAnimation; + QStateMachine *machine; +}; + +#endif //__BOAT__H__ diff --git a/examples/animation/sub-attaq/boat_p.h b/examples/animation/sub-attaq/boat_p.h new file mode 100644 index 0000000000..9022a4ca51 --- /dev/null +++ b/examples/animation/sub-attaq/boat_p.h @@ -0,0 +1,232 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef BOAT_P_H +#define BOAT_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +//Own +#include "bomb.h" +#include "graphicsscene.h" + +// Qt +#include + +static const int MAX_BOMB = 5; + + +//These transtion test if we have to stop the boat (i.e current speed is 1) +class KeyStopTransition : public QKeyEventTransition +{ +public: + KeyStopTransition(Boat *b, QEvent::Type t, int k) + : QKeyEventTransition(b, t, k), boat(b), key(k) + { + } +protected: + virtual bool eventTest(QEvent *event) + { + if (!QKeyEventTransition::eventTest(event)) + return false; + return (boat->currentSpeed() == 1); + } +private: + Boat * boat; + int key; +}; + +//These transtion test if we have to move the boat (i.e current speed was 0 or another value) + class KeyMoveTransition : public QKeyEventTransition +{ +public: + KeyMoveTransition(Boat *b, QEvent::Type t, int k) + : QKeyEventTransition(b, t, k), boat(b), key(k) + { + } +protected: + virtual bool eventTest(QEvent *event) + { + if (!QKeyEventTransition::eventTest(event)) + return false; + return (boat->currentSpeed() >= 0); + } + void onTransition(QEvent *) + { + //We decrease the speed if needed + if (key == Qt::Key_Left && boat->currentDirection() == Boat::Right) + boat->setCurrentSpeed(boat->currentSpeed() - 1); + else if (key == Qt::Key_Right && boat->currentDirection() == Boat::Left) + boat->setCurrentSpeed(boat->currentSpeed() - 1); + else if (boat->currentSpeed() < 3) + boat->setCurrentSpeed(boat->currentSpeed() + 1); + boat->updateBoatMovement(); + } +private: + Boat * boat; + int key; +}; + +//This transition trigger the bombs launch + class KeyLaunchTransition : public QKeyEventTransition +{ +public: + KeyLaunchTransition(Boat *boat, QEvent::Type type, int key) + : QKeyEventTransition(boat, type, key), boat(boat), key(key) + { + } +protected: + virtual bool eventTest(QEvent *event) + { + if (!QKeyEventTransition::eventTest(event)) + return false; + //We have enough bomb? + return (boat->bombsLaunched() < MAX_BOMB); + } +private: + Boat * boat; + int key; +}; + +//This state is describing when the boat is moving right +class MoveStateRight : public QState +{ +public: + MoveStateRight(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + { + } +protected: + void onEntry(QEvent *) + { + boat->setCurrentDirection(Boat::Right); + boat->updateBoatMovement(); + } +private: + Boat * boat; +}; + + //This state is describing when the boat is moving left +class MoveStateLeft : public QState +{ +public: + MoveStateLeft(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + { + } +protected: + void onEntry(QEvent *) + { + boat->setCurrentDirection(Boat::Left); + boat->updateBoatMovement(); + } +private: + Boat * boat; +}; + +//This state is describing when the boat is in a stand by position +class StopState : public QState +{ +public: + StopState(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + { + } +protected: + void onEntry(QEvent *) + { + boat->setCurrentSpeed(0); + boat->setCurrentDirection(Boat::None); + boat->updateBoatMovement(); + } +private: + Boat * boat; +}; + +//This state is describing the launch of the torpedo on the right +class LaunchStateRight : public QState +{ +public: + LaunchStateRight(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + { + } +protected: + void onEntry(QEvent *) + { + Bomb *b = new Bomb(); + b->setPos(boat->x()+boat->size().width(),boat->y()); + GraphicsScene *scene = static_cast(boat->scene()); + scene->addItem(b); + b->launch(Bomb::Right); + boat->setBombsLaunched(boat->bombsLaunched() + 1); + } +private: + Boat * boat; +}; + +//This state is describing the launch of the torpedo on the left +class LaunchStateLeft : public QState +{ +public: + LaunchStateLeft(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + { + } +protected: + void onEntry(QEvent *) + { + Bomb *b = new Bomb(); + b->setPos(boat->x() - b->size().width(), boat->y()); + GraphicsScene *scene = static_cast(boat->scene()); + scene->addItem(b); + b->launch(Bomb::Left); + boat->setBombsLaunched(boat->bombsLaunched() + 1); + } +private: + Boat * boat; +}; + +#endif // BOAT_P_H diff --git a/examples/animation/sub-attaq/bomb.cpp b/examples/animation/sub-attaq/bomb.cpp new file mode 100644 index 0000000000..6811a27e88 --- /dev/null +++ b/examples/animation/sub-attaq/bomb.cpp @@ -0,0 +1,118 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "bomb.h" +#include "submarine.h" +#include "pixmapitem.h" +#include "animationmanager.h" +#include "qanimationstate.h" + +//Qt +#include +#include +#include +#include + +Bomb::Bomb() : PixmapItem(QString("bomb"), GraphicsScene::Big) +{ + setZValue(2); +} + +void Bomb::launch(Bomb::Direction direction) +{ + QSequentialAnimationGroup *launchAnimation = new QSequentialAnimationGroup; + AnimationManager::self()->registerAnimation(launchAnimation); + qreal delta = direction == Right ? 20 : - 20; + QPropertyAnimation *anim = new QPropertyAnimation(this, "pos"); + anim->setEndValue(QPointF(x() + delta,y() - 20)); + anim->setDuration(150); + launchAnimation->addAnimation(anim); + anim = new QPropertyAnimation(this, "pos"); + anim->setEndValue(QPointF(x() + delta*2, y() )); + anim->setDuration(150); + launchAnimation->addAnimation(anim); + anim = new QPropertyAnimation(this, "pos"); + anim->setEndValue(QPointF(x() + delta*2,scene()->height())); + anim->setDuration(y()/2*60); + launchAnimation->addAnimation(anim); + connect(anim,SIGNAL(valueChanged(QVariant)),this,SLOT(onAnimationLaunchValueChanged(QVariant))); + connect(this, SIGNAL(bombExploded()), launchAnimation, SLOT(stop())); + //We setup the state machine of the bomb + QStateMachine *machine = new QStateMachine(this); + + //This state is when the launch animation is playing + QAnimationState *launched = new QAnimationState(machine); + launched->setAnimation(launchAnimation); + + //End + QFinalState *final = new QFinalState(machine); + + machine->setInitialState(launched); + + //### Add a nice animation when the bomb is destroyed + launched->addTransition(this, SIGNAL(bombExploded()),final); + + //If the animation is finished, then we move to the final state + launched->addTransition(launched, SIGNAL(animationFinished()), final); + + //The machine has finished to be executed, then the boat is dead + connect(machine,SIGNAL(finished()),this, SIGNAL(bombExecutionFinished())); + + machine->start(); + +} + +void Bomb::onAnimationLaunchValueChanged(const QVariant &) +{ + foreach (QGraphicsItem * item , collidingItems(Qt::IntersectsItemBoundingRect)) { + if (item->type() == SubMarine::Type) { + SubMarine *s = static_cast(item); + destroy(); + s->destroy(); + } + } +} + +void Bomb::destroy() +{ + emit bombExploded(); +} diff --git a/examples/animation/sub-attaq/bomb.h b/examples/animation/sub-attaq/bomb.h new file mode 100644 index 0000000000..222c3d029f --- /dev/null +++ b/examples/animation/sub-attaq/bomb.h @@ -0,0 +1,67 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __BOMB__H__ +#define __BOMB__H__ + +#include "pixmapitem.h" + +class Bomb : public PixmapItem +{ +Q_OBJECT +public: + enum Direction { + Left = 0, + Right + }; + Bomb(); + void launch(Direction direction); + void destroy(); + +signals: + void bombExploded(); + void bombExecutionFinished(); + +private slots: + void onAnimationLaunchValueChanged(const QVariant &); +}; + +#endif //__BOMB__H__ diff --git a/examples/animation/sub-attaq/data.xml b/examples/animation/sub-attaq/data.xml new file mode 100644 index 0000000000..0f30515ddf --- /dev/null +++ b/examples/animation/sub-attaq/data.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/graphicsscene.cpp b/examples/animation/sub-attaq/graphicsscene.cpp new file mode 100644 index 0000000000..f82d441068 --- /dev/null +++ b/examples/animation/sub-attaq/graphicsscene.cpp @@ -0,0 +1,282 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "graphicsscene.h" +#include "states.h" +#include "boat.h" +#include "submarine.h" +#include "torpedo.h" +#include "bomb.h" +#include "pixmapitem.h" +#include "animationmanager.h" +#include "qanimationstate.h" +#include "progressitem.h" +#include "textinformationitem.h" + +//Qt +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +GraphicsScene::GraphicsScene(int x, int y, int width, int height, Mode mode) + : QGraphicsScene(x , y, width, height), mode(mode), boat(new Boat) +{ + PixmapItem *backgroundItem = new PixmapItem(QString("background"),mode); + backgroundItem->setZValue(1); + backgroundItem->setPos(0,0); + addItem(backgroundItem); + + PixmapItem *surfaceItem = new PixmapItem(QString("surface"),mode); + surfaceItem->setZValue(3); + surfaceItem->setPos(0,sealLevel() - surfaceItem->boundingRect().height()/2); + addItem(surfaceItem); + + //The item that display score and level + progressItem = new ProgressItem(backgroundItem); + + textInformationItem = new TextInformationItem(backgroundItem); + textInformationItem->hide(); + //We create the boat + addItem(boat); + boat->setPos(this->width()/2, sealLevel() - boat->size().height()); + boat->hide(); + + //parse the xml that contain all data of the game + QXmlStreamReader reader; + QFile file(":data.xml"); + file.open(QIODevice::ReadOnly); + reader.setDevice(&file); + LevelDescription currentLevel; + while (!reader.atEnd()) { + reader.readNext(); + if (reader.tokenType() == QXmlStreamReader::StartElement) { + if (reader.name() == "submarine") { + SubmarineDescription desc; + desc.name = reader.attributes().value("name").toString(); + desc.points = reader.attributes().value("points").toString().toInt(); + desc.type = reader.attributes().value("type").toString().toInt(); + submarinesData.append(desc); + } else if (reader.name() == "level") { + currentLevel.id = reader.attributes().value("id").toString().toInt(); + currentLevel.name = reader.attributes().value("name").toString(); + } else if (reader.name() == "subinstance") { + currentLevel.submarines.append(qMakePair(reader.attributes().value("type").toString().toInt(), reader.attributes().value("nb").toString().toInt())); + } + } else if (reader.tokenType() == QXmlStreamReader::EndElement) { + if (reader.name() == "level") { + levelsData.insert(currentLevel.id, currentLevel); + currentLevel.submarines.clear(); + } + } + } +} + +qreal GraphicsScene::sealLevel() const +{ + return (mode == Big) ? 220 : 160; +} + +void GraphicsScene::setupScene(QAction *newAction, QAction *quitAction) +{ + static const int nLetters = 10; + static struct { + char const *pix; + qreal initX, initY; + qreal destX, destY; + } logoData[nLetters] = { + {"s", -1000, -1000, 300, 150 }, + {"u", -800, -1000, 350, 150 }, + {"b", -600, -1000, 400, 120 }, + {"dash", -400, -1000, 460, 150 }, + {"a", 1000, 2000, 350, 250 }, + {"t", 800, 2000, 400, 250 }, + {"t2", 600, 2000, 430, 250 }, + {"a2", 400, 2000, 465, 250 }, + {"q", 200, 2000, 510, 250 }, + {"excl", 0, 2000, 570, 220 } }; + + QSequentialAnimationGroup * lettersGroupMoving = new QSequentialAnimationGroup(this); + QParallelAnimationGroup * lettersGroupFading = new QParallelAnimationGroup(this); + + for (int i = 0; i < nLetters; ++i) { + PixmapItem *logo = new PixmapItem(QLatin1String(":/logo-") + logoData[i].pix, this); + logo->setPos(logoData[i].initX, logoData[i].initY); + logo->setZValue(i + 3); + //creation of the animations for moving letters + QPropertyAnimation *moveAnim = new QPropertyAnimation(logo, "pos", lettersGroupMoving); + moveAnim->setEndValue(QPointF(logoData[i].destX, logoData[i].destY)); + moveAnim->setDuration(200); + moveAnim->setEasingCurve(QEasingCurve::OutElastic); + lettersGroupMoving->addPause(50); + //creation of the animations for fading out the letters + QPropertyAnimation *fadeAnim = new QPropertyAnimation(logo, "opacity", lettersGroupFading); + fadeAnim->setDuration(800); + fadeAnim->setEndValue(0); + fadeAnim->setEasingCurve(QEasingCurve::OutQuad); + } + + QStateMachine *machine = new QStateMachine(this); + + //This state is when the player is playing + PlayState *gameState = new PlayState(this, machine); + + //Final state + QFinalState *final = new QFinalState(machine); + + //Animation when the player enter in the game + QAnimationState *lettersMovingState = new QAnimationState(machine); + lettersMovingState->setAnimation(lettersGroupMoving); + + //Animation when the welcome screen disappear + QAnimationState *lettersFadingState = new QAnimationState(machine); + lettersFadingState->setAnimation(lettersGroupFading); + + //if new game then we fade out the welcome screen and start playing + lettersMovingState->addTransition(newAction, SIGNAL(triggered()), lettersFadingState); + lettersFadingState->addTransition(lettersFadingState, SIGNAL(animationFinished()), gameState); + + //New Game is triggered then player start playing + gameState->addTransition(newAction, SIGNAL(triggered()), gameState); + + //Wanna quit, then connect to CTRL+Q + gameState->addTransition(quitAction, SIGNAL(triggered()), final); + lettersMovingState->addTransition(quitAction, SIGNAL(triggered()), final); + + //Welcome screen is the initial state + machine->setInitialState(lettersMovingState); + + machine->start(); + + //We reach the final state, then we quit + connect(machine, SIGNAL(finished()), qApp, SLOT(quit())); +} + +void GraphicsScene::addItem(Bomb *bomb) +{ + bombs.insert(bomb); + connect(bomb,SIGNAL(bombExecutionFinished()),this, SLOT(onBombExecutionFinished())); + QGraphicsScene::addItem(bomb); +} + +void GraphicsScene::addItem(Torpedo *torpedo) +{ + torpedos.insert(torpedo); + connect(torpedo,SIGNAL(torpedoExecutionFinished()),this, SLOT(onTorpedoExecutionFinished())); + QGraphicsScene::addItem(torpedo); +} + +void GraphicsScene::addItem(SubMarine *submarine) +{ + submarines.insert(submarine); + connect(submarine,SIGNAL(subMarineExecutionFinished()),this, SLOT(onSubMarineExecutionFinished())); + QGraphicsScene::addItem(submarine); +} + +void GraphicsScene::addItem(QGraphicsItem *item) +{ + QGraphicsScene::addItem(item); +} + +void GraphicsScene::onBombExecutionFinished() +{ + Bomb *bomb = qobject_cast(sender()); + bombs.remove(bomb); + bomb->deleteLater(); + if (boat) + boat->setBombsLaunched(boat->bombsLaunched() - 1); +} + +void GraphicsScene::onTorpedoExecutionFinished() +{ + Torpedo *torpedo = qobject_cast(sender()); + torpedos.remove(torpedo); + torpedo->deleteLater(); +} + +void GraphicsScene::onSubMarineExecutionFinished() +{ + SubMarine *submarine = qobject_cast(sender()); + submarines.remove(submarine); + if (submarines.count() == 0) + emit allSubMarineDestroyed(submarine->points()); + else + emit subMarineDestroyed(submarine->points()); + submarine->deleteLater(); +} + +void GraphicsScene::clearScene() +{ + foreach (SubMarine *sub, submarines) { + sub->destroy(); + sub->deleteLater(); + } + + foreach (Torpedo *torpedo, torpedos) { + torpedo->destroy(); + torpedo->deleteLater(); + } + + foreach (Bomb *bomb, bombs) { + bomb->destroy(); + bomb->deleteLater(); + } + + submarines.clear(); + bombs.clear(); + torpedos.clear(); + + AnimationManager::self()->unregisterAllAnimations(); + + boat->stop(); + boat->hide(); + boat->setEnabled(true); +} diff --git a/examples/animation/sub-attaq/graphicsscene.h b/examples/animation/sub-attaq/graphicsscene.h new file mode 100644 index 0000000000..e1220a5eb8 --- /dev/null +++ b/examples/animation/sub-attaq/graphicsscene.h @@ -0,0 +1,122 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __GRAPHICSSCENE__H__ +#define __GRAPHICSSCENE__H__ + +//Qt +#include +#include +#include + + +class Boat; +class SubMarine; +class Torpedo; +class Bomb; +class PixmapItem; +class ProgressItem; +class TextInformationItem; +QT_BEGIN_NAMESPACE +class QAction; +QT_END_NAMESPACE + +class GraphicsScene : public QGraphicsScene +{ +Q_OBJECT +public: + enum Mode { + Big = 0, + Small + }; + + struct SubmarineDescription { + int type; + int points; + QString name; + }; + + struct LevelDescription { + int id; + QString name; + QList > submarines; + }; + + GraphicsScene(int x, int y, int width, int height, Mode mode = Big); + qreal sealLevel() const; + void setupScene(QAction *newAction, QAction *quitAction); + void addItem(Bomb *bomb); + void addItem(Torpedo *torpedo); + void addItem(SubMarine *submarine); + void addItem(QGraphicsItem *item); + void clearScene(); + +signals: + void subMarineDestroyed(int); + void allSubMarineDestroyed(int); + +private slots: + void onBombExecutionFinished(); + void onTorpedoExecutionFinished(); + void onSubMarineExecutionFinished(); + +private: + Mode mode; + ProgressItem *progressItem; + TextInformationItem *textInformationItem; + Boat *boat; + QSet submarines; + QSet bombs; + QSet torpedos; + QVector submarinesData; + QHash levelsData; + + friend class PauseState; + friend class PlayState; + friend class LevelState; + friend class LostState; + friend class WinState; + friend class WinTransition; + friend class UpdateScoreTransition; +}; + +#endif //__GRAPHICSSCENE__H__ + diff --git a/examples/animation/sub-attaq/main.cpp b/examples/animation/sub-attaq/main.cpp new file mode 100644 index 0000000000..c8e534e7e7 --- /dev/null +++ b/examples/animation/sub-attaq/main.cpp @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + Q_INIT_RESOURCE(subattaq); + + qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); + + MainWindow w; + w.show(); + + return app.exec(); +} diff --git a/examples/animation/sub-attaq/mainwindow.cpp b/examples/animation/sub-attaq/mainwindow.cpp new file mode 100644 index 0000000000..81632a50a0 --- /dev/null +++ b/examples/animation/sub-attaq/mainwindow.cpp @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "mainwindow.h" +#include "graphicsscene.h" + +//Qt +#include + +#ifdef QT_NO_OPENGL + #include + #include + #include +#else + #include +#endif + +MainWindow::MainWindow() : QMainWindow(0) +{ + QMenu *file = menuBar()->addMenu(tr("&File")); + + QAction *newAction = file->addAction(tr("New Game")); + newAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_N)); + QAction *quitAction = file->addAction(tr("Quit")); + quitAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q)); + + if (QApplication::arguments().contains("-fullscreen")) { + scene = new GraphicsScene(0, 0, 750, 400, GraphicsScene::Small); + setWindowState(Qt::WindowFullScreen); + } else { + scene = new GraphicsScene(0, 0, 880, 630); + layout()->setSizeConstraint(QLayout::SetFixedSize); + } + + view = new QGraphicsView(scene, this); + view->setAlignment(Qt::AlignLeft | Qt::AlignTop); + scene->setupScene(newAction, quitAction); +#ifndef QT_NO_OPENGL + view->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); +#endif + + setCentralWidget(view); +} diff --git a/examples/animation/sub-attaq/mainwindow.h b/examples/animation/sub-attaq/mainwindow.h new file mode 100644 index 0000000000..933587a262 --- /dev/null +++ b/examples/animation/sub-attaq/mainwindow.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __MAINWINDOW__H__ +#define __MAINWINDOW__H__ + +//Qt +#include +class GraphicsScene; +QT_BEGIN_NAMESPACE +class QGraphicsView; +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ +Q_OBJECT +public: + MainWindow(); + +private: + GraphicsScene *scene; + QGraphicsView *view; +}; + +#endif //__MAINWINDOW__H__ diff --git a/examples/animation/sub-attaq/pics/big/background.png b/examples/animation/sub-attaq/pics/big/background.png new file mode 100644 index 0000000000..9f581571fa Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/background.png differ diff --git a/examples/animation/sub-attaq/pics/big/boat.png b/examples/animation/sub-attaq/pics/big/boat.png new file mode 100644 index 0000000000..be82dff62a Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/boat.png differ diff --git a/examples/animation/sub-attaq/pics/big/bomb.png b/examples/animation/sub-attaq/pics/big/bomb.png new file mode 100644 index 0000000000..3af5f2f29c Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/bomb.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png new file mode 100644 index 0000000000..c9fd8b0984 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png new file mode 100644 index 0000000000..7528f2d2da Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png new file mode 100644 index 0000000000..aae9c9c184 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png new file mode 100644 index 0000000000..d697c1bae8 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png new file mode 100644 index 0000000000..88ca5144b7 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png new file mode 100644 index 0000000000..524f5890ee Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png new file mode 100644 index 0000000000..2cca1e80fe Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png new file mode 100644 index 0000000000..82100a8260 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png differ diff --git a/examples/animation/sub-attaq/pics/big/submarine.png b/examples/animation/sub-attaq/pics/big/submarine.png new file mode 100644 index 0000000000..df435dc47d Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/submarine.png differ diff --git a/examples/animation/sub-attaq/pics/big/surface.png b/examples/animation/sub-attaq/pics/big/surface.png new file mode 100644 index 0000000000..4eba29e9cd Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/surface.png differ diff --git a/examples/animation/sub-attaq/pics/big/torpedo.png b/examples/animation/sub-attaq/pics/big/torpedo.png new file mode 100644 index 0000000000..f9c26873f1 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/torpedo.png differ diff --git a/examples/animation/sub-attaq/pics/scalable/background-n810.svg b/examples/animation/sub-attaq/pics/scalable/background-n810.svg new file mode 100644 index 0000000000..ece9f7aaf1 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/background-n810.svg @@ -0,0 +1,171 @@ + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/background.svg b/examples/animation/sub-attaq/pics/scalable/background.svg new file mode 100644 index 0000000000..0be268010e --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/background.svg @@ -0,0 +1,171 @@ + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/boat.svg b/examples/animation/sub-attaq/pics/scalable/boat.svg new file mode 100644 index 0000000000..5298821ba8 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/boat.svg @@ -0,0 +1,279 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/bomb.svg b/examples/animation/sub-attaq/pics/scalable/bomb.svg new file mode 100644 index 0000000000..294771a6dd --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/bomb.svg @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/sand.svg b/examples/animation/sub-attaq/pics/scalable/sand.svg new file mode 100644 index 0000000000..8af11b7a66 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/sand.svg @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/see.svg b/examples/animation/sub-attaq/pics/scalable/see.svg new file mode 100644 index 0000000000..0666691215 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/see.svg @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/sky.svg b/examples/animation/sub-attaq/pics/scalable/sky.svg new file mode 100644 index 0000000000..1546c087a7 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/sky.svg @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg b/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg new file mode 100644 index 0000000000..b075179b46 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg @@ -0,0 +1,1473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/submarine.svg b/examples/animation/sub-attaq/pics/scalable/submarine.svg new file mode 100644 index 0000000000..8a0ffddbca --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/submarine.svg @@ -0,0 +1,214 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/surface.svg b/examples/animation/sub-attaq/pics/scalable/surface.svg new file mode 100644 index 0000000000..40ed239638 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/surface.svg @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/torpedo.svg b/examples/animation/sub-attaq/pics/scalable/torpedo.svg new file mode 100644 index 0000000000..48e429d2bf --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/torpedo.svg @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/small/background.png b/examples/animation/sub-attaq/pics/small/background.png new file mode 100644 index 0000000000..5ad3db660a Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/background.png differ diff --git a/examples/animation/sub-attaq/pics/small/boat.png b/examples/animation/sub-attaq/pics/small/boat.png new file mode 100644 index 0000000000..114ccc310e Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/boat.png differ diff --git a/examples/animation/sub-attaq/pics/small/bomb.png b/examples/animation/sub-attaq/pics/small/bomb.png new file mode 100644 index 0000000000..3af5f2f29c Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/bomb.png differ diff --git a/examples/animation/sub-attaq/pics/small/submarine.png b/examples/animation/sub-attaq/pics/small/submarine.png new file mode 100644 index 0000000000..0c0c350600 Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/submarine.png differ diff --git a/examples/animation/sub-attaq/pics/small/surface.png b/examples/animation/sub-attaq/pics/small/surface.png new file mode 100644 index 0000000000..06d0e47a5c Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/surface.png differ diff --git a/examples/animation/sub-attaq/pics/small/torpedo.png b/examples/animation/sub-attaq/pics/small/torpedo.png new file mode 100644 index 0000000000..f9c26873f1 Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/torpedo.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-a.png b/examples/animation/sub-attaq/pics/welcome/logo-a.png new file mode 100644 index 0000000000..67dd76dac0 Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-a.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-a2.png b/examples/animation/sub-attaq/pics/welcome/logo-a2.png new file mode 100644 index 0000000000..17668b07de Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-a2.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-b.png b/examples/animation/sub-attaq/pics/welcome/logo-b.png new file mode 100644 index 0000000000..cf6c04560b Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-b.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-dash.png b/examples/animation/sub-attaq/pics/welcome/logo-dash.png new file mode 100644 index 0000000000..219233ce6b Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-dash.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-excl.png b/examples/animation/sub-attaq/pics/welcome/logo-excl.png new file mode 100644 index 0000000000..8dd0a2eb86 Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-excl.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-q.png b/examples/animation/sub-attaq/pics/welcome/logo-q.png new file mode 100644 index 0000000000..86e588d4d8 Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-q.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-s.png b/examples/animation/sub-attaq/pics/welcome/logo-s.png new file mode 100644 index 0000000000..7b6a36e93a Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-s.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-t.png b/examples/animation/sub-attaq/pics/welcome/logo-t.png new file mode 100644 index 0000000000..b2e3526bea Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-t.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-t2.png b/examples/animation/sub-attaq/pics/welcome/logo-t2.png new file mode 100644 index 0000000000..b11a77886e Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-t2.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-u.png b/examples/animation/sub-attaq/pics/welcome/logo-u.png new file mode 100644 index 0000000000..24eede887a Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-u.png differ diff --git a/examples/animation/sub-attaq/pixmapitem.cpp b/examples/animation/sub-attaq/pixmapitem.cpp new file mode 100644 index 0000000000..be75bd1995 --- /dev/null +++ b/examples/animation/sub-attaq/pixmapitem.cpp @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "pixmapitem.h" + +//Qt +#include + +PixmapItem::PixmapItem(const QString &fileName,GraphicsScene::Mode mode, QGraphicsItem * parent) : QGraphicsObject(parent) +{ + if (mode == GraphicsScene::Big) + pix = ":/big/" + fileName; + else + pix = ":/small/" + fileName; +} + +PixmapItem::PixmapItem(const QString &fileName, QGraphicsScene *scene) : QGraphicsObject(), pix(fileName) +{ + scene->addItem(this); +} + +QSizeF PixmapItem::size() const +{ + return pix.size(); +} + +QRectF PixmapItem::boundingRect() const +{ + return QRectF(QPointF(0, 0), pix.size()); +} + +void PixmapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + painter->drawPixmap(0, 0, pix); +} + + diff --git a/examples/animation/sub-attaq/pixmapitem.h b/examples/animation/sub-attaq/pixmapitem.h new file mode 100644 index 0000000000..0a94aab7eb --- /dev/null +++ b/examples/animation/sub-attaq/pixmapitem.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __PIXMAPITEM__H__ +#define __PIXMAPITEM__H__ + +//Own +#include "graphicsscene.h" + +//Qt +#include + +class PixmapItem : public QGraphicsObject +{ +public: + PixmapItem(const QString &fileName, GraphicsScene::Mode mode, QGraphicsItem * parent = 0); + PixmapItem(const QString &fileName, QGraphicsScene *scene); + QSizeF size() const; + QRectF boundingRect() const; + void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *); +private: + QPixmap pix; +}; + +#endif //__PIXMAPITEM__H__ diff --git a/examples/animation/sub-attaq/progressitem.cpp b/examples/animation/sub-attaq/progressitem.cpp new file mode 100644 index 0000000000..426dedfbd4 --- /dev/null +++ b/examples/animation/sub-attaq/progressitem.cpp @@ -0,0 +1,67 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "progressitem.h" +#include "pixmapitem.h" + +ProgressItem::ProgressItem (QGraphicsItem * parent) + : QGraphicsTextItem(parent), currentLevel(1), currentScore(0) +{ + setFont(QFont("Comic Sans MS")); + setPos(parentItem()->boundingRect().topRight() - QPointF(180, -5)); +} + +void ProgressItem::setLevel(int level) +{ + currentLevel = level; + updateProgress(); +} + +void ProgressItem::setScore(int score) +{ + currentScore = score; + updateProgress(); +} + +void ProgressItem::updateProgress() +{ + setHtml(QString("Level : %1 Score : %2").arg(currentLevel).arg(currentScore)); +} diff --git a/examples/animation/sub-attaq/progressitem.h b/examples/animation/sub-attaq/progressitem.h new file mode 100644 index 0000000000..bcf708c512 --- /dev/null +++ b/examples/animation/sub-attaq/progressitem.h @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PROGRESSITEM_H +#define PROGRESSITEM_H + +//Qt +#include + +class ProgressItem : public QGraphicsTextItem +{ +public: + ProgressItem(QGraphicsItem * parent = 0); + void setLevel(int level); + void setScore(int score); + +private: + void updateProgress(); + int currentLevel; + int currentScore; +}; + +#endif // PROGRESSITEM_H diff --git a/examples/animation/sub-attaq/qanimationstate.cpp b/examples/animation/sub-attaq/qanimationstate.cpp new file mode 100644 index 0000000000..593c8dfe8d --- /dev/null +++ b/examples/animation/sub-attaq/qanimationstate.cpp @@ -0,0 +1,150 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qanimationstate.h" + +#include + +QT_BEGIN_NAMESPACE + +/*! +\class QAnimationState + +\brief The QAnimationState class provides state that handle an animation and emit +a signal when this animation is finished. + +\ingroup statemachine + +QAnimationState provides a state that handle an animation. It will start this animation +when the state is entered and stop it when it is leaved. When the animation has finished the +state emit animationFinished signal. +QAnimationState is part of \l{The State Machine Framework}. + +\code +QStateMachine machine; +QAnimationState *s = new QAnimationState(machine->rootState()); +QPropertyAnimation *animation = new QPropertyAnimation(obj, "pos"); +s->setAnimation(animation); +QState *s2 = new QState(machine->rootState()); +s->addTransition(s, SIGNAL(animationFinished()), s2); +machine.start(); +\endcode + +\sa QState, {The Animation Framework} +*/ + + +#ifndef QT_NO_ANIMATION + +/*! + Constructs a new state with the given \a parent state. +*/ +QAnimationState::QAnimationState(QState *parent) + : QState(parent), m_animation(0) +{ +} + +/*! + Destroys the animation state. +*/ +QAnimationState::~QAnimationState() +{ +} + +/*! + Set an \a animation for this QAnimationState. If an animation was previously handle by this + state then it won't emit animationFinished for the old animation. The QAnimationState doesn't + take the ownership of the animation. +*/ +void QAnimationState::setAnimation(QAbstractAnimation *animation) +{ + if (animation == m_animation) + return; + + //Disconnect from the previous animation if exist + if(m_animation) + disconnect(m_animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); + + m_animation = animation; + + if (m_animation) { + //connect the new animation + connect(m_animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); + } +} + +/*! + Returns the animation handle by this animation state, or 0 if there is no animation. +*/ +QAbstractAnimation* QAnimationState::animation() const +{ + return m_animation; +} + +/*! + \reimp +*/ +void QAnimationState::onEntry(QEvent *) +{ + if (m_animation) + m_animation->start(); +} + +/*! + \reimp +*/ +void QAnimationState::onExit(QEvent *) +{ + if (m_animation) + m_animation->stop(); +} + +/*! + \reimp +*/ +bool QAnimationState::event(QEvent *e) +{ + return QState::event(e); +} + +QT_END_NAMESPACE + +#endif diff --git a/examples/animation/sub-attaq/qanimationstate.h b/examples/animation/sub-attaq/qanimationstate.h new file mode 100644 index 0000000000..aace3b502b --- /dev/null +++ b/examples/animation/sub-attaq/qanimationstate.h @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QANIMATIONSTATE_H +#define QANIMATIONSTATE_H + +#ifndef QT_STATEMACHINE_SOLUTION +# include +# include +#else +# include "qstate.h" +# include "qabstractanimation.h" +#endif + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +#ifndef QT_NO_ANIMATION + +class QAbstractAnimation; + +class QAnimationState : public QState +{ + Q_OBJECT +public: + QAnimationState(QState *parent = 0); + ~QAnimationState(); + + void setAnimation(QAbstractAnimation *animation); + QAbstractAnimation* animation() const; + +signals: + void animationFinished(); + +protected: + void onEntry(QEvent *); + void onExit(QEvent *); + bool event(QEvent *e); + +private: + Q_DISABLE_COPY(QAnimationState) + QAbstractAnimation *m_animation; +}; + +#endif + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QANIMATIONSTATE_H diff --git a/examples/animation/sub-attaq/states.cpp b/examples/animation/sub-attaq/states.cpp new file mode 100644 index 0000000000..462e13b90e --- /dev/null +++ b/examples/animation/sub-attaq/states.cpp @@ -0,0 +1,330 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "states.h" +#include "graphicsscene.h" +#include "boat.h" +#include "submarine.h" +#include "torpedo.h" +#include "animationmanager.h" +#include "progressitem.h" +#include "textinformationitem.h" + +//Qt +#include +#include +#include +#include +#include + +PlayState::PlayState(GraphicsScene *scene, QState *parent) + : QState(parent), + scene(scene), + machine(0), + currentLevel(0), + score(0) +{ +} + +PlayState::~PlayState() +{ + delete machine; +} + +void PlayState::onEntry(QEvent *) +{ + //We are now playing? + if (machine) { + machine->stop(); + //we hide the information + scene->textInformationItem->hide(); + scene->clearScene(); + currentLevel = 0; + score = 0; + delete machine; + } + + machine = new QStateMachine; + + //This state is when player is playing + LevelState *levelState = new LevelState(scene, this, machine); + + //This state is when the player is actually playing but the game is not paused + QState *playingState = new QState(levelState); + levelState->setInitialState(playingState); + + //This state is when the game is paused + PauseState *pauseState = new PauseState(scene, levelState); + + //We have one view, it receive the key press event + QKeyEventTransition *pressPplay = new QKeyEventTransition(scene->views().at(0), QEvent::KeyPress, Qt::Key_P); + pressPplay->setTargetState(pauseState); + QKeyEventTransition *pressPpause = new QKeyEventTransition(scene->views().at(0), QEvent::KeyPress, Qt::Key_P); + pressPpause->setTargetState(playingState); + + //Pause "P" is triggered, the player pause the game + playingState->addTransition(pressPplay); + + //To get back playing when the game has been paused + pauseState->addTransition(pressPpause); + + //This state is when player have lost + LostState *lostState = new LostState(scene, this, machine); + + //This state is when player have won + WinState *winState = new WinState(scene, this, machine); + + //The boat has been destroyed then the game is finished + levelState->addTransition(scene->boat, SIGNAL(boatExecutionFinished()),lostState); + + //This transition check if we won or not + WinTransition *winTransition = new WinTransition(scene, this, winState); + + //The boat has been destroyed then the game is finished + levelState->addTransition(winTransition); + + //This state is an animation when the score changed + UpdateScoreState *scoreState = new UpdateScoreState(this, levelState); + + //This transition update the score when a submarine die + UpdateScoreTransition *scoreTransition = new UpdateScoreTransition(scene, this, levelState); + scoreTransition->setTargetState(scoreState); + + //The boat has been destroyed then the game is finished + playingState->addTransition(scoreTransition); + + //We go back to play state + scoreState->addTransition(playingState); + + //We start playing!!! + machine->setInitialState(levelState); + + //Final state + QFinalState *final = new QFinalState(machine); + + //This transition is triggered when the player press space after completing a level + CustomSpaceTransition *spaceTransition = new CustomSpaceTransition(scene->views().at(0), this, QEvent::KeyPress, Qt::Key_Space); + spaceTransition->setTargetState(levelState); + winState->addTransition(spaceTransition); + + //We lost we should reach the final state + lostState->addTransition(lostState, SIGNAL(finished()), final); + + machine->start(); +} + +LevelState::LevelState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) +{ +} +void LevelState::onEntry(QEvent *) +{ + initializeLevel(); +} + +void LevelState::initializeLevel() +{ + //we re-init the boat + scene->boat->setPos(scene->width()/2, scene->sealLevel() - scene->boat->size().height()); + scene->boat->setCurrentSpeed(0); + scene->boat->setCurrentDirection(Boat::None); + scene->boat->setBombsLaunched(0); + scene->boat->show(); + scene->setFocusItem(scene->boat, Qt::OtherFocusReason); + scene->boat->run(); + + scene->progressItem->setScore(game->score); + scene->progressItem->setLevel(game->currentLevel + 1); + + GraphicsScene::LevelDescription currentLevelDescription = scene->levelsData.value(game->currentLevel); + + for (int i = 0; i < currentLevelDescription.submarines.size(); ++i ) { + + QPair subContent = currentLevelDescription.submarines.at(i); + GraphicsScene::SubmarineDescription submarineDesc = scene->submarinesData.at(subContent.first); + + for (int j = 0; j < subContent.second; ++j ) { + SubMarine *sub = new SubMarine(submarineDesc.type, submarineDesc.name, submarineDesc.points); + scene->addItem(sub); + int random = (qrand() % 15 + 1); + qreal x = random == 13 || random == 5 ? 0 : scene->width() - sub->size().width(); + qreal y = scene->height() -(qrand() % 150 + 1) - sub->size().height(); + sub->setPos(x,y); + sub->setCurrentDirection(x == 0 ? SubMarine::Right : SubMarine::Left); + sub->setCurrentSpeed(qrand() % 3 + 1); + } + } +} + +/** Pause State */ +PauseState::PauseState(GraphicsScene *scene, QState *parent) : QState(parent),scene(scene) +{ +} +void PauseState::onEntry(QEvent *) +{ + AnimationManager::self()->pauseAll(); + scene->boat->setEnabled(false); +} +void PauseState::onExit(QEvent *) +{ + AnimationManager::self()->resumeAll(); + scene->boat->setEnabled(true); + scene->boat->setFocus(); +} + +/** Lost State */ +LostState::LostState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) +{ +} + +void LostState::onEntry(QEvent *) +{ + //The message to display + QString message = QString("You lose on level %1. Your score is %2.").arg(game->currentLevel+1).arg(game->score); + + //We set the level back to 0 + game->currentLevel = 0; + + //We set the score back to 0 + game->score = 0; + + //We clear the scene + scene->clearScene(); + + //We inform the player + scene->textInformationItem->setMessage(message); + scene->textInformationItem->show(); +} + +void LostState::onExit(QEvent *) +{ + //we hide the information + scene->textInformationItem->hide(); +} + +/** Win State */ +WinState::WinState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) +{ +} + +void WinState::onEntry(QEvent *) +{ + //We clear the scene + scene->clearScene(); + + QString message; + if (scene->levelsData.size() - 1 != game->currentLevel) { + message = QString("You win the level %1. Your score is %2.\nPress Space to continue.").arg(game->currentLevel+1).arg(game->score); + //We increment the level number + game->currentLevel++; + } else { + message = QString("You finish the game on level %1. Your score is %2.").arg(game->currentLevel+1).arg(game->score); + //We set the level back to 0 + game->currentLevel = 0; + //We set the score back to 0 + game->score = 0; + } + + //We inform the player + scene->textInformationItem->setMessage(message); + scene->textInformationItem->show(); +} + +void WinState::onExit(QEvent *) +{ + //we hide the information + scene->textInformationItem->hide(); +} + +/** UpdateScore State */ +UpdateScoreState::UpdateScoreState(PlayState *g, QState *parent) : QState(parent), game(g) +{ +} + +/** Win transition */ +UpdateScoreTransition::UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) + : QSignalTransition(scene,SIGNAL(subMarineDestroyed(int))), + game(game), scene(scene) +{ + setTargetState(target); +} + +bool UpdateScoreTransition::eventTest(QEvent *event) +{ + if (!QSignalTransition::eventTest(event)) + return false; + QStateMachine::SignalEvent *se = static_cast(event); + game->score += se->arguments().at(0).toInt(); + scene->progressItem->setScore(game->score); + return true; +} + +/** Win transition */ +WinTransition::WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) + : QSignalTransition(scene,SIGNAL(allSubMarineDestroyed(int))), + game(game), scene(scene) +{ + setTargetState(target); +} + +bool WinTransition::eventTest(QEvent *event) +{ + if (!QSignalTransition::eventTest(event)) + return false; + QStateMachine::SignalEvent *se = static_cast(event); + game->score += se->arguments().at(0).toInt(); + scene->progressItem->setScore(game->score); + return true; +} + +/** Space transition */ +CustomSpaceTransition::CustomSpaceTransition(QWidget *widget, PlayState *game, QEvent::Type type, int key) + : QKeyEventTransition(widget, type, key), + game(game) +{ +} + +bool CustomSpaceTransition::eventTest(QEvent *event) +{ + if (!QKeyEventTransition::eventTest(event)) + return false; + return (game->currentLevel != 0); +} diff --git a/examples/animation/sub-attaq/states.h b/examples/animation/sub-attaq/states.h new file mode 100644 index 0000000000..cda9603196 --- /dev/null +++ b/examples/animation/sub-attaq/states.h @@ -0,0 +1,180 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef STATES_H +#define STATES_H + +//Qt +#include +#include +#include +#include +#include + +class GraphicsScene; +class Boat; +class SubMarine; +QT_BEGIN_NAMESPACE +class QStateMachine; +QT_END_NAMESPACE + +class PlayState : public QState +{ +public: + PlayState(GraphicsScene *scene, QState *parent = 0); + ~PlayState(); + + protected: + void onEntry(QEvent *); + +private : + GraphicsScene *scene; + QStateMachine *machine; + int currentLevel; + int score; + QState *parallelChild; + + friend class UpdateScoreState; + friend class UpdateScoreTransition; + friend class WinTransition; + friend class CustomSpaceTransition; + friend class WinState; + friend class LostState; + friend class LevelState; +}; + +class LevelState : public QState +{ +public: + LevelState(GraphicsScene *scene, PlayState *game, QState *parent = 0); +protected: + void onEntry(QEvent *); +private : + void initializeLevel(); + GraphicsScene *scene; + PlayState *game; +}; + +class PauseState : public QState +{ +public: + PauseState(GraphicsScene *scene, QState *parent = 0); + +protected: + void onEntry(QEvent *); + void onExit(QEvent *); +private : + GraphicsScene *scene; + Boat *boat; +}; + +class LostState : public QState +{ +public: + LostState(GraphicsScene *scene, PlayState *game, QState *parent = 0); + +protected: + void onEntry(QEvent *); + void onExit(QEvent *); +private : + GraphicsScene *scene; + PlayState *game; +}; + +class WinState : public QState +{ +public: + WinState(GraphicsScene *scene, PlayState *game, QState *parent = 0); + +protected: + void onEntry(QEvent *); + void onExit(QEvent *); +private : + GraphicsScene *scene; + PlayState *game; +}; + +class UpdateScoreState : public QState +{ +public: + UpdateScoreState(PlayState *game, QState *parent); +private: + QPropertyAnimation *scoreAnimation; + PlayState *game; +}; + +//These transtion is used to update the score +class UpdateScoreTransition : public QSignalTransition +{ +public: + UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target); +protected: + virtual bool eventTest(QEvent *event); +private: + PlayState * game; + GraphicsScene *scene; +}; + +//These transtion test if we have won the game +class WinTransition : public QSignalTransition +{ +public: + WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target); +protected: + virtual bool eventTest(QEvent *event); +private: + PlayState * game; + GraphicsScene *scene; +}; + +//These transtion is true if one level has been completed and the player want to continue + class CustomSpaceTransition : public QKeyEventTransition +{ +public: + CustomSpaceTransition(QWidget *widget, PlayState *game, QEvent::Type type, int key); +protected: + virtual bool eventTest(QEvent *event); +private: + PlayState *game; + int key; +}; + +#endif // STATES_H diff --git a/examples/animation/sub-attaq/sub-attaq.pro b/examples/animation/sub-attaq/sub-attaq.pro new file mode 100644 index 0000000000..5575f5e65f --- /dev/null +++ b/examples/animation/sub-attaq/sub-attaq.pro @@ -0,0 +1,41 @@ +contains(QT_CONFIG, opengl):QT += opengl +HEADERS += boat.h \ + bomb.h \ + mainwindow.h \ + submarine.h \ + torpedo.h \ + pixmapitem.h \ + graphicsscene.h \ + animationmanager.h \ + states.h \ + boat_p.h \ + submarine_p.h \ + qanimationstate.h \ + progressitem.h \ + textinformationitem.h +SOURCES += boat.cpp \ + bomb.cpp \ + main.cpp \ + mainwindow.cpp \ + submarine.cpp \ + torpedo.cpp \ + pixmapitem.cpp \ + graphicsscene.cpp \ + animationmanager.cpp \ + states.cpp \ + qanimationstate.cpp \ + progressitem.cpp \ + textinformationitem.cpp +RESOURCES += subattaq.qrc + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/sub-attaq +sources.files = $$SOURCES \ + $$HEADERS \ + $$RESOURCES \ + $$FORMS \ + sub-attaq.pro \ + pics +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/sub-attaq +INSTALLS += target \ + sources diff --git a/examples/animation/sub-attaq/subattaq.qrc b/examples/animation/sub-attaq/subattaq.qrc new file mode 100644 index 0000000000..80a3af11cc --- /dev/null +++ b/examples/animation/sub-attaq/subattaq.qrc @@ -0,0 +1,39 @@ + + + pics/scalable/sub-attaq.svg + pics/scalable/submarine.svg + pics/scalable/boat.svg + pics/scalable/torpedo.svg + pics/welcome/logo-s.png + pics/welcome/logo-u.png + pics/welcome/logo-b.png + pics/welcome/logo-dash.png + pics/welcome/logo-a.png + pics/welcome/logo-t.png + pics/welcome/logo-t2.png + pics/welcome/logo-a2.png + pics/welcome/logo-q.png + pics/welcome/logo-excl.png + pics/big/background.png + pics/big/boat.png + pics/big/bomb.png + pics/big/submarine.png + pics/big/surface.png + pics/big/torpedo.png + pics/small/background.png + pics/small/boat.png + pics/small/bomb.png + pics/small/submarine.png + pics/small/surface.png + pics/small/torpedo.png + pics/big/explosion/boat/step1.png + pics/big/explosion/boat/step2.png + pics/big/explosion/boat/step3.png + pics/big/explosion/boat/step4.png + pics/big/explosion/submarine/step1.png + pics/big/explosion/submarine/step2.png + pics/big/explosion/submarine/step3.png + pics/big/explosion/submarine/step4.png + data.xml + + diff --git a/examples/animation/sub-attaq/submarine.cpp b/examples/animation/sub-attaq/submarine.cpp new file mode 100644 index 0000000000..2c8a5a2884 --- /dev/null +++ b/examples/animation/sub-attaq/submarine.cpp @@ -0,0 +1,182 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "submarine.h" +#include "submarine_p.h" +#include "torpedo.h" +#include "pixmapitem.h" +#include "graphicsscene.h" +#include "animationmanager.h" +#include "qanimationstate.h" + +#include +#include +#include +#include + +static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub) +{ + QSequentialAnimationGroup *group = new QSequentialAnimationGroup(sub); + for (int i = 1; i <= 4; ++i) { + PixmapItem *step = new PixmapItem(QString::fromLatin1("explosion/submarine/step%1").arg(i), GraphicsScene::Big, sub); + step->setZValue(6); + step->setOpacity(0); + QPropertyAnimation *anim = new QPropertyAnimation(step, "opacity", group); + anim->setDuration(100); + anim->setEndValue(1); + } + AnimationManager::self()->registerAnimation(group); + return group; +} + + +SubMarine::SubMarine(int type, const QString &name, int points) : PixmapItem(QString("submarine"), GraphicsScene::Big), + subType(type), subName(name), subPoints(points), speed(0), direction(SubMarine::None) +{ + setZValue(5); + setTransformOriginPoint(boundingRect().center()); + + graphicsRotation = new QGraphicsRotation(this); + graphicsRotation->setAxis(Qt::YAxis); + graphicsRotation->setOrigin(QVector3D(size().width()/2, size().height()/2, 0)); + QList r; + r.append(graphicsRotation); + setTransformations(r); + + //We setup the state machine of the submarine + QStateMachine *machine = new QStateMachine(this); + + //This state is when the boat is moving/rotating + QState *moving = new QState(machine); + + //This state is when the boat is moving from left to right + MovementState *movement = new MovementState(this, moving); + + //This state is when the boat is moving from left to right + ReturnState *rotation = new ReturnState(this, moving); + + //This is the initial state of the moving root state + moving->setInitialState(movement); + + movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving); + + //This is the initial state of the machine + machine->setInitialState(moving); + + //End + QFinalState *final = new QFinalState(machine); + + //If the moving animation is finished we move to the return state + movement->addTransition(movement, SIGNAL(animationFinished()), rotation); + + //If the return animation is finished we move to the moving state + rotation->addTransition(rotation, SIGNAL(animationFinished()), movement); + + //This state play the destroyed animation + QAnimationState *destroyedState = new QAnimationState(machine); + destroyedState->setAnimation(setupDestroyAnimation(this)); + + //Play a nice animation when the submarine is destroyed + moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState); + + //Transition to final state when the destroyed animation is finished + destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); + + //The machine has finished to be executed, then the submarine is dead + connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished())); + + machine->start(); +} + +int SubMarine::points() const +{ + return subPoints; +} + +void SubMarine::setCurrentDirection(SubMarine::Movement direction) +{ + if (this->direction == direction) + return; + if (direction == SubMarine::Right && this->direction == SubMarine::None) { + graphicsRotation->setAngle(180); + } + this->direction = direction; +} + +enum SubMarine::Movement SubMarine::currentDirection() const +{ + return direction; +} + +void SubMarine::setCurrentSpeed(int speed) +{ + if (speed < 0 || speed > 3) { + qWarning("SubMarine::setCurrentSpeed : The speed is invalid"); + } + this->speed = speed; + emit subMarineStateChanged(); +} + +int SubMarine::currentSpeed() const +{ + return speed; +} + +void SubMarine::launchTorpedo(int speed) +{ + Torpedo * torp = new Torpedo(); + GraphicsScene *scene = static_cast(this->scene()); + scene->addItem(torp); + torp->setPos(pos()); + torp->setCurrentSpeed(speed); + torp->launch(); +} + +void SubMarine::destroy() +{ + emit subMarineDestroyed(); +} + +int SubMarine::type() const +{ + return Type; +} diff --git a/examples/animation/sub-attaq/submarine.h b/examples/animation/sub-attaq/submarine.h new file mode 100644 index 0000000000..0d6087dc26 --- /dev/null +++ b/examples/animation/sub-attaq/submarine.h @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __SUBMARINE__H__ +#define __SUBMARINE__H__ + +//Qt +#include + +#include "pixmapitem.h" + +class Torpedo; + +class SubMarine : public PixmapItem +{ +Q_OBJECT +public: + enum Movement { + None = 0, + Left, + Right + }; + enum { Type = UserType + 1 }; + SubMarine(int type, const QString &name, int points); + + int points() const; + + void setCurrentDirection(Movement direction); + enum Movement currentDirection() const; + + void setCurrentSpeed(int speed); + int currentSpeed() const; + + void launchTorpedo(int speed); + void destroy(); + + virtual int type() const; + + QGraphicsRotation *rotation() const { return graphicsRotation; } + +signals: + void subMarineDestroyed(); + void subMarineExecutionFinished(); + void subMarineStateChanged(); + +private: + int subType; + QString subName; + int subPoints; + int speed; + Movement direction; + QGraphicsRotation *graphicsRotation; +}; + +#endif //__SUBMARINE__H__ diff --git a/examples/animation/sub-attaq/submarine_p.h b/examples/animation/sub-attaq/submarine_p.h new file mode 100644 index 0000000000..f0b370d878 --- /dev/null +++ b/examples/animation/sub-attaq/submarine_p.h @@ -0,0 +1,137 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SUBMARINE_P_H +#define SUBMARINE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +//Own +#include "animationmanager.h" +#include "submarine.h" +#include "qanimationstate.h" + +//Qt +#include +#include + +//This state is describing when the boat is moving right +class MovementState : public QAnimationState +{ +Q_OBJECT +public: + MovementState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) + { + movementAnimation = new QPropertyAnimation(submarine, "pos"); + connect(movementAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationMovementValueChanged(const QVariant &))); + setAnimation(movementAnimation); + AnimationManager::self()->registerAnimation(movementAnimation); + this->submarine = submarine; + } + +protected slots: + void onAnimationMovementValueChanged(const QVariant &) + { + if (qrand() % 200 + 1 == 3) + submarine->launchTorpedo(qrand() % 3 + 1); + } + +protected: + void onEntry(QEvent *e) + { + if (submarine->currentDirection() == SubMarine::Left) { + movementAnimation->setEndValue(QPointF(0,submarine->y())); + movementAnimation->setDuration(submarine->x()/submarine->currentSpeed()*12); + } + else /*if (submarine->currentDirection() == SubMarine::Right)*/ { + movementAnimation->setEndValue(QPointF(submarine->scene()->width()-submarine->size().width(),submarine->y())); + movementAnimation->setDuration((submarine->scene()->width()-submarine->size().width()-submarine->x())/submarine->currentSpeed()*12); + } + QAnimationState::onEntry(e); + } + +private: + SubMarine *submarine; + QPropertyAnimation *movementAnimation; +}; + +//This state is describing when the boat is moving right +class ReturnState : public QAnimationState +{ +public: + ReturnState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) + { + returnAnimation = new QPropertyAnimation(submarine->rotation(), "angle"); + returnAnimation->setDuration(500); + AnimationManager::self()->registerAnimation(returnAnimation); + setAnimation(returnAnimation); + this->submarine = submarine; + } + +protected: + void onEntry(QEvent *e) + { + returnAnimation->stop(); + returnAnimation->setEndValue(submarine->currentDirection() == SubMarine::Right ? 360. : 180.); + QAnimationState::onEntry(e); + } + + void onExit(QEvent *e) + { + submarine->currentDirection() == SubMarine::Right ? submarine->setCurrentDirection(SubMarine::Left) : submarine->setCurrentDirection(SubMarine::Right); + QAnimationState::onExit(e); + } + +private: + SubMarine *submarine; + QPropertyAnimation *returnAnimation; +}; + +#endif // SUBMARINE_P_H diff --git a/examples/animation/sub-attaq/textinformationitem.cpp b/examples/animation/sub-attaq/textinformationitem.cpp new file mode 100644 index 0000000000..e2653361a1 --- /dev/null +++ b/examples/animation/sub-attaq/textinformationitem.cpp @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#include "textinformationitem.h" +#include "pixmapitem.h" + +TextInformationItem::TextInformationItem (QGraphicsItem * parent) + : QGraphicsTextItem(parent) +{ + setFont(QFont("Comic Sans MS", 15)); +} +#include +void TextInformationItem::setMessage(const QString& text) +{ + setHtml(text); + setPos(parentItem()->boundingRect().center().x() - boundingRect().size().width()/2 , parentItem()->boundingRect().center().y()); +} diff --git a/examples/animation/sub-attaq/textinformationitem.h b/examples/animation/sub-attaq/textinformationitem.h new file mode 100644 index 0000000000..4b5f71969f --- /dev/null +++ b/examples/animation/sub-attaq/textinformationitem.h @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TEXTINFORMATIONITEM_H +#define TEXTINFORMATIONITEM_H + +//Qt +#include + +class TextInformationItem : public QGraphicsTextItem +{ +public: + TextInformationItem(QGraphicsItem * parent = 0); + void setMessage(const QString& text); +}; + +#endif // TEXTINFORMATIONITEM_H diff --git a/examples/animation/sub-attaq/torpedo.cpp b/examples/animation/sub-attaq/torpedo.cpp new file mode 100644 index 0000000000..8c9bacfa38 --- /dev/null +++ b/examples/animation/sub-attaq/torpedo.cpp @@ -0,0 +1,114 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "torpedo.h" +#include "pixmapitem.h" +#include "boat.h" +#include "graphicsscene.h" +#include "animationmanager.h" +#include "qanimationstate.h" + +#include +#include +#include + +Torpedo::Torpedo() : PixmapItem(QString::fromLatin1("torpedo"),GraphicsScene::Big), + currentSpeed(0) +{ + setZValue(2); +} + +void Torpedo::launch() +{ + QPropertyAnimation *launchAnimation = new QPropertyAnimation(this, "pos"); + AnimationManager::self()->registerAnimation(launchAnimation); + launchAnimation->setEndValue(QPointF(x(),qobject_cast(scene())->sealLevel() - 15)); + launchAnimation->setEasingCurve(QEasingCurve::InQuad); + launchAnimation->setDuration(y()/currentSpeed*10); + connect(launchAnimation,SIGNAL(valueChanged(QVariant)),this,SLOT(onAnimationLaunchValueChanged(QVariant))); + connect(this,SIGNAL(torpedoExploded()), launchAnimation, SLOT(stop())); + + //We setup the state machine of the torpedo + QStateMachine *machine = new QStateMachine(this); + + //This state is when the launch animation is playing + QAnimationState *launched = new QAnimationState(machine); + launched->setAnimation(launchAnimation); + + //End + QFinalState *final = new QFinalState(machine); + + machine->setInitialState(launched); + + //### Add a nice animation when the torpedo is destroyed + launched->addTransition(this, SIGNAL(torpedoExploded()),final); + + //If the animation is finished, then we move to the final state + launched->addTransition(launched, SIGNAL(animationFinished()), final); + + //The machine has finished to be executed, then the boat is dead + connect(machine,SIGNAL(finished()),this, SIGNAL(torpedoExecutionFinished())); + + machine->start(); +} + +void Torpedo::setCurrentSpeed(int speed) +{ + if (speed < 0) { + qWarning("Torpedo::setCurrentSpeed : The speed is invalid"); + return; + } + currentSpeed = speed; +} + +void Torpedo::onAnimationLaunchValueChanged(const QVariant &) +{ + foreach (QGraphicsItem *item , collidingItems(Qt::IntersectsItemBoundingRect)) { + if (Boat *b = qgraphicsitem_cast(item)) + b->destroy(); + } +} + +void Torpedo::destroy() +{ + emit torpedoExploded(); +} diff --git a/examples/animation/sub-attaq/torpedo.h b/examples/animation/sub-attaq/torpedo.h new file mode 100644 index 0000000000..a5ec24dabf --- /dev/null +++ b/examples/animation/sub-attaq/torpedo.h @@ -0,0 +1,67 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __TORPEDO__H__ +#define __TORPEDO__H__ + +#include "pixmapitem.h" + +class Torpedo : public PixmapItem +{ +Q_OBJECT +public: + Torpedo(); + void launch(); + void setCurrentSpeed(int speed); + void destroy(); + +signals: + void torpedoExploded(); + void torpedoExecutionFinished(); + +private slots: + void onAnimationLaunchValueChanged(const QVariant &); + +private: + int currentSpeed; +}; + +#endif //__TORPEDO__H__ diff --git a/examples/embedded/digiflip/digiflip.cpp b/examples/embedded/digiflip/digiflip.cpp new file mode 100644 index 0000000000..895524355e --- /dev/null +++ b/examples/embedded/digiflip/digiflip.cpp @@ -0,0 +1,425 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +class Digits: public QWidget +{ + Q_OBJECT + +public: + + enum { + Slide, + Flip, + Rotate + }; + + Digits(QWidget *parent) + : QWidget(parent) + , m_number(0) + , m_transition(Slide) + { + setAttribute(Qt::WA_OpaquePaintEvent, true); + setAttribute(Qt::WA_NoSystemBackground, true); + connect(&m_animator, SIGNAL(frameChanged(int)), SLOT(update())); + m_animator.setFrameRange(0, 100); + m_animator.setDuration(600); + m_animator.setCurveShape(QTimeLine::EaseInOutCurve); + } + + void setTransition(int tr) { + m_transition = tr; + } + + int transition() const { + return m_transition; + } + + void setNumber(int n) { + if (m_number != n) { + m_number = qBound(0, n, 99); + preparePixmap(); + update(); + } + } + + void flipTo(int n) { + if (m_number != n) { + m_number = qBound(0, n, 99); + m_lastPixmap = m_pixmap; + preparePixmap(); + m_animator.stop(); + m_animator.start(); + } + } + +protected: + + void drawFrame(QPainter *p, const QRect &rect) { + p->setPen(Qt::NoPen); + QLinearGradient gradient(rect.topLeft(), rect.bottomLeft()); + gradient.setColorAt(0.00, QColor(245, 245, 245)); + gradient.setColorAt(0.49, QColor(192, 192, 192)); + gradient.setColorAt(0.51, QColor(245, 245, 245)); + gradient.setColorAt(1.00, QColor(192, 192, 192)); + p->setBrush(gradient); + QRect r = rect; + p->drawRoundedRect(r, 15, 15, Qt::RelativeSize); + r.adjust(1, 4, -1, -4); + p->setPen(QColor(181, 181, 181)); + p->setBrush(Qt::NoBrush); + p->drawRoundedRect(r, 15, 15, Qt::RelativeSize); + p->setPen(QColor(159, 159, 159)); + int y = rect.top() + rect.height() / 2 - 1; + p->drawLine(rect.left(), y, rect.right(), y); + } + + QPixmap drawDigits(int n, const QRect &rect) { + + int scaleFactor = 2; +#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) + if (rect.height() > 240) + scaleFactor = 1; +#endif + + QString str = QString::number(n); + if (str.length() == 1) + str.prepend("0"); + + QFont font; + font.setFamily("Helvetica"); + int fontHeight = scaleFactor * 0.55 * rect.height(); + font.setPixelSize(fontHeight); + font.setBold(true); + + QPixmap pixmap(rect.size() * scaleFactor); + pixmap.fill(Qt::transparent); + + QLinearGradient gradient(QPoint(0, 0), QPoint(0, pixmap.height())); + gradient.setColorAt(0.00, QColor(128, 128, 128)); + gradient.setColorAt(0.49, QColor(64, 64, 64)); + gradient.setColorAt(0.51, QColor(128, 128, 128)); + gradient.setColorAt(1.00, QColor(16, 16, 16)); + + QPainter p; + p.begin(&pixmap); + p.setFont(font); + QPen pen; + pen.setBrush(QBrush(gradient)); + p.setPen(pen); + p.drawText(pixmap.rect(), Qt::AlignCenter, str); + p.end(); + + return pixmap.scaledToWidth(width(), Qt::SmoothTransformation); + } + + void preparePixmap() { + m_pixmap = QPixmap(size()); + m_pixmap.fill(Qt::transparent); + QPainter p; + p.begin(&m_pixmap); + p.drawPixmap(0, 0, drawDigits(m_number, rect())); + p.end(); + } + + void resizeEvent(QResizeEvent*) { + preparePixmap(); + update(); + } + + void paintStatic() { + QPainter p(this); + p.fillRect(rect(), Qt::black); + + int pad = width() / 10; + drawFrame(&p, rect().adjusted(pad, pad, -pad, -pad)); + p.drawPixmap(0, 0, m_pixmap); + } + + void paintSlide() { + QPainter p(this); + p.fillRect(rect(), Qt::black); + + int pad = width() / 10; + QRect fr = rect().adjusted(pad, pad, -pad, -pad); + drawFrame(&p, fr); + p.setClipRect(fr); + + int y = height() * m_animator.currentFrame() / 100; + p.drawPixmap(0, y, m_lastPixmap); + p.drawPixmap(0, y - height(), m_pixmap); + } + + void paintFlip() { + QPainter p(this); +#if !defined(Q_OS_SYMBIAN) && !defined(Q_OS_WINCE_WM) + p.setRenderHint(QPainter::SmoothPixmapTransform, true); + p.setRenderHint(QPainter::Antialiasing, true); +#endif + p.fillRect(rect(), Qt::black); + + int hw = width() / 2; + int hh = height() / 2; + + // behind is the new pixmap + int pad = width() / 10; + QRect fr = rect().adjusted(pad, pad, -pad, -pad); + drawFrame(&p, fr); + p.drawPixmap(0, 0, m_pixmap); + + int index = m_animator.currentFrame(); + + if (index <= 50) { + + // the top part of the old pixmap is flipping + int angle = -180 * index / 100; + QTransform transform; + transform.translate(hw, hh); + transform.rotate(angle, Qt::XAxis); + p.setTransform(transform); + drawFrame(&p, fr.adjusted(-hw, -hh, -hw, -hh)); + p.drawPixmap(-hw, -hh, m_lastPixmap); + + // the bottom part is still the old pixmap + p.resetTransform(); + p.setClipRect(0, hh, width(), hh); + drawFrame(&p, fr); + p.drawPixmap(0, 0, m_lastPixmap); + } else { + + p.setClipRect(0, hh, width(), hh); + + // the bottom part is still the old pixmap + drawFrame(&p, fr); + p.drawPixmap(0, 0, m_lastPixmap); + + // the bottom part of the new pixmap is flipping + int angle = 180 - 180 * m_animator.currentFrame() / 100; + QTransform transform; + transform.translate(hw, hh); + transform.rotate(angle, Qt::XAxis); + p.setTransform(transform); + drawFrame(&p, fr.adjusted(-hw, -hh, -hw, -hh)); + p.drawPixmap(-hw, -hh, m_pixmap); + + } + + } + + void paintRotate() { + QPainter p(this); + + int pad = width() / 10; + QRect fr = rect().adjusted(pad, pad, -pad, -pad); + drawFrame(&p, fr); + p.setClipRect(fr); + + int angle1 = -180 * m_animator.currentFrame() / 100; + int angle2 = 180 - 180 * m_animator.currentFrame() / 100; + int angle = (m_animator.currentFrame() <= 50) ? angle1 : angle2; + QPixmap pix = (m_animator.currentFrame() <= 50) ? m_lastPixmap : m_pixmap; + + QTransform transform; + transform.translate(width() / 2, height() / 2); + transform.rotate(angle, Qt::XAxis); + + p.setTransform(transform); + p.setRenderHint(QPainter::SmoothPixmapTransform, true); + p.drawPixmap(-width() / 2, -height() / 2, pix); + } + + void paintEvent(QPaintEvent *event) { + Q_UNUSED(event); + if (m_animator.state() == QTimeLine::Running) { + if (m_transition == Slide) + paintSlide(); + if (m_transition == Flip) + paintFlip(); + if (m_transition == Rotate) + paintRotate(); + } else { + paintStatic(); + } + } + +private: + int m_number; + int m_transition; + QPixmap m_pixmap; + QPixmap m_lastPixmap; + QTimeLine m_animator; +}; + +class DigiFlip : public QMainWindow +{ + Q_OBJECT + +public: + DigiFlip(QWidget *parent = 0) + : QMainWindow(parent) + { + m_hour = new Digits(this); + m_hour->show(); + m_minute = new Digits(this); + m_minute->show(); + + QPalette pal = palette(); + pal.setColor(QPalette::Window, Qt::black); + setPalette(pal); + + m_ticker.start(1000, this); + QTime t = QTime::currentTime(); + m_hour->setNumber(t.hour()); + m_minute->setNumber(t.minute()); + updateTime(); + + QAction *slideAction = new QAction("&Slide", this); + QAction *flipAction = new QAction("&Flip", this); + QAction *rotateAction = new QAction("&Rotate", this); + connect(slideAction, SIGNAL(triggered()), SLOT(chooseSlide())); + connect(flipAction, SIGNAL(triggered()), SLOT(chooseFlip())); + connect(rotateAction, SIGNAL(triggered()), SLOT(chooseRotate())); +#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) + menuBar()->addAction(slideAction); + menuBar()->addAction(flipAction); + menuBar()->addAction(rotateAction); +#else + addAction(slideAction); + addAction(flipAction); + addAction(rotateAction); + setContextMenuPolicy(Qt::ActionsContextMenu); +#endif + } + + void updateTime() { + QTime t = QTime::currentTime(); + m_hour->flipTo(t.hour()); + m_minute->flipTo(t.minute()); + QString str = t.toString("hh:mm:ss"); + str.prepend(": "); + if (m_hour->transition() == Digits::Slide) + str.prepend("Slide"); + if (m_hour->transition() == Digits::Flip) + str.prepend("Flip"); + if (m_hour->transition() == Digits::Rotate) + str.prepend("Rotate"); + setWindowTitle(str); + } + + void switchTransition(int delta) { + int i = (m_hour->transition() + delta + 3) % 3; + m_hour->setTransition(i); + m_minute->setTransition(i); + updateTime(); + } + +protected: + void resizeEvent(QResizeEvent*) { + int digitsWidth = width() / 2; + int digitsHeight = digitsWidth * 1.2; + + int y = (height() - digitsHeight) / 3; + + m_hour->resize(digitsWidth, digitsHeight); + m_hour->move(0, y); + + m_minute->resize(digitsWidth, digitsHeight); + m_minute->move(width() / 2, y); + } + + void timerEvent(QTimerEvent*) { + updateTime(); + } + + void keyPressEvent(QKeyEvent *event) { + if (event->key() == Qt::Key_Right) { + switchTransition(1); + event->accept(); + } + if (event->key() == Qt::Key_Left) { + switchTransition(-1); + event->accept(); + } + } + +private slots: + void chooseSlide() { + m_hour->setTransition(0); + m_minute->setTransition(0); + updateTime(); + } + + void chooseFlip() { + m_hour->setTransition(1); + m_minute->setTransition(1); + updateTime(); + } + + void chooseRotate() { + m_hour->setTransition(2); + m_minute->setTransition(2); + updateTime(); + } + +private: + QBasicTimer m_ticker; + Digits *m_hour; + Digits *m_minute; +}; + +#include "digiflip.moc" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + DigiFlip time; +#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) + time.showMaximized(); +#else + time.resize(320, 240); + time.show(); +#endif + + return app.exec(); +} diff --git a/examples/embedded/digiflip/digiflip.pro b/examples/embedded/digiflip/digiflip.pro new file mode 100644 index 0000000000..7fa06fa90a --- /dev/null +++ b/examples/embedded/digiflip/digiflip.pro @@ -0,0 +1,11 @@ +SOURCES = digiflip.cpp + +symbian { + TARGET.UID3 = 0xA000CF72 + CONFIG += qt_demo +} + +target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/digiflip +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/digiflip +INSTALLS += target sources diff --git a/examples/embedded/embedded.pro b/examples/embedded/embedded.pro new file mode 100644 index 0000000000..e9a448b1e3 --- /dev/null +++ b/examples/embedded/embedded.pro @@ -0,0 +1,12 @@ +TEMPLATE = subdirs +SUBDIRS = styledemo raycasting flickable digiflip + +SUBDIRS += lightmaps +SUBDIRS += flightinfo + +# install +sources.files = README *.pro +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded +INSTALLS += sources + +symbian: CONFIG += qt_demo diff --git a/examples/embedded/flickable/flickable.cpp b/examples/embedded/flickable/flickable.cpp new file mode 100644 index 0000000000..edcc1a7396 --- /dev/null +++ b/examples/embedded/flickable/flickable.cpp @@ -0,0 +1,284 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "flickable.h" + +#include +#include + +class FlickableTicker: QObject +{ +public: + FlickableTicker(Flickable *scroller) { + m_scroller = scroller; + } + + void start(int interval) { + if (!m_timer.isActive()) + m_timer.start(interval, this); + } + + void stop() { + m_timer.stop(); + } + +protected: + void timerEvent(QTimerEvent *event) { + Q_UNUSED(event); + m_scroller->tick(); + } + +private: + Flickable *m_scroller; + QBasicTimer m_timer; +}; + +class FlickablePrivate +{ +public: + typedef enum { + Steady, + Pressed, + ManualScroll, + AutoScroll, + Stop + } State; + + State state; + int threshold; + QPoint pressPos; + QPoint offset; + QPoint delta; + QPoint speed; + FlickableTicker *ticker; + QTime timeStamp; + QWidget *target; + QList ignoreList; +}; + +Flickable::Flickable() +{ + d = new FlickablePrivate; + d->state = FlickablePrivate::Steady; + d->threshold = 10; + d->ticker = new FlickableTicker(this); + d->timeStamp = QTime::currentTime(); + d->target = 0; +} + +Flickable::~Flickable() +{ + delete d; +} + +void Flickable::setThreshold(int th) +{ + if (th >= 0) + d->threshold = th; +} + +int Flickable::threshold() const +{ + return d->threshold; +} + +void Flickable::setAcceptMouseClick(QWidget *target) +{ + d->target = target; +} + +static QPoint deaccelerate(const QPoint &speed, int a = 1, int max = 64) +{ + int x = qBound(-max, speed.x(), max); + int y = qBound(-max, speed.y(), max); + x = (x == 0) ? x : (x > 0) ? qMax(0, x - a) : qMin(0, x + a); + y = (y == 0) ? y : (y > 0) ? qMax(0, y - a) : qMin(0, y + a); + return QPoint(x, y); +} + +void Flickable::handleMousePress(QMouseEvent *event) +{ + event->ignore(); + + if (event->button() != Qt::LeftButton) + return; + + if (d->ignoreList.removeAll(event)) + return; + + switch (d->state) { + + case FlickablePrivate::Steady: + event->accept(); + d->state = FlickablePrivate::Pressed; + d->pressPos = event->pos(); + break; + + case FlickablePrivate::AutoScroll: + event->accept(); + d->state = FlickablePrivate::Stop; + d->speed = QPoint(0, 0); + d->pressPos = event->pos(); + d->offset = scrollOffset(); + d->ticker->stop(); + break; + + default: + break; + } +} + +void Flickable::handleMouseRelease(QMouseEvent *event) +{ + event->ignore(); + + if (event->button() != Qt::LeftButton) + return; + + if (d->ignoreList.removeAll(event)) + return; + + QPoint delta; + + switch (d->state) { + + case FlickablePrivate::Pressed: + event->accept(); + d->state = FlickablePrivate::Steady; + if (d->target) { + QMouseEvent *event1 = new QMouseEvent(QEvent::MouseButtonPress, + d->pressPos, Qt::LeftButton, + Qt::LeftButton, Qt::NoModifier); + QMouseEvent *event2 = new QMouseEvent(*event); + d->ignoreList << event1; + d->ignoreList << event2; + QApplication::postEvent(d->target, event1); + QApplication::postEvent(d->target, event2); + } + break; + + case FlickablePrivate::ManualScroll: + event->accept(); + delta = event->pos() - d->pressPos; + if (d->timeStamp.elapsed() > 100) { + d->timeStamp = QTime::currentTime(); + d->speed = delta - d->delta; + d->delta = delta; + } + d->offset = scrollOffset(); + d->pressPos = event->pos(); + if (d->speed == QPoint(0, 0)) { + d->state = FlickablePrivate::Steady; + } else { + d->speed /= 4; + d->state = FlickablePrivate::AutoScroll; + d->ticker->start(20); + } + break; + + case FlickablePrivate::Stop: + event->accept(); + d->state = FlickablePrivate::Steady; + d->offset = scrollOffset(); + break; + + default: + break; + } +} + +void Flickable::handleMouseMove(QMouseEvent *event) +{ + event->ignore(); + + if (!(event->buttons() & Qt::LeftButton)) + return; + + if (d->ignoreList.removeAll(event)) + return; + + QPoint delta; + + switch (d->state) { + + case FlickablePrivate::Pressed: + case FlickablePrivate::Stop: + delta = event->pos() - d->pressPos; + if (delta.x() > d->threshold || delta.x() < -d->threshold || + delta.y() > d->threshold || delta.y() < -d->threshold) { + d->timeStamp = QTime::currentTime(); + d->state = FlickablePrivate::ManualScroll; + d->delta = QPoint(0, 0); + d->pressPos = event->pos(); + event->accept(); + } + break; + + case FlickablePrivate::ManualScroll: + event->accept(); + delta = event->pos() - d->pressPos; + setScrollOffset(d->offset - delta); + if (d->timeStamp.elapsed() > 100) { + d->timeStamp = QTime::currentTime(); + d->speed = delta - d->delta; + d->delta = delta; + } + break; + + default: + break; + } +} + +void Flickable::tick() +{ + if (d->state == FlickablePrivate:: AutoScroll) { + d->speed = deaccelerate(d->speed); + setScrollOffset(d->offset - d->speed); + d->offset = scrollOffset(); + if (d->speed == QPoint(0, 0)) { + d->state = FlickablePrivate::Steady; + d->ticker->stop(); + } + } else { + d->ticker->stop(); + } +} diff --git a/examples/embedded/flickable/flickable.h b/examples/embedded/flickable/flickable.h new file mode 100644 index 0000000000..3195d3297c --- /dev/null +++ b/examples/embedded/flickable/flickable.h @@ -0,0 +1,80 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef FLICKABLE_H +#define FLICKABLE_H + +class QMouseEvent; +class QPoint; +class QWidget; + +class FlickableTicker; +class FlickablePrivate; + +class Flickable +{ +public: + + Flickable(); + virtual ~Flickable(); + + void setThreshold(int threshold); + int threshold() const; + + void setAcceptMouseClick(QWidget *target); + + void handleMousePress(QMouseEvent *event); + void handleMouseMove(QMouseEvent *event); + void handleMouseRelease(QMouseEvent *event); + +protected: + virtual QPoint scrollOffset() const = 0; + virtual void setScrollOffset(const QPoint &offset) = 0; + +private: + void tick(); + +private: + FlickablePrivate *d; + friend class FlickableTicker; +}; + +#endif // FLICKABLE_H diff --git a/examples/embedded/flickable/flickable.pro b/examples/embedded/flickable/flickable.pro new file mode 100644 index 0000000000..6ee744bc63 --- /dev/null +++ b/examples/embedded/flickable/flickable.pro @@ -0,0 +1,12 @@ +SOURCES = flickable.cpp main.cpp +HEADERS = flickable.h + +symbian { + TARGET.UID3 = 0xA000CF73 + CONFIG += qt_demo +} + +target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/flickable +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/flickable +INSTALLS += target sources diff --git a/examples/embedded/flickable/main.cpp b/examples/embedded/flickable/main.cpp new file mode 100644 index 0000000000..3711a6dc57 --- /dev/null +++ b/examples/embedded/flickable/main.cpp @@ -0,0 +1,233 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +#include "flickable.h" + +// Returns a list of two-word color names +static QStringList colorPairs(int max) +{ + // capitalize the first letter + QStringList colors = QColor::colorNames(); + colors.removeAll("transparent"); + int num = colors.count(); + for (int c = 0; c < num; ++c) + colors[c] = colors[c][0].toUpper() + colors[c].mid(1); + + // combine two colors, e.g. "lime skyblue" + QStringList combinedColors; + for (int i = 0; i < num; ++i) + for (int j = 0; j < num; ++j) + combinedColors << QString("%1 %2").arg(colors[i]).arg(colors[j]); + + // randomize it + colors.clear(); + while (combinedColors.count()) { + int i = qrand() % combinedColors.count(); + colors << combinedColors[i]; + combinedColors.removeAt(i); + if (colors.count() == max) + break; + } + + return colors; +} + +class ColorList : public QWidget, public Flickable +{ + Q_OBJECT + +public: + ColorList(QWidget *parent = 0) + : QWidget(parent) { + m_offset = 0; + m_height = QFontMetrics(font()).height() + 5; + m_highlight = -1; + m_selected = -1; + + QStringList colors = colorPairs(999); + for (int i = 0; i < colors.count(); ++i) { + QString c = colors[i]; + QString str; + str.sprintf("%4d", i + 1); + m_colorNames << (str + " " + c); + + QStringList duet = c.split(' '); + m_firstColor << duet[0]; + m_secondColor << duet[1]; + } + + setAttribute(Qt::WA_OpaquePaintEvent, true); + setAttribute(Qt::WA_NoSystemBackground, true); + + setMouseTracking(true); + Flickable::setAcceptMouseClick(this); + } + +protected: + // reimplement from Flickable + virtual QPoint scrollOffset() const { + return QPoint(0, m_offset); + } + + // reimplement from Flickable + virtual void setScrollOffset(const QPoint &offset) { + int yy = offset.y(); + if (yy != m_offset) { + m_offset = qBound(0, yy, m_height * m_colorNames.count() - height()); + update(); + } + } + +protected: + void paintEvent(QPaintEvent *event) { + QPainter p(this); + p.fillRect(event->rect(), Qt::white); + int start = m_offset / m_height; + int y = start * m_height - m_offset; + if (m_offset <= 0) { + start = 0; + y = -m_offset; + } + int end = start + height() / m_height + 1; + if (end > m_colorNames.count() - 1) + end = m_colorNames.count() - 1; + for (int i = start; i <= end; ++i, y += m_height) { + + p.setBrush(Qt::NoBrush); + p.setPen(Qt::black); + if (i == m_highlight) { + p.fillRect(0, y, width(), m_height, QColor(0, 64, 128)); + p.setPen(Qt::white); + } + if (i == m_selected) { + p.fillRect(0, y, width(), m_height, QColor(0, 128, 240)); + p.setPen(Qt::white); + } + + p.drawText(m_height + 2, y, width(), m_height, Qt::AlignVCenter, m_colorNames[i]); + + p.setPen(Qt::NoPen); + p.setBrush(m_firstColor[i]); + p.drawRect(1, y + 1, m_height - 2, m_height - 2); + p.setBrush(m_secondColor[i]); + p.drawRect(5, y + 5, m_height - 11, m_height - 11); + } + p.end(); + } + + void keyReleaseEvent(QKeyEvent *event) { + if (event->key() == Qt::Key_Down) { + m_offset += 20; + event->accept(); + update(); + return; + } + if (event->key() == Qt::Key_Up) { + m_offset -= 20; + event->accept(); + update(); + return; + } + } + + void mousePressEvent(QMouseEvent *event) { + Flickable::handleMousePress(event); + if (event->isAccepted()) + return; + + if (event->button() == Qt::LeftButton) { + int y = event->pos().y() + m_offset; + int i = y / m_height; + if (i != m_highlight) { + m_highlight = i; + m_selected = -1; + update(); + } + event->accept(); + } + } + + void mouseMoveEvent(QMouseEvent *event) { + Flickable::handleMouseMove(event); + } + + void mouseReleaseEvent(QMouseEvent *event) { + Flickable::handleMouseRelease(event); + if (event->isAccepted()) + return; + + if (event->button() == Qt::LeftButton) { + m_selected = m_highlight; + event->accept(); + update(); + } + } + +private: + int m_offset; + int m_height; + int m_highlight; + int m_selected; + QStringList m_colorNames; + QList m_firstColor; + QList m_secondColor; +}; + +#include "main.moc" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + ColorList list; + list.setWindowTitle("Kinetic Scrolling"); +#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) + list.showMaximized(); +#else + list.resize(320, 320); + list.show(); +#endif + + return app.exec(); +} diff --git a/examples/embedded/flightinfo/aircraft.png b/examples/embedded/flightinfo/aircraft.png new file mode 100644 index 0000000000..2312bcc9f0 Binary files /dev/null and b/examples/embedded/flightinfo/aircraft.png differ diff --git a/examples/embedded/flightinfo/flightinfo.cpp b/examples/embedded/flightinfo/flightinfo.cpp new file mode 100644 index 0000000000..58e71c8376 --- /dev/null +++ b/examples/embedded/flightinfo/flightinfo.cpp @@ -0,0 +1,399 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +#include "ui_form.h" + +#define FLIGHTVIEW_URL "http://mobile.flightview.com/TrackByFlight.aspx" +#define FLIGHTVIEW_RANDOM "http://mobile.flightview.com/TrackSampleFlight.aspx" + +// strips all invalid constructs that might trip QXmlStreamReader +static QString sanitized(const QString &xml) +{ + QString data = xml; + + // anything up to the html tag + int i = data.indexOf(" 0) + data.remove(0, i - 1); + + // everything inside the head tag + i = data.indexOf(" 0) + data.remove(i, data.indexOf("") - i + 7); + + // invalid link for JavaScript code + while (true) { + i = data.indexOf("onclick=\"gotoUrl("); + if (i < 0) + break; + data.remove(i, data.indexOf('\"', i + 9) - i + 1); + } + + // all inline frames + while (true) { + i = data.indexOf("") - i + 8); + } + + // entities + data.remove(" "); + data.remove("©"); + + return data; +} + +class FlightInfo : public QMainWindow +{ + Q_OBJECT + +private: + + Ui_Form ui; + QUrl m_url; + QDate m_searchDate; + QPixmap m_map; + QNetworkAccessManager m_manager; + QList mapReplies; + +public: + + FlightInfo(QMainWindow *parent = 0): QMainWindow(parent) { + + QWidget *w = new QWidget(this); + ui.setupUi(w); + setCentralWidget(w); + + ui.searchBar->hide(); + ui.infoBox->hide(); + connect(ui.searchButton, SIGNAL(clicked()), SLOT(startSearch())); + connect(ui.flightEdit, SIGNAL(returnPressed()), SLOT(startSearch())); + + setWindowTitle("Flight Info"); + + // Rendered from the public-domain vectorized aircraft + // http://openclipart.org/media/people/Jarno + m_map = QPixmap(":/aircraft.png"); + + QAction *searchTodayAction = new QAction("Today's Flight", this); + QAction *searchYesterdayAction = new QAction("Yesterday's Flight", this); + QAction *randomAction = new QAction("Random Flight", this); + connect(searchTodayAction, SIGNAL(triggered()), SLOT(today())); + connect(searchYesterdayAction, SIGNAL(triggered()), SLOT(yesterday())); + connect(randomAction, SIGNAL(triggered()), SLOT(randomFlight())); + connect(&m_manager, SIGNAL(finished(QNetworkReply*)), + this, SLOT(handleNetworkData(QNetworkReply*))); +#if defined(Q_OS_SYMBIAN) + menuBar()->addAction(searchTodayAction); + menuBar()->addAction(searchYesterdayAction); + menuBar()->addAction(randomAction); +#else + addAction(searchTodayAction); + addAction(searchYesterdayAction); + addAction(randomAction); + setContextMenuPolicy(Qt::ActionsContextMenu); +#endif + } + +private slots: + + void handleNetworkData(QNetworkReply *networkReply) { + if (!networkReply->error()) { + if (!mapReplies.contains(networkReply)) { + // Assume UTF-8 encoded + QByteArray data = networkReply->readAll(); + QString xml = QString::fromUtf8(data); + digest(xml); + } else { + mapReplies.removeOne(networkReply); + m_map.loadFromData(networkReply->readAll()); + update(); + } + } + networkReply->deleteLater(); + } + + void today() { + QDateTime timestamp = QDateTime::currentDateTime(); + m_searchDate = timestamp.date(); + searchFlight(); + } + + void yesterday() { + QDateTime timestamp = QDateTime::currentDateTime(); + timestamp = timestamp.addDays(-1); + m_searchDate = timestamp.date(); + searchFlight(); + } + + void searchFlight() { + ui.searchBar->show(); + ui.infoBox->hide(); + ui.flightStatus->hide(); + ui.flightName->setText("Enter flight number"); + ui.flightEdit->setFocus(); +#ifdef QT_KEYPAD_NAVIGATION + ui.flightEdit->setEditFocus(true); +#endif + m_map = QPixmap(); + update(); + } + + void startSearch() { + ui.searchBar->hide(); + QString flight = ui.flightEdit->text().simplified(); + if (!flight.isEmpty()) + request(flight, m_searchDate); + } + + void randomFlight() { + request(QString(), QDate::currentDate()); + } + +public slots: + + void request(const QString &flightCode, const QDate &date) { + + setWindowTitle("Loading..."); + + QString code = flightCode.simplified(); + QString airlineCode = code.left(2).toUpper(); + QString flightNumber = code.mid(2, code.length()); + + ui.flightName->setText("Searching for " + code); + + m_url = QUrl(FLIGHTVIEW_URL); + m_url.addEncodedQueryItem("view", "detail"); + m_url.addEncodedQueryItem("al", QUrl::toPercentEncoding(airlineCode)); + m_url.addEncodedQueryItem("fn", QUrl::toPercentEncoding(flightNumber)); + m_url.addEncodedQueryItem("dpdat", QUrl::toPercentEncoding(date.toString("yyyyMMdd"))); + + if (code.isEmpty()) { + // random flight as sample + m_url = QUrl(FLIGHTVIEW_RANDOM); + ui.flightName->setText("Getting a random flight..."); + } + + m_manager.get(QNetworkRequest(m_url)); + } + + +private: + + void digest(const QString &content) { + + setWindowTitle("Flight Info"); + QString data = sanitized(content); + + // do we only get the flight list? + // we grab the first leg in the flight list + // then fetch another URL for the real flight info + int i = data.indexOf("a href=\"?view=detail"); + if (i > 0) { + QString href = data.mid(i, data.indexOf('\"', i + 8) - i + 1); + QRegExp regex("dpap=([A-Za-z0-9]+)"); + regex.indexIn(href); + QString airport = regex.cap(1); + m_url.addEncodedQueryItem("dpap", QUrl::toPercentEncoding(airport)); + m_manager.get(QNetworkRequest(m_url)); + return; + } + + QXmlStreamReader xml(data); + bool inFlightName = false; + bool inFlightStatus = false; + bool inFlightMap = false; + bool inFieldName = false; + bool inFieldValue = false; + + QString flightName; + QString flightStatus; + QStringList fieldNames; + QStringList fieldValues; + + while (!xml.atEnd()) { + xml.readNext(); + + if (xml.tokenType() == QXmlStreamReader::StartElement) { + QStringRef className = xml.attributes().value("class"); + inFlightName |= xml.name() == "h1"; + inFlightStatus |= className == "FlightDetailHeaderStatus"; + inFlightMap |= className == "flightMap"; + if (xml.name() == "td" && !className.isEmpty()) { + QString cn = className.toString(); + if (cn.contains("fieldTitle")) { + inFieldName = true; + fieldNames += QString(); + fieldValues += QString(); + } + if (cn.contains("fieldValue")) + inFieldValue = true; + } + if (xml.name() == "img" && inFlightMap) { + QString src = xml.attributes().value("src").toString(); + src.prepend("http://mobile.flightview.com/"); + QUrl url = QUrl::fromPercentEncoding(src.toAscii()); + mapReplies.append(m_manager.get(QNetworkRequest(url))); + } + } + + if (xml.tokenType() == QXmlStreamReader::EndElement) { + inFlightName &= xml.name() != "h1"; + inFlightStatus &= xml.name() != "div"; + inFlightMap &= xml.name() != "div"; + inFieldName &= xml.name() != "td"; + inFieldValue &= xml.name() != "td"; + } + + if (xml.tokenType() == QXmlStreamReader::Characters) { + if (inFlightName) + flightName += xml.text(); + if (inFlightStatus) + flightStatus += xml.text(); + if (inFieldName) + fieldNames.last() += xml.text(); + if (inFieldValue) + fieldValues.last() += xml.text(); + } + } + + if (fieldNames.isEmpty()) { + QString code = ui.flightEdit->text().simplified().left(10); + QString msg = QString("Flight %1 is not found").arg(code); + ui.flightName->setText(msg); + return; + } + + ui.flightName->setText(flightName); + flightStatus.remove("Status: "); + ui.flightStatus->setText(flightStatus); + ui.flightStatus->show(); + + QStringList whiteList; + whiteList << "Departure"; + whiteList << "Arrival"; + whiteList << "Scheduled"; + whiteList << "Takeoff"; + whiteList << "Estimated"; + whiteList << "Term-Gate"; + + QString text; + text = QString("").arg(width() - 25); + for (int i = 0; i < fieldNames.count(); i++) { + QString fn = fieldNames[i].simplified(); + if (fn.endsWith(':')) + fn = fn.left(fn.length() - 1); + if (!whiteList.contains(fn)) + continue; + + QString fv = fieldValues[i].simplified(); + bool special = false; + special |= fn.startsWith("Departure"); + special |= fn.startsWith("Arrival"); + text += ""; + if (special) { + text += ""; + } else { + text += ""; + text += ""; + } + text += ""; + } + text += "
    "; + text += "" + fv + ""; + text += ""; + text += fn; + text += " : "; + text += " "; + text += ""; + text += fv; + text += "
    "; + ui.detailedInfo->setText(text); + ui.infoBox->show(); + } + + void resizeEvent(QResizeEvent *event) { + Q_UNUSED(event); + ui.detailedInfo->setMaximumWidth(width() - 25); + } + + void paintEvent(QPaintEvent *event) { + QMainWindow::paintEvent(event); + QPainter p(this); + p.fillRect(rect(), QColor(131, 171, 210)); + if (!m_map.isNull()) { + int x = (width() - m_map.width()) / 2; + int space = ui.infoBox->pos().y(); + if (!ui.infoBox->isVisible()) + space = height(); + int top = ui.titleBox->height(); + int y = qMax(top, (space - m_map.height()) / 2); + p.drawPixmap(x, y, m_map); + } + p.end(); + } + +}; + + +#include "flightinfo.moc" + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(flightinfo); + + QApplication app(argc, argv); + + FlightInfo w; +#if defined(Q_OS_SYMBIAN) + w.showMaximized(); +#else + w.resize(360, 504); + w.show(); +#endif + + return app.exec(); +} diff --git a/examples/embedded/flightinfo/flightinfo.pro b/examples/embedded/flightinfo/flightinfo.pro new file mode 100644 index 0000000000..a33423f543 --- /dev/null +++ b/examples/embedded/flightinfo/flightinfo.pro @@ -0,0 +1,17 @@ +TEMPLATE = app +TARGET = flightinfo +SOURCES = flightinfo.cpp +FORMS += form.ui +RESOURCES = flightinfo.qrc +QT += network + +symbian { + TARGET.UID3 = 0xA000CF74 + CONFIG += qt_demo + TARGET.CAPABILITY = NetworkServices +} + +target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/flightinfo +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/flightinfo +INSTALLS += target sources diff --git a/examples/embedded/flightinfo/flightinfo.qrc b/examples/embedded/flightinfo/flightinfo.qrc new file mode 100644 index 0000000000..babea7e0cb --- /dev/null +++ b/examples/embedded/flightinfo/flightinfo.qrc @@ -0,0 +1,5 @@ + + + aircraft.png + + diff --git a/examples/embedded/flightinfo/form.ui b/examples/embedded/flightinfo/form.ui new file mode 100644 index 0000000000..3a24c758a6 --- /dev/null +++ b/examples/embedded/flightinfo/form.ui @@ -0,0 +1,226 @@ + + + Form + + + + 0 + 0 + 220 + 171 + + + + Form + + + + 0 + + + 0 + + + + + QFrame { +background-color: #45629a; +} + +QLabel { +color: white; +} + + + QFrame::NoFrame + + + QFrame::Raised + + + 0 + + + + 0 + + + 4 + + + + + + 0 + 0 + + + + Powered by FlightView + + + + + + + + 0 + 0 + + + + + 75 + true + + + + background-color: white; +color: #45629a; + + + 0 + + + Ready + + + Qt::AlignCenter + + + 4 + + + + + + + + + + QFrame::NoFrame + + + QFrame::Raised + + + + 5 + + + + + color: black; +border: 1px solid black; +background: white; +selection-background-color: lightgray; + + + + + + + color: rgb(255, 255, 255); +background-color: rgb(85, 85, 255); +padding: 2px; +border: 2px solid rgb(0, 0, 127); + + + Search + + + Qt::ToolButtonTextBesideIcon + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + Qt::Vertical + + + + 20 + 58 + + + + + + + + + 0 + 0 + + + + QFrame { border: 2px solid white; +border-radius: 10px; +margin: 5px; +background-color: rgba(69, 98, 154, 192); } + + + QFrame::NoFrame + + + QFrame::Raised + + + + 0 + + + 5 + + + + + + 0 + 0 + + + + color: white; +border: none; +background-color: none; + + + + + + Qt::RichText + + + true + + + Qt::NoTextInteraction + + + + + + + + + + + diff --git a/examples/embedded/lightmaps/lightmaps.cpp b/examples/embedded/lightmaps/lightmaps.cpp new file mode 100644 index 0000000000..d672530e19 --- /dev/null +++ b/examples/embedded/lightmaps/lightmaps.cpp @@ -0,0 +1,287 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +#include + +#include "lightmaps.h" +#include "slippymap.h" + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +// how long (milliseconds) the user need to hold (after a tap on the screen) +// before triggering the magnifying glass feature +// 701, a prime number, is the sum of 229, 233, 239 +// (all three are also prime numbers, consecutive!) +#define HOLD_TIME 701 + +// maximum size of the magnifier +// Hint: see above to find why I picked this one :) +#define MAX_MAGNIFIER 229 + +LightMaps::LightMaps(QWidget *parent) + : QWidget(parent), pressed(false), snapped(false), zoomed(false), + invert(false) +{ + m_normalMap = new SlippyMap(this); + m_largeMap = new SlippyMap(this); + connect(m_normalMap, SIGNAL(updated(QRect)), SLOT(updateMap(QRect))); + connect(m_largeMap, SIGNAL(updated(QRect)), SLOT(update())); +} + +void LightMaps::setCenter(qreal lat, qreal lng) +{ + m_normalMap->latitude = lat; + m_normalMap->longitude = lng; + m_normalMap->invalidate(); + m_largeMap->latitude = lat; + m_largeMap->longitude = lng; + m_largeMap->invalidate(); +} + +void LightMaps::toggleNightMode() +{ + invert = !invert; + update(); +} + +void LightMaps::updateMap(const QRect &r) +{ + update(r); +} + +void LightMaps::activateZoom() +{ + zoomed = true; + tapTimer.stop(); + m_largeMap->zoom = m_normalMap->zoom + 1; + m_largeMap->width = m_normalMap->width * 2; + m_largeMap->height = m_normalMap->height * 2; + m_largeMap->latitude = m_normalMap->latitude; + m_largeMap->longitude = m_normalMap->longitude; + m_largeMap->invalidate(); + update(); +} + +void LightMaps::resizeEvent(QResizeEvent *) +{ + m_normalMap->width = width(); + m_normalMap->height = height(); + m_normalMap->invalidate(); + m_largeMap->width = m_normalMap->width * 2; + m_largeMap->height = m_normalMap->height * 2; + m_largeMap->invalidate(); +} + +void LightMaps::paintEvent(QPaintEvent *event) +{ + QPainter p; + p.begin(this); + m_normalMap->render(&p, event->rect()); + p.setPen(Qt::black); +#if defined(Q_OS_SYMBIAN) + QFont font = p.font(); + font.setPixelSize(13); + p.setFont(font); +#endif + p.drawText(rect(), Qt::AlignBottom | Qt::TextWordWrap, + "Map data CCBYSA 2009 OpenStreetMap.org contributors"); + p.end(); + + if (zoomed) { + int dim = qMin(width(), height()); + int magnifierSize = qMin(MAX_MAGNIFIER, dim * 2 / 3); + int radius = magnifierSize / 2; + int ring = radius - 15; + QSize box = QSize(magnifierSize, magnifierSize); + + // reupdate our mask + if (maskPixmap.size() != box) { + maskPixmap = QPixmap(box); + maskPixmap.fill(Qt::transparent); + + QRadialGradient g; + g.setCenter(radius, radius); + g.setFocalPoint(radius, radius); + g.setRadius(radius); + g.setColorAt(1.0, QColor(255, 255, 255, 0)); + g.setColorAt(0.5, QColor(128, 128, 128, 255)); + + QPainter mask(&maskPixmap); + mask.setRenderHint(QPainter::Antialiasing); + mask.setCompositionMode(QPainter::CompositionMode_Source); + mask.setBrush(g); + mask.setPen(Qt::NoPen); + mask.drawRect(maskPixmap.rect()); + mask.setBrush(QColor(Qt::transparent)); + mask.drawEllipse(g.center(), ring, ring); + mask.end(); + } + + QPoint center = dragPos - QPoint(0, radius); + center = center + QPoint(0, radius / 2); + QPoint corner = center - QPoint(radius, radius); + + QPoint xy = center * 2 - QPoint(radius, radius); + + // only set the dimension to the magnified portion + if (zoomPixmap.size() != box) { + zoomPixmap = QPixmap(box); + zoomPixmap.fill(Qt::lightGray); + } + if (true) { + QPainter p(&zoomPixmap); + p.translate(-xy); + m_largeMap->render(&p, QRect(xy, box)); + p.end(); + } + + QPainterPath clipPath; + clipPath.addEllipse(center, ring, ring); + + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + p.setClipPath(clipPath); + p.drawPixmap(corner, zoomPixmap); + p.setClipping(false); + p.drawPixmap(corner, maskPixmap); + p.setPen(Qt::gray); + p.drawPath(clipPath); + } + if (invert) { + QPainter p(this); + p.setCompositionMode(QPainter::CompositionMode_Difference); + p.fillRect(event->rect(), Qt::white); + p.end(); + } +} + +void LightMaps::timerEvent(QTimerEvent *) +{ + if (!zoomed) + activateZoom(); + update(); +} + +void LightMaps::mousePressEvent(QMouseEvent *event) +{ + if (event->buttons() != Qt::LeftButton) + return; + pressed = snapped = true; + pressPos = dragPos = event->pos(); + tapTimer.stop(); + tapTimer.start(HOLD_TIME, this); +} + +void LightMaps::mouseMoveEvent(QMouseEvent *event) +{ + if (!event->buttons()) + return; + if (!zoomed) { + if (!pressed || !snapped) { + QPoint delta = event->pos() - pressPos; + pressPos = event->pos(); + m_normalMap->pan(delta); + return; + } else { + const int threshold = 10; + QPoint delta = event->pos() - pressPos; + if (snapped) { + snapped &= delta.x() < threshold; + snapped &= delta.y() < threshold; + snapped &= delta.x() > -threshold; + snapped &= delta.y() > -threshold; + } + if (!snapped) + tapTimer.stop(); + } + } else { + dragPos = event->pos(); + update(); + } +} + +void LightMaps::mouseReleaseEvent(QMouseEvent *) +{ + zoomed = false; + update(); +} + +void LightMaps::keyPressEvent(QKeyEvent *event) +{ + if (!zoomed) { + if (event->key() == Qt::Key_Left) + m_normalMap->pan(QPoint(20, 0)); + if (event->key() == Qt::Key_Right) + m_normalMap->pan(QPoint(-20, 0)); + if (event->key() == Qt::Key_Up) + m_normalMap->pan(QPoint(0, 20)); + if (event->key() == Qt::Key_Down) + m_normalMap->pan(QPoint(0, -20)); + if (event->key() == Qt::Key_Z || event->key() == Qt::Key_Select) { + dragPos = QPoint(width() / 2, height() / 2); + activateZoom(); + } + } else { + if (event->key() == Qt::Key_Z || event->key() == Qt::Key_Select) { + zoomed = false; + update(); + } + QPoint delta(0, 0); + if (event->key() == Qt::Key_Left) + delta = QPoint(-15, 0); + if (event->key() == Qt::Key_Right) + delta = QPoint(15, 0); + if (event->key() == Qt::Key_Up) + delta = QPoint(0, -15); + if (event->key() == Qt::Key_Down) + delta = QPoint(0, 15); + if (delta != QPoint(0, 0)) { + dragPos += delta; + update(); + } + } +} diff --git a/examples/embedded/lightmaps/lightmaps.h b/examples/embedded/lightmaps/lightmaps.h new file mode 100644 index 0000000000..45b5c188a2 --- /dev/null +++ b/examples/embedded/lightmaps/lightmaps.h @@ -0,0 +1,88 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef LIGHTMAPS_H +#define LIGHTMAPS_H + +#include +#include + +class SlippyMap; + +class LightMaps: public QWidget +{ + Q_OBJECT + +public: + LightMaps(QWidget *parent = 0); + void setCenter(qreal lat, qreal lng); + +public slots: + void toggleNightMode(); + +protected: + void activateZoom(); + void resizeEvent(QResizeEvent *); + void paintEvent(QPaintEvent *event); + void timerEvent(QTimerEvent *); + void mousePressEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *); + void keyPressEvent(QKeyEvent *event); + +private slots: + void updateMap(const QRect &r); + +private: + SlippyMap *m_normalMap; + SlippyMap *m_largeMap; + bool pressed; + bool snapped; + QPoint pressPos; + QPoint dragPos; + QBasicTimer tapTimer; + bool zoomed; + QPixmap zoomPixmap; + QPixmap maskPixmap; + bool invert; +}; + +#endif \ No newline at end of file diff --git a/examples/embedded/lightmaps/lightmaps.pro b/examples/embedded/lightmaps/lightmaps.pro new file mode 100644 index 0000000000..2751c3a647 --- /dev/null +++ b/examples/embedded/lightmaps/lightmaps.pro @@ -0,0 +1,21 @@ +TEMPLATE = app +HEADERS = lightmaps.h \ + mapzoom.h \ + slippymap.h +SOURCES = lightmaps.cpp \ + main.cpp \ + mapzoom.cpp \ + slippymap.cpp +QT += network + +symbian { + TARGET.UID3 = 0xA000CF75 + CONFIG += qt_demo + TARGET.CAPABILITY = NetworkServices + TARGET.EPOCHEAPSIZE = 0x20000 0x2000000 +} + +target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/lightmaps +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/lightmaps +INSTALLS += target sources diff --git a/examples/embedded/lightmaps/main.cpp b/examples/embedded/lightmaps/main.cpp new file mode 100644 index 0000000000..85f74e638e --- /dev/null +++ b/examples/embedded/lightmaps/main.cpp @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "mapzoom.h" + +int main(int argc, char **argv) +{ +#if defined(Q_WS_X11) + QApplication::setGraphicsSystem("raster"); +#endif + + QApplication app(argc, argv); + app.setApplicationName("LightMaps"); + + MapZoom w; +#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) + w.showMaximized(); +#else + w.resize(600, 450); + w.show(); +#endif + + return app.exec(); +} diff --git a/examples/embedded/lightmaps/mapzoom.cpp b/examples/embedded/lightmaps/mapzoom.cpp new file mode 100644 index 0000000000..d01457e3f4 --- /dev/null +++ b/examples/embedded/lightmaps/mapzoom.cpp @@ -0,0 +1,147 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include "lightmaps.h" +#include "mapzoom.h" + +MapZoom::MapZoom() + : QMainWindow(0) +{ + map = new LightMaps(this); + setCentralWidget(map); + map->setFocus(); + + QAction *osloAction = new QAction(tr("&Oslo"), this); + QAction *berlinAction = new QAction(tr("&Berlin"), this); + QAction *jakartaAction = new QAction(tr("&Jakarta"), this); + QAction *nightModeAction = new QAction(tr("Night Mode"), this); + nightModeAction->setCheckable(true); + nightModeAction->setChecked(false); + QAction *osmAction = new QAction(tr("About OpenStreetMap"), this); + connect(osloAction, SIGNAL(triggered()), SLOT(chooseOslo())); + connect(berlinAction, SIGNAL(triggered()), SLOT(chooseBerlin())); + connect(jakartaAction, SIGNAL(triggered()), SLOT(chooseJakarta())); + connect(nightModeAction, SIGNAL(triggered()), map, SLOT(toggleNightMode())); + connect(osmAction, SIGNAL(triggered()), SLOT(aboutOsm())); + +#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) + menuBar()->addAction(osloAction); + menuBar()->addAction(berlinAction); + menuBar()->addAction(jakartaAction); + menuBar()->addAction(nightModeAction); + menuBar()->addAction(osmAction); +#else + QMenu *menu = menuBar()->addMenu(tr("&Options")); + menu->addAction(osloAction); + menu->addAction(berlinAction); + menu->addAction(jakartaAction); + menu->addSeparator(); + menu->addAction(nightModeAction); + menu->addAction(osmAction); +#endif + + QNetworkConfigurationManager manager; + if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) { + // Get saved network configuration + QSettings settings(QSettings::UserScope, QLatin1String("Trolltech")); + settings.beginGroup(QLatin1String("QtNetwork")); + const QString id = + settings.value(QLatin1String("DefaultNetworkConfiguration")).toString(); + settings.endGroup(); + + // If the saved network configuration is not currently discovered use the system + // default + QNetworkConfiguration config = manager.configurationFromIdentifier(id); + if ((config.state() & QNetworkConfiguration::Discovered) != + QNetworkConfiguration::Discovered) { + config = manager.defaultConfiguration(); + } + + networkSession = new QNetworkSession(config, this); + connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened())); + + networkSession->open(); + } else { + networkSession = 0; + } + + setWindowTitle(tr("Light Maps")); +} + +void MapZoom::sessionOpened() +{ + // Save the used configuration + QNetworkConfiguration config = networkSession->configuration(); + QString id; + if (config.type() == QNetworkConfiguration::UserChoice) { + id = networkSession->sessionProperty( + QLatin1String("UserChoiceConfiguration")).toString(); + } else { + id = config.identifier(); + } + + QSettings settings(QSettings::UserScope, QLatin1String("Trolltech")); + settings.beginGroup(QLatin1String("QtNetwork")); + settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id); + settings.endGroup(); +} + +void MapZoom::chooseOslo() +{ + map->setCenter(59.9138204, 10.7387413); +} + +void MapZoom::chooseBerlin() +{ + map->setCenter(52.52958999943302, 13.383053541183472); +} + +void MapZoom::chooseJakarta() +{ + map->setCenter(-6.211544, 106.845172); +} + +void MapZoom::aboutOsm() +{ + QDesktopServices::openUrl(QUrl("http://www.openstreetmap.org")); +} diff --git a/examples/embedded/lightmaps/mapzoom.h b/examples/embedded/lightmaps/mapzoom.h new file mode 100644 index 0000000000..ac70a23316 --- /dev/null +++ b/examples/embedded/lightmaps/mapzoom.h @@ -0,0 +1,69 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAPZOOM_H +#define MAPZOOM_H + +#include + +class QNetworkSession; +class LightMaps; + +class MapZoom : public QMainWindow +{ + Q_OBJECT + +public: + MapZoom(); + +private slots: + void sessionOpened(); + void chooseOslo(); + void chooseBerlin(); + void chooseJakarta(); + void aboutOsm(); + +private: + LightMaps *map; + QNetworkSession *networkSession; +}; + +#endif \ No newline at end of file diff --git a/examples/embedded/lightmaps/slippymap.cpp b/examples/embedded/lightmaps/slippymap.cpp new file mode 100644 index 0000000000..8c71f2946a --- /dev/null +++ b/examples/embedded/lightmaps/slippymap.cpp @@ -0,0 +1,213 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include +#include +#include "slippymap.h" + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +uint qHash(const QPoint& p) +{ + return p.x() * 17 ^ p.y(); +} + +// tile size in pixels +const int tdim = 256; + +QPointF tileForCoordinate(qreal lat, qreal lng, int zoom) +{ + qreal zn = static_cast(1 << zoom); + qreal tx = (lng + 180.0) / 360.0; + qreal ty = (1.0 - log(tan(lat * M_PI / 180.0) + + 1.0 / cos(lat * M_PI / 180.0)) / M_PI) / 2.0; + return QPointF(tx * zn, ty * zn); +} + +qreal longitudeFromTile(qreal tx, int zoom) +{ + qreal zn = static_cast(1 << zoom); + qreal lat = tx / zn * 360.0 - 180.0; + return lat; +} + +qreal latitudeFromTile(qreal ty, int zoom) +{ + qreal zn = static_cast(1 << zoom); + qreal n = M_PI - 2 * M_PI * ty / zn; + qreal lng = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n))); + return lng; +} + + +SlippyMap::SlippyMap(QObject *parent) + : QObject(parent), width(400), height(300), zoom(15), + latitude(59.9138204), longitude(10.7387413) +{ + m_emptyTile = QPixmap(tdim, tdim); + m_emptyTile.fill(Qt::lightGray); + + QNetworkDiskCache *cache = new QNetworkDiskCache; + cache->setCacheDirectory(QDesktopServices::storageLocation + (QDesktopServices::CacheLocation)); + m_manager.setCache(cache); + connect(&m_manager, SIGNAL(finished(QNetworkReply*)), + this, SLOT(handleNetworkData(QNetworkReply*))); +} + +void SlippyMap::invalidate() +{ + if (width <= 0 || height <= 0) + return; + + QPointF ct = tileForCoordinate(latitude, longitude, zoom); + qreal tx = ct.x(); + qreal ty = ct.y(); + + // top-left corner of the center tile + int xp = width / 2 - (tx - floor(tx)) * tdim; + int yp = height / 2 - (ty - floor(ty)) * tdim; + + // first tile vertical and horizontal + int xa = (xp + tdim - 1) / tdim; + int ya = (yp + tdim - 1) / tdim; + int xs = static_cast(tx) - xa; + int ys = static_cast(ty) - ya; + + // offset for top-left tile + m_offset = QPoint(xp - xa * tdim, yp - ya * tdim); + + // last tile vertical and horizontal + int xe = static_cast(tx) + (width - xp - 1) / tdim; + int ye = static_cast(ty) + (height - yp - 1) / tdim; + + // build a rect + m_tilesRect = QRect(xs, ys, xe - xs + 1, ye - ys + 1); + + if (m_url.isEmpty()) + download(); + + emit updated(QRect(0, 0, width, height)); +} + +void SlippyMap::render(QPainter *p, const QRect &rect) +{ + for (int x = 0; x <= m_tilesRect.width(); ++x) + for (int y = 0; y <= m_tilesRect.height(); ++y) { + QPoint tp(x + m_tilesRect.left(), y + m_tilesRect.top()); + QRect box = tileRect(tp); + if (rect.intersects(box)) { + if (m_tilePixmaps.contains(tp)) + p->drawPixmap(box, m_tilePixmaps.value(tp)); + else + p->drawPixmap(box, m_emptyTile); + } + } +} + +void SlippyMap::pan(const QPoint &delta) +{ + QPointF dx = QPointF(delta) / qreal(tdim); + QPointF center = tileForCoordinate(latitude, longitude, zoom) - dx; + latitude = latitudeFromTile(center.y(), zoom); + longitude = longitudeFromTile(center.x(), zoom); + invalidate(); +} + +void SlippyMap::handleNetworkData(QNetworkReply *reply) +{ + QImage img; + QPoint tp = reply->request().attribute(QNetworkRequest::User).toPoint(); + QUrl url = reply->url(); + if (!reply->error()) + if (!img.load(reply, 0)) + img = QImage(); + reply->deleteLater(); + m_tilePixmaps[tp] = QPixmap::fromImage(img); + if (img.isNull()) + m_tilePixmaps[tp] = m_emptyTile; + emit updated(tileRect(tp)); + + // purge unused spaces + QRect bound = m_tilesRect.adjusted(-2, -2, 2, 2); + foreach(QPoint tp, m_tilePixmaps.keys()) + if (!bound.contains(tp)) + m_tilePixmaps.remove(tp); + + download(); +} + +void SlippyMap::download() +{ + QPoint grab(0, 0); + for (int x = 0; x <= m_tilesRect.width(); ++x) + for (int y = 0; y <= m_tilesRect.height(); ++y) { + QPoint tp = m_tilesRect.topLeft() + QPoint(x, y); + if (!m_tilePixmaps.contains(tp)) { + grab = tp; + break; + } + } + if (grab == QPoint(0, 0)) { + m_url = QUrl(); + return; + } + + QString path = "http://tile.openstreetmap.org/%1/%2/%3.png"; + m_url = QUrl(path.arg(zoom).arg(grab.x()).arg(grab.y())); + QNetworkRequest request; + request.setUrl(m_url); + request.setRawHeader("User-Agent", "Nokia (Qt) Graphics Dojo 1.0"); + request.setAttribute(QNetworkRequest::User, QVariant(grab)); + m_manager.get(request); +} + +QRect SlippyMap::tileRect(const QPoint &tp) +{ + QPoint t = tp - m_tilesRect.topLeft(); + int x = t.x() * tdim + m_offset.x(); + int y = t.y() * tdim + m_offset.y(); + return QRect(x, y, tdim, tdim); +} diff --git a/examples/embedded/lightmaps/slippymap.h b/examples/embedded/lightmaps/slippymap.h new file mode 100644 index 0000000000..64ba5c3e59 --- /dev/null +++ b/examples/embedded/lightmaps/slippymap.h @@ -0,0 +1,87 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SLIPPYMAP_H +#define SLIPPYMAP_H + +#include +#include +#include + +class QNetworkReply; +class QPainter; + +class SlippyMap: public QObject +{ + Q_OBJECT + +public: + SlippyMap(QObject *parent = 0); + void invalidate(); + void render(QPainter *p, const QRect &rect); + void pan(const QPoint &delta); + + int width; + int height; + int zoom; + qreal latitude; + qreal longitude; + +signals: + void updated(const QRect &rect); + +private slots: + void handleNetworkData(QNetworkReply *reply); + void download(); + +protected: + QRect tileRect(const QPoint &tp); + +private: + QPoint m_offset; + QRect m_tilesRect; + QPixmap m_emptyTile; + QHash m_tilePixmaps; + QNetworkAccessManager m_manager; + QUrl m_url; +}; + +#endif \ No newline at end of file diff --git a/examples/embedded/raycasting/raycasting.cpp b/examples/embedded/raycasting/raycasting.cpp new file mode 100644 index 0000000000..d404044a9a --- /dev/null +++ b/examples/embedded/raycasting/raycasting.cpp @@ -0,0 +1,391 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +#define WORLD_SIZE 8 +int world_map[WORLD_SIZE][WORLD_SIZE] = { + { 1, 1, 1, 1, 6, 1, 1, 1 }, + { 1, 0, 0, 1, 0, 0, 0, 7 }, + { 1, 1, 0, 1, 0, 1, 1, 1 }, + { 6, 0, 0, 0, 0, 0, 0, 3 }, + { 1, 8, 8, 0, 8, 0, 8, 1 }, + { 2, 2, 0, 0, 8, 8, 7, 1 }, + { 3, 0, 0, 0, 0, 0, 0, 5 }, + { 2, 2, 2, 2, 7, 4, 4, 4 }, +}; + +#define TEXTURE_SIZE 64 +#define TEXTURE_BLOCK (TEXTURE_SIZE * TEXTURE_SIZE) + +class Raycasting: public QWidget +{ +public: + Raycasting(QWidget *parent = 0) + : QWidget(parent) + , angle(0.5) + , playerPos(1.5, 1.5) + , angleDelta(0) + , moveDelta(0) + , touchDevice(false) { + + // http://www.areyep.com/RIPandMCS-TextureLibrary.html + textureImg.load(":/textures.png"); + textureImg = textureImg.convertToFormat(QImage::Format_ARGB32); + Q_ASSERT(textureImg.width() == TEXTURE_SIZE * 2); + Q_ASSERT(textureImg.bytesPerLine() == 4 * TEXTURE_SIZE * 2); + textureCount = textureImg.height() / TEXTURE_SIZE; + + watch.start(); + ticker.start(25, this); + setAttribute(Qt::WA_OpaquePaintEvent, true); + setMouseTracking(false); + } + + void updatePlayer() { + int interval = qBound(20, watch.elapsed(), 250); + watch.start(); + angle += angleDelta * interval / 1000; + qreal step = moveDelta * interval / 1000; + qreal dx = cos(angle) * step; + qreal dy = sin(angle) * step; + QPointF pos = playerPos + 3 * QPointF(dx, dy); + int xi = static_cast(pos.x()); + int yi = static_cast(pos.y()); + if (world_map[yi][xi] == 0) + playerPos = playerPos + QPointF(dx, dy); + } + + void showFps() { + static QTime frameTick; + static int totalFrame = 0; + if (!(totalFrame & 31)) { + int elapsed = frameTick.elapsed(); + frameTick.start(); + int fps = 32 * 1000 / (1 + elapsed); + setWindowTitle(QString("Raycasting (%1 FPS)").arg(fps)); + } + totalFrame++; + } + + void render() { + + // setup the screen surface + if (buffer.size() != bufferSize) + buffer = QImage(bufferSize, QImage::Format_ARGB32); + int bufw = buffer.width(); + int bufh = buffer.height(); + if (bufw <= 0 || bufh <= 0) + return; + + // we intentionally cheat here, to avoid detach + const uchar *ptr = buffer.bits(); + QRgb *start = (QRgb*)(ptr); + QRgb stride = buffer.bytesPerLine() / 4; + QRgb *finish = start + stride * bufh; + + // prepare the texture pointer + const uchar *src = textureImg.bits(); + const QRgb *texsrc = reinterpret_cast(src); + + // cast all rays here + qreal sina = sin(angle); + qreal cosa = cos(angle); + qreal u = cosa - sina; + qreal v = sina + cosa; + qreal du = 2 * sina / bufw; + qreal dv = -2 * cosa / bufw; + + for (int ray = 0; ray < bufw; ++ray, u += du, v += dv) { + // every time this ray advances 'u' units in x direction, + // it also advanced 'v' units in y direction + qreal uu = (u < 0) ? -u : u; + qreal vv = (v < 0) ? -v : v; + qreal duu = 1 / uu; + qreal dvv = 1 / vv; + int stepx = (u < 0) ? -1 : 1; + int stepy = (v < 0) ? -1 : 1; + + // the cell in the map that we need to check + qreal px = playerPos.x(); + qreal py = playerPos.y(); + int mapx = static_cast(px); + int mapy = static_cast(py); + + // the position and texture for the hit + int texture = 0; + qreal hitdist = 0.1; + qreal texofs = 0; + bool dark = false; + + // first hit at constant x and constant y lines + qreal distx = (u > 0) ? (mapx + 1 - px) * duu : (px - mapx) * duu; + qreal disty = (v > 0) ? (mapy + 1 - py) * dvv : (py - mapy) * dvv; + + // loop until we hit something + while (texture <= 0) { + if (distx > disty) { + // shorter distance to a hit in constant y line + hitdist = disty; + disty += dvv; + mapy += stepy; + texture = world_map[mapy][mapx]; + if (texture > 0) { + dark = true; + if (stepy > 0) { + qreal ofs = px + u * (mapy - py) / v; + texofs = ofs - floor(ofs); + } else { + qreal ofs = px + u * (mapy + 1 - py) / v; + texofs = ofs - floor(ofs); + } + } + } else { + // shorter distance to a hit in constant x line + hitdist = distx; + distx += duu; + mapx += stepx; + texture = world_map[mapy][mapx]; + if (texture > 0) { + if (stepx > 0) { + qreal ofs = py + v * (mapx - px) / u; + texofs = ofs - floor(ofs); + } else { + qreal ofs = py + v * (mapx + 1 - px) / u; + texofs = ceil(ofs) - ofs; + } + } + } + } + + // get the texture, note that the texture image + // has two textures horizontally, "normal" vs "dark" + int col = static_cast(texofs * TEXTURE_SIZE); + col = qBound(0, col, TEXTURE_SIZE - 1); + texture = (texture - 1) % textureCount; + const QRgb *tex = texsrc + TEXTURE_BLOCK * texture * 2 + + (TEXTURE_SIZE * 2 * col); + if (dark) + tex += TEXTURE_SIZE; + + // start from the texture center (horizontally) + int h = static_cast(bufw / hitdist / 2); + int dy = (TEXTURE_SIZE << 12) / h; + int p1 = ((TEXTURE_SIZE / 2) << 12) - dy; + int p2 = p1 + dy; + + // start from the screen center (vertically) + // y1 will go up (decrease), y2 will go down (increase) + int y1 = bufh / 2; + int y2 = y1 + 1; + QRgb *pixel1 = start + y1 * stride + ray; + QRgb *pixel2 = pixel1 + stride; + + // map the texture to the sliver + while (y1 >= 0 && y2 < bufh && p1 >= 0) { + *pixel1 = tex[p1 >> 12]; + *pixel2 = tex[p2 >> 12]; + p1 -= dy; + p2 += dy; + --y1; + ++y2; + pixel1 -= stride; + pixel2 += stride; + } + + // ceiling and floor + for (; pixel1 > start; pixel1 -= stride) + *pixel1 = qRgb(0, 0, 0); + for (; pixel2 < finish; pixel2 += stride) + *pixel2 = qRgb(96, 96, 96); + } + + update(QRect(QPoint(0, 0), bufferSize)); + } + +protected: + + void resizeEvent(QResizeEvent*) { +#if defined(Q_OS_WINCE_WM) + touchDevice = true; +#elif defined(Q_OS_SYMBIAN) + // FIXME: use HAL + if (width() > 480 || height() > 480) + touchDevice = true; +#else + touchDevice = false; +#endif + if (touchDevice) { + if (width() < height()) { + trackPad = QRect(0, height() / 2, width(), height() / 2); + centerPad = QPoint(width() / 2, height() * 3 / 4); + bufferSize = QSize(width(), height() / 2); + } else { + trackPad = QRect(width() / 2, 0, width() / 2, height()); + centerPad = QPoint(width() * 3 / 4, height() / 2); + bufferSize = QSize(width() / 2, height()); + } + } else { + trackPad = QRect(); + bufferSize = size(); + } + update(); + } + + void timerEvent(QTimerEvent*) { + updatePlayer(); + render(); + showFps(); + } + + void paintEvent(QPaintEvent *event) { + QPainter p(this); + p.setCompositionMode(QPainter::CompositionMode_Source); + + p.drawImage(event->rect(), buffer, event->rect()); + + if (touchDevice && event->rect().intersects(trackPad)) { + p.fillRect(trackPad, Qt::white); + p.setPen(QPen(QColor(224, 224, 224), 6)); + int rad = qMin(trackPad.width(), trackPad.height()) * 0.3; + p.drawEllipse(centerPad, rad, rad); + + p.setPen(Qt::NoPen); + p.setBrush(Qt::gray); + + QPolygon poly; + poly << QPoint(-30, 0); + poly << QPoint(0, -40); + poly << QPoint(30, 0); + + p.translate(centerPad); + for (int i = 0; i < 4; ++i) { + p.rotate(90); + p.translate(0, 20 - rad); + p.drawPolygon(poly); + p.translate(0, rad - 20); + } + } + + p.end(); + } + + void keyPressEvent(QKeyEvent *event) { + event->accept(); + if (event->key() == Qt::Key_Left) + angleDelta = 1.3 * M_PI; + if (event->key() == Qt::Key_Right) + angleDelta = -1.3 * M_PI; + if (event->key() == Qt::Key_Up) + moveDelta = 2.5; + if (event->key() == Qt::Key_Down) + moveDelta = -2.5; + } + + void keyReleaseEvent(QKeyEvent *event) { + event->accept(); + if (event->key() == Qt::Key_Left) + angleDelta = (angleDelta > 0) ? 0 : angleDelta; + if (event->key() == Qt::Key_Right) + angleDelta = (angleDelta < 0) ? 0 : angleDelta; + if (event->key() == Qt::Key_Up) + moveDelta = (moveDelta > 0) ? 0 : moveDelta; + if (event->key() == Qt::Key_Down) + moveDelta = (moveDelta < 0) ? 0 : moveDelta; + } + + void mousePressEvent(QMouseEvent *event) { + qreal dx = centerPad.x() - event->pos().x(); + qreal dy = centerPad.y() - event->pos().y(); + angleDelta = dx * 2 * M_PI / width(); + moveDelta = dy * 10 / height(); + } + + void mouseMoveEvent(QMouseEvent *event) { + qreal dx = centerPad.x() - event->pos().x(); + qreal dy = centerPad.y() - event->pos().y(); + angleDelta = dx * 2 * M_PI / width(); + moveDelta = dy * 10 / height(); + } + + void mouseReleaseEvent(QMouseEvent*) { + angleDelta = 0; + moveDelta = 0; + } + +private: + QTime watch; + QBasicTimer ticker; + QImage buffer; + qreal angle; + QPointF playerPos; + qreal angleDelta; + qreal moveDelta; + QImage textureImg; + int textureCount; + bool touchDevice; + QRect trackPad; + QPoint centerPad; + QSize bufferSize; +}; + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + Raycasting w; + w.setWindowTitle("Raycasting"); +#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) + w.showMaximized(); +#else + w.resize(640, 480); + w.show(); +#endif + + return app.exec(); +} diff --git a/examples/embedded/raycasting/raycasting.pro b/examples/embedded/raycasting/raycasting.pro new file mode 100644 index 0000000000..a4bb1826b9 --- /dev/null +++ b/examples/embedded/raycasting/raycasting.pro @@ -0,0 +1,13 @@ +TEMPLATE = app +SOURCES = raycasting.cpp +RESOURCES += raycasting.qrc + +symbian { + TARGET.UID3 = 0xA000CF76 + CONFIG += qt_demo +} + +target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/raycasting +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/raycasting +INSTALLS += target sources diff --git a/examples/embedded/raycasting/raycasting.qrc b/examples/embedded/raycasting/raycasting.qrc new file mode 100644 index 0000000000..974a06093c --- /dev/null +++ b/examples/embedded/raycasting/raycasting.qrc @@ -0,0 +1,5 @@ + + + textures.png + + diff --git a/examples/embedded/raycasting/textures.png b/examples/embedded/raycasting/textures.png new file mode 100644 index 0000000000..2eb1ba7ff6 Binary files /dev/null and b/examples/embedded/raycasting/textures.png differ diff --git a/examples/embedded/styledemo/files/add.png b/examples/embedded/styledemo/files/add.png new file mode 100755 index 0000000000..fc5c16d4c8 Binary files /dev/null and b/examples/embedded/styledemo/files/add.png differ diff --git a/examples/embedded/styledemo/files/application.qss b/examples/embedded/styledemo/files/application.qss new file mode 100644 index 0000000000..432fe6bc76 --- /dev/null +++ b/examples/embedded/styledemo/files/application.qss @@ -0,0 +1,125 @@ +QWidget#StyleWidget +{ + background-color: none; + background-image: url(icons:nature_1.jpg); +} + +QLabel, QAbstractButton +{ + font: bold; + color: beige; +} + +QAbstractButton +{ + background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(173,216,230,60%), stop:1 rgba(0,0,139,60%) ); + border-color: black; + border-style: solid; + border-width: 3px; + border-radius: 6px; +} + +QAbstractButton:pressed, QAbstractButton:checked +{ + background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0,0,139,60%), stop:1 rgba(173,216,230,60%) ); +} + +QSpinBox { + padding-left: 24px; + padding-right: 24px; + border-color: darkkhaki; + border-style: solid; + border-radius: 5; + border-width: 3; +} + +QSpinBox::up-button +{ + subcontrol-origin: padding; + subcontrol-position: right; /* position at the top right corner */ + width: 24px; + height: 24px; + border-width: 3px; + +} + +QSpinBox::up-arrow +{ + image: url(icons:add.png); + width: 18px; + height: 18px; +} + + +QSpinBox::down-button +{ + subcontrol-origin: border; + subcontrol-position: left; + width: 24px; + height: 24px; + border-width: 3px; +} + +QSpinBox::down-arrow +{ + image: url(icons:remove.png); + width: 18px; + height: 18px; +} + + +QScrollBar:horizontal +{ + border: 1px solid black; + background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0,0,139,60%), stop:1 rgba(173,216,230,60%) ); + height: 15px; + margin: 0px 20px 0 20px; +} + +QScrollBar::handle:horizontal +{ + border: 1px solid black; + background: rgba(0,0,139,60%); + min-width: 20px; +} + +QScrollBar::add-line:horizontal +{ + border: 1px solid black; + background: rgba(0,0,139,60%); + width: 20px; + subcontrol-position: right; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:horizontal +{ + border: 1px solid black; + background: rgba(0,0,139,60%); + width: 20px; + subcontrol-position: left; + subcontrol-origin: margin; +} + +QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal +{ + border: none; + width: 16px; + height: 16px; +} + +QScrollBar:left-arrow:horizontal +{ + image: url(icons:add.png) +} + +QScrollBar::right-arrow:horizontal +{ + image: url(icons:remove.png) +} + +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal +{ + background: none; +} + diff --git a/examples/embedded/styledemo/files/blue.qss b/examples/embedded/styledemo/files/blue.qss new file mode 100644 index 0000000000..ac8671b5e4 --- /dev/null +++ b/examples/embedded/styledemo/files/blue.qss @@ -0,0 +1,38 @@ +* +{ + color: beige; +} + +QLabel, QAbstractButton +{ + font: bold; + color: yellow; +} + +QFrame +{ + background-color: rgba(96,96,255,60%); + border-color: rgb(32,32,196); + border-width: 3px; + border-style: solid; + border-radius: 5; + padding: 3px; +} + +QAbstractButton +{ + background: qlineargradient(x1:0, y1:0, x2:0, y2:1, + stop:0 lightblue, stop:0.5 darkblue); + border-width: 3px; + border-color: darkblue; + border-style: solid; + border-radius: 5; + padding: 3px; +} + +QAbstractButton:pressed +{ + background: qlineargradient(x1:0, y1:0, x2:0, y2:1, + stop:0.5 darkblue, stop:1 lightblue); + border-color: beige; +} diff --git a/examples/embedded/styledemo/files/khaki.qss b/examples/embedded/styledemo/files/khaki.qss new file mode 100644 index 0000000000..b0d4a0fa6f --- /dev/null +++ b/examples/embedded/styledemo/files/khaki.qss @@ -0,0 +1,99 @@ + +QWidget#StartScreen, QWidget#MainWidget { + border: none; +} + +QWidget#StartScreen, .QFrame { + background-color: beige; +} + +QPushButton, QToolButton { + background-color: palegoldenrod; + border-width: 2px; + border-color: darkkhaki; + border-style: solid; + border-radius: 5; + padding: 3px; + /* min-width: 96px; */ + /* min-height: 48px; */ +} + +QPushButton:hover, QToolButton:hover { + background-color: khaki; +} + +QPushButton:pressed, QToolButton:pressed { + padding-left: 5px; + padding-top: 5px; + background-color: #d0d67c; +} + +QLabel, QAbstractButton { + font: italic "Times New Roman"; +} + +QFrame, QLabel#title { + border-width: 2px; + padding: 1px; + border-style: solid; + border-color: darkkhaki; + border-radius: 5px; +} + +QFrame:focus { + border-width: 3px; + padding: 0px; +} + + +QLabel { + border: none; + padding: 0; + background: none; +} + +QLabel#title { + font: 32px bold; +} + +QSpinBox { + padding-left: 24px; + padding-right: 24px; + border-color: darkkhaki; + border-style: solid; + border-radius: 5; + border-width: 3; +} + +QSpinBox::up-button +{ + subcontrol-origin: padding; + subcontrol-position: right; /* position at the top right corner */ + width: 24px; + height: 24px; + border-width: 3px; + border-image: url(:/files/spindownpng) 1; +} + +QSpinBox::up-arrow { + image: url(:/files/add.png); + width: 12px; + height: 12px; + } + + +QSpinBox::down-button +{ + subcontrol-origin: border; + subcontrol-position: left; + width: 24px; + height: 24px; + border-width: 3px; + border-image: url(:/files/spindownpng) 1; +} + +QSpinBox::down-arrow { + image: url(:/files/remove.png); + width: 12px; + height: 12px; + } diff --git a/examples/embedded/styledemo/files/nature_1.jpg b/examples/embedded/styledemo/files/nature_1.jpg new file mode 100644 index 0000000000..3a04edb96a Binary files /dev/null and b/examples/embedded/styledemo/files/nature_1.jpg differ diff --git a/examples/embedded/styledemo/files/nostyle.qss b/examples/embedded/styledemo/files/nostyle.qss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/examples/embedded/styledemo/files/remove.png b/examples/embedded/styledemo/files/remove.png new file mode 100755 index 0000000000..a0ab1fa21a Binary files /dev/null and b/examples/embedded/styledemo/files/remove.png differ diff --git a/examples/embedded/styledemo/files/transparent.qss b/examples/embedded/styledemo/files/transparent.qss new file mode 100644 index 0000000000..b38eb366f4 --- /dev/null +++ b/examples/embedded/styledemo/files/transparent.qss @@ -0,0 +1,139 @@ +QWidget#StyleWidget +{ + background-color: none; + background-image: url(:/files/nature_1.jpg); +} + +QLabel, QAbstractButton +{ + color: beige; +} + +QFrame, QLabel#title { + border-width: 2px; + padding: 1px; + border-style: solid; + border-color: black; + border-radius: 5px; +} + +QFrame:focus { + border-width: 3px; + padding: 0px; +} + + + +QAbstractButton +{ + background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(173,216,230,60%), stop:1 rgba(0,0,139,60%) ); + border-color: black; + border-style: solid; + border-width: 3px; + border-radius: 6px; +} + +QAbstractButton:pressed, QAbstractButton:checked +{ + background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0,0,139,60%), stop:1 rgba(173,216,230,60%) ); +} + +QSpinBox { + padding-left: 24px; + padding-right: 24px; + border-color: darkkhaki; + border-style: solid; + border-radius: 5; + border-width: 3; +} + +QSpinBox::up-button +{ + subcontrol-origin: padding; + subcontrol-position: right; /* position at the top right corner */ + width: 24px; + height: 24px; + border-width: 3px; + +} + +QSpinBox::up-arrow +{ + image: url(:/files/add.png); + width: 18px; + height: 18px; +} + + +QSpinBox::down-button +{ + subcontrol-origin: border; + subcontrol-position: left; + width: 24px; + height: 24px; + border-width: 3px; +} + +QSpinBox::down-arrow +{ + image: url(:/files/remove.png); + width: 18px; + height: 18px; +} + + +QScrollBar:horizontal +{ + border: 1px solid black; + background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0,0,139,60%), stop:1 rgba(173,216,230,60%) ); + height: 15px; + margin: 0px 20px 0 20px; +} + +QScrollBar::handle:horizontal +{ + border: 1px solid black; + background: rgba(0,0,139,60%); + min-width: 20px; +} + +QScrollBar::add-line:horizontal +{ + border: 1px solid black; + background: rgba(0,0,139,60%); + width: 20px; + subcontrol-position: right; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:horizontal +{ + border: 1px solid black; + background: rgba(0,0,139,60%); + width: 20px; + subcontrol-position: left; + subcontrol-origin: margin; +} + +QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal +{ + border: none; + width: 16px; + height: 16px; +} + +QScrollBar:left-arrow:horizontal +{ + image: url(:/files/add.png) +} + +QScrollBar::right-arrow:horizontal +{ + image: url(:/files/remove.png) +} + +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal +{ + background: none; +} + diff --git a/examples/embedded/styledemo/main.cpp b/examples/embedded/styledemo/main.cpp new file mode 100644 index 0000000000..7a484b0365 --- /dev/null +++ b/examples/embedded/styledemo/main.cpp @@ -0,0 +1,59 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#include + +#include "stylewidget.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + Q_INIT_RESOURCE(styledemo); + + app.setApplicationName("style"); + app.setOrganizationName("Nokia"); + app.setOrganizationDomain("com.nokia.qt"); + + StyleWidget widget; + widget.showFullScreen(); + + return app.exec(); +} + diff --git a/examples/embedded/styledemo/styledemo.pro b/examples/embedded/styledemo/styledemo.pro new file mode 100644 index 0000000000..60700dd1df --- /dev/null +++ b/examples/embedded/styledemo/styledemo.pro @@ -0,0 +1,17 @@ +TEMPLATE = app + +# Input +HEADERS += stylewidget.h +FORMS += stylewidget.ui +SOURCES += main.cpp stylewidget.cpp +RESOURCES += styledemo.qrc + +target.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/styledemo +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro *.html +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embedded/styledemo +INSTALLS += target sources + +symbian { + TARGET.UID3 = 0xA000A63F + CONFIG += qt_demo +} diff --git a/examples/embedded/styledemo/styledemo.qrc b/examples/embedded/styledemo/styledemo.qrc new file mode 100644 index 0000000000..96237d4203 --- /dev/null +++ b/examples/embedded/styledemo/styledemo.qrc @@ -0,0 +1,13 @@ + + + files/add.png + files/blue.qss + files/khaki.qss + files/nostyle.qss + files/transparent.qss + files/application.qss + files/nature_1.jpg + files/remove.png + + + diff --git a/examples/embedded/styledemo/stylewidget.cpp b/examples/embedded/styledemo/stylewidget.cpp new file mode 100644 index 0000000000..7bac8a84d7 --- /dev/null +++ b/examples/embedded/styledemo/stylewidget.cpp @@ -0,0 +1,112 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#include +#include +#include + +#include "stylewidget.h" + + + +StyleWidget::StyleWidget(QWidget *parent) + : QFrame(parent) +{ + m_ui.setupUi(this); +} + + +void StyleWidget::on_close_clicked() +{ + close(); +} + +void StyleWidget::on_blueStyle_clicked() +{ + QFile styleSheet(":/files/blue.qss"); + + if (!styleSheet.open(QIODevice::ReadOnly)) { + qWarning("Unable to open :/files/blue.qss"); + return; + } + + qApp->setStyleSheet(styleSheet.readAll()); +} + +void StyleWidget::on_khakiStyle_clicked() +{ + QFile styleSheet(":/files/khaki.qss"); + + if (!styleSheet.open(QIODevice::ReadOnly)) { + qWarning("Unable to open :/files/khaki.qss"); + return; + } + + qApp->setStyleSheet(styleSheet.readAll()); +} + + +void StyleWidget::on_noStyle_clicked() +{ + QFile styleSheet(":/files/nostyle.qss"); + + if (!styleSheet.open(QIODevice::ReadOnly)) { + qWarning("Unable to open :/files/nostyle.qss"); + return; + } + + qApp->setStyleSheet(styleSheet.readAll()); +} + + +void StyleWidget::on_transparentStyle_clicked() +{ + QFile styleSheet(":/files/transparent.qss"); + + if (!styleSheet.open(QIODevice::ReadOnly)) { + qWarning("Unable to open :/files/transparent.qss"); + return; + } + + qApp->setStyleSheet(styleSheet.readAll()); +} + + + diff --git a/examples/embedded/styledemo/stylewidget.h b/examples/embedded/styledemo/stylewidget.h new file mode 100644 index 0000000000..11fa5348de --- /dev/null +++ b/examples/embedded/styledemo/stylewidget.h @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#ifndef STYLEWIDGET_H +#define STYLEWIDGET_H + +#include + +#include "ui_stylewidget.h" + +class StyleWidget : public QFrame +{ + Q_OBJECT +public: + StyleWidget(QWidget *parent = 0); + +private: + Ui_StyleWidget m_ui; + +private slots: + void on_close_clicked(); + void on_blueStyle_clicked(); + void on_khakiStyle_clicked(); + void on_noStyle_clicked(); + void on_transparentStyle_clicked(); +}; + +#endif diff --git a/examples/embedded/styledemo/stylewidget.ui b/examples/embedded/styledemo/stylewidget.ui new file mode 100644 index 0000000000..767f44aead --- /dev/null +++ b/examples/embedded/styledemo/stylewidget.ui @@ -0,0 +1,417 @@ + + + StyleWidget + + + + 0 + 0 + 184 + 245 + + + + Form + + + + + + Styles + + + + 4 + + + 4 + + + + + + 0 + 0 + + + + Qt::StrongFocus + + + Transp. + + + true + + + false + + + true + + + + + + + + 0 + 0 + + + + Qt::StrongFocus + + + Blue + + + true + + + false + + + true + + + + + + + + 0 + 0 + + + + Qt::StrongFocus + + + Khaki + + + true + + + false + + + true + + + + + + + + 0 + 0 + + + + Qt::StrongFocus + + + None + + + true + + + true + + + true + + + + + + + + + + Qt::Vertical + + + + 0 + 0 + + + + + + + + 4 + + + + + + 0 + 0 + + + + Value: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Qt::WheelFocus + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + + + + + 0 + 0 + + + + + 0 + 24 + + + + Qt::TabFocus + + + Qt::Horizontal + + + + + + + + 0 + 0 + + + + + 0 + 24 + + + + Qt::TabFocus + + + Qt::Horizontal + + + + + + + + 0 + 0 + + + + Qt::StrongFocus + + + Show + + + true + + + true + + + false + + + + + + + + 0 + 0 + + + + Qt::StrongFocus + + + Enable + + + true + + + true + + + false + + + + + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 0 + 0 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::StrongFocus + + + Close + + + + + + + + + + + horizontalScrollBar + valueChanged(int) + horizontalScrollBar_2 + setValue(int) + + + 84 + 147 + + + 166 + 147 + + + + + horizontalScrollBar_2 + valueChanged(int) + horizontalScrollBar + setValue(int) + + + 166 + 147 + + + 84 + 147 + + + + + pushButton + clicked(bool) + horizontalScrollBar_2 + setEnabled(bool) + + + 166 + 175 + + + 166 + 147 + + + + + pushButton_2 + clicked(bool) + horizontalScrollBar + setVisible(bool) + + + 84 + 175 + + + 84 + 147 + + + + + spinBox + valueChanged(int) + horizontalScrollBar_2 + setValue(int) + + + 166 + 115 + + + 166 + 147 + + + + + horizontalScrollBar_2 + valueChanged(int) + spinBox + setValue(int) + + + 132 + 132 + + + 135 + 110 + + + + + diff --git a/examples/graphicsview/boxes/3rdparty/fbm.c b/examples/graphicsview/boxes/3rdparty/fbm.c new file mode 100644 index 0000000000..98eb87a33b --- /dev/null +++ b/examples/graphicsview/boxes/3rdparty/fbm.c @@ -0,0 +1,207 @@ +/***************************************************************** + + Implementation of the fractional Brownian motion algorithm. These + functions were originally the work of F. Kenton Musgrave. + For documentation of the different functions please refer to the + book: + "Texturing and modeling: a procedural approach" + by David S. Ebert et. al. + +******************************************************************/ + +#if defined (_MSC_VER) +#include +#endif + +#include +#include +#include "fbm.h" + +#if defined(Q_CC_MSVC) +#pragma warning(disable:4244) +#endif + +/* Definitions used by the noise2() functions */ + +//#define B 0x100 +//#define BM 0xff +#define B 0x20 +#define BM 0x1f + +#define N 0x1000 +#define NP 12 /* 2^N */ +#define NM 0xfff + +static int p[B + B + 2]; +static float g3[B + B + 2][3]; +static float g2[B + B + 2][2]; +static float g1[B + B + 2]; +static int start = 1; + +static void init(void); + +#define s_curve(t) ( t * t * (3. - 2. * t) ) + +#define lerp(t, a, b) ( a + t * (b - a) ) + +#define setup(i,b0,b1,r0,r1)\ + t = vec[i] + N;\ + b0 = ((int)t) & BM;\ + b1 = (b0+1) & BM;\ + r0 = t - (int)t;\ + r1 = r0 - 1.; +#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) + +/* Fractional Brownian Motion function */ + +double fBm( Vector point, double H, double lacunarity, double octaves, + int init ) +{ + + double value, frequency, remainder; + int i; + static double exponent_array[10]; + float vec[3]; + + /* precompute and store spectral weights */ + if ( init ) { + start = 1; + srand( time(0) ); + /* seize required memory for exponent_array */ + frequency = 1.0; + for (i=0; i<=octaves; i++) { + /* compute weight for each frequency */ + exponent_array[i] = pow( frequency, -H ); + frequency *= lacunarity; + } + } + + value = 0.0; /* initialize vars to proper values */ + frequency = 1.0; + vec[0]=point.x; + vec[1]=point.y; + vec[2]=point.z; + + + /* inner loop of spectral construction */ + for (i=0; i + +#ifdef __cplusplus +extern "C" { +#endif + +//#define TRUE 1 +//#define FALSE 0 + +typedef struct { + double x; + double y; + double z; +} Vector; + +float noise3(float vec[]); +double fBm( Vector point, double H, double lacunarity, double octaves, + int init ); +#endif + +#ifdef __cplusplus +} +#endif + + + + diff --git a/examples/graphicsview/boxes/basic.fsh b/examples/graphicsview/boxes/basic.fsh new file mode 100644 index 0000000000..faf3601606 --- /dev/null +++ b/examples/graphicsview/boxes/basic.fsh @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform vec4 basicColor; + +void main() +{ + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + vec3 absN = abs(gl_TexCoord[1].xyz); + vec3 texCoord; + if (absN.x > absN.y && absN.x > absN.z) + texCoord = gl_TexCoord[1].yzx; + else if (absN.y > absN.z) + texCoord = gl_TexCoord[1].zxy; + else + texCoord = gl_TexCoord[1].xyz; + texCoord.y *= -sign(texCoord.z); + texCoord += 0.5; + + vec4 texColor = texture2D(tex, texCoord.xy); + vec4 unlitColor = gl_Color * mix(basicColor, vec4(texColor.xyz, 1.0), texColor.w); + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/graphicsview/boxes/basic.vsh b/examples/graphicsview/boxes/basic.vsh new file mode 100644 index 0000000000..31acc4224a --- /dev/null +++ b/examples/graphicsview/boxes/basic.vsh @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform mat4 view; + +void main() +{ + gl_TexCoord[0] = gl_MultiTexCoord0; + gl_TexCoord[1] = gl_Vertex; + specular = gl_LightSource[0].specular; + ambient = gl_LightSource[0].ambient; + diffuse = gl_LightSource[0].diffuse; + lightDirection = view * gl_LightSource[0].position; + + normal = gl_NormalMatrix * gl_Normal; + position = (gl_ModelViewMatrix * gl_Vertex).xyz; + + gl_FrontColor = gl_Color; + gl_Position = ftransform(); +} diff --git a/examples/graphicsview/boxes/boxes.pro b/examples/graphicsview/boxes/boxes.pro new file mode 100644 index 0000000000..d599a3a0ac --- /dev/null +++ b/examples/graphicsview/boxes/boxes.pro @@ -0,0 +1,49 @@ +###################################################################### +# Automatically generated by qmake (2.01a) ma 3. nov 17:33:30 2008 +###################################################################### + +TEMPLATE = app +TARGET = +DEPENDPATH += . +INCLUDEPATH += . + +# Input +HEADERS += 3rdparty/fbm.h \ + glbuffers.h \ + glextensions.h \ + gltrianglemesh.h \ + qtbox.h \ + roundedbox.h \ + scene.h \ + trackball.h +SOURCES += 3rdparty/fbm.c \ + glbuffers.cpp \ + glextensions.cpp \ + main.cpp \ + qtbox.cpp \ + roundedbox.cpp \ + scene.cpp \ + trackball.cpp + +RESOURCES += boxes.qrc + +QT += opengl + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/boxes +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html *.jpg *.png *.fsh *.vsh *.par +sources.files -= 3rdparty/fbm.h 3rdparty/fbm.c +sources.files += 3rdparty +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/boxes +INSTALLS += target sources + +wince*: { + DEPLOYMENT_PLUGIN += qjpeg +} + +win32-msvc* { + QMAKE_CXXFLAGS -= -Zm200 + QMAKE_CFLAGS -= -Zm200 + QMAKE_CXXFLAGS += -Zm500 + QMAKE_CFLAGS += -Zm500 +} diff --git a/examples/graphicsview/boxes/boxes.qrc b/examples/graphicsview/boxes/boxes.qrc new file mode 100644 index 0000000000..d27506dc5a --- /dev/null +++ b/examples/graphicsview/boxes/boxes.qrc @@ -0,0 +1,25 @@ + + + cubemap_negx.jpg + cubemap_negy.jpg + cubemap_negz.jpg + cubemap_posx.jpg + cubemap_posy.jpg + cubemap_posz.jpg + square.jpg + basic.vsh + basic.fsh + dotted.fsh + fresnel.fsh + glass.fsh + granite.fsh + marble.fsh + reflection.fsh + refraction.fsh + wood.fsh + parameters.par + qt-logo.png + smiley.png + qt-logo.jpg + + diff --git a/examples/graphicsview/boxes/cubemap_negx.jpg b/examples/graphicsview/boxes/cubemap_negx.jpg new file mode 100644 index 0000000000..07c282eab9 Binary files /dev/null and b/examples/graphicsview/boxes/cubemap_negx.jpg differ diff --git a/examples/graphicsview/boxes/cubemap_negy.jpg b/examples/graphicsview/boxes/cubemap_negy.jpg new file mode 100644 index 0000000000..46cd2f9cf3 Binary files /dev/null and b/examples/graphicsview/boxes/cubemap_negy.jpg differ diff --git a/examples/graphicsview/boxes/cubemap_negz.jpg b/examples/graphicsview/boxes/cubemap_negz.jpg new file mode 100644 index 0000000000..40c01ddff3 Binary files /dev/null and b/examples/graphicsview/boxes/cubemap_negz.jpg differ diff --git a/examples/graphicsview/boxes/cubemap_posx.jpg b/examples/graphicsview/boxes/cubemap_posx.jpg new file mode 100644 index 0000000000..0b42e8a1b1 Binary files /dev/null and b/examples/graphicsview/boxes/cubemap_posx.jpg differ diff --git a/examples/graphicsview/boxes/cubemap_posy.jpg b/examples/graphicsview/boxes/cubemap_posy.jpg new file mode 100644 index 0000000000..2aca9b1e98 Binary files /dev/null and b/examples/graphicsview/boxes/cubemap_posy.jpg differ diff --git a/examples/graphicsview/boxes/cubemap_posz.jpg b/examples/graphicsview/boxes/cubemap_posz.jpg new file mode 100644 index 0000000000..2e49173848 Binary files /dev/null and b/examples/graphicsview/boxes/cubemap_posz.jpg differ diff --git a/examples/graphicsview/boxes/dotted.fsh b/examples/graphicsview/boxes/dotted.fsh new file mode 100644 index 0000000000..a9f1bcbefb --- /dev/null +++ b/examples/graphicsview/boxes/dotted.fsh @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; + +void main() +{ + vec3 N = normalize(normal); + + gl_MaterialParameters M = gl_FrontMaterial; + + // assume directional light + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + float r1 = length(fract(7.0 * gl_TexCoord[1].xyz) - 0.5); + float r2 = length(fract(5.0 * gl_TexCoord[1].xyz + 0.2) - 0.5); + float r3 = length(fract(11.0 * gl_TexCoord[1].xyz + 0.7) - 0.5); + vec4 rs = vec4(r1, r2, r3, 0.0); + + vec4 unlitColor = gl_Color * (0.8 - clamp(10.0 * (0.4 - rs), 0.0, 0.2)); + unlitColor.w = 1.0; + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/graphicsview/boxes/fresnel.fsh b/examples/graphicsview/boxes/fresnel.fsh new file mode 100644 index 0000000000..462f9674f4 --- /dev/null +++ b/examples/graphicsview/boxes/fresnel.fsh @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform samplerCube env; +uniform mat4 view; +uniform vec4 basicColor; + +void main() +{ + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + vec3 absN = abs(gl_TexCoord[1].xyz); + vec3 texCoord; + if (absN.x > absN.y && absN.x > absN.z) + texCoord = gl_TexCoord[1].yzx; + else if (absN.y > absN.z) + texCoord = gl_TexCoord[1].zxy; + else + texCoord = gl_TexCoord[1].xyz; + texCoord.y *= -sign(texCoord.z); + texCoord += 0.5; + + vec4 texColor = texture2D(tex, texCoord.xy); + vec4 unlitColor = gl_Color * mix(basicColor, vec4(texColor.xyz, 1.0), texColor.w); + vec4 litColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); + + vec3 R = 2.0 * dot(-position, N) * N + position; + vec4 reflectedColor = textureCube(env, R * mat3(view[0].xyz, view[1].xyz, view[2].xyz)); + gl_FragColor = mix(litColor, reflectedColor, 0.2 + 0.8 * pow(1.0 + dot(N, normalize(position)), 2.0)); +} diff --git a/examples/graphicsview/boxes/glass.fsh b/examples/graphicsview/boxes/glass.fsh new file mode 100644 index 0000000000..aeac2c2fed --- /dev/null +++ b/examples/graphicsview/boxes/glass.fsh @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform samplerCube env; +uniform mat4 view; + +// Some arbitrary values +// Arrays don't work here on glsl < 120, apparently. +//const float coeffs[6] = float[6](1.0/4.0, 1.0/4.1, 1.0/4.2, 1.0/4.3, 1.0/4.4, 1.0/4.5); +float coeffs(int i) +{ + return 1.0 / (3.0 + 0.1 * float(i)); +} + +void main() +{ + vec3 N = normalize(normal); + vec3 I = -normalize(position); + mat3 V = mat3(view[0].xyz, view[1].xyz, view[2].xyz); + float IdotN = dot(I, N); + float scales[6]; + vec3 C[6]; + for (int i = 0; i < 6; ++i) { + scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN))); + C[i] = textureCube(env, (-I + coeffs(i) * N) * V).xyz; + } + vec4 refractedColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y, + C[3].z + 2.0*C[4].z + C[5].z, 4.0); + + vec3 R = 2.0 * dot(-position, N) * N + position; + vec4 reflectedColor = textureCube(env, R * V); + + gl_FragColor = mix(refractedColor, reflectedColor, 0.4 + 0.6 * pow(1.0 - IdotN, 2.0)); +} diff --git a/examples/graphicsview/boxes/glbuffers.cpp b/examples/graphicsview/boxes/glbuffers.cpp new file mode 100644 index 0000000000..e12132b4cd --- /dev/null +++ b/examples/graphicsview/boxes/glbuffers.cpp @@ -0,0 +1,402 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glbuffers.h" +#include + + +void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) +{ + const GLdouble ymax = zNear * tan(fovy * M_PI / 360.0); + const GLdouble ymin = -ymax; + const GLdouble xmin = ymin * aspect; + const GLdouble xmax = ymax * aspect; + glFrustum(xmin, xmax, ymin, ymax, zNear, zFar); +} + +//============================================================================// +// GLTexture // +//============================================================================// + +GLTexture::GLTexture() : m_texture(0), m_failed(false) +{ + glGenTextures(1, &m_texture); +} + +GLTexture::~GLTexture() +{ + glDeleteTextures(1, &m_texture); +} + +//============================================================================// +// GLTexture2D // +//============================================================================// + +GLTexture2D::GLTexture2D(int width, int height) +{ + glBindTexture(GL_TEXTURE_2D, m_texture); + glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, + GL_BGRA, GL_UNSIGNED_BYTE, 0); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_2D, 0); +} + + +GLTexture2D::GLTexture2D(const QString& fileName, int width, int height) +{ + // TODO: Add error handling. + QImage image(fileName); + + if (image.isNull()) { + m_failed = true; + return; + } + + image = image.convertToFormat(QImage::Format_ARGB32); + + //qDebug() << "Image size:" << image.width() << "x" << image.height(); + if (width <= 0) + width = image.width(); + if (height <= 0) + height = image.height(); + if (width != image.width() || height != image.height()) + image = image.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + + glBindTexture(GL_TEXTURE_2D, m_texture); + + // Works on x86, so probably works on all little-endian systems. + // Does it work on big-endian systems? + glTexImage2D(GL_TEXTURE_2D, 0, 4, image.width(), image.height(), 0, + GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_2D, 0); +} + +void GLTexture2D::load(int width, int height, QRgb *data) +{ + glBindTexture(GL_TEXTURE_2D, m_texture); + glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, + GL_BGRA, GL_UNSIGNED_BYTE, data); + glBindTexture(GL_TEXTURE_2D, 0); +} + +void GLTexture2D::bind() +{ + glBindTexture(GL_TEXTURE_2D, m_texture); + glEnable(GL_TEXTURE_2D); +} + +void GLTexture2D::unbind() +{ + glBindTexture(GL_TEXTURE_2D, 0); + glDisable(GL_TEXTURE_2D); +} + + +//============================================================================// +// GLTexture3D // +//============================================================================// + +GLTexture3D::GLTexture3D(int width, int height, int depth) +{ + GLBUFFERS_ASSERT_OPENGL("GLTexture3D::GLTexture3D", glTexImage3D, return) + + glBindTexture(GL_TEXTURE_3D, m_texture); + glTexImage3D(GL_TEXTURE_3D, 0, 4, width, height, depth, 0, + GL_BGRA, GL_UNSIGNED_BYTE, 0); + + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_3D, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_3D, 0); +} + +void GLTexture3D::load(int width, int height, int depth, QRgb *data) +{ + GLBUFFERS_ASSERT_OPENGL("GLTexture3D::load", glTexImage3D, return) + + glBindTexture(GL_TEXTURE_3D, m_texture); + glTexImage3D(GL_TEXTURE_3D, 0, 4, width, height, depth, 0, + GL_BGRA, GL_UNSIGNED_BYTE, data); + glBindTexture(GL_TEXTURE_3D, 0); +} + +void GLTexture3D::bind() +{ + glBindTexture(GL_TEXTURE_3D, m_texture); + glEnable(GL_TEXTURE_3D); +} + +void GLTexture3D::unbind() +{ + glBindTexture(GL_TEXTURE_3D, 0); + glDisable(GL_TEXTURE_3D); +} + +//============================================================================// +// GLTextureCube // +//============================================================================// + +GLTextureCube::GLTextureCube(int size) +{ + glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); + + for (int i = 0; i < 6; ++i) + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 4, size, size, 0, + GL_BGRA, GL_UNSIGNED_BYTE, 0); + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +} + +GLTextureCube::GLTextureCube(const QStringList& fileNames, int size) +{ + // TODO: Add error handling. + + glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); + + int index = 0; + foreach (QString file, fileNames) { + QImage image(file); + if (image.isNull()) { + m_failed = true; + break; + } + + image = image.convertToFormat(QImage::Format_ARGB32); + + //qDebug() << "Image size:" << image.width() << "x" << image.height(); + if (size <= 0) + size = image.width(); + if (size != image.width() || size != image.height()) + image = image.scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + + // Works on x86, so probably works on all little-endian systems. + // Does it work on big-endian systems? + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, 4, image.width(), image.height(), 0, + GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); + + if (++index == 6) + break; + } + + // Clear remaining faces. + while (index < 6) { + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, 4, size, size, 0, + GL_BGRA, GL_UNSIGNED_BYTE, 0); + ++index; + } + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +} + +void GLTextureCube::load(int size, int face, QRgb *data) +{ + glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, 4, size, size, 0, + GL_BGRA, GL_UNSIGNED_BYTE, data); + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +} + +void GLTextureCube::bind() +{ + glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); + glEnable(GL_TEXTURE_CUBE_MAP); +} + +void GLTextureCube::unbind() +{ + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); + glDisable(GL_TEXTURE_CUBE_MAP); +} + +//============================================================================// +// GLFrameBufferObject // +//============================================================================// + +GLFrameBufferObject::GLFrameBufferObject(int width, int height) + : m_fbo(0) + , m_depthBuffer(0) + , m_width(width) + , m_height(height) + , m_failed(false) +{ + GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::GLFrameBufferObject", + glGenFramebuffersEXT && glGenRenderbuffersEXT && glBindRenderbufferEXT && glRenderbufferStorageEXT, return) + + // TODO: share depth buffers of same size + glGenFramebuffersEXT(1, &m_fbo); + //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + glGenRenderbuffersEXT(1, &m_depthBuffer); + glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthBuffer); + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, m_width, m_height); + //glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthBuffer); + //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); +} + +GLFrameBufferObject::~GLFrameBufferObject() +{ + GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::~GLFrameBufferObject", + glDeleteFramebuffersEXT && glDeleteRenderbuffersEXT, return) + + glDeleteFramebuffersEXT(1, &m_fbo); + glDeleteRenderbuffersEXT(1, &m_depthBuffer); +} + +void GLFrameBufferObject::setAsRenderTarget(bool state) +{ + GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::setAsRenderTarget", glBindFramebufferEXT, return) + + if (state) { + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + glPushAttrib(GL_VIEWPORT_BIT); + glViewport(0, 0, m_width, m_height); + } else { + glPopAttrib(); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + } +} + +bool GLFrameBufferObject::isComplete() +{ + GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::isComplete", glCheckFramebufferStatusEXT, return false) + + return GL_FRAMEBUFFER_COMPLETE_EXT == glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); +} + +//============================================================================// +// GLRenderTargetCube // +//============================================================================// + +GLRenderTargetCube::GLRenderTargetCube(int size) + : GLTextureCube(size) + , m_fbo(size, size) +{ +} + +void GLRenderTargetCube::begin(int face) +{ + GLBUFFERS_ASSERT_OPENGL("GLRenderTargetCube::begin", + glFramebufferTexture2DEXT && glFramebufferRenderbufferEXT, return) + + m_fbo.setAsRenderTarget(true); + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, m_texture, 0); + glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_fbo.m_depthBuffer); +} + +void GLRenderTargetCube::end() +{ + m_fbo.setAsRenderTarget(false); +} + +void GLRenderTargetCube::getViewMatrix(QMatrix4x4& mat, int face) +{ + if (face < 0 || face >= 6) { + qWarning("GLRenderTargetCube::getViewMatrix: 'face' must be in the range [0, 6). (face == %d)", face); + return; + } + + static int perm[6][3] = { + {2, 1, 0}, + {2, 1, 0}, + {0, 2, 1}, + {0, 2, 1}, + {0, 1, 2}, + {0, 1, 2}, + }; + + static float signs[6][3] = { + {-1.0f, -1.0f, -1.0f}, + {+1.0f, -1.0f, +1.0f}, + {+1.0f, +1.0f, -1.0f}, + {+1.0f, -1.0f, +1.0f}, + {+1.0f, -1.0f, -1.0f}, + {-1.0f, -1.0f, +1.0f}, + }; + + mat.fill(0.0f); + for (int i = 0; i < 3; ++i) + mat(i, perm[face][i]) = signs[face][i]; + mat(3, 3) = 1.0f; +} + +void GLRenderTargetCube::getProjectionMatrix(QMatrix4x4& mat, float nearZ, float farZ) +{ + static const QMatrix4x4 reference( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, -1.0f, 0.0f); + + mat = reference; + mat(2, 2) = (nearZ+farZ)/(nearZ-farZ); + mat(2, 3) = 2.0f*nearZ*farZ/(nearZ-farZ); +} diff --git a/examples/graphicsview/boxes/glbuffers.h b/examples/graphicsview/boxes/glbuffers.h new file mode 100644 index 0000000000..6b18d3f128 --- /dev/null +++ b/examples/graphicsview/boxes/glbuffers.h @@ -0,0 +1,366 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GLBUFFERS_H +#define GLBUFFERS_H + +//#include +#include "glextensions.h" + +#include +#include + +#define BUFFER_OFFSET(i) ((char*)0 + (i)) +#define SIZE_OF_MEMBER(cls, member) sizeof(static_cast(0)->member) + +#define GLBUFFERS_ASSERT_OPENGL(prefix, assertion, returnStatement) \ +if (m_failed || !(assertion)) { \ + if (!m_failed) qCritical(prefix ": The necessary OpenGL functions are not available."); \ + m_failed = true; \ + returnStatement; \ +} + +void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar); + +QT_BEGIN_NAMESPACE +class QMatrix4x4; +QT_END_NAMESPACE + +class GLTexture +{ +public: + GLTexture(); + virtual ~GLTexture(); + virtual void bind() = 0; + virtual void unbind() = 0; + virtual bool failed() const {return m_failed;} +protected: + GLuint m_texture; + bool m_failed; +}; + +class GLFrameBufferObject +{ +public: + friend class GLRenderTargetCube; + // friend class GLRenderTarget2D; + + GLFrameBufferObject(int width, int height); + virtual ~GLFrameBufferObject(); + bool isComplete(); + virtual bool failed() const {return m_failed;} +protected: + void setAsRenderTarget(bool state = true); + GLuint m_fbo; + GLuint m_depthBuffer; + int m_width, m_height; + bool m_failed; +}; + +class GLTexture2D : public GLTexture +{ +public: + GLTexture2D(int width, int height); + GLTexture2D(const QString& fileName, int width = 0, int height = 0); + void load(int width, int height, QRgb *data); + virtual void bind(); + virtual void unbind(); +}; + +class GLTexture3D : public GLTexture +{ +public: + GLTexture3D(int width, int height, int depth); + // TODO: Implement function below + //GLTexture3D(const QString& fileName, int width = 0, int height = 0); + void load(int width, int height, int depth, QRgb *data); + virtual void bind(); + virtual void unbind(); +}; + +class GLTextureCube : public GLTexture +{ +public: + GLTextureCube(int size); + GLTextureCube(const QStringList& fileNames, int size = 0); + void load(int size, int face, QRgb *data); + virtual void bind(); + virtual void unbind(); +}; + +// TODO: Define and implement class below +//class GLRenderTarget2D : public GLTexture2D + +class GLRenderTargetCube : public GLTextureCube +{ +public: + GLRenderTargetCube(int size); + // begin rendering to one of the cube's faces. 0 <= face < 6 + void begin(int face); + // end rendering + void end(); + virtual bool failed() {return m_failed || m_fbo.failed();} + + static void getViewMatrix(QMatrix4x4& mat, int face); + static void getProjectionMatrix(QMatrix4x4& mat, float nearZ, float farZ); +private: + GLFrameBufferObject m_fbo; +}; + +struct VertexDescription +{ + enum + { + Null = 0, // Terminates a VertexDescription array + Position, + TexCoord, + Normal, + Color, + }; + int field; // Position, TexCoord, Normal, Color + int type; // GL_FLOAT, GL_UNSIGNED_BYTE + int count; // number of elements + int offset; // field's offset into vertex struct + int index; // 0 (unused at the moment) +}; + +// Implementation of interleaved buffers. +// 'T' is a struct which must include a null-terminated static array +// 'VertexDescription* description'. +// Example: +/* +struct Vertex +{ + GLfloat position[3]; + GLfloat texCoord[2]; + GLfloat normal[3]; + GLbyte color[4]; + static VertexDescription description[]; +}; + +VertexDescription Vertex::description[] = { + {VertexDescription::Position, GL_FLOAT, SIZE_OF_MEMBER(Vertex, position) / sizeof(GLfloat), offsetof(Vertex, position), 0}, + {VertexDescription::TexCoord, GL_FLOAT, SIZE_OF_MEMBER(Vertex, texCoord) / sizeof(GLfloat), offsetof(Vertex, texCoord), 0}, + {VertexDescription::Normal, GL_FLOAT, SIZE_OF_MEMBER(Vertex, normal) / sizeof(GLfloat), offsetof(Vertex, normal), 0}, + {VertexDescription::Color, GL_BYTE, SIZE_OF_MEMBER(Vertex, color) / sizeof(GLbyte), offsetof(Vertex, color), 0}, + {VertexDescription::Null, 0, 0, 0, 0}, +}; +*/ +template +class GLVertexBuffer +{ +public: + GLVertexBuffer(int length, const T *data = 0, int mode = GL_STATIC_DRAW) + : m_length(0) + , m_mode(mode) + , m_buffer(0) + , m_failed(false) + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::GLVertexBuffer", glGenBuffers && glBindBuffer && glBufferData, return) + + glGenBuffers(1, &m_buffer); + glBindBuffer(GL_ARRAY_BUFFER, m_buffer); + glBufferData(GL_ARRAY_BUFFER, (m_length = length) * sizeof(T), data, mode); + } + + ~GLVertexBuffer() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::~GLVertexBuffer", glDeleteBuffers, return) + + glDeleteBuffers(1, &m_buffer); + } + + void bind() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::bind", glBindBuffer, return) + + glBindBuffer(GL_ARRAY_BUFFER, m_buffer); + for (VertexDescription *desc = T::description; desc->field != VertexDescription::Null; ++desc) { + switch (desc->field) { + case VertexDescription::Position: + glVertexPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); + glEnableClientState(GL_VERTEX_ARRAY); + break; + case VertexDescription::TexCoord: + glTexCoordPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + break; + case VertexDescription::Normal: + glNormalPointer(desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); + glEnableClientState(GL_NORMAL_ARRAY); + break; + case VertexDescription::Color: + glColorPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); + glEnableClientState(GL_COLOR_ARRAY); + break; + default: + break; + } + } + } + + void unbind() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::unbind", glBindBuffer, return) + + glBindBuffer(GL_ARRAY_BUFFER, 0); + for (VertexDescription *desc = T::description; desc->field != VertexDescription::Null; ++desc) { + switch (desc->field) { + case VertexDescription::Position: + glDisableClientState(GL_VERTEX_ARRAY); + break; + case VertexDescription::TexCoord: + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + break; + case VertexDescription::Normal: + glDisableClientState(GL_NORMAL_ARRAY); + break; + case VertexDescription::Color: + glDisableClientState(GL_COLOR_ARRAY); + break; + default: + break; + } + } + } + + int length() const {return m_length;} + + T *lock() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::lock", glBindBuffer && glMapBuffer, return 0) + + glBindBuffer(GL_ARRAY_BUFFER, m_buffer); + //glBufferData(GL_ARRAY_BUFFER, m_length, NULL, m_mode); + GLvoid* buffer = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); + m_failed = (buffer == 0); + return reinterpret_cast(buffer); + } + + void unlock() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::unlock", glBindBuffer && glUnmapBuffer, return) + + glBindBuffer(GL_ARRAY_BUFFER, m_buffer); + glUnmapBuffer(GL_ARRAY_BUFFER); + } + + bool failed() + { + return m_failed; + } + +private: + int m_length, m_mode; + GLuint m_buffer; + bool m_failed; +}; + +template +class GLIndexBuffer +{ +public: + GLIndexBuffer(int length, const T *data = 0, int mode = GL_STATIC_DRAW) + : m_length(0) + , m_mode(mode) + , m_buffer(0) + , m_failed(false) + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::GLIndexBuffer", glGenBuffers && glBindBuffer && glBufferData, return) + + glGenBuffers(1, &m_buffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, (m_length = length) * sizeof(T), data, mode); + } + + ~GLIndexBuffer() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::~GLIndexBuffer", glDeleteBuffers, return) + + glDeleteBuffers(1, &m_buffer); + } + + void bind() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::bind", glBindBuffer, return) + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); + } + + void unbind() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::unbind", glBindBuffer, return) + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + + int length() const {return m_length;} + + T *lock() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::lock", glBindBuffer && glMapBuffer, return 0) + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); + GLvoid* buffer = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_WRITE); + m_failed = (buffer == 0); + return reinterpret_cast(buffer); + } + + void unlock() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::unlock", glBindBuffer && glUnmapBuffer, return) + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); + glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); + } + + bool failed() + { + return m_failed; + } + +private: + int m_length, m_mode; + GLuint m_buffer; + bool m_failed; +}; + +#endif diff --git a/examples/graphicsview/boxes/glextensions.cpp b/examples/graphicsview/boxes/glextensions.cpp new file mode 100644 index 0000000000..b712efe38b --- /dev/null +++ b/examples/graphicsview/boxes/glextensions.cpp @@ -0,0 +1,98 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glextensions.h" + +#define RESOLVE_GL_FUNC(f) ok &= bool((f = (_gl##f) context->getProcAddress(QLatin1String("gl" #f)))); + +bool GLExtensionFunctions::resolve(const QGLContext *context) +{ + bool ok = true; + + RESOLVE_GL_FUNC(GenFramebuffersEXT) + RESOLVE_GL_FUNC(GenRenderbuffersEXT) + RESOLVE_GL_FUNC(BindRenderbufferEXT) + RESOLVE_GL_FUNC(RenderbufferStorageEXT) + RESOLVE_GL_FUNC(DeleteFramebuffersEXT) + RESOLVE_GL_FUNC(DeleteRenderbuffersEXT) + RESOLVE_GL_FUNC(BindFramebufferEXT) + RESOLVE_GL_FUNC(FramebufferTexture2DEXT) + RESOLVE_GL_FUNC(FramebufferRenderbufferEXT) + RESOLVE_GL_FUNC(CheckFramebufferStatusEXT) + + RESOLVE_GL_FUNC(ActiveTexture) + RESOLVE_GL_FUNC(TexImage3D) + + RESOLVE_GL_FUNC(GenBuffers) + RESOLVE_GL_FUNC(BindBuffer) + RESOLVE_GL_FUNC(BufferData) + RESOLVE_GL_FUNC(DeleteBuffers) + RESOLVE_GL_FUNC(MapBuffer) + RESOLVE_GL_FUNC(UnmapBuffer) + + return ok; +} + +bool GLExtensionFunctions::fboSupported() { + return GenFramebuffersEXT + && GenRenderbuffersEXT + && BindRenderbufferEXT + && RenderbufferStorageEXT + && DeleteFramebuffersEXT + && DeleteRenderbuffersEXT + && BindFramebufferEXT + && FramebufferTexture2DEXT + && FramebufferRenderbufferEXT + && CheckFramebufferStatusEXT; +} + +bool GLExtensionFunctions::openGL15Supported() { + return ActiveTexture + && TexImage3D + && GenBuffers + && BindBuffer + && BufferData + && DeleteBuffers + && MapBuffer + && UnmapBuffer; +} + +#undef RESOLVE_GL_FUNC diff --git a/examples/graphicsview/boxes/glextensions.h b/examples/graphicsview/boxes/glextensions.h new file mode 100644 index 0000000000..54de548cd7 --- /dev/null +++ b/examples/graphicsview/boxes/glextensions.h @@ -0,0 +1,202 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GLEXTENSIONS_H +#define GLEXTENSIONS_H + +#include + +/* +Functions resolved: + +glGenFramebuffersEXT +glGenRenderbuffersEXT +glBindRenderbufferEXT +glRenderbufferStorageEXT +glDeleteFramebuffersEXT +glDeleteRenderbuffersEXT +glBindFramebufferEXT +glFramebufferTexture2DEXT +glFramebufferRenderbufferEXT +glCheckFramebufferStatusEXT + +glActiveTexture +glTexImage3D + +glGenBuffers +glBindBuffer +glBufferData +glDeleteBuffers +glMapBuffer +glUnmapBuffer +*/ + +#ifndef Q_WS_MAC +# ifndef APIENTRYP +# ifdef APIENTRY +# define APIENTRYP APIENTRY * +# else +# define APIENTRY +# define APIENTRYP * +# endif +# endif +#else +# define APIENTRY +# define APIENTRYP * +#endif + +#ifndef GL_VERSION_1_2 +#define GL_TEXTURE_3D 0x806F +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_BGRA 0x80E1 +#endif + +#ifndef GL_VERSION_1_3 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#endif + +#ifndef GL_ARB_vertex_buffer_object +typedef ptrdiff_t GLsizeiptrARB; +#endif + +#ifndef GL_VERSION_1_5 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_READ_WRITE 0x88BA +#define GL_STATIC_DRAW 0x88E4 +#endif + +#ifndef GL_EXT_framebuffer_object +#define GL_RENDERBUFFER_EXT 0x8D41 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#endif + +typedef void (APIENTRY *_glGenFramebuffersEXT) (GLsizei, GLuint *); +typedef void (APIENTRY *_glGenRenderbuffersEXT) (GLsizei, GLuint *); +typedef void (APIENTRY *_glBindRenderbufferEXT) (GLenum, GLuint); +typedef void (APIENTRY *_glRenderbufferStorageEXT) (GLenum, GLenum, GLsizei, GLsizei); +typedef void (APIENTRY *_glDeleteFramebuffersEXT) (GLsizei, const GLuint*); +typedef void (APIENTRY *_glDeleteRenderbuffersEXT) (GLsizei, const GLuint*); +typedef void (APIENTRY *_glBindFramebufferEXT) (GLenum, GLuint); +typedef void (APIENTRY *_glFramebufferTexture2DEXT) (GLenum, GLenum, GLenum, GLuint, GLint); +typedef void (APIENTRY *_glFramebufferRenderbufferEXT) (GLenum, GLenum, GLenum, GLuint); +typedef GLenum (APIENTRY *_glCheckFramebufferStatusEXT) (GLenum); + +typedef void (APIENTRY *_glActiveTexture) (GLenum); +typedef void (APIENTRY *_glTexImage3D) (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); + +typedef void (APIENTRY *_glGenBuffers) (GLsizei, GLuint *); +typedef void (APIENTRY *_glBindBuffer) (GLenum, GLuint); +typedef void (APIENTRY *_glBufferData) (GLenum, GLsizeiptrARB, const GLvoid *, GLenum); +typedef void (APIENTRY *_glDeleteBuffers) (GLsizei, const GLuint *); +typedef void *(APIENTRY *_glMapBuffer) (GLenum, GLenum); +typedef GLboolean (APIENTRY *_glUnmapBuffer) (GLenum); + +struct GLExtensionFunctions +{ + bool resolve(const QGLContext *context); + + bool fboSupported(); + bool openGL15Supported(); // the rest: multi-texture, 3D-texture, vertex buffer objects + + _glGenFramebuffersEXT GenFramebuffersEXT; + _glGenRenderbuffersEXT GenRenderbuffersEXT; + _glBindRenderbufferEXT BindRenderbufferEXT; + _glRenderbufferStorageEXT RenderbufferStorageEXT; + _glDeleteFramebuffersEXT DeleteFramebuffersEXT; + _glDeleteRenderbuffersEXT DeleteRenderbuffersEXT; + _glBindFramebufferEXT BindFramebufferEXT; + _glFramebufferTexture2DEXT FramebufferTexture2DEXT; + _glFramebufferRenderbufferEXT FramebufferRenderbufferEXT; + _glCheckFramebufferStatusEXT CheckFramebufferStatusEXT; + + _glActiveTexture ActiveTexture; + _glTexImage3D TexImage3D; + + _glGenBuffers GenBuffers; + _glBindBuffer BindBuffer; + _glBufferData BufferData; + _glDeleteBuffers DeleteBuffers; + _glMapBuffer MapBuffer; + _glUnmapBuffer UnmapBuffer; +}; + +inline GLExtensionFunctions &getGLExtensionFunctions() +{ + static GLExtensionFunctions funcs; + return funcs; +} + +#define glGenFramebuffersEXT getGLExtensionFunctions().GenFramebuffersEXT +#define glGenRenderbuffersEXT getGLExtensionFunctions().GenRenderbuffersEXT +#define glBindRenderbufferEXT getGLExtensionFunctions().BindRenderbufferEXT +#define glRenderbufferStorageEXT getGLExtensionFunctions().RenderbufferStorageEXT +#define glDeleteFramebuffersEXT getGLExtensionFunctions().DeleteFramebuffersEXT +#define glDeleteRenderbuffersEXT getGLExtensionFunctions().DeleteRenderbuffersEXT +#define glBindFramebufferEXT getGLExtensionFunctions().BindFramebufferEXT +#define glFramebufferTexture2DEXT getGLExtensionFunctions().FramebufferTexture2DEXT +#define glFramebufferRenderbufferEXT getGLExtensionFunctions().FramebufferRenderbufferEXT +#define glCheckFramebufferStatusEXT getGLExtensionFunctions().CheckFramebufferStatusEXT + +#define glActiveTexture getGLExtensionFunctions().ActiveTexture +#define glTexImage3D getGLExtensionFunctions().TexImage3D + +#define glGenBuffers getGLExtensionFunctions().GenBuffers +#define glBindBuffer getGLExtensionFunctions().BindBuffer +#define glBufferData getGLExtensionFunctions().BufferData +#define glDeleteBuffers getGLExtensionFunctions().DeleteBuffers +#define glMapBuffer getGLExtensionFunctions().MapBuffer +#define glUnmapBuffer getGLExtensionFunctions().UnmapBuffer + +#endif diff --git a/examples/graphicsview/boxes/gltrianglemesh.h b/examples/graphicsview/boxes/gltrianglemesh.h new file mode 100644 index 0000000000..ecf6531d85 --- /dev/null +++ b/examples/graphicsview/boxes/gltrianglemesh.h @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GLTRIANGLEMESH_H +#define GLTRIANGLEMESH_H + +//#include +#include "glextensions.h" + +#include +#include + +#include "glbuffers.h" + +template +class GLTriangleMesh +{ +public: + GLTriangleMesh(int vertexCount, int indexCount) : m_vb(vertexCount), m_ib(indexCount) + { + } + + virtual ~GLTriangleMesh() + { + } + + virtual void draw() + { + if (failed()) + return; + + int type = GL_UNSIGNED_INT; + if (sizeof(TIndex) == sizeof(char)) type = GL_UNSIGNED_BYTE; + if (sizeof(TIndex) == sizeof(short)) type = GL_UNSIGNED_SHORT; + + m_vb.bind(); + m_ib.bind(); + glDrawElements(GL_TRIANGLES, m_ib.length(), type, BUFFER_OFFSET(0)); + m_vb.unbind(); + m_ib.unbind(); + } + + bool failed() + { + return m_vb.failed() || m_ib.failed(); + } +protected: + GLVertexBuffer m_vb; + GLIndexBuffer m_ib; +}; + + +#endif diff --git a/examples/graphicsview/boxes/granite.fsh b/examples/graphicsview/boxes/granite.fsh new file mode 100644 index 0000000000..abaeeb97bc --- /dev/null +++ b/examples/graphicsview/boxes/granite.fsh @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform sampler3D noise; + +//const vec4 graniteColors[3] = {vec4(0.0, 0.0, 0.0, 1), vec4(0.30, 0.15, 0.10, 1), vec4(0.80, 0.70, 0.75, 1)}; +uniform vec4 graniteColors[3]; + +float steep(float x) +{ + return clamp(5.0 * x - 2.0, 0.0, 1.0); +} + +void main() +{ + vec2 turbulence = vec2(0, 0); + float scale = 1.0; + for (int i = 0; i < 4; ++i) { + turbulence += scale * (texture3D(noise, gl_TexCoord[1].xyz / scale).xy - 0.5); + scale *= 0.5; + } + + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + vec4 unlitColor = mix(graniteColors[1], mix(graniteColors[0], graniteColors[2], steep(0.5 + turbulence.y)), 4.0 * abs(turbulence.x)); + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/graphicsview/boxes/main.cpp b/examples/graphicsview/boxes/main.cpp new file mode 100644 index 0000000000..483170801f --- /dev/null +++ b/examples/graphicsview/boxes/main.cpp @@ -0,0 +1,150 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//#include +#include "glextensions.h" + +#include "scene.h" + +#include +#include + +class GraphicsView : public QGraphicsView +{ +public: + GraphicsView() + { + setWindowTitle(tr("Boxes")); + setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + //setRenderHints(QPainter::SmoothPixmapTransform); + } + +protected: + void resizeEvent(QResizeEvent *event) { + if (scene()) + scene()->setSceneRect(QRect(QPoint(0, 0), event->size())); + QGraphicsView::resizeEvent(event); + } +}; + +inline bool matchString(const char *extensionString, const char *subString) +{ + int subStringLength = strlen(subString); + return (strncmp(extensionString, subString, subStringLength) == 0) + && ((extensionString[subStringLength] == ' ') || (extensionString[subStringLength] == '\0')); +} + +bool necessaryExtensionsSupported() +{ + const char *extensionString = reinterpret_cast(glGetString(GL_EXTENSIONS)); + const char *p = extensionString; + + const int GL_EXT_FBO = 1; + const int GL_ARB_VS = 2; + const int GL_ARB_FS = 4; + const int GL_ARB_SO = 8; + int extensions = 0; + + while (*p) { + if (matchString(p, "GL_EXT_framebuffer_object")) + extensions |= GL_EXT_FBO; + else if (matchString(p, "GL_ARB_vertex_shader")) + extensions |= GL_ARB_VS; + else if (matchString(p, "GL_ARB_fragment_shader")) + extensions |= GL_ARB_FS; + else if (matchString(p, "GL_ARB_shader_objects")) + extensions |= GL_ARB_SO; + while ((*p != ' ') && (*p != '\0')) + ++p; + if (*p == ' ') + ++p; + } + return (extensions == 15); +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_5) == 0) { + QMessageBox::critical(0, "OpenGL features missing", + "OpenGL version 1.5 or higher is required to run this demo.\n" + "The program will now exit."); + return -1; + } + + int maxTextureSize = 1024; + QGLWidget *widget = new QGLWidget(QGLFormat(QGL::SampleBuffers)); + widget->makeCurrent(); + + if (!necessaryExtensionsSupported()) { + QMessageBox::critical(0, "OpenGL features missing", + "The OpenGL extensions required to run this demo are missing.\n" + "The program will now exit."); + delete widget; + return -2; + } + + // Check if all the necessary functions are resolved. + if (!getGLExtensionFunctions().resolve(widget->context())) { + QMessageBox::critical(0, "OpenGL features missing", + "Failed to resolve OpenGL functions required to run this demo.\n" + "The program will now exit."); + delete widget; + return -3; + } + + // TODO: Make conditional for final release + QMessageBox::information(0, "For your information", + "This demo can be GPU and CPU intensive and may\n" + "work poorly or not at all on your system."); + + widget->makeCurrent(); // The current context must be set before calling Scene's constructor + Scene scene(1024, 768, maxTextureSize); + GraphicsView view; + view.setViewport(widget); + view.setViewportUpdateMode(QGraphicsView::FullViewportUpdate); + view.setScene(&scene); + view.show(); + + return app.exec(); +} + diff --git a/examples/graphicsview/boxes/marble.fsh b/examples/graphicsview/boxes/marble.fsh new file mode 100644 index 0000000000..170ec3abef --- /dev/null +++ b/examples/graphicsview/boxes/marble.fsh @@ -0,0 +1,71 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform sampler3D noise; + +//const vec4 marbleColors[2] = {vec4(0.9, 0.9, 0.9, 1), vec4(0.6, 0.5, 0.5, 1)}; +uniform vec4 marbleColors[2]; + +void main() +{ + float turbulence = 0.0; + float scale = 1.0; + for (int i = 0; i < 4; ++i) { + turbulence += scale * (texture3D(noise, 0.125 * gl_TexCoord[1].xyz / scale).x - 0.5); + scale *= 0.5; + } + + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + vec4 unlitColor = mix(marbleColors[0], marbleColors[1], exp(-4.0 * abs(turbulence))); + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/graphicsview/boxes/parameters.par b/examples/graphicsview/boxes/parameters.par new file mode 100644 index 0000000000..50e20739b9 --- /dev/null +++ b/examples/graphicsview/boxes/parameters.par @@ -0,0 +1,5 @@ +color basicColor ff0e3d0e +color woodColors ff5e3d33 ffcc9966 +float woodTubulence 0.1 +color graniteColors ff000000 ff4d261a ffccb3bf +color marbleColors ffe6e6e6 ff998080 diff --git a/examples/graphicsview/boxes/qt-logo.jpg b/examples/graphicsview/boxes/qt-logo.jpg new file mode 100644 index 0000000000..4014b4659c Binary files /dev/null and b/examples/graphicsview/boxes/qt-logo.jpg differ diff --git a/examples/graphicsview/boxes/qt-logo.png b/examples/graphicsview/boxes/qt-logo.png new file mode 100644 index 0000000000..7d3e97eb36 Binary files /dev/null and b/examples/graphicsview/boxes/qt-logo.png differ diff --git a/examples/graphicsview/boxes/qtbox.cpp b/examples/graphicsview/boxes/qtbox.cpp new file mode 100644 index 0000000000..d24116578c --- /dev/null +++ b/examples/graphicsview/boxes/qtbox.cpp @@ -0,0 +1,480 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qtbox.h" + +const qreal ROTATE_SPEED_X = 30.0 / 1000.0; +const qreal ROTATE_SPEED_Y = 20.0 / 1000.0; +const qreal ROTATE_SPEED_Z = 40.0 / 1000.0; +const int MAX_ITEM_SIZE = 512; +const int MIN_ITEM_SIZE = 16; + +//============================================================================// +// ItemBase // +//============================================================================// + +ItemBase::ItemBase(int size, int x, int y) : m_size(size), m_isResizing(false) +{ + setFlag(QGraphicsItem::ItemIsMovable, true); + setFlag(QGraphicsItem::ItemIsSelectable, true); + setFlag(QGraphicsItem::ItemIsFocusable, true); + setAcceptHoverEvents(true); + setPos(x, y); + m_startTime = QTime::currentTime(); +} + +ItemBase::~ItemBase() +{ +} + +QRectF ItemBase::boundingRect() const +{ + return QRectF(-m_size / 2, -m_size / 2, m_size, m_size); +} + +void ItemBase::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) +{ + if (option->state & QStyle::State_Selected) { + painter->setRenderHint(QPainter::Antialiasing, true); + if (option->state & QStyle::State_HasFocus) + painter->setPen(Qt::yellow); + else + painter->setPen(Qt::white); + painter->drawRect(boundingRect()); + + painter->drawLine(m_size / 2 - 9, m_size / 2, m_size / 2, m_size / 2 - 9); + painter->drawLine(m_size / 2 - 6, m_size / 2, m_size / 2, m_size / 2 - 6); + painter->drawLine(m_size / 2 - 3, m_size / 2, m_size / 2, m_size / 2 - 3); + + painter->setRenderHint(QPainter::Antialiasing, false); + } +} + +void ItemBase::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) +{ + if (!isSelected() && scene()) { + scene()->clearSelection(); + setSelected(true); + } + + QMenu menu; + QAction *delAction = menu.addAction("Delete"); + QAction *newAction = menu.addAction("New"); + QAction *growAction = menu.addAction("Grow"); + QAction *shrinkAction = menu.addAction("Shrink"); + + QAction *selectedAction = menu.exec(event->screenPos()); + + if (selectedAction == delAction) + deleteSelectedItems(scene()); + else if (selectedAction == newAction) + duplicateSelectedItems(scene()); + else if (selectedAction == growAction) + growSelectedItems(scene()); + else if (selectedAction == shrinkAction) + shrinkSelectedItems(scene()); +} + +void ItemBase::duplicateSelectedItems(QGraphicsScene *scene) +{ + if (!scene) + return; + + QList selected; + selected = scene->selectedItems(); + + foreach (QGraphicsItem *item, selected) { + ItemBase *itemBase = qgraphicsitem_cast(item); + if (itemBase) + scene->addItem(itemBase->createNew(itemBase->m_size, itemBase->pos().x() + itemBase->m_size, itemBase->pos().y())); + } +} + +void ItemBase::deleteSelectedItems(QGraphicsScene *scene) +{ + if (!scene) + return; + + QList selected; + selected = scene->selectedItems(); + + foreach (QGraphicsItem *item, selected) { + ItemBase *itemBase = qgraphicsitem_cast(item); + if (itemBase) + delete itemBase; + } +} + +void ItemBase::growSelectedItems(QGraphicsScene *scene) +{ + if (!scene) + return; + + QList selected; + selected = scene->selectedItems(); + + foreach (QGraphicsItem *item, selected) { + ItemBase *itemBase = qgraphicsitem_cast(item); + if (itemBase) { + itemBase->prepareGeometryChange(); + itemBase->m_size *= 2; + if (itemBase->m_size > MAX_ITEM_SIZE) + itemBase->m_size = MAX_ITEM_SIZE; + } + } +} + +void ItemBase::shrinkSelectedItems(QGraphicsScene *scene) +{ + if (!scene) + return; + + QList selected; + selected = scene->selectedItems(); + + foreach (QGraphicsItem *item, selected) { + ItemBase *itemBase = qgraphicsitem_cast(item); + if (itemBase) { + itemBase->prepareGeometryChange(); + itemBase->m_size /= 2; + if (itemBase->m_size < MIN_ITEM_SIZE) + itemBase->m_size = MIN_ITEM_SIZE; + } + } +} + +void ItemBase::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + if (m_isResizing) { + int dx = int(2.0 * event->pos().x()); + int dy = int(2.0 * event->pos().y()); + prepareGeometryChange(); + m_size = (dx > dy ? dx : dy); + if (m_size < MIN_ITEM_SIZE) + m_size = MIN_ITEM_SIZE; + else if (m_size > MAX_ITEM_SIZE) + m_size = MAX_ITEM_SIZE; + } else { + QGraphicsItem::mouseMoveEvent(event); + } +} + +void ItemBase::hoverMoveEvent(QGraphicsSceneHoverEvent *event) +{ + if (m_isResizing || (isInResizeArea(event->pos()) && isSelected())) + setCursor(Qt::SizeFDiagCursor); + else + setCursor(Qt::ArrowCursor); + QGraphicsItem::hoverMoveEvent(event); +} + +void ItemBase::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + static qreal z = 0.0; + setZValue(z += 1.0); + if (event->button() == Qt::LeftButton && isInResizeArea(event->pos())) { + m_isResizing = true; + } else { + QGraphicsItem::mousePressEvent(event); + } +} + +void ItemBase::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + if (event->button() == Qt::LeftButton && m_isResizing) { + m_isResizing = false; + } else { + QGraphicsItem::mouseReleaseEvent(event); + } +} + +void ItemBase::keyPressEvent(QKeyEvent *event) +{ + switch (event->key()) { + case Qt::Key_Delete: + deleteSelectedItems(scene()); + break; + case Qt::Key_Insert: + duplicateSelectedItems(scene()); + break; + case Qt::Key_Plus: + growSelectedItems(scene()); + break; + case Qt::Key_Minus: + shrinkSelectedItems(scene()); + break; + default: + QGraphicsItem::keyPressEvent(event); + break; + } +} + +void ItemBase::wheelEvent(QGraphicsSceneWheelEvent *event) +{ + prepareGeometryChange(); + m_size = int(m_size * exp(-event->delta() / 600.0)); + if (m_size > MAX_ITEM_SIZE) + m_size = MAX_ITEM_SIZE; + else if (m_size < MIN_ITEM_SIZE) + m_size = MIN_ITEM_SIZE; +} + +int ItemBase::type() const +{ + return Type; +} + + +bool ItemBase::isInResizeArea(const QPointF &pos) +{ + return (-pos.y() < pos.x() - m_size + 9); +} + +//============================================================================// +// QtBox // +//============================================================================// + +QtBox::QtBox(int size, int x, int y) : ItemBase(size, x, y), m_texture(0) +{ + for (int i = 0; i < 8; ++i) { + m_vertices[i].setX(i & 1 ? 0.5f : -0.5f); + m_vertices[i].setY(i & 2 ? 0.5f : -0.5f); + m_vertices[i].setZ(i & 4 ? 0.5f : -0.5f); + } + for (int i = 0; i < 4; ++i) { + m_texCoords[i].setX(i & 1 ? 1.0f : 0.0f); + m_texCoords[i].setY(i & 2 ? 1.0f : 0.0f); + } + m_normals[0] = QVector3D(-1.0f, 0.0f, 0.0f); + m_normals[1] = QVector3D(1.0f, 0.0f, 0.0f); + m_normals[2] = QVector3D(0.0f, -1.0f, 0.0f); + m_normals[3] = QVector3D(0.0f, 1.0f, 0.0f); + m_normals[4] = QVector3D(0.0f, 0.0f, -1.0f); + m_normals[5] = QVector3D(0.0f, 0.0f, 1.0f); +} + +QtBox::~QtBox() +{ + if (m_texture) + delete m_texture; +} + +ItemBase *QtBox::createNew(int size, int x, int y) +{ + return new QtBox(size, x, y); +} + +void QtBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + QRectF rect = boundingRect().translated(pos()); + float width = float(painter->device()->width()); + float height = float(painter->device()->height()); + + float left = 2.0f * float(rect.left()) / width - 1.0f; + float right = 2.0f * float(rect.right()) / width - 1.0f; + float top = 1.0f - 2.0f * float(rect.top()) / height; + float bottom = 1.0f - 2.0f * float(rect.bottom()) / height; + float moveToRectMatrix[] = { + 0.5f * (right - left), 0.0f, 0.0f, 0.0f, + 0.0f, 0.5f * (bottom - top), 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.5f * (right + left), 0.5f * (bottom + top), 0.0f, 1.0f + }; + + painter->beginNativePainting(); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadMatrixf(moveToRectMatrix); + qgluPerspective(60.0, 1.0, 0.01, 10.0); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + //glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + glEnable(GL_COLOR_MATERIAL); + glEnable(GL_NORMALIZE); + + if(m_texture == 0) + m_texture = new GLTexture2D(":/res/boxes/qt-logo.jpg", 64, 64); + m_texture->bind(); + glEnable(GL_TEXTURE_2D); + + glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); + float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f}; + float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f}; + glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour); + glLightfv(GL_LIGHT0, GL_POSITION, lightDir); + glEnable(GL_LIGHT0); + + glTranslatef(0.0f, 0.0f, -1.5f); + glRotatef(ROTATE_SPEED_X * m_startTime.msecsTo(QTime::currentTime()), 1.0f, 0.0f, 0.0f); + glRotatef(ROTATE_SPEED_Y * m_startTime.msecsTo(QTime::currentTime()), 0.0f, 1.0f, 0.0f); + glRotatef(ROTATE_SPEED_Z * m_startTime.msecsTo(QTime::currentTime()), 0.0f, 0.0f, 1.0f); + int dt = m_startTime.msecsTo(QTime::currentTime()); + if (dt < 500) + glScalef(dt / 500.0f, dt / 500.0f, dt / 500.0f); + + for (int dir = 0; dir < 3; ++dir) { + glColor4f(1.0f, 1.0f, 1.0f, 1.0); + + glBegin(GL_TRIANGLE_STRIP); + glNormal3fv(reinterpret_cast(&m_normals[2 * dir + 0])); + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 2; ++j) { + glTexCoord2fv(reinterpret_cast(&m_texCoords[(j << 1) | i])); + glVertex3fv(reinterpret_cast(&m_vertices[(i << ((dir + 2) % 3)) | (j << ((dir + 1) % 3))])); + } + } + glEnd(); + + glBegin(GL_TRIANGLE_STRIP); + glNormal3fv(reinterpret_cast(&m_normals[2 * dir + 1])); + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 2; ++j) { + glTexCoord2fv(reinterpret_cast(&m_texCoords[(j << 1) | i])); + glVertex3fv(reinterpret_cast(&m_vertices[(1 << dir) | (i << ((dir + 1) % 3)) | (j << ((dir + 2) % 3))])); + } + } + glEnd(); + } + m_texture->unbind(); + + //glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_LIGHTING); + glDisable(GL_COLOR_MATERIAL); + glDisable(GL_TEXTURE_2D); + glDisable(GL_LIGHT0); + glDisable(GL_NORMALIZE); + + glPopMatrix(); + + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + painter->endNativePainting(); + + ItemBase::paint(painter, option, widget); +} + +//============================================================================// +// CircleItem // +//============================================================================// + +CircleItem::CircleItem(int size, int x, int y) : ItemBase(size, x, y) +{ + m_color = QColor::fromHsv(rand() % 360, 255, 255); +} + +void CircleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + int dt = m_startTime.msecsTo(QTime::currentTime()); + + qreal r0 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 3800) % 4000))); + qreal r1 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 0) % 4000))); + qreal r2 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 1800) % 4000))); + qreal r3 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 2000) % 4000))); + + if (r0 > r1) + r0 = 0.0; + if (r2 > r3) + r2 = 0.0; + + QPainterPath path; + path.moveTo(r1, 0.0); + path.arcTo(-r1, -r1, 2 * r1, 2 * r1, 0.0, 360.0); + path.lineTo(r0, 0.0); + path.arcTo(-r0, -r0, 2 * r0, 2 * r0, 0.0, -360.0); + path.closeSubpath(); + path.moveTo(r3, 0.0); + path.arcTo(-r3, -r3, 2 * r3, 2 * r3, 0.0, 360.0); + path.lineTo(r0, 0.0); + path.arcTo(-r2, -r2, 2 * r2, 2 * r2, 0.0, -360.0); + path.closeSubpath(); + painter->setRenderHint(QPainter::Antialiasing, true); + painter->setBrush(QBrush(m_color)); + painter->setPen(Qt::NoPen); + painter->drawPath(path); + painter->setBrush(Qt::NoBrush); + painter->setPen(Qt::SolidLine); + painter->setRenderHint(QPainter::Antialiasing, false); + + ItemBase::paint(painter, option, widget); +} + +ItemBase *CircleItem::createNew(int size, int x, int y) +{ + return new CircleItem(size, x, y); +} + +//============================================================================// +// SquareItem // +//============================================================================// + +SquareItem::SquareItem(int size, int x, int y) : ItemBase(size, x, y) +{ + m_image = QPixmap(":/res/boxes/square.jpg"); +} + +void SquareItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + int dt = m_startTime.msecsTo(QTime::currentTime()); + QTransform oldTransform = painter->worldTransform(); + int dtMod = dt % 2000; + qreal amp = 0.002 * (dtMod < 1000 ? dtMod : 2000 - dtMod) - 1.0; + + qreal scale = 0.6 + 0.2 * amp * amp; + painter->setWorldTransform(QTransform().rotate(15.0 * amp).scale(scale, scale), true); + + painter->drawPixmap(-m_size / 2, -m_size / 2, m_size, m_size, m_image); + + painter->setWorldTransform(oldTransform, false); + ItemBase::paint(painter, option, widget); +} + +ItemBase *SquareItem::createNew(int size, int x, int y) +{ + return new SquareItem(size, x, y); +} diff --git a/examples/graphicsview/boxes/qtbox.h b/examples/graphicsview/boxes/qtbox.h new file mode 100644 index 0000000000..56b86a55bb --- /dev/null +++ b/examples/graphicsview/boxes/qtbox.h @@ -0,0 +1,118 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTBOX_H +#define QTBOX_H + +#include + +#include +#include "glbuffers.h" + +class ItemBase : public QGraphicsItem +{ +public: + enum { Type = UserType + 1 }; + + ItemBase(int size, int x, int y); + virtual ~ItemBase(); + virtual QRectF boundingRect() const; + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +protected: + virtual ItemBase *createNew(int size, int x, int y) = 0; + virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); + virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + virtual void hoverMoveEvent(QGraphicsSceneHoverEvent *event); + virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); + virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + virtual void keyPressEvent(QKeyEvent *event); + virtual void wheelEvent(QGraphicsSceneWheelEvent *event); + virtual int type() const; + bool isInResizeArea(const QPointF &pos); + + static void duplicateSelectedItems(QGraphicsScene *scene); + static void deleteSelectedItems(QGraphicsScene *scene); + static void growSelectedItems(QGraphicsScene *scene); + static void shrinkSelectedItems(QGraphicsScene *scene); + + int m_size; + QTime m_startTime; + bool m_isResizing; +}; + +class QtBox : public ItemBase +{ +public: + QtBox(int size, int x, int y); + virtual ~QtBox(); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +protected: + virtual ItemBase *createNew(int size, int x, int y); +private: + QVector3D m_vertices[8]; + QVector3D m_texCoords[4]; + QVector3D m_normals[6]; + GLTexture *m_texture; +}; + +class CircleItem : public ItemBase +{ +public: + CircleItem(int size, int x, int y); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +protected: + virtual ItemBase *createNew(int size, int x, int y); + + QColor m_color; +}; + +class SquareItem : public ItemBase +{ +public: + SquareItem(int size, int x, int y); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +protected: + virtual ItemBase *createNew(int size, int x, int y); + + QPixmap m_image; +}; + +#endif diff --git a/examples/graphicsview/boxes/reflection.fsh b/examples/graphicsview/boxes/reflection.fsh new file mode 100644 index 0000000000..576c522bbb --- /dev/null +++ b/examples/graphicsview/boxes/reflection.fsh @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform samplerCube env; +uniform mat4 view; + +void main() +{ + vec3 N = normalize(normal); + vec3 R = 2.0 * dot(-position, N) * N + position; + gl_FragColor = textureCube(env, R * mat3(view[0].xyz, view[1].xyz, view[2].xyz)); +} diff --git a/examples/graphicsview/boxes/refraction.fsh b/examples/graphicsview/boxes/refraction.fsh new file mode 100644 index 0000000000..10ab38a54c --- /dev/null +++ b/examples/graphicsview/boxes/refraction.fsh @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform samplerCube env; +uniform mat4 view; + +// Arrays don't work here on glsl < 120, apparently. +//const float coeffs[6] = float[6](1.0/2.0, 1.0/2.1, 1.0/2.2, 1.0/2.3, 1.0/2.4, 1.0/2.5); +float coeffs(int i) +{ + return 1.0 / (2.0 + 0.1 * float(i)); +} + +void main() +{ + vec3 N = normalize(normal); + vec3 I = -normalize(position); + float IdotN = dot(I, N); + float scales[6]; + vec3 C[6]; + for (int i = 0; i < 6; ++i) { + scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN))); + C[i] = textureCube(env, (-I + coeffs(i) * N) * mat3(view[0].xyz, view[1].xyz, view[2].xyz)).xyz; + } + + gl_FragColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y, + C[3].z + 2.0*C[4].z + C[5].z, 4.0); +} diff --git a/examples/graphicsview/boxes/roundedbox.cpp b/examples/graphicsview/boxes/roundedbox.cpp new file mode 100644 index 0000000000..5058043707 --- /dev/null +++ b/examples/graphicsview/boxes/roundedbox.cpp @@ -0,0 +1,161 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "roundedbox.h" + +//============================================================================// +// P3T2N3Vertex // +//============================================================================// + +VertexDescription P3T2N3Vertex::description[] = { + {VertexDescription::Position, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, position) / sizeof(float), 0, 0}, + {VertexDescription::TexCoord, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, texCoord) / sizeof(float), sizeof(QVector3D), 0}, + {VertexDescription::Normal, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, normal) / sizeof(float), sizeof(QVector3D) + sizeof(QVector2D), 0}, + + {VertexDescription::Null, 0, 0, 0, 0}, +}; + +//============================================================================// +// GLRoundedBox // +//============================================================================// + +float lerp(float a, float b, float t) +{ + return a * (1.0f - t) + b * t; +} + +GLRoundedBox::GLRoundedBox(float r, float scale, int n) + : GLTriangleMesh((n+2)*(n+3)*4, (n+1)*(n+1)*24+36+72*(n+1)) +{ + int vidx = 0, iidx = 0; + int vertexCountPerCorner = (n + 2) * (n + 3) / 2; + + P3T2N3Vertex *vp = m_vb.lock(); + unsigned short *ip = m_ib.lock(); + + if (!vp || !ip) { + qWarning("GLRoundedBox::GLRoundedBox: Failed to lock vertex buffer and/or index buffer."); + m_ib.unlock(); + m_vb.unlock(); + return; + } + + for (int corner = 0; corner < 8; ++corner) { + QVector3D centre(corner & 1 ? 1.0f : -1.0f, + corner & 2 ? 1.0f : -1.0f, + corner & 4 ? 1.0f : -1.0f); + int winding = (corner & 1) ^ ((corner >> 1) & 1) ^ (corner >> 2); + int offsX = ((corner ^ 1) - corner) * vertexCountPerCorner; + int offsY = ((corner ^ 2) - corner) * vertexCountPerCorner; + int offsZ = ((corner ^ 4) - corner) * vertexCountPerCorner; + + // Face polygons + if (winding) { + ip[iidx++] = vidx; + ip[iidx++] = vidx + offsX; + ip[iidx++] = vidx + offsY; + + ip[iidx++] = vidx + vertexCountPerCorner - n - 2; + ip[iidx++] = vidx + vertexCountPerCorner - n - 2 + offsY; + ip[iidx++] = vidx + vertexCountPerCorner - n - 2 + offsZ; + + ip[iidx++] = vidx + vertexCountPerCorner - 1; + ip[iidx++] = vidx + vertexCountPerCorner - 1 + offsZ; + ip[iidx++] = vidx + vertexCountPerCorner - 1 + offsX; + } + + for (int i = 0; i < n + 2; ++i) { + + // Edge polygons + if (winding && i < n + 1) { + ip[iidx++] = vidx + i + 1; + ip[iidx++] = vidx; + ip[iidx++] = vidx + offsY + i + 1; + ip[iidx++] = vidx + offsY; + ip[iidx++] = vidx + offsY + i + 1; + ip[iidx++] = vidx; + + ip[iidx++] = vidx + i; + ip[iidx++] = vidx + 2 * i + 2; + ip[iidx++] = vidx + i + offsX; + ip[iidx++] = vidx + 2 * i + offsX + 2; + ip[iidx++] = vidx + i + offsX; + ip[iidx++] = vidx + 2 * i + 2; + + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i + offsZ; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i + offsZ; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i + offsZ; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i; + } + + for (int j = 0; j <= i; ++j) { + QVector3D normal = QVector3D(i - j, j, n + 1 - i).normalized(); + QVector3D offset(0.5f - r, 0.5f - r, 0.5f - r); + QVector3D pos = centre * (offset + r * normal); + + vp[vidx].position = scale * pos; + vp[vidx].normal = centre * normal; + vp[vidx].texCoord = QVector2D(pos.x() + 0.5f, pos.y() + 0.5f); + + // Corner polygons + if (i < n + 1) { + ip[iidx++] = vidx; + ip[iidx++] = vidx + i + 2 - winding; + ip[iidx++] = vidx + i + 1 + winding; + } + if (i < n) { + ip[iidx++] = vidx + i + 1 + winding; + ip[iidx++] = vidx + i + 2 - winding; + ip[iidx++] = vidx + 2 * i + 4; + } + + ++vidx; + } + } + + } + + m_ib.unlock(); + m_vb.unlock(); +} + diff --git a/examples/graphicsview/boxes/roundedbox.h b/examples/graphicsview/boxes/roundedbox.h new file mode 100644 index 0000000000..54dda82000 --- /dev/null +++ b/examples/graphicsview/boxes/roundedbox.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ROUNDEDBOX_H +#define ROUNDEDBOX_H + +//#include +#include "glextensions.h" + +#include +#include + +#include "gltrianglemesh.h" +#include +#include +#include "glbuffers.h" + +struct P3T2N3Vertex +{ + QVector3D position; + QVector2D texCoord; + QVector3D normal; + static VertexDescription description[]; +}; + +class GLRoundedBox : public GLTriangleMesh +{ +public: + // 0 < r < 0.5, 0 <= n <= 125 + GLRoundedBox(float r = 0.25f, float scale = 1.0f, int n = 10); +}; + + +#endif diff --git a/examples/graphicsview/boxes/scene.cpp b/examples/graphicsview/boxes/scene.cpp new file mode 100644 index 0000000000..39cd0fcafd --- /dev/null +++ b/examples/graphicsview/boxes/scene.cpp @@ -0,0 +1,1085 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "scene.h" +#include +#include + +#include "3rdparty/fbm.h" + +void checkGLErrors(const QString& prefix) +{ + switch (glGetError()) { + case GL_NO_ERROR: + //qDebug() << prefix << tr("No error."); + break; + case GL_INVALID_ENUM: + qDebug() << prefix << QObject::tr("Invalid enum."); + break; + case GL_INVALID_VALUE: + qDebug() << prefix << QObject::tr("Invalid value."); + break; + case GL_INVALID_OPERATION: + qDebug() << prefix << QObject::tr("Invalid operation."); + break; + case GL_STACK_OVERFLOW: + qDebug() << prefix << QObject::tr("Stack overflow."); + break; + case GL_STACK_UNDERFLOW: + qDebug() << prefix << QObject::tr("Stack underflow."); + break; + case GL_OUT_OF_MEMORY: + qDebug() << prefix << QObject::tr("Out of memory."); + break; + default: + qDebug() << prefix << QObject::tr("Unknown error."); + break; + } +} + +//============================================================================// +// ColorEdit // +//============================================================================// + +ColorEdit::ColorEdit(QRgb initialColor, int id) + : m_color(initialColor), m_id(id) +{ + QHBoxLayout *layout = new QHBoxLayout; + setLayout(layout); + layout->setContentsMargins(0, 0, 0, 0); + + m_lineEdit = new QLineEdit(QString::number(m_color, 16)); + layout->addWidget(m_lineEdit); + + m_button = new QFrame; + QPalette palette = m_button->palette(); + palette.setColor(QPalette::Window, QColor(m_color)); + m_button->setPalette(palette); + m_button->setAutoFillBackground(true); + m_button->setMinimumSize(32, 0); + m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); + m_button->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); + layout->addWidget(m_button); + + connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone())); +} + +void ColorEdit::editDone() +{ + bool ok; + QRgb newColor = m_lineEdit->text().toUInt(&ok, 16); + if (ok) + setColor(newColor); +} + +void ColorEdit::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + QColor color(m_color); + QColorDialog dialog(color, 0); + dialog.setOption(QColorDialog::ShowAlphaChannel, true); +// The ifdef block is a workaround for the beta, TODO: remove when bug 238525 is fixed +#ifdef Q_WS_MAC + dialog.setOption(QColorDialog::DontUseNativeDialog, true); +#endif + dialog.move(280, 120); + if (dialog.exec() == QDialog::Rejected) + return; + QRgb newColor = dialog.selectedColor().rgba(); + if (newColor == m_color) + return; + setColor(newColor); + } +} + +void ColorEdit::setColor(QRgb color) +{ + m_color = color; + m_lineEdit->setText(QString::number(m_color, 16)); // "Clean up" text + QPalette palette = m_button->palette(); + palette.setColor(QPalette::Window, QColor(m_color)); + m_button->setPalette(palette); + emit colorChanged(m_color, m_id); +} + +//============================================================================// +// FloatEdit // +//============================================================================// + +FloatEdit::FloatEdit(float initialValue, int id) + : m_value(initialValue), m_id(id) +{ + QHBoxLayout *layout = new QHBoxLayout; + setLayout(layout); + layout->setContentsMargins(0, 0, 0, 0); + + m_lineEdit = new QLineEdit(QString::number(m_value)); + layout->addWidget(m_lineEdit); + + connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone())); +} + +void FloatEdit::editDone() +{ + bool ok; + float newValue = m_lineEdit->text().toFloat(&ok); + if (ok) { + m_value = newValue; + m_lineEdit->setText(QString::number(m_value)); // "Clean up" text + emit valueChanged(m_value, m_id); + } +} + +//============================================================================// +// TwoSidedGraphicsWidget // +//============================================================================// + +TwoSidedGraphicsWidget::TwoSidedGraphicsWidget(QGraphicsScene *scene) + : QObject(scene) + , m_current(0) + , m_angle(0) + , m_delta(0) +{ + for (int i = 0; i < 2; ++i) + m_proxyWidgets[i] = 0; +} + +void TwoSidedGraphicsWidget::setWidget(int index, QWidget *widget) +{ + if (index < 0 || index >= 2) + { + qWarning("TwoSidedGraphicsWidget::setWidget: Index out of bounds, index == %d", index); + return; + } + + GraphicsWidget *proxy = new GraphicsWidget; + proxy->setWidget(widget); + + if (m_proxyWidgets[index]) + delete m_proxyWidgets[index]; + m_proxyWidgets[index] = proxy; + + proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache); + proxy->setZValue(1e30); // Make sure the dialog is drawn on top of all other (OpenGL) items + + if (index != m_current) + proxy->setVisible(false); + + qobject_cast(parent())->addItem(proxy); +} + +QWidget *TwoSidedGraphicsWidget::widget(int index) +{ + if (index < 0 || index >= 2) + { + qWarning("TwoSidedGraphicsWidget::widget: Index out of bounds, index == %d", index); + return 0; + } + return m_proxyWidgets[index]->widget(); +} + +void TwoSidedGraphicsWidget::flip() +{ + m_delta = (m_current == 0 ? 9 : -9); + animateFlip(); +} + +void TwoSidedGraphicsWidget::animateFlip() +{ + m_angle += m_delta; + if (m_angle == 90) { + int old = m_current; + m_current ^= 1; + m_proxyWidgets[old]->setVisible(false); + m_proxyWidgets[m_current]->setVisible(true); + m_proxyWidgets[m_current]->setGeometry(m_proxyWidgets[old]->geometry()); + } + + QRectF r = m_proxyWidgets[m_current]->boundingRect(); + m_proxyWidgets[m_current]->setTransform(QTransform() + .translate(r.width() / 2, r.height() / 2) + .rotate(m_angle - 180 * m_current, Qt::YAxis) + .translate(-r.width() / 2, -r.height() / 2)); + + if ((m_current == 0 && m_angle > 0) || (m_current == 1 && m_angle < 180)) + QTimer::singleShot(25, this, SLOT(animateFlip())); +} + +QVariant GraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value) +{ + if (change == ItemPositionChange && scene()) { + QRectF rect = boundingRect(); + QPointF pos = value.toPointF(); + QRectF sceneRect = scene()->sceneRect(); + if (pos.x() + rect.left() < sceneRect.left()) + pos.setX(sceneRect.left() - rect.left()); + else if (pos.x() + rect.right() >= sceneRect.right()) + pos.setX(sceneRect.right() - rect.right()); + if (pos.y() + rect.top() < sceneRect.top()) + pos.setY(sceneRect.top() - rect.top()); + else if (pos.y() + rect.bottom() >= sceneRect.bottom()) + pos.setY(sceneRect.bottom() - rect.bottom()); + return pos; + } + return QGraphicsProxyWidget::itemChange(change, value); +} + +void GraphicsWidget::resizeEvent(QGraphicsSceneResizeEvent *event) +{ + setCacheMode(QGraphicsItem::NoCache); + setCacheMode(QGraphicsItem::ItemCoordinateCache); + QGraphicsProxyWidget::resizeEvent(event); +} + +void GraphicsWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + painter->setRenderHint(QPainter::Antialiasing, false); + QGraphicsProxyWidget::paint(painter, option, widget); + //painter->setRenderHint(QPainter::Antialiasing, true); +} + +//============================================================================// +// RenderOptionsDialog // +//============================================================================// + +RenderOptionsDialog::RenderOptionsDialog() + : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint) +{ + setWindowOpacity(0.75); + setWindowTitle(tr("Options (double click to flip)")); + QGridLayout *layout = new QGridLayout; + setLayout(layout); + layout->setColumnStretch(1, 1); + + int row = 0; + + QCheckBox *check = new QCheckBox(tr("Dynamic cube map")); + check->setCheckState(Qt::Unchecked); + // Dynamic cube maps are only enabled when multi-texturing and render to texture are available. + check->setEnabled(glActiveTexture && glGenFramebuffersEXT); + connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int))); + layout->addWidget(check, 0, 0, 1, 2); + ++row; + + QPalette palette; + + // Load all .par files + // .par files have a simple syntax for specifying user adjustable uniform variables. + QSet uniforms; + QList filter = QStringList("*.par"); + QList files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); + + foreach (QFileInfo fileInfo, files) { + QFile file(fileInfo.absoluteFilePath()); + if (file.open(QIODevice::ReadOnly)) { + while (!file.atEnd()) { + QList tokens = file.readLine().simplified().split(' '); + QList::const_iterator it = tokens.begin(); + if (it == tokens.end()) + continue; + QByteArray type = *it; + if (++it == tokens.end()) + continue; + QByteArray name = *it; + bool singleElement = (tokens.size() == 3); // type, name and one value + char counter[10] = "000000000"; + int counterPos = 8; // position of last digit + while (++it != tokens.end()) { + m_parameterNames << name; + if (!singleElement) { + m_parameterNames.back() += "["; + m_parameterNames.back() += counter + counterPos; + m_parameterNames.back() += "]"; + int j = 8; // position of last digit + ++counter[j]; + while (j > 0 && counter[j] > '9') { + counter[j] = '0'; + ++counter[--j]; + } + if (j < counterPos) + counterPos = j; + } + + if (type == "color") { + layout->addWidget(new QLabel(m_parameterNames.back())); + bool ok; + ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1); + m_parameterEdits << colorEdit; + layout->addWidget(colorEdit); + connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int))); + ++row; + } else if (type == "float") { + layout->addWidget(new QLabel(m_parameterNames.back())); + bool ok; + FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1); + m_parameterEdits << floatEdit; + layout->addWidget(floatEdit); + connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int))); + ++row; + } + } + } + file.close(); + } + } + + layout->addWidget(new QLabel(tr("Texture:"))); + m_textureCombo = new QComboBox; + connect(m_textureCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(textureChanged(int))); + layout->addWidget(m_textureCombo); + ++row; + + layout->addWidget(new QLabel(tr("Shader:"))); + m_shaderCombo = new QComboBox; + connect(m_shaderCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(shaderChanged(int))); + layout->addWidget(m_shaderCombo); + ++row; + + layout->setRowStretch(row, 1); +} + +int RenderOptionsDialog::addTexture(const QString &name) +{ + m_textureCombo->addItem(name); + return m_textureCombo->count() - 1; +} + +int RenderOptionsDialog::addShader(const QString &name) +{ + m_shaderCombo->addItem(name); + return m_shaderCombo->count() - 1; +} + +void RenderOptionsDialog::emitParameterChanged() +{ + foreach (ParameterEdit *edit, m_parameterEdits) + edit->emitChange(); +} + +void RenderOptionsDialog::setColorParameter(QRgb color, int id) +{ + emit colorParameterChanged(m_parameterNames[id], color); +} + +void RenderOptionsDialog::setFloatParameter(float value, int id) +{ + emit floatParameterChanged(m_parameterNames[id], value); +} + +void RenderOptionsDialog::mouseDoubleClickEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) + emit doubleClicked(); +} + +//============================================================================// +// ItemDialog // +//============================================================================// + +ItemDialog::ItemDialog() + : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint) +{ + setWindowTitle(tr("Items (double click to flip)")); + setWindowOpacity(0.75); + resize(160, 100); + + QVBoxLayout *layout = new QVBoxLayout; + setLayout(layout); + QPushButton *button; + + button = new QPushButton(tr("Add Qt box")); + layout->addWidget(button); + connect(button, SIGNAL(clicked()), this, SLOT(triggerNewQtBox())); + + button = new QPushButton(tr("Add circle")); + layout->addWidget(button); + connect(button, SIGNAL(clicked()), this, SLOT(triggerNewCircleItem())); + + button = new QPushButton(tr("Add square")); + layout->addWidget(button); + connect(button, SIGNAL(clicked()), this, SLOT(triggerNewSquareItem())); + + layout->addStretch(1); +} + +void ItemDialog::triggerNewQtBox() +{ + emit newItemTriggered(QtBoxItem); +} + +void ItemDialog::triggerNewCircleItem() +{ + emit newItemTriggered(CircleItem); +} + +void ItemDialog::triggerNewSquareItem() +{ + emit newItemTriggered(SquareItem); +} + +void ItemDialog::mouseDoubleClickEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) + emit doubleClicked(); +} + +//============================================================================// +// Scene // +//============================================================================// + +const static char environmentShaderText[] = + "uniform samplerCube env;" + "void main() {" + "gl_FragColor = textureCube(env, gl_TexCoord[1].xyz);" + "}"; + +Scene::Scene(int width, int height, int maxTextureSize) + : m_distExp(600) + , m_frame(0) + , m_maxTextureSize(maxTextureSize) + , m_currentShader(0) + , m_currentTexture(0) + , m_dynamicCubemap(false) + , m_updateAllCubemaps(true) + , m_box(0) + , m_vertexShader(0) + , m_environmentShader(0) + , m_environmentProgram(0) +{ + setSceneRect(0, 0, width, height); + + m_trackBalls[0] = TrackBall(0.05f, QVector3D(0, 1, 0), TrackBall::Sphere); + m_trackBalls[1] = TrackBall(0.005f, QVector3D(0, 0, 1), TrackBall::Sphere); + m_trackBalls[2] = TrackBall(0.0f, QVector3D(0, 1, 0), TrackBall::Plane); + + m_renderOptions = new RenderOptionsDialog; + m_renderOptions->move(20, 120); + m_renderOptions->resize(m_renderOptions->sizeHint()); + + connect(m_renderOptions, SIGNAL(dynamicCubemapToggled(int)), this, SLOT(toggleDynamicCubemap(int))); + connect(m_renderOptions, SIGNAL(colorParameterChanged(QString,QRgb)), this, SLOT(setColorParameter(QString,QRgb))); + connect(m_renderOptions, SIGNAL(floatParameterChanged(QString,float)), this, SLOT(setFloatParameter(QString,float))); + connect(m_renderOptions, SIGNAL(textureChanged(int)), this, SLOT(setTexture(int))); + connect(m_renderOptions, SIGNAL(shaderChanged(int)), this, SLOT(setShader(int))); + + m_itemDialog = new ItemDialog; + connect(m_itemDialog, SIGNAL(newItemTriggered(ItemDialog::ItemType)), this, SLOT(newItem(ItemDialog::ItemType))); + + TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this); + twoSided->setWidget(0, m_renderOptions); + twoSided->setWidget(1, m_itemDialog); + + connect(m_renderOptions, SIGNAL(doubleClicked()), twoSided, SLOT(flip())); + connect(m_itemDialog, SIGNAL(doubleClicked()), twoSided, SLOT(flip())); + + addItem(new QtBox(64, width - 64, height - 64)); + addItem(new QtBox(64, width - 64, 64)); + addItem(new QtBox(64, 64, height - 64)); + addItem(new QtBox(64, 64, 64)); + + initGL(); + + m_timer = new QTimer(this); + m_timer->setInterval(20); + connect(m_timer, SIGNAL(timeout()), this, SLOT(update())); + m_timer->start(); + + m_time.start(); +} + +Scene::~Scene() +{ + if (m_box) + delete m_box; + foreach (GLTexture *texture, m_textures) + if (texture) delete texture; + if (m_mainCubemap) + delete m_mainCubemap; + foreach (QGLShaderProgram *program, m_programs) + if (program) delete program; + if (m_vertexShader) + delete m_vertexShader; + foreach (QGLShader *shader, m_fragmentShaders) + if (shader) delete shader; + foreach (GLRenderTargetCube *rt, m_cubemaps) + if (rt) delete rt; + if (m_environmentShader) + delete m_environmentShader; + if (m_environmentProgram) + delete m_environmentProgram; +} + +void Scene::initGL() +{ + m_box = new GLRoundedBox(0.25f, 1.0f, 10); + + m_vertexShader = new QGLShader(QGLShader::Vertex); + m_vertexShader->compileSourceFile(QLatin1String(":/res/boxes/basic.vsh")); + + QStringList list; + list << ":/res/boxes/cubemap_posx.jpg" << ":/res/boxes/cubemap_negx.jpg" << ":/res/boxes/cubemap_posy.jpg" + << ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg"; + m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize)); + m_environmentShader = new QGLShader(QGLShader::Fragment); + m_environmentShader->compileSourceCode(environmentShaderText); + m_environmentProgram = new QGLShaderProgram; + m_environmentProgram->addShader(m_vertexShader); + m_environmentProgram->addShader(m_environmentShader); + m_environmentProgram->link(); + + const int NOISE_SIZE = 128; // for a different size, B and BM in fbm.c must also be changed + m_noise = new GLTexture3D(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE); + QRgb *data = new QRgb[NOISE_SIZE * NOISE_SIZE * NOISE_SIZE]; + memset(data, 0, NOISE_SIZE * NOISE_SIZE * NOISE_SIZE * sizeof(QRgb)); + QRgb *p = data; + float pos[3]; + for (int k = 0; k < NOISE_SIZE; ++k) { + pos[2] = k * (0x20 / (float)NOISE_SIZE); + for (int j = 0; j < NOISE_SIZE; ++j) { + for (int i = 0; i < NOISE_SIZE; ++i) { + for (int byte = 0; byte < 4; ++byte) { + pos[0] = (i + (byte & 1) * 16) * (0x20 / (float)NOISE_SIZE); + pos[1] = (j + (byte & 2) * 8) * (0x20 / (float)NOISE_SIZE); + *p |= (int)(128.0f * (noise3(pos) + 1.0f)) << (byte * 8); + } + ++p; + } + } + } + m_noise->load(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, data); + delete[] data; + + m_mainCubemap = new GLRenderTargetCube(512); + + QStringList filter; + QList files; + + // Load all .png files as textures + m_currentTexture = 0; + filter = QStringList("*.png"); + files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); + + foreach (QFileInfo file, files) { + GLTexture *texture = new GLTexture2D(file.absoluteFilePath(), qMin(256, m_maxTextureSize), qMin(256, m_maxTextureSize)); + if (texture->failed()) { + delete texture; + continue; + } + m_textures << texture; + m_renderOptions->addTexture(file.baseName()); + } + + if (m_textures.size() == 0) + m_textures << new GLTexture2D(qMin(64, m_maxTextureSize), qMin(64, m_maxTextureSize)); + + // Load all .fsh files as fragment shaders + m_currentShader = 0; + filter = QStringList("*.fsh"); + files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); + foreach (QFileInfo file, files) { + QGLShaderProgram *program = new QGLShaderProgram; + QGLShader* shader = new QGLShader(QGLShader::Fragment); + shader->compileSourceFile(file.absoluteFilePath()); + // The program does not take ownership over the shaders, so store them in a vector so they can be deleted afterwards. + program->addShader(m_vertexShader); + program->addShader(shader); + if (!program->link()) { + qWarning("Failed to compile and link shader program"); + qWarning("Vertex shader log:"); + qWarning() << m_vertexShader->log(); + qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):"; + qWarning() << shader->log(); + qWarning("Shader program log:"); + qWarning() << program->log(); + + delete shader; + delete program; + continue; + } + + m_fragmentShaders << shader; + m_programs << program; + m_renderOptions->addShader(file.baseName()); + + program->bind(); + m_cubemaps << ((program->uniformLocation("env") != -1) ? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : 0); + program->release(); + } + + if (m_programs.size() == 0) + m_programs << new QGLShaderProgram; + + m_renderOptions->emitParameterChanged(); +} + +static void loadMatrix(const QMatrix4x4& m) +{ + // static to prevent glLoadMatrixf to fail on certain drivers + static GLfloat mat[16]; + const qreal *data = m.constData(); + for (int index = 0; index < 16; ++index) + mat[index] = data[index]; + glLoadMatrixf(mat); +} + +static void multMatrix(const QMatrix4x4& m) +{ + // static to prevent glMultMatrixf to fail on certain drivers + static GLfloat mat[16]; + const qreal *data = m.constData(); + for (int index = 0; index < 16; ++index) + mat[index] = data[index]; + glMultMatrixf(mat); +} + +// If one of the boxes should not be rendered, set excludeBox to its index. +// If the main box should not be rendered, set excludeBox to -1. +void Scene::renderBoxes(const QMatrix4x4 &view, int excludeBox) +{ + QMatrix4x4 invView = view.inverted(); + + // If multi-texturing is supported, use three saplers. + if (glActiveTexture) { + glActiveTexture(GL_TEXTURE0); + m_textures[m_currentTexture]->bind(); + glActiveTexture(GL_TEXTURE2); + m_noise->bind(); + glActiveTexture(GL_TEXTURE1); + } else { + m_textures[m_currentTexture]->bind(); + } + + glDisable(GL_LIGHTING); + glDisable(GL_CULL_FACE); + + QMatrix4x4 viewRotation(view); + viewRotation(3, 0) = viewRotation(3, 1) = viewRotation(3, 2) = 0.0f; + viewRotation(0, 3) = viewRotation(1, 3) = viewRotation(2, 3) = 0.0f; + viewRotation(3, 3) = 1.0f; + loadMatrix(viewRotation); + glScalef(20.0f, 20.0f, 20.0f); + + // Don't render the environment if the environment texture can't be set for the correct sampler. + if (glActiveTexture) { + m_environment->bind(); + m_environmentProgram->bind(); + m_environmentProgram->setUniformValue("tex", GLint(0)); + m_environmentProgram->setUniformValue("env", GLint(1)); + m_environmentProgram->setUniformValue("noise", GLint(2)); + m_box->draw(); + m_environmentProgram->release(); + m_environment->unbind(); + } + + loadMatrix(view); + + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + + for (int i = 0; i < m_programs.size(); ++i) { + if (i == excludeBox) + continue; + + glPushMatrix(); + QMatrix4x4 m; + m.rotate(m_trackBalls[1].rotation()); + multMatrix(m); + + glRotatef(360.0f * i / m_programs.size(), 0.0f, 0.0f, 1.0f); + glTranslatef(2.0f, 0.0f, 0.0f); + glScalef(0.3f, 0.6f, 0.6f); + + if (glActiveTexture) { + if (m_dynamicCubemap && m_cubemaps[i]) + m_cubemaps[i]->bind(); + else + m_environment->bind(); + } + m_programs[i]->bind(); + m_programs[i]->setUniformValue("tex", GLint(0)); + m_programs[i]->setUniformValue("env", GLint(1)); + m_programs[i]->setUniformValue("noise", GLint(2)); + m_programs[i]->setUniformValue("view", view); + m_programs[i]->setUniformValue("invView", invView); + m_box->draw(); + m_programs[i]->release(); + + if (glActiveTexture) { + if (m_dynamicCubemap && m_cubemaps[i]) + m_cubemaps[i]->unbind(); + else + m_environment->unbind(); + } + glPopMatrix(); + } + + if (-1 != excludeBox) { + QMatrix4x4 m; + m.rotate(m_trackBalls[0].rotation()); + multMatrix(m); + + if (glActiveTexture) { + if (m_dynamicCubemap) + m_mainCubemap->bind(); + else + m_environment->bind(); + } + + m_programs[m_currentShader]->bind(); + m_programs[m_currentShader]->setUniformValue("tex", GLint(0)); + m_programs[m_currentShader]->setUniformValue("env", GLint(1)); + m_programs[m_currentShader]->setUniformValue("noise", GLint(2)); + m_programs[m_currentShader]->setUniformValue("view", view); + m_programs[m_currentShader]->setUniformValue("invView", invView); + m_box->draw(); + m_programs[m_currentShader]->release(); + + if (glActiveTexture) { + if (m_dynamicCubemap) + m_mainCubemap->unbind(); + else + m_environment->unbind(); + } + } + + if (glActiveTexture) { + glActiveTexture(GL_TEXTURE2); + m_noise->unbind(); + glActiveTexture(GL_TEXTURE0); + } + m_textures[m_currentTexture]->unbind(); +} + +void Scene::setStates() +{ + //glClearColor(0.25f, 0.25f, 0.5f, 1.0f); + + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + //glEnable(GL_COLOR_MATERIAL); + glEnable(GL_TEXTURE_2D); + glEnable(GL_NORMALIZE); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + setLights(); + + float materialSpecular[] = {0.5f, 0.5f, 0.5f, 1.0f}; + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular); + glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 32.0f); +} + +void Scene::setLights() +{ + glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); + //float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f}; + float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f}; + //glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour); + //glLightfv(GL_LIGHT0, GL_SPECULAR, lightColour); + glLightfv(GL_LIGHT0, GL_POSITION, lightDir); + glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0f); + glEnable(GL_LIGHT0); +} + +void Scene::defaultStates() +{ + //glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_LIGHTING); + //glDisable(GL_COLOR_MATERIAL); + glDisable(GL_TEXTURE_2D); + glDisable(GL_LIGHT0); + glDisable(GL_NORMALIZE); + + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 0.0f); + float defaultMaterialSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f}; + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defaultMaterialSpecular); + glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f); +} + +void Scene::renderCubemaps() +{ + // To speed things up, only update the cubemaps for the small cubes every N frames. + const int N = (m_updateAllCubemaps ? 1 : 3); + + QMatrix4x4 mat; + GLRenderTargetCube::getProjectionMatrix(mat, 0.1f, 100.0f); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + loadMatrix(mat); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + + QVector3D center; + + for (int i = m_frame % N; i < m_cubemaps.size(); i += N) { + if (0 == m_cubemaps[i]) + continue; + + float angle = 2.0f * PI * i / m_cubemaps.size(); + + center = m_trackBalls[1].rotation().rotatedVector(QVector3D(cos(angle), sin(angle), 0.0f)); + + for (int face = 0; face < 6; ++face) { + m_cubemaps[i]->begin(face); + + GLRenderTargetCube::getViewMatrix(mat, face); + QVector4D v = QVector4D(-center.x(), -center.y(), -center.z(), 1.0); + mat.setColumn(3, mat * v); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + renderBoxes(mat, i); + + m_cubemaps[i]->end(); + } + } + + for (int face = 0; face < 6; ++face) { + m_mainCubemap->begin(face); + GLRenderTargetCube::getViewMatrix(mat, face); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + renderBoxes(mat, -1); + + m_mainCubemap->end(); + } + + glPopMatrix(); + + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + m_updateAllCubemaps = false; +} + +void Scene::drawBackground(QPainter *painter, const QRectF &) +{ + float width = float(painter->device()->width()); + float height = float(painter->device()->height()); + + painter->beginNativePainting(); + setStates(); + + if (m_dynamicCubemap) + renderCubemaps(); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glMatrixMode(GL_PROJECTION); + qgluPerspective(60.0, width / height, 0.01, 15.0); + + glMatrixMode(GL_MODELVIEW); + + QMatrix4x4 view; + view.rotate(m_trackBalls[2].rotation()); + view(2, 3) -= 2.0f * exp(m_distExp / 1200.0f); + renderBoxes(view); + + defaultStates(); + ++m_frame; + + painter->endNativePainting(); +} + +QPointF Scene::pixelPosToViewPos(const QPointF& p) +{ + return QPointF(2.0 * float(p.x()) / width() - 1.0, + 1.0 - 2.0 * float(p.y()) / height()); +} + +void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsScene::mouseMoveEvent(event); + if (event->isAccepted()) + return; + + if (event->buttons() & Qt::LeftButton) { + m_trackBalls[0].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } else { + m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + } + + if (event->buttons() & Qt::RightButton) { + m_trackBalls[1].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } else { + m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + } + + if (event->buttons() & Qt::MidButton) { + m_trackBalls[2].move(pixelPosToViewPos(event->scenePos()), QQuaternion()); + event->accept(); + } else { + m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion()); + } +} + +void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsScene::mousePressEvent(event); + if (event->isAccepted()) + return; + + if (event->buttons() & Qt::LeftButton) { + m_trackBalls[0].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } + + if (event->buttons() & Qt::RightButton) { + m_trackBalls[1].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } + + if (event->buttons() & Qt::MidButton) { + m_trackBalls[2].push(pixelPosToViewPos(event->scenePos()), QQuaternion()); + event->accept(); + } +} + +void Scene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsScene::mouseReleaseEvent(event); + if (event->isAccepted()) + return; + + if (event->button() == Qt::LeftButton) { + m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } + + if (event->button() == Qt::RightButton) { + m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } + + if (event->button() == Qt::MidButton) { + m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion()); + event->accept(); + } +} + +void Scene::wheelEvent(QGraphicsSceneWheelEvent * event) +{ + QGraphicsScene::wheelEvent(event); + if (!event->isAccepted()) { + m_distExp += event->delta(); + if (m_distExp < -8 * 120) + m_distExp = -8 * 120; + if (m_distExp > 10 * 120) + m_distExp = 10 * 120; + event->accept(); + } +} + +void Scene::setShader(int index) +{ + if (index >= 0 && index < m_fragmentShaders.size()) + m_currentShader = index; +} + +void Scene::setTexture(int index) +{ + if (index >= 0 && index < m_textures.size()) + m_currentTexture = index; +} + +void Scene::toggleDynamicCubemap(int state) +{ + if ((m_dynamicCubemap = (state == Qt::Checked))) + m_updateAllCubemaps = true; +} + +void Scene::setColorParameter(const QString &name, QRgb color) +{ + // set the color in all programs + foreach (QGLShaderProgram *program, m_programs) { + program->bind(); + program->setUniformValue(program->uniformLocation(name), QColor(color)); + program->release(); + } +} + +void Scene::setFloatParameter(const QString &name, float value) +{ + // set the color in all programs + foreach (QGLShaderProgram *program, m_programs) { + program->bind(); + program->setUniformValue(program->uniformLocation(name), value); + program->release(); + } +} + +void Scene::newItem(ItemDialog::ItemType type) +{ + QSize size = sceneRect().size().toSize(); + switch (type) { + case ItemDialog::QtBoxItem: + addItem(new QtBox(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + break; + case ItemDialog::CircleItem: + addItem(new CircleItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + break; + case ItemDialog::SquareItem: + addItem(new SquareItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + break; + default: + break; + } +} diff --git a/examples/graphicsview/boxes/scene.h b/examples/graphicsview/boxes/scene.h new file mode 100644 index 0000000000..96ee908d58 --- /dev/null +++ b/examples/graphicsview/boxes/scene.h @@ -0,0 +1,245 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SCENE_H +#define SCENE_H + +//#include +#include "glextensions.h" + +#include +#include + +#include "roundedbox.h" +#include "gltrianglemesh.h" +#include "trackball.h" +#include "glbuffers.h" +#include "qtbox.h" + +#define PI 3.14159265358979 + +QT_BEGIN_NAMESPACE +class QMatrix4x4; +QT_END_NAMESPACE + +class ParameterEdit : public QWidget +{ +public: + virtual void emitChange() = 0; +}; + +class ColorEdit : public ParameterEdit +{ + Q_OBJECT +public: + ColorEdit(QRgb initialColor, int id); + QRgb color() const {return m_color;} + virtual void emitChange() {emit colorChanged(m_color, m_id);} +public slots: + void editDone(); +signals: + void colorChanged(QRgb color, int id); +protected: + virtual void mousePressEvent(QMouseEvent *event); + void setColor(QRgb color); // also emits colorChanged() +private: + QGraphicsScene *m_dialogParentScene; + QLineEdit *m_lineEdit; + QFrame *m_button; + QRgb m_color; + int m_id; +}; + +class FloatEdit : public ParameterEdit +{ + Q_OBJECT +public: + FloatEdit(float initialValue, int id); + float value() const {return m_value;} + virtual void emitChange() {emit valueChanged(m_value, m_id);} +public slots: + void editDone(); +signals: + void valueChanged(float value, int id); +private: + QGraphicsScene *m_dialogParentScene; + QLineEdit *m_lineEdit; + float m_value; + int m_id; +}; + +class GraphicsWidget : public QGraphicsProxyWidget +{ +public: + GraphicsWidget() : QGraphicsProxyWidget(0, Qt::Window) {} +protected: + virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); + virtual void resizeEvent(QGraphicsSceneResizeEvent *event); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +}; + +class TwoSidedGraphicsWidget : public QObject +{ + Q_OBJECT +public: + TwoSidedGraphicsWidget(QGraphicsScene *scene); + void setWidget(int index, QWidget *widget); + QWidget *widget(int index); +public slots: + void flip(); +protected slots: + void animateFlip(); +private: + GraphicsWidget *m_proxyWidgets[2]; + int m_current; + int m_angle; // angle in degrees + int m_delta; +}; + +class RenderOptionsDialog : public QDialog +{ + Q_OBJECT +public: + RenderOptionsDialog(); + int addTexture(const QString &name); + int addShader(const QString &name); + void emitParameterChanged(); +protected slots: + void setColorParameter(QRgb color, int id); + void setFloatParameter(float value, int id); +signals: + void dynamicCubemapToggled(int); + void colorParameterChanged(const QString &, QRgb); + void floatParameterChanged(const QString &, float); + void textureChanged(int); + void shaderChanged(int); + void doubleClicked(); +protected: + virtual void mouseDoubleClickEvent(QMouseEvent *event); + + QVector m_parameterNames; + QComboBox *m_textureCombo; + QComboBox *m_shaderCombo; + QVector m_parameterEdits; +}; + +class ItemDialog : public QDialog +{ + Q_OBJECT +public: + enum ItemType { + QtBoxItem, + CircleItem, + SquareItem, + }; + + ItemDialog(); +public slots: + void triggerNewQtBox(); + void triggerNewCircleItem(); + void triggerNewSquareItem(); +signals: + void doubleClicked(); + void newItemTriggered(ItemDialog::ItemType type); +protected: + virtual void mouseDoubleClickEvent(QMouseEvent *event); +}; + +class Scene : public QGraphicsScene +{ + Q_OBJECT +public: + Scene(int width, int height, int maxTextureSize); + ~Scene(); + virtual void drawBackground(QPainter *painter, const QRectF &rect); + +public slots: + void setShader(int index); + void setTexture(int index); + void toggleDynamicCubemap(int state); + void setColorParameter(const QString &name, QRgb color); + void setFloatParameter(const QString &name, float value); + void newItem(ItemDialog::ItemType type); +protected: + void renderBoxes(const QMatrix4x4 &view, int excludeBox = -2); + void setStates(); + void setLights(); + void defaultStates(); + void renderCubemaps(); + + virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); + virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + virtual void wheelEvent(QGraphicsSceneWheelEvent * event); +private: + void initGL(); + QPointF pixelPosToViewPos(const QPointF& p); + + QTime m_time; + int m_lastTime; + int m_mouseEventTime; + int m_distExp; + int m_frame; + int m_maxTextureSize; + + int m_currentShader; + int m_currentTexture; + bool m_dynamicCubemap; + bool m_updateAllCubemaps; + + RenderOptionsDialog *m_renderOptions; + ItemDialog *m_itemDialog; + QTimer *m_timer; + GLRoundedBox *m_box; + TrackBall m_trackBalls[3]; + QVector m_textures; + GLTextureCube *m_environment; + GLTexture3D *m_noise; + GLRenderTargetCube *m_mainCubemap; + QVector m_cubemaps; + QVector m_programs; + QGLShader *m_vertexShader; + QVector m_fragmentShaders; + QGLShader *m_environmentShader; + QGLShaderProgram *m_environmentProgram; +}; + +#endif diff --git a/examples/graphicsview/boxes/smiley.png b/examples/graphicsview/boxes/smiley.png new file mode 100644 index 0000000000..41cfda6b23 Binary files /dev/null and b/examples/graphicsview/boxes/smiley.png differ diff --git a/examples/graphicsview/boxes/square.jpg b/examples/graphicsview/boxes/square.jpg new file mode 100644 index 0000000000..03f53bd530 Binary files /dev/null and b/examples/graphicsview/boxes/square.jpg differ diff --git a/examples/graphicsview/boxes/trackball.cpp b/examples/graphicsview/boxes/trackball.cpp new file mode 100644 index 0000000000..1bb864ce90 --- /dev/null +++ b/examples/graphicsview/boxes/trackball.cpp @@ -0,0 +1,160 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "trackball.h" +#include "scene.h" + +//============================================================================// +// TrackBall // +//============================================================================// + +TrackBall::TrackBall(TrackMode mode) + : m_angularVelocity(0) + , m_paused(false) + , m_pressed(false) + , m_mode(mode) +{ + m_axis = QVector3D(0, 1, 0); + m_rotation = QQuaternion(); + m_lastTime = QTime::currentTime(); +} + +TrackBall::TrackBall(float angularVelocity, const QVector3D& axis, TrackMode mode) + : m_axis(axis) + , m_angularVelocity(angularVelocity) + , m_paused(false) + , m_pressed(false) + , m_mode(mode) +{ + m_rotation = QQuaternion(); + m_lastTime = QTime::currentTime(); +} + +void TrackBall::push(const QPointF& p, const QQuaternion &) +{ + m_rotation = rotation(); + m_pressed = true; + m_lastTime = QTime::currentTime(); + m_lastPos = p; + m_angularVelocity = 0.0f; +} + +void TrackBall::move(const QPointF& p, const QQuaternion &transformation) +{ + if (!m_pressed) + return; + + QTime currentTime = QTime::currentTime(); + int msecs = m_lastTime.msecsTo(currentTime); + if (msecs <= 20) + return; + + switch (m_mode) { + case Plane: + { + QLineF delta(m_lastPos, p); + m_angularVelocity = 180*delta.length() / (PI*msecs); + m_axis = QVector3D(-delta.dy(), delta.dx(), 0.0f).normalized(); + m_axis = transformation.rotatedVector(m_axis); + m_rotation = QQuaternion::fromAxisAndAngle(m_axis, 180 / PI * delta.length()) * m_rotation; + } + break; + case Sphere: + { + QVector3D lastPos3D = QVector3D(m_lastPos.x(), m_lastPos.y(), 0.0f); + float sqrZ = 1 - QVector3D::dotProduct(lastPos3D, lastPos3D); + if (sqrZ > 0) + lastPos3D.setZ(sqrt(sqrZ)); + else + lastPos3D.normalize(); + + QVector3D currentPos3D = QVector3D(p.x(), p.y(), 0.0f); + sqrZ = 1 - QVector3D::dotProduct(currentPos3D, currentPos3D); + if (sqrZ > 0) + currentPos3D.setZ(sqrt(sqrZ)); + else + currentPos3D.normalize(); + + m_axis = QVector3D::crossProduct(lastPos3D, currentPos3D); + float angle = 180 / PI * asin(sqrt(QVector3D::dotProduct(m_axis, m_axis))); + + m_angularVelocity = angle / msecs; + m_axis.normalize(); + m_axis = transformation.rotatedVector(m_axis); + m_rotation = QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation; + } + break; + } + + + m_lastPos = p; + m_lastTime = currentTime; +} + +void TrackBall::release(const QPointF& p, const QQuaternion &transformation) +{ + // Calling move() caused the rotation to stop if the framerate was too low. + move(p, transformation); + m_pressed = false; +} + +void TrackBall::start() +{ + m_lastTime = QTime::currentTime(); + m_paused = false; +} + +void TrackBall::stop() +{ + m_rotation = rotation(); + m_paused = true; +} + +QQuaternion TrackBall::rotation() const +{ + if (m_paused || m_pressed) + return m_rotation; + + QTime currentTime = QTime::currentTime(); + float angle = m_angularVelocity * m_lastTime.msecsTo(currentTime); + return QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation; +} + diff --git a/examples/graphicsview/boxes/trackball.h b/examples/graphicsview/boxes/trackball.h new file mode 100644 index 0000000000..097851a42c --- /dev/null +++ b/examples/graphicsview/boxes/trackball.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TRACKBALL_H +#define TRACKBALL_H + +#include + +#include +#include + +class TrackBall +{ +public: + enum TrackMode + { + Plane, + Sphere, + }; + TrackBall(TrackMode mode = Sphere); + TrackBall(float angularVelocity, const QVector3D& axis, TrackMode mode = Sphere); + // coordinates in [-1,1]x[-1,1] + void push(const QPointF& p, const QQuaternion &transformation); + void move(const QPointF& p, const QQuaternion &transformation); + void release(const QPointF& p, const QQuaternion &transformation); + void start(); // starts clock + void stop(); // stops clock + QQuaternion rotation() const; +private: + QQuaternion m_rotation; + QVector3D m_axis; + float m_angularVelocity; + + QPointF m_lastPos; + QTime m_lastTime; + bool m_paused; + bool m_pressed; + TrackMode m_mode; +}; + +#endif diff --git a/examples/graphicsview/boxes/wood.fsh b/examples/graphicsview/boxes/wood.fsh new file mode 100644 index 0000000000..19950b252c --- /dev/null +++ b/examples/graphicsview/boxes/wood.fsh @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform sampler3D noise; + +//const vec4 woodColors[2] = {vec4(0.37,0.24,0.20,1), vec4(0.8,0.6,0.4,1)}; +uniform vec4 woodColors[2]; +//const float woodTubulence = 0.1; +uniform float woodTubulence; + +void main() +{ + float r = length(gl_TexCoord[1].yz); + r += woodTubulence * texture3D(noise, 0.25 * gl_TexCoord[1].xyz).x; + + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + float f = fract(16.0 * r); + vec4 unlitColor = mix(woodColors[0], woodColors[1], min(1.25 * f, 5.0 - 5.0 * f)); + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/graphicsview/chip/chip.cpp b/examples/graphicsview/chip/chip.cpp new file mode 100644 index 0000000000..21b63bae2c --- /dev/null +++ b/examples/graphicsview/chip/chip.cpp @@ -0,0 +1,183 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "chip.h" + +#include + +Chip::Chip(const QColor &color, int x, int y) +{ + this->x = x; + this->y = y; + this->color = color; + setZValue((x + y) % 2); + + setFlags(ItemIsSelectable | ItemIsMovable); + setAcceptsHoverEvents(true); +} + +QRectF Chip::boundingRect() const +{ + return QRectF(0, 0, 110, 70); +} + +QPainterPath Chip::shape() const +{ + QPainterPath path; + path.addRect(14, 14, 82, 42); + return path; +} + +void Chip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + Q_UNUSED(widget); + + QColor fillColor = (option->state & QStyle::State_Selected) ? color.dark(150) : color; + if (option->state & QStyle::State_MouseOver) + fillColor = fillColor.light(125); + + const qreal lod = option->levelOfDetailFromTransform(painter->worldTransform()); + if (lod < 0.2) { + if (lod < 0.125) { + painter->fillRect(QRectF(0, 0, 110, 70), fillColor); + return; + } + + QBrush b = painter->brush(); + painter->setBrush(fillColor); + painter->drawRect(13, 13, 97, 57); + painter->setBrush(b); + return; + } + + QPen oldPen = painter->pen(); + QPen pen = oldPen; + int width = 0; + if (option->state & QStyle::State_Selected) + width += 2; + + pen.setWidth(width); + QBrush b = painter->brush(); + painter->setBrush(QBrush(fillColor.dark(option->state & QStyle::State_Sunken ? 120 : 100))); + + painter->drawRect(QRect(14, 14, 79, 39)); + painter->setBrush(b); + + if (lod >= 1) { + painter->setPen(QPen(Qt::gray, 1)); + painter->drawLine(15, 54, 94, 54); + painter->drawLine(94, 53, 94, 15); + painter->setPen(QPen(Qt::black, 0)); + } + + // Draw text + if (lod >= 2) { + QFont font("Times", 10); + font.setStyleStrategy(QFont::ForceOutline); + painter->setFont(font); + painter->save(); + painter->scale(0.1, 0.1); + painter->drawText(170, 180, QString("Model: VSC-2000 (Very Small Chip) at %1x%2").arg(x).arg(y)); + painter->drawText(170, 200, QString("Serial number: DLWR-WEER-123L-ZZ33-SDSJ")); + painter->drawText(170, 220, QString("Manufacturer: Chip Manufacturer")); + painter->restore(); + } + + // Draw lines + QVarLengthArray lines; + if (lod >= 0.5) { + for (int i = 0; i <= 10; i += (lod > 0.5 ? 1 : 2)) { + lines.append(QLineF(18 + 7 * i, 13, 18 + 7 * i, 5)); + lines.append(QLineF(18 + 7 * i, 54, 18 + 7 * i, 62)); + } + for (int i = 0; i <= 6; i += (lod > 0.5 ? 1 : 2)) { + lines.append(QLineF(5, 18 + i * 5, 13, 18 + i * 5)); + lines.append(QLineF(94, 18 + i * 5, 102, 18 + i * 5)); + } + } + if (lod >= 0.4) { + const QLineF lineData[] = { + QLineF(25, 35, 35, 35), + QLineF(35, 30, 35, 40), + QLineF(35, 30, 45, 35), + QLineF(35, 40, 45, 35), + QLineF(45, 30, 45, 40), + QLineF(45, 35, 55, 35) + }; + lines.append(lineData, 6); + } + painter->drawLines(lines.data(), lines.size()); + + // Draw red ink + if (stuff.size() > 1) { + QPen p = painter->pen(); + painter->setPen(QPen(Qt::red, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo(stuff.first()); + for (int i = 1; i < stuff.size(); ++i) + path.lineTo(stuff.at(i)); + painter->drawPath(path); + painter->setPen(p); + } +} + +void Chip::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsItem::mousePressEvent(event); + update(); +} + +void Chip::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + if (event->modifiers() & Qt::ShiftModifier) { + stuff << event->pos(); + update(); + return; + } + QGraphicsItem::mouseMoveEvent(event); +} + +void Chip::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsItem::mouseReleaseEvent(event); + update(); +} diff --git a/examples/graphicsview/chip/chip.h b/examples/graphicsview/chip/chip.h new file mode 100644 index 0000000000..ff9f636843 --- /dev/null +++ b/examples/graphicsview/chip/chip.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CHIP_H +#define CHIP_H + +#include +#include + +class Chip : public QGraphicsItem +{ +public: + Chip(const QColor &color, int x, int y); + + QRectF boundingRect() const; + QPainterPath shape() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget); + +protected: + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + +private: + int x, y; + QColor color; + QList stuff; +}; + +#endif diff --git a/examples/graphicsview/chip/chip.pro b/examples/graphicsview/chip/chip.pro new file mode 100644 index 0000000000..1e1a7de735 --- /dev/null +++ b/examples/graphicsview/chip/chip.pro @@ -0,0 +1,20 @@ +RESOURCES += images.qrc + +HEADERS += mainwindow.h view.h chip.h +SOURCES += main.cpp +SOURCES += mainwindow.cpp view.cpp chip.cpp + +contains(QT_CONFIG, opengl):QT += opengl + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/chip +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.png *.pro *.html *.doc images +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/chip +INSTALLS += target sources + +symbian: CONFIG += qt_demo diff --git a/examples/graphicsview/chip/fileprint.png b/examples/graphicsview/chip/fileprint.png new file mode 100644 index 0000000000..ba7c02dc18 Binary files /dev/null and b/examples/graphicsview/chip/fileprint.png differ diff --git a/examples/graphicsview/chip/images.qrc b/examples/graphicsview/chip/images.qrc new file mode 100644 index 0000000000..c7cdf0c4c0 --- /dev/null +++ b/examples/graphicsview/chip/images.qrc @@ -0,0 +1,10 @@ + + + qt4logo.png + zoomin.png + zoomout.png + rotateleft.png + rotateright.png + fileprint.png + + diff --git a/examples/graphicsview/chip/main.cpp b/examples/graphicsview/chip/main.cpp new file mode 100644 index 0000000000..e983e4cca6 --- /dev/null +++ b/examples/graphicsview/chip/main.cpp @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mainwindow.h" + +#include + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(images); + + QApplication app(argc, argv); + app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); + + MainWindow window; + window.show(); + + return app.exec(); +} diff --git a/examples/graphicsview/chip/mainwindow.cpp b/examples/graphicsview/chip/mainwindow.cpp new file mode 100644 index 0000000000..7476c00ab1 --- /dev/null +++ b/examples/graphicsview/chip/mainwindow.cpp @@ -0,0 +1,109 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mainwindow.h" +#include "view.h" +#include "chip.h" + +#include + +MainWindow::MainWindow(QWidget *parent) + : QWidget(parent) +{ + populateScene(); + + h1Splitter = new QSplitter; + h2Splitter = new QSplitter; + + QSplitter *vSplitter = new QSplitter; + vSplitter->setOrientation(Qt::Vertical); + vSplitter->addWidget(h1Splitter); + vSplitter->addWidget(h2Splitter); + + View *view = new View("Top left view"); + view->view()->setScene(scene); + h1Splitter->addWidget(view); + + view = new View("Top right view"); + view->view()->setScene(scene); + h1Splitter->addWidget(view); + + view = new View("Bottom left view"); + view->view()->setScene(scene); + h2Splitter->addWidget(view); + + view = new View("Bottom right view"); + view->view()->setScene(scene); + h2Splitter->addWidget(view); + + QHBoxLayout *layout = new QHBoxLayout; + layout->addWidget(vSplitter); + setLayout(layout); + + setWindowTitle(tr("Chip Demo")); +} + +void MainWindow::populateScene() +{ + scene = new QGraphicsScene; + + QImage image(":/qt4logo.png"); + + // Populate scene + int xx = 0; + int nitems = 0; + for (int i = -11000; i < 11000; i += 110) { + ++xx; + int yy = 0; + for (int j = -7000; j < 7000; j += 70) { + ++yy; + qreal x = (i + 11000) / 22000.0; + qreal y = (j + 7000) / 14000.0; + + QColor color(image.pixel(int(image.width() * x), int(image.height() * y))); + QGraphicsItem *item = new Chip(color, xx, yy); + item->setPos(QPointF(i, j)); + scene->addItem(item); + + ++nitems; + } + } +} diff --git a/examples/graphicsview/chip/mainwindow.h b/examples/graphicsview/chip/mainwindow.h new file mode 100644 index 0000000000..650e1f1f3c --- /dev/null +++ b/examples/graphicsview/chip/mainwindow.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include + +QT_FORWARD_DECLARE_CLASS(QGraphicsScene) +QT_FORWARD_DECLARE_CLASS(QGraphicsView) +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QSlider) +QT_FORWARD_DECLARE_CLASS(QSplitter) + +class MainWindow : public QWidget +{ + Q_OBJECT +public: + MainWindow(QWidget *parent = 0); + +private: + void setupMatrix(); + void populateScene(); + + QGraphicsScene *scene; + QSplitter *h1Splitter; + QSplitter *h2Splitter; +}; + +#endif diff --git a/examples/graphicsview/chip/qt4logo.png b/examples/graphicsview/chip/qt4logo.png new file mode 100644 index 0000000000..157e86ed64 Binary files /dev/null and b/examples/graphicsview/chip/qt4logo.png differ diff --git a/examples/graphicsview/chip/rotateleft.png b/examples/graphicsview/chip/rotateleft.png new file mode 100644 index 0000000000..8cfa931986 Binary files /dev/null and b/examples/graphicsview/chip/rotateleft.png differ diff --git a/examples/graphicsview/chip/rotateright.png b/examples/graphicsview/chip/rotateright.png new file mode 100644 index 0000000000..ec5e8664a1 Binary files /dev/null and b/examples/graphicsview/chip/rotateright.png differ diff --git a/examples/graphicsview/chip/view.cpp b/examples/graphicsview/chip/view.cpp new file mode 100644 index 0000000000..5634f85d98 --- /dev/null +++ b/examples/graphicsview/chip/view.cpp @@ -0,0 +1,276 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "view.h" + +#include +#ifndef QT_NO_OPENGL +#include +#endif + +#include + +void GraphicsView::wheelEvent(QWheelEvent *e) +{ + if (e->modifiers() & Qt::ControlModifier) { + if (e->delta() > 0) + view->zoomIn(6); + else + view->zoomOut(6); + e->accept(); + } else { + QGraphicsView::wheelEvent(e); + } +} + +View::View(const QString &name, QWidget *parent) + : QFrame(parent) +{ + setFrameStyle(Sunken | StyledPanel); + graphicsView = new GraphicsView(this); + graphicsView->setRenderHint(QPainter::Antialiasing, false); + graphicsView->setDragMode(QGraphicsView::RubberBandDrag); + graphicsView->setOptimizationFlags(QGraphicsView::DontSavePainterState); + graphicsView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate); + graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse); + + int size = style()->pixelMetric(QStyle::PM_ToolBarIconSize); + QSize iconSize(size, size); + + QToolButton *zoomInIcon = new QToolButton; + zoomInIcon->setAutoRepeat(true); + zoomInIcon->setAutoRepeatInterval(33); + zoomInIcon->setAutoRepeatDelay(0); + zoomInIcon->setIcon(QPixmap(":/zoomin.png")); + zoomInIcon->setIconSize(iconSize); + QToolButton *zoomOutIcon = new QToolButton; + zoomOutIcon->setAutoRepeat(true); + zoomOutIcon->setAutoRepeatInterval(33); + zoomOutIcon->setAutoRepeatDelay(0); + zoomOutIcon->setIcon(QPixmap(":/zoomout.png")); + zoomOutIcon->setIconSize(iconSize); + zoomSlider = new QSlider; + zoomSlider->setMinimum(0); + zoomSlider->setMaximum(500); + zoomSlider->setValue(250); + zoomSlider->setTickPosition(QSlider::TicksRight); + + // Zoom slider layout + QVBoxLayout *zoomSliderLayout = new QVBoxLayout; + zoomSliderLayout->addWidget(zoomInIcon); + zoomSliderLayout->addWidget(zoomSlider); + zoomSliderLayout->addWidget(zoomOutIcon); + + QToolButton *rotateLeftIcon = new QToolButton; + rotateLeftIcon->setIcon(QPixmap(":/rotateleft.png")); + rotateLeftIcon->setIconSize(iconSize); + QToolButton *rotateRightIcon = new QToolButton; + rotateRightIcon->setIcon(QPixmap(":/rotateright.png")); + rotateRightIcon->setIconSize(iconSize); + rotateSlider = new QSlider; + rotateSlider->setOrientation(Qt::Horizontal); + rotateSlider->setMinimum(-360); + rotateSlider->setMaximum(360); + rotateSlider->setValue(0); + rotateSlider->setTickPosition(QSlider::TicksBelow); + + // Rotate slider layout + QHBoxLayout *rotateSliderLayout = new QHBoxLayout; + rotateSliderLayout->addWidget(rotateLeftIcon); + rotateSliderLayout->addWidget(rotateSlider); + rotateSliderLayout->addWidget(rotateRightIcon); + + resetButton = new QToolButton; + resetButton->setText(tr("0")); + resetButton->setEnabled(false); + + // Label layout + QHBoxLayout *labelLayout = new QHBoxLayout; + label = new QLabel(name); + label2 = new QLabel(tr("Pointer Mode")); + selectModeButton = new QToolButton; + selectModeButton->setText(tr("Select")); + selectModeButton->setCheckable(true); + selectModeButton->setChecked(true); + dragModeButton = new QToolButton; + dragModeButton->setText(tr("Drag")); + dragModeButton->setCheckable(true); + dragModeButton->setChecked(false); + antialiasButton = new QToolButton; + antialiasButton->setText(tr("Antialiasing")); + antialiasButton->setCheckable(true); + antialiasButton->setChecked(false); + openGlButton = new QToolButton; + openGlButton->setText(tr("OpenGL")); + openGlButton->setCheckable(true); +#ifndef QT_NO_OPENGL + openGlButton->setEnabled(QGLFormat::hasOpenGL()); +#else + openGlButton->setEnabled(false); +#endif + printButton = new QToolButton; + printButton->setIcon(QIcon(QPixmap(":/fileprint.png"))); + + QButtonGroup *pointerModeGroup = new QButtonGroup; + pointerModeGroup->setExclusive(true); + pointerModeGroup->addButton(selectModeButton); + pointerModeGroup->addButton(dragModeButton); + + labelLayout->addWidget(label); + labelLayout->addStretch(); + labelLayout->addWidget(label2); + labelLayout->addWidget(selectModeButton); + labelLayout->addWidget(dragModeButton); + labelLayout->addStretch(); + labelLayout->addWidget(antialiasButton); + labelLayout->addWidget(openGlButton); + labelLayout->addWidget(printButton); + + QGridLayout *topLayout = new QGridLayout; + topLayout->addLayout(labelLayout, 0, 0); + topLayout->addWidget(graphicsView, 1, 0); + topLayout->addLayout(zoomSliderLayout, 1, 1); + topLayout->addLayout(rotateSliderLayout, 2, 0); + topLayout->addWidget(resetButton, 2, 1); + setLayout(topLayout); + + connect(resetButton, SIGNAL(clicked()), this, SLOT(resetView())); + connect(zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); + connect(rotateSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); + connect(graphicsView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setResetButtonEnabled())); + connect(graphicsView->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setResetButtonEnabled())); + connect(selectModeButton, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); + connect(dragModeButton, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); + connect(antialiasButton, SIGNAL(toggled(bool)), this, SLOT(toggleAntialiasing())); + connect(openGlButton, SIGNAL(toggled(bool)), this, SLOT(toggleOpenGL())); + connect(rotateLeftIcon, SIGNAL(clicked()), this, SLOT(rotateLeft())); + connect(rotateRightIcon, SIGNAL(clicked()), this, SLOT(rotateRight())); + connect(zoomInIcon, SIGNAL(clicked()), this, SLOT(zoomIn())); + connect(zoomOutIcon, SIGNAL(clicked()), this, SLOT(zoomOut())); + connect(printButton, SIGNAL(clicked()), this, SLOT(print())); + + setupMatrix(); +} + +QGraphicsView *View::view() const +{ + return static_cast(graphicsView); +} + +void View::resetView() +{ + zoomSlider->setValue(250); + rotateSlider->setValue(0); + setupMatrix(); + graphicsView->ensureVisible(QRectF(0, 0, 0, 0)); + + resetButton->setEnabled(false); +} + +void View::setResetButtonEnabled() +{ + resetButton->setEnabled(true); +} + +void View::setupMatrix() +{ + qreal scale = qPow(qreal(2), (zoomSlider->value() - 250) / qreal(50)); + + QMatrix matrix; + matrix.scale(scale, scale); + matrix.rotate(rotateSlider->value()); + + graphicsView->setMatrix(matrix); + setResetButtonEnabled(); +} + +void View::togglePointerMode() +{ + graphicsView->setDragMode(selectModeButton->isChecked() + ? QGraphicsView::RubberBandDrag + : QGraphicsView::ScrollHandDrag); + graphicsView->setInteractive(selectModeButton->isChecked()); +} + +void View::toggleOpenGL() +{ +#ifndef QT_NO_OPENGL + graphicsView->setViewport(openGlButton->isChecked() ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget); +#endif +} + +void View::toggleAntialiasing() +{ + graphicsView->setRenderHint(QPainter::Antialiasing, antialiasButton->isChecked()); +} + +void View::print() +{ +#ifndef QT_NO_PRINTER + QPrinter printer; + QPrintDialog dialog(&printer, this); + if (dialog.exec() == QDialog::Accepted) { + QPainter painter(&printer); + graphicsView->render(&painter); + } +#endif +} + +void View::zoomIn(int level) +{ + zoomSlider->setValue(zoomSlider->value() + level); +} + +void View::zoomOut(int level) +{ + zoomSlider->setValue(zoomSlider->value() - level); +} + +void View::rotateLeft() +{ + rotateSlider->setValue(rotateSlider->value() - 10); +} + +void View::rotateRight() +{ + rotateSlider->setValue(rotateSlider->value() + 10); +} + diff --git a/examples/graphicsview/chip/view.h b/examples/graphicsview/chip/view.h new file mode 100644 index 0000000000..7c587d4147 --- /dev/null +++ b/examples/graphicsview/chip/view.h @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef VIEW_H +#define VIEW_H + +#include +#include + +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QSlider) +QT_FORWARD_DECLARE_CLASS(QToolButton) + +class View; + +class GraphicsView : public QGraphicsView +{ + Q_OBJECT +public: + GraphicsView(View *v) : QGraphicsView(), view(v) { } + +protected: + void wheelEvent(QWheelEvent *); + +private: + View *view; +}; + +class View : public QFrame +{ + Q_OBJECT +public: + View(const QString &name, QWidget *parent = 0); + + QGraphicsView *view() const; + +public slots: + void zoomIn(int level = 1); + void zoomOut(int level = 1); + +private slots: + void resetView(); + void setResetButtonEnabled(); + void setupMatrix(); + void togglePointerMode(); + void toggleOpenGL(); + void toggleAntialiasing(); + void print(); + void rotateLeft(); + void rotateRight(); + +private: + GraphicsView *graphicsView; + QLabel *label; + QLabel *label2; + QToolButton *selectModeButton; + QToolButton *dragModeButton; + QToolButton *openGlButton; + QToolButton *antialiasButton; + QToolButton *printButton; + QToolButton *resetButton; + QSlider *zoomSlider; + QSlider *rotateSlider; +}; + +#endif diff --git a/examples/graphicsview/chip/zoomin.png b/examples/graphicsview/chip/zoomin.png new file mode 100644 index 0000000000..8b0daeea48 Binary files /dev/null and b/examples/graphicsview/chip/zoomin.png differ diff --git a/examples/graphicsview/chip/zoomout.png b/examples/graphicsview/chip/zoomout.png new file mode 100644 index 0000000000..1575dd24f6 Binary files /dev/null and b/examples/graphicsview/chip/zoomout.png differ diff --git a/examples/graphicsview/embeddeddialogs/No-Ones-Laughing-3.jpg b/examples/graphicsview/embeddeddialogs/No-Ones-Laughing-3.jpg new file mode 100644 index 0000000000..445567fbda Binary files /dev/null and b/examples/graphicsview/embeddeddialogs/No-Ones-Laughing-3.jpg differ diff --git a/examples/graphicsview/embeddeddialogs/customproxy.cpp b/examples/graphicsview/embeddeddialogs/customproxy.cpp new file mode 100644 index 0000000000..cbc622a34f --- /dev/null +++ b/examples/graphicsview/embeddeddialogs/customproxy.cpp @@ -0,0 +1,167 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "customproxy.h" + +#include + +CustomProxy::CustomProxy(QGraphicsItem *parent, Qt::WindowFlags wFlags) + : QGraphicsProxyWidget(parent, wFlags), popupShown(false), currentPopup(0) +{ + timeLine = new QTimeLine(250, this); + connect(timeLine, SIGNAL(valueChanged(qreal)), + this, SLOT(updateStep(qreal))); + connect(timeLine, SIGNAL(stateChanged(QTimeLine::State)), + this, SLOT(stateChanged(QTimeLine::State))); +} + +QRectF CustomProxy::boundingRect() const +{ + return QGraphicsProxyWidget::boundingRect().adjusted(0, 0, 10, 10); +} + +void CustomProxy::paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget) +{ + const QColor color(0, 0, 0, 64); + + QRectF r = windowFrameRect(); + QRectF right(r.right(), r.top() + 10, 10, r.height() - 10); + QRectF bottom(r.left() + 10, r.bottom(), r.width(), 10); + bool intersectsRight = right.intersects(option->exposedRect); + bool intersectsBottom = bottom.intersects(option->exposedRect); + if (intersectsRight && intersectsBottom) { + QPainterPath path; + path.addRect(right); + path.addRect(bottom); + painter->setPen(Qt::NoPen); + painter->setBrush(color); + painter->drawPath(path); + } else if (intersectsBottom) { + painter->fillRect(bottom, color); + } else if (intersectsRight) { + painter->fillRect(right, color); + } + + QGraphicsProxyWidget::paintWindowFrame(painter, option, widget); +} + +void CustomProxy::hoverEnterEvent(QGraphicsSceneHoverEvent *event) +{ + QGraphicsProxyWidget::hoverEnterEvent(event); + scene()->setActiveWindow(this); + if (timeLine->currentValue() != 1) + zoomIn(); +} + +void CustomProxy::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) +{ + QGraphicsProxyWidget::hoverLeaveEvent(event); + if (!popupShown && (timeLine->direction() != QTimeLine::Backward || timeLine->currentValue() != 0)) + zoomOut(); +} + +bool CustomProxy::sceneEventFilter(QGraphicsItem *watched, QEvent *event) +{ + if (watched->isWindow() && (event->type() == QEvent::UngrabMouse || event->type() == QEvent::GrabMouse)) { + popupShown = watched->isVisible(); + if (!popupShown && !isUnderMouse()) + zoomOut(); + } + return QGraphicsProxyWidget::sceneEventFilter(watched, event); +} + +QVariant CustomProxy::itemChange(GraphicsItemChange change, const QVariant &value) +{ + if (change == ItemChildAddedChange || change == ItemChildRemovedChange) { + if (change == ItemChildAddedChange) { + currentPopup = qvariant_cast(value); + currentPopup->setCacheMode(ItemCoordinateCache); + if (scene()) + currentPopup->installSceneEventFilter(this); + } else if (scene()) { + currentPopup->removeSceneEventFilter(this); + currentPopup = 0; + } + } else if (currentPopup && change == ItemSceneHasChanged) { + currentPopup->installSceneEventFilter(this); + } + return QGraphicsProxyWidget::itemChange(change, value); +} + +void CustomProxy::updateStep(qreal step) +{ + QRectF r = boundingRect(); + setTransform(QTransform() + .translate(r.width() / 2, r.height() / 2) + .rotate(step * 30, Qt::XAxis) + .rotate(step * 10, Qt::YAxis) + .rotate(step * 5, Qt::ZAxis) + .scale(1 + 1.5 * step, 1 + 1.5 * step) + .translate(-r.width() / 2, -r.height() / 2)); +} + +void CustomProxy::stateChanged(QTimeLine::State state) +{ + if (state == QTimeLine::Running) { + if (timeLine->direction() == QTimeLine::Forward) + setCacheMode(ItemCoordinateCache); + } else if (state == QTimeLine::NotRunning) { + if (timeLine->direction() == QTimeLine::Backward) + setCacheMode(DeviceCoordinateCache); + } +} + +void CustomProxy::zoomIn() +{ + if (timeLine->direction() != QTimeLine::Forward) + timeLine->setDirection(QTimeLine::Forward); + if (timeLine->state() == QTimeLine::NotRunning) + timeLine->start(); +} + +void CustomProxy::zoomOut() +{ + if (timeLine->direction() != QTimeLine::Backward) + timeLine->setDirection(QTimeLine::Backward); + if (timeLine->state() == QTimeLine::NotRunning) + timeLine->start(); +} diff --git a/examples/graphicsview/embeddeddialogs/customproxy.h b/examples/graphicsview/embeddeddialogs/customproxy.h new file mode 100644 index 0000000000..1ceaa06bb3 --- /dev/null +++ b/examples/graphicsview/embeddeddialogs/customproxy.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CUSTOMPROXY_H +#define CUSTOMPROXY_H + +#include +#include + +class CustomProxy : public QGraphicsProxyWidget +{ + Q_OBJECT +public: + CustomProxy(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); + + QRectF boundingRect() const; + void paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget); + +protected: + void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); + bool sceneEventFilter(QGraphicsItem *watched, QEvent *event); + QVariant itemChange(GraphicsItemChange change, const QVariant &value); + +private slots: + void updateStep(qreal step); + void stateChanged(QTimeLine::State); + void zoomIn(); + void zoomOut(); + +private: + QTimeLine *timeLine; + bool popupShown; + QGraphicsItem *currentPopup; +}; + +#endif diff --git a/examples/graphicsview/embeddeddialogs/embeddeddialog.cpp b/examples/graphicsview/embeddeddialogs/embeddeddialog.cpp new file mode 100644 index 0000000000..f932307925 --- /dev/null +++ b/examples/graphicsview/embeddeddialogs/embeddeddialog.cpp @@ -0,0 +1,106 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "embeddeddialog.h" +#include "ui_embeddeddialog.h" + +#include + +EmbeddedDialog::EmbeddedDialog(QWidget *parent) + : QDialog(parent) +{ + ui = new Ui_embeddedDialog; + ui->setupUi(this); + ui->layoutDirection->setCurrentIndex(layoutDirection() != Qt::LeftToRight); + + foreach (QString styleName, QStyleFactory::keys()) { + ui->style->addItem(styleName); + if (style()->objectName().toLower() == styleName.toLower()) + ui->style->setCurrentIndex(ui->style->count() - 1); + } + + connect(ui->layoutDirection, SIGNAL(activated(int)), + this, SLOT(layoutDirectionChanged(int))); + connect(ui->spacing, SIGNAL(valueChanged(int)), + this, SLOT(spacingChanged(int))); + connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), + this, SLOT(fontChanged(QFont))); + connect(ui->style, SIGNAL(activated(QString)), + this, SLOT(styleChanged(QString))); +} + +EmbeddedDialog::~EmbeddedDialog() +{ + delete ui; +} + +void EmbeddedDialog::layoutDirectionChanged(int index) +{ + setLayoutDirection(index == 0 ? Qt::LeftToRight : Qt::RightToLeft); +} + +void EmbeddedDialog::spacingChanged(int spacing) +{ + layout()->setSpacing(spacing); + adjustSize(); +} + +void EmbeddedDialog::fontChanged(const QFont &font) +{ + setFont(font); +} + +static void setStyleHelper(QWidget *widget, QStyle *style) +{ + widget->setStyle(style); + widget->setPalette(style->standardPalette()); + foreach (QObject *child, widget->children()) { + if (QWidget *childWidget = qobject_cast(child)) + setStyleHelper(childWidget, style); + } +} + +void EmbeddedDialog::styleChanged(const QString &styleName) +{ + QStyle *style = QStyleFactory::create(styleName); + if (style) + setStyleHelper(this, style); +} diff --git a/examples/graphicsview/embeddeddialogs/embeddeddialog.h b/examples/graphicsview/embeddeddialogs/embeddeddialog.h new file mode 100644 index 0000000000..b7f8da085e --- /dev/null +++ b/examples/graphicsview/embeddeddialogs/embeddeddialog.h @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef EMBEDDEDDIALOG_H +#define EMBEDDEDDIALOG_H + +#include + +QT_FORWARD_DECLARE_CLASS(Ui_embeddedDialog); + +class EmbeddedDialog : public QDialog +{ + Q_OBJECT +public: + EmbeddedDialog(QWidget *parent = 0); + ~EmbeddedDialog(); + +private slots: + void layoutDirectionChanged(int index); + void spacingChanged(int spacing); + void fontChanged(const QFont &font); + void styleChanged(const QString &styleName); + +private: + Ui_embeddedDialog *ui; +}; + +#endif diff --git a/examples/graphicsview/embeddeddialogs/embeddeddialog.ui b/examples/graphicsview/embeddeddialogs/embeddeddialog.ui new file mode 100644 index 0000000000..f967b10085 --- /dev/null +++ b/examples/graphicsview/embeddeddialogs/embeddeddialog.ui @@ -0,0 +1,87 @@ + + embeddedDialog + + + + 0 + 0 + 407 + 134 + + + + Embedded Dialog + + + + + + Layout Direction: + + + layoutDirection + + + + + + + + Left to Right + + + + + Right to Left + + + + + + + + Select Font: + + + fontComboBox + + + + + + + + + + Style: + + + style + + + + + + + + + + Layout spacing: + + + spacing + + + + + + + Qt::Horizontal + + + + + + + + diff --git a/examples/graphicsview/embeddeddialogs/embeddeddialogs.pro b/examples/graphicsview/embeddeddialogs/embeddeddialogs.pro new file mode 100644 index 0000000000..675a9889a2 --- /dev/null +++ b/examples/graphicsview/embeddeddialogs/embeddeddialogs.pro @@ -0,0 +1,19 @@ +SOURCES += main.cpp +SOURCES += customproxy.cpp embeddeddialog.cpp +HEADERS += customproxy.h embeddeddialog.h + +FORMS += embeddeddialog.ui +RESOURCES += embeddeddialogs.qrc + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/embeddeddialogs +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.png *.jpg *.plist *.icns *.ico *.rc *.pro *.html *.doc images +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/embeddeddialogs +INSTALLS += target sources + +symbian: CONFIG += qt_demo diff --git a/examples/graphicsview/embeddeddialogs/embeddeddialogs.qrc b/examples/graphicsview/embeddeddialogs/embeddeddialogs.qrc new file mode 100644 index 0000000000..33be5038da --- /dev/null +++ b/examples/graphicsview/embeddeddialogs/embeddeddialogs.qrc @@ -0,0 +1,5 @@ + + + No-Ones-Laughing-3.jpg + + diff --git a/examples/graphicsview/embeddeddialogs/main.cpp b/examples/graphicsview/embeddeddialogs/main.cpp new file mode 100644 index 0000000000..bca81b8c79 --- /dev/null +++ b/examples/graphicsview/embeddeddialogs/main.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "customproxy.h" +#include "embeddeddialog.h" + +#include + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(embeddeddialogs); + QApplication app(argc, argv); + + QGraphicsScene scene; + scene.setStickyFocus(true); +#ifndef Q_OS_WINCE + const int gridSize = 10; +#else + const int gridSize = 5; +#endif + + for (int y = 0; y < gridSize; ++y) { + for (int x = 0; x < gridSize; ++x) { + CustomProxy *proxy = new CustomProxy(0, Qt::Window); + proxy->setWidget(new EmbeddedDialog); + + QRectF rect = proxy->boundingRect(); + + proxy->setPos(x * rect.width() * 1.05, y * rect.height() * 1.05); + proxy->setCacheMode(QGraphicsItem::DeviceCoordinateCache); + + scene.addItem(proxy); + } + } + scene.setSceneRect(scene.itemsBoundingRect()); + + QGraphicsView view(&scene); + view.scale(0.5, 0.5); + view.setRenderHints(view.renderHints() | QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + view.setBackgroundBrush(QPixmap(":/No-Ones-Laughing-3.jpg")); + view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); + view.show(); + view.setWindowTitle("Embedded Dialogs Demo"); + return app.exec(); +} diff --git a/examples/itemviews/interview/README b/examples/itemviews/interview/README new file mode 100644 index 0000000000..50894428f6 --- /dev/null +++ b/examples/itemviews/interview/README @@ -0,0 +1,2 @@ +The interview example shows the same model and selection being shared +between three different views. diff --git a/examples/itemviews/interview/images/folder.png b/examples/itemviews/interview/images/folder.png new file mode 100644 index 0000000000..589fd2df59 Binary files /dev/null and b/examples/itemviews/interview/images/folder.png differ diff --git a/examples/itemviews/interview/images/interview.png b/examples/itemviews/interview/images/interview.png new file mode 100644 index 0000000000..0c3d690258 Binary files /dev/null and b/examples/itemviews/interview/images/interview.png differ diff --git a/examples/itemviews/interview/images/services.png b/examples/itemviews/interview/images/services.png new file mode 100644 index 0000000000..6b2ad969d4 Binary files /dev/null and b/examples/itemviews/interview/images/services.png differ diff --git a/examples/itemviews/interview/interview.pro b/examples/itemviews/interview/interview.pro new file mode 100644 index 0000000000..a497fbc407 --- /dev/null +++ b/examples/itemviews/interview/interview.pro @@ -0,0 +1,19 @@ +TEMPLATE = app + +CONFIG += qt warn_on +HEADERS += model.h +SOURCES += model.cpp main.cpp +RESOURCES += interview.qrc + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/interview +sources.files = $$SOURCES $$HEADERS $$RESOURCES README *.pro images +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/interview +INSTALLS += target sources + +symbian: CONFIG += qt_demo diff --git a/examples/itemviews/interview/interview.qrc b/examples/itemviews/interview/interview.qrc new file mode 100644 index 0000000000..b28ea34d8a --- /dev/null +++ b/examples/itemviews/interview/interview.qrc @@ -0,0 +1,7 @@ + + + images/folder.png + images/services.png + images/interview.png + + diff --git a/examples/itemviews/interview/main.cpp b/examples/itemviews/interview/main.cpp new file mode 100644 index 0000000000..b9656c6185 --- /dev/null +++ b/examples/itemviews/interview/main.cpp @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "model.h" + +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(interview); + + QApplication app(argc, argv); + QSplitter page; + + QAbstractItemModel *data = new Model(1000, 10, &page); + QItemSelectionModel *selections = new QItemSelectionModel(data); + + QTableView *table = new QTableView; + table->setModel(data); + table->setSelectionModel(selections); + table->horizontalHeader()->setMovable(true); + table->verticalHeader()->setMovable(true); + // Set StaticContents to enable minimal repaints on resizes. + table->viewport()->setAttribute(Qt::WA_StaticContents); + page.addWidget(table); + + QTreeView *tree = new QTreeView; + tree->setModel(data); + tree->setSelectionModel(selections); + tree->setUniformRowHeights(true); + tree->header()->setStretchLastSection(false); + tree->viewport()->setAttribute(Qt::WA_StaticContents); + // Disable the focus rect to get minimal repaints when scrolling on Mac. + tree->setAttribute(Qt::WA_MacShowFocusRect, false); + page.addWidget(tree); + + QListView *list = new QListView; + list->setModel(data); + list->setSelectionModel(selections); + list->setViewMode(QListView::IconMode); + list->setSelectionMode(QAbstractItemView::ExtendedSelection); + list->setAlternatingRowColors(false); + list->viewport()->setAttribute(Qt::WA_StaticContents); + list->setAttribute(Qt::WA_MacShowFocusRect, false); + page.addWidget(list); + + page.setWindowIcon(QPixmap(":/images/interview.png")); + page.setWindowTitle("Interview"); + page.show(); + + return app.exec(); +} diff --git a/examples/itemviews/interview/model.cpp b/examples/itemviews/interview/model.cpp new file mode 100644 index 0000000000..6031615711 --- /dev/null +++ b/examples/itemviews/interview/model.cpp @@ -0,0 +1,147 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "model.h" +#include +#include + +Model::Model(int rows, int columns, QObject *parent) + : QAbstractItemModel(parent), + services(QPixmap(":/images/services.png")), + rc(rows), cc(columns), + tree(new QVector(rows, Node(0))) +{ + +} + +Model::~Model() +{ + delete tree; +} + +QModelIndex Model::index(int row, int column, const QModelIndex &parent) const +{ + if (row < rc && row >= 0 && column < cc && column >= 0) { + Node *p = static_cast(parent.internalPointer()); + Node *n = node(row, p); + if (n) + return createIndex(row, column, n); + } + return QModelIndex(); +} + +QModelIndex Model::parent(const QModelIndex &child) const +{ + if (child.isValid()) { + Node *n = static_cast(child.internalPointer()); + Node *p = parent(n); + if (p) + return createIndex(row(p), 0, p); + } + return QModelIndex(); +} + +int Model::rowCount(const QModelIndex &parent) const +{ + return (parent.isValid() && parent.column() != 0) ? 0 : rc; +} + +int Model::columnCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return cc; +} + +QVariant Model::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + if (role == Qt::DisplayRole) + return "Item " + QString::number(index.row()) + ":" + QString::number(index.column()); + if (role == Qt::DecorationRole) { + if (index.column() == 0) + return iconProvider.icon(QFileIconProvider::Folder); + return iconProvider.icon(QFileIconProvider::File); + } + return QVariant(); +} + +QVariant Model::headerData(int section, Qt::Orientation orientation, int role) const +{ + if (role == Qt::DisplayRole) + return QString::number(section); + if (role == Qt::DecorationRole) + return QVariant::fromValue(services); + return QAbstractItemModel::headerData(section, orientation, role); +} + +bool Model::hasChildren(const QModelIndex &parent) const +{ + if (parent.isValid() && parent.column() != 0) + return false; + return rc > 0 && cc > 0; +} + +Qt::ItemFlags Model::flags(const QModelIndex &index) const +{ + if (!index.isValid()) + return 0; + return (Qt::ItemIsDragEnabled|Qt::ItemIsSelectable|Qt::ItemIsEnabled); +} + +Model::Node *Model::node(int row, Node *parent) const +{ + if (parent && !parent->children) + parent->children = new QVector(rc, Node(parent)); + QVector *v = parent ? parent->children : tree; + return const_cast(&(v->at(row))); +} + +Model::Node *Model::parent(Node *child) const +{ + return child ? child->parent : 0; +} + +int Model::row(Node *node) const +{ + const Node *first = node->parent ? &(node->parent->children->at(0)) : &(tree->at(0)); + return (node - first); +} diff --git a/examples/itemviews/interview/model.h b/examples/itemviews/interview/model.h new file mode 100644 index 0000000000..f0ae556ce3 --- /dev/null +++ b/examples/itemviews/interview/model.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MODEL_H +#define MODEL_H + +#include +#include +#include +#include + +class Model : public QAbstractItemModel +{ + Q_OBJECT + +public: + Model(int rows, int columns, QObject *parent = 0); + ~Model(); + + QModelIndex index(int row, int column, const QModelIndex &parent) const; + QModelIndex parent(const QModelIndex &child) const; + + int rowCount(const QModelIndex &parent) const; + int columnCount(const QModelIndex &parent) const; + + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role) const; + + bool hasChildren(const QModelIndex &parent) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + +private: + + struct Node + { + Node(Node *parent = 0) : parent(parent), children(0) {} + ~Node() { delete children; } + Node *parent; + QVector *children; + }; + + Node *node(int row, Node *parent) const; + Node *parent(Node *child) const; + int row(Node *node) const; + + QIcon services; + int rc, cc; + QVector *tree; + QFileIconProvider iconProvider; +}; + +#endif diff --git a/examples/itemviews/spreadsheet/images/interview.png b/examples/itemviews/spreadsheet/images/interview.png new file mode 100644 index 0000000000..0c3d690258 Binary files /dev/null and b/examples/itemviews/spreadsheet/images/interview.png differ diff --git a/examples/itemviews/spreadsheet/main.cpp b/examples/itemviews/spreadsheet/main.cpp new file mode 100644 index 0000000000..4c20646f9c --- /dev/null +++ b/examples/itemviews/spreadsheet/main.cpp @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "spreadsheet.h" + +int main(int argc, char** argv) { + Q_INIT_RESOURCE(spreadsheet); + QApplication app(argc, argv); + SpreadSheet sheet(10, 6); + sheet.setWindowIcon(QPixmap(":/images/interview.png")); + sheet.resize(640, 420); + sheet.show(); + return app.exec(); +} + + diff --git a/examples/itemviews/spreadsheet/printview.cpp b/examples/itemviews/spreadsheet/printview.cpp new file mode 100644 index 0000000000..0962e28844 --- /dev/null +++ b/examples/itemviews/spreadsheet/printview.cpp @@ -0,0 +1,59 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "printview.h" +#include +#include + +PrintView::PrintView() +{ + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); +} + +void PrintView::print(QPrinter *printer) +{ +#ifndef QT_NO_PRINTER + resize(printer->width(), printer->height()); + render(printer); +#endif +} + diff --git a/examples/itemviews/spreadsheet/printview.h b/examples/itemviews/spreadsheet/printview.h new file mode 100644 index 0000000000..7c74844483 --- /dev/null +++ b/examples/itemviews/spreadsheet/printview.h @@ -0,0 +1,60 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PRINTVIEW_H +#define PRINTVIEW_H + +#include + +class PrintView : public QTableView +{ + Q_OBJECT + +public: + PrintView(); + +public Q_SLOTS: + void print(QPrinter *printer); +}; + +#endif // PRINTVIEW_H + + diff --git a/examples/itemviews/spreadsheet/spreadsheet.cpp b/examples/itemviews/spreadsheet/spreadsheet.cpp new file mode 100644 index 0000000000..6b99521b7b --- /dev/null +++ b/examples/itemviews/spreadsheet/spreadsheet.cpp @@ -0,0 +1,633 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "spreadsheet.h" +#include "spreadsheetdelegate.h" +#include "spreadsheetitem.h" +#include "printview.h" + +SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent) + : QMainWindow(parent) +{ + addToolBar(toolBar = new QToolBar()); + formulaInput = new QLineEdit(); + + cellLabel = new QLabel(toolBar); + cellLabel->setMinimumSize(80, 0); + + toolBar->addWidget(cellLabel); + toolBar->addWidget(formulaInput); + + table = new QTableWidget(rows, cols, this); + for (int c = 0; c < cols; ++c) { + QString character(QChar('A' + c)); + table->setHorizontalHeaderItem(c, new QTableWidgetItem(character)); + } + + table->setItemPrototype(table->item(rows -1, cols - 1)); + table->setItemDelegate(new SpreadSheetDelegate()); + + createActions(); + updateColor(0); + setupMenuBar(); + setupContents(); + setupContextMenu(); + setCentralWidget(table); + + statusBar(); + connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), + this, SLOT(updateStatus(QTableWidgetItem*))); + connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), + this, SLOT(updateColor(QTableWidgetItem*))); + connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), + this, SLOT(updateLineEdit(QTableWidgetItem*))); + connect(table, SIGNAL(itemChanged(QTableWidgetItem*)), + this, SLOT(updateStatus(QTableWidgetItem*))); + connect(formulaInput, SIGNAL(returnPressed()), this, SLOT(returnPressed())); + connect(table, SIGNAL(itemChanged(QTableWidgetItem*)), + this, SLOT(updateLineEdit(QTableWidgetItem*))); + + setWindowTitle(tr("Spreadsheet")); +} + +void SpreadSheet::createActions() +{ + cell_sumAction = new QAction(tr("Sum"), this); + connect(cell_sumAction, SIGNAL(triggered()), this, SLOT(actionSum())); + + cell_addAction = new QAction(tr("&Add"), this); + cell_addAction->setShortcut(Qt::CTRL | Qt::Key_Plus); + connect(cell_addAction, SIGNAL(triggered()), this, SLOT(actionAdd())); + + cell_subAction = new QAction(tr("&Subtract"), this); + cell_subAction->setShortcut(Qt::CTRL | Qt::Key_Minus); + connect(cell_subAction, SIGNAL(triggered()), this, SLOT(actionSubtract())); + + cell_mulAction = new QAction(tr("&Multiply"), this); + cell_mulAction->setShortcut(Qt::CTRL | Qt::Key_multiply); + connect(cell_mulAction, SIGNAL(triggered()), this, SLOT(actionMultiply())); + + cell_divAction = new QAction(tr("&Divide"), this); + cell_divAction->setShortcut(Qt::CTRL | Qt::Key_division); + connect(cell_divAction, SIGNAL(triggered()), this, SLOT(actionDivide())); + + fontAction = new QAction(tr("Font..."), this); + fontAction->setShortcut(Qt::CTRL | Qt::Key_F); + connect(fontAction, SIGNAL(triggered()), this, SLOT(selectFont())); + + colorAction = new QAction(QPixmap(16, 16), tr("Background &Color..."), this); + connect(colorAction, SIGNAL(triggered()), this, SLOT(selectColor())); + + clearAction = new QAction(tr("Clear"), this); + clearAction->setShortcut(Qt::Key_Delete); + connect(clearAction, SIGNAL(triggered()), this, SLOT(clear())); + + aboutSpreadSheet = new QAction(tr("About Spreadsheet"), this); + connect(aboutSpreadSheet, SIGNAL(triggered()), this, SLOT(showAbout())); + + exitAction = new QAction(tr("E&xit"), this); + connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + + printAction = new QAction(tr("&Print"), this); + connect(printAction, SIGNAL(triggered()), this, SLOT(print())); + + firstSeparator = new QAction(this); + firstSeparator->setSeparator(true); + + secondSeparator = new QAction(this); + secondSeparator->setSeparator(true); +} + +void SpreadSheet::setupMenuBar() +{ + QMenu *fileMenu = menuBar()->addMenu(tr("&File")); + fileMenu->addAction(printAction); + fileMenu->addAction(exitAction); + + QMenu *cellMenu = menuBar()->addMenu(tr("&Cell")); + cellMenu->addAction(cell_addAction); + cellMenu->addAction(cell_subAction); + cellMenu->addAction(cell_mulAction); + cellMenu->addAction(cell_divAction); + cellMenu->addAction(cell_sumAction); + cellMenu->addSeparator(); + cellMenu->addAction(colorAction); + cellMenu->addAction(fontAction); + + menuBar()->addSeparator(); + + QMenu *aboutMenu = menuBar()->addMenu(tr("&Help")); + aboutMenu->addAction(aboutSpreadSheet); +} + +void SpreadSheet::updateStatus(QTableWidgetItem *item) +{ + if (item && item == table->currentItem()) { + statusBar()->showMessage(item->data(Qt::StatusTipRole).toString(), + 1000); + cellLabel->setText(tr("Cell: (%1)").arg(encode_pos(table->row(item), + table->column(item)))); + } +} + +void SpreadSheet::updateColor(QTableWidgetItem *item) +{ + QPixmap pix(16, 16); + QColor col; + if (item) + col = item->backgroundColor(); + if (!col.isValid()) + col = palette().base().color(); + + QPainter pt(&pix); + pt.fillRect(0, 0, 16, 16, col); + + QColor lighter = col.light(); + pt.setPen(lighter); + QPoint lightFrame[] = { QPoint(0, 15), QPoint(0, 0), QPoint(15, 0) }; + pt.drawPolyline(lightFrame, 3); + + pt.setPen(col.dark()); + QPoint darkFrame[] = { QPoint(1, 15), QPoint(15, 15), QPoint(15, 1) }; + pt.drawPolyline(darkFrame, 3); + + pt.end(); + + colorAction->setIcon(pix); +} + +void SpreadSheet::updateLineEdit(QTableWidgetItem *item) +{ + if (item != table->currentItem()) + return; + if (item) + formulaInput->setText(item->data(Qt::EditRole).toString()); + else + formulaInput->clear(); +} + +void SpreadSheet::returnPressed() +{ + QString text = formulaInput->text(); + int row = table->currentRow(); + int col = table->currentColumn(); + QTableWidgetItem *item = table->item(row, col); + if (!item) + table->setItem(row, col, new SpreadSheetItem(text)); + else + item->setData(Qt::EditRole, text); + table->viewport()->update(); +} + +void SpreadSheet::selectColor() +{ + QTableWidgetItem *item = table->currentItem(); + QColor col = item ? item->backgroundColor() : table->palette().base().color(); + col = QColorDialog::getColor(col, this); + if (!col.isValid()) + return; + + QList selected = table->selectedItems(); + if (selected.count() == 0) + return; + + foreach(QTableWidgetItem *i, selected) + if (i) + i->setBackgroundColor(col); + + updateColor(table->currentItem()); +} + +void SpreadSheet::selectFont() +{ + QList selected = table->selectedItems(); + if (selected.count() == 0) + return; + + bool ok = false; + QFont fnt = QFontDialog::getFont(&ok, font(), this); + + if (!ok) + return; + foreach(QTableWidgetItem *i, selected) + if (i) + i->setFont(fnt); +} + +bool SpreadSheet::runInputDialog(const QString &title, + const QString &c1Text, + const QString &c2Text, + const QString &opText, + const QString &outText, + QString *cell1, QString *cell2, QString *outCell) +{ + QStringList rows, cols; + for (int c = 0; c < table->columnCount(); ++c) + cols << QChar('A' + c); + for (int r = 0; r < table->rowCount(); ++r) + rows << QString::number(1 + r); + + QDialog addDialog(this); + addDialog.setWindowTitle(title); + + QGroupBox group(title, &addDialog); + group.setMinimumSize(250, 100); + + QLabel cell1Label(c1Text, &group); + QComboBox cell1RowInput(&group); + int c1Row, c1Col; + decode_pos(*cell1, &c1Row, &c1Col); + cell1RowInput.addItems(rows); + cell1RowInput.setCurrentIndex(c1Row); + + QComboBox cell1ColInput(&group); + cell1ColInput.addItems(cols); + cell1ColInput.setCurrentIndex(c1Col); + + QLabel operatorLabel(opText, &group); + operatorLabel.setAlignment(Qt::AlignHCenter); + + QLabel cell2Label(c2Text, &group); + QComboBox cell2RowInput(&group); + int c2Row, c2Col; + decode_pos(*cell2, &c2Row, &c2Col); + cell2RowInput.addItems(rows); + cell2RowInput.setCurrentIndex(c2Row); + QComboBox cell2ColInput(&group); + cell2ColInput.addItems(cols); + cell2ColInput.setCurrentIndex(c2Col); + + QLabel equalsLabel("=", &group); + equalsLabel.setAlignment(Qt::AlignHCenter); + + QLabel outLabel(outText, &group); + QComboBox outRowInput(&group); + int outRow, outCol; + decode_pos(*outCell, &outRow, &outCol); + outRowInput.addItems(rows); + outRowInput.setCurrentIndex(outRow); + QComboBox outColInput(&group); + outColInput.addItems(cols); + outColInput.setCurrentIndex(outCol); + + QPushButton cancelButton(tr("Cancel"), &addDialog); + connect(&cancelButton, SIGNAL(clicked()), &addDialog, SLOT(reject())); + + QPushButton okButton(tr("OK"), &addDialog); + okButton.setDefault(true); + connect(&okButton, SIGNAL(clicked()), &addDialog, SLOT(accept())); + + QHBoxLayout *buttonsLayout = new QHBoxLayout; + buttonsLayout->addStretch(1); + buttonsLayout->addWidget(&okButton); + buttonsLayout->addSpacing(10); + buttonsLayout->addWidget(&cancelButton); + + QVBoxLayout *dialogLayout = new QVBoxLayout(&addDialog); + dialogLayout->addWidget(&group); + dialogLayout->addStretch(1); + dialogLayout->addItem(buttonsLayout); + + QHBoxLayout *cell1Layout = new QHBoxLayout; + cell1Layout->addWidget(&cell1Label); + cell1Layout->addSpacing(10); + cell1Layout->addWidget(&cell1ColInput); + cell1Layout->addSpacing(10); + cell1Layout->addWidget(&cell1RowInput); + + QHBoxLayout *cell2Layout = new QHBoxLayout; + cell2Layout->addWidget(&cell2Label); + cell2Layout->addSpacing(10); + cell2Layout->addWidget(&cell2ColInput); + cell2Layout->addSpacing(10); + cell2Layout->addWidget(&cell2RowInput); + + QHBoxLayout *outLayout = new QHBoxLayout; + outLayout->addWidget(&outLabel); + outLayout->addSpacing(10); + outLayout->addWidget(&outColInput); + outLayout->addSpacing(10); + outLayout->addWidget(&outRowInput); + + QVBoxLayout *vLayout = new QVBoxLayout(&group); + vLayout->addItem(cell1Layout); + vLayout->addWidget(&operatorLabel); + vLayout->addItem(cell2Layout); + vLayout->addWidget(&equalsLabel); + vLayout->addStretch(1); + vLayout->addItem(outLayout); + + if (addDialog.exec()) { + *cell1 = cell1ColInput.currentText() + cell1RowInput.currentText(); + *cell2 = cell2ColInput.currentText() + cell2RowInput.currentText(); + *outCell = outColInput.currentText() + outRowInput.currentText(); + return true; + } + + return false; +} + +void SpreadSheet::actionSum() +{ + int row_first = 0; + int row_last = 0; + int row_cur = 0; + + int col_first = 0; + int col_last = 0; + int col_cur = 0; + + QList selected = table->selectedItems(); + + if (!selected.isEmpty()) { + QTableWidgetItem *first = selected.first(); + QTableWidgetItem *last = selected.last(); + row_first = table->row(first); + row_last = table->row(last); + col_first = table->column(first); + col_last = table->column(last); + } + + QTableWidgetItem *current = table->currentItem(); + + if (current) { + row_cur = table->row(current); + col_cur = table->column(current); + } + + QString cell1 = encode_pos(row_first, col_first); + QString cell2 = encode_pos(row_last, col_last); + QString out = encode_pos(row_cur, col_cur); + + if (runInputDialog(tr("Sum cells"), tr("First cell:"), tr("Last cell:"), + QString("%1").arg(QChar(0x03a3)), tr("Output to:"), + &cell1, &cell2, &out)) { + int row, col; + decode_pos(out, &row, &col); + table->item(row, col)->setText(tr("sum %1 %2").arg(cell1, cell2)); + } +} + +void SpreadSheet::actionMath_helper(const QString &title, const QString &op) +{ + QString cell1 = "C1"; + QString cell2 = "C2"; + QString out = "C3"; + + QTableWidgetItem *current = table->currentItem(); + if (current) + out = encode_pos(table->currentRow(), table->currentColumn()); + + if (runInputDialog(title, tr("Cell 1"), tr("Cell 2"), op, tr("Output to:"), + &cell1, &cell2, &out)) { + int row, col; + decode_pos(out, &row, &col); + table->item(row, col)->setText(tr("%1 %2 %3").arg(op, cell1, cell2)); + } +} + +void SpreadSheet::actionAdd() +{ + actionMath_helper(tr("Addition"), "+"); +} + +void SpreadSheet::actionSubtract() +{ + actionMath_helper(tr("Subtraction"), "-"); +} + +void SpreadSheet::actionMultiply() +{ + actionMath_helper(tr("Multiplication"), "*"); +} +void SpreadSheet::actionDivide() +{ + actionMath_helper(tr("Division"), "/"); +} + +void SpreadSheet::clear() +{ + foreach (QTableWidgetItem *i, table->selectedItems()) + i->setText(""); +} + +void SpreadSheet::setupContextMenu() +{ + addAction(cell_addAction); + addAction(cell_subAction); + addAction(cell_mulAction); + addAction(cell_divAction); + addAction(cell_sumAction); + addAction(firstSeparator); + addAction(colorAction); + addAction(fontAction); + addAction(secondSeparator); + addAction(clearAction); + setContextMenuPolicy(Qt::ActionsContextMenu); +} + +void SpreadSheet::setupContents() +{ + QColor titleBackground(Qt::lightGray); + QFont titleFont = table->font(); + titleFont.setBold(true); + + // column 0 + table->setItem(0, 0, new SpreadSheetItem("Item")); + table->item(0, 0)->setBackgroundColor(titleBackground); + table->item(0, 0)->setToolTip("This column shows the purchased item/service"); + table->item(0, 0)->setFont(titleFont); + + table->setItem(1, 0, new SpreadSheetItem("AirportBus")); + table->setItem(2, 0, new SpreadSheetItem("Flight (Munich)")); + table->setItem(3, 0, new SpreadSheetItem("Lunch")); + table->setItem(4, 0, new SpreadSheetItem("Flight (LA)")); + table->setItem(5, 0, new SpreadSheetItem("Taxi")); + table->setItem(6, 0, new SpreadSheetItem("Dinner")); + table->setItem(7, 0, new SpreadSheetItem("Hotel")); + table->setItem(8, 0, new SpreadSheetItem("Flight (Oslo)")); + table->setItem(9, 0, new SpreadSheetItem("Total:")); + + table->item(9, 0)->setFont(titleFont); + table->item(9, 0)->setBackgroundColor(Qt::lightGray); + + // column 1 + table->setItem(0, 1, new SpreadSheetItem("Date")); + table->item(0, 1)->setBackgroundColor(titleBackground); + table->item(0, 1)->setToolTip("This column shows the purchase date, double click to change"); + table->item(0, 1)->setFont(titleFont); + + table->setItem(1, 1, new SpreadSheetItem("15/6/2006")); + table->setItem(2, 1, new SpreadSheetItem("15/6/2006")); + table->setItem(3, 1, new SpreadSheetItem("15/6/2006")); + table->setItem(4, 1, new SpreadSheetItem("21/5/2006")); + table->setItem(5, 1, new SpreadSheetItem("16/6/2006")); + table->setItem(6, 1, new SpreadSheetItem("16/6/2006")); + table->setItem(7, 1, new SpreadSheetItem("16/6/2006")); + table->setItem(8, 1, new SpreadSheetItem("18/6/2006")); + + table->setItem(9, 1, new SpreadSheetItem()); + table->item(9, 1)->setBackgroundColor(Qt::lightGray); + + // column 2 + table->setItem(0, 2, new SpreadSheetItem("Price")); + table->item(0, 2)->setBackgroundColor(titleBackground); + table->item(0, 2)->setToolTip("This column shows the price of the purchase"); + table->item(0, 2)->setFont(titleFont); + + table->setItem(1, 2, new SpreadSheetItem("150")); + table->setItem(2, 2, new SpreadSheetItem("2350")); + table->setItem(3, 2, new SpreadSheetItem("-14")); + table->setItem(4, 2, new SpreadSheetItem("980")); + table->setItem(5, 2, new SpreadSheetItem("5")); + table->setItem(6, 2, new SpreadSheetItem("120")); + table->setItem(7, 2, new SpreadSheetItem("300")); + table->setItem(8, 2, new SpreadSheetItem("1240")); + + table->setItem(9, 2, new SpreadSheetItem()); + table->item(9, 2)->setBackgroundColor(Qt::lightGray); + + // column 3 + table->setItem(0, 3, new SpreadSheetItem("Currency")); + table->item(0, 3)->setBackgroundColor(titleBackground); + table->item(0, 3)->setToolTip("This column shows the currency"); + table->item(0, 3)->setFont(titleFont); + + table->setItem(1, 3, new SpreadSheetItem("NOK")); + table->setItem(2, 3, new SpreadSheetItem("NOK")); + table->setItem(3, 3, new SpreadSheetItem("EUR")); + table->setItem(4, 3, new SpreadSheetItem("EUR")); + table->setItem(5, 3, new SpreadSheetItem("USD")); + table->setItem(6, 3, new SpreadSheetItem("USD")); + table->setItem(7, 3, new SpreadSheetItem("USD")); + table->setItem(8, 3, new SpreadSheetItem("USD")); + + table->setItem(9, 3, new SpreadSheetItem()); + table->item(9,3)->setBackgroundColor(Qt::lightGray); + + // column 4 + table->setItem(0, 4, new SpreadSheetItem("Ex. Rate")); + table->item(0, 4)->setBackgroundColor(titleBackground); + table->item(0, 4)->setToolTip("This column shows the exchange rate to NOK"); + table->item(0, 4)->setFont(titleFont); + + table->setItem(1, 4, new SpreadSheetItem("1")); + table->setItem(2, 4, new SpreadSheetItem("1")); + table->setItem(3, 4, new SpreadSheetItem("8")); + table->setItem(4, 4, new SpreadSheetItem("8")); + table->setItem(5, 4, new SpreadSheetItem("7")); + table->setItem(6, 4, new SpreadSheetItem("7")); + table->setItem(7, 4, new SpreadSheetItem("7")); + table->setItem(8, 4, new SpreadSheetItem("7")); + + table->setItem(9, 4, new SpreadSheetItem()); + table->item(9,4)->setBackgroundColor(Qt::lightGray); + + // column 5 + table->setItem(0, 5, new SpreadSheetItem("NOK")); + table->item(0, 5)->setBackgroundColor(titleBackground); + table->item(0, 5)->setToolTip("This column shows the expenses in NOK"); + table->item(0, 5)->setFont(titleFont); + + table->setItem(1, 5, new SpreadSheetItem("* C2 E2")); + table->setItem(2, 5, new SpreadSheetItem("* C3 E3")); + table->setItem(3, 5, new SpreadSheetItem("* C4 E4")); + table->setItem(4, 5, new SpreadSheetItem("* C5 E5")); + table->setItem(5, 5, new SpreadSheetItem("* C6 E6")); + table->setItem(6, 5, new SpreadSheetItem("* C7 E7")); + table->setItem(7, 5, new SpreadSheetItem("* C8 E8")); + table->setItem(8, 5, new SpreadSheetItem("* C9 E9")); + + table->setItem(9, 5, new SpreadSheetItem("sum F2 F9")); + table->item(9,5)->setBackgroundColor(Qt::lightGray); +} + +const char *htmlText = +"" +"

    This demo shows use of QTableWidget with custom handling for" +" individual cells.

    " +"

    Using a customized table item we make it possible to have dynamic" +" output in different cells. The content that is implemented for this" +" particular demo is:" +"

      " +"
    • Adding two cells.
    • " +"
    • Subtracting one cell from another.
    • " +"
    • Multiplying two cells.
    • " +"
    • Dividing one cell with another.
    • " +"
    • Summing the contents of an arbitrary number of cells.
    • " +""; + +void SpreadSheet::showAbout() +{ + QMessageBox::about(this, "About Spreadsheet", htmlText); +} + +void decode_pos(const QString &pos, int *row, int *col) +{ + if (pos.isEmpty()) { + *col = -1; + *row = -1; + } else { + *col = pos.at(0).toLatin1() - 'A'; + *row = pos.right(pos.size() - 1).toInt() - 1; + } +} + +QString encode_pos(int row, int col) +{ + return QString(col + 'A') + QString::number(row + 1); +} + + +void SpreadSheet::print() +{ +#ifndef QT_NO_PRINTER + QPrinter printer(QPrinter::ScreenResolution); + QPrintPreviewDialog dlg(&printer); + PrintView view; + view.setModel(table->model()); + connect(&dlg, SIGNAL(paintRequested(QPrinter*)), + &view, SLOT(print(QPrinter*))); + dlg.exec(); +#endif +} + diff --git a/examples/itemviews/spreadsheet/spreadsheet.h b/examples/itemviews/spreadsheet/spreadsheet.h new file mode 100644 index 0000000000..386a469c99 --- /dev/null +++ b/examples/itemviews/spreadsheet/spreadsheet.h @@ -0,0 +1,124 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPREADSHEET_H +#define SPREADSHEET_H + +#include + +QT_BEGIN_NAMESPACE +class QAction; +class QLabel; +class QLineEdit; +class QToolBar; +class QTableWidgetItem; +class QTableWidget; +QT_END_NAMESPACE + +class SpreadSheet : public QMainWindow +{ + Q_OBJECT + +public: + + SpreadSheet(int rows, int cols, QWidget *parent = 0); + +public slots: + void updateStatus(QTableWidgetItem *item); + void updateColor(QTableWidgetItem *item); + void updateLineEdit(QTableWidgetItem *item); + void returnPressed(); + void selectColor(); + void selectFont(); + void clear(); + void showAbout(); + + void print(); + + void actionSum(); + void actionSubtract(); + void actionAdd(); + void actionMultiply(); + void actionDivide(); + +protected: + void setupContextMenu(); + void setupContents(); + + void setupMenuBar(); + void createActions(); + + void actionMath_helper(const QString &title, const QString &op); + bool runInputDialog(const QString &title, + const QString &c1Text, + const QString &c2Text, + const QString &opText, + const QString &outText, + QString *cell1, QString *cell2, QString *outCell); +private: + QToolBar *toolBar; + QAction *colorAction; + QAction *fontAction; + QAction *firstSeparator; + QAction *cell_sumAction; + QAction *cell_addAction; + QAction *cell_subAction; + QAction *cell_mulAction; + QAction *cell_divAction; + QAction *secondSeparator; + QAction *clearAction; + QAction *aboutSpreadSheet; + QAction *exitAction; + + QAction *printAction; + + QLabel *cellLabel; + QTableWidget *table; + QLineEdit *formulaInput; + +}; + +void decode_pos(const QString &pos, int *row, int *col); +QString encode_pos(int row, int col); + + +#endif // SPREADSHEET_H + diff --git a/examples/itemviews/spreadsheet/spreadsheet.pro b/examples/itemviews/spreadsheet/spreadsheet.pro new file mode 100644 index 0000000000..7179d98eba --- /dev/null +++ b/examples/itemviews/spreadsheet/spreadsheet.pro @@ -0,0 +1,34 @@ +###################################################################### +# Automatically generated by qmake (2.01a) Thu Mar 5 14:39:33 2009 +###################################################################### + +TEMPLATE = app +TARGET = +DEPENDPATH += . +INCLUDEPATH += . + +CONFIG += qt warn_on +#unix:contains(QT_CONFIG, dbus):QT += dbus + +# Input +HEADERS += printview.h spreadsheet.h spreadsheetdelegate.h spreadsheetitem.h +SOURCES += main.cpp \ + printview.cpp \ + spreadsheet.cpp \ + spreadsheetdelegate.cpp \ + spreadsheetitem.cpp +RESOURCES += spreadsheet.qrc + + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/spreadsheet +sources.files = $$SOURCES $$RESOURCES *.pro images $$HEADERS +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/spreadsheet +INSTALLS += target sources + +symbian: CONFIG += qt_demo diff --git a/examples/itemviews/spreadsheet/spreadsheet.qrc b/examples/itemviews/spreadsheet/spreadsheet.qrc new file mode 100644 index 0000000000..13f496d8e3 --- /dev/null +++ b/examples/itemviews/spreadsheet/spreadsheet.qrc @@ -0,0 +1,5 @@ + + + images/interview.png + + diff --git a/examples/itemviews/spreadsheet/spreadsheetdelegate.cpp b/examples/itemviews/spreadsheet/spreadsheetdelegate.cpp new file mode 100644 index 0000000000..6f2f2dd071 --- /dev/null +++ b/examples/itemviews/spreadsheet/spreadsheetdelegate.cpp @@ -0,0 +1,114 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spreadsheetdelegate.h" +#include + +SpreadSheetDelegate::SpreadSheetDelegate(QObject *parent) + : QItemDelegate(parent) {} + +QWidget *SpreadSheetDelegate::createEditor(QWidget *parent, + const QStyleOptionViewItem &, + const QModelIndex &index) const +{ + if (index.column() == 1) { + QDateTimeEdit *editor = new QDateTimeEdit(parent); + editor->setDisplayFormat("dd/M/yyyy"); + editor->setCalendarPopup(true); + return editor; + } + + QLineEdit *editor = new QLineEdit(parent); + + // create a completer with the strings in the column as model + QStringList allStrings; + for (int i = 1; irowCount(); i++) { + QString strItem(index.model()->data(index.sibling(i, index.column()), + Qt::EditRole).toString()); + + if (!allStrings.contains(strItem)) + allStrings.append(strItem); + } + + QCompleter *autoComplete = new QCompleter(allStrings); + editor->setCompleter(autoComplete); + connect(editor, SIGNAL(editingFinished()), + this, SLOT(commitAndCloseEditor())); + return editor; +} + +void SpreadSheetDelegate::commitAndCloseEditor() +{ + QLineEdit *editor = qobject_cast(sender()); + emit commitData(editor); + emit closeEditor(editor); +} + +void SpreadSheetDelegate::setEditorData(QWidget *editor, + const QModelIndex &index) const +{ + QLineEdit *edit = qobject_cast(editor); + if (edit) { + edit->setText(index.model()->data(index, Qt::EditRole).toString()); + } else { + QDateTimeEdit *dateEditor = qobject_cast(editor); + if (dateEditor) { + dateEditor->setDate(QDate::fromString( + index.model()->data(index, Qt::EditRole).toString(), + "d/M/yyyy")); + } + } +} + +void SpreadSheetDelegate::setModelData(QWidget *editor, + QAbstractItemModel *model, const QModelIndex &index) const +{ + QLineEdit *edit = qobject_cast(editor); + if (edit) { + model->setData(index, edit->text()); + } else { + QDateTimeEdit *dateEditor = qobject_cast(editor); + if (dateEditor) { + model->setData(index, dateEditor->date().toString("dd/M/yyyy")); + } + } +} + diff --git a/examples/itemviews/spreadsheet/spreadsheetdelegate.h b/examples/itemviews/spreadsheet/spreadsheetdelegate.h new file mode 100644 index 0000000000..7987f35499 --- /dev/null +++ b/examples/itemviews/spreadsheet/spreadsheetdelegate.h @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPREADSHEETDELEGATE_H +#define SPREADSHEETDELEGATE_H + +#include +#include "spreadsheet.h" + +class SpreadSheetDelegate : public QItemDelegate +{ + Q_OBJECT + +public: + SpreadSheetDelegate(QObject *parent = 0); + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &, + const QModelIndex &index) const; + void setEditorData(QWidget *editor, const QModelIndex &index) const; + void setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const; + +private slots: + void commitAndCloseEditor(); +}; + +#endif // SPREADSHEETDELEGATE_H + diff --git a/examples/itemviews/spreadsheet/spreadsheetitem.cpp b/examples/itemviews/spreadsheet/spreadsheetitem.cpp new file mode 100644 index 0000000000..74a1967a8a --- /dev/null +++ b/examples/itemviews/spreadsheet/spreadsheetitem.cpp @@ -0,0 +1,167 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spreadsheetitem.h" + +SpreadSheetItem::SpreadSheetItem() + : QTableWidgetItem(), isResolving(false) +{ +} + +SpreadSheetItem::SpreadSheetItem(const QString &text) + : QTableWidgetItem(text), isResolving(false) +{ +} + +QTableWidgetItem *SpreadSheetItem::clone() const +{ + SpreadSheetItem *item = new SpreadSheetItem(); + *item = *this; + return item; +} + +QVariant SpreadSheetItem::data(int role) const +{ + if (role == Qt::EditRole || role == Qt::StatusTipRole) + return formula(); + + if (role == Qt::DisplayRole) + return display(); + + QString t = display().toString(); + bool isNumber = false; + int number = t.toInt(&isNumber); + + if (role == Qt::TextColorRole) { + if (!isNumber) + return QVariant::fromValue(QColor(Qt::black)); + else if (number < 0) + return QVariant::fromValue(QColor(Qt::red)); + return QVariant::fromValue(QColor(Qt::blue)); + } + + if (role == Qt::TextAlignmentRole) + if (!t.isEmpty() && (t.at(0).isNumber() || t.at(0) == '-')) + return (int)(Qt::AlignRight | Qt::AlignVCenter); + + return QTableWidgetItem::data(role); + } + +void SpreadSheetItem::setData(int role, const QVariant &value) +{ + QTableWidgetItem::setData(role, value); + if (tableWidget()) + tableWidget()->viewport()->update(); +} + +QVariant SpreadSheetItem::display() const +{ + // avoid circular dependencies + if (isResolving) + return QVariant(); + + isResolving = true; + QVariant result = computeFormula(formula(), tableWidget(), this); + isResolving = false; + return result; +} + +QVariant SpreadSheetItem::computeFormula(const QString &formula, + const QTableWidget *widget, + const QTableWidgetItem *self) +{ + // check if the s tring is actually a formula or not + QStringList list = formula.split(' '); + if (list.isEmpty() || !widget) + return formula; // it is a normal string + + QString op = list.value(0).toLower(); + + int firstRow = -1; + int firstCol = -1; + int secondRow = -1; + int secondCol = -1; + + if (list.count() > 1) + decode_pos(list.value(1), &firstRow, &firstCol); + + if (list.count() > 2) + decode_pos(list.value(2), &secondRow, &secondCol); + + const QTableWidgetItem *start = widget->item(firstRow, firstCol); + const QTableWidgetItem *end = widget->item(secondRow, secondCol); + + int firstVal = start ? start->text().toInt() : 0; + int secondVal = end ? end->text().toInt() : 0; + + QVariant result; + if (op == "sum") { + int sum = 0; + for (int r = firstRow; r <= secondRow; ++r) { + for (int c = firstCol; c <= secondCol; ++c) { + const QTableWidgetItem *tableItem = widget->item(r, c); + if (tableItem && tableItem != self) + sum += tableItem->text().toInt(); + } + } + + result = sum; + } else if (op == "+") { + result = (firstVal + secondVal); + } else if (op == "-") { + result = (firstVal - secondVal); + } else if (op == "*") { + result = (firstVal * secondVal); + } else if (op == "/") { + if (secondVal == 0) + result = QString("nan"); + else + result = (firstVal / secondVal); + } else if (op == "=") { + if (start) + result = start->text(); + } else { + result = formula; + } + + return result; +} + diff --git a/examples/itemviews/spreadsheet/spreadsheetitem.h b/examples/itemviews/spreadsheet/spreadsheetitem.h new file mode 100644 index 0000000000..b0e7e337ed --- /dev/null +++ b/examples/itemviews/spreadsheet/spreadsheetitem.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPREADSHEETITEM_H +#define SPREADSHEETITEM_H + +#include +#include +#include "spreadsheet.h" + +class SpreadSheetItem : public QTableWidgetItem +{ +public: + SpreadSheetItem(); + SpreadSheetItem(const QString &text); + + QTableWidgetItem *clone() const; + + QVariant data(int role) const; + void setData(int role, const QVariant &value); + QVariant display() const; + + inline QString formula() const + { return QTableWidgetItem::data(Qt::DisplayRole).toString(); } + + static QVariant computeFormula(const QString &formula, + const QTableWidget *widget, + const QTableWidgetItem *self = 0); + +private: + mutable bool isResolving; +}; + +#endif // SPREADSHEETITEM_H + diff --git a/examples/mainwindows/macmainwindow/macmainwindow.h b/examples/mainwindows/macmainwindow/macmainwindow.h new file mode 100644 index 0000000000..10ff3b5147 --- /dev/null +++ b/examples/mainwindows/macmainwindow/macmainwindow.h @@ -0,0 +1,137 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#ifndef MACMAINWINDOW_H +#define MACMAINWINDOW_H + +#include + +#ifdef Q_WS_MAC + +#import + +#ifdef QT_MAC_USE_COCOA +class SearchWidget : public QMacCocoaViewContainer +{ + Q_OBJECT +public: + SearchWidget(QWidget *parent = 0); + ~SearchWidget(); + + QSize sizeHint() const; +private: +}; + +#else +#include + +// The SearchWidget class wraps a native HISearchField. +class SearchWidget : public QWidget +{ + Q_OBJECT +private: + HIViewRef searchField; + CFStringRef searchFieldText; + +public: + QSize sizeHint() const; + SearchWidget(QWidget *parent = 0); + ~SearchWidget(); +}; + +#endif + +QMenu *createMenu(QWidget *parent); + +class SearchWrapper : public QWidget +{ +Q_OBJECT +public: + SearchWrapper(QWidget *parent = 0); + QSize sizeHint() const; + QWidget *s; +}; + +class Spacer : public QWidget +{ +Q_OBJECT +public: + Spacer(QWidget *parent = 0); + QSize sizeHint() const; +}; + +class MacSplitterHandle : public QSplitterHandle +{ +Q_OBJECT +public: + MacSplitterHandle(Qt::Orientation orientation, QSplitter *parent); + void paintEvent(QPaintEvent *); + QSize sizeHint() const; +}; + +class MacSplitter : public QSplitter +{ +public: + QSplitterHandle *createHandle(); +}; + +class MacMainWindow : public QMainWindow +{ +Q_OBJECT +public: + MacMainWindow(); + ~MacMainWindow(); + QAbstractItemModel *createItemModel(); + void resizeEvent(QResizeEvent *e); + QAbstractItemModel *createDocumentModel(); +public: + QSplitter *splitter; + QSplitter *horizontalSplitter; + QTreeView *sidebar; + QListView *documents; + QTextEdit *textedit; + QVBoxLayout *layout; + SearchWidget *searchWidget; + QToolBar * toolBar; +}; + +#endif // Q_WS_MAC + +#endif //MACMAINWINDOW_H diff --git a/examples/mainwindows/macmainwindow/macmainwindow.mm b/examples/mainwindows/macmainwindow/macmainwindow.mm new file mode 100644 index 0000000000..3b0ba6f02a --- /dev/null +++ b/examples/mainwindows/macmainwindow/macmainwindow.mm @@ -0,0 +1,347 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#include "macmainwindow.h" +#import +#include + + +#ifdef Q_WS_MAC + +#include + +#ifdef QT_MAC_USE_COCOA + +//![0] +SearchWidget::SearchWidget(QWidget *parent) + : QMacCocoaViewContainer(0, parent) +{ + // Many Cocoa objects create temporary autorelease objects, + // so create a pool to catch them. + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + // Create the NSSearchField, set it on the QCocoaViewContainer. + NSSearchField *search = [[NSSearchField alloc] init]; + setCocoaView(search); + + // Use a Qt menu for the search field menu. + QMenu *qtMenu = createMenu(this); + NSMenu *nsMenu = qtMenu->macMenu(0); + [[search cell] setSearchMenuTemplate:nsMenu]; + + // Release our reference, since our super class takes ownership and we + // don't need it anymore. + [search release]; + + // Clean up our pool as we no longer need it. + [pool release]; +} +//![0] + +SearchWidget::~SearchWidget() +{ +} + +QSize SearchWidget::sizeHint() const +{ + return QSize(150, 40); +} + +#else + +// The SearchWidget class wraps a native HISearchField. +SearchWidget::SearchWidget(QWidget *parent) + :QWidget(parent) +{ + + // Create a native search field and pass its window id to QWidget::create. + searchFieldText = CFStringCreateWithCString(0, "search", 0); + HISearchFieldCreate(NULL/*bounds*/, kHISearchFieldAttributesSearchIcon | kHISearchFieldAttributesCancel, + NULL/*menu ref*/, searchFieldText, &searchField); + create(reinterpret_cast(searchField)); + + // Use a Qt menu for the search field menu. + QMenu *searchMenu = createMenu(this); + MenuRef menuRef = searchMenu->macMenu(0); + HISearchFieldSetSearchMenu(searchField, menuRef); + setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); +} + +SearchWidget::~SearchWidget() +{ + CFRelease(searchField); + CFRelease(searchFieldText); +} + +// Get the size hint from the search field. +QSize SearchWidget::sizeHint() const +{ + EventRef event; + HIRect optimalBounds; + CreateEvent(0, kEventClassControl, + kEventControlGetOptimalBounds, + GetCurrentEventTime(), + kEventAttributeUserEvent, &event); + + SendEventToEventTargetWithOptions(event, + HIObjectGetEventTarget(HIObjectRef(winId())), + kEventTargetDontPropagate); + + GetEventParameter(event, + kEventParamControlOptimalBounds, typeHIRect, + 0, sizeof(HIRect), 0, &optimalBounds); + + ReleaseEvent(event); + return QSize(optimalBounds.size.width + 100, // make it a bit wider. + optimalBounds.size.height); +} + +#endif + +QMenu *createMenu(QWidget *parent) +{ + QMenu *searchMenu = new QMenu(parent); + + QAction * indexAction = searchMenu->addAction("Index Search"); + indexAction->setCheckable(true); + indexAction->setChecked(true); + + QAction * fulltextAction = searchMenu->addAction("Full Text Search"); + fulltextAction->setCheckable(true); + + QActionGroup *searchActionGroup = new QActionGroup(parent); + searchActionGroup->addAction(indexAction); + searchActionGroup->addAction(fulltextAction); + searchActionGroup->setExclusive(true); + + return searchMenu; +} + +SearchWrapper::SearchWrapper(QWidget *parent) +:QWidget(parent) +{ + s = new SearchWidget(this); + s->move(2,2); + setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); +} + +QSize SearchWrapper::sizeHint() const +{ + return s->sizeHint() + QSize(6, 2); +} + +Spacer::Spacer(QWidget *parent) +:QWidget(parent) +{ + QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + setSizePolicy(sizePolicy); +} + +QSize Spacer::sizeHint() const +{ + return QSize(1, 1); +} + +MacSplitterHandle::MacSplitterHandle(Qt::Orientation orientation, QSplitter *parent) +: QSplitterHandle(orientation, parent) { } + +// Paint the horizontal handle as a gradient, paint +// the vertical handle as a line. +void MacSplitterHandle::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + + QColor topColor(145, 145, 145); + QColor bottomColor(142, 142, 142); + QColor gradientStart(252, 252, 252); + QColor gradientStop(223, 223, 223); + + if (orientation() == Qt::Vertical) { + painter.setPen(topColor); + painter.drawLine(0, 0, width(), 0); + painter.setPen(bottomColor); + painter.drawLine(0, height() - 1, width(), height() - 1); + + QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, height() -3)); + linearGrad.setColorAt(0, gradientStart); + linearGrad.setColorAt(1, gradientStop); + painter.fillRect(QRect(QPoint(0,1), size() - QSize(0, 2)), QBrush(linearGrad)); + } else { + painter.setPen(topColor); + painter.drawLine(0, 0, 0, height()); + } +} + +QSize MacSplitterHandle::sizeHint() const +{ + QSize parent = QSplitterHandle::sizeHint(); + if (orientation() == Qt::Vertical) { + return parent + QSize(0, 3); + } else { + return QSize(1, parent.height()); + } +} + +QSplitterHandle *MacSplitter::createHandle() +{ + return new MacSplitterHandle(orientation(), this); +} + +MacMainWindow::MacMainWindow() +{ + QSettings settings; + restoreGeometry(settings.value("Geometry").toByteArray()); + + setWindowTitle("Mac Main Window"); + + splitter = new MacSplitter(); + + // Set up the left-hand side blue side bar. + sidebar = new QTreeView(); + sidebar->setFrameStyle(QFrame::NoFrame); + sidebar->setAttribute(Qt::WA_MacShowFocusRect, false); + sidebar->setAutoFillBackground(true); + + // Set the palette. + QPalette palette = sidebar->palette(); + QColor macSidebarColor(231, 237, 246); + QColor macSidebarHighlightColor(168, 183, 205); + palette.setColor(QPalette::Base, macSidebarColor); + palette.setColor(QPalette::Highlight, macSidebarHighlightColor); + sidebar->setPalette(palette); + + sidebar->setModel(createItemModel()); + sidebar->header()->hide(); + sidebar->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + sidebar->setTextElideMode(Qt::ElideMiddle); + + splitter->addWidget(sidebar); + + horizontalSplitter = new MacSplitter(); + horizontalSplitter->setOrientation(Qt::Vertical); + splitter->addWidget(horizontalSplitter); + + splitter->setStretchFactor(0, 0); + splitter->setStretchFactor(1, 1); + + // Set up the top document list view. + documents = new QListView(); + documents->setFrameStyle(QFrame::NoFrame); + documents->setAttribute(Qt::WA_MacShowFocusRect, false); + documents->setModel(createDocumentModel()); + documents->setAlternatingRowColors(true); + documents->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); + horizontalSplitter->addWidget(documents); + horizontalSplitter->setStretchFactor(0, 0); + + // Set up the text view. + textedit = new QTextEdit(); + textedit->setFrameStyle(QFrame::NoFrame); + textedit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); + textedit->setText("





      This demo shows how to create a \ + Qt main window application that has the same appearance as other \ + Mac OS X applications such as Mail or iTunes. This includes \ + customizing the item views and QSplitter and wrapping native widgets \ + such as the search field.
      "); + + horizontalSplitter->addWidget(textedit); + + setCentralWidget(splitter); + + toolBar = addToolBar(tr("Search")); + toolBar->addWidget(new Spacer()); + toolBar->addWidget(new SearchWrapper()); + + setUnifiedTitleAndToolBarOnMac(true); +} + +MacMainWindow::~MacMainWindow() +{ + QSettings settings; + settings.setValue("Geometry", saveGeometry()); +} + +QAbstractItemModel *MacMainWindow::createItemModel() +{ + QStandardItemModel *model = new QStandardItemModel(); + QStandardItem *parentItem = model->invisibleRootItem(); + + QStandardItem *documentationItem = new QStandardItem("Documentation"); + parentItem->appendRow(documentationItem); + + QStandardItem *assistantItem = new QStandardItem("Qt MainWindow Manual"); + documentationItem->appendRow(assistantItem); + + QStandardItem *designerItem = new QStandardItem("Qt Designer Manual"); + documentationItem->appendRow(designerItem); + + QStandardItem *qtItem = new QStandardItem("Qt Reference Documentation"); + qtItem->appendRow(new QStandardItem("Classes")); + qtItem->appendRow(new QStandardItem("Overviews")); + qtItem->appendRow(new QStandardItem("Tutorial & Examples")); + documentationItem->appendRow(qtItem); + + QStandardItem *bookmarksItem = new QStandardItem("Bookmarks"); + parentItem->appendRow(bookmarksItem); + bookmarksItem->appendRow(new QStandardItem("QWidget")); + bookmarksItem->appendRow(new QStandardItem("QObject")); + bookmarksItem->appendRow(new QStandardItem("QWizard")); + + return model; +} + +void MacMainWindow::resizeEvent(QResizeEvent *) +{ + if (toolBar) + toolBar->updateGeometry(); +} + +QAbstractItemModel *MacMainWindow::createDocumentModel() +{ + QStandardItemModel *model = new QStandardItemModel(); + QStandardItem *parentItem = model->invisibleRootItem(); + parentItem->appendRow(new QStandardItem("QWidget Class Reference")); + parentItem->appendRow(new QStandardItem("QObject Class Reference")); + parentItem->appendRow(new QStandardItem("QListView Class Reference")); + + return model; +} + +#endif // Q_WS_MAC diff --git a/examples/mainwindows/macmainwindow/macmainwindow.pro b/examples/mainwindows/macmainwindow/macmainwindow.pro new file mode 100644 index 0000000000..435905612a --- /dev/null +++ b/examples/mainwindows/macmainwindow/macmainwindow.pro @@ -0,0 +1,23 @@ +TEMPLATE = app +TARGET = macmainwindow + +CONFIG += qt warn_on console + +OBJECTIVE_SOURCES += macmainwindow.mm +SOURCES += main.cpp +HEADERS += macmainwindow.h + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +LIBS += -framework Cocoa -framework Carbon + +# install +mac { +target.path = $$[QT_INSTALL_DEMOS]/qtbase/macmainwindow +sources.files = $$SOURCES *.pro *.html +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/macmainwindow +INSTALLS += target sources +} diff --git a/examples/mainwindows/macmainwindow/main.cpp b/examples/mainwindows/macmainwindow/main.cpp new file mode 100644 index 0000000000..34e4847068 --- /dev/null +++ b/examples/mainwindows/macmainwindow/main.cpp @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "macmainwindow.h" + +#ifdef Q_WS_MAC + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + MacMainWindow mainWindow; + mainWindow.show(); + return app.exec(); +} + +#else +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + QLabel label; + label.resize(300, 200); + label.setText(" This demo requires Mac OS X."); + label.show(); + return app.exec(); +} + +#endif diff --git a/examples/mainwindows/mainwindow/colorswatch.cpp b/examples/mainwindows/mainwindow/colorswatch.cpp new file mode 100644 index 0000000000..dd16fddbe7 --- /dev/null +++ b/examples/mainwindows/mainwindow/colorswatch.cpp @@ -0,0 +1,746 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "colorswatch.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#undef DEBUG_SIZEHINTS + +QColor bgColorForName(const QString &name) +{ + if (name == "Black") + return QColor("#D8D8D8"); + else if (name == "White") + return QColor("#F1F1F1"); + else if (name == "Red") + return QColor("#F1D8D8"); + else if (name == "Green") + return QColor("#D8E4D8"); + else if (name == "Blue") + return QColor("#D8D8F1"); + else if (name == "Yellow") + return QColor("#F1F0D8"); + return QColor(name).light(110); +} + +QColor fgColorForName(const QString &name) +{ + if (name == "Black") + return QColor("#6C6C6C"); + else if (name == "White") + return QColor("#F8F8F8"); + else if (name == "Red") + return QColor("#F86C6C"); + else if (name == "Green") + return QColor("#6CB26C"); + else if (name == "Blue") + return QColor("#6C6CF8"); + else if (name == "Yellow") + return QColor("#F8F76C"); + return QColor(name); +} + +class ColorDock : public QFrame +{ + Q_OBJECT +public: + ColorDock(const QString &c, QWidget *parent); + + virtual QSize sizeHint() const; + virtual QSize minimumSizeHint() const; + + void setCustomSizeHint(const QSize &size); + +public slots: + void changeSizeHints(); + +protected: + void paintEvent(QPaintEvent *); + QString color; + QSize szHint, minSzHint; +}; + +ColorDock::ColorDock(const QString &c, QWidget *parent) + : QFrame(parent) , color(c) +{ + QFont font = this->font(); + font.setPointSize(8); + setFont(font); + szHint = QSize(-1, -1); + minSzHint = QSize(125, 75); +} + +QSize ColorDock::sizeHint() const +{ + return szHint; +} + +QSize ColorDock::minimumSizeHint() const +{ + return minSzHint; +} + +void ColorDock::paintEvent(QPaintEvent *) +{ + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + p.fillRect(rect(), bgColorForName(color)); + + p.save(); + + extern void render_qt_text(QPainter *, int, int, const QColor &); + render_qt_text(&p, width(), height(), fgColorForName(color)); + + p.restore(); + +#ifdef DEBUG_SIZEHINTS + p.setRenderHint(QPainter::Antialiasing, false); + + QSize sz = size(); + QSize szHint = sizeHint(); + QSize minSzHint = minimumSizeHint(); + QSize maxSz = maximumSize(); + QString text = QString::fromLatin1("sz: %1x%2\nszHint: %3x%4\nminSzHint: %5x%6\n" + "maxSz: %8x%9") + .arg(sz.width()).arg(sz.height()) + .arg(szHint.width()).arg(szHint.height()) + .arg(minSzHint.width()).arg(minSzHint.height()) + .arg(maxSz.width()).arg(maxSz.height()); + + QRect r = fontMetrics().boundingRect(rect(), Qt::AlignLeft|Qt::AlignTop, text); + r.adjust(-2, -2, 1, 1); + p.translate(4, 4); + QColor bg = Qt::yellow; + bg.setAlpha(120); + p.setBrush(bg); + p.setPen(Qt::black); + p.drawRect(r); + p.drawText(rect(), Qt::AlignLeft|Qt::AlignTop, text); +#endif // DEBUG_SIZEHINTS +} + +static QSpinBox *createSpinBox(int value, QWidget *parent, int max = 1000) +{ + QSpinBox *result = new QSpinBox(parent); + result->setMinimum(-1); + result->setMaximum(max); + result->setValue(value); + return result; +} + +void ColorDock::changeSizeHints() +{ + QDialog dialog(this); + dialog.setWindowTitle(color); + + QVBoxLayout *topLayout = new QVBoxLayout(&dialog); + + QGridLayout *inputLayout = new QGridLayout(); + topLayout->addLayout(inputLayout); + + inputLayout->addWidget(new QLabel(tr("Size Hint:"), &dialog), 0, 0); + inputLayout->addWidget(new QLabel(tr("Min Size Hint:"), &dialog), 1, 0); + inputLayout->addWidget(new QLabel(tr("Max Size:"), &dialog), 2, 0); + inputLayout->addWidget(new QLabel(tr("Dockwgt Max Size:"), &dialog), 3, 0); + + QSpinBox *szHintW = createSpinBox(szHint.width(), &dialog); + inputLayout->addWidget(szHintW, 0, 1); + QSpinBox *szHintH = createSpinBox(szHint.height(), &dialog); + inputLayout->addWidget(szHintH, 0, 2); + + QSpinBox *minSzHintW = createSpinBox(minSzHint.width(), &dialog); + inputLayout->addWidget(minSzHintW, 1, 1); + QSpinBox *minSzHintH = createSpinBox(minSzHint.height(), &dialog); + inputLayout->addWidget(minSzHintH, 1, 2); + + QSize maxSz = maximumSize(); + QSpinBox *maxSzW = createSpinBox(maxSz.width(), &dialog, QWIDGETSIZE_MAX); + inputLayout->addWidget(maxSzW, 2, 1); + QSpinBox *maxSzH = createSpinBox(maxSz.height(), &dialog, QWIDGETSIZE_MAX); + inputLayout->addWidget(maxSzH, 2, 2); + + QSize dwMaxSz = parentWidget()->maximumSize(); + QSpinBox *dwMaxSzW = createSpinBox(dwMaxSz.width(), &dialog, QWIDGETSIZE_MAX); + inputLayout->addWidget(dwMaxSzW, 3, 1); + QSpinBox *dwMaxSzH = createSpinBox(dwMaxSz.height(), &dialog, QWIDGETSIZE_MAX); + inputLayout->addWidget(dwMaxSzH, 3, 2); + + inputLayout->setColumnStretch(1, 1); + inputLayout->setColumnStretch(2, 1); + + topLayout->addStretch(); + + QHBoxLayout *buttonBox = new QHBoxLayout(); + topLayout->addLayout(buttonBox); + + QPushButton *okButton = new QPushButton(tr("Ok"), &dialog); + QPushButton *cancelButton = new QPushButton(tr("Cancel"), &dialog); + connect(okButton, SIGNAL(clicked()), &dialog, SLOT(accept())); + connect(cancelButton, SIGNAL(clicked()), &dialog, SLOT(reject())); + buttonBox->addStretch(); + buttonBox->addWidget(cancelButton); + buttonBox->addWidget(okButton); + + + if (!dialog.exec()) + return; + + szHint = QSize(szHintW->value(), szHintH->value()); + minSzHint = QSize(minSzHintW->value(), minSzHintH->value()); + maxSz = QSize(maxSzW->value(), maxSzH->value()); + setMaximumSize(maxSz); + dwMaxSz = QSize(dwMaxSzW->value(), dwMaxSzH->value()); + parentWidget()->setMaximumSize(dwMaxSz); + updateGeometry(); + update(); +} + +void ColorDock::setCustomSizeHint(const QSize &size) +{ + szHint = size; + updateGeometry(); +} + +ColorSwatch::ColorSwatch(const QString &colorName, QWidget *parent, Qt::WindowFlags flags) + : QDockWidget(parent, flags) +{ + setObjectName(colorName + QLatin1String(" Dock Widget")); + setWindowTitle(objectName() + QLatin1String(" [*]")); + + QFrame *swatch = new ColorDock(colorName, this); + swatch->setFrameStyle(QFrame::Box | QFrame::Sunken); + + setWidget(swatch); + + changeSizeHintsAction = new QAction(tr("Change Size Hints"), this); + connect(changeSizeHintsAction, SIGNAL(triggered()), swatch, SLOT(changeSizeHints())); + + closableAction = new QAction(tr("Closable"), this); + closableAction->setCheckable(true); + connect(closableAction, SIGNAL(triggered(bool)), SLOT(changeClosable(bool))); + + movableAction = new QAction(tr("Movable"), this); + movableAction->setCheckable(true); + connect(movableAction, SIGNAL(triggered(bool)), SLOT(changeMovable(bool))); + + floatableAction = new QAction(tr("Floatable"), this); + floatableAction->setCheckable(true); + connect(floatableAction, SIGNAL(triggered(bool)), SLOT(changeFloatable(bool))); + + verticalTitleBarAction = new QAction(tr("Vertical title bar"), this); + verticalTitleBarAction->setCheckable(true); + connect(verticalTitleBarAction, SIGNAL(triggered(bool)), + SLOT(changeVerticalTitleBar(bool))); + + floatingAction = new QAction(tr("Floating"), this); + floatingAction->setCheckable(true); + connect(floatingAction, SIGNAL(triggered(bool)), SLOT(changeFloating(bool))); + + allowedAreasActions = new QActionGroup(this); + allowedAreasActions->setExclusive(false); + + allowLeftAction = new QAction(tr("Allow on Left"), this); + allowLeftAction->setCheckable(true); + connect(allowLeftAction, SIGNAL(triggered(bool)), SLOT(allowLeft(bool))); + + allowRightAction = new QAction(tr("Allow on Right"), this); + allowRightAction->setCheckable(true); + connect(allowRightAction, SIGNAL(triggered(bool)), SLOT(allowRight(bool))); + + allowTopAction = new QAction(tr("Allow on Top"), this); + allowTopAction->setCheckable(true); + connect(allowTopAction, SIGNAL(triggered(bool)), SLOT(allowTop(bool))); + + allowBottomAction = new QAction(tr("Allow on Bottom"), this); + allowBottomAction->setCheckable(true); + connect(allowBottomAction, SIGNAL(triggered(bool)), SLOT(allowBottom(bool))); + + allowedAreasActions->addAction(allowLeftAction); + allowedAreasActions->addAction(allowRightAction); + allowedAreasActions->addAction(allowTopAction); + allowedAreasActions->addAction(allowBottomAction); + + areaActions = new QActionGroup(this); + areaActions->setExclusive(true); + + leftAction = new QAction(tr("Place on Left") , this); + leftAction->setCheckable(true); + connect(leftAction, SIGNAL(triggered(bool)), SLOT(placeLeft(bool))); + + rightAction = new QAction(tr("Place on Right") , this); + rightAction->setCheckable(true); + connect(rightAction, SIGNAL(triggered(bool)), SLOT(placeRight(bool))); + + topAction = new QAction(tr("Place on Top") , this); + topAction->setCheckable(true); + connect(topAction, SIGNAL(triggered(bool)), SLOT(placeTop(bool))); + + bottomAction = new QAction(tr("Place on Bottom") , this); + bottomAction->setCheckable(true); + connect(bottomAction, SIGNAL(triggered(bool)), SLOT(placeBottom(bool))); + + areaActions->addAction(leftAction); + areaActions->addAction(rightAction); + areaActions->addAction(topAction); + areaActions->addAction(bottomAction); + + connect(movableAction, SIGNAL(triggered(bool)), areaActions, SLOT(setEnabled(bool))); + + connect(movableAction, SIGNAL(triggered(bool)), allowedAreasActions, SLOT(setEnabled(bool))); + + connect(floatableAction, SIGNAL(triggered(bool)), floatingAction, SLOT(setEnabled(bool))); + + connect(floatingAction, SIGNAL(triggered(bool)), floatableAction, SLOT(setDisabled(bool))); + connect(movableAction, SIGNAL(triggered(bool)), floatableAction, SLOT(setEnabled(bool))); + + tabMenu = new QMenu(this); + tabMenu->setTitle(tr("Tab into")); + connect(tabMenu, SIGNAL(triggered(QAction*)), this, SLOT(tabInto(QAction*))); + + splitHMenu = new QMenu(this); + splitHMenu->setTitle(tr("Split horizontally into")); + connect(splitHMenu, SIGNAL(triggered(QAction*)), this, SLOT(splitInto(QAction*))); + + splitVMenu = new QMenu(this); + splitVMenu->setTitle(tr("Split vertically into")); + connect(splitVMenu, SIGNAL(triggered(QAction*)), this, SLOT(splitInto(QAction*))); + + windowModifiedAction = new QAction(tr("Modified"), this); + windowModifiedAction->setCheckable(true); + windowModifiedAction->setChecked(false); + connect(windowModifiedAction, SIGNAL(toggled(bool)), this, SLOT(setWindowModified(bool))); + + menu = new QMenu(colorName, this); + menu->addAction(toggleViewAction()); + QAction *action = menu->addAction(tr("Raise")); + connect(action, SIGNAL(triggered()), this, SLOT(raise())); + menu->addAction(changeSizeHintsAction); + menu->addSeparator(); + menu->addAction(closableAction); + menu->addAction(movableAction); + menu->addAction(floatableAction); + menu->addAction(floatingAction); + menu->addAction(verticalTitleBarAction); + menu->addSeparator(); + menu->addActions(allowedAreasActions->actions()); + menu->addSeparator(); + menu->addActions(areaActions->actions()); + menu->addSeparator(); + menu->addMenu(splitHMenu); + menu->addMenu(splitVMenu); + menu->addMenu(tabMenu); + menu->addSeparator(); + menu->addAction(windowModifiedAction); + + connect(menu, SIGNAL(aboutToShow()), this, SLOT(updateContextMenu())); + + if(colorName == "Black") { + leftAction->setShortcut(Qt::CTRL|Qt::Key_W); + rightAction->setShortcut(Qt::CTRL|Qt::Key_E); + toggleViewAction()->setShortcut(Qt::CTRL|Qt::Key_R); + } +} + +void ColorSwatch::updateContextMenu() +{ + QMainWindow *mainWindow = qobject_cast(parentWidget()); + const Qt::DockWidgetArea area = mainWindow->dockWidgetArea(this); + const Qt::DockWidgetAreas areas = allowedAreas(); + + closableAction->setChecked(features() & QDockWidget::DockWidgetClosable); + if (windowType() == Qt::Drawer) { + floatableAction->setEnabled(false); + floatingAction->setEnabled(false); + movableAction->setEnabled(false); + verticalTitleBarAction->setChecked(false); + } else { + floatableAction->setChecked(features() & QDockWidget::DockWidgetFloatable); + floatingAction->setChecked(isWindow()); + // done after floating, to get 'floatable' correctly initialized + movableAction->setChecked(features() & QDockWidget::DockWidgetMovable); + verticalTitleBarAction + ->setChecked(features() & QDockWidget::DockWidgetVerticalTitleBar); + } + + allowLeftAction->setChecked(isAreaAllowed(Qt::LeftDockWidgetArea)); + allowRightAction->setChecked(isAreaAllowed(Qt::RightDockWidgetArea)); + allowTopAction->setChecked(isAreaAllowed(Qt::TopDockWidgetArea)); + allowBottomAction->setChecked(isAreaAllowed(Qt::BottomDockWidgetArea)); + + if (allowedAreasActions->isEnabled()) { + allowLeftAction->setEnabled(area != Qt::LeftDockWidgetArea); + allowRightAction->setEnabled(area != Qt::RightDockWidgetArea); + allowTopAction->setEnabled(area != Qt::TopDockWidgetArea); + allowBottomAction->setEnabled(area != Qt::BottomDockWidgetArea); + } + + leftAction->blockSignals(true); + rightAction->blockSignals(true); + topAction->blockSignals(true); + bottomAction->blockSignals(true); + + leftAction->setChecked(area == Qt::LeftDockWidgetArea); + rightAction->setChecked(area == Qt::RightDockWidgetArea); + topAction->setChecked(area == Qt::TopDockWidgetArea); + bottomAction->setChecked(area == Qt::BottomDockWidgetArea); + + leftAction->blockSignals(false); + rightAction->blockSignals(false); + topAction->blockSignals(false); + bottomAction->blockSignals(false); + + if (areaActions->isEnabled()) { + leftAction->setEnabled(areas & Qt::LeftDockWidgetArea); + rightAction->setEnabled(areas & Qt::RightDockWidgetArea); + topAction->setEnabled(areas & Qt::TopDockWidgetArea); + bottomAction->setEnabled(areas & Qt::BottomDockWidgetArea); + } + + tabMenu->clear(); + splitHMenu->clear(); + splitVMenu->clear(); + QList dock_list = mainWindow->findChildren(); + foreach (ColorSwatch *dock, dock_list) { +// if (!dock->isVisible() || dock->isFloating()) +// continue; + tabMenu->addAction(dock->objectName()); + splitHMenu->addAction(dock->objectName()); + splitVMenu->addAction(dock->objectName()); + } +} + +void ColorSwatch::splitInto(QAction *action) +{ + QMainWindow *mainWindow = qobject_cast(parentWidget()); + QList dock_list = mainWindow->findChildren(); + ColorSwatch *target = 0; + foreach (ColorSwatch *dock, dock_list) { + if (action->text() == dock->objectName()) { + target = dock; + break; + } + } + if (target == 0) + return; + + Qt::Orientation o = action->parent() == splitHMenu + ? Qt::Horizontal : Qt::Vertical; + mainWindow->splitDockWidget(target, this, o); +} + +void ColorSwatch::tabInto(QAction *action) +{ + QMainWindow *mainWindow = qobject_cast(parentWidget()); + QList dock_list = mainWindow->findChildren(); + ColorSwatch *target = 0; + foreach (ColorSwatch *dock, dock_list) { + if (action->text() == dock->objectName()) { + target = dock; + break; + } + } + if (target == 0) + return; + + mainWindow->tabifyDockWidget(target, this); +} + +void ColorSwatch::contextMenuEvent(QContextMenuEvent *event) +{ + event->accept(); + menu->exec(event->globalPos()); +} + +void ColorSwatch::resizeEvent(QResizeEvent *e) +{ + if (BlueTitleBar *btb = qobject_cast(titleBarWidget())) + btb->updateMask(); + + QDockWidget::resizeEvent(e); +} + + +void ColorSwatch::allow(Qt::DockWidgetArea area, bool a) +{ + Qt::DockWidgetAreas areas = allowedAreas(); + areas = a ? areas | area : areas & ~area; + setAllowedAreas(areas); + + if (areaActions->isEnabled()) { + leftAction->setEnabled(areas & Qt::LeftDockWidgetArea); + rightAction->setEnabled(areas & Qt::RightDockWidgetArea); + topAction->setEnabled(areas & Qt::TopDockWidgetArea); + bottomAction->setEnabled(areas & Qt::BottomDockWidgetArea); + } +} + +void ColorSwatch::place(Qt::DockWidgetArea area, bool p) +{ + if (!p) return; + + QMainWindow *mainWindow = qobject_cast(parentWidget()); + mainWindow->addDockWidget(area, this); + + if (allowedAreasActions->isEnabled()) { + allowLeftAction->setEnabled(area != Qt::LeftDockWidgetArea); + allowRightAction->setEnabled(area != Qt::RightDockWidgetArea); + allowTopAction->setEnabled(area != Qt::TopDockWidgetArea); + allowBottomAction->setEnabled(area != Qt::BottomDockWidgetArea); + } +} + +void ColorSwatch::setCustomSizeHint(const QSize &size) +{ + if (ColorDock *dock = qobject_cast(widget())) + dock->setCustomSizeHint(size); +} + +void ColorSwatch::changeClosable(bool on) +{ setFeatures(on ? features() | DockWidgetClosable : features() & ~DockWidgetClosable); } + +void ColorSwatch::changeMovable(bool on) +{ setFeatures(on ? features() | DockWidgetMovable : features() & ~DockWidgetMovable); } + +void ColorSwatch::changeFloatable(bool on) +{ setFeatures(on ? features() | DockWidgetFloatable : features() & ~DockWidgetFloatable); } + +void ColorSwatch::changeFloating(bool floating) +{ setFloating(floating); } + +void ColorSwatch::allowLeft(bool a) +{ allow(Qt::LeftDockWidgetArea, a); } + +void ColorSwatch::allowRight(bool a) +{ allow(Qt::RightDockWidgetArea, a); } + +void ColorSwatch::allowTop(bool a) +{ allow(Qt::TopDockWidgetArea, a); } + +void ColorSwatch::allowBottom(bool a) +{ allow(Qt::BottomDockWidgetArea, a); } + +void ColorSwatch::placeLeft(bool p) +{ place(Qt::LeftDockWidgetArea, p); } + +void ColorSwatch::placeRight(bool p) +{ place(Qt::RightDockWidgetArea, p); } + +void ColorSwatch::placeTop(bool p) +{ place(Qt::TopDockWidgetArea, p); } + +void ColorSwatch::placeBottom(bool p) +{ place(Qt::BottomDockWidgetArea, p); } + +void ColorSwatch::changeVerticalTitleBar(bool on) +{ + setFeatures(on ? features() | DockWidgetVerticalTitleBar + : features() & ~DockWidgetVerticalTitleBar); +} + +QSize BlueTitleBar::minimumSizeHint() const +{ + QDockWidget *dw = qobject_cast(parentWidget()); + Q_ASSERT(dw != 0); + QSize result(leftPm.width() + rightPm.width(), centerPm.height()); + if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) + result.transpose(); + return result; +} + +BlueTitleBar::BlueTitleBar(QWidget *parent) + : QWidget(parent) +{ + leftPm = QPixmap(":/res/titlebarLeft.png"); + centerPm = QPixmap(":/res/titlebarCenter.png"); + rightPm = QPixmap(":/res/titlebarRight.png"); +} + +void BlueTitleBar::paintEvent(QPaintEvent*) +{ + QPainter painter(this); + QRect rect = this->rect(); + + QDockWidget *dw = qobject_cast(parentWidget()); + Q_ASSERT(dw != 0); + + if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) { + QSize s = rect.size(); + s.transpose(); + rect.setSize(s); + + painter.translate(rect.left(), rect.top() + rect.width()); + painter.rotate(-90); + painter.translate(-rect.left(), -rect.top()); + } + + painter.drawPixmap(rect.topLeft(), leftPm); + painter.drawPixmap(rect.topRight() - QPoint(rightPm.width() - 1, 0), rightPm); + QBrush brush(centerPm); + painter.fillRect(rect.left() + leftPm.width(), rect.top(), + rect.width() - leftPm.width() - rightPm.width(), + centerPm.height(), centerPm); +} + +void BlueTitleBar::mousePressEvent(QMouseEvent *event) +{ + QPoint pos = event->pos(); + + QRect rect = this->rect(); + + QDockWidget *dw = qobject_cast(parentWidget()); + Q_ASSERT(dw != 0); + + if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) { + QPoint p = pos; + pos.setX(rect.left() + rect.bottom() - p.y()); + pos.setY(rect.top() + p.x() - rect.left()); + + QSize s = rect.size(); + s.transpose(); + rect.setSize(s); + } + + const int buttonRight = 7; + const int buttonWidth = 20; + int right = rect.right() - pos.x(); + int button = (right - buttonRight)/buttonWidth; + switch (button) { + case 0: + event->accept(); + dw->close(); + break; + case 1: + event->accept(); + dw->setFloating(!dw->isFloating()); + break; + case 2: { + event->accept(); + QDockWidget::DockWidgetFeatures features = dw->features(); + if (features & QDockWidget::DockWidgetVerticalTitleBar) + features &= ~QDockWidget::DockWidgetVerticalTitleBar; + else + features |= QDockWidget::DockWidgetVerticalTitleBar; + dw->setFeatures(features); + break; + } + default: + event->ignore(); + break; + } +} + +void BlueTitleBar::updateMask() +{ + QDockWidget *dw = qobject_cast(parent()); + Q_ASSERT(dw != 0); + + QRect rect = dw->rect(); + QPixmap bitmap(dw->size()); + + { + QPainter painter(&bitmap); + + ///initialize to transparent + painter.fillRect(rect, Qt::color0); + + QRect contents = rect; + contents.setTopLeft(geometry().bottomLeft()); + contents.setRight(geometry().right()); + contents.setBottom(contents.bottom()-y()); + painter.fillRect(contents, Qt::color1); + + + + //let's pait the titlebar + + QRect titleRect = this->geometry(); + + if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) { + QSize s = rect.size(); + s.transpose(); + rect.setSize(s); + + QSize s2 = size(); + s2.transpose(); + titleRect.setSize(s2); + + painter.translate(rect.left(), rect.top() + rect.width()); + painter.rotate(-90); + painter.translate(-rect.left(), -rect.top()); + } + + contents.setTopLeft(titleRect.bottomLeft()); + contents.setRight(titleRect.right()); + contents.setBottom(rect.bottom()-y()); + + QRect rect = titleRect; + + + painter.drawPixmap(rect.topLeft(), leftPm.mask()); + painter.fillRect(rect.left() + leftPm.width(), rect.top(), + rect.width() - leftPm.width() - rightPm.width(), + centerPm.height(), Qt::color1); + painter.drawPixmap(rect.topRight() - QPoint(rightPm.width() - 1, 0), rightPm.mask()); + + painter.fillRect(contents, Qt::color1); + } + + dw->setMask(bitmap); +} + +#include "colorswatch.moc" diff --git a/examples/mainwindows/mainwindow/colorswatch.h b/examples/mainwindows/mainwindow/colorswatch.h new file mode 100644 index 0000000000..555f1c6cd4 --- /dev/null +++ b/examples/mainwindows/mainwindow/colorswatch.h @@ -0,0 +1,136 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef COLORSWATCH_H +#define COLORSWATCH_H + +#include + +QT_FORWARD_DECLARE_CLASS(QAction) +QT_FORWARD_DECLARE_CLASS(QActionGroup) +QT_FORWARD_DECLARE_CLASS(QMenu) + +class ColorSwatch : public QDockWidget +{ + Q_OBJECT + + QAction *closableAction; + QAction *movableAction; + QAction *floatableAction; + QAction *floatingAction; + QAction *verticalTitleBarAction; + + QActionGroup *allowedAreasActions; + QAction *allowLeftAction; + QAction *allowRightAction; + QAction *allowTopAction; + QAction *allowBottomAction; + + QActionGroup *areaActions; + QAction *leftAction; + QAction *rightAction; + QAction *topAction; + QAction *bottomAction; + + QAction *changeSizeHintsAction; + + QMenu *tabMenu; + QMenu *splitHMenu; + QMenu *splitVMenu; + + QAction *windowModifiedAction; + +public: + ColorSwatch(const QString &colorName, QWidget *parent = 0, Qt::WindowFlags flags = 0); + + QMenu *menu; + void setCustomSizeHint(const QSize &size); + +protected: + virtual void contextMenuEvent(QContextMenuEvent *event); + virtual void resizeEvent(QResizeEvent *e); + +private: + void allow(Qt::DockWidgetArea area, bool allow); + void place(Qt::DockWidgetArea area, bool place); + +private slots: + void changeClosable(bool on); + void changeMovable(bool on); + void changeFloatable(bool on); + void changeFloating(bool on); + void changeVerticalTitleBar(bool on); + void updateContextMenu(); + + void allowLeft(bool a); + void allowRight(bool a); + void allowTop(bool a); + void allowBottom(bool a); + + void placeLeft(bool p); + void placeRight(bool p); + void placeTop(bool p); + void placeBottom(bool p); + + void splitInto(QAction *action); + void tabInto(QAction *action); +}; + +class BlueTitleBar : public QWidget +{ + Q_OBJECT +public: + BlueTitleBar(QWidget *parent = 0); + + QSize sizeHint() const { return minimumSizeHint(); } + QSize minimumSizeHint() const; +protected: + void paintEvent(QPaintEvent *event); + void mousePressEvent(QMouseEvent *event); +public slots: + void updateMask(); + +private: + QPixmap leftPm, centerPm, rightPm; +}; + + +#endif diff --git a/examples/mainwindows/mainwindow/main.cpp b/examples/mainwindows/mainwindow/main.cpp new file mode 100644 index 0000000000..71cff13cb8 --- /dev/null +++ b/examples/mainwindows/mainwindow/main.cpp @@ -0,0 +1,164 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mainwindow.h" + +#include +#include +#include +#include +#include + +void render_qt_text(QPainter *painter, int w, int h, const QColor &color) { + QPainterPath path; + path.moveTo(-0.083695, 0.283849); + path.cubicTo(-0.049581, 0.349613, -0.012720, 0.397969, 0.026886, 0.428917); + path.cubicTo(0.066493, 0.459865, 0.111593, 0.477595, 0.162186, 0.482108); + path.lineTo(0.162186, 0.500000); + path.cubicTo(0.115929, 0.498066, 0.066565, 0.487669, 0.014094, 0.468810); + path.cubicTo(-0.038378, 0.449952, -0.088103, 0.423839, -0.135082, 0.390474); + path.cubicTo(-0.182061, 0.357108, -0.222608, 0.321567, -0.256722, 0.283849); + path.cubicTo(-0.304712, 0.262250, -0.342874, 0.239362, -0.371206, 0.215184); + path.cubicTo(-0.411969, 0.179078, -0.443625, 0.134671, -0.466175, 0.081963); + path.cubicTo(-0.488725, 0.029255, -0.500000, -0.033043, -0.500000, -0.104932); + path.cubicTo(-0.500000, -0.218407, -0.467042, -0.312621, -0.401127, -0.387573); + path.cubicTo(-0.335212, -0.462524, -0.255421, -0.500000, -0.161752, -0.500000); + path.cubicTo(-0.072998, -0.500000, 0.003903, -0.462444, 0.068951, -0.387331); + path.cubicTo(0.133998, -0.312218, 0.166522, -0.217440, 0.166522, -0.102998); + path.cubicTo(0.166522, -0.010155, 0.143394, 0.071325, 0.097138, 0.141441); + path.cubicTo(0.050882, 0.211557, -0.009396, 0.259026, -0.083695, 0.283849); + path.moveTo(-0.167823, -0.456963); + path.cubicTo(-0.228823, -0.456963, -0.277826, -0.432624, -0.314831, -0.383946); + path.cubicTo(-0.361665, -0.323340, -0.385082, -0.230335, -0.385082, -0.104932); + path.cubicTo(-0.385082, 0.017569, -0.361376, 0.112025, -0.313964, 0.178433); + path.cubicTo(-0.277248, 0.229368, -0.228534, 0.254836, -0.167823, 0.254836); + path.cubicTo(-0.105088, 0.254836, -0.054496, 0.229368, -0.016045, 0.178433); + path.cubicTo(0.029055, 0.117827, 0.051605, 0.028691, 0.051605, -0.088975); + path.cubicTo(0.051605, -0.179562, 0.039318, -0.255803, 0.014744, -0.317698); + path.cubicTo(-0.004337, -0.365409, -0.029705, -0.400548, -0.061362, -0.423114); + path.cubicTo(-0.093018, -0.445680, -0.128505, -0.456963, -0.167823, -0.456963); + path.moveTo(0.379011, -0.404739); + path.lineTo(0.379011, -0.236460); + path.lineTo(0.486123, -0.236460); + path.lineTo(0.486123, -0.197292); + path.lineTo(0.379011, -0.197292); + path.lineTo(0.379011, 0.134913); + path.cubicTo(0.379011, 0.168117, 0.383276, 0.190442, 0.391804, 0.201886); + path.cubicTo(0.400332, 0.213330, 0.411246, 0.219052, 0.424545, 0.219052); + path.cubicTo(0.435531, 0.219052, 0.446227, 0.215264, 0.456635, 0.207689); + path.cubicTo(0.467042, 0.200113, 0.474993, 0.188910, 0.480486, 0.174081); + path.lineTo(0.500000, 0.174081); + path.cubicTo(0.488436, 0.210509, 0.471957, 0.237911, 0.450564, 0.256286); + path.cubicTo(0.429170, 0.274662, 0.407054, 0.283849, 0.384215, 0.283849); + path.cubicTo(0.368893, 0.283849, 0.353859, 0.279094, 0.339115, 0.269584); + path.cubicTo(0.324371, 0.260074, 0.313530, 0.246534, 0.306592, 0.228965); + path.cubicTo(0.299653, 0.211396, 0.296184, 0.184075, 0.296184, 0.147002); + path.lineTo(0.296184, -0.197292); + path.lineTo(0.223330, -0.197292); + path.lineTo(0.223330, -0.215667); + path.cubicTo(0.241833, -0.224049, 0.260697, -0.237992, 0.279922, -0.257495); + path.cubicTo(0.299147, -0.276999, 0.316276, -0.300129, 0.331310, -0.326886); + path.cubicTo(0.338826, -0.341070, 0.349523, -0.367021, 0.363400, -0.404739); + path.lineTo(0.379011, -0.404739); + path.moveTo(-0.535993, 0.275629); + + painter->translate(w / 2, h / 2); + double scale = qMin(w, h) * 8 / 10.0; + painter->scale(scale, scale); + + painter->setRenderHint(QPainter::Antialiasing); + + painter->save(); + painter->translate(.1, .1); + painter->fillPath(path, QColor(0, 0, 0, 63)); + painter->restore(); + + painter->setBrush(color); + painter->setPen(QPen(Qt::black, 0.02, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); + painter->drawPath(path); +} + +void usage() +{ + qWarning() << "Usage: mainwindow [-SizeHint x] ..."; + exit(1); +} + +QMap parseCustomSizeHints(int argc, char **argv) +{ + QMap result; + + for (int i = 1; i < argc; ++i) { + QString arg = QString::fromLocal8Bit(argv[i]); + + if (arg.startsWith(QLatin1String("-SizeHint"))) { + QString name = arg.mid(9); + if (name.isEmpty()) + usage(); + if (++i == argc) + usage(); + QString sizeStr = QString::fromLocal8Bit(argv[i]); + int idx = sizeStr.indexOf(QLatin1Char('x')); + if (idx == -1) + usage(); + bool ok; + int w = sizeStr.left(idx).toInt(&ok); + if (!ok) + usage(); + int h = sizeStr.mid(idx + 1).toInt(&ok); + if (!ok) + usage(); + result[name] = QSize(w, h); + } + } + + return result; +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + QMap customSizeHints = parseCustomSizeHints(argc, argv); + MainWindow mainWin(customSizeHints); + mainWin.resize(800, 600); + mainWin.show(); + return app.exec(); +} diff --git a/examples/mainwindows/mainwindow/mainwindow.cpp b/examples/mainwindows/mainwindow/mainwindow.cpp new file mode 100644 index 0000000000..a58a713c0b --- /dev/null +++ b/examples/mainwindows/mainwindow/mainwindow.cpp @@ -0,0 +1,514 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mainwindow.h" +#include "colorswatch.h" +#include "toolbar.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char * const message = + "

      Qt Main Window Demo

      " + + "

      This is a demonstration of the QMainWindow, QToolBar and " + "QDockWidget classes.

      " + + "

      The tool bar and dock widgets can be dragged around and rearranged " + "using the mouse or via the menu.

      " + + "

      Each dock widget contains a colored frame and a context " + "(right-click) menu.

      " + +#ifdef Q_WS_MAC + "

      On Mac OS X, the \"Black\" dock widget has been created as a " + "Drawer, which is a special kind of QDockWidget.

      " +#endif + ; + +Q_DECLARE_METATYPE(QDockWidget::DockWidgetFeatures) + +MainWindow::MainWindow(const QMap &customSizeHints, + QWidget *parent, Qt::WindowFlags flags) + : QMainWindow(parent, flags) +{ + setObjectName("MainWindow"); + setWindowTitle("Qt Main Window Demo"); + + center = new QTextEdit(this); + center->setReadOnly(true); + center->setMinimumSize(400, 205); + setCentralWidget(center); + + setupToolBar(); + setupMenuBar(); + setupDockWidgets(customSizeHints); + + statusBar()->showMessage(tr("Status Bar")); +} + +void MainWindow::actionTriggered(QAction *action) +{ + qDebug("action '%s' triggered", action->text().toLocal8Bit().data()); +} + +void MainWindow::setupToolBar() +{ + for (int i = 0; i < 3; ++i) { + ToolBar *tb = new ToolBar(QString::fromLatin1("Tool Bar %1").arg(i + 1), this); + toolBars.append(tb); + addToolBar(tb); + } +} + +void MainWindow::setupMenuBar() +{ + QMenu *menu = menuBar()->addMenu(tr("&File")); + + QAction *action = menu->addAction(tr("Save layout...")); + connect(action, SIGNAL(triggered()), this, SLOT(saveLayout())); + + action = menu->addAction(tr("Load layout...")); + connect(action, SIGNAL(triggered()), this, SLOT(loadLayout())); + + action = menu->addAction(tr("Switch layout direction")); + connect(action, SIGNAL(triggered()), this, SLOT(switchLayoutDirection())); + + menu->addSeparator(); + + menu->addAction(tr("&Quit"), this, SLOT(close())); + + mainWindowMenu = menuBar()->addMenu(tr("Main window")); + + action = mainWindowMenu->addAction(tr("Animated docks")); + action->setCheckable(true); + action->setChecked(dockOptions() & AnimatedDocks); + connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); + + action = mainWindowMenu->addAction(tr("Allow nested docks")); + action->setCheckable(true); + action->setChecked(dockOptions() & AllowNestedDocks); + connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); + + action = mainWindowMenu->addAction(tr("Allow tabbed docks")); + action->setCheckable(true); + action->setChecked(dockOptions() & AllowTabbedDocks); + connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); + + action = mainWindowMenu->addAction(tr("Force tabbed docks")); + action->setCheckable(true); + action->setChecked(dockOptions() & ForceTabbedDocks); + connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); + + action = mainWindowMenu->addAction(tr("Vertical tabs")); + action->setCheckable(true); + action->setChecked(dockOptions() & VerticalTabs); + connect(action, SIGNAL(toggled(bool)), this, SLOT(setDockOptions())); + + QMenu *toolBarMenu = menuBar()->addMenu(tr("Tool bars")); + for (int i = 0; i < toolBars.count(); ++i) + toolBarMenu->addMenu(toolBars.at(i)->menu); + + dockWidgetMenu = menuBar()->addMenu(tr("&Dock Widgets")); +} + +void MainWindow::setDockOptions() +{ + DockOptions opts; + QList actions = mainWindowMenu->actions(); + + if (actions.at(0)->isChecked()) + opts |= AnimatedDocks; + if (actions.at(1)->isChecked()) + opts |= AllowNestedDocks; + if (actions.at(2)->isChecked()) + opts |= AllowTabbedDocks; + if (actions.at(3)->isChecked()) + opts |= ForceTabbedDocks; + if (actions.at(4)->isChecked()) + opts |= VerticalTabs; + + QMainWindow::setDockOptions(opts); +} + +void MainWindow::saveLayout() +{ + QString fileName + = QFileDialog::getSaveFileName(this, tr("Save layout")); + if (fileName.isEmpty()) + return; + QFile file(fileName); + if (!file.open(QFile::WriteOnly)) { + QString msg = tr("Failed to open %1\n%2") + .arg(fileName) + .arg(file.errorString()); + QMessageBox::warning(this, tr("Error"), msg); + return; + } + + QByteArray geo_data = saveGeometry(); + QByteArray layout_data = saveState(); + + bool ok = file.putChar((uchar)geo_data.size()); + if (ok) + ok = file.write(geo_data) == geo_data.size(); + if (ok) + ok = file.write(layout_data) == layout_data.size(); + + if (!ok) { + QString msg = tr("Error writing to %1\n%2") + .arg(fileName) + .arg(file.errorString()); + QMessageBox::warning(this, tr("Error"), msg); + return; + } +} + +void MainWindow::loadLayout() +{ + QString fileName + = QFileDialog::getOpenFileName(this, tr("Load layout")); + if (fileName.isEmpty()) + return; + QFile file(fileName); + if (!file.open(QFile::ReadOnly)) { + QString msg = tr("Failed to open %1\n%2") + .arg(fileName) + .arg(file.errorString()); + QMessageBox::warning(this, tr("Error"), msg); + return; + } + + uchar geo_size; + QByteArray geo_data; + QByteArray layout_data; + + bool ok = file.getChar((char*)&geo_size); + if (ok) { + geo_data = file.read(geo_size); + ok = geo_data.size() == geo_size; + } + if (ok) { + layout_data = file.readAll(); + ok = layout_data.size() > 0; + } + + if (ok) + ok = restoreGeometry(geo_data); + if (ok) + ok = restoreState(layout_data); + + if (!ok) { + QString msg = tr("Error reading %1") + .arg(fileName); + QMessageBox::warning(this, tr("Error"), msg); + return; + } +} + +QAction *addAction(QMenu *menu, const QString &text, QActionGroup *group, QSignalMapper *mapper, + int id) +{ + bool first = group->actions().isEmpty(); + QAction *result = menu->addAction(text); + result->setCheckable(true); + result->setChecked(first); + group->addAction(result); + QObject::connect(result, SIGNAL(triggered()), mapper, SLOT(map())); + mapper->setMapping(result, id); + return result; +} + +void MainWindow::setupDockWidgets(const QMap &customSizeHints) +{ + qRegisterMetaType(); + + mapper = new QSignalMapper(this); + connect(mapper, SIGNAL(mapped(int)), this, SLOT(setCorner(int))); + + QMenu *corner_menu = dockWidgetMenu->addMenu(tr("Top left corner")); + QActionGroup *group = new QActionGroup(this); + group->setExclusive(true); + ::addAction(corner_menu, tr("Top dock area"), group, mapper, 0); + ::addAction(corner_menu, tr("Left dock area"), group, mapper, 1); + + corner_menu = dockWidgetMenu->addMenu(tr("Top right corner")); + group = new QActionGroup(this); + group->setExclusive(true); + ::addAction(corner_menu, tr("Top dock area"), group, mapper, 2); + ::addAction(corner_menu, tr("Right dock area"), group, mapper, 3); + + corner_menu = dockWidgetMenu->addMenu(tr("Bottom left corner")); + group = new QActionGroup(this); + group->setExclusive(true); + ::addAction(corner_menu, tr("Bottom dock area"), group, mapper, 4); + ::addAction(corner_menu, tr("Left dock area"), group, mapper, 5); + + corner_menu = dockWidgetMenu->addMenu(tr("Bottom right corner")); + group = new QActionGroup(this); + group->setExclusive(true); + ::addAction(corner_menu, tr("Bottom dock area"), group, mapper, 6); + ::addAction(corner_menu, tr("Right dock area"), group, mapper, 7); + + dockWidgetMenu->addSeparator(); + + static const struct Set { + const char * name; + uint flags; + Qt::DockWidgetArea area; + } sets [] = { +#ifndef Q_WS_MAC + { "Black", 0, Qt::LeftDockWidgetArea }, +#else + { "Black", Qt::Drawer, Qt::LeftDockWidgetArea }, +#endif + { "White", 0, Qt::RightDockWidgetArea }, + { "Red", 0, Qt::TopDockWidgetArea }, + { "Green", 0, Qt::TopDockWidgetArea }, + { "Blue", 0, Qt::BottomDockWidgetArea }, + { "Yellow", 0, Qt::BottomDockWidgetArea } + }; + const int setCount = sizeof(sets) / sizeof(Set); + + for (int i = 0; i < setCount; ++i) { + ColorSwatch *swatch = new ColorSwatch(tr(sets[i].name), this, Qt::WindowFlags(sets[i].flags)); + if (i%2) + swatch->setWindowIcon(QIcon(QPixmap(":/res/qt.png"))); + if (qstrcmp(sets[i].name, "Blue") == 0) { + BlueTitleBar *titlebar = new BlueTitleBar(swatch); + swatch->setTitleBarWidget(titlebar); + connect(swatch, SIGNAL(topLevelChanged(bool)), titlebar, SLOT(updateMask())); + connect(swatch, SIGNAL(featuresChanged(QDockWidget::DockWidgetFeatures)), titlebar, SLOT(updateMask()), Qt::QueuedConnection); + +#ifdef Q_WS_QWS + QPalette pal = palette(); + pal.setBrush(backgroundRole(), QColor(0,0,0,0)); + swatch->setPalette(pal); +#endif + } + + QString name = QString::fromLatin1(sets[i].name); + if (customSizeHints.contains(name)) + swatch->setCustomSizeHint(customSizeHints.value(name)); + + addDockWidget(sets[i].area, swatch); + dockWidgetMenu->addMenu(swatch->menu); + } + + createDockWidgetAction = new QAction(tr("Add dock widget..."), this); + connect(createDockWidgetAction, SIGNAL(triggered()), this, SLOT(createDockWidget())); + destroyDockWidgetMenu = new QMenu(tr("Destroy dock widget"), this); + destroyDockWidgetMenu->setEnabled(false); + connect(destroyDockWidgetMenu, SIGNAL(triggered(QAction*)), this, SLOT(destroyDockWidget(QAction*))); + + dockWidgetMenu->addSeparator(); + dockWidgetMenu->addAction(createDockWidgetAction); + dockWidgetMenu->addMenu(destroyDockWidgetMenu); +} + +void MainWindow::setCorner(int id) +{ + switch (id) { + case 0: + QMainWindow::setCorner(Qt::TopLeftCorner, Qt::TopDockWidgetArea); + break; + case 1: + QMainWindow::setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); + break; + case 2: + QMainWindow::setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea); + break; + case 3: + QMainWindow::setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); + break; + case 4: + QMainWindow::setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); + break; + case 5: + QMainWindow::setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); + break; + case 6: + QMainWindow::setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea); + break; + case 7: + QMainWindow::setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); + break; + } +} + +void MainWindow::showEvent(QShowEvent *event) +{ + QMainWindow::showEvent(event); +} + +void MainWindow::switchLayoutDirection() +{ + if (layoutDirection() == Qt::LeftToRight) + qApp->setLayoutDirection(Qt::RightToLeft); + else + qApp->setLayoutDirection(Qt::LeftToRight); +} + +class CreateDockWidgetDialog : public QDialog +{ +public: + CreateDockWidgetDialog(QWidget *parent = 0); + + QString objectName() const; + Qt::DockWidgetArea location() const; + +private: + QLineEdit *m_objectName; + QComboBox *m_location; +}; + +CreateDockWidgetDialog::CreateDockWidgetDialog(QWidget *parent) + : QDialog(parent) +{ + QGridLayout *layout = new QGridLayout(this); + + layout->addWidget(new QLabel(tr("Object name:")), 0, 0); + m_objectName = new QLineEdit; + layout->addWidget(m_objectName, 0, 1); + + layout->addWidget(new QLabel(tr("Location:")), 1, 0); + m_location = new QComboBox; + m_location->setEditable(false); + m_location->addItem(tr("Top")); + m_location->addItem(tr("Left")); + m_location->addItem(tr("Right")); + m_location->addItem(tr("Bottom")); + m_location->addItem(tr("Restore")); + layout->addWidget(m_location, 1, 1); + + QHBoxLayout *buttonLayout = new QHBoxLayout; + layout->addLayout(buttonLayout, 2, 0, 1, 2); + buttonLayout->addStretch(); + + QPushButton *cancelButton = new QPushButton(tr("Cancel")); + connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); + buttonLayout->addWidget(cancelButton); + QPushButton *okButton = new QPushButton(tr("Ok")); + connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); + buttonLayout->addWidget(okButton); + + okButton->setDefault(true); +} + +QString CreateDockWidgetDialog::objectName() const +{ + return m_objectName->text(); +} + +Qt::DockWidgetArea CreateDockWidgetDialog::location() const +{ + switch (m_location->currentIndex()) { + case 0: return Qt::TopDockWidgetArea; + case 1: return Qt::LeftDockWidgetArea; + case 2: return Qt::RightDockWidgetArea; + case 3: return Qt::BottomDockWidgetArea; + default: + break; + } + return Qt::NoDockWidgetArea; +} + +void MainWindow::createDockWidget() +{ + CreateDockWidgetDialog dialog(this); + int ret = dialog.exec(); + if (ret == QDialog::Rejected) + return; + + QDockWidget *dw = new QDockWidget; + dw->setObjectName(dialog.objectName()); + dw->setWindowTitle(dialog.objectName()); + dw->setWidget(new QTextEdit); + + Qt::DockWidgetArea area = dialog.location(); + switch (area) { + case Qt::LeftDockWidgetArea: + case Qt::RightDockWidgetArea: + case Qt::TopDockWidgetArea: + case Qt::BottomDockWidgetArea: + addDockWidget(area, dw); + break; + default: + if (!restoreDockWidget(dw)) { + QMessageBox::warning(this, QString(), tr("Failed to restore dock widget")); + delete dw; + return; + } + break; + } + + extraDockWidgets.append(dw); + destroyDockWidgetMenu->setEnabled(true); + destroyDockWidgetMenu->addAction(new QAction(dialog.objectName(), this)); +} + +void MainWindow::destroyDockWidget(QAction *action) +{ + int index = destroyDockWidgetMenu->actions().indexOf(action); + delete extraDockWidgets.takeAt(index); + destroyDockWidgetMenu->removeAction(action); + action->deleteLater(); + + if (destroyDockWidgetMenu->isEmpty()) + destroyDockWidgetMenu->setEnabled(false); +} diff --git a/examples/mainwindows/mainwindow/mainwindow.h b/examples/mainwindows/mainwindow/mainwindow.h new file mode 100644 index 0000000000..aa01ffa131 --- /dev/null +++ b/examples/mainwindows/mainwindow/mainwindow.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include + +class ToolBar; +QT_FORWARD_DECLARE_CLASS(QMenu) +QT_FORWARD_DECLARE_CLASS(QSignalMapper) + +class MainWindow : public QMainWindow +{ + Q_OBJECT + + QTextEdit *center; + QList toolBars; + QMenu *dockWidgetMenu; + QMenu *mainWindowMenu; + QSignalMapper *mapper; + QList extraDockWidgets; + QAction *createDockWidgetAction; + QMenu *destroyDockWidgetMenu; + +public: + MainWindow(const QMap &customSizeHints, + QWidget *parent = 0, Qt::WindowFlags flags = 0); + +protected: + void showEvent(QShowEvent *event); + +public slots: + void actionTriggered(QAction *action); + void saveLayout(); + void loadLayout(); + void setCorner(int id); + void switchLayoutDirection(); + void setDockOptions(); + + void createDockWidget(); + void destroyDockWidget(QAction *action); + +private: + void setupToolBar(); + void setupMenuBar(); + void setupDockWidgets(const QMap &customSizeHints); +}; + + +#endif diff --git a/examples/mainwindows/mainwindow/mainwindow.pro b/examples/mainwindows/mainwindow/mainwindow.pro new file mode 100644 index 0000000000..6da113d722 --- /dev/null +++ b/examples/mainwindows/mainwindow/mainwindow.pro @@ -0,0 +1,17 @@ +TEMPLATE = app +HEADERS += colorswatch.h mainwindow.h toolbar.h +SOURCES += colorswatch.cpp mainwindow.cpp toolbar.cpp main.cpp +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +RESOURCES += mainwindow.qrc + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/mainwindow +sources.files = $$SOURCES $$HEADERS $$FORMS $$RESOURCES *.png *.jpg *.pro +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/mainwindow +INSTALLS += target sources + +symbian: CONFIG += qt_demo diff --git a/examples/mainwindows/mainwindow/mainwindow.qrc b/examples/mainwindows/mainwindow/mainwindow.qrc new file mode 100644 index 0000000000..47ff22a3e4 --- /dev/null +++ b/examples/mainwindows/mainwindow/mainwindow.qrc @@ -0,0 +1,8 @@ + + + qt.png + titlebarLeft.png + titlebarCenter.png + titlebarRight.png + + diff --git a/examples/mainwindows/mainwindow/qt.png b/examples/mainwindows/mainwindow/qt.png new file mode 100644 index 0000000000..48fa9fc2ef Binary files /dev/null and b/examples/mainwindows/mainwindow/qt.png differ diff --git a/examples/mainwindows/mainwindow/titlebarCenter.png b/examples/mainwindows/mainwindow/titlebarCenter.png new file mode 100644 index 0000000000..5cc141355c Binary files /dev/null and b/examples/mainwindows/mainwindow/titlebarCenter.png differ diff --git a/examples/mainwindows/mainwindow/titlebarLeft.png b/examples/mainwindows/mainwindow/titlebarLeft.png new file mode 100644 index 0000000000..315166202b Binary files /dev/null and b/examples/mainwindows/mainwindow/titlebarLeft.png differ diff --git a/examples/mainwindows/mainwindow/titlebarRight.png b/examples/mainwindows/mainwindow/titlebarRight.png new file mode 100644 index 0000000000..a4505268ec Binary files /dev/null and b/examples/mainwindows/mainwindow/titlebarRight.png differ diff --git a/examples/mainwindows/mainwindow/toolbar.cpp b/examples/mainwindows/mainwindow/toolbar.cpp new file mode 100644 index 0000000000..1176ee5480 --- /dev/null +++ b/examples/mainwindows/mainwindow/toolbar.cpp @@ -0,0 +1,383 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "toolbar.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +static QPixmap genIcon(const QSize &iconSize, const QString &, const QColor &color) +{ + int w = iconSize.width(); + int h = iconSize.height(); + + QImage image(w, h, QImage::Format_ARGB32_Premultiplied); + image.fill(0); + + QPainter p(&image); + + extern void render_qt_text(QPainter *, int, int, const QColor &); + render_qt_text(&p, w, h, color); + + return QPixmap::fromImage(image, Qt::DiffuseDither | Qt::DiffuseAlphaDither); +} + +static QPixmap genIcon(const QSize &iconSize, int number, const QColor &color) +{ return genIcon(iconSize, QString::number(number), color); } + +ToolBar::ToolBar(const QString &title, QWidget *parent) + : QToolBar(parent), spinbox(0), spinboxAction(0) +{ + tip = 0; + setWindowTitle(title); + setObjectName(title); + + setIconSize(QSize(32, 32)); + + QColor bg(palette().background().color()); + menu = new QMenu("One", this); + menu->setIcon(genIcon(iconSize(), 1, Qt::black)); + menu->addAction(genIcon(iconSize(), "A", Qt::blue), "A"); + menu->addAction(genIcon(iconSize(), "B", Qt::blue), "B"); + menu->addAction(genIcon(iconSize(), "C", Qt::blue), "C"); + addAction(menu->menuAction()); + + QAction *two = addAction(genIcon(iconSize(), 2, Qt::white), "Two"); + QFont boldFont; + boldFont.setBold(true); + two->setFont(boldFont); + + addAction(genIcon(iconSize(), 3, Qt::red), "Three"); + addAction(genIcon(iconSize(), 4, Qt::green), "Four"); + addAction(genIcon(iconSize(), 5, Qt::blue), "Five"); + addAction(genIcon(iconSize(), 6, Qt::yellow), "Six"); + orderAction = new QAction(this); + orderAction->setText(tr("Order Items in Tool Bar")); + connect(orderAction, SIGNAL(triggered()), SLOT(order())); + + randomizeAction = new QAction(this); + randomizeAction->setText(tr("Randomize Items in Tool Bar")); + connect(randomizeAction, SIGNAL(triggered()), SLOT(randomize())); + + addSpinBoxAction = new QAction(this); + addSpinBoxAction->setText(tr("Add Spin Box")); + connect(addSpinBoxAction, SIGNAL(triggered()), SLOT(addSpinBox())); + + removeSpinBoxAction = new QAction(this); + removeSpinBoxAction->setText(tr("Remove Spin Box")); + removeSpinBoxAction->setEnabled(false); + connect(removeSpinBoxAction, SIGNAL(triggered()), SLOT(removeSpinBox())); + + movableAction = new QAction(tr("Movable"), this); + movableAction->setCheckable(true); + connect(movableAction, SIGNAL(triggered(bool)), SLOT(changeMovable(bool))); + + allowedAreasActions = new QActionGroup(this); + allowedAreasActions->setExclusive(false); + + allowLeftAction = new QAction(tr("Allow on Left"), this); + allowLeftAction->setCheckable(true); + connect(allowLeftAction, SIGNAL(triggered(bool)), SLOT(allowLeft(bool))); + + allowRightAction = new QAction(tr("Allow on Right"), this); + allowRightAction->setCheckable(true); + connect(allowRightAction, SIGNAL(triggered(bool)), SLOT(allowRight(bool))); + + allowTopAction = new QAction(tr("Allow on Top"), this); + allowTopAction->setCheckable(true); + connect(allowTopAction, SIGNAL(triggered(bool)), SLOT(allowTop(bool))); + + allowBottomAction = new QAction(tr("Allow on Bottom"), this); + allowBottomAction->setCheckable(true); + connect(allowBottomAction, SIGNAL(triggered(bool)), SLOT(allowBottom(bool))); + + allowedAreasActions->addAction(allowLeftAction); + allowedAreasActions->addAction(allowRightAction); + allowedAreasActions->addAction(allowTopAction); + allowedAreasActions->addAction(allowBottomAction); + + areaActions = new QActionGroup(this); + areaActions->setExclusive(true); + + leftAction = new QAction(tr("Place on Left") , this); + leftAction->setCheckable(true); + connect(leftAction, SIGNAL(triggered(bool)), SLOT(placeLeft(bool))); + + rightAction = new QAction(tr("Place on Right") , this); + rightAction->setCheckable(true); + connect(rightAction, SIGNAL(triggered(bool)), SLOT(placeRight(bool))); + + topAction = new QAction(tr("Place on Top") , this); + topAction->setCheckable(true); + connect(topAction, SIGNAL(triggered(bool)), SLOT(placeTop(bool))); + + bottomAction = new QAction(tr("Place on Bottom") , this); + bottomAction->setCheckable(true); + connect(bottomAction, SIGNAL(triggered(bool)), SLOT(placeBottom(bool))); + + areaActions->addAction(leftAction); + areaActions->addAction(rightAction); + areaActions->addAction(topAction); + areaActions->addAction(bottomAction); + + toolBarBreakAction = new QAction(tr("Insert break"), this); + connect(toolBarBreakAction, SIGNAL(triggered(bool)), this, SLOT(insertToolBarBreak())); + + connect(movableAction, SIGNAL(triggered(bool)), areaActions, SLOT(setEnabled(bool))); + + connect(movableAction, SIGNAL(triggered(bool)), allowedAreasActions, SLOT(setEnabled(bool))); + + menu = new QMenu(title, this); + menu->addAction(toggleViewAction()); + menu->addSeparator(); + menu->addAction(orderAction); + menu->addAction(randomizeAction); + menu->addSeparator(); + menu->addAction(addSpinBoxAction); + menu->addAction(removeSpinBoxAction); + menu->addSeparator(); + menu->addAction(movableAction); + menu->addSeparator(); + menu->addActions(allowedAreasActions->actions()); + menu->addSeparator(); + menu->addActions(areaActions->actions()); + menu->addSeparator(); + menu->addAction(toolBarBreakAction); + + connect(menu, SIGNAL(aboutToShow()), this, SLOT(updateMenu())); + + randomize(); +} + +void ToolBar::updateMenu() +{ + QMainWindow *mainWindow = qobject_cast(parentWidget()); + Q_ASSERT(mainWindow != 0); + + const Qt::ToolBarArea area = mainWindow->toolBarArea(this); + const Qt::ToolBarAreas areas = allowedAreas(); + + movableAction->setChecked(isMovable()); + + allowLeftAction->setChecked(isAreaAllowed(Qt::LeftToolBarArea)); + allowRightAction->setChecked(isAreaAllowed(Qt::RightToolBarArea)); + allowTopAction->setChecked(isAreaAllowed(Qt::TopToolBarArea)); + allowBottomAction->setChecked(isAreaAllowed(Qt::BottomToolBarArea)); + + if (allowedAreasActions->isEnabled()) { + allowLeftAction->setEnabled(area != Qt::LeftToolBarArea); + allowRightAction->setEnabled(area != Qt::RightToolBarArea); + allowTopAction->setEnabled(area != Qt::TopToolBarArea); + allowBottomAction->setEnabled(area != Qt::BottomToolBarArea); + } + + leftAction->setChecked(area == Qt::LeftToolBarArea); + rightAction->setChecked(area == Qt::RightToolBarArea); + topAction->setChecked(area == Qt::TopToolBarArea); + bottomAction->setChecked(area == Qt::BottomToolBarArea); + + if (areaActions->isEnabled()) { + leftAction->setEnabled(areas & Qt::LeftToolBarArea); + rightAction->setEnabled(areas & Qt::RightToolBarArea); + topAction->setEnabled(areas & Qt::TopToolBarArea); + bottomAction->setEnabled(areas & Qt::BottomToolBarArea); + } +} + +void ToolBar::order() +{ + QList ordered, actions1 = actions(), + actions2 = findChildren(); + while (!actions2.isEmpty()) { + QAction *action = actions2.takeFirst(); + if (!actions1.contains(action)) + continue; + actions1.removeAll(action); + ordered.append(action); + } + + clear(); + addActions(ordered); + + orderAction->setEnabled(false); +} + +void ToolBar::randomize() +{ + QList randomized, actions = this->actions(); + while (!actions.isEmpty()) { + QAction *action = actions.takeAt(rand() % actions.size()); + randomized.append(action); + } + clear(); + addActions(randomized); + + orderAction->setEnabled(true); +} + +void ToolBar::addSpinBox() +{ + if (!spinbox) { + spinbox = new QSpinBox(this); + } + if (!spinboxAction) + spinboxAction = addWidget(spinbox); + else + addAction(spinboxAction); + + addSpinBoxAction->setEnabled(false); + removeSpinBoxAction->setEnabled(true); +} + +void ToolBar::removeSpinBox() +{ + if (spinboxAction) + removeAction(spinboxAction); + + addSpinBoxAction->setEnabled(true); + removeSpinBoxAction->setEnabled(false); +} + +void ToolBar::allow(Qt::ToolBarArea area, bool a) +{ + Qt::ToolBarAreas areas = allowedAreas(); + areas = a ? areas | area : areas & ~area; + setAllowedAreas(areas); + + if (areaActions->isEnabled()) { + leftAction->setEnabled(areas & Qt::LeftToolBarArea); + rightAction->setEnabled(areas & Qt::RightToolBarArea); + topAction->setEnabled(areas & Qt::TopToolBarArea); + bottomAction->setEnabled(areas & Qt::BottomToolBarArea); + } +} + +void ToolBar::place(Qt::ToolBarArea area, bool p) +{ + if (!p) + return; + + QMainWindow *mainWindow = qobject_cast(parentWidget()); + Q_ASSERT(mainWindow != 0); + + mainWindow->addToolBar(area, this); + + if (allowedAreasActions->isEnabled()) { + allowLeftAction->setEnabled(area != Qt::LeftToolBarArea); + allowRightAction->setEnabled(area != Qt::RightToolBarArea); + allowTopAction->setEnabled(area != Qt::TopToolBarArea); + allowBottomAction->setEnabled(area != Qt::BottomToolBarArea); + } +} + +void ToolBar::changeMovable(bool movable) +{ setMovable(movable); } + +void ToolBar::allowLeft(bool a) +{ allow(Qt::LeftToolBarArea, a); } + +void ToolBar::allowRight(bool a) +{ allow(Qt::RightToolBarArea, a); } + +void ToolBar::allowTop(bool a) +{ allow(Qt::TopToolBarArea, a); } + +void ToolBar::allowBottom(bool a) +{ allow(Qt::BottomToolBarArea, a); } + +void ToolBar::placeLeft(bool p) +{ place(Qt::LeftToolBarArea, p); } + +void ToolBar::placeRight(bool p) +{ place(Qt::RightToolBarArea, p); } + +void ToolBar::placeTop(bool p) +{ place(Qt::TopToolBarArea, p); } + +void ToolBar::placeBottom(bool p) +{ place(Qt::BottomToolBarArea, p); } + +void ToolBar::insertToolBarBreak() +{ + QMainWindow *mainWindow = qobject_cast(parentWidget()); + Q_ASSERT(mainWindow != 0); + + mainWindow->insertToolBarBreak(this); +} + +void ToolBar::enterEvent(QEvent*) +{ +/* + These labels on top of toolbars look darn ugly + + if (tip == 0) { + tip = new QLabel(windowTitle(), this); + QPalette pal = tip->palette(); + QColor c = Qt::black; + c.setAlpha(100); + pal.setColor(QPalette::Window, c); + pal.setColor(QPalette::Foreground, Qt::white); + tip->setPalette(pal); + tip->setAutoFillBackground(true); + tip->setMargin(3); + tip->setText(windowTitle()); + } + QPoint c = rect().center(); + QSize hint = tip->sizeHint(); + tip->setGeometry(c.x() - hint.width()/2, c.y() - hint.height()/2, + hint.width(), hint.height()); + + tip->show(); +*/ +} + +void ToolBar::leaveEvent(QEvent*) +{ + if (tip != 0) + tip->hide(); +} diff --git a/examples/mainwindows/mainwindow/toolbar.h b/examples/mainwindows/mainwindow/toolbar.h new file mode 100644 index 0000000000..5b982ee73b --- /dev/null +++ b/examples/mainwindows/mainwindow/toolbar.h @@ -0,0 +1,118 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TOOLBAR_H +#define TOOLBAR_H + +#include + +QT_FORWARD_DECLARE_CLASS(QAction) +QT_FORWARD_DECLARE_CLASS(QActionGroup) +QT_FORWARD_DECLARE_CLASS(QMenu) +QT_FORWARD_DECLARE_CLASS(QSpinBox) +QT_FORWARD_DECLARE_CLASS(QLabel) + +class ToolBar : public QToolBar +{ + Q_OBJECT + + QSpinBox *spinbox; + QAction *spinboxAction; + + QAction *orderAction; + QAction *randomizeAction; + QAction *addSpinBoxAction; + QAction *removeSpinBoxAction; + + QAction *movableAction; + + QActionGroup *allowedAreasActions; + QAction *allowLeftAction; + QAction *allowRightAction; + QAction *allowTopAction; + QAction *allowBottomAction; + + QActionGroup *areaActions; + QAction *leftAction; + QAction *rightAction; + QAction *topAction; + QAction *bottomAction; + + QAction *toolBarBreakAction; + +public: + ToolBar(const QString &title, QWidget *parent); + + QMenu *menu; + +protected: + void enterEvent(QEvent*); + void leaveEvent(QEvent*); + +private: + void allow(Qt::ToolBarArea area, bool allow); + void place(Qt::ToolBarArea area, bool place); + QLabel *tip; + +private slots: + void order(); + void randomize(); + void addSpinBox(); + void removeSpinBox(); + + void changeMovable(bool movable); + + void allowLeft(bool a); + void allowRight(bool a); + void allowTop(bool a); + void allowBottom(bool a); + + void placeLeft(bool p); + void placeRight(bool p); + void placeTop(bool p); + void placeBottom(bool p); + + void updateMenu(); + void insertToolBarBreak(); + +}; + +#endif diff --git a/examples/painting/composition/composition.cpp b/examples/painting/composition/composition.cpp new file mode 100644 index 0000000000..b3f810b26c --- /dev/null +++ b/examples/painting/composition/composition.cpp @@ -0,0 +1,544 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "composition.h" +#include +#include +#include +#include +#include +#include +#include + +const int animationInterval = 15; // update every 16 ms = ~60FPS + +CompositionWidget::CompositionWidget(QWidget *parent) + : QWidget(parent) +{ + CompositionRenderer *view = new CompositionRenderer(this); + + QGroupBox *mainGroup = new QGroupBox(parent); + mainGroup->setTitle(tr("Composition Modes")); + + QGroupBox *modesGroup = new QGroupBox(mainGroup); + modesGroup->setTitle(tr("Mode")); + + rbClear = new QRadioButton(tr("Clear"), modesGroup); + connect(rbClear, SIGNAL(clicked()), view, SLOT(setClearMode())); + rbSource = new QRadioButton(tr("Source"), modesGroup); + connect(rbSource, SIGNAL(clicked()), view, SLOT(setSourceMode())); + rbDest = new QRadioButton(tr("Destination"), modesGroup); + connect(rbDest, SIGNAL(clicked()), view, SLOT(setDestMode())); + rbSourceOver = new QRadioButton(tr("Source Over"), modesGroup); + connect(rbSourceOver, SIGNAL(clicked()), view, SLOT(setSourceOverMode())); + rbDestOver = new QRadioButton(tr("Destination Over"), modesGroup); + connect(rbDestOver, SIGNAL(clicked()), view, SLOT(setDestOverMode())); + rbSourceIn = new QRadioButton(tr("Source In"), modesGroup); + connect(rbSourceIn, SIGNAL(clicked()), view, SLOT(setSourceInMode())); + rbDestIn = new QRadioButton(tr("Dest In"), modesGroup); + connect(rbDestIn, SIGNAL(clicked()), view, SLOT(setDestInMode())); + rbSourceOut = new QRadioButton(tr("Source Out"), modesGroup); + connect(rbSourceOut, SIGNAL(clicked()), view, SLOT(setSourceOutMode())); + rbDestOut = new QRadioButton(tr("Dest Out"), modesGroup); + connect(rbDestOut, SIGNAL(clicked()), view, SLOT(setDestOutMode())); + rbSourceAtop = new QRadioButton(tr("Source Atop"), modesGroup); + connect(rbSourceAtop, SIGNAL(clicked()), view, SLOT(setSourceAtopMode())); + rbDestAtop = new QRadioButton(tr("Dest Atop"), modesGroup); + connect(rbDestAtop, SIGNAL(clicked()), view, SLOT(setDestAtopMode())); + rbXor = new QRadioButton(tr("Xor"), modesGroup); + connect(rbXor, SIGNAL(clicked()), view, SLOT(setXorMode())); + + rbPlus = new QRadioButton(tr("Plus"), modesGroup); + connect(rbPlus, SIGNAL(clicked()), view, SLOT(setPlusMode())); + rbMultiply = new QRadioButton(tr("Multiply"), modesGroup); + connect(rbMultiply, SIGNAL(clicked()), view, SLOT(setMultiplyMode())); + rbScreen = new QRadioButton(tr("Screen"), modesGroup); + connect(rbScreen, SIGNAL(clicked()), view, SLOT(setScreenMode())); + rbOverlay = new QRadioButton(tr("Overlay"), modesGroup); + connect(rbOverlay, SIGNAL(clicked()), view, SLOT(setOverlayMode())); + rbDarken = new QRadioButton(tr("Darken"), modesGroup); + connect(rbDarken, SIGNAL(clicked()), view, SLOT(setDarkenMode())); + rbLighten = new QRadioButton(tr("Lighten"), modesGroup); + connect(rbLighten, SIGNAL(clicked()), view, SLOT(setLightenMode())); + rbColorDodge = new QRadioButton(tr("Color Dodge"), modesGroup); + connect(rbColorDodge, SIGNAL(clicked()), view, SLOT(setColorDodgeMode())); + rbColorBurn = new QRadioButton(tr("Color Burn"), modesGroup); + connect(rbColorBurn, SIGNAL(clicked()), view, SLOT(setColorBurnMode())); + rbHardLight = new QRadioButton(tr("Hard Light"), modesGroup); + connect(rbHardLight, SIGNAL(clicked()), view, SLOT(setHardLightMode())); + rbSoftLight = new QRadioButton(tr("Soft Light"), modesGroup); + connect(rbSoftLight, SIGNAL(clicked()), view, SLOT(setSoftLightMode())); + rbDifference = new QRadioButton(tr("Difference"), modesGroup); + connect(rbDifference, SIGNAL(clicked()), view, SLOT(setDifferenceMode())); + rbExclusion = new QRadioButton(tr("Exclusion"), modesGroup); + connect(rbExclusion, SIGNAL(clicked()), view, SLOT(setExclusionMode())); + + QGroupBox *circleColorGroup = new QGroupBox(mainGroup); + circleColorGroup->setTitle(tr("Circle color")); + QSlider *circleColorSlider = new QSlider(Qt::Horizontal, circleColorGroup); + circleColorSlider->setRange(0, 359); + circleColorSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + connect(circleColorSlider, SIGNAL(valueChanged(int)), view, SLOT(setCircleColor(int))); + + QGroupBox *circleAlphaGroup = new QGroupBox(mainGroup); + circleAlphaGroup->setTitle(tr("Circle alpha")); + QSlider *circleAlphaSlider = new QSlider(Qt::Horizontal, circleAlphaGroup); + circleAlphaSlider->setRange(0, 255); + circleAlphaSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + connect(circleAlphaSlider, SIGNAL(valueChanged(int)), view, SLOT(setCircleAlpha(int))); + + QPushButton *showSourceButton = new QPushButton(mainGroup); + showSourceButton->setText(tr("Show Source")); +#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) + QPushButton *enableOpenGLButton = new QPushButton(mainGroup); + enableOpenGLButton->setText(tr("Use OpenGL")); + enableOpenGLButton->setCheckable(true); + enableOpenGLButton->setChecked(view->usesOpenGL()); + + if (!QGLFormat::hasOpenGL() || !QGLPixelBuffer::hasOpenGLPbuffers()) + enableOpenGLButton->hide(); +#endif + QPushButton *whatsThisButton = new QPushButton(mainGroup); + whatsThisButton->setText(tr("What's This?")); + whatsThisButton->setCheckable(true); + + QPushButton *animateButton = new QPushButton(mainGroup); + animateButton->setText(tr("Animated")); + animateButton->setCheckable(true); + animateButton->setChecked(true); + + QHBoxLayout *viewLayout = new QHBoxLayout(this); + viewLayout->addWidget(view); + viewLayout->addWidget(mainGroup); + + QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); + mainGroupLayout->addWidget(circleColorGroup); + mainGroupLayout->addWidget(circleAlphaGroup); + mainGroupLayout->addWidget(modesGroup); + mainGroupLayout->addStretch(); + mainGroupLayout->addWidget(animateButton); + mainGroupLayout->addWidget(whatsThisButton); + mainGroupLayout->addWidget(showSourceButton); +#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) + mainGroupLayout->addWidget(enableOpenGLButton); +#endif + + QGridLayout *modesLayout = new QGridLayout(modesGroup); + modesLayout->addWidget(rbClear, 0, 0); + modesLayout->addWidget(rbSource, 1, 0); + modesLayout->addWidget(rbDest, 2, 0); + modesLayout->addWidget(rbSourceOver, 3, 0); + modesLayout->addWidget(rbDestOver, 4, 0); + modesLayout->addWidget(rbSourceIn, 5, 0); + modesLayout->addWidget(rbDestIn, 6, 0); + modesLayout->addWidget(rbSourceOut, 7, 0); + modesLayout->addWidget(rbDestOut, 8, 0); + modesLayout->addWidget(rbSourceAtop, 9, 0); + modesLayout->addWidget(rbDestAtop, 10, 0); + modesLayout->addWidget(rbXor, 11, 0); + + modesLayout->addWidget(rbPlus, 0, 1); + modesLayout->addWidget(rbMultiply, 1, 1); + modesLayout->addWidget(rbScreen, 2, 1); + modesLayout->addWidget(rbOverlay, 3, 1); + modesLayout->addWidget(rbDarken, 4, 1); + modesLayout->addWidget(rbLighten, 5, 1); + modesLayout->addWidget(rbColorDodge, 6, 1); + modesLayout->addWidget(rbColorBurn, 7, 1); + modesLayout->addWidget(rbHardLight, 8, 1); + modesLayout->addWidget(rbSoftLight, 9, 1); + modesLayout->addWidget(rbDifference, 10, 1); + modesLayout->addWidget(rbExclusion, 11, 1); + + + QVBoxLayout *circleColorLayout = new QVBoxLayout(circleColorGroup); + circleColorLayout->addWidget(circleColorSlider); + + QVBoxLayout *circleAlphaLayout = new QVBoxLayout(circleAlphaGroup); + circleAlphaLayout->addWidget(circleAlphaSlider); + + view->loadDescription(":res/composition/composition.html"); + view->loadSourceFile(":res/composition/composition.cpp"); + + connect(whatsThisButton, SIGNAL(clicked(bool)), view, SLOT(setDescriptionEnabled(bool))); + connect(view, SIGNAL(descriptionEnabledChanged(bool)), whatsThisButton, SLOT(setChecked(bool))); + connect(showSourceButton, SIGNAL(clicked()), view, SLOT(showSource())); +#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) + connect(enableOpenGLButton, SIGNAL(clicked(bool)), view, SLOT(enableOpenGL(bool))); +#endif + connect(animateButton, SIGNAL(toggled(bool)), view, SLOT(setAnimationEnabled(bool))); + + circleColorSlider->setValue(270); + circleAlphaSlider->setValue(200); + rbSourceOut->animateClick(); + + setWindowTitle(tr("Composition Modes")); +} + + +void CompositionWidget::nextMode() +{ + /* + if (!m_animation_enabled) + return; + if (rbClear->isChecked()) rbSource->animateClick(); + if (rbSource->isChecked()) rbDest->animateClick(); + if (rbDest->isChecked()) rbSourceOver->animateClick(); + if (rbSourceOver->isChecked()) rbDestOver->animateClick(); + if (rbDestOver->isChecked()) rbSourceIn->animateClick(); + if (rbSourceIn->isChecked()) rbDestIn->animateClick(); + if (rbDestIn->isChecked()) rbSourceOut->animateClick(); + if (rbSourceOut->isChecked()) rbDestOut->animateClick(); + if (rbDestOut->isChecked()) rbSourceAtop->animateClick(); + if (rbSourceAtop->isChecked()) rbDestAtop->animateClick(); + if (rbDestAtop->isChecked()) rbXor->animateClick(); + if (rbXor->isChecked()) rbClear->animateClick(); + */ +} + +CompositionRenderer::CompositionRenderer(QWidget *parent) + : ArthurFrame(parent) +{ + m_animation_enabled = true; + m_animationTimer = startTimer(animationInterval); +#ifdef Q_WS_QWS + m_image = QPixmap(":res/composition/flower.jpg"); + m_image.setAlphaChannel(QPixmap(":res/composition/flower_alpha.jpg")); +#else + m_image = QImage(":res/composition/flower.jpg"); + m_image.setAlphaChannel(QImage(":res/composition/flower_alpha.jpg")); +#endif + m_circle_alpha = 127; + m_circle_hue = 255; + m_current_object = NoObject; + m_composition_mode = QPainter::CompositionMode_SourceOut; + + m_circle_pos = QPoint(200, 100); + + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); +#ifdef QT_OPENGL_SUPPORT + m_pbuffer = 0; + m_pbuffer_size = 1024; +#endif +} + +QRectF rectangle_around(const QPointF &p, const QSizeF &size = QSize(250, 200)) +{ + QRectF rect(p, size); + rect.translate(-size.width()/2, -size.height()/2); + return rect; +} + +void CompositionRenderer::setAnimationEnabled(bool enabled) +{ + if (m_animation_enabled == enabled) + return; + m_animation_enabled = enabled; + if (enabled) { + Q_ASSERT(!m_animationTimer); + m_animationTimer = startTimer(animationInterval); + } else { + killTimer(m_animationTimer); + m_animationTimer = 0; + } +} + +void CompositionRenderer::updateCirclePos() +{ + if (m_current_object != NoObject) + return; + QDateTime dt = QDateTime::currentDateTime(); + qreal t = (dt.toTime_t() * 1000 + dt.time().msec()) / 1000.0; + + qreal x = width() / qreal(2) + (qCos(t*8/11) + qSin(-t)) * width() / qreal(4); + qreal y = height() / qreal(2) + (qSin(t*6/7) + qCos(t * qreal(1.5))) * height() / qreal(4); + + setCirclePos(QLineF(m_circle_pos, QPointF(x, y)).pointAt(0.02)); +} + +void CompositionRenderer::drawBase(QPainter &p) +{ + p.setPen(Qt::NoPen); + + QLinearGradient rect_gradient(0, 0, 0, height()); + rect_gradient.setColorAt(0, Qt::red); + rect_gradient.setColorAt(.17, Qt::yellow); + rect_gradient.setColorAt(.33, Qt::green); + rect_gradient.setColorAt(.50, Qt::cyan); + rect_gradient.setColorAt(.66, Qt::blue); + rect_gradient.setColorAt(.81, Qt::magenta); + rect_gradient.setColorAt(1, Qt::red); + p.setBrush(rect_gradient); + p.drawRect(width() / 2, 0, width() / 2, height()); + + QLinearGradient alpha_gradient(0, 0, width(), 0); + alpha_gradient.setColorAt(0, Qt::white); + alpha_gradient.setColorAt(0.2, Qt::white); + alpha_gradient.setColorAt(0.5, Qt::transparent); + alpha_gradient.setColorAt(0.8, Qt::white); + alpha_gradient.setColorAt(1, Qt::white); + + p.setCompositionMode(QPainter::CompositionMode_DestinationIn); + p.setBrush(alpha_gradient); + p.drawRect(0, 0, width(), height()); + + p.setCompositionMode(QPainter::CompositionMode_DestinationOver); + + p.setPen(Qt::NoPen); + p.setRenderHint(QPainter::SmoothPixmapTransform); +#ifdef Q_WS_QWS + p.drawPixmap(rect(), m_image); +#else + p.drawImage(rect(), m_image); +#endif +} + +void CompositionRenderer::drawSource(QPainter &p) +{ + p.setPen(Qt::NoPen); + p.setRenderHint(QPainter::Antialiasing); + p.setCompositionMode(m_composition_mode); + + QRectF circle_rect = rectangle_around(m_circle_pos); + QColor color = QColor::fromHsvF(m_circle_hue / 360.0, 1, 1, m_circle_alpha / 255.0); + QLinearGradient circle_gradient(circle_rect.topLeft(), circle_rect.bottomRight()); + circle_gradient.setColorAt(0, color.light()); + circle_gradient.setColorAt(0.5, color); + circle_gradient.setColorAt(1, color.dark()); + p.setBrush(circle_gradient); + + p.drawEllipse(circle_rect); +} + +void CompositionRenderer::paint(QPainter *painter) +{ +#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) + if (usesOpenGL()) { + + int new_pbuf_size = m_pbuffer_size; + if (size().width() > m_pbuffer_size || + size().height() > m_pbuffer_size) + new_pbuf_size *= 2; + + if (size().width() < m_pbuffer_size/2 && + size().height() < m_pbuffer_size/2) + new_pbuf_size /= 2; + + if (!m_pbuffer || new_pbuf_size != m_pbuffer_size) { + if (m_pbuffer) { + m_pbuffer->deleteTexture(m_base_tex); + m_pbuffer->deleteTexture(m_compositing_tex); + delete m_pbuffer; + } + + m_pbuffer = new QGLPixelBuffer(QSize(new_pbuf_size, new_pbuf_size), QGLFormat::defaultFormat(), glWidget()); + m_pbuffer->makeCurrent(); + m_base_tex = m_pbuffer->generateDynamicTexture(); + m_compositing_tex = m_pbuffer->generateDynamicTexture(); + m_pbuffer_size = new_pbuf_size; + } + + if (size() != m_previous_size) { + m_previous_size = size(); + QPainter p(m_pbuffer); + p.setCompositionMode(QPainter::CompositionMode_Source); + p.fillRect(QRect(0, 0, m_pbuffer->width(), m_pbuffer->height()), Qt::transparent); + drawBase(p); + p.end(); + m_pbuffer->updateDynamicTexture(m_base_tex); + } + + qreal x_fraction = width()/float(m_pbuffer->width()); + qreal y_fraction = height()/float(m_pbuffer->height()); + + { + QPainter p(m_pbuffer); + p.setCompositionMode(QPainter::CompositionMode_Source); + p.fillRect(QRect(0, 0, m_pbuffer->width(), m_pbuffer->height()), Qt::transparent); + + p.save(); // Needed when using the GL1 engine + p.beginNativePainting(); // Needed when using the GL2 engine + + glBindTexture(GL_TEXTURE_2D, m_base_tex); + glEnable(GL_TEXTURE_2D); + glColor4f(1.,1.,1.,1.); + + glBegin(GL_QUADS); + { + glTexCoord2f(0, 1.0); + glVertex2f(0, 0); + + glTexCoord2f(x_fraction, 1.0); + glVertex2f(width(), 0); + + glTexCoord2f(x_fraction, 1.0-y_fraction); + glVertex2f(width(), height()); + + glTexCoord2f(0, 1.0-y_fraction); + glVertex2f(0, height()); + } + glEnd(); + + glDisable(GL_TEXTURE_2D); + + p.endNativePainting(); // Needed when using the GL2 engine + p.restore(); // Needed when using the GL1 engine + + drawSource(p); + p.end(); + m_pbuffer->updateDynamicTexture(m_compositing_tex); + } + + painter->beginNativePainting(); // Needed when using the GL2 engine + glWidget()->makeCurrent(); // Needed when using the GL1 engine + glBindTexture(GL_TEXTURE_2D, m_compositing_tex); + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(1.,1.,1.,1.); + glBegin(GL_QUADS); + { + glTexCoord2f(0, 1.0); + glVertex2f(0, 0); + + glTexCoord2f(x_fraction, 1.0); + glVertex2f(width(), 0); + + glTexCoord2f(x_fraction, 1.0-y_fraction); + glVertex2f(width(), height()); + + glTexCoord2f(0, 1.0-y_fraction); + glVertex2f(0, height()); + } + glEnd(); + glDisable(GL_TEXTURE_2D); + painter->endNativePainting(); // Needed when using the GL2 engine + } else +#endif + { + // using a QImage + if (m_buffer.size() != size()) { +#ifdef Q_WS_QWS + m_base_buffer = QPixmap(size()); + m_base_buffer.fill(Qt::transparent); +#else + m_buffer = QImage(size(), QImage::Format_ARGB32_Premultiplied); + m_base_buffer = QImage(size(), QImage::Format_ARGB32_Premultiplied); + + m_base_buffer.fill(0); +#endif + + QPainter p(&m_base_buffer); + + drawBase(p); + } + +#ifdef Q_WS_QWS + m_buffer = m_base_buffer; +#else + memcpy(m_buffer.bits(), m_base_buffer.bits(), m_buffer.byteCount()); +#endif + + { + QPainter p(&m_buffer); + drawSource(p); + } + +#ifdef Q_WS_QWS + painter->drawPixmap(0, 0, m_buffer); +#else + painter->drawImage(0, 0, m_buffer); +#endif + } +} + +void CompositionRenderer::mousePressEvent(QMouseEvent *e) +{ + setDescriptionEnabled(false); + + QRectF circle = rectangle_around(m_circle_pos); + + if (circle.contains(e->pos())) { + m_current_object = Circle; + m_offset = circle.center() - e->pos(); + } else { + m_current_object = NoObject; + } + if (m_animation_enabled) { + killTimer(m_animationTimer); + m_animationTimer = 0; + } +} + +void CompositionRenderer::mouseMoveEvent(QMouseEvent *e) +{ + if (m_current_object == Circle) setCirclePos(e->pos() + m_offset); +} + +void CompositionRenderer::mouseReleaseEvent(QMouseEvent *) +{ + m_current_object = NoObject; + + if (m_animation_enabled) { + Q_ASSERT(!m_animationTimer); + m_animationTimer = startTimer(animationInterval); + } +} + +void CompositionRenderer::timerEvent(QTimerEvent *event) +{ + if (event->timerId() == m_animationTimer) + updateCirclePos(); +} + +void CompositionRenderer::setCirclePos(const QPointF &pos) +{ + const QRect oldRect = rectangle_around(m_circle_pos).toAlignedRect(); + m_circle_pos = pos; + const QRect newRect = rectangle_around(m_circle_pos).toAlignedRect(); +#if defined(QT_OPENGL_SUPPORT) && !defined(QT_OPENGL_ES) + if (usesOpenGL()) + update(); + else +#endif + update(oldRect | newRect); +} + diff --git a/examples/painting/composition/composition.h b/examples/painting/composition/composition.h new file mode 100644 index 0000000000..86e8f5c0df --- /dev/null +++ b/examples/painting/composition/composition.h @@ -0,0 +1,193 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef COMPOSITION_H +#define COMPOSITION_H + +#include "arthurwidgets.h" + +#include +#include + +QT_FORWARD_DECLARE_CLASS(QPushButton) +QT_FORWARD_DECLARE_CLASS(QRadioButton) + +#ifdef QT_OPENGL_SUPPORT +#include +#endif + +class CompositionWidget : public QWidget +{ + Q_OBJECT + +public: + CompositionWidget(QWidget *parent); + +public slots: +void nextMode(); + +private: + bool m_cycle_enabled; + + QRadioButton *rbClear; + QRadioButton *rbSource; + QRadioButton *rbDest; + QRadioButton *rbSourceOver; + QRadioButton *rbDestOver; + QRadioButton *rbSourceIn; + QRadioButton *rbDestIn; + QRadioButton *rbSourceOut; + QRadioButton *rbDestOut; + QRadioButton *rbSourceAtop; + QRadioButton *rbDestAtop; + QRadioButton *rbXor; + + QRadioButton *rbPlus; + QRadioButton *rbMultiply; + QRadioButton *rbScreen; + QRadioButton *rbOverlay; + QRadioButton *rbDarken; + QRadioButton *rbLighten; + QRadioButton *rbColorDodge; + QRadioButton *rbColorBurn; + QRadioButton *rbHardLight; + QRadioButton *rbSoftLight; + QRadioButton *rbDifference; + QRadioButton *rbExclusion; +}; + +class CompositionRenderer : public ArthurFrame +{ + Q_OBJECT + + enum ObjectType { NoObject, Circle, Rectangle, Image }; + + Q_PROPERTY(int circleColor READ circleColor WRITE setCircleColor) + Q_PROPERTY(int circleAlpha READ circleAlpha WRITE setCircleAlpha) + Q_PROPERTY(bool animation READ animationEnabled WRITE setAnimationEnabled) + +public: + CompositionRenderer(QWidget *parent); + + void paint(QPainter *); + + void setCirclePos(const QPointF &pos); + + QSize sizeHint() const { return QSize(500, 400); } + + bool animationEnabled() const { return m_animation_enabled; } + int circleColor() const { return m_circle_hue; } + int circleAlpha() const { return m_circle_alpha; } + +protected: + void mousePressEvent(QMouseEvent *); + void mouseMoveEvent(QMouseEvent *); + void mouseReleaseEvent(QMouseEvent *); + void timerEvent(QTimerEvent *); + +public slots: + void setClearMode() { m_composition_mode = QPainter::CompositionMode_Clear; update(); } + void setSourceMode() { m_composition_mode = QPainter::CompositionMode_Source; update(); } + void setDestMode() { m_composition_mode = QPainter::CompositionMode_Destination; update(); } + void setSourceOverMode() { m_composition_mode = QPainter::CompositionMode_SourceOver; update(); } + void setDestOverMode() { m_composition_mode = QPainter::CompositionMode_DestinationOver; update(); } + void setSourceInMode() { m_composition_mode = QPainter::CompositionMode_SourceIn; update(); } + void setDestInMode() { m_composition_mode = QPainter::CompositionMode_DestinationIn; update(); } + void setSourceOutMode() { m_composition_mode = QPainter::CompositionMode_SourceOut; update(); } + void setDestOutMode() { m_composition_mode = QPainter::CompositionMode_DestinationOut; update(); } + void setSourceAtopMode() { m_composition_mode = QPainter::CompositionMode_SourceAtop; update(); } + void setDestAtopMode() { m_composition_mode = QPainter::CompositionMode_DestinationAtop; update(); } + void setXorMode() { m_composition_mode = QPainter::CompositionMode_Xor; update(); } + + void setPlusMode() { m_composition_mode = QPainter::CompositionMode_Plus; update(); } + void setMultiplyMode() { m_composition_mode = QPainter::CompositionMode_Multiply; update(); } + void setScreenMode() { m_composition_mode = QPainter::CompositionMode_Screen; update(); } + void setOverlayMode() { m_composition_mode = QPainter::CompositionMode_Overlay; update(); } + void setDarkenMode() { m_composition_mode = QPainter::CompositionMode_Darken; update(); } + void setLightenMode() { m_composition_mode = QPainter::CompositionMode_Lighten; update(); } + void setColorDodgeMode() { m_composition_mode = QPainter::CompositionMode_ColorDodge; update(); } + void setColorBurnMode() { m_composition_mode = QPainter::CompositionMode_ColorBurn; update(); } + void setHardLightMode() { m_composition_mode = QPainter::CompositionMode_HardLight; update(); } + void setSoftLightMode() { m_composition_mode = QPainter::CompositionMode_SoftLight; update(); } + void setDifferenceMode() { m_composition_mode = QPainter::CompositionMode_Difference; update(); } + void setExclusionMode() { m_composition_mode = QPainter::CompositionMode_Exclusion; update(); } + + void setCircleAlpha(int alpha) { m_circle_alpha = alpha; update(); } + void setCircleColor(int hue) { m_circle_hue = hue; update(); } + void setAnimationEnabled(bool enabled); + +private: + void updateCirclePos(); + void drawBase(QPainter &p); + void drawSource(QPainter &p); + + QPainter::CompositionMode m_composition_mode; + +#ifdef Q_WS_QWS + QPixmap m_image; + QPixmap m_buffer; + QPixmap m_base_buffer; +#else + QImage m_image; + QImage m_buffer; + QImage m_base_buffer; +#endif + + int m_circle_alpha; + int m_circle_hue; + + QPointF m_circle_pos; + QPointF m_offset; + + ObjectType m_current_object; + bool m_animation_enabled; + int m_animationTimer; + +#ifdef QT_OPENGL_SUPPORT + QGLPixelBuffer *m_pbuffer; + GLuint m_base_tex; + GLuint m_compositing_tex; + int m_pbuffer_size; // width==height==size of pbuffer + QSize m_previous_size; +#endif +}; + +#endif // COMPOSITION_H diff --git a/examples/painting/composition/composition.html b/examples/painting/composition/composition.html new file mode 100644 index 0000000000..1848ad8bd1 --- /dev/null +++ b/examples/painting/composition/composition.html @@ -0,0 +1,23 @@ + + +

      Demo for composition modes

      + +

      + This demo shows some of the more advanced composition modes supported by Qt. +

      + +

      + The two most common forms of composition are Source and SourceOver. + Source is used to draw opaque objects onto a paint device. In this mode, + each pixel in the source replaces the corresponding pixel in the destination. + In SourceOver composition mode, the source object is transparent and is + drawn on top of the destination. +

      + +

      + In addition to these standard modes, Qt defines the complete set of composition + modes as defined by Thomas Porter and Tom Duff. See the QPainter documentation + for details. +

      + + diff --git a/examples/painting/composition/composition.pro b/examples/painting/composition/composition.pro new file mode 100644 index 0000000000..59b91126b9 --- /dev/null +++ b/examples/painting/composition/composition.pro @@ -0,0 +1,29 @@ +SOURCES += main.cpp composition.cpp +HEADERS += composition.h + +SHARED_FOLDER = ../shared + +include($$SHARED_FOLDER/shared.pri) + +RESOURCES += composition.qrc +contains(QT_CONFIG, opengl) { + DEFINES += QT_OPENGL_SUPPORT + QT += opengl +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/composition +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.png *.jpg *.pro *.html +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/composition +INSTALLS += target sources + +symbian: CONFIG += qt_demo + +win32-msvc* { + QMAKE_CXXFLAGS += /Zm500 + QMAKE_CFLAGS += /Zm500 +} + +wince* { + DEPLOYMENT_PLUGIN += qjpeg +} diff --git a/examples/painting/composition/composition.qrc b/examples/painting/composition/composition.qrc new file mode 100644 index 0000000000..d02c397ee8 --- /dev/null +++ b/examples/painting/composition/composition.qrc @@ -0,0 +1,8 @@ + + + composition.cpp + composition.html + flower.jpg + flower_alpha.jpg + + diff --git a/examples/painting/composition/flower.jpg b/examples/painting/composition/flower.jpg new file mode 100644 index 0000000000..f8e022c98c Binary files /dev/null and b/examples/painting/composition/flower.jpg differ diff --git a/examples/painting/composition/flower_alpha.jpg b/examples/painting/composition/flower_alpha.jpg new file mode 100644 index 0000000000..6a3c2a02ef Binary files /dev/null and b/examples/painting/composition/flower_alpha.jpg differ diff --git a/examples/painting/composition/main.cpp b/examples/painting/composition/main.cpp new file mode 100644 index 0000000000..d6bc170a97 --- /dev/null +++ b/examples/painting/composition/main.cpp @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "composition.h" + +#include +#ifdef QT_OPENGL_SUPPORT +#include +#endif + +int main(int argc, char **argv) +{ + // Q_INIT_RESOURCE(deform); + +#ifdef QT_OPENGL_SUPPORT + QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); +#endif + QApplication app(argc, argv); + + CompositionWidget compWidget(0); + QStyle *arthurStyle = new ArthurStyle(); + compWidget.setStyle(arthurStyle); + + QList widgets = compWidget.findChildren(); + foreach (QWidget *w, widgets) + w->setStyle(arthurStyle); + compWidget.show(); + + return app.exec(); +} diff --git a/examples/painting/deform/deform.pro b/examples/painting/deform/deform.pro new file mode 100644 index 0000000000..3393b8e83c --- /dev/null +++ b/examples/painting/deform/deform.pro @@ -0,0 +1,24 @@ +SOURCES += main.cpp pathdeform.cpp +HEADERS += pathdeform.h + +SHARED_FOLDER = ../shared + +include($$SHARED_FOLDER/shared.pri) + +RESOURCES += deform.qrc + +contains(QT_CONFIG, opengl) { + DEFINES += QT_OPENGL_SUPPORT + QT += opengl +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/deform +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/deform +INSTALLS += target sources + +symbian { + TARGET.UID3 = 0xA000A63D + CONFIG += qt_demo +} diff --git a/examples/painting/deform/deform.qrc b/examples/painting/deform/deform.qrc new file mode 100644 index 0000000000..2e59ebcfc5 --- /dev/null +++ b/examples/painting/deform/deform.qrc @@ -0,0 +1,6 @@ + + + pathdeform.cpp + pathdeform.html + + diff --git a/examples/painting/deform/main.cpp b/examples/painting/deform/main.cpp new file mode 100644 index 0000000000..c49117a2f2 --- /dev/null +++ b/examples/painting/deform/main.cpp @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "pathdeform.h" + +#include +#include + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(deform); + + QApplication app(argc, argv); + + bool smallScreen = QApplication::arguments().contains("-small-screen"); + + PathDeformWidget deformWidget(0, smallScreen); + + QStyle *arthurStyle = new ArthurStyle(); + deformWidget.setStyle(arthurStyle); + QList widgets = deformWidget.findChildren(); + foreach (QWidget *w, widgets) + w->setStyle(arthurStyle); + + if (smallScreen) + deformWidget.showFullScreen(); + else + deformWidget.show(); + +#ifdef QT_KEYPAD_NAVIGATION + QApplication::setNavigationMode(Qt::NavigationModeCursorAuto); +#endif + return app.exec(); +} diff --git a/examples/painting/deform/pathdeform.cpp b/examples/painting/deform/pathdeform.cpp new file mode 100644 index 0000000000..f80ef2b8be --- /dev/null +++ b/examples/painting/deform/pathdeform.cpp @@ -0,0 +1,647 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "pathdeform.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +PathDeformControls::PathDeformControls(QWidget *parent, PathDeformRenderer* renderer, bool smallScreen) + : QWidget(parent) +{ + m_renderer = renderer; + + if (smallScreen) + layoutForSmallScreen(); + else + layoutForDesktop(); +} + + +void PathDeformControls::layoutForDesktop() +{ + QGroupBox* mainGroup = new QGroupBox(this); + mainGroup->setTitle(tr("Controls")); + + QGroupBox *radiusGroup = new QGroupBox(mainGroup); + radiusGroup->setTitle(tr("Lens Radius")); + QSlider *radiusSlider = new QSlider(Qt::Horizontal, radiusGroup); + radiusSlider->setRange(15, 150); + radiusSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + + QGroupBox *deformGroup = new QGroupBox(mainGroup); + deformGroup->setTitle(tr("Deformation")); + QSlider *deformSlider = new QSlider(Qt::Horizontal, deformGroup); + deformSlider->setRange(-100, 100); + deformSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + + QGroupBox *fontSizeGroup = new QGroupBox(mainGroup); + fontSizeGroup->setTitle(tr("Font Size")); + QSlider *fontSizeSlider = new QSlider(Qt::Horizontal, fontSizeGroup); + fontSizeSlider->setRange(16, 200); + fontSizeSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + + QGroupBox *textGroup = new QGroupBox(mainGroup); + textGroup->setTitle(tr("Text")); + QLineEdit *textInput = new QLineEdit(textGroup); + + QPushButton *animateButton = new QPushButton(mainGroup); + animateButton->setText(tr("Animated")); + animateButton->setCheckable(true); + + QPushButton *showSourceButton = new QPushButton(mainGroup); + showSourceButton->setText(tr("Show Source")); + +#ifdef QT_OPENGL_SUPPORT + QPushButton *enableOpenGLButton = new QPushButton(mainGroup); + enableOpenGLButton->setText(tr("Use OpenGL")); + enableOpenGLButton->setCheckable(true); + enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); + if (!QGLFormat::hasOpenGL()) + enableOpenGLButton->hide(); +#endif + + QPushButton *whatsThisButton = new QPushButton(mainGroup); + whatsThisButton->setText(tr("What's This?")); + whatsThisButton->setCheckable(true); + + + mainGroup->setFixedWidth(180); + + QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); + mainGroupLayout->addWidget(radiusGroup); + mainGroupLayout->addWidget(deformGroup); + mainGroupLayout->addWidget(fontSizeGroup); + mainGroupLayout->addWidget(textGroup); + mainGroupLayout->addWidget(animateButton); + mainGroupLayout->addStretch(1); +#ifdef QT_OPENGL_SUPPORT + mainGroupLayout->addWidget(enableOpenGLButton); +#endif + mainGroupLayout->addWidget(showSourceButton); + mainGroupLayout->addWidget(whatsThisButton); + + QVBoxLayout *radiusGroupLayout = new QVBoxLayout(radiusGroup); + radiusGroupLayout->addWidget(radiusSlider); + + QVBoxLayout *deformGroupLayout = new QVBoxLayout(deformGroup); + deformGroupLayout->addWidget(deformSlider); + + QVBoxLayout *fontSizeGroupLayout = new QVBoxLayout(fontSizeGroup); + fontSizeGroupLayout->addWidget(fontSizeSlider); + + QVBoxLayout *textGroupLayout = new QVBoxLayout(textGroup); + textGroupLayout->addWidget(textInput); + + QVBoxLayout * mainLayout = new QVBoxLayout(this); + mainLayout->addWidget(mainGroup); + mainLayout->setMargin(0); + + connect(radiusSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setRadius(int))); + connect(deformSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setIntensity(int))); + connect(fontSizeSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setFontSize(int))); + connect(animateButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setAnimated(bool))); +#ifdef QT_OPENGL_SUPPORT + connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); +#endif + + connect(textInput, SIGNAL(textChanged(QString)), m_renderer, SLOT(setText(QString))); + connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), + whatsThisButton, SLOT(setChecked(bool))); + connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); + connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); + + animateButton->animateClick(); + deformSlider->setValue(80); + fontSizeSlider->setValue(120); + radiusSlider->setValue(100); + textInput->setText(tr("Qt")); +} + +void PathDeformControls::layoutForSmallScreen() +{ + QGroupBox* mainGroup = new QGroupBox(this); + mainGroup->setTitle(tr("Controls")); + + QLabel *radiusLabel = new QLabel(mainGroup); + radiusLabel->setText(tr("Lens Radius:")); + QSlider *radiusSlider = new QSlider(Qt::Horizontal, mainGroup); + radiusSlider->setRange(15, 150); + radiusSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + + QLabel *deformLabel = new QLabel(mainGroup); + deformLabel->setText(tr("Deformation:")); + QSlider *deformSlider = new QSlider(Qt::Horizontal, mainGroup); + deformSlider->setRange(-100, 100); + deformSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + + QLabel *fontSizeLabel = new QLabel(mainGroup); + fontSizeLabel->setText(tr("Font Size:")); + QSlider *fontSizeSlider = new QSlider(Qt::Horizontal, mainGroup); + fontSizeSlider->setRange(16, 200); + fontSizeSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + + QPushButton *animateButton = new QPushButton(tr("Animated"), mainGroup); + animateButton->setCheckable(true); + +#ifdef QT_OPENGL_SUPPORT + QPushButton *enableOpenGLButton = new QPushButton(mainGroup); + enableOpenGLButton->setText(tr("Use OpenGL")); + enableOpenGLButton->setCheckable(mainGroup); + enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); + if (!QGLFormat::hasOpenGL()) + enableOpenGLButton->hide(); +#endif + + QPushButton *quitButton = new QPushButton(tr("Quit"), mainGroup); + QPushButton *okButton = new QPushButton(tr("OK"), mainGroup); + + + QGridLayout *mainGroupLayout = new QGridLayout(mainGroup); + mainGroupLayout->setMargin(0); + mainGroupLayout->addWidget(radiusLabel, 0, 0, Qt::AlignRight); + mainGroupLayout->addWidget(radiusSlider, 0, 1); + mainGroupLayout->addWidget(deformLabel, 1, 0, Qt::AlignRight); + mainGroupLayout->addWidget(deformSlider, 1, 1); + mainGroupLayout->addWidget(fontSizeLabel, 2, 0, Qt::AlignRight); + mainGroupLayout->addWidget(fontSizeSlider, 2, 1); + mainGroupLayout->addWidget(animateButton, 3,0, 1,2); +#ifdef QT_OPENGL_SUPPORT + mainGroupLayout->addWidget(enableOpenGLButton, 4,0, 1,2); +#endif + + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->addWidget(mainGroup); + mainLayout->addStretch(1); + mainLayout->addWidget(okButton); + mainLayout->addWidget(quitButton); + + connect(quitButton, SIGNAL(clicked()), this, SLOT(emitQuitSignal())); + connect(okButton, SIGNAL(clicked()), this, SLOT(emitOkSignal())); + connect(radiusSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setRadius(int))); + connect(deformSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setIntensity(int))); + connect(fontSizeSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setFontSize(int))); + connect(animateButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setAnimated(bool))); +#ifdef QT_OPENGL_SUPPORT + connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); +#endif + + + animateButton->animateClick(); + deformSlider->setValue(80); + fontSizeSlider->setValue(120); + + QRect screen_size = QApplication::desktop()->screenGeometry(); + radiusSlider->setValue(qMin(screen_size.width(), screen_size.height())/5); + + m_renderer->setText(tr("Qt")); +} + + +void PathDeformControls::emitQuitSignal() +{ emit quitPressed(); } + +void PathDeformControls::emitOkSignal() +{ emit okPressed(); } + + +PathDeformWidget::PathDeformWidget(QWidget *parent, bool smallScreen) + : QWidget(parent) +{ + setWindowTitle(tr("Vector Deformation")); + + m_renderer = new PathDeformRenderer(this, smallScreen); + m_renderer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + + // Layouts + QHBoxLayout *mainLayout = new QHBoxLayout(this); + mainLayout->addWidget(m_renderer); + + m_controls = new PathDeformControls(0, m_renderer, smallScreen); + m_controls->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum); + + if (!smallScreen) + mainLayout->addWidget(m_controls); + + m_renderer->loadSourceFile(":res/deform/pathdeform.cpp"); + m_renderer->loadDescription(":res/deform/pathdeform.html"); + m_renderer->setDescriptionEnabled(false); + + connect(m_renderer, SIGNAL(clicked()), this, SLOT(showControls())); + connect(m_controls, SIGNAL(okPressed()), this, SLOT(hideControls())); + connect(m_controls, SIGNAL(quitPressed()), QApplication::instance(), SLOT(quit())); +} + + +void PathDeformWidget::showControls() +{ + m_controls->showFullScreen(); +} + +void PathDeformWidget::hideControls() +{ + m_controls->hide(); +} + +void PathDeformWidget::setStyle( QStyle * style ) +{ + QWidget::setStyle(style); + if (m_controls != 0) + { + m_controls->setStyle(style); + + QList widgets = m_controls->findChildren(); + foreach (QWidget *w, widgets) + w->setStyle(style); + } +} + +static inline QRect circle_bounds(const QPointF ¢er, qreal radius, qreal compensation) +{ + return QRect(qRound(center.x() - radius - compensation), + qRound(center.y() - radius - compensation), + qRound((radius + compensation) * 2), + qRound((radius + compensation) * 2)); + +} + +const int LENS_EXTENT = 10; + +PathDeformRenderer::PathDeformRenderer(QWidget *widget, bool smallScreen) + : ArthurFrame(widget) +{ + m_radius = 100; + m_pos = QPointF(m_radius, m_radius); + m_direction = QPointF(1, 1); + m_fontSize = 24; + m_animated = true; + m_repaintTimer.start(25, this); + m_repaintTracker.start(); + m_intensity = 100; + m_smallScreen = smallScreen; + +// m_fpsTimer.start(1000, this); +// m_fpsCounter = 0; + + generateLensPixmap(); +} + +void PathDeformRenderer::setText(const QString &text) +{ + m_text = text; + + QFont f("times new roman,utopia"); + f.setStyleStrategy(QFont::ForceOutline); + f.setPointSize(m_fontSize); + f.setStyleHint(QFont::Times); + + QFontMetrics fm(f); + + m_paths.clear(); + m_pathBounds = QRect(); + + QPointF advance(0, 0); + + bool do_quick = true; + for (int i=0; i= 0x4ff && text.at(i).unicode() <= 0x1e00) { + do_quick = false; + break; + } + } + + if (do_quick) { + for (int i=0; itimerId() == m_repaintTimer.timerId()) { + + if (QLineF(QPointF(0,0), m_direction).length() > 1) + m_direction *= 0.995; + qreal time = m_repaintTracker.restart(); + + QRect rectBefore = circle_bounds(m_pos, m_radius, m_fontSize); + + qreal dx = m_direction.x(); + qreal dy = m_direction.y(); + if (time > 0) { + dx = dx * time * .1; + dy = dy * time * .1; + } + + m_pos += QPointF(dx, dy); + + + + if (m_pos.x() - m_radius < 0) { + m_direction.setX(-m_direction.x()); + m_pos.setX(m_radius); + } else if (m_pos.x() + m_radius > width()) { + m_direction.setX(-m_direction.x()); + m_pos.setX(width() - m_radius); + } + + if (m_pos.y() - m_radius < 0) { + m_direction.setY(-m_direction.y()); + m_pos.setY(m_radius); + } else if (m_pos.y() + m_radius > height()) { + m_direction.setY(-m_direction.y()); + m_pos.setY(height() - m_radius); + } + +#ifdef QT_OPENGL_SUPPORT + if (usesOpenGL()) { + update(); + } else +#endif + { + QRect rectAfter = circle_bounds(m_pos, m_radius, m_fontSize); + update(rectAfter | rectBefore); + QApplication::syncX(); + } + } +// else if (e->timerId() == m_fpsTimer.timerId()) { +// printf("fps: %d\n", m_fpsCounter); +// emit frameRate(m_fpsCounter); +// m_fpsCounter = 0; + +// } +} + +void PathDeformRenderer::mousePressEvent(QMouseEvent *e) +{ + setDescriptionEnabled(false); + + m_repaintTimer.stop(); + m_offset = QPointF(); + if (QLineF(m_pos, e->pos()).length() <= m_radius) + m_offset = m_pos - e->pos(); + + m_mousePress = e->pos(); + + // If we're not running in small screen mode, always assume we're dragging + m_mouseDrag = !m_smallScreen; + + mouseMoveEvent(e); +} + +void PathDeformRenderer::mouseReleaseEvent(QMouseEvent *e) +{ + if (e->buttons() == Qt::NoButton && m_animated) { + m_repaintTimer.start(10, this); + m_repaintTracker.start(); + } + + if (!m_mouseDrag && m_smallScreen) + emit clicked(); +} + +void PathDeformRenderer::mouseMoveEvent(QMouseEvent *e) +{ + if (!m_mouseDrag && (QLineF(m_mousePress, e->pos()).length() > 25.0) ) + m_mouseDrag = true; + + if (m_mouseDrag) { + QRect rectBefore = circle_bounds(m_pos, m_radius, m_fontSize); + if (e->type() == QEvent::MouseMove) { + QLineF line(m_pos, e->pos() + m_offset); + line.setLength(line.length() * .1); + QPointF dir(line.dx(), line.dy()); + m_direction = (m_direction + dir) / 2; + } + m_pos = e->pos() + m_offset; +#ifdef QT_OPENGL_SUPPORT + if (usesOpenGL()) { + update(); + } else +#endif + { + QRect rectAfter = circle_bounds(m_pos, m_radius, m_fontSize); + update(rectBefore | rectAfter); + } + } +} + +QPainterPath PathDeformRenderer::lensDeform(const QPainterPath &source, const QPointF &offset) +{ + QPainterPath path; + path.addPath(source); + + qreal flip = m_intensity / qreal(100); + + for (int i=0; i 0) { + path.setElementPositionAt(i, + x + flip * dx * len / m_radius, + y + flip * dy * len / m_radius); + } else { + path.setElementPositionAt(i, x, y); + } + + } + + return path; +} + + +void PathDeformRenderer::paint(QPainter *painter) +{ + int pad_x = 5; + int pad_y = 5; + + int skip_x = qRound(m_pathBounds.width() + pad_x + m_fontSize/2); + int skip_y = qRound(m_pathBounds.height() + pad_y); + + painter->setPen(Qt::NoPen); + painter->setBrush(Qt::black); + + QRectF clip(painter->clipPath().boundingRect()); + + int overlap = pad_x / 2; + + for (int start_y=0; start_y < height(); start_y += skip_y) { + + if (start_y > clip.bottom()) + break; + + int start_x = -overlap; + for (; start_x < width(); start_x += skip_x) { + + if (start_y + skip_y >= clip.top() && + start_x + skip_x >= clip.left() && + start_x <= clip.right()) { + for (int i=0; idrawPath(path); + } + } + } + overlap = skip_x - (start_x - width()); + + } + + if (preferImage()) { + painter->drawImage(m_pos - QPointF(m_radius + LENS_EXTENT, m_radius + LENS_EXTENT), + m_lens_image); + } else { + painter->drawPixmap(m_pos - QPointF(m_radius + LENS_EXTENT, m_radius + LENS_EXTENT), + m_lens_pixmap); + } +} + + + +void PathDeformRenderer::setRadius(int radius) +{ + qreal max = qMax(m_radius, (qreal)radius); + m_radius = radius; + generateLensPixmap(); + if (!m_animated || m_radius < max) { +#ifdef QT_OPENGL_SUPPORT + if (usesOpenGL()) { + update(); + } else +#endif + { + update(circle_bounds(m_pos, max, m_fontSize)); + } + } +} + +void PathDeformRenderer::setIntensity(int intensity) +{ + m_intensity = intensity; + if (!m_animated) { +#ifdef QT_OPENGL_SUPPORT + if (usesOpenGL()) { + update(); + } else +#endif + { + update(circle_bounds(m_pos, m_radius, m_fontSize)); + } + } +} diff --git a/examples/painting/deform/pathdeform.h b/examples/painting/deform/pathdeform.h new file mode 100644 index 0000000000..73a1955082 --- /dev/null +++ b/examples/painting/deform/pathdeform.h @@ -0,0 +1,153 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PATHDEFORM_H +#define PATHDEFORM_H + +#include "arthurwidgets.h" + +#include +#include +#include + +class PathDeformRenderer : public ArthurFrame +{ + Q_OBJECT + Q_PROPERTY(bool animated READ animated WRITE setAnimated) + Q_PROPERTY(int radius READ radius WRITE setRadius) + Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize) + Q_PROPERTY(int intensity READ intensity WRITE setIntensity) + Q_PROPERTY(QString text READ text WRITE setText) + +public: + PathDeformRenderer(QWidget *widget, bool smallScreen = false); + + void paint(QPainter *painter); + + void mousePressEvent(QMouseEvent *e); + void mouseReleaseEvent(QMouseEvent *e); + void mouseMoveEvent(QMouseEvent *e); + void timerEvent(QTimerEvent *e); + + QSize sizeHint() const { return QSize(600, 500); } + + bool animated() const { return m_animated; } + int radius() const { return int(m_radius); } + int fontSize() const { return m_fontSize; } + int intensity() const { return int(m_intensity); } + QString text() const { return m_text; } + +public slots: + void setRadius(int radius); + void setFontSize(int fontSize) { m_fontSize = fontSize; setText(m_text); } + void setText(const QString &text); + void setIntensity(int intensity); + + void setAnimated(bool animated); + +signals: + void clicked(); +// void frameRate(double fps); + +private: + void generateLensPixmap(); + QPainterPath lensDeform(const QPainterPath &source, const QPointF &offset); + + QBasicTimer m_repaintTimer; +// QBasicTimer m_fpsTimer; +// int m_fpsCounter; + QTime m_repaintTracker; + + QVector m_paths; + QVector m_advances; + QRectF m_pathBounds; + QString m_text; + + QPixmap m_lens_pixmap; + QImage m_lens_image; + + int m_fontSize; + bool m_animated; + + qreal m_intensity; + qreal m_radius; + QPointF m_pos; + QPointF m_offset; + QPointF m_direction; + QPointF m_mousePress; + bool m_mouseDrag; + bool m_smallScreen; +}; + +class PathDeformControls : public QWidget +{ + Q_OBJECT +public: + PathDeformControls(QWidget *parent, PathDeformRenderer* renderer, bool smallScreen); +signals: + void okPressed(); + void quitPressed(); +private: + PathDeformRenderer* m_renderer; + void layoutForDesktop(); + void layoutForSmallScreen(); +private slots: + void emitQuitSignal(); + void emitOkSignal(); +}; + +class PathDeformWidget : public QWidget +{ + Q_OBJECT +public: + PathDeformWidget(QWidget *parent, bool smallScreen); + void setStyle ( QStyle * style ); + +private: + PathDeformRenderer *m_renderer; + PathDeformControls *m_controls; + +private slots: + void showControls(); + void hideControls(); +}; + +#endif // PATHDEFORM_H diff --git a/examples/painting/deform/pathdeform.html b/examples/painting/deform/pathdeform.html new file mode 100644 index 0000000000..b3f63a8e0a --- /dev/null +++ b/examples/painting/deform/pathdeform.html @@ -0,0 +1,24 @@ + +
      +

      Vector deformation

      +
      + +

      This demo shows how to use advanced vector techniques to draw text +using a QPainterPath.

      + +

      We define a vector deformation field in the shape of a lens and apply +this to all points in a path. This means that what is rendered on +screen is not pixel manipulation, but modified vector representations of +the glyphs themselves. This is visible from the high quality of the +antialiased edges for the deformed glyphs.

      + +

      To get a fairly complex path we allow the user to type in text and +convert the text to paths. This is done using the +QPainterPath::addText() function.

      + +

      The lens is drawn using a single call to drawEllipse(), using +a QRadialGradient to fill it with a specialized color table, +giving the effect of the Sun's reflection and a drop shadow. The lens +is cached as a pixmap for better performance.

      + + diff --git a/examples/painting/gradients/gradients.cpp b/examples/painting/gradients/gradients.cpp new file mode 100644 index 0000000000..d8b739b3b0 --- /dev/null +++ b/examples/painting/gradients/gradients.cpp @@ -0,0 +1,516 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "gradients.h" +#include "hoverpoints.h" + +ShadeWidget::ShadeWidget(ShadeType type, QWidget *parent) + : QWidget(parent), m_shade_type(type), m_alpha_gradient(QLinearGradient(0, 0, 0, 0)) +{ + + // Checkers background + if (m_shade_type == ARGBShade) { + QPixmap pm(20, 20); + QPainter pmp(&pm); + pmp.fillRect(0, 0, 10, 10, Qt::lightGray); + pmp.fillRect(10, 10, 10, 10, Qt::lightGray); + pmp.fillRect(0, 10, 10, 10, Qt::darkGray); + pmp.fillRect(10, 0, 10, 10, Qt::darkGray); + pmp.end(); + QPalette pal = palette(); + pal.setBrush(backgroundRole(), QBrush(pm)); + setAutoFillBackground(true); + setPalette(pal); + + } else { + setAttribute(Qt::WA_NoBackground); + + } + + QPolygonF points; + points << QPointF(0, sizeHint().height()) + << QPointF(sizeHint().width(), 0); + + m_hoverPoints = new HoverPoints(this, HoverPoints::CircleShape); +// m_hoverPoints->setConnectionType(HoverPoints::LineConnection); + m_hoverPoints->setPoints(points); + m_hoverPoints->setPointLock(0, HoverPoints::LockToLeft); + m_hoverPoints->setPointLock(1, HoverPoints::LockToRight); + m_hoverPoints->setSortType(HoverPoints::XSort); + + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + + connect(m_hoverPoints, SIGNAL(pointsChanged(QPolygonF)), this, SIGNAL(colorsChanged())); +} + + +QPolygonF ShadeWidget::points() const +{ + return m_hoverPoints->points(); +} + + +uint ShadeWidget::colorAt(int x) +{ + generateShade(); + + QPolygonF pts = m_hoverPoints->points(); + for (int i=1; i < pts.size(); ++i) { + if (pts.at(i-1).x() <= x && pts.at(i).x() >= x) { + QLineF l(pts.at(i-1), pts.at(i)); + l.setLength(l.length() * ((x - l.x1()) / l.dx())); + return m_shade.pixel(qRound(qMin(l.x2(), (qreal(m_shade.width() - 1)))), + qRound(qMin(l.y2(), qreal(m_shade.height() - 1)))); + } + } + return 0; +} + + +void ShadeWidget::setGradientStops(const QGradientStops &stops) +{ + if (m_shade_type == ARGBShade) { + m_alpha_gradient = QLinearGradient(0, 0, width(), 0); + + for (int i=0; isetSpacing(1); + vbox->setMargin(1); + + m_red_shade = new ShadeWidget(ShadeWidget::RedShade, this); + m_green_shade = new ShadeWidget(ShadeWidget::GreenShade, this); + m_blue_shade = new ShadeWidget(ShadeWidget::BlueShade, this); + m_alpha_shade = new ShadeWidget(ShadeWidget::ARGBShade, this); + + vbox->addWidget(m_red_shade); + vbox->addWidget(m_green_shade); + vbox->addWidget(m_blue_shade); + vbox->addWidget(m_alpha_shade); + + connect(m_red_shade, SIGNAL(colorsChanged()), this, SLOT(pointsUpdated())); + connect(m_green_shade, SIGNAL(colorsChanged()), this, SLOT(pointsUpdated())); + connect(m_blue_shade, SIGNAL(colorsChanged()), this, SLOT(pointsUpdated())); + connect(m_alpha_shade, SIGNAL(colorsChanged()), this, SLOT(pointsUpdated())); +} + + +inline static bool x_less_than(const QPointF &p1, const QPointF &p2) +{ + return p1.x() < p2.x(); +} + + +void GradientEditor::pointsUpdated() +{ + qreal w = m_alpha_shade->width(); + + QGradientStops stops; + + QPolygonF points; + + points += m_red_shade->points(); + points += m_green_shade->points(); + points += m_blue_shade->points(); + points += m_alpha_shade->points(); + + qSort(points.begin(), points.end(), x_less_than); + + for (int i=0; icolorAt(int(x))) >> 16, + (0x0000ff00 & m_green_shade->colorAt(int(x))) >> 8, + (0x000000ff & m_blue_shade->colorAt(int(x))), + (0xff000000 & m_alpha_shade->colorAt(int(x))) >> 24); + + if (x / w > 1) + return; + + stops << QGradientStop(x / w, color); + } + + m_alpha_shade->setGradientStops(stops); + + emit gradientStopsChanged(stops); +} + + +static void set_shade_points(const QPolygonF &points, ShadeWidget *shade) +{ + shade->hoverPoints()->setPoints(points); + shade->hoverPoints()->setPointLock(0, HoverPoints::LockToLeft); + shade->hoverPoints()->setPointLock(points.size() - 1, HoverPoints::LockToRight); + shade->update(); +} + +void GradientEditor::setGradientStops(const QGradientStops &stops) +{ + QPolygonF pts_red, pts_green, pts_blue, pts_alpha; + + qreal h_red = m_red_shade->height(); + qreal h_green = m_green_shade->height(); + qreal h_blue = m_blue_shade->height(); + qreal h_alpha = m_alpha_shade->height(); + + for (int i=0; iwidth(), h_red - qRed(color) * h_red / 255); + pts_green << QPointF(pos * m_green_shade->width(), h_green - qGreen(color) * h_green / 255); + pts_blue << QPointF(pos * m_blue_shade->width(), h_blue - qBlue(color) * h_blue / 255); + pts_alpha << QPointF(pos * m_alpha_shade->width(), h_alpha - qAlpha(color) * h_alpha / 255); + } + + set_shade_points(pts_red, m_red_shade); + set_shade_points(pts_green, m_green_shade); + set_shade_points(pts_blue, m_blue_shade); + set_shade_points(pts_alpha, m_alpha_shade); + +} + +GradientWidget::GradientWidget(QWidget *parent) + : QWidget(parent) +{ + setWindowTitle(tr("Gradients")); + + m_renderer = new GradientRenderer(this); + + QGroupBox *mainGroup = new QGroupBox(this); + mainGroup->setTitle(tr("Gradients")); + + QGroupBox *editorGroup = new QGroupBox(mainGroup); + editorGroup->setTitle(tr("Color Editor")); + m_editor = new GradientEditor(editorGroup); + + QGroupBox *typeGroup = new QGroupBox(mainGroup); + typeGroup->setTitle(tr("Gradient Type")); + m_linearButton = new QRadioButton(tr("Linear Gradient"), typeGroup); + m_radialButton = new QRadioButton(tr("Radial Gradient"), typeGroup); + m_conicalButton = new QRadioButton(tr("Conical Gradient"), typeGroup); + + QGroupBox *spreadGroup = new QGroupBox(mainGroup); + spreadGroup->setTitle(tr("Spread Method")); + m_padSpreadButton = new QRadioButton(tr("Pad Spread"), spreadGroup); + m_reflectSpreadButton = new QRadioButton(tr("Reflect Spread"), spreadGroup); + m_repeatSpreadButton = new QRadioButton(tr("Repeat Spread"), spreadGroup); + + QGroupBox *defaultsGroup = new QGroupBox(mainGroup); + defaultsGroup->setTitle(tr("Defaults")); + QPushButton *default1Button = new QPushButton(tr("1"), defaultsGroup); + QPushButton *default2Button = new QPushButton(tr("2"), defaultsGroup); + QPushButton *default3Button = new QPushButton(tr("3"), defaultsGroup); + QPushButton *default4Button = new QPushButton(tr("Reset"), editorGroup); + + QPushButton *showSourceButton = new QPushButton(mainGroup); + showSourceButton->setText(tr("Show Source")); +#ifdef QT_OPENGL_SUPPORT + QPushButton *enableOpenGLButton = new QPushButton(mainGroup); + enableOpenGLButton->setText(tr("Use OpenGL")); + enableOpenGLButton->setCheckable(true); + enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); + if (!QGLFormat::hasOpenGL()) + enableOpenGLButton->hide(); +#endif + QPushButton *whatsThisButton = new QPushButton(mainGroup); + whatsThisButton->setText(tr("What's This?")); + whatsThisButton->setCheckable(true); + + // Layouts + QHBoxLayout *mainLayout = new QHBoxLayout(this); + mainLayout->addWidget(m_renderer); + mainLayout->addWidget(mainGroup); + + mainGroup->setFixedWidth(180); + QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); + mainGroupLayout->addWidget(editorGroup); + mainGroupLayout->addWidget(typeGroup); + mainGroupLayout->addWidget(spreadGroup); + mainGroupLayout->addWidget(defaultsGroup); + mainGroupLayout->addStretch(1); + mainGroupLayout->addWidget(showSourceButton); +#ifdef QT_OPENGL_SUPPORT + mainGroupLayout->addWidget(enableOpenGLButton); +#endif + mainGroupLayout->addWidget(whatsThisButton); + + QVBoxLayout *editorGroupLayout = new QVBoxLayout(editorGroup); + editorGroupLayout->addWidget(m_editor); + + QVBoxLayout *typeGroupLayout = new QVBoxLayout(typeGroup); + typeGroupLayout->addWidget(m_linearButton); + typeGroupLayout->addWidget(m_radialButton); + typeGroupLayout->addWidget(m_conicalButton); + + QVBoxLayout *spreadGroupLayout = new QVBoxLayout(spreadGroup); + spreadGroupLayout->addWidget(m_padSpreadButton); + spreadGroupLayout->addWidget(m_repeatSpreadButton); + spreadGroupLayout->addWidget(m_reflectSpreadButton); + + QHBoxLayout *defaultsGroupLayout = new QHBoxLayout(defaultsGroup); + defaultsGroupLayout->addWidget(default1Button); + defaultsGroupLayout->addWidget(default2Button); + defaultsGroupLayout->addWidget(default3Button); + editorGroupLayout->addWidget(default4Button); + + connect(m_editor, SIGNAL(gradientStopsChanged(QGradientStops)), + m_renderer, SLOT(setGradientStops(QGradientStops))); + + connect(m_linearButton, SIGNAL(clicked()), m_renderer, SLOT(setLinearGradient())); + connect(m_radialButton, SIGNAL(clicked()), m_renderer, SLOT(setRadialGradient())); + connect(m_conicalButton, SIGNAL(clicked()), m_renderer, SLOT(setConicalGradient())); + + connect(m_padSpreadButton, SIGNAL(clicked()), m_renderer, SLOT(setPadSpread())); + connect(m_reflectSpreadButton, SIGNAL(clicked()), m_renderer, SLOT(setReflectSpread())); + connect(m_repeatSpreadButton, SIGNAL(clicked()), m_renderer, SLOT(setRepeatSpread())); + + connect(default1Button, SIGNAL(clicked()), this, SLOT(setDefault1())); + connect(default2Button, SIGNAL(clicked()), this, SLOT(setDefault2())); + connect(default3Button, SIGNAL(clicked()), this, SLOT(setDefault3())); + connect(default4Button, SIGNAL(clicked()), this, SLOT(setDefault4())); + + connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); +#ifdef QT_OPENGL_SUPPORT + connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); +#endif + connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); + connect(whatsThisButton, SIGNAL(clicked(bool)), + m_renderer->hoverPoints(), SLOT(setDisabled(bool))); + connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), + whatsThisButton, SLOT(setChecked(bool))); + connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), + m_renderer->hoverPoints(), SLOT(setDisabled(bool))); + + m_renderer->loadSourceFile(":res/gradients/gradients.cpp"); + m_renderer->loadDescription(":res/gradients/gradients.html"); + + QTimer::singleShot(50, this, SLOT(setDefault1())); +} + +void GradientWidget::setDefault(int config) +{ + QGradientStops stops; + QPolygonF points; + switch (config) { + case 1: + stops << QGradientStop(0.00, QColor::fromRgba(0)); + stops << QGradientStop(0.04, QColor::fromRgba(0xff131360)); + stops << QGradientStop(0.08, QColor::fromRgba(0xff202ccc)); + stops << QGradientStop(0.42, QColor::fromRgba(0xff93d3f9)); + stops << QGradientStop(0.51, QColor::fromRgba(0xffb3e6ff)); + stops << QGradientStop(0.73, QColor::fromRgba(0xffffffec)); + stops << QGradientStop(0.92, QColor::fromRgba(0xff5353d9)); + stops << QGradientStop(0.96, QColor::fromRgba(0xff262666)); + stops << QGradientStop(1.00, QColor::fromRgba(0)); + m_linearButton->animateClick(); + m_repeatSpreadButton->animateClick(); + break; + + case 2: + stops << QGradientStop(0.00, QColor::fromRgba(0xffffffff)); + stops << QGradientStop(0.11, QColor::fromRgba(0xfff9ffa0)); + stops << QGradientStop(0.13, QColor::fromRgba(0xfff9ff99)); + stops << QGradientStop(0.14, QColor::fromRgba(0xfff3ff86)); + stops << QGradientStop(0.49, QColor::fromRgba(0xff93b353)); + stops << QGradientStop(0.87, QColor::fromRgba(0xff264619)); + stops << QGradientStop(0.96, QColor::fromRgba(0xff0c1306)); + stops << QGradientStop(1.00, QColor::fromRgba(0)); + m_radialButton->animateClick(); + m_padSpreadButton->animateClick(); + break; + + case 3: + stops << QGradientStop(0.00, QColor::fromRgba(0)); + stops << QGradientStop(0.10, QColor::fromRgba(0xffe0cc73)); + stops << QGradientStop(0.17, QColor::fromRgba(0xffc6a006)); + stops << QGradientStop(0.46, QColor::fromRgba(0xff600659)); + stops << QGradientStop(0.72, QColor::fromRgba(0xff0680ac)); + stops << QGradientStop(0.92, QColor::fromRgba(0xffb9d9e6)); + stops << QGradientStop(1.00, QColor::fromRgba(0)); + m_conicalButton->animateClick(); + m_padSpreadButton->animateClick(); + break; + + case 4: + stops << QGradientStop(0.00, QColor::fromRgba(0xff000000)); + stops << QGradientStop(1.00, QColor::fromRgba(0xffffffff)); + break; + + default: + qWarning("bad default: %d\n", config); + break; + } + + QPolygonF pts; + int h_off = m_renderer->width() / 10; + int v_off = m_renderer->height() / 8; + pts << QPointF(m_renderer->width() / 2, m_renderer->height() / 2) + << QPointF(m_renderer->width() / 2 - h_off, m_renderer->height() / 2 - v_off); + + m_editor->setGradientStops(stops); + m_renderer->hoverPoints()->setPoints(pts); + m_renderer->setGradientStops(stops); +} + + +GradientRenderer::GradientRenderer(QWidget *parent) + : ArthurFrame(parent) +{ + m_hoverPoints = new HoverPoints(this, HoverPoints::CircleShape); + m_hoverPoints->setPointSize(QSize(20, 20)); + m_hoverPoints->setConnectionType(HoverPoints::NoConnection); + m_hoverPoints->setEditable(false); + + QVector points; + points << QPointF(100, 100) << QPointF(200, 200); + m_hoverPoints->setPoints(points); + + m_spread = QGradient::PadSpread; + m_gradientType = Qt::LinearGradientPattern; +} + +void GradientRenderer::setGradientStops(const QGradientStops &stops) +{ + m_stops = stops; + update(); +} + + +void GradientRenderer::mousePressEvent(QMouseEvent *) +{ + setDescriptionEnabled(false); +} + +void GradientRenderer::paint(QPainter *p) +{ + QPolygonF pts = m_hoverPoints->points(); + + QGradient g; + + if (m_gradientType == Qt::LinearGradientPattern) { + g = QLinearGradient(pts.at(0), pts.at(1)); + + } else if (m_gradientType == Qt::RadialGradientPattern) { + g = QRadialGradient(pts.at(0), qMin(width(), height()) / 3.0, pts.at(1)); + + } else { + QLineF l(pts.at(0), pts.at(1)); + qreal angle = l.angle(QLineF(0, 0, 1, 0)); + if (l.dy() > 0) + angle = 360 - angle; + g = QConicalGradient(pts.at(0), angle); + } + + for (int i=0; isetBrush(g); + p->setPen(Qt::NoPen); + + p->drawRect(rect()); + +} diff --git a/examples/painting/gradients/gradients.h b/examples/painting/gradients/gradients.h new file mode 100644 index 0000000000..e1a2bcb41e --- /dev/null +++ b/examples/painting/gradients/gradients.h @@ -0,0 +1,170 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GRADIENTS_H +#define GRADIENTS_H + +#include "arthurwidgets.h" + +#include + +class HoverPoints; + + +class ShadeWidget : public QWidget +{ + Q_OBJECT +public: + enum ShadeType { + RedShade, + GreenShade, + BlueShade, + ARGBShade + }; + + ShadeWidget(ShadeType type, QWidget *parent); + + void setGradientStops(const QGradientStops &stops); + + void paintEvent(QPaintEvent *e); + + QSize sizeHint() const { return QSize(150, 40); } + QPolygonF points() const; + + HoverPoints *hoverPoints() const { return m_hoverPoints; } + + uint colorAt(int x); + +signals: + void colorsChanged(); + +private: + void generateShade(); + + ShadeType m_shade_type; + QImage m_shade; + HoverPoints *m_hoverPoints; + QLinearGradient m_alpha_gradient; +}; + +class GradientEditor : public QWidget +{ + Q_OBJECT +public: + GradientEditor(QWidget *parent); + + void setGradientStops(const QGradientStops &stops); + +public slots: + void pointsUpdated(); + +signals: + void gradientStopsChanged(const QGradientStops &stops); + +private: + ShadeWidget *m_red_shade; + ShadeWidget *m_green_shade; + ShadeWidget *m_blue_shade; + ShadeWidget *m_alpha_shade; +}; + + +class GradientRenderer : public ArthurFrame +{ + Q_OBJECT +public: + GradientRenderer(QWidget *parent); + void paint(QPainter *p); + + QSize sizeHint() const { return QSize(400, 400); } + + HoverPoints *hoverPoints() const { return m_hoverPoints; } + void mousePressEvent(QMouseEvent *e); + +public slots: + void setGradientStops(const QGradientStops &stops); + + void setPadSpread() { m_spread = QGradient::PadSpread; update(); } + void setRepeatSpread() { m_spread = QGradient::RepeatSpread; update(); } + void setReflectSpread() { m_spread = QGradient::ReflectSpread; update(); } + + void setLinearGradient() { m_gradientType = Qt::LinearGradientPattern; update(); } + void setRadialGradient() { m_gradientType = Qt::RadialGradientPattern; update(); } + void setConicalGradient() { m_gradientType = Qt::ConicalGradientPattern; update(); } + + +private: + QGradientStops m_stops; + HoverPoints *m_hoverPoints; + + QGradient::Spread m_spread; + Qt::BrushStyle m_gradientType; +}; + + +class GradientWidget : public QWidget +{ + Q_OBJECT +public: + GradientWidget(QWidget *parent); + +public slots: + void setDefault1() { setDefault(1); } + void setDefault2() { setDefault(2); } + void setDefault3() { setDefault(3); } + void setDefault4() { setDefault(4); } + +private: + void setDefault(int i); + + GradientRenderer *m_renderer; + GradientEditor *m_editor; + + QRadioButton *m_linearButton; + QRadioButton *m_radialButton; + QRadioButton *m_conicalButton; + QRadioButton *m_padSpreadButton; + QRadioButton *m_reflectSpreadButton; + QRadioButton *m_repeatSpreadButton; + +}; + +#endif // GRADIENTS_H diff --git a/examples/painting/gradients/gradients.html b/examples/painting/gradients/gradients.html new file mode 100644 index 0000000000..1ea2c0ed6c --- /dev/null +++ b/examples/painting/gradients/gradients.html @@ -0,0 +1,31 @@ + +
      +

      Gradients

      +
      + +

      In this demo we show the various types of gradients that can +be used in Qt.

      + +

      There are three types of gradients: + +

        +
      • Linear gradients interpolate colors between start and end + points.
      • +
      • Radial gradients interpolate colors between a focal point and the + points on a circle surrounding it.
      • +
      • Conical gradients interpolate colors around a center point.
      • +
      + +

      + +

      The panel on the right contains a color table editor that defines +the colors in the gradient. The three topmost controls determine the red, +green and blue components while the last defines the alpha of the +gradient. You can move points, and add new ones, by clicking with the left +mouse button, and remove points by clicking with the right button.

      + +

      There are three default configurations available at the bottom of +the page that are provided as suggestions on how a color table could be +configured.

      + + diff --git a/examples/painting/gradients/gradients.pro b/examples/painting/gradients/gradients.pro new file mode 100644 index 0000000000..ed4120e01c --- /dev/null +++ b/examples/painting/gradients/gradients.pro @@ -0,0 +1,20 @@ +SOURCES += main.cpp gradients.cpp +HEADERS += gradients.h + +SHARED_FOLDER = ../shared + +include($$SHARED_FOLDER/shared.pri) + +RESOURCES += gradients.qrc +contains(QT_CONFIG, opengl) { + DEFINES += QT_OPENGL_SUPPORT + QT += opengl +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/gradients +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/gradients +INSTALLS += target sources + +symbian: CONFIG += qt_demo diff --git a/examples/painting/gradients/gradients.qrc b/examples/painting/gradients/gradients.qrc new file mode 100644 index 0000000000..fb971eb17b --- /dev/null +++ b/examples/painting/gradients/gradients.qrc @@ -0,0 +1,6 @@ + + + gradients.cpp + gradients.html + + diff --git a/examples/painting/gradients/main.cpp b/examples/painting/gradients/main.cpp new file mode 100644 index 0000000000..1d2f0d5775 --- /dev/null +++ b/examples/painting/gradients/main.cpp @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "gradients.h" + +#include + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(gradients); + + QApplication app(argc, argv); + + GradientWidget gradientWidget(0); + QStyle *arthurStyle = new ArthurStyle(); + gradientWidget.setStyle(arthurStyle); + QList widgets = gradientWidget.findChildren(); + foreach (QWidget *w, widgets) { + w->setStyle(arthurStyle); + w->setAttribute(Qt::WA_AcceptTouchEvents); + } + gradientWidget.show(); + + return app.exec(); +} diff --git a/examples/painting/pathstroke/main.cpp b/examples/painting/pathstroke/main.cpp new file mode 100644 index 0000000000..b357f99336 --- /dev/null +++ b/examples/painting/pathstroke/main.cpp @@ -0,0 +1,71 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "pathstroke.h" +#include + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(pathstroke); + + QApplication app(argc, argv); + + bool smallScreen = QApplication::arguments().contains("-small-screen"); + + PathStrokeWidget pathStrokeWidget(smallScreen); + QStyle *arthurStyle = new ArthurStyle(); + pathStrokeWidget.setStyle(arthurStyle); + QList widgets = pathStrokeWidget.findChildren(); + foreach (QWidget *w, widgets) { + w->setStyle(arthurStyle); + w->setAttribute(Qt::WA_AcceptTouchEvents); + } + + if (smallScreen) + pathStrokeWidget.showFullScreen(); + else + pathStrokeWidget.show(); + +#ifdef QT_KEYPAD_NAVIGATION + QApplication::setNavigationMode(Qt::NavigationModeCursorAuto); +#endif + return app.exec(); +} diff --git a/examples/painting/pathstroke/pathstroke.cpp b/examples/painting/pathstroke/pathstroke.cpp new file mode 100644 index 0000000000..02c35f7721 --- /dev/null +++ b/examples/painting/pathstroke/pathstroke.cpp @@ -0,0 +1,686 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "pathstroke.h" +#include "arthurstyle.h" +#include "arthurwidgets.h" + +#include + +extern void draw_round_rect(QPainter *p, const QRect &bounds, int radius); + + +PathStrokeControls::PathStrokeControls(QWidget* parent, PathStrokeRenderer* renderer, bool smallScreen) + : QWidget(parent) +{ + m_renderer = renderer; + + if (smallScreen) + layoutForSmallScreens(); + else + layoutForDesktop(); +} + +void PathStrokeControls::createCommonControls(QWidget* parent) +{ + m_capGroup = new QGroupBox(parent); + m_capGroup->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + QRadioButton *flatCap = new QRadioButton(m_capGroup); + QRadioButton *squareCap = new QRadioButton(m_capGroup); + QRadioButton *roundCap = new QRadioButton(m_capGroup); + m_capGroup->setTitle(tr("Cap Style")); + flatCap->setText(tr("Flat")); + squareCap->setText(tr("Square")); + roundCap->setText(tr("Round")); + flatCap->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + squareCap->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + roundCap->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + + m_joinGroup = new QGroupBox(parent); + m_joinGroup->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + QRadioButton *bevelJoin = new QRadioButton(m_joinGroup); + QRadioButton *miterJoin = new QRadioButton(m_joinGroup); + QRadioButton *roundJoin = new QRadioButton(m_joinGroup); + m_joinGroup->setTitle(tr("Join Style")); + bevelJoin->setText(tr("Bevel")); + miterJoin->setText(tr("Miter")); + roundJoin->setText(tr("Round")); + + m_styleGroup = new QGroupBox(parent); + m_styleGroup->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + QRadioButton *solidLine = new QRadioButton(m_styleGroup); + QRadioButton *dashLine = new QRadioButton(m_styleGroup); + QRadioButton *dotLine = new QRadioButton(m_styleGroup); + QRadioButton *dashDotLine = new QRadioButton(m_styleGroup); + QRadioButton *dashDotDotLine = new QRadioButton(m_styleGroup); + QRadioButton *customDashLine = new QRadioButton(m_styleGroup); + m_styleGroup->setTitle(tr("Pen Style")); + + QPixmap line_solid(":res/images/line_solid.png"); + solidLine->setIcon(line_solid); + solidLine->setIconSize(line_solid.size()); + QPixmap line_dashed(":res/images/line_dashed.png"); + dashLine->setIcon(line_dashed); + dashLine->setIconSize(line_dashed.size()); + QPixmap line_dotted(":res/images/line_dotted.png"); + dotLine->setIcon(line_dotted); + dotLine->setIconSize(line_dotted.size()); + QPixmap line_dash_dot(":res/images/line_dash_dot.png"); + dashDotLine->setIcon(line_dash_dot); + dashDotLine->setIconSize(line_dash_dot.size()); + QPixmap line_dash_dot_dot(":res/images/line_dash_dot_dot.png"); + dashDotDotLine->setIcon(line_dash_dot_dot); + dashDotDotLine->setIconSize(line_dash_dot_dot.size()); + customDashLine->setText(tr("Custom")); + + int fixedHeight = bevelJoin->sizeHint().height(); + solidLine->setFixedHeight(fixedHeight); + dashLine->setFixedHeight(fixedHeight); + dotLine->setFixedHeight(fixedHeight); + dashDotLine->setFixedHeight(fixedHeight); + dashDotDotLine->setFixedHeight(fixedHeight); + + m_pathModeGroup = new QGroupBox(parent); + m_pathModeGroup->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + QRadioButton *curveMode = new QRadioButton(m_pathModeGroup); + QRadioButton *lineMode = new QRadioButton(m_pathModeGroup); + m_pathModeGroup->setTitle(tr("Line Style")); + curveMode->setText(tr("Curves")); + lineMode->setText(tr("Lines")); + + + // Layouts + QVBoxLayout *capGroupLayout = new QVBoxLayout(m_capGroup); + capGroupLayout->addWidget(flatCap); + capGroupLayout->addWidget(squareCap); + capGroupLayout->addWidget(roundCap); + + QVBoxLayout *joinGroupLayout = new QVBoxLayout(m_joinGroup); + joinGroupLayout->addWidget(bevelJoin); + joinGroupLayout->addWidget(miterJoin); + joinGroupLayout->addWidget(roundJoin); + + QVBoxLayout *styleGroupLayout = new QVBoxLayout(m_styleGroup); + styleGroupLayout->addWidget(solidLine); + styleGroupLayout->addWidget(dashLine); + styleGroupLayout->addWidget(dotLine); + styleGroupLayout->addWidget(dashDotLine); + styleGroupLayout->addWidget(dashDotDotLine); + styleGroupLayout->addWidget(customDashLine); + + QVBoxLayout *pathModeGroupLayout = new QVBoxLayout(m_pathModeGroup); + pathModeGroupLayout->addWidget(curveMode); + pathModeGroupLayout->addWidget(lineMode); + + + // Connections + connect(flatCap, SIGNAL(clicked()), m_renderer, SLOT(setFlatCap())); + connect(squareCap, SIGNAL(clicked()), m_renderer, SLOT(setSquareCap())); + connect(roundCap, SIGNAL(clicked()), m_renderer, SLOT(setRoundCap())); + + connect(bevelJoin, SIGNAL(clicked()), m_renderer, SLOT(setBevelJoin())); + connect(miterJoin, SIGNAL(clicked()), m_renderer, SLOT(setMiterJoin())); + connect(roundJoin, SIGNAL(clicked()), m_renderer, SLOT(setRoundJoin())); + + connect(curveMode, SIGNAL(clicked()), m_renderer, SLOT(setCurveMode())); + connect(lineMode, SIGNAL(clicked()), m_renderer, SLOT(setLineMode())); + + connect(solidLine, SIGNAL(clicked()), m_renderer, SLOT(setSolidLine())); + connect(dashLine, SIGNAL(clicked()), m_renderer, SLOT(setDashLine())); + connect(dotLine, SIGNAL(clicked()), m_renderer, SLOT(setDotLine())); + connect(dashDotLine, SIGNAL(clicked()), m_renderer, SLOT(setDashDotLine())); + connect(dashDotDotLine, SIGNAL(clicked()), m_renderer, SLOT(setDashDotDotLine())); + connect(customDashLine, SIGNAL(clicked()), m_renderer, SLOT(setCustomDashLine())); + + // Set the defaults: + flatCap->setChecked(true); + bevelJoin->setChecked(true); + curveMode->setChecked(true); + solidLine->setChecked(true); +} + + +void PathStrokeControls::layoutForDesktop() +{ + QGroupBox *mainGroup = new QGroupBox(this); + mainGroup->setFixedWidth(180); + mainGroup->setTitle(tr("Path Stroking")); + + createCommonControls(mainGroup); + + QGroupBox* penWidthGroup = new QGroupBox(mainGroup); + QSlider *penWidth = new QSlider(Qt::Horizontal, penWidthGroup); + penWidth->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + penWidthGroup->setTitle(tr("Pen Width")); + penWidth->setRange(0, 500); + + QPushButton *animated = new QPushButton(mainGroup); + animated->setText(tr("Animate")); + animated->setCheckable(true); + + QPushButton *showSourceButton = new QPushButton(mainGroup); + showSourceButton->setText(tr("Show Source")); +#ifdef QT_OPENGL_SUPPORT + QPushButton *enableOpenGLButton = new QPushButton(mainGroup); + enableOpenGLButton->setText(tr("Use OpenGL")); + enableOpenGLButton->setCheckable(true); + enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); + if (!QGLFormat::hasOpenGL()) + enableOpenGLButton->hide(); +#endif + QPushButton *whatsThisButton = new QPushButton(mainGroup); + whatsThisButton->setText(tr("What's This?")); + whatsThisButton->setCheckable(true); + + + // Layouts: + QVBoxLayout *penWidthLayout = new QVBoxLayout(penWidthGroup); + penWidthLayout->addWidget(penWidth); + + QVBoxLayout * mainLayout = new QVBoxLayout(this); + mainLayout->setMargin(0); + mainLayout->addWidget(mainGroup); + + QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); + mainGroupLayout->setMargin(3); + mainGroupLayout->addWidget(m_capGroup); + mainGroupLayout->addWidget(m_joinGroup); + mainGroupLayout->addWidget(m_styleGroup); + mainGroupLayout->addWidget(penWidthGroup); + mainGroupLayout->addWidget(m_pathModeGroup); + mainGroupLayout->addWidget(animated); + mainGroupLayout->addStretch(1); + mainGroupLayout->addWidget(showSourceButton); +#ifdef QT_OPENGL_SUPPORT + mainGroupLayout->addWidget(enableOpenGLButton); +#endif + mainGroupLayout->addWidget(whatsThisButton); + + + // Set up connections + connect(animated, SIGNAL(toggled(bool)), + m_renderer, SLOT(setAnimation(bool))); + + connect(penWidth, SIGNAL(valueChanged(int)), + m_renderer, SLOT(setPenWidth(int))); + + connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); +#ifdef QT_OPENGL_SUPPORT + connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); +#endif + connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); + connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), + whatsThisButton, SLOT(setChecked(bool))); + + + // Set the defaults + animated->setChecked(true); + penWidth->setValue(50); + +} + +void PathStrokeControls::layoutForSmallScreens() +{ + createCommonControls(this); + + m_capGroup->layout()->setMargin(0); + m_joinGroup->layout()->setMargin(0); + m_styleGroup->layout()->setMargin(0); + m_pathModeGroup->layout()->setMargin(0); + + QPushButton* okBtn = new QPushButton(tr("OK"), this); + okBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + okBtn->setMinimumSize(100,okBtn->minimumSize().height()); + + QPushButton* quitBtn = new QPushButton(tr("Quit"), this); + quitBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + quitBtn->setMinimumSize(100, okBtn->minimumSize().height()); + + QLabel *penWidthLabel = new QLabel(tr(" Width:")); + QSlider *penWidth = new QSlider(Qt::Horizontal, this); + penWidth->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + penWidth->setRange(0, 500); + +#ifdef QT_OPENGL_SUPPORT + QPushButton *enableOpenGLButton = new QPushButton(this); + enableOpenGLButton->setText(tr("Use OpenGL")); + enableOpenGLButton->setCheckable(true); + enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); + if (!QGLFormat::hasOpenGL()) + enableOpenGLButton->hide(); +#endif + + // Layouts: + QHBoxLayout *penWidthLayout = new QHBoxLayout(0); + penWidthLayout->addWidget(penWidthLabel, 0, Qt::AlignRight); + penWidthLayout->addWidget(penWidth); + + QVBoxLayout *leftLayout = new QVBoxLayout(0); + leftLayout->addWidget(m_capGroup); + leftLayout->addWidget(m_joinGroup); +#ifdef QT_OPENGL_SUPPORT + leftLayout->addWidget(enableOpenGLButton); +#endif + leftLayout->addLayout(penWidthLayout); + + QVBoxLayout *rightLayout = new QVBoxLayout(0); + rightLayout->addWidget(m_styleGroup); + rightLayout->addWidget(m_pathModeGroup); + + QGridLayout *mainLayout = new QGridLayout(this); + mainLayout->setMargin(0); + + // Add spacers around the form items so we don't look stupid at higher resolutions + mainLayout->addItem(new QSpacerItem(0,0), 0, 0, 1, 4); + mainLayout->addItem(new QSpacerItem(0,0), 1, 0, 2, 1); + mainLayout->addItem(new QSpacerItem(0,0), 1, 3, 2, 1); + mainLayout->addItem(new QSpacerItem(0,0), 3, 0, 1, 4); + + mainLayout->addLayout(leftLayout, 1, 1); + mainLayout->addLayout(rightLayout, 1, 2); + mainLayout->addWidget(quitBtn, 2, 1, Qt::AlignHCenter | Qt::AlignTop); + mainLayout->addWidget(okBtn, 2, 2, Qt::AlignHCenter | Qt::AlignTop); + +#ifdef QT_OPENGL_SUPPORT + connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); +#endif + + connect(penWidth, SIGNAL(valueChanged(int)), m_renderer, SLOT(setPenWidth(int))); + connect(quitBtn, SIGNAL(clicked()), this, SLOT(emitQuitSignal())); + connect(okBtn, SIGNAL(clicked()), this, SLOT(emitOkSignal())); + + m_renderer->setAnimation(true); + penWidth->setValue(50); +} + +void PathStrokeControls::emitQuitSignal() +{ emit quitPressed(); } + +void PathStrokeControls::emitOkSignal() +{ emit okPressed(); } + + +PathStrokeWidget::PathStrokeWidget(bool smallScreen) +{ + setWindowTitle(tr("Path Stroking")); + + // Widget construction and property setting + m_renderer = new PathStrokeRenderer(this, smallScreen); + + m_controls = new PathStrokeControls(0, m_renderer, smallScreen); + + // Layouting + QHBoxLayout *viewLayout = new QHBoxLayout(this); + viewLayout->addWidget(m_renderer); + + if (!smallScreen) + viewLayout->addWidget(m_controls); + + m_renderer->loadSourceFile(":res/pathstroke/pathstroke.cpp"); + m_renderer->loadDescription(":res/pathstroke/pathstroke.html"); + + connect(m_renderer, SIGNAL(clicked()), this, SLOT(showControls())); + connect(m_controls, SIGNAL(okPressed()), this, SLOT(hideControls())); + connect(m_controls, SIGNAL(quitPressed()), QApplication::instance(), SLOT(quit())); +} + + +void PathStrokeWidget::showControls() +{ + m_controls->showFullScreen(); +} + + +void PathStrokeWidget::hideControls() +{ + m_controls->hide(); +} + + +void PathStrokeWidget::setStyle( QStyle * style ) +{ + QWidget::setStyle(style); + if (m_controls != 0) + { + m_controls->setStyle(style); + + QList widgets = m_controls->findChildren(); + foreach (QWidget *w, widgets) + w->setStyle(style); + } +} + + +PathStrokeRenderer::PathStrokeRenderer(QWidget *parent, bool smallScreen) + : ArthurFrame(parent) +{ + m_smallScreen = smallScreen; + m_pointSize = 10; + m_activePoint = -1; + m_capStyle = Qt::FlatCap; + m_joinStyle = Qt::BevelJoin; + m_pathMode = CurveMode; + m_penWidth = 1; + m_penStyle = Qt::SolidLine; + m_wasAnimated = true; + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + setAttribute(Qt::WA_AcceptTouchEvents); +} + +void PathStrokeRenderer::paint(QPainter *painter) +{ + if (m_points.isEmpty()) + initializePoints(); + + painter->setRenderHint(QPainter::Antialiasing); + + QPalette pal = palette(); + painter->setPen(Qt::NoPen); + + // Construct the path + QPainterPath path; + path.moveTo(m_points.at(0)); + + if (m_pathMode == LineMode) { + for (int i=1; i dashes; + qreal space = 4; + dashes << 1 << space + << 3 << space + << 9 << space + << 27 << space + << 9 << space + << 3 << space; + stroker.setDashPattern(dashes); + QPainterPath stroke = stroker.createStroke(path); + painter->fillPath(stroke, lg); + + } else { + QPen pen(lg, m_penWidth, m_penStyle, m_capStyle, m_joinStyle); + painter->strokePath(path, pen); + } + } + + if (1) { + // Draw the control points + painter->setPen(QColor(50, 100, 120, 200)); + painter->setBrush(QColor(200, 200, 210, 120)); + for (int i=0; idrawEllipse(QRectF(pos.x() - m_pointSize, + pos.y() - m_pointSize, + m_pointSize*2, m_pointSize*2)); + } + painter->setPen(QPen(Qt::lightGray, 0, Qt::SolidLine)); + painter->setBrush(Qt::NoBrush); + painter->drawPolyline(m_points); + } + +} + +void PathStrokeRenderer::initializePoints() +{ + const int count = 7; + m_points.clear(); + m_vectors.clear(); + + QMatrix m; + qreal rot = 360 / count; + QPointF center(width() / 2, height() / 2); + QMatrix vm; + vm.shear(2, -1); + vm.scale(3, 3); + + for (int i=0; i right) { + vec.setX(-vec.x()); + pos.setX(pos.x() < left ? left : right); + } if (pos.y() < top || pos.y() > bottom) { + vec.setY(-vec.y()); + pos.setY(pos.y() < top ? top : bottom); + } + m_points[i] = pos; + m_vectors[i] = vec; + } + update(); +} + +void PathStrokeRenderer::mousePressEvent(QMouseEvent *e) +{ + if (!m_fingerPointMapping.isEmpty()) + return; + setDescriptionEnabled(false); + m_activePoint = -1; + qreal distance = -1; + for (int i=0; ipos(), m_points.at(i)).length(); + if ((distance < 0 && d < 8 * m_pointSize) || d < distance) { + distance = d; + m_activePoint = i; + } + } + + if (m_activePoint != -1) { + m_wasAnimated = m_timer.isActive(); + setAnimation(false); + mouseMoveEvent(e); + } + + // If we're not running in small screen mode, always assume we're dragging + m_mouseDrag = !m_smallScreen; + m_mousePress = e->pos(); +} + +void PathStrokeRenderer::mouseMoveEvent(QMouseEvent *e) +{ + if (!m_fingerPointMapping.isEmpty()) + return; + // If we've moved more then 25 pixels, assume user is dragging + if (!m_mouseDrag && QPoint(m_mousePress - e->pos()).manhattanLength() > 25) + m_mouseDrag = true; + + if (m_mouseDrag && m_activePoint >= 0 && m_activePoint < m_points.size()) { + m_points[m_activePoint] = e->pos(); + update(); + } +} + +void PathStrokeRenderer::mouseReleaseEvent(QMouseEvent *) +{ + if (!m_fingerPointMapping.isEmpty()) + return; + m_activePoint = -1; + setAnimation(m_wasAnimated); + + if (!m_mouseDrag && m_smallScreen) + emit clicked(); +} + +void PathStrokeRenderer::timerEvent(QTimerEvent *e) +{ + if (e->timerId() == m_timer.timerId()) { + updatePoints(); + QApplication::syncX(); + } // else if (e->timerId() == m_fpsTimer.timerId()) { +// emit frameRate(m_frameCount); +// m_frameCount = 0; +// } +} + +bool PathStrokeRenderer::event(QEvent *e) +{ + bool touchBegin = false; + switch (e->type()) { + case QEvent::TouchBegin: + touchBegin = true; + case QEvent::TouchUpdate: + { + const QTouchEvent *const event = static_cast(e); + const QList points = event->touchPoints(); + foreach (const QTouchEvent::TouchPoint &touchPoint, points) { + const int id = touchPoint.id(); + switch (touchPoint.state()) { + case Qt::TouchPointPressed: + { + // find the point, move it + QSet activePoints = QSet::fromList(m_fingerPointMapping.values()); + int activePoint = -1; + qreal distance = -1; + const int pointsCount = m_points.size(); + for (int i=0; i::iterator it = m_fingerPointMapping.find(id); + m_points[it.value()] = touchPoint.pos(); + m_fingerPointMapping.erase(it); + } + break; + case Qt::TouchPointMoved: + { + // move the point + const int pointIdx = m_fingerPointMapping.value(id, -1); + if (pointIdx >= 0) + m_points[pointIdx] = touchPoint.pos(); + } + break; + default: + break; + } + } + if (m_fingerPointMapping.isEmpty()) { + e->ignore(); + return false; + } else { + if (touchBegin) { + m_wasAnimated = m_timer.isActive(); + setAnimation(false); + } + update(); + return true; + } + } + break; + case QEvent::TouchEnd: + if (m_fingerPointMapping.isEmpty()) { + e->ignore(); + return false; + } + m_fingerPointMapping.clear(); + setAnimation(m_wasAnimated); + return true; + break; + default: + break; + } + return QWidget::event(e); +} + +void PathStrokeRenderer::setAnimation(bool animation) +{ + m_timer.stop(); +// m_fpsTimer.stop(); + + if (animation) { + m_timer.start(25, this); +// m_fpsTimer.start(1000, this); +// m_frameCount = 0; + } +} diff --git a/examples/painting/pathstroke/pathstroke.h b/examples/painting/pathstroke/pathstroke.h new file mode 100644 index 0000000000..f0360b6648 --- /dev/null +++ b/examples/painting/pathstroke/pathstroke.h @@ -0,0 +1,171 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PATHSTROKE_H +#define PATHSTROKE_H + +#include "arthurwidgets.h" +#include + +class PathStrokeRenderer : public ArthurFrame +{ + Q_OBJECT + Q_PROPERTY(bool animation READ animation WRITE setAnimation) + Q_PROPERTY(qreal penWidth READ realPenWidth WRITE setRealPenWidth) +public: + enum PathMode { CurveMode, LineMode }; + + PathStrokeRenderer(QWidget *parent, bool smallScreen = false); + + void paint(QPainter *); + void mousePressEvent(QMouseEvent *e); + void mouseMoveEvent(QMouseEvent *e); + void mouseReleaseEvent(QMouseEvent *e); + void timerEvent(QTimerEvent *e); + bool event(QEvent *e); + + QSize sizeHint() const { return QSize(500, 500); } + + bool animation() const { return m_timer.isActive(); } + + qreal realPenWidth() const { return m_penWidth; } + void setRealPenWidth(qreal penWidth) { m_penWidth = penWidth; update(); } + +signals: + void clicked(); + +public slots: + void setPenWidth(int penWidth) { m_penWidth = penWidth / 10.0; update(); } + void setAnimation(bool animation); + + void setFlatCap() { m_capStyle = Qt::FlatCap; update(); } + void setSquareCap() { m_capStyle = Qt::SquareCap; update(); } + void setRoundCap() { m_capStyle = Qt::RoundCap; update(); } + + void setBevelJoin() { m_joinStyle = Qt::BevelJoin; update(); } + void setMiterJoin() { m_joinStyle = Qt::MiterJoin; update(); } + void setRoundJoin() { m_joinStyle = Qt::RoundJoin; update(); } + + void setCurveMode() { m_pathMode = CurveMode; update(); } + void setLineMode() { m_pathMode = LineMode; update(); } + + void setSolidLine() { m_penStyle = Qt::SolidLine; update(); } + void setDashLine() { m_penStyle = Qt::DashLine; update(); } + void setDotLine() { m_penStyle = Qt::DotLine; update(); } + void setDashDotLine() { m_penStyle = Qt::DashDotLine; update(); } + void setDashDotDotLine() { m_penStyle = Qt::DashDotDotLine; update(); } + void setCustomDashLine() { m_penStyle = Qt::NoPen; update(); } + +private: + void initializePoints(); + void updatePoints(); + + QBasicTimer m_timer; + + PathMode m_pathMode; + + bool m_wasAnimated; + + qreal m_penWidth; + int m_pointCount; + int m_pointSize; + int m_activePoint; + QVector m_points; + QVector m_vectors; + + Qt::PenJoinStyle m_joinStyle; + Qt::PenCapStyle m_capStyle; + + Qt::PenStyle m_penStyle; + + bool m_smallScreen; + QPoint m_mousePress; + bool m_mouseDrag; + + QHash m_fingerPointMapping; +}; + +class PathStrokeControls : public QWidget +{ + Q_OBJECT +public: + PathStrokeControls(QWidget* parent, PathStrokeRenderer* renderer, bool smallScreen); + +signals: + void okPressed(); + void quitPressed(); + +private: + PathStrokeRenderer* m_renderer; + + QGroupBox *m_capGroup; + QGroupBox *m_joinGroup; + QGroupBox *m_styleGroup; + QGroupBox *m_pathModeGroup; + + void createCommonControls(QWidget* parent); + void layoutForDesktop(); + void layoutForSmallScreens(); + +private slots: + void emitQuitSignal(); + void emitOkSignal(); + +}; + +class PathStrokeWidget : public QWidget +{ + Q_OBJECT +public: + PathStrokeWidget(bool smallScreen); + void setStyle ( QStyle * style ); + +private: + PathStrokeRenderer *m_renderer; + PathStrokeControls *m_controls; + +private slots: + void showControls(); + void hideControls(); + +}; + +#endif // PATHSTROKE_H diff --git a/examples/painting/pathstroke/pathstroke.html b/examples/painting/pathstroke/pathstroke.html new file mode 100644 index 0000000000..9e7e50de76 --- /dev/null +++ b/examples/painting/pathstroke/pathstroke.html @@ -0,0 +1,20 @@ + +
      +

      Primitive Stroking

      +
      + +

      In this demo we show some of the various types of pens that can be +used in Qt.

      + +

      Qt defines cap styles for how the end points are treated and join +styles for how path segments are joined together. A standard set of +predefined dash patterns are also included that can be used with +QPen.

      + +

      In addition to the predefined patterns available in +QPen we also demonstrate direct use of the +QPainterPathStroker class which can be used to define +custom dash patterns. You can see this by enabling the +Custom Pattern option.

      + + diff --git a/examples/painting/pathstroke/pathstroke.pro b/examples/painting/pathstroke/pathstroke.pro new file mode 100644 index 0000000000..9bbf8a6f77 --- /dev/null +++ b/examples/painting/pathstroke/pathstroke.pro @@ -0,0 +1,24 @@ +SOURCES += main.cpp pathstroke.cpp +HEADERS += pathstroke.h + +SHARED_FOLDER = ../shared + +include($$SHARED_FOLDER/shared.pri) + +RESOURCES += pathstroke.qrc + +contains(QT_CONFIG, opengl) { + DEFINES += QT_OPENGL_SUPPORT + QT += opengl +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/pathstroke +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/pathstroke +INSTALLS += target sources + +symbian { + TARGET.UID3 = 0xA000A63E + CONFIG += qt_demo +} diff --git a/examples/painting/pathstroke/pathstroke.qrc b/examples/painting/pathstroke/pathstroke.qrc new file mode 100644 index 0000000000..a9a723409e --- /dev/null +++ b/examples/painting/pathstroke/pathstroke.qrc @@ -0,0 +1,6 @@ + + + pathstroke.cpp + pathstroke.html + + diff --git a/examples/painting/shared/arthurstyle.cpp b/examples/painting/shared/arthurstyle.cpp new file mode 100644 index 0000000000..432b8b34e5 --- /dev/null +++ b/examples/painting/shared/arthurstyle.cpp @@ -0,0 +1,452 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "arthurstyle.h" +#include "arthurwidgets.h" +#include +#include +#include +#include +#include +#include +#include +#include + +QPixmap cached(const QString &img) +{ + if (QPixmap *p = QPixmapCache::find(img)) + return *p; + + QPixmap pm; + pm = QPixmap::fromImage(QImage(img), Qt::OrderedDither | Qt::OrderedAlphaDither); + if (pm.isNull()) + return QPixmap(); + + QPixmapCache::insert(img, pm); + return pm; +} + + +ArthurStyle::ArthurStyle() + : QWindowsStyle() +{ + Q_INIT_RESOURCE(shared); +} + + +void ArthurStyle::drawHoverRect(QPainter *painter, const QRect &r) const +{ + qreal h = r.height(); + qreal h2 = r.height() / qreal(2); + QPainterPath path; + path.addRect(r.x() + h2, r.y() + 0, r.width() - h2 * 2, r.height()); + path.addEllipse(r.x(), r.y(), h, h); + path.addEllipse(r.x() + r.width() - h, r.y(), h, h); + path.setFillRule(Qt::WindingFill); + painter->setPen(Qt::NoPen); + painter->setBrush(QColor(191, 215, 191)); + painter->setRenderHint(QPainter::Antialiasing); + painter->drawPath(path); +} + + +void ArthurStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, + QPainter *painter, const QWidget *widget) const +{ + + Q_ASSERT(option); + switch (element) { + case PE_FrameFocusRect: + break; + + case PE_IndicatorRadioButton: + if (const QStyleOptionButton *button = qstyleoption_cast(option)) { + bool hover = (button->state & State_Enabled) && (button->state & State_MouseOver); + painter->save(); + QPixmap radio; + if (hover) + drawHoverRect(painter, widget->rect()); + + if (button->state & State_Sunken) + radio = cached(":res/images/radiobutton-on.png"); + else if (button->state & State_On) + radio = cached(":res/images/radiobutton_on.png"); + else + radio = cached(":res/images/radiobutton_off.png"); + painter->drawPixmap(button->rect.topLeft(), radio); + + painter->restore(); + } + break; + + case PE_PanelButtonCommand: + if (const QStyleOptionButton *button = qstyleoption_cast(option)) { + bool hover = (button->state & State_Enabled) && (button->state & State_MouseOver); + + painter->save(); + const QPushButton *pushButton = qobject_cast(widget); + Q_ASSERT(pushButton); + QWidget *parent = pushButton->parentWidget(); + if (parent && qobject_cast(parent)) { + QLinearGradient lg(0, 0, 0, parent->height()); + lg.setColorAt(0, QColor(224,224,224)); + lg.setColorAt(1, QColor(255,255,255)); + painter->setPen(Qt::NoPen); + painter->setBrush(lg); + painter->setBrushOrigin(-widget->mapToParent(QPoint(0,0))); + painter->drawRect(button->rect); + painter->setBrushOrigin(0,0); + } + + bool down = (button->state & State_Sunken) || (button->state & State_On); + + QPixmap left, right, mid; + if (down) { + left = cached(":res/images/button_pressed_cap_left.png"); + right = cached(":res/images/button_pressed_cap_right.png"); + mid = cached(":res/images/button_pressed_stretch.png"); + } else { + left = cached(":res/images/button_normal_cap_left.png"); + right = cached(":res/images/button_normal_cap_right.png"); + mid = cached(":res/images/button_normal_stretch.png"); + } + painter->drawPixmap(button->rect.topLeft(), left); + painter->drawTiledPixmap(QRect(button->rect.x() + left.width(), + button->rect.y(), + button->rect.width() - left.width() - right.width(), + left.height()), + mid); + painter->drawPixmap(button->rect.x() + button->rect.width() - right.width(), + button->rect.y(), + right); + if (hover) + painter->fillRect(widget->rect().adjusted(3,5,-3,-5), QColor(31,127,31,63)); + painter->restore(); + } + break; + + case PE_FrameGroupBox: + if (const QStyleOptionFrameV2 *group + = qstyleoption_cast(option)) { + const QRect &r = group->rect; + + painter->save(); + int radius = 14; + int radius2 = radius*2; + QPainterPath clipPath; + clipPath.moveTo(radius, 0); + clipPath.arcTo(r.right() - radius2, 0, radius2, radius2, 90, -90); + clipPath.arcTo(r.right() - radius2, r.bottom() - radius2, radius2, radius2, 0, -90); + clipPath.arcTo(r.left(), r.bottom() - radius2, radius2, radius2, 270, -90); + clipPath.arcTo(r.left(), r.top(), radius2, radius2, 180, -90); + painter->setClipPath(clipPath); + QPixmap titleStretch = cached(":res/images/title_stretch.png"); + QPixmap topLeft = cached(":res/images/groupframe_topleft.png"); + QPixmap topRight = cached(":res/images/groupframe_topright.png"); + QPixmap bottomLeft = cached(":res/images/groupframe_bottom_left.png"); + QPixmap bottomRight = cached(":res/images/groupframe_bottom_right.png"); + QPixmap leftStretch = cached(":res/images/groupframe_left_stretch.png"); + QPixmap topStretch = cached(":res/images/groupframe_top_stretch.png"); + QPixmap rightStretch = cached(":res/images/groupframe_right_stretch.png"); + QPixmap bottomStretch = cached(":res/images/groupframe_bottom_stretch.png"); + QLinearGradient lg(0, 0, 0, r.height()); + lg.setColorAt(0, QColor(224,224,224)); + lg.setColorAt(1, QColor(255,255,255)); + painter->setPen(Qt::NoPen); + painter->setBrush(lg); + painter->drawRect(r.adjusted(0, titleStretch.height()/2, 0, 0)); + painter->setClipping(false); + + int topFrameOffset = titleStretch.height()/2 - 2; + painter->drawPixmap(r.topLeft() + QPoint(0, topFrameOffset), topLeft); + painter->drawPixmap(r.topRight() - QPoint(topRight.width()-1, 0) + + QPoint(0, topFrameOffset), topRight); + painter->drawPixmap(r.bottomLeft() - QPoint(0, bottomLeft.height()-1), bottomLeft); + painter->drawPixmap(r.bottomRight() - QPoint(bottomRight.width()-1, + bottomRight.height()-1), bottomRight); + + QRect left = r; + left.setY(r.y() + topLeft.height() + topFrameOffset); + left.setWidth(leftStretch.width()); + left.setHeight(r.height() - topLeft.height() - bottomLeft.height() - topFrameOffset); + painter->drawTiledPixmap(left, leftStretch); + + QRect top = r; + top.setX(r.x() + topLeft.width()); + top.setY(r.y() + topFrameOffset); + top.setWidth(r.width() - topLeft.width() - topRight.width()); + top.setHeight(topLeft.height()); + painter->drawTiledPixmap(top, topStretch); + + QRect right = r; + right.setX(r.right() - rightStretch.width()+1); + right.setY(r.y() + topRight.height() + topFrameOffset); + right.setWidth(rightStretch.width()); + right.setHeight(r.height() - topRight.height() + - bottomRight.height() - topFrameOffset); + painter->drawTiledPixmap(right, rightStretch); + + QRect bottom = r; + bottom.setX(r.x() + bottomLeft.width()); + bottom.setY(r.bottom() - bottomStretch.height()+1); + bottom.setWidth(r.width() - bottomLeft.width() - bottomRight.width()); + bottom.setHeight(bottomLeft.height()); + painter->drawTiledPixmap(bottom, bottomStretch); + painter->restore(); + } + break; + + default: + QWindowsStyle::drawPrimitive(element, option, painter, widget); + break; + } + return; +} + + +void ArthurStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, + QPainter *painter, const QWidget *widget) const +{ + switch (control) { + case CC_Slider: + if (const QStyleOptionSlider *slider = qstyleoption_cast(option)) { + QRect groove = subControlRect(CC_Slider, option, SC_SliderGroove, widget); + QRect handle = subControlRect(CC_Slider, option, SC_SliderHandle, widget); + + painter->save(); + + bool hover = (slider->state & State_Enabled) && (slider->state & State_MouseOver); + if (hover) { + QRect moderated = widget->rect().adjusted(0, 4, 0, -4); + drawHoverRect(painter, moderated); + } + + if ((option->subControls & SC_SliderGroove) && groove.isValid()) { + QPixmap grv = cached(":res/images/slider_bar.png"); + painter->drawPixmap(QRect(groove.x() + 5, groove.y(), + groove.width() - 10, grv.height()), + grv); + } + if ((option->subControls & SC_SliderHandle) && handle.isValid()) { + QPixmap hndl = cached(":res/images/slider_thumb_on.png"); + painter->drawPixmap(handle.topLeft(), hndl); + } + + painter->restore(); + } + break; + case CC_GroupBox: + if (const QStyleOptionGroupBox *groupBox + = qstyleoption_cast(option)) { + QStyleOptionGroupBox groupBoxCopy(*groupBox); + groupBoxCopy.subControls &= ~SC_GroupBoxLabel; + QWindowsStyle::drawComplexControl(control, &groupBoxCopy, painter, widget); + + if (groupBox->subControls & SC_GroupBoxLabel) { + const QRect &r = groupBox->rect; + QPixmap titleLeft = cached(":res/images/title_cap_left.png"); + QPixmap titleRight = cached(":res/images/title_cap_right.png"); + QPixmap titleStretch = cached(":res/images/title_stretch.png"); + int txt_width = groupBox->fontMetrics.width(groupBox->text) + 20; + painter->drawPixmap(r.center().x() - txt_width/2, 0, titleLeft); + QRect tileRect = subControlRect(control, groupBox, SC_GroupBoxLabel, widget); + painter->drawTiledPixmap(tileRect, titleStretch); + painter->drawPixmap(tileRect.x() + tileRect.width(), 0, titleRight); + int opacity = 31; + painter->setPen(QColor(0, 0, 0, opacity)); + painter->drawText(tileRect.translated(0, 1), + Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text); + painter->drawText(tileRect.translated(2, 1), + Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text); + painter->setPen(QColor(0, 0, 0, opacity * 2)); + painter->drawText(tileRect.translated(1, 1), + Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text); + painter->setPen(Qt::white); + painter->drawText(tileRect, Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text); + } + } + break; + default: + QWindowsStyle::drawComplexControl(control, option, painter, widget); + break; + } + return; +} + +QRect ArthurStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option, + SubControl subControl, const QWidget *widget) const +{ + QRect rect; + + switch (control) { + default: + rect = QWindowsStyle::subControlRect(control, option, subControl, widget); + break; + case CC_GroupBox: + if (const QStyleOptionGroupBox *group + = qstyleoption_cast(option)) { + switch (subControl) { + default: + rect = QWindowsStyle::subControlRect(control, option, subControl, widget); + break; + case SC_GroupBoxContents: + rect = QWindowsStyle::subControlRect(control, option, subControl, widget); + rect.adjust(0, -8, 0, 0); + break; + case SC_GroupBoxFrame: + rect = group->rect; + break; + case SC_GroupBoxLabel: + QPixmap titleLeft = cached(":res/images/title_cap_left.png"); + QPixmap titleRight = cached(":res/images/title_cap_right.png"); + QPixmap titleStretch = cached(":res/images/title_stretch.png"); + int txt_width = group->fontMetrics.width(group->text) + 20; + rect = QRect(group->rect.center().x() - txt_width/2 + titleLeft.width(), 0, + txt_width - titleLeft.width() - titleRight.width(), + titleStretch.height()); + break; + } + } + break; + } + + if (control == CC_Slider && subControl == SC_SliderHandle) { + rect.setWidth(13); + rect.setHeight(27); + } else if (control == CC_Slider && subControl == SC_SliderGroove) { + rect.setHeight(9); + rect.moveTop(27/2 - 9/2); + } + return rect; +} + +QSize ArthurStyle::sizeFromContents(ContentsType type, const QStyleOption *option, + const QSize &size, const QWidget *widget) const +{ + QSize newSize = QWindowsStyle::sizeFromContents(type, option, size, widget); + + + switch (type) { + case CT_RadioButton: + newSize += QSize(20, 0); + break; + + case CT_PushButton: + newSize.setHeight(26); + break; + + case CT_Slider: + newSize.setHeight(27); + break; + + default: + break; + } + + return newSize; +} + +int ArthurStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QWidget *widget) const +{ + if (pm == PM_SliderLength) + return 13; + return QWindowsStyle::pixelMetric(pm, opt, widget); +} + +void ArthurStyle::polish(QWidget *widget) +{ + if (widget->layout() && qobject_cast(widget)) { + if (widget->findChildren().size() == 0) { + widget->layout()->setSpacing(0); + widget->layout()->setMargin(12); + } else { + widget->layout()->setMargin(13); + } + } + + if (qobject_cast(widget) + || qobject_cast(widget) + || qobject_cast(widget)) { + widget->setAttribute(Qt::WA_Hover); + } + + QPalette pal = widget->palette(); + if (widget->isWindow()) { + pal.setColor(QPalette::Background, QColor(241, 241, 241)); + widget->setPalette(pal); + } + +} + +void ArthurStyle::unpolish(QWidget *widget) +{ + if (qobject_cast(widget) + || qobject_cast(widget) + || qobject_cast(widget)) { + widget->setAttribute(Qt::WA_Hover, false); + } +} + +void ArthurStyle::polish(QPalette &palette) +{ + palette.setColor(QPalette::Background, QColor(241, 241, 241)); +} + +QRect ArthurStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const +{ + QRect r; + switch(element) { + case SE_RadioButtonClickRect: + r = widget->rect(); + break; + case SE_RadioButtonContents: + r = widget->rect().adjusted(20, 0, 0, 0); + break; + default: + r = QWindowsStyle::subElementRect(element, option, widget); + break; + } + + if (qobject_cast(widget)) + r = r.adjusted(5, 0, -5, 0); + + return r; +} diff --git a/examples/painting/shared/arthurstyle.h b/examples/painting/shared/arthurstyle.h new file mode 100644 index 0000000000..32c7fad970 --- /dev/null +++ b/examples/painting/shared/arthurstyle.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ARTHURSTYLE_H +#define ARTHURSTYLE_H + +#include + +QT_USE_NAMESPACE + +class ArthurStyle : public QWindowsStyle +{ +public: + ArthurStyle(); + + void drawHoverRect(QPainter *painter, const QRect &rect) const; + + void drawPrimitive(PrimitiveElement element, const QStyleOption *option, + QPainter *painter, const QWidget *widget = 0) const; +// void drawControl(ControlElement element, const QStyleOption *option, +// QPainter *painter, const QWidget *widget) const; + void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, + QPainter *painter, const QWidget *widget) const; + QSize sizeFromContents(ContentsType type, const QStyleOption *option, + const QSize &size, const QWidget *widget) const; + + QRect subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const; + QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, + SubControl sc, const QWidget *widget) const; + +// SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, +// const QPoint &pos, const QWidget *widget = 0) const; + + int pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const; + + void polish(QPalette &palette); + void polish(QWidget *widget); + void unpolish(QWidget *widget); +}; + +#endif diff --git a/examples/painting/shared/arthurwidgets.cpp b/examples/painting/shared/arthurwidgets.cpp new file mode 100644 index 0000000000..b3c75f0fc4 --- /dev/null +++ b/examples/painting/shared/arthurwidgets.cpp @@ -0,0 +1,371 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "arthurwidgets.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +extern QPixmap cached(const QString &img); + +ArthurFrame::ArthurFrame(QWidget *parent) + : QWidget(parent) + , m_prefer_image(false) +{ +#ifdef QT_OPENGL_SUPPORT + glw = 0; + m_use_opengl = false; + QGLFormat f = QGLFormat::defaultFormat(); + f.setSampleBuffers(true); + f.setStencil(true); + f.setAlpha(true); + f.setAlphaBufferSize(8); + QGLFormat::setDefaultFormat(f); +#endif + m_document = 0; + m_show_doc = false; + + m_tile = QPixmap(128, 128); + m_tile.fill(Qt::white); + QPainter pt(&m_tile); + QColor color(230, 230, 230); + pt.fillRect(0, 0, 64, 64, color); + pt.fillRect(64, 64, 64, 64, color); + pt.end(); + +// QPalette pal = palette(); +// pal.setBrush(backgroundRole(), m_tile); +// setPalette(pal); + +#ifdef Q_WS_X11 + QPixmap xRenderPixmap(1, 1); + m_prefer_image = xRenderPixmap.pixmapData()->classId() == QPixmapData::X11Class && !xRenderPixmap.x11PictureHandle(); +#endif +} + + +#ifdef QT_OPENGL_SUPPORT +void ArthurFrame::enableOpenGL(bool use_opengl) +{ + m_use_opengl = use_opengl; + + if (!glw) { + glw = new GLWidget(this); + glw->setAutoFillBackground(false); + glw->disableAutoBufferSwap(); + QApplication::postEvent(this, new QResizeEvent(size(), size())); + } + + if (use_opengl) { + glw->show(); + } else { + glw->hide(); + } + + update(); +} +#endif + +void ArthurFrame::paintEvent(QPaintEvent *e) +{ +#ifdef Q_WS_QWS + static QPixmap *static_image = 0; +#else + static QImage *static_image = 0; +#endif + QPainter painter; + if (preferImage() +#ifdef QT_OPENGL_SUPPORT + && !m_use_opengl +#endif + ) { + if (!static_image || static_image->size() != size()) { + delete static_image; +#ifdef Q_WS_QWS + static_image = new QPixmap(size()); +#else + static_image = new QImage(size(), QImage::Format_RGB32); +#endif + } + painter.begin(static_image); + + int o = 10; + + QBrush bg = palette().brush(QPalette::Background); + painter.fillRect(0, 0, o, o, bg); + painter.fillRect(width() - o, 0, o, o, bg); + painter.fillRect(0, height() - o, o, o, bg); + painter.fillRect(width() - o, height() - o, o, o, bg); + } else { +#ifdef QT_OPENGL_SUPPORT + if (m_use_opengl) { + painter.begin(glw); + painter.fillRect(QRectF(0, 0, glw->width(), glw->height()), palette().color(backgroundRole())); + } else { + painter.begin(this); + } +#else + painter.begin(this); +#endif + } + + painter.setClipRect(e->rect()); + + painter.setRenderHint(QPainter::Antialiasing); + + QPainterPath clipPath; + + QRect r = rect(); + qreal left = r.x() + 1; + qreal top = r.y() + 1; + qreal right = r.right(); + qreal bottom = r.bottom(); + qreal radius2 = 8 * 2; + + clipPath.moveTo(right - radius2, top); + clipPath.arcTo(right - radius2, top, radius2, radius2, 90, -90); + clipPath.arcTo(right - radius2, bottom - radius2, radius2, radius2, 0, -90); + clipPath.arcTo(left, bottom - radius2, radius2, radius2, 270, -90); + clipPath.arcTo(left, top, radius2, radius2, 180, -90); + clipPath.closeSubpath(); + + painter.save(); + painter.setClipPath(clipPath, Qt::IntersectClip); + + painter.drawTiledPixmap(rect(), m_tile); + + // client painting + + paint(&painter); + + painter.restore(); + + painter.save(); + if (m_show_doc) + paintDescription(&painter); + painter.restore(); + + int level = 180; + painter.setPen(QPen(QColor(level, level, level), 2)); + painter.setBrush(Qt::NoBrush); + painter.drawPath(clipPath); + + if (preferImage() +#ifdef QT_OPENGL_SUPPORT + && !m_use_opengl +#endif + ) { + painter.end(); + painter.begin(this); +#ifdef Q_WS_QWS + painter.drawPixmap(e->rect(), *static_image, e->rect()); +#else + painter.drawImage(e->rect(), *static_image, e->rect()); +#endif + } + +#ifdef QT_OPENGL_SUPPORT + if (m_use_opengl && (inherits("PathDeformRenderer") || inherits("PathStrokeRenderer") || inherits("CompositionRenderer") || m_show_doc)) + glw->swapBuffers(); +#endif +} + +void ArthurFrame::resizeEvent(QResizeEvent *e) +{ +#ifdef QT_OPENGL_SUPPORT + if (glw) + glw->setGeometry(0, 0, e->size().width()-1, e->size().height()-1); +#endif + QWidget::resizeEvent(e); +} + +void ArthurFrame::setDescriptionEnabled(bool enabled) +{ + if (m_show_doc != enabled) { + m_show_doc = enabled; + emit descriptionEnabledChanged(m_show_doc); + update(); + } +} + +void ArthurFrame::loadDescription(const QString &fileName) +{ + QFile textFile(fileName); + QString text; + if (!textFile.open(QFile::ReadOnly)) + text = QString("Unable to load resource file: '%1'").arg(fileName); + else + text = textFile.readAll(); + setDescription(text); +} + + +void ArthurFrame::setDescription(const QString &text) +{ + m_document = new QTextDocument(this); + m_document->setHtml(text); +} + +void ArthurFrame::paintDescription(QPainter *painter) +{ + if (!m_document) + return; + + int pageWidth = qMax(width() - 100, 100); + int pageHeight = qMax(height() - 100, 100); + if (pageWidth != m_document->pageSize().width()) { + m_document->setPageSize(QSize(pageWidth, pageHeight)); + } + + QRect textRect(width() / 2 - pageWidth / 2, + height() / 2 - pageHeight / 2, + pageWidth, + pageHeight); + int pad = 10; + QRect clearRect = textRect.adjusted(-pad, -pad, pad, pad); + painter->setPen(Qt::NoPen); + painter->setBrush(QColor(0, 0, 0, 63)); + int shade = 10; + painter->drawRect(clearRect.x() + clearRect.width() + 1, + clearRect.y() + shade, + shade, + clearRect.height() + 1); + painter->drawRect(clearRect.x() + shade, + clearRect.y() + clearRect.height() + 1, + clearRect.width() - shade + 1, + shade); + + painter->setRenderHint(QPainter::Antialiasing, false); + painter->setBrush(QColor(255, 255, 255, 220)); + painter->setPen(Qt::black); + painter->drawRect(clearRect); + + painter->setClipRegion(textRect, Qt::IntersectClip); + painter->translate(textRect.topLeft()); + + QAbstractTextDocumentLayout::PaintContext ctx; + + QLinearGradient g(0, 0, 0, textRect.height()); + g.setColorAt(0, Qt::black); + g.setColorAt(0.9, Qt::black); + g.setColorAt(1, Qt::transparent); + + QPalette pal = palette(); + pal.setBrush(QPalette::Text, g); + + ctx.palette = pal; + ctx.clip = QRect(0, 0, textRect.width(), textRect.height()); + m_document->documentLayout()->draw(painter, ctx); +} + +void ArthurFrame::loadSourceFile(const QString &sourceFile) +{ + m_sourceFileName = sourceFile; +} + +void ArthurFrame::showSource() +{ + // Check for existing source + if (findChild()) + return; + + QString contents; + if (m_sourceFileName.isEmpty()) { + contents = QString("No source for widget: '%1'").arg(objectName()); + } else { + QFile f(m_sourceFileName); + if (!f.open(QFile::ReadOnly)) + contents = QString("Could not open file: '%1'").arg(m_sourceFileName); + else + contents = f.readAll(); + } + + contents.replace('&', "&"); + contents.replace('<', "<"); + contents.replace('>', ">"); + + QStringList keywords; + keywords << "for " << "if " << "switch " << " int " << "#include " << "const" + << "void " << "uint " << "case " << "double " << "#define " << "static" + << "new" << "this"; + + foreach (QString keyword, keywords) + contents.replace(keyword, QLatin1String("") + keyword + QLatin1String("")); + contents.replace("(int ", "(int "); + + QStringList ppKeywords; + ppKeywords << "#ifdef" << "#ifndef" << "#if" << "#endif" << "#else"; + + foreach (QString keyword, ppKeywords) + contents.replace(keyword, QLatin1String("") + keyword + QLatin1String("")); + + contents.replace(QRegExp("(\\d\\d?)"), QLatin1String("\\1")); + + QRegExp commentRe("(//.+)\\n"); + commentRe.setMinimal(true); + contents.replace(commentRe, QLatin1String("\\1\n")); + + QRegExp stringLiteralRe("(\".+\")"); + stringLiteralRe.setMinimal(true); + contents.replace(stringLiteralRe, QLatin1String("\\1")); + + QString html = contents; + html.prepend("
      ");
      +    html.append("
      "); + + QTextBrowser *sourceViewer = new QTextBrowser(0); + sourceViewer->setWindowTitle("Source: " + m_sourceFileName.mid(5)); + sourceViewer->setParent(this, Qt::Dialog); + sourceViewer->setAttribute(Qt::WA_DeleteOnClose); + sourceViewer->setLineWrapMode(QTextEdit::NoWrap); + sourceViewer->setHtml(html); + sourceViewer->resize(600, 600); + sourceViewer->show(); +} diff --git a/examples/painting/shared/arthurwidgets.h b/examples/painting/shared/arthurwidgets.h new file mode 100644 index 0000000000..dc8f92505d --- /dev/null +++ b/examples/painting/shared/arthurwidgets.h @@ -0,0 +1,137 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ARTHURWIDGETS_H +#define ARTHURWIDGETS_H + +#include "arthurstyle.h" +#include +#include +#include + +#if defined(QT_OPENGL_SUPPORT) +#include +#include +class GLWidget : public QGLWidget +{ +public: + GLWidget(QWidget *parent) + : QGLWidget(QGLFormat(QGL::SampleBuffers), parent) + { + setAttribute(Qt::WA_AcceptTouchEvents); + } + void disableAutoBufferSwap() { setAutoBufferSwap(false); } + void paintEvent(QPaintEvent *) { parentWidget()->update(); } +protected: + bool event(QEvent *event) + { + switch (event->type()) { + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: + event->ignore(); + return false; + break; + default: + break; + } + return QGLWidget::event(event); + } +}; +#endif + +QT_FORWARD_DECLARE_CLASS(QTextDocument) +QT_FORWARD_DECLARE_CLASS(QTextEdit) +QT_FORWARD_DECLARE_CLASS(QVBoxLayout) + +class ArthurFrame : public QWidget +{ + Q_OBJECT +public: + ArthurFrame(QWidget *parent); + virtual void paint(QPainter *) {} + + + void paintDescription(QPainter *p); + + void loadDescription(const QString &filename); + void setDescription(const QString &htmlDesc); + + void loadSourceFile(const QString &fileName); + + bool preferImage() const { return m_prefer_image; } + +#if defined(QT_OPENGL_SUPPORT) + QGLWidget *glWidget() const { return glw; } +#endif + +public slots: + void setPreferImage(bool pi) { m_prefer_image = pi; } + void setDescriptionEnabled(bool enabled); + void showSource(); + +#if defined(QT_OPENGL_SUPPORT) + void enableOpenGL(bool use_opengl); + bool usesOpenGL() { return m_use_opengl; } +#endif + +signals: + void descriptionEnabledChanged(bool); + +protected: + void paintEvent(QPaintEvent *); + void resizeEvent(QResizeEvent *); + +#if defined(QT_OPENGL_SUPPORT) + GLWidget *glw; + bool m_use_opengl; +#endif + QPixmap m_tile; + + bool m_show_doc; + bool m_prefer_image; + QTextDocument *m_document; + + QString m_sourceFileName; + +}; + +#endif diff --git a/examples/painting/shared/hoverpoints.cpp b/examples/painting/shared/hoverpoints.cpp new file mode 100644 index 0000000000..36c24186d3 --- /dev/null +++ b/examples/painting/shared/hoverpoints.cpp @@ -0,0 +1,415 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifdef QT_OPENGL_SUPPORT +#include +#endif + +#include "arthurwidgets.h" +#include "hoverpoints.h" + +#define printf + +HoverPoints::HoverPoints(QWidget *widget, PointShape shape) + : QObject(widget) +{ + m_widget = widget; + widget->installEventFilter(this); + widget->setAttribute(Qt::WA_AcceptTouchEvents); + + m_connectionType = CurveConnection; + m_sortType = NoSort; + m_shape = shape; + m_pointPen = QPen(QColor(255, 255, 255, 191), 1); + m_connectionPen = QPen(QColor(255, 255, 255, 127), 2); + m_pointBrush = QBrush(QColor(191, 191, 191, 127)); + m_pointSize = QSize(11, 11); + m_currentIndex = -1; + m_editable = true; + m_enabled = true; + + connect(this, SIGNAL(pointsChanged(QPolygonF)), + m_widget, SLOT(update())); +} + + +void HoverPoints::setEnabled(bool enabled) +{ + if (m_enabled != enabled) { + m_enabled = enabled; + m_widget->update(); + } +} + + +bool HoverPoints::eventFilter(QObject *object, QEvent *event) +{ + if (object == m_widget && m_enabled) { + switch (event->type()) { + + case QEvent::MouseButtonPress: + { + if (!m_fingerPointMapping.isEmpty()) + return true; + QMouseEvent *me = (QMouseEvent *) event; + + QPointF clickPos = me->pos(); + int index = -1; + for (int i=0; ibutton() == Qt::LeftButton) { + if (index == -1) { + if (!m_editable) + return false; + int pos = 0; + // Insert sort for x or y + if (m_sortType == XSort) { + for (int i=0; i clickPos.x()) { + pos = i; + break; + } + } else if (m_sortType == YSort) { + for (int i=0; i clickPos.y()) { + pos = i; + break; + } + } + + m_points.insert(pos, clickPos); + m_locks.insert(pos, 0); + m_currentIndex = pos; + firePointChange(); + } else { + m_currentIndex = index; + } + return true; + + } else if (me->button() == Qt::RightButton) { + if (index >= 0 && m_editable) { + if (m_locks[index] == 0) { + m_locks.remove(index); + m_points.remove(index); + } + firePointChange(); + return true; + } + } + + } + break; + + case QEvent::MouseButtonRelease: + if (!m_fingerPointMapping.isEmpty()) + return true; + m_currentIndex = -1; + break; + + case QEvent::MouseMove: + if (!m_fingerPointMapping.isEmpty()) + return true; + if (m_currentIndex >= 0) + movePoint(m_currentIndex, ((QMouseEvent *)event)->pos()); + break; + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + { + const QTouchEvent *const touchEvent = static_cast(event); + const QList points = touchEvent->touchPoints(); + const qreal pointSize = qMax(m_pointSize.width(), m_pointSize.height()); + foreach (const QTouchEvent::TouchPoint &touchPoint, points) { + const int id = touchPoint.id(); + switch (touchPoint.state()) { + case Qt::TouchPointPressed: + { + // find the point, move it + QSet activePoints = QSet::fromList(m_fingerPointMapping.values()); + int activePoint = -1; + qreal distance = -1; + const int pointsCount = m_points.size(); + const int activePointCount = activePoints.size(); + if (pointsCount == 2 && activePointCount == 1) { // only two points + activePoint = activePoints.contains(0) ? 1 : 0; + } else { + for (int i=0; i::iterator it = m_fingerPointMapping.find(id); + movePoint(it.value(), touchPoint.pos()); + m_fingerPointMapping.erase(it); + } + break; + case Qt::TouchPointMoved: + { + // move the point + const int pointIdx = m_fingerPointMapping.value(id, -1); + if (pointIdx >= 0) // do we track this point? + movePoint(pointIdx, touchPoint.pos()); + } + break; + default: + break; + } + } + if (m_fingerPointMapping.isEmpty()) { + event->ignore(); + return false; + } else { + return true; + } + } + break; + case QEvent::TouchEnd: + if (m_fingerPointMapping.isEmpty()) { + event->ignore(); + return false; + } + return true; + break; + + case QEvent::Resize: + { + QResizeEvent *e = (QResizeEvent *) event; + if (e->oldSize().width() == 0 || e->oldSize().height() == 0) + break; + qreal stretch_x = e->size().width() / qreal(e->oldSize().width()); + qreal stretch_y = e->size().height() / qreal(e->oldSize().height()); + for (int i=0; i(that_widget); + if (af && af->usesOpenGL()) + af->glWidget()->swapBuffers(); +#endif + return true; + } + default: + break; + } + } + + return false; +} + + +void HoverPoints::paintPoints() +{ + QPainter p; +#ifdef QT_OPENGL_SUPPORT + ArthurFrame *af = qobject_cast(m_widget); + if (af && af->usesOpenGL()) + p.begin(af->glWidget()); + else + p.begin(m_widget); +#else + p.begin(m_widget); +#endif + + p.setRenderHint(QPainter::Antialiasing); + + if (m_connectionPen.style() != Qt::NoPen && m_connectionType != NoConnection) { + p.setPen(m_connectionPen); + + if (m_connectionType == CurveConnection) { + QPainterPath path; + path.moveTo(m_points.at(0)); + for (int i=1; i right || (lock & HoverPoints::LockToRight)) p.setX(right); + + if (p.y() < top || (lock & HoverPoints::LockToTop)) p.setY(top); + else if (p.y() > bottom || (lock & HoverPoints::LockToBottom)) p.setY(bottom); + + return p; +} + +void HoverPoints::setPoints(const QPolygonF &points) +{ + if (points.size() != m_points.size()) + m_fingerPointMapping.clear(); + m_points.clear(); + for (int i=0; i 0) { + m_locks.resize(m_points.size()); + + m_locks.fill(0); + } +} + + +void HoverPoints::movePoint(int index, const QPointF &point, bool emitUpdate) +{ + m_points[index] = bound_point(point, boundingRect(), m_locks.at(index)); + if (emitUpdate) + firePointChange(); +} + + +inline static bool x_less_than(const QPointF &p1, const QPointF &p2) +{ + return p1.x() < p2.x(); +} + + +inline static bool y_less_than(const QPointF &p1, const QPointF &p2) +{ + return p1.y() < p2.y(); +} + +void HoverPoints::firePointChange() +{ +// printf("HoverPoints::firePointChange(), current=%d\n", m_currentIndex); + + if (m_sortType != NoSort) { + + QPointF oldCurrent; + if (m_currentIndex != -1) { + oldCurrent = m_points[m_currentIndex]; + } + + if (m_sortType == XSort) + qSort(m_points.begin(), m_points.end(), x_less_than); + else if (m_sortType == YSort) + qSort(m_points.begin(), m_points.end(), y_less_than); + + // Compensate for changed order... + if (m_currentIndex != -1) { + for (int i=0; i + +QT_FORWARD_DECLARE_CLASS(QBypassWidget) + +class HoverPoints : public QObject +{ + Q_OBJECT +public: + enum PointShape { + CircleShape, + RectangleShape + }; + + enum LockType { + LockToLeft = 0x01, + LockToRight = 0x02, + LockToTop = 0x04, + LockToBottom = 0x08 + }; + + enum SortType { + NoSort, + XSort, + YSort + }; + + enum ConnectionType { + NoConnection, + LineConnection, + CurveConnection + }; + + HoverPoints(QWidget *widget, PointShape shape); + + bool eventFilter(QObject *object, QEvent *event); + + void paintPoints(); + + inline QRectF boundingRect() const; + void setBoundingRect(const QRectF &boundingRect) { m_bounds = boundingRect; } + + QPolygonF points() const { return m_points; } + void setPoints(const QPolygonF &points); + + QSizeF pointSize() const { return m_pointSize; } + void setPointSize(const QSizeF &size) { m_pointSize = size; } + + SortType sortType() const { return m_sortType; } + void setSortType(SortType sortType) { m_sortType = sortType; } + + ConnectionType connectionType() const { return m_connectionType; } + void setConnectionType(ConnectionType connectionType) { m_connectionType = connectionType; } + + void setConnectionPen(const QPen &pen) { m_connectionPen = pen; } + void setShapePen(const QPen &pen) { m_pointPen = pen; } + void setShapeBrush(const QBrush &brush) { m_pointBrush = brush; } + + void setPointLock(int pos, LockType lock) { m_locks[pos] = lock; } + + void setEditable(bool editable) { m_editable = editable; } + bool editable() const { return m_editable; } + +public slots: + void setEnabled(bool enabled); + void setDisabled(bool disabled) { setEnabled(!disabled); } + +signals: + void pointsChanged(const QPolygonF &points); + +public: + void firePointChange(); + +private: + inline QRectF pointBoundingRect(int i) const; + void movePoint(int i, const QPointF &newPos, bool emitChange = true); + + QWidget *m_widget; + + QPolygonF m_points; + QRectF m_bounds; + PointShape m_shape; + SortType m_sortType; + ConnectionType m_connectionType; + + QVector m_locks; + + QSizeF m_pointSize; + int m_currentIndex; + bool m_editable; + bool m_enabled; + + QHash m_fingerPointMapping; + + QPen m_pointPen; + QBrush m_pointBrush; + QPen m_connectionPen; +}; + + +inline QRectF HoverPoints::pointBoundingRect(int i) const +{ + QPointF p = m_points.at(i); + qreal w = m_pointSize.width(); + qreal h = m_pointSize.height(); + qreal x = p.x() - w / 2; + qreal y = p.y() - h / 2; + return QRectF(x, y, w, h); +} + +inline QRectF HoverPoints::boundingRect() const +{ + if (m_bounds.isEmpty()) + return m_widget->rect(); + else + return m_bounds; +} + +#endif // HOVERPOINTS_H diff --git a/examples/painting/shared/images/bg_pattern.png b/examples/painting/shared/images/bg_pattern.png new file mode 100644 index 0000000000..ee670266f0 Binary files /dev/null and b/examples/painting/shared/images/bg_pattern.png differ diff --git a/examples/painting/shared/images/button_normal_cap_left.png b/examples/painting/shared/images/button_normal_cap_left.png new file mode 100644 index 0000000000..db31dd971d Binary files /dev/null and b/examples/painting/shared/images/button_normal_cap_left.png differ diff --git a/examples/painting/shared/images/button_normal_cap_right.png b/examples/painting/shared/images/button_normal_cap_right.png new file mode 100644 index 0000000000..38ead1c719 Binary files /dev/null and b/examples/painting/shared/images/button_normal_cap_right.png differ diff --git a/examples/painting/shared/images/button_normal_stretch.png b/examples/painting/shared/images/button_normal_stretch.png new file mode 100644 index 0000000000..87abe67ac9 Binary files /dev/null and b/examples/painting/shared/images/button_normal_stretch.png differ diff --git a/examples/painting/shared/images/button_pressed_cap_left.png b/examples/painting/shared/images/button_pressed_cap_left.png new file mode 100644 index 0000000000..66bfc13cb4 Binary files /dev/null and b/examples/painting/shared/images/button_pressed_cap_left.png differ diff --git a/examples/painting/shared/images/button_pressed_cap_right.png b/examples/painting/shared/images/button_pressed_cap_right.png new file mode 100644 index 0000000000..3d4cfe25b1 Binary files /dev/null and b/examples/painting/shared/images/button_pressed_cap_right.png differ diff --git a/examples/painting/shared/images/button_pressed_stretch.png b/examples/painting/shared/images/button_pressed_stretch.png new file mode 100644 index 0000000000..4dd4ad11e6 Binary files /dev/null and b/examples/painting/shared/images/button_pressed_stretch.png differ diff --git a/examples/painting/shared/images/curve_thing_edit-6.png b/examples/painting/shared/images/curve_thing_edit-6.png new file mode 100644 index 0000000000..034b474d02 Binary files /dev/null and b/examples/painting/shared/images/curve_thing_edit-6.png differ diff --git a/examples/painting/shared/images/frame_bottom.png b/examples/painting/shared/images/frame_bottom.png new file mode 100644 index 0000000000..889b40d304 Binary files /dev/null and b/examples/painting/shared/images/frame_bottom.png differ diff --git a/examples/painting/shared/images/frame_bottomleft.png b/examples/painting/shared/images/frame_bottomleft.png new file mode 100644 index 0000000000..0b3023f397 Binary files /dev/null and b/examples/painting/shared/images/frame_bottomleft.png differ diff --git a/examples/painting/shared/images/frame_bottomright.png b/examples/painting/shared/images/frame_bottomright.png new file mode 100644 index 0000000000..0021e35864 Binary files /dev/null and b/examples/painting/shared/images/frame_bottomright.png differ diff --git a/examples/painting/shared/images/frame_left.png b/examples/painting/shared/images/frame_left.png new file mode 100644 index 0000000000..40f331c293 Binary files /dev/null and b/examples/painting/shared/images/frame_left.png differ diff --git a/examples/painting/shared/images/frame_right.png b/examples/painting/shared/images/frame_right.png new file mode 100644 index 0000000000..023af8c700 Binary files /dev/null and b/examples/painting/shared/images/frame_right.png differ diff --git a/examples/painting/shared/images/frame_top.png b/examples/painting/shared/images/frame_top.png new file mode 100644 index 0000000000..001f3a7144 Binary files /dev/null and b/examples/painting/shared/images/frame_top.png differ diff --git a/examples/painting/shared/images/frame_topleft.png b/examples/painting/shared/images/frame_topleft.png new file mode 100644 index 0000000000..58c68d407a Binary files /dev/null and b/examples/painting/shared/images/frame_topleft.png differ diff --git a/examples/painting/shared/images/frame_topright.png b/examples/painting/shared/images/frame_topright.png new file mode 100644 index 0000000000..6a7e8d3eb3 Binary files /dev/null and b/examples/painting/shared/images/frame_topright.png differ diff --git a/examples/painting/shared/images/groupframe_bottom_left.png b/examples/painting/shared/images/groupframe_bottom_left.png new file mode 100644 index 0000000000..af2fe061e3 Binary files /dev/null and b/examples/painting/shared/images/groupframe_bottom_left.png differ diff --git a/examples/painting/shared/images/groupframe_bottom_right.png b/examples/painting/shared/images/groupframe_bottom_right.png new file mode 100644 index 0000000000..fdf2e97b13 Binary files /dev/null and b/examples/painting/shared/images/groupframe_bottom_right.png differ diff --git a/examples/painting/shared/images/groupframe_bottom_stretch.png b/examples/painting/shared/images/groupframe_bottom_stretch.png new file mode 100644 index 0000000000..f47b67d7c0 Binary files /dev/null and b/examples/painting/shared/images/groupframe_bottom_stretch.png differ diff --git a/examples/painting/shared/images/groupframe_left_stretch.png b/examples/painting/shared/images/groupframe_left_stretch.png new file mode 100644 index 0000000000..c122f462ed Binary files /dev/null and b/examples/painting/shared/images/groupframe_left_stretch.png differ diff --git a/examples/painting/shared/images/groupframe_right_stretch.png b/examples/painting/shared/images/groupframe_right_stretch.png new file mode 100644 index 0000000000..1056b7812a Binary files /dev/null and b/examples/painting/shared/images/groupframe_right_stretch.png differ diff --git a/examples/painting/shared/images/groupframe_top_stretch.png b/examples/painting/shared/images/groupframe_top_stretch.png new file mode 100644 index 0000000000..5746ef96fc Binary files /dev/null and b/examples/painting/shared/images/groupframe_top_stretch.png differ diff --git a/examples/painting/shared/images/groupframe_topleft.png b/examples/painting/shared/images/groupframe_topleft.png new file mode 100644 index 0000000000..98d9cd96b4 Binary files /dev/null and b/examples/painting/shared/images/groupframe_topleft.png differ diff --git a/examples/painting/shared/images/groupframe_topright.png b/examples/painting/shared/images/groupframe_topright.png new file mode 100644 index 0000000000..1a0a328c20 Binary files /dev/null and b/examples/painting/shared/images/groupframe_topright.png differ diff --git a/examples/painting/shared/images/line_dash_dot.png b/examples/painting/shared/images/line_dash_dot.png new file mode 100644 index 0000000000..1c61442d9f Binary files /dev/null and b/examples/painting/shared/images/line_dash_dot.png differ diff --git a/examples/painting/shared/images/line_dash_dot_dot.png b/examples/painting/shared/images/line_dash_dot_dot.png new file mode 100644 index 0000000000..0d9bb972f9 Binary files /dev/null and b/examples/painting/shared/images/line_dash_dot_dot.png differ diff --git a/examples/painting/shared/images/line_dashed.png b/examples/painting/shared/images/line_dashed.png new file mode 100644 index 0000000000..d5bc7ea5fe Binary files /dev/null and b/examples/painting/shared/images/line_dashed.png differ diff --git a/examples/painting/shared/images/line_dotted.png b/examples/painting/shared/images/line_dotted.png new file mode 100644 index 0000000000..a2f9a35925 Binary files /dev/null and b/examples/painting/shared/images/line_dotted.png differ diff --git a/examples/painting/shared/images/line_solid.png b/examples/painting/shared/images/line_solid.png new file mode 100644 index 0000000000..60ef3f9485 Binary files /dev/null and b/examples/painting/shared/images/line_solid.png differ diff --git a/examples/painting/shared/images/radiobutton-off.png b/examples/painting/shared/images/radiobutton-off.png new file mode 100644 index 0000000000..af1753a3e7 Binary files /dev/null and b/examples/painting/shared/images/radiobutton-off.png differ diff --git a/examples/painting/shared/images/radiobutton-on.png b/examples/painting/shared/images/radiobutton-on.png new file mode 100644 index 0000000000..f875838bb5 Binary files /dev/null and b/examples/painting/shared/images/radiobutton-on.png differ diff --git a/examples/painting/shared/images/radiobutton_off.png b/examples/painting/shared/images/radiobutton_off.png new file mode 100644 index 0000000000..400906ebfa Binary files /dev/null and b/examples/painting/shared/images/radiobutton_off.png differ diff --git a/examples/painting/shared/images/radiobutton_on.png b/examples/painting/shared/images/radiobutton_on.png new file mode 100644 index 0000000000..50a049ec56 Binary files /dev/null and b/examples/painting/shared/images/radiobutton_on.png differ diff --git a/examples/painting/shared/images/slider_bar.png b/examples/painting/shared/images/slider_bar.png new file mode 100644 index 0000000000..1b3d62c007 Binary files /dev/null and b/examples/painting/shared/images/slider_bar.png differ diff --git a/examples/painting/shared/images/slider_thumb_off.png b/examples/painting/shared/images/slider_thumb_off.png new file mode 100644 index 0000000000..d7f141daef Binary files /dev/null and b/examples/painting/shared/images/slider_thumb_off.png differ diff --git a/examples/painting/shared/images/slider_thumb_on.png b/examples/painting/shared/images/slider_thumb_on.png new file mode 100644 index 0000000000..8e1f510813 Binary files /dev/null and b/examples/painting/shared/images/slider_thumb_on.png differ diff --git a/examples/painting/shared/images/title_cap_left.png b/examples/painting/shared/images/title_cap_left.png new file mode 100644 index 0000000000..2d475070c8 Binary files /dev/null and b/examples/painting/shared/images/title_cap_left.png differ diff --git a/examples/painting/shared/images/title_cap_right.png b/examples/painting/shared/images/title_cap_right.png new file mode 100644 index 0000000000..dc3ff8536c Binary files /dev/null and b/examples/painting/shared/images/title_cap_right.png differ diff --git a/examples/painting/shared/images/title_stretch.png b/examples/painting/shared/images/title_stretch.png new file mode 100644 index 0000000000..11043345d0 Binary files /dev/null and b/examples/painting/shared/images/title_stretch.png differ diff --git a/examples/painting/shared/shared.pri b/examples/painting/shared/shared.pri new file mode 100644 index 0000000000..fb7b04c0be --- /dev/null +++ b/examples/painting/shared/shared.pri @@ -0,0 +1,21 @@ +INCLUDEPATH += $$SHARED_FOLDER + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} +contains(CONFIG, debug_and_release_target) { + CONFIG(debug, debug|release) { + QMAKE_LIBDIR += $$SHARED_FOLDER/debug + } else { + QMAKE_LIBDIR += $$SHARED_FOLDER/release + } +} else { + QMAKE_LIBDIR += $$SHARED_FOLDER +} + +hpux-acc*:LIBS += $$SHARED_FOLDER/libdemo_shared.a +hpuxi-acc*:LIBS += $$SHARED_FOLDER/libdemo_shared.a +symbian:LIBS += -ldemo_shared.lib +!hpuxi-acc*:!hpux-acc*:!symbian:LIBS += -ldemo_shared + diff --git a/examples/painting/shared/shared.pro b/examples/painting/shared/shared.pro new file mode 100644 index 0000000000..88d7fbedab --- /dev/null +++ b/examples/painting/shared/shared.pro @@ -0,0 +1,39 @@ +TEMPLATE = lib +CONFIG += static + +contains(QT_CONFIG, opengl)|contains(QT_CONFIG, opengles1)|contains(QT_CONFIG, opengles2) { + DEFINES += QT_OPENGL_SUPPORT + QT += opengl +} + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} +TARGET = demo_shared +QT += gui-private + +SOURCES += \ + arthurstyle.cpp\ + arthurwidgets.cpp \ + hoverpoints.cpp + +HEADERS += \ + arthurstyle.h \ + arthurwidgets.h \ + hoverpoints.h + +RESOURCES += shared.qrc + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/shared +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.pri images +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/shared +INSTALLS += sources + +!cross_compile:INSTALLS += target + +symbian { + TARGET.UID3 = 0xA000A63C + CONFIG += qt_demo +} diff --git a/examples/painting/shared/shared.qrc b/examples/painting/shared/shared.qrc new file mode 100644 index 0000000000..17336ecf80 --- /dev/null +++ b/examples/painting/shared/shared.qrc @@ -0,0 +1,39 @@ + + + images/button_normal_cap_left.png + images/button_normal_cap_right.png + images/button_normal_stretch.png + images/button_pressed_cap_left.png + images/button_pressed_cap_right.png + images/button_pressed_stretch.png + images/radiobutton-on.png + images/radiobutton_on.png + images/radiobutton_off.png + images/slider_bar.png + images/slider_thumb_on.png + images/groupframe_topleft.png + images/groupframe_topright.png + images/groupframe_bottom_left.png + images/groupframe_bottom_right.png + images/groupframe_top_stretch.png + images/groupframe_bottom_stretch.png + images/groupframe_left_stretch.png + images/groupframe_right_stretch.png + images/frame_topleft.png + images/frame_topright.png + images/frame_bottomleft.png + images/frame_bottomright.png + images/frame_left.png + images/frame_top.png + images/frame_right.png + images/frame_bottom.png + images/title_cap_left.png + images/title_cap_right.png + images/title_stretch.png + images/line_dash_dot.png + images/line_dotted.png + images/line_dashed.png + images/line_solid.png + images/line_dash_dot_dot.png + + diff --git a/examples/richtext/textedit/example.html b/examples/richtext/textedit/example.html new file mode 100644 index 0000000000..6327b5f8fc --- /dev/null +++ b/examples/richtext/textedit/example.html @@ -0,0 +1,79 @@ +QTextEdit Demonstration +

      QTextEdit

      +

      The QTextEdit widget is an advanced editor that supports formatted rich text. It can be used to display HTML and other rich document formats. Internally, QTextEdit uses the QTextDocument class to describe both the high-level structure of each document and the low-level formatting of paragraphs.

      +

      If you are viewing this document in the textedit demo, you can edit this document to explore Qt's rich text editing features. We have included some comments in each of the following sections to encourage you to experiment.

      +

      Font and Paragraph Styles

      +

      QTextEdit supports bold, italic, and underlined font styles, and can display multicolored text. Font families such as Times New Roman and Courier can also be used directly. If you place the cursor in a region of styled text, the controls in the tool bars will change to reflect the current style.

      +

      Paragraphs can be formatted so that the text is left-aligned, right-aligned, centered, or fully justified.

      +

      Try changing the alignment of some text and resize the editor to see how the text layout changes.

      +

      Lists

      +

      Different kinds of lists can be included in rich text documents. Standard bullet lists can be nested, using different symbols for each level of the list:

      +
      • Disc symbols are typically used for top-level list items.
      +
      • Circle symbols can be used to distinguish between items in lower-level lists.
      +
      • Square symbols provide a reasonable alternative to discs and circles.
      +

      Ordered lists can be created that can be used for tables of contents. Different characters can be used to enumerate items, and we can use both Roman and Arabic numerals in the same list structure:

      +
      1. Introduction
      2. +
      3. Qt Tools
      +
      1. Qt Assistant
      2. +
      3. Qt Designer
      4. +
        1. Form Editor
        2. +
        3. Component Architecture
        +
      5. Qt Linguist
      +

      +

      The list will automatically be renumbered if you add or remove items. Try adding new sections to the above list or removing existing item to see the numbers change.

      +

      +

      Images

      +

      Inline images are treated like ordinary ranges of characters in the text editor, so they flow with the surrounding text. Images can also be selected in the same way as text, making it easy to cut, copy, and paste them.

      +

      Try to select this image by clicking and dragging over it with the mouse, or use the text cursor to select it by holding down Shift and using the arrow keys. You can then cut or copy it, and paste it into different parts of this document.

      +

      Tables

      +

      QTextEdit can arrange and format tables, supporting features such as row and column spans, text formatting within cells, and size constraints for columns.

      +

      +

      + + + + + + + + + + + + + + + + + + + + + + +
      +

      +

      Development Tools

      +

      Programming Techniques

      +

      Graphical User Interfaces

      +

      9:00 - 11:00

      +

      Introduction to Qt

      +

      11:00 - 13:00

      +

      Using qmake

      +

      Object-oriented Programming

      +

      Layouts in Qt

      +

      13:00 - 15:00

      +

      Qt Designer Tutorial

      +

      Extreme Programming

      +

      Writing Custom Styles

      +

      15:00 - 17:00

      +

      Qt Linguist and Internationalization

      +

      +

      Try adding text to the cells in the table and experiment with the alignment of the paragraphs.

      +

      Hyperlinks

      +

      QTextEdit is designed to support hyperlinks between documents, and this feature is used extensively in Qt Assistant. Hyperlinks are automatically created when an HTML file is imported into an editor. Since the rich text framework supports hyperlinks natively, they can also be created programatically.

      +

      Undo and Redo

      +

      Full support for undo and redo operations is built into QTextEdit and the underlying rich text framework. Operations on a document can be packaged together to make editing a more comfortable experience for the user.

      +

      Try making changes to this document and press Ctrl+Z to undo them. You can always recover the original contents of the document.

      diff --git a/examples/richtext/textedit/images/logo32.png b/examples/richtext/textedit/images/logo32.png new file mode 100644 index 0000000000..5f91e9873b Binary files /dev/null and b/examples/richtext/textedit/images/logo32.png differ diff --git a/examples/richtext/textedit/images/mac/editcopy.png b/examples/richtext/textedit/images/mac/editcopy.png new file mode 100644 index 0000000000..f551364464 Binary files /dev/null and b/examples/richtext/textedit/images/mac/editcopy.png differ diff --git a/examples/richtext/textedit/images/mac/editcut.png b/examples/richtext/textedit/images/mac/editcut.png new file mode 100644 index 0000000000..a784fd5709 Binary files /dev/null and b/examples/richtext/textedit/images/mac/editcut.png differ diff --git a/examples/richtext/textedit/images/mac/editpaste.png b/examples/richtext/textedit/images/mac/editpaste.png new file mode 100644 index 0000000000..64c0b2d6ab Binary files /dev/null and b/examples/richtext/textedit/images/mac/editpaste.png differ diff --git a/examples/richtext/textedit/images/mac/editredo.png b/examples/richtext/textedit/images/mac/editredo.png new file mode 100644 index 0000000000..8875bf246c Binary files /dev/null and b/examples/richtext/textedit/images/mac/editredo.png differ diff --git a/examples/richtext/textedit/images/mac/editundo.png b/examples/richtext/textedit/images/mac/editundo.png new file mode 100644 index 0000000000..a3bd5e0bf2 Binary files /dev/null and b/examples/richtext/textedit/images/mac/editundo.png differ diff --git a/examples/richtext/textedit/images/mac/exportpdf.png b/examples/richtext/textedit/images/mac/exportpdf.png new file mode 100644 index 0000000000..ebb44e6b88 Binary files /dev/null and b/examples/richtext/textedit/images/mac/exportpdf.png differ diff --git a/examples/richtext/textedit/images/mac/filenew.png b/examples/richtext/textedit/images/mac/filenew.png new file mode 100644 index 0000000000..d3882c7b3f Binary files /dev/null and b/examples/richtext/textedit/images/mac/filenew.png differ diff --git a/examples/richtext/textedit/images/mac/fileopen.png b/examples/richtext/textedit/images/mac/fileopen.png new file mode 100644 index 0000000000..fc06c5ec63 Binary files /dev/null and b/examples/richtext/textedit/images/mac/fileopen.png differ diff --git a/examples/richtext/textedit/images/mac/fileprint.png b/examples/richtext/textedit/images/mac/fileprint.png new file mode 100644 index 0000000000..10ca56c82a Binary files /dev/null and b/examples/richtext/textedit/images/mac/fileprint.png differ diff --git a/examples/richtext/textedit/images/mac/filesave.png b/examples/richtext/textedit/images/mac/filesave.png new file mode 100644 index 0000000000..b41ecf5319 Binary files /dev/null and b/examples/richtext/textedit/images/mac/filesave.png differ diff --git a/examples/richtext/textedit/images/mac/textbold.png b/examples/richtext/textedit/images/mac/textbold.png new file mode 100644 index 0000000000..38400bd1f6 Binary files /dev/null and b/examples/richtext/textedit/images/mac/textbold.png differ diff --git a/examples/richtext/textedit/images/mac/textcenter.png b/examples/richtext/textedit/images/mac/textcenter.png new file mode 100644 index 0000000000..2ef5b2ee6f Binary files /dev/null and b/examples/richtext/textedit/images/mac/textcenter.png differ diff --git a/examples/richtext/textedit/images/mac/textitalic.png b/examples/richtext/textedit/images/mac/textitalic.png new file mode 100644 index 0000000000..0170ee26a6 Binary files /dev/null and b/examples/richtext/textedit/images/mac/textitalic.png differ diff --git a/examples/richtext/textedit/images/mac/textjustify.png b/examples/richtext/textedit/images/mac/textjustify.png new file mode 100644 index 0000000000..39cd6c1a9d Binary files /dev/null and b/examples/richtext/textedit/images/mac/textjustify.png differ diff --git a/examples/richtext/textedit/images/mac/textleft.png b/examples/richtext/textedit/images/mac/textleft.png new file mode 100644 index 0000000000..83a66d5535 Binary files /dev/null and b/examples/richtext/textedit/images/mac/textleft.png differ diff --git a/examples/richtext/textedit/images/mac/textright.png b/examples/richtext/textedit/images/mac/textright.png new file mode 100644 index 0000000000..e7c04645cf Binary files /dev/null and b/examples/richtext/textedit/images/mac/textright.png differ diff --git a/examples/richtext/textedit/images/mac/textunder.png b/examples/richtext/textedit/images/mac/textunder.png new file mode 100644 index 0000000000..968bac5e90 Binary files /dev/null and b/examples/richtext/textedit/images/mac/textunder.png differ diff --git a/examples/richtext/textedit/images/mac/zoomin.png b/examples/richtext/textedit/images/mac/zoomin.png new file mode 100644 index 0000000000..d46f5aff0d Binary files /dev/null and b/examples/richtext/textedit/images/mac/zoomin.png differ diff --git a/examples/richtext/textedit/images/mac/zoomout.png b/examples/richtext/textedit/images/mac/zoomout.png new file mode 100644 index 0000000000..46326566d1 Binary files /dev/null and b/examples/richtext/textedit/images/mac/zoomout.png differ diff --git a/examples/richtext/textedit/images/win/editcopy.png b/examples/richtext/textedit/images/win/editcopy.png new file mode 100644 index 0000000000..1121b47d8b Binary files /dev/null and b/examples/richtext/textedit/images/win/editcopy.png differ diff --git a/examples/richtext/textedit/images/win/editcut.png b/examples/richtext/textedit/images/win/editcut.png new file mode 100644 index 0000000000..38e55f7420 Binary files /dev/null and b/examples/richtext/textedit/images/win/editcut.png differ diff --git a/examples/richtext/textedit/images/win/editpaste.png b/examples/richtext/textedit/images/win/editpaste.png new file mode 100644 index 0000000000..ffab15aaf8 Binary files /dev/null and b/examples/richtext/textedit/images/win/editpaste.png differ diff --git a/examples/richtext/textedit/images/win/editredo.png b/examples/richtext/textedit/images/win/editredo.png new file mode 100644 index 0000000000..9d679fe6fc Binary files /dev/null and b/examples/richtext/textedit/images/win/editredo.png differ diff --git a/examples/richtext/textedit/images/win/editundo.png b/examples/richtext/textedit/images/win/editundo.png new file mode 100644 index 0000000000..eee23d24a3 Binary files /dev/null and b/examples/richtext/textedit/images/win/editundo.png differ diff --git a/examples/richtext/textedit/images/win/exportpdf.png b/examples/richtext/textedit/images/win/exportpdf.png new file mode 100644 index 0000000000..eef5132928 Binary files /dev/null and b/examples/richtext/textedit/images/win/exportpdf.png differ diff --git a/examples/richtext/textedit/images/win/filenew.png b/examples/richtext/textedit/images/win/filenew.png new file mode 100644 index 0000000000..af5d122141 Binary files /dev/null and b/examples/richtext/textedit/images/win/filenew.png differ diff --git a/examples/richtext/textedit/images/win/fileopen.png b/examples/richtext/textedit/images/win/fileopen.png new file mode 100644 index 0000000000..fc6f17e977 Binary files /dev/null and b/examples/richtext/textedit/images/win/fileopen.png differ diff --git a/examples/richtext/textedit/images/win/fileprint.png b/examples/richtext/textedit/images/win/fileprint.png new file mode 100644 index 0000000000..ba7c02dc18 Binary files /dev/null and b/examples/richtext/textedit/images/win/fileprint.png differ diff --git a/examples/richtext/textedit/images/win/filesave.png b/examples/richtext/textedit/images/win/filesave.png new file mode 100644 index 0000000000..8feec99bee Binary files /dev/null and b/examples/richtext/textedit/images/win/filesave.png differ diff --git a/examples/richtext/textedit/images/win/textbold.png b/examples/richtext/textedit/images/win/textbold.png new file mode 100644 index 0000000000..9cbc7138b9 Binary files /dev/null and b/examples/richtext/textedit/images/win/textbold.png differ diff --git a/examples/richtext/textedit/images/win/textcenter.png b/examples/richtext/textedit/images/win/textcenter.png new file mode 100644 index 0000000000..11efb4b852 Binary files /dev/null and b/examples/richtext/textedit/images/win/textcenter.png differ diff --git a/examples/richtext/textedit/images/win/textitalic.png b/examples/richtext/textedit/images/win/textitalic.png new file mode 100644 index 0000000000..b30ce14c14 Binary files /dev/null and b/examples/richtext/textedit/images/win/textitalic.png differ diff --git a/examples/richtext/textedit/images/win/textjustify.png b/examples/richtext/textedit/images/win/textjustify.png new file mode 100644 index 0000000000..9de0c88085 Binary files /dev/null and b/examples/richtext/textedit/images/win/textjustify.png differ diff --git a/examples/richtext/textedit/images/win/textleft.png b/examples/richtext/textedit/images/win/textleft.png new file mode 100644 index 0000000000..16f80bc325 Binary files /dev/null and b/examples/richtext/textedit/images/win/textleft.png differ diff --git a/examples/richtext/textedit/images/win/textright.png b/examples/richtext/textedit/images/win/textright.png new file mode 100644 index 0000000000..16872df62a Binary files /dev/null and b/examples/richtext/textedit/images/win/textright.png differ diff --git a/examples/richtext/textedit/images/win/textunder.png b/examples/richtext/textedit/images/win/textunder.png new file mode 100644 index 0000000000..c72eff53fb Binary files /dev/null and b/examples/richtext/textedit/images/win/textunder.png differ diff --git a/examples/richtext/textedit/images/win/zoomin.png b/examples/richtext/textedit/images/win/zoomin.png new file mode 100644 index 0000000000..2e586fc7bf Binary files /dev/null and b/examples/richtext/textedit/images/win/zoomin.png differ diff --git a/examples/richtext/textedit/images/win/zoomout.png b/examples/richtext/textedit/images/win/zoomout.png new file mode 100644 index 0000000000..a736d39343 Binary files /dev/null and b/examples/richtext/textedit/images/win/zoomout.png differ diff --git a/examples/richtext/textedit/main.cpp b/examples/richtext/textedit/main.cpp new file mode 100644 index 0000000000..036fa80ba7 --- /dev/null +++ b/examples/richtext/textedit/main.cpp @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "textedit.h" +#include + +int main( int argc, char ** argv ) +{ + Q_INIT_RESOURCE(textedit); + + QApplication a( argc, argv ); + TextEdit mw; + mw.resize( 700, 800 ); + mw.show(); + return a.exec(); +} diff --git a/examples/richtext/textedit/textedit.cpp b/examples/richtext/textedit/textedit.cpp new file mode 100644 index 0000000000..c8373262c9 --- /dev/null +++ b/examples/richtext/textedit/textedit.cpp @@ -0,0 +1,734 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "textedit.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef Q_WS_MAC +const QString rsrcPath = ":/images/mac"; +#else +const QString rsrcPath = ":/images/win"; +#endif + +TextEdit::TextEdit(QWidget *parent) + : QMainWindow(parent) +{ + setToolButtonStyle(Qt::ToolButtonFollowStyle); + setupFileActions(); + setupEditActions(); + setupTextActions(); + + { + QMenu *helpMenu = new QMenu(tr("Help"), this); + menuBar()->addMenu(helpMenu); + helpMenu->addAction(tr("About"), this, SLOT(about())); + helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt())); + } + + textEdit = new QTextEdit(this); + connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)), + this, SLOT(currentCharFormatChanged(QTextCharFormat))); + connect(textEdit, SIGNAL(cursorPositionChanged()), + this, SLOT(cursorPositionChanged())); + + setCentralWidget(textEdit); + textEdit->setFocus(); + setCurrentFileName(QString()); + + fontChanged(textEdit->font()); + colorChanged(textEdit->textColor()); + alignmentChanged(textEdit->alignment()); + + connect(textEdit->document(), SIGNAL(modificationChanged(bool)), + actionSave, SLOT(setEnabled(bool))); + connect(textEdit->document(), SIGNAL(modificationChanged(bool)), + this, SLOT(setWindowModified(bool))); + connect(textEdit->document(), SIGNAL(undoAvailable(bool)), + actionUndo, SLOT(setEnabled(bool))); + connect(textEdit->document(), SIGNAL(redoAvailable(bool)), + actionRedo, SLOT(setEnabled(bool))); + + setWindowModified(textEdit->document()->isModified()); + actionSave->setEnabled(textEdit->document()->isModified()); + actionUndo->setEnabled(textEdit->document()->isUndoAvailable()); + actionRedo->setEnabled(textEdit->document()->isRedoAvailable()); + + connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo())); + connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo())); + + actionCut->setEnabled(false); + actionCopy->setEnabled(false); + + connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut())); + connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy())); + connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste())); + + connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool))); + connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool))); + +#ifndef QT_NO_CLIPBOARD + connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged())); +#endif + + QString initialFile = ":/example.html"; + const QStringList args = QCoreApplication::arguments(); + if (args.count() == 2) + initialFile = args.at(1); + + if (!load(initialFile)) + fileNew(); +} + +void TextEdit::closeEvent(QCloseEvent *e) +{ + if (maybeSave()) + e->accept(); + else + e->ignore(); +} + +void TextEdit::setupFileActions() +{ + QToolBar *tb = new QToolBar(this); + tb->setWindowTitle(tr("File Actions")); + addToolBar(tb); + + QMenu *menu = new QMenu(tr("&File"), this); + menuBar()->addMenu(menu); + + QAction *a; + + QIcon newIcon = QIcon::fromTheme("document-new", QIcon(rsrcPath + "/filenew.png")); + a = new QAction( newIcon, tr("&New"), this); + a->setPriority(QAction::LowPriority); + a->setShortcut(QKeySequence::New); + connect(a, SIGNAL(triggered()), this, SLOT(fileNew())); + tb->addAction(a); + menu->addAction(a); + + a = new QAction(QIcon::fromTheme("document-open", QIcon(rsrcPath + "/fileopen.png")), + tr("&Open..."), this); + a->setShortcut(QKeySequence::Open); + connect(a, SIGNAL(triggered()), this, SLOT(fileOpen())); + tb->addAction(a); + menu->addAction(a); + + menu->addSeparator(); + + actionSave = a = new QAction(QIcon::fromTheme("document-save", QIcon(rsrcPath + "/filesave.png")), + tr("&Save"), this); + a->setShortcut(QKeySequence::Save); + connect(a, SIGNAL(triggered()), this, SLOT(fileSave())); + a->setEnabled(false); + tb->addAction(a); + menu->addAction(a); + + a = new QAction(tr("Save &As..."), this); + a->setPriority(QAction::LowPriority); + connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs())); + menu->addAction(a); + menu->addSeparator(); + +#ifndef QT_NO_PRINTER + a = new QAction(QIcon::fromTheme("document-print", QIcon(rsrcPath + "/fileprint.png")), + tr("&Print..."), this); + a->setPriority(QAction::LowPriority); + a->setShortcut(QKeySequence::Print); + connect(a, SIGNAL(triggered()), this, SLOT(filePrint())); + tb->addAction(a); + menu->addAction(a); + + a = new QAction(QIcon::fromTheme("fileprint", QIcon(rsrcPath + "/fileprint.png")), + tr("Print Preview..."), this); + connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview())); + menu->addAction(a); + + a = new QAction(QIcon::fromTheme("exportpdf", QIcon(rsrcPath + "/exportpdf.png")), + tr("&Export PDF..."), this); + a->setPriority(QAction::LowPriority); + a->setShortcut(Qt::CTRL + Qt::Key_D); + connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf())); + tb->addAction(a); + menu->addAction(a); + + menu->addSeparator(); +#endif + + a = new QAction(tr("&Quit"), this); + a->setShortcut(Qt::CTRL + Qt::Key_Q); + connect(a, SIGNAL(triggered()), this, SLOT(close())); + menu->addAction(a); +} + +void TextEdit::setupEditActions() +{ + QToolBar *tb = new QToolBar(this); + tb->setWindowTitle(tr("Edit Actions")); + addToolBar(tb); + QMenu *menu = new QMenu(tr("&Edit"), this); + menuBar()->addMenu(menu); + + QAction *a; + a = actionUndo = new QAction(QIcon::fromTheme("edit-undo", QIcon(rsrcPath + "/editundo.png")), + tr("&Undo"), this); + a->setShortcut(QKeySequence::Undo); + tb->addAction(a); + menu->addAction(a); + a = actionRedo = new QAction(QIcon::fromTheme("edit-redo", QIcon(rsrcPath + "/editredo.png")), + tr("&Redo"), this); + a->setPriority(QAction::LowPriority); + a->setShortcut(QKeySequence::Redo); + tb->addAction(a); + menu->addAction(a); + menu->addSeparator(); + a = actionCut = new QAction(QIcon::fromTheme("edit-cut", QIcon(rsrcPath + "/editcut.png")), + tr("Cu&t"), this); + a->setPriority(QAction::LowPriority); + a->setShortcut(QKeySequence::Cut); + tb->addAction(a); + menu->addAction(a); + a = actionCopy = new QAction(QIcon::fromTheme("edit-copy", QIcon(rsrcPath + "/editcopy.png")), + tr("&Copy"), this); + a->setPriority(QAction::LowPriority); + a->setShortcut(QKeySequence::Copy); + tb->addAction(a); + menu->addAction(a); + a = actionPaste = new QAction(QIcon::fromTheme("edit-paste", QIcon(rsrcPath + "/editpaste.png")), + tr("&Paste"), this); + a->setPriority(QAction::LowPriority); + a->setShortcut(QKeySequence::Paste); + tb->addAction(a); + menu->addAction(a); +#ifndef QT_NO_CLIPBOARD + if (const QMimeData *md = QApplication::clipboard()->mimeData()) + actionPaste->setEnabled(md->hasText()); +#endif +} + +void TextEdit::setupTextActions() +{ + QToolBar *tb = new QToolBar(this); + tb->setWindowTitle(tr("Format Actions")); + addToolBar(tb); + + QMenu *menu = new QMenu(tr("F&ormat"), this); + menuBar()->addMenu(menu); + + actionTextBold = new QAction(QIcon::fromTheme("format-text-bold", QIcon(rsrcPath + "/textbold.png")), + tr("&Bold"), this); + actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); + actionTextBold->setPriority(QAction::LowPriority); + QFont bold; + bold.setBold(true); + actionTextBold->setFont(bold); + connect(actionTextBold, SIGNAL(triggered()), this, SLOT(textBold())); + tb->addAction(actionTextBold); + menu->addAction(actionTextBold); + actionTextBold->setCheckable(true); + + actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic", QIcon(rsrcPath + "/textitalic.png")), + tr("&Italic"), this); + actionTextItalic->setPriority(QAction::LowPriority); + actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); + QFont italic; + italic.setItalic(true); + actionTextItalic->setFont(italic); + connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic())); + tb->addAction(actionTextItalic); + menu->addAction(actionTextItalic); + actionTextItalic->setCheckable(true); + + actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline", QIcon(rsrcPath + "/textunder.png")), + tr("&Underline"), this); + actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); + actionTextUnderline->setPriority(QAction::LowPriority); + QFont underline; + underline.setUnderline(true); + actionTextUnderline->setFont(underline); + connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline())); + tb->addAction(actionTextUnderline); + menu->addAction(actionTextUnderline); + actionTextUnderline->setCheckable(true); + + menu->addSeparator(); + + QActionGroup *grp = new QActionGroup(this); + connect(grp, SIGNAL(triggered(QAction*)), this, SLOT(textAlign(QAction*))); + + // Make sure the alignLeft is always left of the alignRight + if (QApplication::isLeftToRight()) { + actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")), + tr("&Left"), grp); + actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp); + actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp); + } else { + actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp); + actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp); + actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")), tr("&Left"), grp); + } + actionAlignJustify = new QAction(QIcon::fromTheme("format-justify-fill", QIcon(rsrcPath + "/textjustify.png")), tr("&Justify"), grp); + + actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); + actionAlignLeft->setCheckable(true); + actionAlignLeft->setPriority(QAction::LowPriority); + actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); + actionAlignCenter->setCheckable(true); + actionAlignCenter->setPriority(QAction::LowPriority); + actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); + actionAlignRight->setCheckable(true); + actionAlignRight->setPriority(QAction::LowPriority); + actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); + actionAlignJustify->setCheckable(true); + actionAlignJustify->setPriority(QAction::LowPriority); + + tb->addActions(grp->actions()); + menu->addActions(grp->actions()); + + menu->addSeparator(); + + QPixmap pix(16, 16); + pix.fill(Qt::black); + actionTextColor = new QAction(pix, tr("&Color..."), this); + connect(actionTextColor, SIGNAL(triggered()), this, SLOT(textColor())); + tb->addAction(actionTextColor); + menu->addAction(actionTextColor); + + + tb = new QToolBar(this); + tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea); + tb->setWindowTitle(tr("Format Actions")); + addToolBarBreak(Qt::TopToolBarArea); + addToolBar(tb); + + comboStyle = new QComboBox(tb); + tb->addWidget(comboStyle); + comboStyle->addItem("Standard"); + comboStyle->addItem("Bullet List (Disc)"); + comboStyle->addItem("Bullet List (Circle)"); + comboStyle->addItem("Bullet List (Square)"); + comboStyle->addItem("Ordered List (Decimal)"); + comboStyle->addItem("Ordered List (Alpha lower)"); + comboStyle->addItem("Ordered List (Alpha upper)"); + comboStyle->addItem("Ordered List (Roman lower)"); + comboStyle->addItem("Ordered List (Roman upper)"); + connect(comboStyle, SIGNAL(activated(int)), + this, SLOT(textStyle(int))); + + comboFont = new QFontComboBox(tb); + tb->addWidget(comboFont); + connect(comboFont, SIGNAL(activated(QString)), + this, SLOT(textFamily(QString))); + + comboSize = new QComboBox(tb); + comboSize->setObjectName("comboSize"); + tb->addWidget(comboSize); + comboSize->setEditable(true); + + QFontDatabase db; + foreach(int size, db.standardSizes()) + comboSize->addItem(QString::number(size)); + + connect(comboSize, SIGNAL(activated(QString)), + this, SLOT(textSize(QString))); + comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font() + .pointSize()))); +} + +bool TextEdit::load(const QString &f) +{ + if (!QFile::exists(f)) + return false; + QFile file(f); + if (!file.open(QFile::ReadOnly)) + return false; + + QByteArray data = file.readAll(); + QTextCodec *codec = Qt::codecForHtml(data); + QString str = codec->toUnicode(data); + if (Qt::mightBeRichText(str)) { + textEdit->setHtml(str); + } else { + str = QString::fromLocal8Bit(data); + textEdit->setPlainText(str); + } + + setCurrentFileName(f); + return true; +} + +bool TextEdit::maybeSave() +{ + if (!textEdit->document()->isModified()) + return true; + if (fileName.startsWith(QLatin1String(":/"))) + return true; + QMessageBox::StandardButton ret; + ret = QMessageBox::warning(this, 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 fileSave(); + else if (ret == QMessageBox::Cancel) + return false; + return true; +} + +void TextEdit::setCurrentFileName(const QString &fileName) +{ + this->fileName = fileName; + textEdit->document()->setModified(false); + + QString shownName; + if (fileName.isEmpty()) + shownName = "untitled.txt"; + else + shownName = QFileInfo(fileName).fileName(); + + setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text"))); + setWindowModified(false); +} + +void TextEdit::fileNew() +{ + if (maybeSave()) { + textEdit->clear(); + setCurrentFileName(QString()); + } +} + +void TextEdit::fileOpen() +{ + QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."), + QString(), tr("HTML-Files (*.htm *.html);;All Files (*)")); + if (!fn.isEmpty()) + load(fn); +} + +bool TextEdit::fileSave() +{ + if (fileName.isEmpty()) + return fileSaveAs(); + + QTextDocumentWriter writer(fileName); + bool success = writer.write(textEdit->document()); + if (success) + textEdit->document()->setModified(false); + return success; +} + +bool TextEdit::fileSaveAs() +{ + QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."), + QString(), tr("ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)")); + if (fn.isEmpty()) + return false; + if (! (fn.endsWith(".odt", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive)) ) + fn += ".odt"; // default + setCurrentFileName(fn); + return fileSave(); +} + +void TextEdit::filePrint() +{ +#ifndef QT_NO_PRINTER + QPrinter printer(QPrinter::HighResolution); + QPrintDialog *dlg = new QPrintDialog(&printer, this); + if (textEdit->textCursor().hasSelection()) + dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); + dlg->setWindowTitle(tr("Print Document")); + if (dlg->exec() == QDialog::Accepted) { + textEdit->print(&printer); + } + delete dlg; +#endif +} + +void TextEdit::filePrintPreview() +{ +#ifndef QT_NO_PRINTER + QPrinter printer(QPrinter::HighResolution); + QPrintPreviewDialog preview(&printer, this); + connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*))); + preview.exec(); +#endif +} + +void TextEdit::printPreview(QPrinter *printer) +{ +#ifdef QT_NO_PRINTER + Q_UNUSED(printer); +#else + textEdit->print(printer); +#endif +} + + +void TextEdit::filePrintPdf() +{ +#ifndef QT_NO_PRINTER +//! [0] + QString fileName = QFileDialog::getSaveFileName(this, "Export PDF", + QString(), "*.pdf"); + if (!fileName.isEmpty()) { + if (QFileInfo(fileName).suffix().isEmpty()) + fileName.append(".pdf"); + QPrinter printer(QPrinter::HighResolution); + printer.setOutputFormat(QPrinter::PdfFormat); + printer.setOutputFileName(fileName); + textEdit->document()->print(&printer); + } +//! [0] +#endif +} + +void TextEdit::textBold() +{ + QTextCharFormat fmt; + fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); + mergeFormatOnWordOrSelection(fmt); +} + +void TextEdit::textUnderline() +{ + QTextCharFormat fmt; + fmt.setFontUnderline(actionTextUnderline->isChecked()); + mergeFormatOnWordOrSelection(fmt); +} + +void TextEdit::textItalic() +{ + QTextCharFormat fmt; + fmt.setFontItalic(actionTextItalic->isChecked()); + mergeFormatOnWordOrSelection(fmt); +} + +void TextEdit::textFamily(const QString &f) +{ + QTextCharFormat fmt; + fmt.setFontFamily(f); + mergeFormatOnWordOrSelection(fmt); +} + +void TextEdit::textSize(const QString &p) +{ + qreal pointSize = p.toFloat(); + if (p.toFloat() > 0) { + QTextCharFormat fmt; + fmt.setFontPointSize(pointSize); + mergeFormatOnWordOrSelection(fmt); + } +} + +void TextEdit::textStyle(int styleIndex) +{ + QTextCursor cursor = textEdit->textCursor(); + + if (styleIndex != 0) { + QTextListFormat::Style style = QTextListFormat::ListDisc; + + switch (styleIndex) { + default: + case 1: + style = QTextListFormat::ListDisc; + break; + case 2: + style = QTextListFormat::ListCircle; + break; + case 3: + style = QTextListFormat::ListSquare; + break; + case 4: + style = QTextListFormat::ListDecimal; + break; + case 5: + style = QTextListFormat::ListLowerAlpha; + break; + case 6: + style = QTextListFormat::ListUpperAlpha; + break; + case 7: + style = QTextListFormat::ListLowerRoman; + break; + case 8: + style = QTextListFormat::ListUpperRoman; + break; + } + + cursor.beginEditBlock(); + + QTextBlockFormat blockFmt = cursor.blockFormat(); + + QTextListFormat listFmt; + + if (cursor.currentList()) { + listFmt = cursor.currentList()->format(); + } else { + listFmt.setIndent(blockFmt.indent() + 1); + blockFmt.setIndent(0); + cursor.setBlockFormat(blockFmt); + } + + listFmt.setStyle(style); + + cursor.createList(listFmt); + + cursor.endEditBlock(); + } else { + // #### + QTextBlockFormat bfmt; + bfmt.setObjectIndex(-1); + cursor.mergeBlockFormat(bfmt); + } +} + +void TextEdit::textColor() +{ + QColor col = QColorDialog::getColor(textEdit->textColor(), this); + if (!col.isValid()) + return; + QTextCharFormat fmt; + fmt.setForeground(col); + mergeFormatOnWordOrSelection(fmt); + colorChanged(col); +} + +void TextEdit::textAlign(QAction *a) +{ + if (a == actionAlignLeft) + textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); + else if (a == actionAlignCenter) + textEdit->setAlignment(Qt::AlignHCenter); + else if (a == actionAlignRight) + textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); + else if (a == actionAlignJustify) + textEdit->setAlignment(Qt::AlignJustify); +} + +void TextEdit::currentCharFormatChanged(const QTextCharFormat &format) +{ + fontChanged(format.font()); + colorChanged(format.foreground().color()); +} + +void TextEdit::cursorPositionChanged() +{ + alignmentChanged(textEdit->alignment()); +} + +void TextEdit::clipboardDataChanged() +{ +#ifndef QT_NO_CLIPBOARD + if (const QMimeData *md = QApplication::clipboard()->mimeData()) + actionPaste->setEnabled(md->hasText()); +#endif +} + +void TextEdit::about() +{ + QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's " + "rich text editing facilities in action, providing an example " + "document for you to experiment with.")); +} + +void TextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format) +{ + QTextCursor cursor = textEdit->textCursor(); + if (!cursor.hasSelection()) + cursor.select(QTextCursor::WordUnderCursor); + cursor.mergeCharFormat(format); + textEdit->mergeCurrentCharFormat(format); +} + +void TextEdit::fontChanged(const QFont &f) +{ + comboFont->setCurrentIndex(comboFont->findText(QFontInfo(f).family())); + comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize()))); + actionTextBold->setChecked(f.bold()); + actionTextItalic->setChecked(f.italic()); + actionTextUnderline->setChecked(f.underline()); +} + +void TextEdit::colorChanged(const QColor &c) +{ + QPixmap pix(16, 16); + pix.fill(c); + actionTextColor->setIcon(pix); +} + +void TextEdit::alignmentChanged(Qt::Alignment a) +{ + if (a & Qt::AlignLeft) { + actionAlignLeft->setChecked(true); + } else if (a & Qt::AlignHCenter) { + actionAlignCenter->setChecked(true); + } else if (a & Qt::AlignRight) { + actionAlignRight->setChecked(true); + } else if (a & Qt::AlignJustify) { + actionAlignJustify->setChecked(true); + } +} + diff --git a/examples/richtext/textedit/textedit.h b/examples/richtext/textedit/textedit.h new file mode 100644 index 0000000000..6436178ab5 --- /dev/null +++ b/examples/richtext/textedit/textedit.h @@ -0,0 +1,129 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TEXTEDIT_H +#define TEXTEDIT_H + +#include +#include +#include + +QT_FORWARD_DECLARE_CLASS(QAction) +QT_FORWARD_DECLARE_CLASS(QComboBox) +QT_FORWARD_DECLARE_CLASS(QFontComboBox) +QT_FORWARD_DECLARE_CLASS(QTextEdit) +QT_FORWARD_DECLARE_CLASS(QTextCharFormat) +QT_FORWARD_DECLARE_CLASS(QMenu) + +class TextEdit : public QMainWindow +{ + Q_OBJECT + +public: + TextEdit(QWidget *parent = 0); + +protected: + virtual void closeEvent(QCloseEvent *e); + +private: + void setupFileActions(); + void setupEditActions(); + void setupTextActions(); + bool load(const QString &f); + bool maybeSave(); + void setCurrentFileName(const QString &fileName); + +private slots: + void fileNew(); + void fileOpen(); + bool fileSave(); + bool fileSaveAs(); + void filePrint(); + void filePrintPreview(); + void filePrintPdf(); + + void textBold(); + void textUnderline(); + void textItalic(); + void textFamily(const QString &f); + void textSize(const QString &p); + void textStyle(int styleIndex); + void textColor(); + void textAlign(QAction *a); + + void currentCharFormatChanged(const QTextCharFormat &format); + void cursorPositionChanged(); + + void clipboardDataChanged(); + void about(); + void printPreview(QPrinter *); + +private: + void mergeFormatOnWordOrSelection(const QTextCharFormat &format); + void fontChanged(const QFont &f); + void colorChanged(const QColor &c); + void alignmentChanged(Qt::Alignment a); + + QAction *actionSave, + *actionTextBold, + *actionTextUnderline, + *actionTextItalic, + *actionTextColor, + *actionAlignLeft, + *actionAlignCenter, + *actionAlignRight, + *actionAlignJustify, + *actionUndo, + *actionRedo, + *actionCut, + *actionCopy, + *actionPaste; + + QComboBox *comboStyle; + QFontComboBox *comboFont; + QComboBox *comboSize; + + QToolBar *tb; + QString fileName; + QTextEdit *textEdit; +}; + +#endif diff --git a/examples/richtext/textedit/textedit.pro b/examples/richtext/textedit/textedit.pro new file mode 100644 index 0000000000..b37ac3036a --- /dev/null +++ b/examples/richtext/textedit/textedit.pro @@ -0,0 +1,22 @@ +TEMPLATE = app +TARGET = textedit + +CONFIG += qt warn_on + +HEADERS = textedit.h +SOURCES = textedit.cpp \ + main.cpp + +RESOURCES += textedit.qrc +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/textedit +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html *.doc images +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/textedit +INSTALLS += target sources + +symbian: CONFIG += qt_demo diff --git a/examples/richtext/textedit/textedit.qdoc b/examples/richtext/textedit/textedit.qdoc new file mode 100644 index 0000000000..8fc9609407 --- /dev/null +++ b/examples/richtext/textedit/textedit.qdoc @@ -0,0 +1,45 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! \page textedit-example.html + + \ingroup examples + \title Text Edit Example + + This example displays a text editor with the user interface written + in pure C++. + + A similar example which uses \link designer-manual.book Qt + Designer\endlink to produce the user interface is in the \link + designer-manual.book Qt Designer manual\endlink. + + + See \c{$QTDIR/examples/textedit} for the source code. + +*/ + + diff --git a/examples/richtext/textedit/textedit.qrc b/examples/richtext/textedit/textedit.qrc new file mode 100644 index 0000000000..7d6efd7d67 --- /dev/null +++ b/examples/richtext/textedit/textedit.qrc @@ -0,0 +1,44 @@ + + + images/logo32.png + images/mac/editcopy.png + images/mac/editcut.png + images/mac/editpaste.png + images/mac/editredo.png + images/mac/editundo.png + images/mac/exportpdf.png + images/mac/filenew.png + images/mac/fileopen.png + images/mac/fileprint.png + images/mac/filesave.png + images/mac/textbold.png + images/mac/textcenter.png + images/mac/textitalic.png + images/mac/textjustify.png + images/mac/textleft.png + images/mac/textright.png + images/mac/textunder.png + images/mac/zoomin.png + images/mac/zoomout.png + images/win/editcopy.png + images/win/editcut.png + images/win/editpaste.png + images/win/editredo.png + images/win/editundo.png + images/win/exportpdf.png + images/win/filenew.png + images/win/fileopen.png + images/win/fileprint.png + images/win/filesave.png + images/win/textbold.png + images/win/textcenter.png + images/win/textitalic.png + images/win/textjustify.png + images/win/textleft.png + images/win/textright.png + images/win/textunder.png + images/win/zoomin.png + images/win/zoomout.png + example.html + + diff --git a/examples/sql/books/bookdelegate.cpp b/examples/sql/books/bookdelegate.cpp new file mode 100644 index 0000000000..566dd81928 --- /dev/null +++ b/examples/sql/books/bookdelegate.cpp @@ -0,0 +1,126 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "bookdelegate.h" + +#include + +BookDelegate::BookDelegate(QObject *parent) + : QSqlRelationalDelegate(parent), star(QPixmap(":images/star.png")) +{ +} + +void BookDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.column() != 5) { + QStyleOptionViewItemV3 opt = option; + opt.rect.adjust(0, 0, -1, -1); // since we draw the grid ourselves + QSqlRelationalDelegate::paint(painter, opt, index); + } else { + const QAbstractItemModel *model = index.model(); + QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled) ? + (option.state & QStyle::State_Active) ? QPalette::Normal : QPalette::Inactive : QPalette::Disabled; + + if (option.state & QStyle::State_Selected) + painter->fillRect(option.rect, option.palette.color(cg, QPalette::Highlight)); + + int rating = model->data(index, Qt::DisplayRole).toInt(); + int width = star.width(); + int height = star.height(); + int x = option.rect.x(); + int y = option.rect.y() + (option.rect.height() / 2) - (height / 2); + for (int i = 0; i < rating; ++i) { + painter->drawPixmap(x, y, star); + x += width; + } + drawFocus(painter, option, option.rect.adjusted(0, 0, -1, -1)); // since we draw the grid ourselves + } + + QPen pen = painter->pen(); + painter->setPen(option.palette.color(QPalette::Mid)); + painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); + painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); + painter->setPen(pen); +} + +QSize BookDelegate::sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.column() == 5) + return QSize(5 * star.width(), star.height()) + QSize(1, 1); + + return QSqlRelationalDelegate::sizeHint(option, index) + QSize(1, 1); // since we draw the grid ourselves +} + +bool BookDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, + const QStyleOptionViewItem &option, + const QModelIndex &index) +{ + if (index.column() != 5) + return QSqlRelationalDelegate::editorEvent(event, model, option, index); + + if (event->type() == QEvent::MouseButtonPress) { + QMouseEvent *mouseEvent = static_cast(event); + int stars = qBound(0, int(0.7 + qreal(mouseEvent->pos().x() + - option.rect.x()) / star.width()), 5); + model->setData(index, QVariant(stars)); + return false; //so that the selection can change + } + + return true; +} + +QWidget *BookDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.column() != 4) + return QSqlRelationalDelegate::createEditor(parent, option, index); + + // for editing the year, return a spinbox with a range from -1000 to 2100. + QSpinBox *sb = new QSpinBox(parent); + sb->setFrame(false); + sb->setMaximum(2100); + sb->setMinimum(-1000); + + return sb; +} + diff --git a/examples/sql/books/bookdelegate.h b/examples/sql/books/bookdelegate.h new file mode 100644 index 0000000000..5dc39c0223 --- /dev/null +++ b/examples/sql/books/bookdelegate.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef BOOKDELEGATE_H +#define BOOKDELEGATE_H + +#include +#include +#include +#include + +QT_FORWARD_DECLARE_CLASS(QPainter) + +class BookDelegate : public QSqlRelationalDelegate +{ +public: + BookDelegate(QObject *parent); + + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; + + bool editorEvent(QEvent *event, QAbstractItemModel *model, + const QStyleOptionViewItem &option, + const QModelIndex &index); + + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + +private: + QPixmap star; +}; + +#endif diff --git a/examples/sql/books/books.pro b/examples/sql/books/books.pro new file mode 100644 index 0000000000..1588288f3e --- /dev/null +++ b/examples/sql/books/books.pro @@ -0,0 +1,23 @@ +TEMPLATE = app +INCLUDEPATH += . + +HEADERS = bookdelegate.h bookwindow.h initdb.h +RESOURCES = books.qrc +SOURCES = bookdelegate.cpp main.cpp bookwindow.cpp +FORMS = bookwindow.ui + +QT += sql + +target.path = $$[QT_INSTALL_DEMOS]/qtbase/books +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro images +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/books +INSTALLS += target sources + +symbian: CONFIG += qt_demo + +wince*: { + CONFIG(debug, debug|release):sqlPlugins.files = $$QT_BUILD_TREE/plugins/sqldrivers/*d4.dll + CONFIG(release, debug|release):sqlPlugins.files = $$QT_BUILD_TREE/plugins/sqldrivers/*[^d]4.dll + sqlPlugins.path = sqldrivers + DEPLOYMENT += sqlPlugins +} diff --git a/examples/sql/books/books.qrc b/examples/sql/books/books.qrc new file mode 100644 index 0000000000..342638ecb0 --- /dev/null +++ b/examples/sql/books/books.qrc @@ -0,0 +1,5 @@ + + + images/star.png + + diff --git a/examples/sql/books/bookwindow.cpp b/examples/sql/books/bookwindow.cpp new file mode 100644 index 0000000000..40d23d1761 --- /dev/null +++ b/examples/sql/books/bookwindow.cpp @@ -0,0 +1,121 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "bookwindow.h" +#include "bookdelegate.h" +#include "initdb.h" + +#include + +BookWindow::BookWindow() +{ + ui.setupUi(this); + + if (!QSqlDatabase::drivers().contains("QSQLITE")) + QMessageBox::critical(this, "Unable to load database", "This demo needs the SQLITE driver"); + + // initialize the database + QSqlError err = initDb(); + if (err.type() != QSqlError::NoError) { + showError(err); + return; + } + + // Create the data model + model = new QSqlRelationalTableModel(ui.bookTable); + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + model->setTable("books"); + + // Remember the indexes of the columns + authorIdx = model->fieldIndex("author"); + genreIdx = model->fieldIndex("genre"); + + // Set the relations to the other database tables + model->setRelation(authorIdx, QSqlRelation("authors", "id", "name")); + model->setRelation(genreIdx, QSqlRelation("genres", "id", "name")); + + // Set the localized header captions + model->setHeaderData(authorIdx, Qt::Horizontal, tr("Author Name")); + model->setHeaderData(genreIdx, Qt::Horizontal, tr("Genre")); + model->setHeaderData(model->fieldIndex("title"), Qt::Horizontal, tr("Title")); + model->setHeaderData(model->fieldIndex("year"), Qt::Horizontal, tr("Year")); + model->setHeaderData(model->fieldIndex("rating"), Qt::Horizontal, tr("Rating")); + + // Populate the model + if (!model->select()) { + showError(model->lastError()); + return; + } + + // Set the model and hide the ID column + ui.bookTable->setModel(model); + ui.bookTable->setItemDelegate(new BookDelegate(ui.bookTable)); + ui.bookTable->setColumnHidden(model->fieldIndex("id"), true); + ui.bookTable->setSelectionMode(QAbstractItemView::SingleSelection); + + // Initialize the Author combo box + ui.authorEdit->setModel(model->relationModel(authorIdx)); + ui.authorEdit->setModelColumn(model->relationModel(authorIdx)->fieldIndex("name")); + + ui.genreEdit->setModel(model->relationModel(genreIdx)); + ui.genreEdit->setModelColumn(model->relationModel(genreIdx)->fieldIndex("name")); + + QDataWidgetMapper *mapper = new QDataWidgetMapper(this); + mapper->setModel(model); + mapper->setItemDelegate(new BookDelegate(this)); + mapper->addMapping(ui.titleEdit, model->fieldIndex("title")); + mapper->addMapping(ui.yearEdit, model->fieldIndex("year")); + mapper->addMapping(ui.authorEdit, authorIdx); + mapper->addMapping(ui.genreEdit, genreIdx); + mapper->addMapping(ui.ratingEdit, model->fieldIndex("rating")); + + connect(ui.bookTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + mapper, SLOT(setCurrentModelIndex(QModelIndex))); + + ui.bookTable->setCurrentIndex(model->index(0, 0)); +} + +void BookWindow::showError(const QSqlError &err) +{ + QMessageBox::critical(this, "Unable to initialize Database", + "Error initializing database: " + err.text()); +} + diff --git a/examples/sql/books/bookwindow.h b/examples/sql/books/bookwindow.h new file mode 100644 index 0000000000..4cd609650d --- /dev/null +++ b/examples/sql/books/bookwindow.h @@ -0,0 +1,64 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef BOOKWINDOW_H +#define BOOKWINDOW_H + +#include +#include + +#include "ui_bookwindow.h" + + +class BookWindow: public QMainWindow +{ + Q_OBJECT +public: + BookWindow(); + +private: + void showError(const QSqlError &err); + Ui::BookWindow ui; + QSqlRelationalTableModel *model; + int authorIdx, genreIdx; +}; + +#endif diff --git a/examples/sql/books/bookwindow.ui b/examples/sql/books/bookwindow.ui new file mode 100644 index 0000000000..659d324564 --- /dev/null +++ b/examples/sql/books/bookwindow.ui @@ -0,0 +1,149 @@ + + + + + BookWindow + + + + 0 + 0 + 601 + 420 + + + + Books + + + + + 9 + + + 6 + + + + + Books + + + + 9 + + + 6 + + + + + QAbstractItemView::SelectRows + + + + + + + Details + + + + + + <b>Title:</b> + + + + + + + true + + + + + + + <b>Author: </b> + + + + + + + true + + + + + + + <b>Genre:</b> + + + + + + + true + + + + + + + <b>Year:</b> + + + + + + + true + + + + + + 2100 + + + -1000 + + + + + + + <b>Rating:</b> + + + + + + + 5 + + + + + + + + + + + + + + + bookTable + titleEdit + authorEdit + genreEdit + yearEdit + + + + diff --git a/examples/sql/books/images/star.png b/examples/sql/books/images/star.png new file mode 100644 index 0000000000..87f4464bd5 Binary files /dev/null and b/examples/sql/books/images/star.png differ diff --git a/examples/sql/books/initdb.h b/examples/sql/books/initdb.h new file mode 100644 index 0000000000..9c9bebcba1 --- /dev/null +++ b/examples/sql/books/initdb.h @@ -0,0 +1,125 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef INITDB_H +#define INITDB_H + +#include + +void addBook(QSqlQuery &q, const QString &title, int year, const QVariant &authorId, + const QVariant &genreId, int rating) +{ + q.addBindValue(title); + q.addBindValue(year); + q.addBindValue(authorId); + q.addBindValue(genreId); + q.addBindValue(rating); + q.exec(); +} + +QVariant addGenre(QSqlQuery &q, const QString &name) +{ + q.addBindValue(name); + q.exec(); + return q.lastInsertId(); +} + +QVariant addAuthor(QSqlQuery &q, const QString &name, const QDate &birthdate) +{ + q.addBindValue(name); + q.addBindValue(birthdate); + q.exec(); + return q.lastInsertId(); +} + +QSqlError initDb() +{ + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); + db.setDatabaseName(":memory:"); + + if (!db.open()) + return db.lastError(); + + QStringList tables = db.tables(); + if (tables.contains("books", Qt::CaseInsensitive) + && tables.contains("authors", Qt::CaseInsensitive)) + return QSqlError(); + + QSqlQuery q; + if (!q.exec(QLatin1String("create table books(id integer primary key, title varchar, author integer, genre integer, year integer, rating integer)"))) + return q.lastError(); + if (!q.exec(QLatin1String("create table authors(id integer primary key, name varchar, birthdate date)"))) + return q.lastError(); + if (!q.exec(QLatin1String("create table genres(id integer primary key, name varchar)"))) + return q.lastError(); + + if (!q.prepare(QLatin1String("insert into authors(name, birthdate) values(?, ?)"))) + return q.lastError(); + QVariant asimovId = addAuthor(q, QLatin1String("Isaac Asimov"), QDate(1920, 2, 1)); + QVariant greeneId = addAuthor(q, QLatin1String("Graham Greene"), QDate(1904, 10, 2)); + QVariant pratchettId = addAuthor(q, QLatin1String("Terry Pratchett"), QDate(1948, 4, 28)); + + if (!q.prepare(QLatin1String("insert into genres(name) values(?)"))) + return q.lastError(); + QVariant sfiction = addGenre(q, QLatin1String("Science Fiction")); + QVariant fiction = addGenre(q, QLatin1String("Fiction")); + QVariant fantasy = addGenre(q, QLatin1String("Fantasy")); + + if (!q.prepare(QLatin1String("insert into books(title, year, author, genre, rating) values(?, ?, ?, ?, ?)"))) + return q.lastError(); + addBook(q, QLatin1String("Foundation"), 1951, asimovId, sfiction, 3); + addBook(q, QLatin1String("Foundation and Empire"), 1952, asimovId, sfiction, 4); + addBook(q, QLatin1String("Second Foundation"), 1953, asimovId, sfiction, 3); + addBook(q, QLatin1String("Foundation's Edge"), 1982, asimovId, sfiction, 3); + addBook(q, QLatin1String("Foundation and Earth"), 1986, asimovId, sfiction, 4); + addBook(q, QLatin1String("Prelude to Foundation"), 1988, asimovId, sfiction, 3); + addBook(q, QLatin1String("Forward the Foundation"), 1993, asimovId, sfiction, 3); + addBook(q, QLatin1String("The Power and the Glory"), 1940, greeneId, fiction, 4); + addBook(q, QLatin1String("The Third Man"), 1950, greeneId, fiction, 5); + addBook(q, QLatin1String("Our Man in Havana"), 1958, greeneId, fiction, 4); + addBook(q, QLatin1String("Guards! Guards!"), 1989, pratchettId, fantasy, 3); + addBook(q, QLatin1String("Night Watch"), 2002, pratchettId, fantasy, 3); + addBook(q, QLatin1String("Going Postal"), 2004, pratchettId, fantasy, 3); + + return QSqlError(); +} + +#endif diff --git a/examples/sql/books/main.cpp b/examples/sql/books/main.cpp new file mode 100644 index 0000000000..45aa8f87cf --- /dev/null +++ b/examples/sql/books/main.cpp @@ -0,0 +1,56 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "bookwindow.h" + +#include + +int main(int argc, char * argv[]) +{ + Q_INIT_RESOURCE(books); + + QApplication app(argc, argv); + + BookWindow win; + win.show(); + + return app.exec(); +} diff --git a/examples/sql/sqlbrowser/browser.cpp b/examples/sql/sqlbrowser/browser.cpp new file mode 100644 index 0000000000..1c53743059 --- /dev/null +++ b/examples/sql/sqlbrowser/browser.cpp @@ -0,0 +1,247 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "browser.h" +#include "qsqlconnectiondialog.h" + +#include +#include + +Browser::Browser(QWidget *parent) + : QWidget(parent) +{ + setupUi(this); + + table->addAction(insertRowAction); + table->addAction(deleteRowAction); + + if (QSqlDatabase::drivers().isEmpty()) + QMessageBox::information(this, tr("No database drivers found"), + tr("This demo requires at least one Qt database driver. " + "Please check the documentation how to build the " + "Qt SQL plugins.")); + + emit statusMessage(tr("Ready.")); +} + +Browser::~Browser() +{ +} + +void Browser::exec() +{ + QSqlQueryModel *model = new QSqlQueryModel(table); + model->setQuery(QSqlQuery(sqlEdit->toPlainText(), connectionWidget->currentDatabase())); + table->setModel(model); + + if (model->lastError().type() != QSqlError::NoError) + emit statusMessage(model->lastError().text()); + else if (model->query().isSelect()) + emit statusMessage(tr("Query OK.")); + else + emit statusMessage(tr("Query OK, number of affected rows: %1").arg( + model->query().numRowsAffected())); + + updateActions(); +} + +QSqlError Browser::addConnection(const QString &driver, const QString &dbName, const QString &host, + const QString &user, const QString &passwd, int port) +{ + static int cCount = 0; + + QSqlError err; + QSqlDatabase db = QSqlDatabase::addDatabase(driver, QString("Browser%1").arg(++cCount)); + db.setDatabaseName(dbName); + db.setHostName(host); + db.setPort(port); + if (!db.open(user, passwd)) { + err = db.lastError(); + db = QSqlDatabase(); + QSqlDatabase::removeDatabase(QString("Browser%1").arg(cCount)); + } + connectionWidget->refresh(); + + return err; +} + +void Browser::addConnection() +{ + QSqlConnectionDialog dialog(this); + if (dialog.exec() != QDialog::Accepted) + return; + + if (dialog.useInMemoryDatabase()) { + QSqlDatabase::database("in_mem_db", false).close(); + QSqlDatabase::removeDatabase("in_mem_db"); + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "in_mem_db"); + db.setDatabaseName(":memory:"); + if (!db.open()) + QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while " + "opening the connection: ") + db.lastError().text()); + QSqlQuery q("", db); + q.exec("drop table Movies"); + q.exec("drop table Names"); + q.exec("create table Movies (id integer primary key, Title varchar, Director varchar, Rating number)"); + q.exec("insert into Movies values (0, 'Metropolis', 'Fritz Lang', '8.4')"); + q.exec("insert into Movies values (1, 'Nosferatu, eine Symphonie des Grauens', 'F.W. Murnau', '8.1')"); + q.exec("insert into Movies values (2, 'Bis ans Ende der Welt', 'Wim Wenders', '6.5')"); + q.exec("insert into Movies values (3, 'Hardware', 'Richard Stanley', '5.2')"); + q.exec("insert into Movies values (4, 'Mitchell', 'Andrew V. McLaglen', '2.1')"); + q.exec("create table Names (id integer primary key, Firstname varchar, Lastname varchar, City varchar)"); + q.exec("insert into Names values (0, 'Sala', 'Palmer', 'Morristown')"); + q.exec("insert into Names values (1, 'Christopher', 'Walker', 'Morristown')"); + q.exec("insert into Names values (2, 'Donald', 'Duck', 'Andeby')"); + q.exec("insert into Names values (3, 'Buck', 'Rogers', 'Paris')"); + q.exec("insert into Names values (4, 'Sherlock', 'Holmes', 'London')"); + connectionWidget->refresh(); + } else { + QSqlError err = addConnection(dialog.driverName(), dialog.databaseName(), dialog.hostName(), + dialog.userName(), dialog.password(), dialog.port()); + if (err.type() != QSqlError::NoError) + QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while " + "opening the connection: ") + err.text()); + } +} + +void Browser::showTable(const QString &t) +{ + QSqlTableModel *model = new QSqlTableModel(table, connectionWidget->currentDatabase()); + model->setEditStrategy(QSqlTableModel::OnRowChange); + model->setTable(connectionWidget->currentDatabase().driver()->escapeIdentifier(t, QSqlDriver::TableName)); + model->select(); + if (model->lastError().type() != QSqlError::NoError) + emit statusMessage(model->lastError().text()); + table->setModel(model); + table->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed); + + connect(table->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + this, SLOT(currentChanged())); + updateActions(); +} + +void Browser::showMetaData(const QString &t) +{ + QSqlRecord rec = connectionWidget->currentDatabase().record(t); + QStandardItemModel *model = new QStandardItemModel(table); + + model->insertRows(0, rec.count()); + model->insertColumns(0, 7); + + model->setHeaderData(0, Qt::Horizontal, "Fieldname"); + model->setHeaderData(1, Qt::Horizontal, "Type"); + model->setHeaderData(2, Qt::Horizontal, "Length"); + model->setHeaderData(3, Qt::Horizontal, "Precision"); + model->setHeaderData(4, Qt::Horizontal, "Required"); + model->setHeaderData(5, Qt::Horizontal, "AutoValue"); + model->setHeaderData(6, Qt::Horizontal, "DefaultValue"); + + + for (int i = 0; i < rec.count(); ++i) { + QSqlField fld = rec.field(i); + model->setData(model->index(i, 0), fld.name()); + model->setData(model->index(i, 1), fld.typeID() == -1 + ? QString(QVariant::typeToName(fld.type())) + : QString("%1 (%2)").arg(QVariant::typeToName(fld.type())).arg(fld.typeID())); + model->setData(model->index(i, 2), fld.length()); + model->setData(model->index(i, 3), fld.precision()); + model->setData(model->index(i, 4), fld.requiredStatus() == -1 ? QVariant("?") + : QVariant(bool(fld.requiredStatus()))); + model->setData(model->index(i, 5), fld.isAutoValue()); + model->setData(model->index(i, 6), fld.defaultValue()); + } + + table->setModel(model); + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + + updateActions(); +} + +void Browser::insertRow() +{ + QSqlTableModel *model = qobject_cast(table->model()); + if (!model) + return; + + QModelIndex insertIndex = table->currentIndex(); + int row = insertIndex.row() == -1 ? 0 : insertIndex.row(); + model->insertRow(row); + insertIndex = model->index(row, 0); + table->setCurrentIndex(insertIndex); + table->edit(insertIndex); +} + +void Browser::deleteRow() +{ + QSqlTableModel *model = qobject_cast(table->model()); + if (!model) + return; + + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + + QModelIndexList currentSelection = table->selectionModel()->selectedIndexes(); + for (int i = 0; i < currentSelection.count(); ++i) { + if (currentSelection.at(i).column() != 0) + continue; + model->removeRow(currentSelection.at(i).row()); + } + + model->submitAll(); + model->setEditStrategy(QSqlTableModel::OnRowChange); + + updateActions(); +} + +void Browser::updateActions() +{ + bool enableIns = qobject_cast(table->model()); + bool enableDel = enableIns && table->currentIndex().isValid(); + + insertRowAction->setEnabled(enableIns); + deleteRowAction->setEnabled(enableDel); +} + +void Browser::about() +{ + QMessageBox::about(this, tr("About"), tr("The SQL Browser demonstration " + "shows how a data browser can be used to visualize the results of SQL" + "statements on a live database")); +} diff --git a/examples/sql/sqlbrowser/browser.h b/examples/sql/sqlbrowser/browser.h new file mode 100644 index 0000000000..11f9e36211 --- /dev/null +++ b/examples/sql/sqlbrowser/browser.h @@ -0,0 +1,99 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef BROWSER_H +#define BROWSER_H + +#include +#include "ui_browserwidget.h" + +class ConnectionWidget; +QT_FORWARD_DECLARE_CLASS(QTableView) +QT_FORWARD_DECLARE_CLASS(QPushButton) +QT_FORWARD_DECLARE_CLASS(QTextEdit) +QT_FORWARD_DECLARE_CLASS(QSqlError) + +class Browser: public QWidget, private Ui::Browser +{ + Q_OBJECT +public: + Browser(QWidget *parent = 0); + virtual ~Browser(); + + QSqlError addConnection(const QString &driver, const QString &dbName, const QString &host, + const QString &user, const QString &passwd, int port = -1); + + void insertRow(); + void deleteRow(); + void updateActions(); + +public slots: + void exec(); + void showTable(const QString &table); + void showMetaData(const QString &table); + void addConnection(); + void currentChanged() { updateActions(); } + void about(); + + void on_insertRowAction_triggered() + { insertRow(); } + void on_deleteRowAction_triggered() + { deleteRow(); } + void on_connectionWidget_tableActivated(const QString &table) + { showTable(table); } + void on_connectionWidget_metaDataRequested(const QString &table) + { showMetaData(table); } + void on_submitButton_clicked() + { + exec(); + sqlEdit->setFocus(); + } + void on_clearButton_clicked() + { + sqlEdit->clear(); + sqlEdit->setFocus(); + } + +signals: + void statusMessage(const QString &message); +}; + +#endif diff --git a/examples/sql/sqlbrowser/browserwidget.ui b/examples/sql/sqlbrowser/browserwidget.ui new file mode 100644 index 0000000000..20946f0ede --- /dev/null +++ b/examples/sql/sqlbrowser/browserwidget.ui @@ -0,0 +1,199 @@ + + + + + Browser + + + + 0 + 0 + 765 + 515 + + + + Qt SQL Browser + + + + 8 + + + 6 + + + + + + 7 + 7 + 0 + 0 + + + + Qt::Horizontal + + + + + 13 + 7 + 1 + 0 + + + + + + + 7 + 7 + 2 + 0 + + + + Qt::ActionsContextMenu + + + QAbstractItemView::SelectRows + + + + + + + + + 5 + 3 + 0 + 0 + + + + + 16777215 + 180 + + + + SQL Query + + + + 9 + + + 6 + + + + + + 7 + 3 + 0 + 0 + + + + + 0 + 18 + + + + + 0 + 120 + + + + + + + + 1 + + + 6 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + &Clear + + + + + + + &Submit + + + + + + + + + + + + false + + + &Insert Row + + + Inserts a new Row + + + + + false + + + &Delete Row + + + Deletes the current Row + + + + + + + ConnectionWidget + QTreeView +
      connectionwidget.h
      + 0 + +
      +
      + + sqlEdit + clearButton + submitButton + connectionWidget + table + + + +
      diff --git a/examples/sql/sqlbrowser/connectionwidget.cpp b/examples/sql/sqlbrowser/connectionwidget.cpp new file mode 100644 index 0000000000..936f32f29f --- /dev/null +++ b/examples/sql/sqlbrowser/connectionwidget.cpp @@ -0,0 +1,165 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "connectionwidget.h" + +#include +#include + +ConnectionWidget::ConnectionWidget(QWidget *parent) + : QWidget(parent) +{ + QVBoxLayout *layout = new QVBoxLayout(this); + tree = new QTreeWidget(this); + tree->setObjectName(QLatin1String("tree")); + tree->setHeaderLabels(QStringList(tr("database"))); + tree->header()->setResizeMode(QHeaderView::Stretch); + QAction *refreshAction = new QAction(tr("Refresh"), tree); + metaDataAction = new QAction(tr("Show Schema"), tree); + connect(refreshAction, SIGNAL(triggered()), SLOT(refresh())); + connect(metaDataAction, SIGNAL(triggered()), SLOT(showMetaData())); + tree->addAction(refreshAction); + tree->addAction(metaDataAction); + tree->setContextMenuPolicy(Qt::ActionsContextMenu); + + layout->addWidget(tree); + + QMetaObject::connectSlotsByName(this); +} + +ConnectionWidget::~ConnectionWidget() +{ +} + +static QString qDBCaption(const QSqlDatabase &db) +{ + QString nm = db.driverName(); + nm.append(QLatin1Char(':')); + if (!db.userName().isEmpty()) + nm.append(db.userName()).append(QLatin1Char('@')); + nm.append(db.databaseName()); + return nm; +} + +void ConnectionWidget::refresh() +{ + tree->clear(); + QStringList connectionNames = QSqlDatabase::connectionNames(); + + bool gotActiveDb = false; + for (int i = 0; i < connectionNames.count(); ++i) { + QTreeWidgetItem *root = new QTreeWidgetItem(tree); + QSqlDatabase db = QSqlDatabase::database(connectionNames.at(i), false); + root->setText(0, qDBCaption(db)); + if (connectionNames.at(i) == activeDb) { + gotActiveDb = true; + setActive(root); + } + if (db.isOpen()) { + QStringList tables = db.tables(); + for (int t = 0; t < tables.count(); ++t) { + QTreeWidgetItem *table = new QTreeWidgetItem(root); + table->setText(0, tables.at(t)); + } + } + } + if (!gotActiveDb) { + activeDb = connectionNames.value(0); + setActive(tree->topLevelItem(0)); + } + + tree->doItemsLayout(); // HACK +} + +QSqlDatabase ConnectionWidget::currentDatabase() const +{ + return QSqlDatabase::database(activeDb); +} + +static void qSetBold(QTreeWidgetItem *item, bool bold) +{ + QFont font = item->font(0); + font.setBold(bold); + item->setFont(0, font); +} + +void ConnectionWidget::setActive(QTreeWidgetItem *item) +{ + for (int i = 0; i < tree->topLevelItemCount(); ++i) { + if (tree->topLevelItem(i)->font(0).bold()) + qSetBold(tree->topLevelItem(i), false); + } + + if (!item) + return; + + qSetBold(item, true); + activeDb = QSqlDatabase::connectionNames().value(tree->indexOfTopLevelItem(item)); +} + +void ConnectionWidget::on_tree_itemActivated(QTreeWidgetItem *item, int /* column */) +{ + + if (!item) + return; + + if (!item->parent()) { + setActive(item); + } else { + setActive(item->parent()); + emit tableActivated(item->text(0)); + } +} + +void ConnectionWidget::showMetaData() +{ + QTreeWidgetItem *cItem = tree->currentItem(); + if (!cItem || !cItem->parent()) + return; + setActive(cItem->parent()); + emit metaDataRequested(cItem->text(0)); +} + +void ConnectionWidget::on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *) +{ + metaDataAction->setEnabled(current && current->parent()); +} + diff --git a/examples/sql/sqlbrowser/connectionwidget.h b/examples/sql/sqlbrowser/connectionwidget.h new file mode 100644 index 0000000000..aa04fc25bf --- /dev/null +++ b/examples/sql/sqlbrowser/connectionwidget.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CONNECTIONWIDGET_H +#define CONNECTIONWIDGET_H + +#include + +QT_FORWARD_DECLARE_CLASS(QTreeWidget) +QT_FORWARD_DECLARE_CLASS(QTreeWidgetItem) +QT_FORWARD_DECLARE_CLASS(QSqlDatabase) +QT_FORWARD_DECLARE_CLASS(QMenu) + +class ConnectionWidget: public QWidget +{ + Q_OBJECT +public: + ConnectionWidget(QWidget *parent = 0); + virtual ~ConnectionWidget(); + + QSqlDatabase currentDatabase() const; + +signals: + void tableActivated(const QString &table); + void metaDataRequested(const QString &tableName); + +public slots: + void refresh(); + void showMetaData(); + void on_tree_itemActivated(QTreeWidgetItem *item, int column); + void on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); + +private: + void setActive(QTreeWidgetItem *); + + QTreeWidget *tree; + QAction *metaDataAction; + QString activeDb; +}; + +#endif diff --git a/examples/sql/sqlbrowser/main.cpp b/examples/sql/sqlbrowser/main.cpp new file mode 100644 index 0000000000..dc006176b7 --- /dev/null +++ b/examples/sql/sqlbrowser/main.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "browser.h" + +#include +#include +#include + +void addConnectionsFromCommandline(const QStringList &args, Browser *browser) +{ + for (int i = 1; i < args.count(); ++i) { + QUrl url(args.at(i), QUrl::TolerantMode); + if (!url.isValid()) { + qWarning("Invalid URL: %s", qPrintable(args.at(i))); + continue; + } + QSqlError err = browser->addConnection(url.scheme(), url.path().mid(1), url.host(), + url.userName(), url.password(), url.port(-1)); + if (err.type() != QSqlError::NoError) + qDebug() << "Unable to open connection:" << err; + } +} + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QMainWindow mainWin; + mainWin.setWindowTitle(QObject::tr("Qt SQL Browser")); + + Browser browser(&mainWin); + mainWin.setCentralWidget(&browser); + + QMenu *fileMenu = mainWin.menuBar()->addMenu(QObject::tr("&File")); + fileMenu->addAction(QObject::tr("Add &Connection..."), &browser, SLOT(addConnection())); + fileMenu->addSeparator(); + fileMenu->addAction(QObject::tr("&Quit"), &app, SLOT(quit())); + + QMenu *helpMenu = mainWin.menuBar()->addMenu(QObject::tr("&Help")); + helpMenu->addAction(QObject::tr("About"), &browser, SLOT(about())); + helpMenu->addAction(QObject::tr("About Qt"), qApp, SLOT(aboutQt())); + + QObject::connect(&browser, SIGNAL(statusMessage(QString)), + mainWin.statusBar(), SLOT(showMessage(QString))); + + addConnectionsFromCommandline(app.arguments(), &browser); + mainWin.show(); + if (QSqlDatabase::connectionNames().isEmpty()) + QMetaObject::invokeMethod(&browser, "addConnection", Qt::QueuedConnection); + + return app.exec(); +} diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp b/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp new file mode 100644 index 0000000000..56b6c031db --- /dev/null +++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qsqlconnectiondialog.h" +#include "ui_qsqlconnectiondialog.h" + +#include + +QSqlConnectionDialog::QSqlConnectionDialog(QWidget *parent) + : QDialog(parent) +{ + ui.setupUi(this); + + QStringList drivers = QSqlDatabase::drivers(); + + // remove compat names + drivers.removeAll("QMYSQL3"); + drivers.removeAll("QOCI8"); + drivers.removeAll("QODBC3"); + drivers.removeAll("QPSQL7"); + drivers.removeAll("QTDS7"); + + if (!drivers.contains("QSQLITE")) + ui.dbCheckBox->setEnabled(false); + + ui.comboDriver->addItems(drivers); +} + +QSqlConnectionDialog::~QSqlConnectionDialog() +{ +} + +QString QSqlConnectionDialog::driverName() const +{ + return ui.comboDriver->currentText(); +} + +QString QSqlConnectionDialog::databaseName() const +{ + return ui.editDatabase->text(); +} + +QString QSqlConnectionDialog::userName() const +{ + return ui.editUsername->text(); +} + +QString QSqlConnectionDialog::password() const +{ + return ui.editPassword->text(); +} + +QString QSqlConnectionDialog::hostName() const +{ + return ui.editHostname->text(); +} + +int QSqlConnectionDialog::port() const +{ + return ui.portSpinBox->value(); +} + +bool QSqlConnectionDialog::useInMemoryDatabase() const +{ + return ui.dbCheckBox->isChecked(); +} + +void QSqlConnectionDialog::on_okButton_clicked() +{ + if (ui.comboDriver->currentText().isEmpty()) { + QMessageBox::information(this, tr("No database driver selected"), + tr("Please select a database driver")); + ui.comboDriver->setFocus(); + } else { + accept(); + } +} diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.h b/examples/sql/sqlbrowser/qsqlconnectiondialog.h new file mode 100644 index 0000000000..8c4519a195 --- /dev/null +++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.h @@ -0,0 +1,74 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSQLCONNECTIONDIALOG_H +#define QSQLCONNECTIONDIALOG_H + +#include +#include + +#include "ui_qsqlconnectiondialog.h" + +class QSqlConnectionDialog: public QDialog +{ + Q_OBJECT +public: + QSqlConnectionDialog(QWidget *parent = 0); + ~QSqlConnectionDialog(); + + QString driverName() const; + QString databaseName() const; + QString userName() const; + QString password() const; + QString hostName() const; + int port() const; + bool useInMemoryDatabase() const; + +private slots: + void on_okButton_clicked(); + void on_cancelButton_clicked() { reject(); } + void on_dbCheckBox_clicked() { ui.connGroupBox->setEnabled(!ui.dbCheckBox->isChecked()); } + +private: + Ui::QSqlConnectionDialogUi ui; +}; + +#endif diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.ui b/examples/sql/sqlbrowser/qsqlconnectiondialog.ui new file mode 100644 index 0000000000..91a8700579 --- /dev/null +++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.ui @@ -0,0 +1,224 @@ + + + + + QSqlConnectionDialogUi + + + + 0 + 0 + 315 + 302 + + + + Connect... + + + + 8 + + + 6 + + + + + Connection settings + + + + 8 + + + 6 + + + + + + + + &Username: + + + editUsername + + + + + + + D&river + + + comboDriver + + + + + + + + + + Default + + + 65535 + + + -1 + + + -1 + + + + + + + Database Name: + + + editDatabase + + + + + + + QLineEdit::Password + + + + + + + + + + + + + &Hostname: + + + editHostname + + + + + + + P&ort: + + + portSpinBox + + + + + + + &Password: + + + editPassword + + + + + + + + + + 0 + + + 6 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Us&e predefined in-memory database + + + + + + + + + 0 + + + 6 + + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 20 + 20 + + + + + + + + &OK + + + true + + + + + + + &Cancel + + + + + + + + + + comboDriver + editDatabase + editUsername + editPassword + editHostname + portSpinBox + dbCheckBox + okButton + cancelButton + + + + diff --git a/examples/sql/sqlbrowser/sqlbrowser.pro b/examples/sql/sqlbrowser/sqlbrowser.pro new file mode 100644 index 0000000000..dc6214622c --- /dev/null +++ b/examples/sql/sqlbrowser/sqlbrowser.pro @@ -0,0 +1,25 @@ +TEMPLATE = app +TARGET = sqlbrowser + +QT += sql + +HEADERS = browser.h connectionwidget.h qsqlconnectiondialog.h +SOURCES = main.cpp browser.cpp connectionwidget.cpp qsqlconnectiondialog.cpp + +FORMS = browserwidget.ui qsqlconnectiondialog.ui +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/sqlbrowser +sources.files = $$SOURCES $$HEADERS $$FORMS *.pro +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/sqlbrowser +INSTALLS += target sources + +symbian: CONFIG += qt_demo + +wince*: { + DEPLOYMENT_PLUGIN += qsqlite +} diff --git a/examples/tools/undo/commands.cpp b/examples/tools/undo/commands.cpp new file mode 100644 index 0000000000..e688cad602 --- /dev/null +++ b/examples/tools/undo/commands.cpp @@ -0,0 +1,180 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "commands.h" + +static const int setShapeRectCommandId = 1; +static const int setShapeColorCommandId = 2; + +/****************************************************************************** +** AddShapeCommand +*/ + +AddShapeCommand::AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent) + : QUndoCommand(parent) +{ + m_doc = doc; + m_shape = shape; +} + +void AddShapeCommand::undo() +{ + m_doc->deleteShape(m_shapeName); +} + +void AddShapeCommand::redo() +{ + // A shape only gets a name when it is inserted into a document + m_shapeName = m_doc->addShape(m_shape); + setText(QObject::tr("Add %1").arg(m_shapeName)); +} + +/****************************************************************************** +** RemoveShapeCommand +*/ + +RemoveShapeCommand::RemoveShapeCommand(Document *doc, const QString &shapeName, + QUndoCommand *parent) + : QUndoCommand(parent) +{ + setText(QObject::tr("Remove %1").arg(shapeName)); + m_doc = doc; + m_shape = doc->shape(shapeName); + m_shapeName = shapeName; +} + +void RemoveShapeCommand::undo() +{ + m_shapeName = m_doc->addShape(m_shape); +} + +void RemoveShapeCommand::redo() +{ + m_doc->deleteShape(m_shapeName); +} + +/****************************************************************************** +** SetShapeColorCommand +*/ + +SetShapeColorCommand::SetShapeColorCommand(Document *doc, const QString &shapeName, + const QColor &color, QUndoCommand *parent) + : QUndoCommand(parent) +{ + setText(QObject::tr("Set %1's color").arg(shapeName)); + + m_doc = doc; + m_shapeName = shapeName; + m_oldColor = doc->shape(shapeName).color(); + m_newColor = color; +} + +void SetShapeColorCommand::undo() +{ + m_doc->setShapeColor(m_shapeName, m_oldColor); +} + +void SetShapeColorCommand::redo() +{ + m_doc->setShapeColor(m_shapeName, m_newColor); +} + +bool SetShapeColorCommand::mergeWith(const QUndoCommand *command) +{ + if (command->id() != setShapeColorCommandId) + return false; + + const SetShapeColorCommand *other = static_cast(command); + if (m_shapeName != other->m_shapeName) + return false; + + m_newColor = other->m_newColor; + return true; +} + +int SetShapeColorCommand::id() const +{ + return setShapeColorCommandId; +} + +/****************************************************************************** +** SetShapeRectCommand +*/ + +SetShapeRectCommand::SetShapeRectCommand(Document *doc, const QString &shapeName, + const QRect &rect, QUndoCommand *parent) + : QUndoCommand(parent) +{ + setText(QObject::tr("Change %1's geometry").arg(shapeName)); + + m_doc = doc; + m_shapeName = shapeName; + m_oldRect = doc->shape(shapeName).rect(); + m_newRect = rect; +} + +void SetShapeRectCommand::undo() +{ + m_doc->setShapeRect(m_shapeName, m_oldRect); +} + +void SetShapeRectCommand::redo() +{ + m_doc->setShapeRect(m_shapeName, m_newRect); +} + +bool SetShapeRectCommand::mergeWith(const QUndoCommand *command) +{ + if (command->id() != setShapeRectCommandId) + return false; + + const SetShapeRectCommand *other = static_cast(command); + if (m_shapeName != other->m_shapeName) + return false; + + m_newRect = other->m_newRect; + return true; +} + +int SetShapeRectCommand::id() const +{ + return setShapeRectCommandId; +} diff --git a/examples/tools/undo/commands.h b/examples/tools/undo/commands.h new file mode 100644 index 0000000000..ca7bd2b307 --- /dev/null +++ b/examples/tools/undo/commands.h @@ -0,0 +1,112 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef COMMANDS_H +#define COMMANDS_H + +#include +#include "document.h" + +class AddShapeCommand : public QUndoCommand +{ +public: + AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent = 0); + void undo(); + void redo(); + +private: + Document *m_doc; + Shape m_shape; + QString m_shapeName; +}; + +class RemoveShapeCommand : public QUndoCommand +{ +public: + RemoveShapeCommand(Document *doc, const QString &shapeName, QUndoCommand *parent = 0); + void undo(); + void redo(); + +private: + Document *m_doc; + Shape m_shape; + QString m_shapeName; +}; + +class SetShapeColorCommand : public QUndoCommand +{ +public: + SetShapeColorCommand(Document *doc, const QString &shapeName, const QColor &color, + QUndoCommand *parent = 0); + + void undo(); + void redo(); + + bool mergeWith(const QUndoCommand *command); + int id() const; + +private: + Document *m_doc; + QString m_shapeName; + QColor m_oldColor; + QColor m_newColor; +}; + +class SetShapeRectCommand : public QUndoCommand +{ +public: + SetShapeRectCommand(Document *doc, const QString &shapeName, const QRect &rect, + QUndoCommand *parent = 0); + + void undo(); + void redo(); + + bool mergeWith(const QUndoCommand *command); + int id() const; + +private: + Document *m_doc; + QString m_shapeName; + QRect m_oldRect; + QRect m_newRect; +}; + +#endif // COMMANDS_H diff --git a/examples/tools/undo/document.cpp b/examples/tools/undo/document.cpp new file mode 100644 index 0000000000..e143f98061 --- /dev/null +++ b/examples/tools/undo/document.cpp @@ -0,0 +1,445 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include "document.h" +#include "commands.h" + +static const int resizeHandleWidth = 6; + +/****************************************************************************** +** Shape +*/ + +const QSize Shape::minSize(80, 50); + +Shape::Shape(Type type, const QColor &color, const QRect &rect) + : m_type(type), m_rect(rect), m_color(color) +{ +} + +Shape::Type Shape::type() const +{ + return m_type; +} + +QRect Shape::rect() const +{ + return m_rect; +} + +QColor Shape::color() const +{ + return m_color; +} + +QString Shape::name() const +{ + return m_name; +} + +QRect Shape::resizeHandle() const +{ + QPoint br = m_rect.bottomRight(); + return QRect(br - QPoint(resizeHandleWidth, resizeHandleWidth), br); +} + +QString Shape::typeToString(Type type) +{ + QString result; + + switch (type) { + case Rectangle: + result = QLatin1String("Rectangle"); + break; + case Circle: + result = QLatin1String("Circle"); + break; + case Triangle: + result = QLatin1String("Triangle"); + break; + } + + return result; +} + +Shape::Type Shape::stringToType(const QString &s, bool *ok) +{ + if (ok != 0) + *ok = true; + + if (s == QLatin1String("Rectangle")) + return Rectangle; + if (s == QLatin1String("Circle")) + return Circle; + if (s == QLatin1String("Triangle")) + return Triangle; + + if (ok != 0) + *ok = false; + return Rectangle; +} + +/****************************************************************************** +** Document +*/ + +Document::Document(QWidget *parent) + : QWidget(parent), m_currentIndex(-1), m_mousePressIndex(-1), m_resizeHandlePressed(false) +{ + m_undoStack = new QUndoStack(this); + + setAutoFillBackground(true); + setBackgroundRole(QPalette::Base); + + QPalette pal = palette(); + pal.setBrush(QPalette::Base, QPixmap(":/icons/background.png")); + pal.setColor(QPalette::HighlightedText, Qt::red); + setPalette(pal); +} + +QString Document::addShape(const Shape &shape) +{ + QString name = Shape::typeToString(shape.type()); + name = uniqueName(name); + + m_shapeList.append(shape); + m_shapeList[m_shapeList.count() - 1].m_name = name; + setCurrentShape(m_shapeList.count() - 1); + + return name; +} + +void Document::deleteShape(const QString &shapeName) +{ + int index = indexOf(shapeName); + if (index == -1) + return; + + update(m_shapeList.at(index).rect()); + + m_shapeList.removeAt(index); + + if (index <= m_currentIndex) { + m_currentIndex = -1; + if (index == m_shapeList.count()) + --index; + setCurrentShape(index); + } +} + +Shape Document::shape(const QString &shapeName) const +{ + int index = indexOf(shapeName); + if (index == -1) + return Shape(); + return m_shapeList.at(index); +} + +void Document::setShapeRect(const QString &shapeName, const QRect &rect) +{ + int index = indexOf(shapeName); + if (index == -1) + return; + + Shape &shape = m_shapeList[index]; + + update(shape.rect()); + update(rect); + + shape.m_rect = rect; +} + +void Document::setShapeColor(const QString &shapeName, const QColor &color) +{ + + int index = indexOf(shapeName); + if (index == -1) + return; + + Shape &shape = m_shapeList[index]; + shape.m_color = color; + + update(shape.rect()); +} + +QUndoStack *Document::undoStack() const +{ + return m_undoStack; +} + +bool Document::load(QTextStream &stream) +{ + m_shapeList.clear(); + + while (!stream.atEnd()) { + QString shapeType, shapeName, colorName; + int left, top, width, height; + stream >> shapeType >> shapeName >> colorName >> left >> top >> width >> height; + if (stream.status() != QTextStream::Ok) + return false; + bool ok; + Shape::Type type = Shape::stringToType(shapeType, &ok); + if (!ok) + return false; + QColor color(colorName); + if (!color.isValid()) + return false; + + Shape shape(type); + shape.m_name = shapeName; + shape.m_color = color; + shape.m_rect = QRect(left, top, width, height); + + m_shapeList.append(shape); + } + + m_currentIndex = m_shapeList.isEmpty() ? -1 : 0; + + return true; +} + +void Document::save(QTextStream &stream) +{ + for (int i = 0; i < m_shapeList.count(); ++i) { + const Shape &shape = m_shapeList.at(i); + QRect r = shape.rect(); + stream << Shape::typeToString(shape.type()) << QLatin1Char(' ') + << shape.name() << QLatin1Char(' ') + << shape.color().name() << QLatin1Char(' ') + << r.left() << QLatin1Char(' ') + << r.top() << QLatin1Char(' ') + << r.width() << QLatin1Char(' ') + << r.height(); + if (i != m_shapeList.count() - 1) + stream << QLatin1Char('\n'); + } + m_undoStack->setClean(); +} + +QString Document::fileName() const +{ + return m_fileName; +} + +void Document::setFileName(const QString &fileName) +{ + m_fileName = fileName; +} + +int Document::indexAt(const QPoint &pos) const +{ + for (int i = m_shapeList.count() - 1; i >= 0; --i) { + if (m_shapeList.at(i).rect().contains(pos)) + return i; + } + return -1; +} + +void Document::mousePressEvent(QMouseEvent *event) +{ + event->accept(); + int index = indexAt(event->pos());; + if (index != -1) { + setCurrentShape(index); + + const Shape &shape = m_shapeList.at(index); + m_resizeHandlePressed = shape.resizeHandle().contains(event->pos()); + + if (m_resizeHandlePressed) + m_mousePressOffset = shape.rect().bottomRight() - event->pos(); + else + m_mousePressOffset = event->pos() - shape.rect().topLeft(); + } + m_mousePressIndex = index; +} + +void Document::mouseReleaseEvent(QMouseEvent *event) +{ + event->accept(); + m_mousePressIndex = -1; +} + +void Document::mouseMoveEvent(QMouseEvent *event) +{ + event->accept(); + + if (m_mousePressIndex == -1) + return; + + const Shape &shape = m_shapeList.at(m_mousePressIndex); + + QRect rect; + if (m_resizeHandlePressed) { + rect = QRect(shape.rect().topLeft(), event->pos() + m_mousePressOffset); + } else { + rect = shape.rect(); + rect.moveTopLeft(event->pos() - m_mousePressOffset); + } + + QSize size = rect.size().expandedTo(Shape::minSize); + rect.setSize(size); + + m_undoStack->push(new SetShapeRectCommand(this, shape.name(), rect)); +} + +static QGradient gradient(const QColor &color, const QRect &rect) +{ + QColor c = color; + c.setAlpha(160); + QLinearGradient result(rect.topLeft(), rect.bottomRight()); + result.setColorAt(0, c.dark(150)); + result.setColorAt(0.5, c.light(200)); + result.setColorAt(1, c.dark(150)); + return result; +} + +static QPolygon triangle(const QRect &rect) +{ + QPolygon result(3); + result.setPoint(0, rect.center().x(), rect.top()); + result.setPoint(1, rect.right(), rect.bottom()); + result.setPoint(2, rect.left(), rect.bottom()); + return result; +} + +void Document::paintEvent(QPaintEvent *event) +{ + QRegion paintRegion = event->region(); + QPainter painter(this); + QPalette pal = palette(); + + for (int i = 0; i < m_shapeList.count(); ++i) { + const Shape &shape = m_shapeList.at(i); + + if (!paintRegion.contains(shape.rect())) + continue; + + QPen pen = pal.text().color(); + pen.setWidth(i == m_currentIndex ? 2 : 1); + painter.setPen(pen); + painter.setBrush(gradient(shape.color(), shape.rect())); + + QRect rect = shape.rect(); + rect.adjust(1, 1, -resizeHandleWidth/2, -resizeHandleWidth/2); + + // paint the shape + switch (shape.type()) { + case Shape::Rectangle: + painter.drawRect(rect); + break; + case Shape::Circle: + painter.setRenderHint(QPainter::Antialiasing); + painter.drawEllipse(rect); + painter.setRenderHint(QPainter::Antialiasing, false); + break; + case Shape::Triangle: + painter.setRenderHint(QPainter::Antialiasing); + painter.drawPolygon(triangle(rect)); + painter.setRenderHint(QPainter::Antialiasing, false); + break; + } + + // paint the resize handle + painter.setPen(pal.text().color()); + painter.setBrush(Qt::white); + painter.drawRect(shape.resizeHandle().adjusted(0, 0, -1, -1)); + + // paint the shape name + painter.setBrush(pal.text()); + if (shape.type() == Shape::Triangle) + rect.adjust(0, rect.height()/2, 0, 0); + painter.drawText(rect, Qt::AlignCenter, shape.name()); + } +} + +void Document::setCurrentShape(int index) +{ + QString currentName; + + if (m_currentIndex != -1) + update(m_shapeList.at(m_currentIndex).rect()); + + m_currentIndex = index; + + if (m_currentIndex != -1) { + const Shape ¤t = m_shapeList.at(m_currentIndex); + update(current.rect()); + currentName = current.name(); + } + + emit currentShapeChanged(currentName); +} + +int Document::indexOf(const QString &shapeName) const +{ + for (int i = 0; i < m_shapeList.count(); ++i) { + if (m_shapeList.at(i).name() == shapeName) + return i; + } + return -1; +} + +QString Document::uniqueName(const QString &name) const +{ + QString unique; + + for (int i = 0; ; ++i) { + unique = name; + if (i > 0) + unique += QString::number(i); + if (indexOf(unique) == -1) + break; + } + + return unique; +} + +QString Document::currentShapeName() const +{ + if (m_currentIndex == -1) + return QString(); + return m_shapeList.at(m_currentIndex).name(); +} + diff --git a/examples/tools/undo/document.h b/examples/tools/undo/document.h new file mode 100644 index 0000000000..b0eda92d41 --- /dev/null +++ b/examples/tools/undo/document.h @@ -0,0 +1,125 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DOCUMENT_H +#define DOCUMENT_H + +#include + +QT_FORWARD_DECLARE_CLASS(QUndoStack) +QT_FORWARD_DECLARE_CLASS(QTextStream) + +class Shape +{ +public: + enum Type { Rectangle, Circle, Triangle }; + + Shape(Type type = Rectangle, const QColor &color = Qt::red, const QRect &rect = QRect()); + + Type type() const; + QString name() const; + QRect rect() const; + QRect resizeHandle() const; + QColor color() const; + + static QString typeToString(Type type); + static Type stringToType(const QString &s, bool *ok = 0); + + static const QSize minSize; + +private: + Type m_type; + QRect m_rect; + QColor m_color; + QString m_name; + + friend class Document; +}; + +class Document : public QWidget +{ + Q_OBJECT + +public: + Document(QWidget *parent = 0); + + QString addShape(const Shape &shape); + void deleteShape(const QString &shapeName); + Shape shape(const QString &shapeName) const; + QString currentShapeName() const; + + void setShapeRect(const QString &shapeName, const QRect &rect); + void setShapeColor(const QString &shapeName, const QColor &color); + + bool load(QTextStream &stream); + void save(QTextStream &stream); + + QString fileName() const; + void setFileName(const QString &fileName); + + QUndoStack *undoStack() const; + +signals: + void currentShapeChanged(const QString &shapeName); + +protected: + void paintEvent(QPaintEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); + +private: + void setCurrentShape(int index); + int indexOf(const QString &shapeName) const; + int indexAt(const QPoint &pos) const; + QString uniqueName(const QString &name) const; + + QList m_shapeList; + int m_currentIndex; + int m_mousePressIndex; + QPoint m_mousePressOffset; + bool m_resizeHandlePressed; + QString m_fileName; + + QUndoStack *m_undoStack; +}; + +#endif // DOCUMENT_H diff --git a/examples/tools/undo/icons/background.png b/examples/tools/undo/icons/background.png new file mode 100644 index 0000000000..3bc5ed8cf0 Binary files /dev/null and b/examples/tools/undo/icons/background.png differ diff --git a/examples/tools/undo/icons/blue.png b/examples/tools/undo/icons/blue.png new file mode 100644 index 0000000000..4e181bb61a Binary files /dev/null and b/examples/tools/undo/icons/blue.png differ diff --git a/examples/tools/undo/icons/circle.png b/examples/tools/undo/icons/circle.png new file mode 100644 index 0000000000..ed16c6e144 Binary files /dev/null and b/examples/tools/undo/icons/circle.png differ diff --git a/examples/tools/undo/icons/exit.png b/examples/tools/undo/icons/exit.png new file mode 100644 index 0000000000..539cb2ead9 Binary files /dev/null and b/examples/tools/undo/icons/exit.png differ diff --git a/examples/tools/undo/icons/fileclose.png b/examples/tools/undo/icons/fileclose.png new file mode 100644 index 0000000000..c5483d14ab Binary files /dev/null and b/examples/tools/undo/icons/fileclose.png differ diff --git a/examples/tools/undo/icons/filenew.png b/examples/tools/undo/icons/filenew.png new file mode 100644 index 0000000000..57e57e343b Binary files /dev/null and b/examples/tools/undo/icons/filenew.png differ diff --git a/examples/tools/undo/icons/fileopen.png b/examples/tools/undo/icons/fileopen.png new file mode 100644 index 0000000000..33e0d6394c Binary files /dev/null and b/examples/tools/undo/icons/fileopen.png differ diff --git a/examples/tools/undo/icons/filesave.png b/examples/tools/undo/icons/filesave.png new file mode 100644 index 0000000000..57fd5e2f34 Binary files /dev/null and b/examples/tools/undo/icons/filesave.png differ diff --git a/examples/tools/undo/icons/green.png b/examples/tools/undo/icons/green.png new file mode 100644 index 0000000000..e2e7cc9e50 Binary files /dev/null and b/examples/tools/undo/icons/green.png differ diff --git a/examples/tools/undo/icons/ok.png b/examples/tools/undo/icons/ok.png new file mode 100644 index 0000000000..e355ea91bc Binary files /dev/null and b/examples/tools/undo/icons/ok.png differ diff --git a/examples/tools/undo/icons/rectangle.png b/examples/tools/undo/icons/rectangle.png new file mode 100644 index 0000000000..3a7d9795fd Binary files /dev/null and b/examples/tools/undo/icons/rectangle.png differ diff --git a/examples/tools/undo/icons/red.png b/examples/tools/undo/icons/red.png new file mode 100644 index 0000000000..58c3e7253b Binary files /dev/null and b/examples/tools/undo/icons/red.png differ diff --git a/examples/tools/undo/icons/redo.png b/examples/tools/undo/icons/redo.png new file mode 100644 index 0000000000..5591517e1c Binary files /dev/null and b/examples/tools/undo/icons/redo.png differ diff --git a/examples/tools/undo/icons/remove.png b/examples/tools/undo/icons/remove.png new file mode 100644 index 0000000000..7a7b048c0a Binary files /dev/null and b/examples/tools/undo/icons/remove.png differ diff --git a/examples/tools/undo/icons/triangle.png b/examples/tools/undo/icons/triangle.png new file mode 100644 index 0000000000..2969131c31 Binary files /dev/null and b/examples/tools/undo/icons/triangle.png differ diff --git a/examples/tools/undo/icons/undo.png b/examples/tools/undo/icons/undo.png new file mode 100644 index 0000000000..8cf63a8ec9 Binary files /dev/null and b/examples/tools/undo/icons/undo.png differ diff --git a/examples/tools/undo/main.cpp b/examples/tools/undo/main.cpp new file mode 100644 index 0000000000..a1bb49533a --- /dev/null +++ b/examples/tools/undo/main.cpp @@ -0,0 +1,56 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "mainwindow.h" + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(undo); + + QApplication app(argc, argv); + + MainWindow win; + win.resize(800, 600); + win.show(); + + return app.exec(); +}; diff --git a/examples/tools/undo/mainwindow.cpp b/examples/tools/undo/mainwindow.cpp new file mode 100644 index 0000000000..fb16606686 --- /dev/null +++ b/examples/tools/undo/mainwindow.cpp @@ -0,0 +1,446 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "document.h" +#include "mainwindow.h" +#include "commands.h" + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) +{ + setupUi(this); + + QWidget *w = documentTabs->widget(0); + documentTabs->removeTab(0); + delete w; + + connect(actionOpen, SIGNAL(triggered()), this, SLOT(openDocument())); + connect(actionClose, SIGNAL(triggered()), this, SLOT(closeDocument())); + connect(actionNew, SIGNAL(triggered()), this, SLOT(newDocument())); + connect(actionSave, SIGNAL(triggered()), this, SLOT(saveDocument())); + connect(actionExit, SIGNAL(triggered()), this, SLOT(close())); + connect(actionRed, SIGNAL(triggered()), this, SLOT(setShapeColor())); + connect(actionGreen, SIGNAL(triggered()), this, SLOT(setShapeColor())); + connect(actionBlue, SIGNAL(triggered()), this, SLOT(setShapeColor())); + connect(actionAddCircle, SIGNAL(triggered()), this, SLOT(addShape())); + connect(actionAddRectangle, SIGNAL(triggered()), this, SLOT(addShape())); + connect(actionAddTriangle, SIGNAL(triggered()), this, SLOT(addShape())); + connect(actionRemoveShape, SIGNAL(triggered()), this, SLOT(removeShape())); + connect(actionAddRobot, SIGNAL(triggered()), this, SLOT(addRobot())); + connect(actionAddSnowman, SIGNAL(triggered()), this, SLOT(addSnowman())); + connect(actionAbout, SIGNAL(triggered()), this, SLOT(about())); + connect(actionAboutQt, SIGNAL(triggered()), this, SLOT(aboutQt())); + + connect(undoLimit, SIGNAL(valueChanged(int)), this, SLOT(updateActions())); + connect(documentTabs, SIGNAL(currentChanged(int)), this, SLOT(updateActions())); + + actionOpen->setShortcut(QString("Ctrl+O")); + actionClose->setShortcut(QString("Ctrl+W")); + actionNew->setShortcut(QString("Ctrl+N")); + actionSave->setShortcut(QString("Ctrl+S")); + actionExit->setShortcut(QString("Ctrl+Q")); + actionRemoveShape->setShortcut(QString("Del")); + actionRed->setShortcut(QString("Alt+R")); + actionGreen->setShortcut(QString("Alt+G")); + actionBlue->setShortcut(QString("Alt+B")); + actionAddCircle->setShortcut(QString("Alt+C")); + actionAddRectangle->setShortcut(QString("Alt+L")); + actionAddTriangle->setShortcut(QString("Alt+T")); + + m_undoGroup = new QUndoGroup(this); + undoView->setGroup(m_undoGroup); + undoView->setCleanIcon(QIcon(":/icons/ok.png")); + + QAction *undoAction = m_undoGroup->createUndoAction(this); + QAction *redoAction = m_undoGroup->createRedoAction(this); + undoAction->setIcon(QIcon(":/icons/undo.png")); + redoAction->setIcon(QIcon(":/icons/redo.png")); + menuShape->insertAction(menuShape->actions().at(0), undoAction); + menuShape->insertAction(undoAction, redoAction); + + toolBar->addAction(undoAction); + toolBar->addAction(redoAction); + + newDocument(); + updateActions(); +}; + +void MainWindow::updateActions() +{ + Document *doc = currentDocument(); + m_undoGroup->setActiveStack(doc == 0 ? 0 : doc->undoStack()); + QString shapeName = doc == 0 ? QString() : doc->currentShapeName(); + + actionAddRobot->setEnabled(doc != 0); + actionAddSnowman->setEnabled(doc != 0); + actionAddCircle->setEnabled(doc != 0); + actionAddRectangle->setEnabled(doc != 0); + actionAddTriangle->setEnabled(doc != 0); + actionClose->setEnabled(doc != 0); + actionSave->setEnabled(doc != 0 && !doc->undoStack()->isClean()); + undoLimit->setEnabled(doc != 0 && doc->undoStack()->count() == 0); + + if (shapeName.isEmpty()) { + actionRed->setEnabled(false); + actionGreen->setEnabled(false); + actionBlue->setEnabled(false); + actionRemoveShape->setEnabled(false); + } else { + Shape shape = doc->shape(shapeName); + actionRed->setEnabled(shape.color() != Qt::red); + actionGreen->setEnabled(shape.color() != Qt::green); + actionBlue->setEnabled(shape.color() != Qt::blue); + actionRemoveShape->setEnabled(true); + } + + if (doc != 0) { + int index = documentTabs->indexOf(doc); + Q_ASSERT(index != -1); + static const QIcon unsavedIcon(":/icons/filesave.png"); + documentTabs->setTabIcon(index, doc->undoStack()->isClean() ? QIcon() : unsavedIcon); + + if (doc->undoStack()->count() == 0) + doc->undoStack()->setUndoLimit(undoLimit->value()); + } +} + +void MainWindow::openDocument() +{ + QString fileName = QFileDialog::getOpenFileName(this); + if (fileName.isEmpty()) + return; + + QFile file(fileName); + if (!file.open(QIODevice::ReadOnly)) { + QMessageBox::warning(this, + tr("File error"), + tr("Failed to open\n%1").arg(fileName)); + return; + } + QTextStream stream(&file); + + Document *doc = new Document(); + if (!doc->load(stream)) { + QMessageBox::warning(this, + tr("Parse error"), + tr("Failed to parse\n%1").arg(fileName)); + delete doc; + return; + } + + doc->setFileName(fileName); + addDocument(doc); +} + +QString MainWindow::fixedWindowTitle(const Document *doc) const +{ + QString title = doc->fileName(); + + if (title.isEmpty()) + title = tr("Unnamed"); + else + title = QFileInfo(title).fileName(); + + QString result; + + for (int i = 0; ; ++i) { + result = title; + if (i > 0) + result += QString::number(i); + + bool unique = true; + for (int j = 0; j < documentTabs->count(); ++j) { + const QWidget *widget = documentTabs->widget(j); + if (widget == doc) + continue; + if (result == documentTabs->tabText(j)) { + unique = false; + break; + } + } + + if (unique) + break; + } + + return result; +} + +void MainWindow::addDocument(Document *doc) +{ + if (documentTabs->indexOf(doc) != -1) + return; + m_undoGroup->addStack(doc->undoStack()); + documentTabs->addTab(doc, fixedWindowTitle(doc)); + connect(doc, SIGNAL(currentShapeChanged(QString)), this, SLOT(updateActions())); + connect(doc->undoStack(), SIGNAL(indexChanged(int)), this, SLOT(updateActions())); + connect(doc->undoStack(), SIGNAL(cleanChanged(bool)), this, SLOT(updateActions())); + + setCurrentDocument(doc); +} + +void MainWindow::setCurrentDocument(Document *doc) +{ + documentTabs->setCurrentWidget(doc); +} + +Document *MainWindow::currentDocument() const +{ + return qobject_cast(documentTabs->currentWidget()); +} + +void MainWindow::removeDocument(Document *doc) +{ + int index = documentTabs->indexOf(doc); + if (index == -1) + return; + + documentTabs->removeTab(index); + m_undoGroup->removeStack(doc->undoStack()); + disconnect(doc, SIGNAL(currentShapeChanged(QString)), this, SLOT(updateActions())); + disconnect(doc->undoStack(), SIGNAL(indexChanged(int)), this, SLOT(updateActions())); + disconnect(doc->undoStack(), SIGNAL(cleanChanged(bool)), this, SLOT(updateActions())); + + if (documentTabs->count() == 0) { + newDocument(); + updateActions(); + } +} + +void MainWindow::saveDocument() +{ + Document *doc = currentDocument(); + if (doc == 0) + return; + + for (;;) { + QString fileName = doc->fileName(); + + if (fileName.isEmpty()) + fileName = QFileDialog::getSaveFileName(this); + if (fileName.isEmpty()) + break; + + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly)) { + QMessageBox::warning(this, + tr("File error"), + tr("Failed to open\n%1").arg(fileName)); + doc->setFileName(QString()); + } else { + QTextStream stream(&file); + doc->save(stream); + doc->setFileName(fileName); + + int index = documentTabs->indexOf(doc); + Q_ASSERT(index != -1); + documentTabs->setTabText(index, fixedWindowTitle(doc)); + + break; + } + } +} + +void MainWindow::closeDocument() +{ + Document *doc = currentDocument(); + if (doc == 0) + return; + + if (!doc->undoStack()->isClean()) { + int button + = QMessageBox::warning(this, + tr("Unsaved changes"), + tr("Would you like to save this document?"), + QMessageBox::Yes, QMessageBox::No); + if (button == QMessageBox::Yes) + saveDocument(); + } + + removeDocument(doc); + delete doc; +} + +void MainWindow::newDocument() +{ + addDocument(new Document()); +} + +static QColor randomColor() +{ + int r = (int) (3.0*(rand()/(RAND_MAX + 1.0))); + switch (r) { + case 0: + return Qt::red; + case 1: + return Qt::green; + default: + break; + } + return Qt::blue; +} + +static QRect randomRect(const QSize &s) +{ + QSize min = Shape::minSize; + + int left = (int) ((0.0 + s.width() - min.width())*(rand()/(RAND_MAX + 1.0))); + int top = (int) ((0.0 + s.height() - min.height())*(rand()/(RAND_MAX + 1.0))); + int width = (int) ((0.0 + s.width() - left - min.width())*(rand()/(RAND_MAX + 1.0))) + min.width(); + int height = (int) ((0.0 + s.height() - top - min.height())*(rand()/(RAND_MAX + 1.0))) + min.height(); + + return QRect(left, top, width, height); +} + +void MainWindow::addShape() +{ + Document *doc = currentDocument(); + if (doc == 0) + return; + + Shape::Type type; + + if (sender() == actionAddCircle) + type = Shape::Circle; + else if (sender() == actionAddRectangle) + type = Shape::Rectangle; + else if (sender() == actionAddTriangle) + type = Shape::Triangle; + else return; + + Shape newShape(type, randomColor(), randomRect(doc->size())); + doc->undoStack()->push(new AddShapeCommand(doc, newShape)); +} + +void MainWindow::removeShape() +{ + Document *doc = currentDocument(); + if (doc == 0) + return; + + QString shapeName = doc->currentShapeName(); + if (shapeName.isEmpty()) + return; + + doc->undoStack()->push(new RemoveShapeCommand(doc, shapeName)); +} + +void MainWindow::setShapeColor() +{ + Document *doc = currentDocument(); + if (doc == 0) + return; + + QString shapeName = doc->currentShapeName(); + if (shapeName.isEmpty()) + return; + + QColor color; + + if (sender() == actionRed) + color = Qt::red; + else if (sender() == actionGreen) + color = Qt::green; + else if (sender() == actionBlue) + color = Qt::blue; + else + return; + + if (color == doc->shape(shapeName).color()) + return; + + doc->undoStack()->push(new SetShapeColorCommand(doc, shapeName, color)); +} + +void MainWindow::addSnowman() +{ + Document *doc = currentDocument(); + if (doc == 0) + return; + + // Create a macro command using beginMacro() and endMacro() + + doc->undoStack()->beginMacro(tr("Add snowman")); + doc->undoStack()->push(new AddShapeCommand(doc, + Shape(Shape::Circle, Qt::blue, QRect(51, 30, 97, 95)))); + doc->undoStack()->push(new AddShapeCommand(doc, + Shape(Shape::Circle, Qt::blue, QRect(27, 123, 150, 133)))); + doc->undoStack()->push(new AddShapeCommand(doc, + Shape(Shape::Circle, Qt::blue, QRect(11, 253, 188, 146)))); + doc->undoStack()->endMacro(); +} + +void MainWindow::addRobot() +{ + Document *doc = currentDocument(); + if (doc == 0) + return; + + // Compose a macro command by explicitly adding children to a parent command + + QUndoCommand *parent = new QUndoCommand(tr("Add robot")); + + new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(115, 15, 81, 70)), parent); + new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(82, 89, 148, 188)), parent); + new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(76, 280, 80, 165)), parent); + new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(163, 280, 80, 164)), parent); + new AddShapeCommand(doc, Shape(Shape::Circle, Qt::blue, QRect(116, 25, 80, 50)), parent); + new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(232, 92, 80, 127)), parent); + new AddShapeCommand(doc, Shape(Shape::Rectangle, Qt::green, QRect(2, 92, 80, 125)), parent); + + doc->undoStack()->push(parent); +} + +void MainWindow::about() +{ + QMessageBox::about(this, tr("About Undo"), tr("The Undo demonstration shows how to use the Qt Undo framework.")); +} + +void MainWindow::aboutQt() +{ + QMessageBox::aboutQt(this, tr("About Qt")); +} diff --git a/examples/tools/undo/mainwindow.h b/examples/tools/undo/mainwindow.h new file mode 100644 index 0000000000..4500c6d68d --- /dev/null +++ b/examples/tools/undo/mainwindow.h @@ -0,0 +1,87 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include "ui_mainwindow.h" + +class Document; + +class MainWindow : public QMainWindow, public Ui::MainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = 0); + + void addDocument(Document *doc); + void removeDocument(Document *doc); + void setCurrentDocument(Document *doc); + Document *currentDocument() const; + +public slots: + void openDocument(); + void saveDocument(); + void closeDocument(); + void newDocument(); + + void addShape(); + void removeShape(); + void setShapeColor(); + + void addSnowman(); + void addRobot(); + + void about(); + void aboutQt(); + +private slots: + void updateActions(); + +private: + QUndoGroup *m_undoGroup; + + QString fixedWindowTitle(const Document *doc) const; +}; + +#endif // MAINWINDOW_H diff --git a/examples/tools/undo/mainwindow.ui b/examples/tools/undo/mainwindow.ui new file mode 100644 index 0000000000..91a0b437e5 --- /dev/null +++ b/examples/tools/undo/mainwindow.ui @@ -0,0 +1,322 @@ + + MainWindow + + + + 0 + 0 + 567 + 600 + + + + + 32 + 32 + + + + + + 0 + + + 0 + + + + + 0 + + + + Tab 1 + + + + + + + + + + 0 + 0 + 567 + 27 + + + + + File + + + + + + + + + + + Edit + + + + Macros + + + + + + + + + + + + + + + + + + + Help + + + + + + + + + + + + File actions + + + Qt::Horizontal + + + TopToolBarArea + + + false + + + + + + + + + + Shape actions + + + Qt::Vertical + + + LeftToolBarArea + + + false + + + + + + + + + + + + + Undo Stack + + + 2 + + + + + 0 + + + 4 + + + + + 0 + + + 6 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Undo limit + + + + + + + + + + + + false + + + + + + + + + :/icons/fileopen.png + + + &Open + + + + + :/icons/fileclose.png + + + &Close + + + + + :/icons/filenew.png + + + &New + + + + + :/icons/filesave.png + + + &Save + + + + + :/icons/exit.png + + + E&xit + + + + + :/icons/red.png + + + Red + + + + + :/icons/green.png + + + Green + + + + + :/icons/blue.png + + + Blue + + + + + :/icons/rectangle.png + + + Add Rectangle + + + + + :/icons/circle.png + + + Add Circle + + + + + :/icons/remove.png + + + Remove Shape + + + + + Add robot + + + + + Add snowan + + + + + :/icons/triangle.png + + + addTriangle + + + + + About + + + + + About Qt + + + + + + QUndoView + QListView +
      qundoview.h
      +
      +
      + + + + +
      diff --git a/examples/tools/undo/undo.pro b/examples/tools/undo/undo.pro new file mode 100644 index 0000000000..84f1d7b326 --- /dev/null +++ b/examples/tools/undo/undo.pro @@ -0,0 +1,18 @@ +SOURCES += main.cpp mainwindow.cpp commands.cpp document.cpp +HEADERS += mainwindow.h commands.h document.h +FORMS += mainwindow.ui + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +RESOURCES += undo.qrc + +# install +target.path = $$[QT_INSTALL_DEMOS]/qtbase/undo +sources.files = $$SOURCES $$HEADERS *.pro icons $$RESOURCES $$FORMS +sources.path = $$[QT_INSTALL_DEMOS]/qtbase/undo +INSTALLS += target sources + +symbian: CONFIG += qt_demo diff --git a/examples/tools/undo/undo.qrc b/examples/tools/undo/undo.qrc new file mode 100644 index 0000000000..65619b8f1a --- /dev/null +++ b/examples/tools/undo/undo.qrc @@ -0,0 +1,20 @@ + + + icons/background.png + icons/blue.png + icons/circle.png + icons/exit.png + icons/fileclose.png + icons/filenew.png + icons/fileopen.png + icons/filesave.png + icons/green.png + icons/ok.png + icons/rectangle.png + icons/red.png + icons/redo.png + icons/remove.png + icons/triangle.png + icons/undo.png + + -- cgit v1.2.3