summaryrefslogtreecommitdiffstats
path: root/src/widgets
diff options
context:
space:
mode:
Diffstat (limited to 'src/widgets')
-rw-r--r--src/widgets/CMakeLists.txt135
-rw-r--r--src/widgets/accessible/complexwidgets.cpp191
-rw-r--r--src/widgets/accessible/complexwidgets_p.h14
-rw-r--r--src/widgets/accessible/itemviews.cpp228
-rw-r--r--src/widgets/accessible/itemviews_p.h2
-rw-r--r--src/widgets/accessible/qaccessiblewidget.cpp25
-rw-r--r--src/widgets/accessible/qaccessiblewidgetfactory.cpp3
-rw-r--r--src/widgets/accessible/qaccessiblewidgets.cpp22
-rw-r--r--src/widgets/accessible/qaccessiblewidgets_p.h1
-rw-r--r--src/widgets/accessible/simplewidgets.cpp23
-rw-r--r--src/widgets/accessible/simplewidgets_p.h2
-rw-r--r--src/widgets/compat/removed_api.cpp27
-rw-r--r--src/widgets/configure.cmake4
-rw-r--r--src/widgets/dialogs/images/qtlogo-64.pngbin1032 -> 1219 bytes
-rw-r--r--src/widgets/dialogs/qcolordialog.cpp215
-rw-r--r--src/widgets/dialogs/qcolordialog.h12
-rw-r--r--src/widgets/dialogs/qdialog.cpp115
-rw-r--r--src/widgets/dialogs/qdialog.h1
-rw-r--r--src/widgets/dialogs/qdialog_p.h8
-rw-r--r--src/widgets/dialogs/qerrormessage.cpp43
-rw-r--r--src/widgets/dialogs/qerrormessage.h2
-rw-r--r--src/widgets/dialogs/qfiledialog.cpp782
-rw-r--r--src/widgets/dialogs/qfiledialog.h44
-rw-r--r--src/widgets/dialogs/qfiledialog_p.h61
-rw-r--r--src/widgets/dialogs/qfontdialog.cpp91
-rw-r--r--src/widgets/dialogs/qfontdialog.h7
-rw-r--r--src/widgets/dialogs/qfontdialog_p.h15
-rw-r--r--src/widgets/dialogs/qinputdialog.cpp68
-rw-r--r--src/widgets/dialogs/qinputdialog.h3
-rw-r--r--src/widgets/dialogs/qmessagebox.cpp444
-rw-r--r--src/widgets/dialogs/qmessagebox.h46
-rw-r--r--src/widgets/dialogs/qprogressdialog.cpp52
-rw-r--r--src/widgets/dialogs/qsidebar.cpp93
-rw-r--r--src/widgets/dialogs/qsidebar_p.h2
-rw-r--r--src/widgets/dialogs/qwizard.cpp166
-rw-r--r--src/widgets/dialogs/qwizard_win.cpp242
-rw-r--r--src/widgets/dialogs/qwizard_win_p.h12
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part1-labeled-layout.pngbin19114 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part1-labeled-screenshot.pngbin23223 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part1-screenshot.pngbin9872 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part2-add-contact.pngbin12936 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part2-add-flowchart.pngbin23533 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part2-add-successful.pngbin10825 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part2-labeled-layout.pngbin27103 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part2-signals-and-slots.pngbin9968 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part2-stretch-effects.pngbin12268 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part3-labeled-layout.pngbin27467 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part3-linkedlist.pngbin10209 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part3-screenshot.pngbin14041 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part4-remove.pngbin22248 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part5-finddialog.pngbin10046 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part5-notfound.pngbin10789 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part5-screenshot.pngbin15849 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part5-signals-and-slots.pngbin5542 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part6-load.pngbin24797 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part6-save.pngbin24747 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part6-screenshot.pngbin16819 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-part7-screenshot.pngbin18369 -> 0 bytes
-rw-r--r--src/widgets/doc/images/addressbook-tutorial-screenshot.pngbin15275 -> 0 bytes
-rw-r--r--src/widgets/doc/images/collapsed_combobox.pngbin0 -> 6507 bytes
-rw-r--r--src/widgets/doc/images/cuberhiwidget-example.jpgbin0 -> 70232 bytes
-rw-r--r--src/widgets/doc/images/expanded_combobox.pngbin0 -> 11699 bytes
-rw-r--r--src/widgets/doc/images/qrhiwidget-intro.jpgbin0 -> 9508 bytes
-rw-r--r--src/widgets/doc/images/qtquickdialogs-filedialog-gtk.pngbin0 -> 39560 bytes
-rw-r--r--src/widgets/doc/images/simplerhiwidget-example.jpgbin0 -> 12489 bytes
-rw-r--r--src/widgets/doc/images/spinboxdelegate-example.pngbin4762 -> 0 bytes
-rw-r--r--src/widgets/doc/images/spinboxdelegate-example.webpbin0 -> 40364 bytes
-rw-r--r--src/widgets/doc/images/stylesheet-coffee-cleanlooks.pngbin14820 -> 0 bytes
-rw-r--r--src/widgets/doc/images/stylesheet-pagefold-mac.pngbin20618 -> 0 bytes
-rw-r--r--src/widgets/doc/images/system-tray.pngbin6326 -> 0 bytes
-rw-r--r--src/widgets/doc/images/system-tray.webpbin0 -> 19180 bytes
-rw-r--r--src/widgets/doc/qtwidgets.qdocconf29
-rw-r--r--src/widgets/doc/snippets/CMakeLists.txt2
-rw-r--r--src/widgets/doc/snippets/cmake-macros/examples.cmake4
-rw-r--r--src/widgets/doc/snippets/code/doc_src_qt4-mainwindow.cpp45
-rw-r--r--src/widgets/doc/snippets/code/doc_src_qt4-styles.cpp19
-rw-r--r--src/widgets/doc/snippets/code/doc_src_stylesheet.cpp2
-rw-r--r--src/widgets/doc/snippets/code/doc_src_stylesheet.qdoc56
-rw-r--r--src/widgets/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp26
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp34
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsview.cpp10
-rw-r--r--src/widgets/doc/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp4
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp94
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qformlayout.cpp2
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp18
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qgroupbox.cpp17
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp4
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qspinbox.cpp20
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qstatusbar.cpp8
-rw-r--r--src/widgets/doc/snippets/code/src_widgets_util_qscroller.cpp2
-rw-r--r--src/widgets/doc/snippets/code/src_widgets_widgets_qmainwindow.cpp2
-rw-r--r--src/widgets/doc/snippets/customviewstyle/CMakeLists.txt4
-rw-r--r--src/widgets/doc/snippets/dialogs/dialogs.cpp29
-rw-r--r--src/widgets/doc/snippets/filedialogurls/CMakeLists.txt2
-rw-r--r--src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt2
-rw-r--r--src/widgets/doc/snippets/graphicsview/CMakeLists.txt2
-rw-r--r--src/widgets/doc/snippets/mdiarea/CMakeLists.txt2
-rw-r--r--src/widgets/doc/snippets/myscrollarea/CMakeLists.txt2
-rw-r--r--src/widgets/doc/snippets/qitemdelegate/CMakeLists.txt12
-rw-r--r--src/widgets/doc/snippets/qitemdelegate/spinbox-delegate.cpp79
-rw-r--r--src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.cpp109
-rw-r--r--src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.frag10
-rw-r--r--src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.vert15
-rw-r--r--src/widgets/doc/snippets/splitter/splitter.cpp6
-rw-r--r--src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp2
-rw-r--r--src/widgets/doc/snippets/tooltips/main.cpp74
-rw-r--r--src/widgets/doc/src/cmake-macros.qdoc2
-rw-r--r--src/widgets/doc/src/model-view-programming.qdoc32
-rw-r--r--src/widgets/doc/src/modelview.qdoc7
-rw-r--r--src/widgets/doc/src/qt6-changes.qdoc2
-rw-r--r--src/widgets/doc/src/qtwidgets-index.qdoc17
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/focus.qdoc23
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/gallery.qdoc27
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/layout.qdoc8
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc1443
-rw-r--r--src/widgets/doc/src/widgets-tutorial.qdoc6
-rw-r--r--src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc74
-rw-r--r--src/widgets/effects/qgraphicseffect_p.h1
-rw-r--r--src/widgets/effects/qpixmapfilter.cpp311
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp26
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout_p.h7
-rw-r--r--src/widgets/graphicsview/qgraphicsgridlayout.cpp2
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.cpp63
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.h3
-rw-r--r--src/widgets/graphicsview/qgraphicsitem_p.h67
-rw-r--r--src/widgets/graphicsview/qgraphicslayout_p.h4
-rw-r--r--src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp2
-rw-r--r--src/widgets/graphicsview/qgraphicsproxywidget.cpp14
-rw-r--r--src/widgets/graphicsview/qgraphicsproxywidget_p.h2
-rw-r--r--src/widgets/graphicsview/qgraphicsscene.cpp21
-rw-r--r--src/widgets/graphicsview/qgraphicsview.cpp19
-rw-r--r--src/widgets/graphicsview/qgraphicsview_p.h2
-rw-r--r--src/widgets/itemviews/qabstractitemdelegate.cpp10
-rw-r--r--src/widgets/itemviews/qabstractitemview.cpp461
-rw-r--r--src/widgets/itemviews/qabstractitemview.h14
-rw-r--r--src/widgets/itemviews/qabstractitemview_p.h53
-rw-r--r--src/widgets/itemviews/qcolumnview.cpp82
-rw-r--r--src/widgets/itemviews/qcolumnview.h3
-rw-r--r--src/widgets/itemviews/qcolumnview_p.h17
-rw-r--r--src/widgets/itemviews/qdatawidgetmapper.cpp73
-rw-r--r--src/widgets/itemviews/qdatawidgetmapper.h6
-rw-r--r--src/widgets/itemviews/qheaderview.cpp201
-rw-r--r--src/widgets/itemviews/qheaderview.h10
-rw-r--r--src/widgets/itemviews/qheaderview_p.h32
-rw-r--r--src/widgets/itemviews/qitemdelegate.cpp36
-rw-r--r--src/widgets/itemviews/qitemeditorfactory.cpp8
-rw-r--r--src/widgets/itemviews/qlistview.cpp26
-rw-r--r--src/widgets/itemviews/qlistview_p.h1
-rw-r--r--src/widgets/itemviews/qlistwidget.cpp167
-rw-r--r--src/widgets/itemviews/qlistwidget.h10
-rw-r--r--src/widgets/itemviews/qlistwidget_p.h25
-rw-r--r--src/widgets/itemviews/qstyleditemdelegate.cpp34
-rw-r--r--src/widgets/itemviews/qtableview.cpp226
-rw-r--r--src/widgets/itemviews/qtableview.h7
-rw-r--r--src/widgets/itemviews/qtableview_p.h32
-rw-r--r--src/widgets/itemviews/qtablewidget.cpp88
-rw-r--r--src/widgets/itemviews/qtablewidget.h16
-rw-r--r--src/widgets/itemviews/qtablewidget_p.h30
-rw-r--r--src/widgets/itemviews/qtreeview.cpp263
-rw-r--r--src/widgets/itemviews/qtreeview.h5
-rw-r--r--src/widgets/itemviews/qtreeview_p.h42
-rw-r--r--src/widgets/itemviews/qtreewidget.cpp90
-rw-r--r--src/widgets/itemviews/qtreewidget.h13
-rw-r--r--src/widgets/itemviews/qtreewidget_p.h29
-rw-r--r--src/widgets/itemviews/qwidgetitemdata_p.h1
-rw-r--r--src/widgets/kernel/qaction_widgets.cpp5
-rw-r--r--src/widgets/kernel/qaction_widgets_p.h2
-rw-r--r--src/widgets/kernel/qapplication.cpp154
-rw-r--r--src/widgets/kernel/qapplication.h6
-rw-r--r--src/widgets/kernel/qapplication_p.h3
-rw-r--r--src/widgets/kernel/qformlayout.cpp24
-rw-r--r--src/widgets/kernel/qgesturemanager.cpp53
-rw-r--r--src/widgets/kernel/qgesturemanager_p.h10
-rw-r--r--src/widgets/kernel/qlayout.cpp16
-rw-r--r--src/widgets/kernel/qlayoutitem.cpp2
-rw-r--r--src/widgets/kernel/qrhiwidget.cpp1309
-rw-r--r--src/widgets/kernel/qrhiwidget.h101
-rw-r--r--src/widgets/kernel/qrhiwidget_p.h64
-rw-r--r--src/widgets/kernel/qshortcut_widgets.cpp18
-rw-r--r--src/widgets/kernel/qstackedlayout.cpp2
-rw-r--r--src/widgets/kernel/qtestsupport_widgets.cpp32
-rw-r--r--src/widgets/kernel/qtestsupport_widgets.h1
-rw-r--r--src/widgets/kernel/qtooltip.cpp40
-rw-r--r--src/widgets/kernel/qwhatsthis.cpp16
-rw-r--r--src/widgets/kernel/qwidget.cpp1245
-rw-r--r--src/widgets/kernel/qwidget.h10
-rw-r--r--src/widgets/kernel/qwidget_p.h57
-rw-r--r--src/widgets/kernel/qwidgetaction.cpp18
-rw-r--r--src/widgets/kernel/qwidgetaction.h1
-rw-r--r--src/widgets/kernel/qwidgetaction_p.h4
-rw-r--r--src/widgets/kernel/qwidgetrepaintmanager.cpp60
-rw-r--r--src/widgets/kernel/qwidgetsvariant.cpp3
-rw-r--r--src/widgets/kernel/qwidgetwindow.cpp84
-rw-r--r--src/widgets/kernel/qwidgetwindow_p.h5
-rw-r--r--src/widgets/kernel/qwindowcontainer.cpp65
-rw-r--r--src/widgets/kernel/qwindowcontainer_p.h4
-rw-r--r--src/widgets/platform/ios/PrivacyInfo.xcprivacy25
-rw-r--r--src/widgets/qtwidgets.tracepoints8
-rw-r--r--src/widgets/styles/images/cleartext-128.pngbin0 -> 3638 bytes
-rw-r--r--src/widgets/styles/images/cleartext-16.pngbin760 -> 985 bytes
-rw-r--r--src/widgets/styles/images/cleartext-32.pngbin410 -> 1310 bytes
-rw-r--r--src/widgets/styles/images/cleartext.svg71
-rw-r--r--src/widgets/styles/images/critical-128.pngbin0 -> 2938 bytes
-rw-r--r--src/widgets/styles/images/critical-16.pngbin0 -> 835 bytes
-rw-r--r--src/widgets/styles/images/critical-32.pngbin0 -> 1148 bytes
-rw-r--r--src/widgets/styles/images/filedialog_end-128.pngbin0 -> 1393 bytes
-rw-r--r--src/widgets/styles/images/filedialog_end-16.pngbin0 -> 686 bytes
-rw-r--r--src/widgets/styles/images/filedialog_end-32.pngbin0 -> 787 bytes
-rw-r--r--src/widgets/styles/images/filedialog_start-128.pngbin0 -> 1326 bytes
-rw-r--r--src/widgets/styles/images/filedialog_start-16.pngbin0 -> 677 bytes
-rw-r--r--src/widgets/styles/images/filedialog_start-32.pngbin0 -> 761 bytes
-rw-r--r--src/widgets/styles/images/fusion_closedock-10.pngbin0 -> 238 bytes
-rw-r--r--src/widgets/styles/images/fusion_closedock-16.pngbin0 -> 288 bytes
-rw-r--r--src/widgets/styles/images/fusion_closedock-20.pngbin0 -> 303 bytes
-rw-r--r--src/widgets/styles/images/fusion_closedock-32.pngbin0 -> 333 bytes
-rw-r--r--src/widgets/styles/images/fusion_closedock-48.pngbin0 -> 492 bytes
-rw-r--r--src/widgets/styles/images/fusion_closedock-64.pngbin0 -> 617 bytes
-rw-r--r--src/widgets/styles/images/fusion_closedock.svg87
-rw-r--r--src/widgets/styles/images/fusion_normalizedockup-16.pngbin0 -> 314 bytes
-rw-r--r--src/widgets/styles/images/fusion_normalizedockup-32.pngbin0 -> 413 bytes
-rw-r--r--src/widgets/styles/images/fusion_normalizedockup.svg75
-rw-r--r--src/widgets/styles/images/fusion_normalizedockup_10.pngbin0 -> 234 bytes
-rw-r--r--src/widgets/styles/images/fusion_normalizedockup_20.pngbin0 -> 342 bytes
-rw-r--r--src/widgets/styles/images/fusion_normalizedockup_48.pngbin0 -> 487 bytes
-rw-r--r--src/widgets/styles/images/fusion_normalizedockup_64.pngbin0 -> 579 bytes
-rw-r--r--src/widgets/styles/images/fusion_titlebar-min-10.pngbin0 -> 167 bytes
-rw-r--r--src/widgets/styles/images/fusion_titlebar-min-16.pngbin0 -> 141 bytes
-rw-r--r--src/widgets/styles/images/fusion_titlebar-min-20.pngbin0 -> 176 bytes
-rw-r--r--src/widgets/styles/images/fusion_titlebar-min-32.pngbin0 -> 214 bytes
-rw-r--r--src/widgets/styles/images/fusion_titlebar-min-48.pngbin0 -> 179 bytes
-rw-r--r--src/widgets/styles/images/fusion_titlebar-min-64.pngbin0 -> 190 bytes
-rw-r--r--src/widgets/styles/images/fusion_titlebar-min.svg67
-rw-r--r--src/widgets/styles/images/information-128.pngbin0 -> 2099 bytes
-rw-r--r--src/widgets/styles/images/information-16.pngbin0 -> 697 bytes
-rw-r--r--src/widgets/styles/images/information-32.pngbin0 -> 874 bytes
-rw-r--r--src/widgets/styles/images/media-pause-128.pngbin0 -> 262 bytes
-rw-r--r--src/widgets/styles/images/media-pause-16.pngbin229 -> 141 bytes
-rw-r--r--src/widgets/styles/images/media-pause-32.pngbin185 -> 157 bytes
-rw-r--r--src/widgets/styles/images/media-pause.svg67
-rw-r--r--src/widgets/styles/images/media-play-128.pngbin0 -> 584 bytes
-rw-r--r--src/widgets/styles/images/media-play-16.pngbin262 -> 172 bytes
-rw-r--r--src/widgets/styles/images/media-play-32.pngbin413 -> 227 bytes
-rw-r--r--src/widgets/styles/images/media-play.svg57
-rw-r--r--src/widgets/styles/images/media-seek-backward-128.pngbin0 -> 532 bytes
-rw-r--r--src/widgets/styles/images/media-seek-backward-16.pngbin384 -> 182 bytes
-rw-r--r--src/widgets/styles/images/media-seek-backward-32.pngbin548 -> 235 bytes
-rw-r--r--src/widgets/styles/images/media-seek-backward.svg62
-rw-r--r--src/widgets/styles/images/media-seek-forward-128.pngbin0 -> 544 bytes
-rw-r--r--src/widgets/styles/images/media-seek-forward-16.pngbin370 -> 175 bytes
-rw-r--r--src/widgets/styles/images/media-seek-forward-32.pngbin524 -> 232 bytes
-rw-r--r--src/widgets/styles/images/media-seek-forward.svg61
-rw-r--r--src/widgets/styles/images/media-skip-backward-128.pngbin0 -> 582 bytes
-rw-r--r--src/widgets/styles/images/media-skip-backward-16.pngbin396 -> 183 bytes
-rw-r--r--src/widgets/styles/images/media-skip-backward-32.pngbin570 -> 248 bytes
-rw-r--r--src/widgets/styles/images/media-skip-backward.svg67
-rw-r--r--src/widgets/styles/images/media-skip-forward-128.pngbin0 -> 532 bytes
-rw-r--r--src/widgets/styles/images/media-skip-forward-16.pngbin384 -> 176 bytes
-rw-r--r--src/widgets/styles/images/media-skip-forward-32.pngbin549 -> 233 bytes
-rw-r--r--src/widgets/styles/images/media-skip-forward.svg67
-rw-r--r--src/widgets/styles/images/media-stop-128.pngbin0 -> 264 bytes
-rw-r--r--src/widgets/styles/images/media-stop-16.pngbin166 -> 136 bytes
-rw-r--r--src/widgets/styles/images/media-stop-32.pngbin176 -> 147 bytes
-rw-r--r--src/widgets/styles/images/media-stop.svg60
-rw-r--r--src/widgets/styles/images/question-128.pngbin0 -> 2770 bytes
-rw-r--r--src/widgets/styles/images/question-16.pngbin0 -> 797 bytes
-rw-r--r--src/widgets/styles/images/question-32.pngbin0 -> 1063 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-128.pngbin0 -> 1657 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-16.pngbin406 -> 674 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-32.pngbin305 -> 819 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-down-128.pngbin0 -> 1599 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-down-16.pngbin481 -> 666 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-down-32.pngbin278 -> 810 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-down.svg85
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-hover-128.pngbin0 -> 1660 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-hover-16.pngbin570 -> 675 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-hover-32.pngbin305 -> 822 bytes
-rw-r--r--src/widgets/styles/images/standardbutton-closetab-hover.svg86
-rw-r--r--src/widgets/styles/images/standardbutton-closetab.svg86
-rw-r--r--src/widgets/styles/images/toolbar-ext-h-128.pngbin0 -> 1765 bytes
-rw-r--r--src/widgets/styles/images/toolbar-ext-h-rtl-128.pngbin0 -> 1740 bytes
-rw-r--r--src/widgets/styles/images/toolbar-ext-v-80.pngbin0 -> 2035 bytes
-rw-r--r--src/widgets/styles/images/warning-128.pngbin0 -> 1625 bytes
-rw-r--r--src/widgets/styles/images/warning-16.pngbin0 -> 660 bytes
-rw-r--r--src/widgets/styles/images/warning-32.pngbin0 -> 799 bytes
-rw-r--r--src/widgets/styles/qcommonstyle.cpp1912
-rw-r--r--src/widgets/styles/qcommonstyle.h3
-rw-r--r--src/widgets/styles/qcommonstyle_p.h23
-rw-r--r--src/widgets/styles/qdrawutil.cpp112
-rw-r--r--src/widgets/styles/qdrawutil.h11
-rw-r--r--src/widgets/styles/qfusionstyle.cpp582
-rw-r--r--src/widgets/styles/qfusionstyle_p.h1
-rw-r--r--src/widgets/styles/qproxystyle.cpp13
-rw-r--r--src/widgets/styles/qproxystyle_p.h2
-rw-r--r--src/widgets/styles/qstyle.cpp17
-rw-r--r--src/widgets/styles/qstyle.h11
-rw-r--r--src/widgets/styles/qstyle_p.h28
-rw-r--r--src/widgets/styles/qstyleanimation.cpp1
-rw-r--r--src/widgets/styles/qstylehelper.cpp15
-rw-r--r--src/widgets/styles/qstylehelper_p.h2
-rw-r--r--src/widgets/styles/qstyleoption.cpp77
-rw-r--r--src/widgets/styles/qstyleoption.h3
-rw-r--r--src/widgets/styles/qstylepainter.h2
-rw-r--r--src/widgets/styles/qstylesheetstyle.cpp260
-rw-r--r--src/widgets/styles/qstylesheetstyle_default.cpp62
-rw-r--r--src/widgets/styles/qwindowsstyle.cpp182
-rw-r--r--src/widgets/styles/qwindowsstyle_p_p.h9
-rw-r--r--src/widgets/util/qcompleter.cpp49
-rw-r--r--src/widgets/util/qcompleter_p.h2
-rw-r--r--src/widgets/util/qflickgesture.cpp45
-rw-r--r--src/widgets/util/qflickgesture_p.h2
-rw-r--r--src/widgets/util/qscroller.cpp170
-rw-r--r--src/widgets/util/qsystemtrayicon.cpp13
-rw-r--r--src/widgets/util/qsystemtrayicon_qpa.cpp10
-rw-r--r--src/widgets/widgets/qabstractbutton.cpp15
-rw-r--r--src/widgets/widgets/qabstractscrollarea.cpp37
-rw-r--r--src/widgets/widgets/qabstractslider.cpp11
-rw-r--r--src/widgets/widgets/qabstractspinbox.cpp22
-rw-r--r--src/widgets/widgets/qabstractspinbox.h3
-rw-r--r--src/widgets/widgets/qabstractspinbox_p.h4
-rw-r--r--src/widgets/widgets/qbuttongroup.cpp4
-rw-r--r--src/widgets/widgets/qcalendarwidget.cpp56
-rw-r--r--src/widgets/widgets/qcalendarwidget.h6
-rw-r--r--src/widgets/widgets/qcheckbox.cpp27
-rw-r--r--src/widgets/widgets/qcheckbox.h4
-rw-r--r--src/widgets/widgets/qcombobox.cpp460
-rw-r--r--src/widgets/widgets/qcombobox.h15
-rw-r--r--src/widgets/widgets/qcombobox_p.h45
-rw-r--r--src/widgets/widgets/qcommandlinkbutton.cpp8
-rw-r--r--src/widgets/widgets/qdatetimeedit.cpp242
-rw-r--r--src/widgets/widgets/qdatetimeedit.h11
-rw-r--r--src/widgets/widgets/qdatetimeedit_p.h32
-rw-r--r--src/widgets/widgets/qdial.cpp2
-rw-r--r--src/widgets/widgets/qdialogbuttonbox.cpp323
-rw-r--r--src/widgets/widgets/qdialogbuttonbox.h2
-rw-r--r--src/widgets/widgets/qdialogbuttonbox_p.h80
-rw-r--r--src/widgets/widgets/qdockarealayout.cpp93
-rw-r--r--src/widgets/widgets/qdockarealayout_p.h8
-rw-r--r--src/widgets/widgets/qdockwidget.cpp185
-rw-r--r--src/widgets/widgets/qdockwidget.h10
-rw-r--r--src/widgets/widgets/qdockwidget_p.h19
-rw-r--r--src/widgets/widgets/qeffects.cpp9
-rw-r--r--src/widgets/widgets/qfocusframe.cpp8
-rw-r--r--src/widgets/widgets/qfontcombobox.cpp72
-rw-r--r--src/widgets/widgets/qfontcombobox.h2
-rw-r--r--src/widgets/widgets/qgroupbox.cpp11
-rw-r--r--src/widgets/widgets/qkeysequenceedit.cpp24
-rw-r--r--src/widgets/widgets/qkeysequenceedit.h2
-rw-r--r--src/widgets/widgets/qlabel.cpp47
-rw-r--r--src/widgets/widgets/qlabel.h9
-rw-r--r--src/widgets/widgets/qlabel_p.h12
-rw-r--r--src/widgets/widgets/qlcdnumber.cpp4
-rw-r--r--src/widgets/widgets/qlineedit.cpp443
-rw-r--r--src/widgets/widgets/qlineedit.h14
-rw-r--r--src/widgets/widgets/qlineedit_p.cpp112
-rw-r--r--src/widgets/widgets/qlineedit_p.h22
-rw-r--r--src/widgets/widgets/qmainwindow.cpp51
-rw-r--r--src/widgets/widgets/qmainwindow.h1
-rw-r--r--src/widgets/widgets/qmainwindowlayout.cpp549
-rw-r--r--src/widgets/widgets/qmainwindowlayout_p.h45
-rw-r--r--src/widgets/widgets/qmdiarea.cpp94
-rw-r--r--src/widgets/widgets/qmdiarea_p.h2
-rw-r--r--src/widgets/widgets/qmdisubwindow.cpp24
-rw-r--r--src/widgets/widgets/qmdisubwindow.h1
-rw-r--r--src/widgets/widgets/qmdisubwindow_p.h4
-rw-r--r--src/widgets/widgets/qmenu.cpp64
-rw-r--r--src/widgets/widgets/qmenu_p.h7
-rw-r--r--src/widgets/widgets/qmenubar.cpp51
-rw-r--r--src/widgets/widgets/qmenubar_p.h2
-rw-r--r--src/widgets/widgets/qplaintextedit.cpp222
-rw-r--r--src/widgets/widgets/qplaintextedit.h5
-rw-r--r--src/widgets/widgets/qplaintextedit_p.h21
-rw-r--r--src/widgets/widgets/qpushbutton.cpp18
-rw-r--r--src/widgets/widgets/qpushbutton.h5
-rw-r--r--src/widgets/widgets/qpushbutton_p.h4
-rw-r--r--src/widgets/widgets/qradiobutton.cpp2
-rw-r--r--src/widgets/widgets/qscrollarea.cpp6
-rw-r--r--src/widgets/widgets/qscrollarea_p.h2
-rw-r--r--src/widgets/widgets/qscrollbar.cpp28
-rw-r--r--src/widgets/widgets/qsizegrip.cpp6
-rw-r--r--src/widgets/widgets/qspinbox.cpp7
-rw-r--r--src/widgets/widgets/qsplashscreen.cpp54
-rw-r--r--src/widgets/widgets/qsplitter.cpp2
-rw-r--r--src/widgets/widgets/qsplitter_p.h2
-rw-r--r--src/widgets/widgets/qstackedwidget.cpp7
-rw-r--r--src/widgets/widgets/qstatusbar.cpp34
-rw-r--r--src/widgets/widgets/qtabbar.cpp94
-rw-r--r--src/widgets/widgets/qtabbar.h2
-rw-r--r--src/widgets/widgets/qtabbar_p.h12
-rw-r--r--src/widgets/widgets/qtabwidget.cpp50
-rw-r--r--src/widgets/widgets/qtabwidget.h3
-rw-r--r--src/widgets/widgets/qtextbrowser.cpp29
-rw-r--r--src/widgets/widgets/qtextbrowser.h3
-rw-r--r--src/widgets/widgets/qtextedit.cpp156
-rw-r--r--src/widgets/widgets/qtextedit.h8
-rw-r--r--src/widgets/widgets/qtextedit_p.h19
-rw-r--r--src/widgets/widgets/qtoolbar.cpp60
-rw-r--r--src/widgets/widgets/qtoolbarextension.cpp6
-rw-r--r--src/widgets/widgets/qtoolbutton.cpp60
-rw-r--r--src/widgets/widgets/qtoolbutton.h8
-rw-r--r--src/widgets/widgets/qwidgetanimator.cpp3
-rw-r--r--src/widgets/widgets/qwidgetlinecontrol.cpp19
-rw-r--r--src/widgets/widgets/qwidgetlinecontrol_p.h2
-rw-r--r--src/widgets/widgets/qwidgettextcontrol.cpp40
-rw-r--r--src/widgets/widgets/qwidgettextcontrol_p.h5
404 files changed, 12868 insertions, 7855 deletions
diff --git a/src/widgets/CMakeLists.txt b/src/widgets/CMakeLists.txt
index d0c0790921..fdef309a4a 100644
--- a/src/widgets/CMakeLists.txt
+++ b/src/widgets/CMakeLists.txt
@@ -1,8 +1,6 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
-# Generated from widgets.pro.
-
#####################################################################
## Widgets Module:
#####################################################################
@@ -22,6 +20,7 @@ qt_internal_add_module(Widgets
kernel/qlayout.cpp kernel/qlayout.h kernel/qlayout_p.h
kernel/qlayoutengine.cpp kernel/qlayoutengine_p.h
kernel/qlayoutitem.cpp kernel/qlayoutitem.h
+ kernel/qrhiwidget.cpp kernel/qrhiwidget.h kernel/qrhiwidget_p.h
kernel/qsizepolicy.cpp kernel/qsizepolicy.h
kernel/qstackedlayout.cpp kernel/qstackedlayout.h
kernel/qstandardgestures.cpp kernel/qstandardgestures_p.h
@@ -53,7 +52,10 @@ qt_internal_add_module(Widgets
widgets/qframe.cpp widgets/qframe.h widgets/qframe_p.h
widgets/qwidgetanimator.cpp widgets/qwidgetanimator_p.h
DEFINES
+ QT_NO_CONTEXTLESS_CONNECT
QT_NO_USING_NAMESPACE
+ QT_NO_FOREACH
+ QT_USE_NODISCARD_FILE_OPEN
INCLUDE_DIRECTORIES
dialogs
LIBRARIES
@@ -67,14 +69,22 @@ qt_internal_add_module(Widgets
Qt::GuiPrivate
PRECOMPILED_HEADER
"kernel/qt_widgets_pch.h"
+ NO_PCH_SOURCES
+ compat/removed_api.cpp
GENERATE_CPP_EXPORTS
)
+qt_internal_extend_target(Widgets CONDITION APPLE
+ NO_UNITY_BUILD_SOURCES
+ kernel/qapplication.cpp
+)
+
# Resources:
set(qstyle_resource_files
"styles/images/cdr-128.png"
"styles/images/cdr-16.png"
"styles/images/cdr-32.png"
+ "styles/images/cleartext-128.png"
"styles/images/cleartext-16.png"
"styles/images/cleartext-32.png"
"styles/images/closedock-10.png"
@@ -85,6 +95,9 @@ set(qstyle_resource_files
"styles/images/closedock-64.png"
"styles/images/computer-16.png"
"styles/images/computer-32.png"
+ "styles/images/critical-128.png"
+ "styles/images/critical-16.png"
+ "styles/images/critical-32.png"
"styles/images/desktop-16.png"
"styles/images/desktop-32.png"
"styles/images/dirclosed-128.png"
@@ -108,6 +121,12 @@ set(qstyle_resource_files
"styles/images/filecontents-128.png"
"styles/images/filecontents-16.png"
"styles/images/filecontents-32.png"
+ "styles/images/filedialog_end-128.png"
+ "styles/images/filedialog_end-16.png"
+ "styles/images/filedialog_end-32.png"
+ "styles/images/filedialog_start-128.png"
+ "styles/images/filedialog_start-16.png"
+ "styles/images/filedialog_start-32.png"
"styles/images/fileinfo-128.png"
"styles/images/fileinfo-16.png"
"styles/images/fileinfo-32.png"
@@ -123,21 +142,31 @@ set(qstyle_resource_files
"styles/images/harddrive-128.png"
"styles/images/harddrive-16.png"
"styles/images/harddrive-32.png"
+ "styles/images/information-128.png"
+ "styles/images/information-16.png"
+ "styles/images/information-32.png"
"styles/images/left-128.png"
"styles/images/left-16.png"
"styles/images/left-32.png"
+ "styles/images/media-pause-128.png"
"styles/images/media-pause-16.png"
"styles/images/media-pause-32.png"
+ "styles/images/media-play-128.png"
"styles/images/media-play-16.png"
"styles/images/media-play-32.png"
+ "styles/images/media-seek-backward-128.png"
"styles/images/media-seek-backward-16.png"
"styles/images/media-seek-backward-32.png"
+ "styles/images/media-seek-forward-128.png"
"styles/images/media-seek-forward-16.png"
"styles/images/media-seek-forward-32.png"
+ "styles/images/media-skip-backward-128.png"
"styles/images/media-skip-backward-16.png"
"styles/images/media-skip-backward-32.png"
+ "styles/images/media-skip-forward-128.png"
"styles/images/media-skip-forward-16.png"
"styles/images/media-skip-forward-32.png"
+ "styles/images/media-stop-128.png"
"styles/images/media-stop-16.png"
"styles/images/media-stop-32.png"
"styles/images/media-volume-16.png"
@@ -157,6 +186,9 @@ set(qstyle_resource_files
"styles/images/parentdir-128.png"
"styles/images/parentdir-16.png"
"styles/images/parentdir-32.png"
+ "styles/images/question-128.png"
+ "styles/images/question-16.png"
+ "styles/images/question-32.png"
"styles/images/refresh-24.png"
"styles/images/refresh-32.png"
"styles/images/right-128.png"
@@ -174,12 +206,15 @@ set(qstyle_resource_files
"styles/images/standardbutton-close-128.png"
"styles/images/standardbutton-close-16.png"
"styles/images/standardbutton-close-32.png"
- "styles/images/standardbutton-closetab-32.png"
+ "styles/images/standardbutton-closetab-128.png"
"styles/images/standardbutton-closetab-16.png"
- "styles/images/standardbutton-closetab-down-32.png"
+ "styles/images/standardbutton-closetab-32.png"
+ "styles/images/standardbutton-closetab-down-128.png"
"styles/images/standardbutton-closetab-down-16.png"
- "styles/images/standardbutton-closetab-hover-32.png"
+ "styles/images/standardbutton-closetab-down-32.png"
+ "styles/images/standardbutton-closetab-hover-128.png"
"styles/images/standardbutton-closetab-hover-16.png"
+ "styles/images/standardbutton-closetab-hover-32.png"
"styles/images/standardbutton-delete-128.png"
"styles/images/standardbutton-delete-16.png"
"styles/images/standardbutton-delete-32.png"
@@ -218,14 +253,17 @@ set(qstyle_resource_files
"styles/images/titlebar-unshade-16.png"
"styles/images/titlebar-unshade-32.png"
"styles/images/titlebar-unshade-48.png"
+ "styles/images/toolbar-ext-h-128.png"
"styles/images/toolbar-ext-h-16.png"
"styles/images/toolbar-ext-h-32.png"
"styles/images/toolbar-ext-h-8.png"
+ "styles/images/toolbar-ext-h-rtl-128.png"
"styles/images/toolbar-ext-h-rtl-16.png"
"styles/images/toolbar-ext-h-rtl-32.png"
"styles/images/toolbar-ext-h-rtl-8.png"
"styles/images/toolbar-ext-v-10.png"
"styles/images/toolbar-ext-v-20.png"
+ "styles/images/toolbar-ext-v-80.png"
"styles/images/toolbar-ext-v-5.png"
"styles/images/trash-128.png"
"styles/images/trash-16.png"
@@ -239,17 +277,11 @@ set(qstyle_resource_files
"styles/images/viewlist-128.png"
"styles/images/viewlist-16.png"
"styles/images/viewlist-32.png"
+ "styles/images/warning-128.png"
+ "styles/images/warning-16.png"
+ "styles/images/warning-32.png"
)
-set(widgets_no_pch_sources
- compat/removed_api.cpp
-)
-
-foreach(src ${widgets_no_pch_sources})
- qt_update_ignore_pch_source(Widgets ${src})
-endforeach()
-
-
qt_internal_add_resource(Widgets "qstyle"
PREFIX
"/qt-project.org/styles/commonstyle"
@@ -296,15 +328,41 @@ qt_internal_add_resource(Widgets "qstyle1"
${qstyle1_resource_files}
)
+set(qstyle_resource_fusion_files
+ "styles/images/fusion_closedock-10.png"
+ "styles/images/fusion_closedock-16.png"
+ "styles/images/fusion_closedock-20.png"
+ "styles/images/fusion_closedock-32.png"
+ "styles/images/fusion_closedock-48.png"
+ "styles/images/fusion_closedock-64.png"
+ "styles/images/fusion_normalizedockup_10.png"
+ "styles/images/fusion_normalizedockup-16.png"
+ "styles/images/fusion_normalizedockup_20.png"
+ "styles/images/fusion_normalizedockup-32.png"
+ "styles/images/fusion_normalizedockup_48.png"
+ "styles/images/fusion_normalizedockup_64.png"
+ "styles/images/fusion_titlebar-min-10.png"
+ "styles/images/fusion_titlebar-min-16.png"
+ "styles/images/fusion_titlebar-min-20.png"
+ "styles/images/fusion_titlebar-min-32.png"
+ "styles/images/fusion_titlebar-min-48.png"
+ "styles/images/fusion_titlebar-min-64.png"
+)
+
+qt_internal_add_resource(Widgets "qstyle_fusion"
+ PREFIX
+ "/qt-project.org/styles/fusionstyle"
+ BASE
+ "styles"
+ FILES
+ ${qstyle_resource_fusion_files}
+)
+
if(QT_FEATURE_reduce_relocations AND UNIX AND GCC)
target_link_options(Widgets PRIVATE
"LINKER:--dynamic-list=${CMAKE_CURRENT_LIST_DIR}/QtWidgets.dynlist")
endif()
-#### Keys ignored in scope 1:.:.:widgets.pro:<TRUE>:
-# MODULE_CONFIG = "uic"
-# QMAKE_LIBS = "$$QMAKE_LIBS_GUI"
-
## Scopes:
#####################################################################
@@ -511,7 +569,7 @@ qt_internal_extend_target(Widgets CONDITION QT_FEATURE_resizehandler
qt_internal_extend_target(Widgets CONDITION QT_FEATURE_dialogbuttonbox
SOURCES
- widgets/qdialogbuttonbox.cpp widgets/qdialogbuttonbox.h
+ widgets/qdialogbuttonbox.cpp widgets/qdialogbuttonbox.h widgets/qdialogbuttonbox_p.h
)
qt_internal_extend_target(Widgets CONDITION QT_FEATURE_rubberband
@@ -662,6 +720,8 @@ qt_internal_extend_target(Widgets CONDITION QT_FEATURE_inputdialog
qt_internal_extend_target(Widgets CONDITION QT_FEATURE_messagebox
SOURCES
dialogs/qmessagebox.cpp dialogs/qmessagebox.h
+ NO_UNITY_BUILD_SOURCES
+ dialogs/qmessagebox.cpp # error: ‘Old_Ok’ [etc] was not declared in this scope
)
if(QT_FEATURE_messagebox)
@@ -685,15 +745,25 @@ qt_internal_extend_target(Widgets CONDITION QT_FEATURE_progressdialog
dialogs/qprogressdialog.cpp dialogs/qprogressdialog.h
)
-qt_internal_extend_target(Widgets CONDITION QT_FEATURE_wizard
- SOURCES
- dialogs/qwizard.cpp dialogs/qwizard.h
-)
+if(QT_FEATURE_wizard)
+ qt_internal_extend_target(Widgets CONDITION
+ SOURCES
+ dialogs/qwizard.cpp dialogs/qwizard.h
+ )
-qt_internal_extend_target(Widgets CONDITION QT_FEATURE_wizard AND WIN32
- SOURCES
- dialogs/qwizard_win.cpp dialogs/qwizard_win_p.h
-)
+ if(APPLE)
+ set_source_files_properties(dialogs/qwizard.cpp
+ PROPERTIES
+ LANGUAGE OBJCXX
+ SKIP_PRECOMPILE_HEADERS ON
+ )
+ endif()
+
+ qt_internal_extend_target(Widgets CONDITION WIN32
+ SOURCES
+ dialogs/qwizard_win.cpp dialogs/qwizard_win_p.h
+ )
+endif()
qt_internal_extend_target(Widgets CONDITION QT_FEATURE_accessibility
SOURCES
@@ -833,11 +903,20 @@ qt_internal_extend_target(Widgets CONDITION NOT QT_FEATURE_xcb
)
-qt_internal_create_tracepoints(Widgets qtwidgets.tracepoints)
+qt_internal_generate_tracepoints(Widgets widgets
+ SOURCES
+ kernel/qapplication.cpp
+)
+
qt_internal_add_docs(Widgets
doc/qtwidgets.qdocconf
)
+if(IOS)
+ qt_internal_set_apple_privacy_manifest(Widgets
+ "${CMAKE_CURRENT_SOURCE_DIR}/platform/ios/PrivacyInfo.xcprivacy")
+endif()
+
# include the snippet projects for developer-builds
if(QT_FEATURE_private_tests)
add_subdirectory(doc/snippets/customviewstyle)
diff --git a/src/widgets/accessible/complexwidgets.cpp b/src/widgets/accessible/complexwidgets.cpp
index df81713d72..77bf8504fa 100644
--- a/src/widgets/accessible/complexwidgets.cpp
+++ b/src/widgets/accessible/complexwidgets.cpp
@@ -78,7 +78,9 @@ public:
}
QAccessible::State s = parent()->state();
+ s.selectable = true;
s.focused = (m_index == m_parent->currentIndex());
+ s.selected = s.focused;
return s;
}
QRect rect() const override {
@@ -181,6 +183,14 @@ QAccessibleTabBar::~QAccessibleTabBar()
QAccessible::deleteAccessibleInterface(id);
}
+void *QAccessibleTabBar::interface_cast(QAccessible::InterfaceType t)
+{
+ if (t == QAccessible::SelectionInterface) {
+ return static_cast<QAccessibleSelectionInterface*>(this);
+ }
+ return QAccessibleWidget::interface_cast(t);
+}
+
/*! Returns the QTabBar. */
QTabBar *QAccessibleTabBar::tabBar() const
{
@@ -258,6 +268,60 @@ QString QAccessibleTabBar::text(QAccessible::Text t) const
return QString();
}
+int QAccessibleTabBar::selectedItemCount() const
+{
+ if (tabBar()->currentIndex() >= 0)
+ return 1;
+ return 0;
+}
+
+QList<QAccessibleInterface*> QAccessibleTabBar::selectedItems() const
+{
+ QList<QAccessibleInterface*> items;
+ QAccessibleInterface *selected = selectedItem(0);
+ if (selected)
+ items.push_back(selected);
+ return items;
+}
+
+QAccessibleInterface* QAccessibleTabBar::selectedItem(int selectionIndex) const
+{
+ const int currentIndex = tabBar()->currentIndex();
+ if (selectionIndex != 0 || currentIndex < 0)
+ return nullptr;
+ return child(currentIndex);
+}
+
+bool QAccessibleTabBar::isSelected(QAccessibleInterface *childItem) const
+{
+ return childItem && selectedItem(0) == childItem;
+}
+
+bool QAccessibleTabBar::select(QAccessibleInterface *childItem)
+{
+ const int childIndex = indexOfChild(childItem);
+ if (childIndex >= 0) {
+ tabBar()->setCurrentIndex(childIndex);
+ return true;
+ }
+ return false;
+}
+
+bool QAccessibleTabBar::unselect(QAccessibleInterface *)
+{
+ return false;
+}
+
+bool QAccessibleTabBar::selectAll()
+{
+ return false;
+}
+
+bool QAccessibleTabBar::clear()
+{
+ return false;
+}
+
#endif // QT_CONFIG(tabbar)
#if QT_CONFIG(combobox)
@@ -283,17 +347,19 @@ QAccessibleComboBox::QAccessibleComboBox(QWidget *w)
*/
QComboBox *QAccessibleComboBox::comboBox() const
{
- return qobject_cast<QComboBox*>(object());
+ return qobject_cast<QComboBox *>(object());
}
QAccessibleInterface *QAccessibleComboBox::child(int index) const
{
- if (index == 0) {
- QAbstractItemView *view = comboBox()->view();
- //QWidget *parent = view ? view->parentWidget() : 0;
- return QAccessible::queryAccessibleInterface(view);
- } else if (index == 1 && comboBox()->isEditable()) {
- return QAccessible::queryAccessibleInterface(comboBox()->lineEdit());
+ if (QComboBox *cBox = comboBox()) {
+ if (index == 0) {
+ QAbstractItemView *view = cBox->view();
+ //QWidget *parent = view ? view->parentWidget() : 0;
+ return QAccessible::queryAccessibleInterface(view);
+ } else if (index == 1 && cBox->isEditable()) {
+ return QAccessible::queryAccessibleInterface(cBox->lineEdit());
+ }
}
return nullptr;
}
@@ -301,22 +367,28 @@ QAccessibleInterface *QAccessibleComboBox::child(int index) const
int QAccessibleComboBox::childCount() const
{
// list and text edit
- return comboBox()->isEditable() ? 2 : 1;
+ if (QComboBox *cBox = comboBox())
+ return (cBox->isEditable()) ? 2 : 1;
+ return 0;
}
QAccessibleInterface *QAccessibleComboBox::childAt(int x, int y) const
{
- if (comboBox()->isEditable() && comboBox()->lineEdit()->rect().contains(x, y))
- return child(1);
+ if (QComboBox *cBox = comboBox()) {
+ if (cBox->isEditable() && cBox->lineEdit()->rect().contains(x, y))
+ return child(1);
+ }
return nullptr;
}
int QAccessibleComboBox::indexOfChild(const QAccessibleInterface *child) const
{
- if (comboBox()->view() == child->object())
- return 0;
- if (comboBox()->isEditable() && comboBox()->lineEdit() == child->object())
- return 1;
+ if (QComboBox *cBox = comboBox()) {
+ if (cBox->view() == child->object())
+ return 0;
+ if (cBox->isEditable() && cBox->lineEdit() == child->object())
+ return 1;
+ }
return -1;
}
@@ -325,8 +397,10 @@ QAccessibleInterface *QAccessibleComboBox::focusChild() const
// The editable combobox is the focus proxy of its lineedit, so the
// lineedit itself never gets focus. But it is the accessible focus
// child of an editable combobox.
- if (comboBox()->isEditable())
- return child(1);
+ if (QComboBox *cBox = comboBox()) {
+ if (cBox->isEditable())
+ return child(1);
+ }
return nullptr;
}
@@ -334,29 +408,30 @@ QAccessibleInterface *QAccessibleComboBox::focusChild() const
QString QAccessibleComboBox::text(QAccessible::Text t) const
{
QString str;
-
- switch (t) {
- case QAccessible::Name:
+ if (QComboBox *cBox = comboBox()) {
+ switch (t) {
+ case QAccessible::Name:
#ifndef Q_OS_UNIX // on Linux we use relations for this, name is text (fall through to Value)
str = QAccessibleWidget::text(t);
break;
#endif
- case QAccessible::Value:
- if (comboBox()->isEditable())
- str = comboBox()->lineEdit()->text();
- else
- str = comboBox()->currentText();
- break;
+ case QAccessible::Value:
+ if (cBox->isEditable())
+ str = cBox->lineEdit()->text();
+ else
+ str = cBox->currentText();
+ break;
#ifndef QT_NO_SHORTCUT
- case QAccessible::Accelerator:
- str = QKeySequence(Qt::Key_Down).toString(QKeySequence::NativeText);
- break;
+ case QAccessible::Accelerator:
+ str = QKeySequence(Qt::Key_Down).toString(QKeySequence::NativeText);
+ break;
#endif
- default:
- break;
+ default:
+ break;
+ }
+ if (str.isEmpty())
+ str = QAccessibleWidget::text(t);
}
- if (str.isEmpty())
- str = QAccessibleWidget::text(t);
return str;
}
@@ -364,9 +439,11 @@ QAccessible::State QAccessibleComboBox::state() const
{
QAccessible::State s = QAccessibleWidget::state();
- s.expandable = true;
- s.expanded = isValid() && comboBox()->view()->isVisible();
-
+ if (QComboBox *cBox = comboBox()) {
+ s.expandable = true;
+ s.expanded = isValid() && cBox->view()->isVisible();
+ s.editable = cBox->isEditable();
+ }
return s;
}
@@ -384,26 +461,28 @@ QString QAccessibleComboBox::localizedActionDescription(const QString &actionNam
void QAccessibleComboBox::doAction(const QString &actionName)
{
- if (actionName == showMenuAction() || actionName == pressAction()) {
- if (comboBox()->view()->isVisible()) {
+ if (QComboBox *cBox = comboBox()) {
+ if (actionName == showMenuAction() || actionName == pressAction()) {
+ if (cBox->view()->isVisible()) {
#if defined(Q_OS_ANDROID)
- const auto list = child(0)->tableInterface();
- if (list && list->selectedRowCount() > 0) {
- comboBox()->setCurrentIndex(list->selectedRows().at(0));
- }
- comboBox()->setFocus();
+ const auto list = child(0)->tableInterface();
+ if (list && list->selectedRowCount() > 0) {
+ cBox->setCurrentIndex(list->selectedRows().at(0));
+ }
+ cBox->setFocus();
#endif
- comboBox()->hidePopup();
- } else {
- comboBox()->showPopup();
+ cBox->hidePopup();
+ } else {
+ cBox->showPopup();
#if defined(Q_OS_ANDROID)
- const auto list = child(0)->tableInterface();
- if (list && list->selectedRowCount() > 0) {
- auto selectedCells = list->selectedCells();
- QAccessibleEvent ev(selectedCells.at(0),QAccessible::Focus);
- QAccessible::updateAccessibility(&ev);
- }
+ const auto list = child(0)->tableInterface();
+ if (list && list->selectedRowCount() > 0) {
+ auto selectedCells = list->selectedCells();
+ QAccessibleEvent ev(selectedCells.at(0),QAccessible::Focus);
+ QAccessible::updateAccessibility(&ev);
+ }
#endif
+ }
}
}
}
@@ -476,13 +555,19 @@ QWidgetList QAccessibleAbstractScrollArea::accessibleChildren() const
// Horizontal scrollBar container.
QScrollBar *horizontalScrollBar = abstractScrollArea()->horizontalScrollBar();
if (horizontalScrollBar && horizontalScrollBar->isVisible()) {
- children.append(horizontalScrollBar->parentWidget());
+ QWidget *scrollBarParent = horizontalScrollBar->parentWidget();
+ // Add container only if scroll bar is in the container
+ if (elementType(scrollBarParent) == HorizontalContainer)
+ children.append(scrollBarParent);
}
// Vertical scrollBar container.
QScrollBar *verticalScrollBar = abstractScrollArea()->verticalScrollBar();
if (verticalScrollBar && verticalScrollBar->isVisible()) {
- children.append(verticalScrollBar->parentWidget());
+ QWidget *scrollBarParent = verticalScrollBar->parentWidget();
+ // Add container only if scroll bar is in the container
+ if (elementType(scrollBarParent) == VerticalContainer)
+ children.append(scrollBarParent);
}
// CornerWidget.
diff --git a/src/widgets/accessible/complexwidgets_p.h b/src/widgets/accessible/complexwidgets_p.h
index 12535f21a0..5169aa8243 100644
--- a/src/widgets/accessible/complexwidgets_p.h
+++ b/src/widgets/accessible/complexwidgets_p.h
@@ -70,12 +70,14 @@ public:
#endif // QT_CONFIG(scrollarea)
#if QT_CONFIG(tabbar)
-class QAccessibleTabBar : public QAccessibleWidget
+class QAccessibleTabBar : public QAccessibleWidget, public QAccessibleSelectionInterface
{
public:
explicit QAccessibleTabBar(QWidget *w);
~QAccessibleTabBar();
+ void *interface_cast(QAccessible::InterfaceType t) override;
+
QAccessibleInterface *focusChild() const override;
int childCount() const override;
QString text(QAccessible::Text t) const override;
@@ -83,6 +85,16 @@ public:
QAccessibleInterface* child(int index) const override;
int indexOfChild(const QAccessibleInterface *child) const override;
+ // QAccessibleSelectionInterface
+ int selectedItemCount() const override;
+ QList<QAccessibleInterface*> selectedItems() const override;
+ QAccessibleInterface* selectedItem(int selectionIndex) const override;
+ bool isSelected(QAccessibleInterface *childItem) const override;
+ bool select(QAccessibleInterface *childItem) override;
+ bool unselect(QAccessibleInterface *childItem) override;
+ bool selectAll() override;
+ bool clear() override;
+
protected:
QTabBar *tabBar() const;
mutable QHash<int, QAccessible::Id> m_childInterfaces;
diff --git a/src/widgets/accessible/itemviews.cpp b/src/widgets/accessible/itemviews.cpp
index ae1de6cab4..aa5f729820 100644
--- a/src/widgets/accessible/itemviews.cpp
+++ b/src/widgets/accessible/itemviews.cpp
@@ -39,11 +39,16 @@ QAbstractItemView *QAccessibleTable::view() const
int QAccessibleTable::logicalIndex(const QModelIndex &index) const
{
- if (!view()->model() || !index.isValid())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = index.model();
+ if (!theModel || !index.isValid())
return -1;
- int vHeader = verticalHeader() ? 1 : 0;
- int hHeader = horizontalHeader() ? 1 : 0;
- return (index.row() + hHeader)*(index.model()->columnCount() + vHeader) + (index.column() + vHeader);
+
+ const QModelIndex rootIndex = theView->rootIndex();
+ const int vHeader = verticalHeader() ? 1 : 0;
+ const int hHeader = horizontalHeader() ? 1 : 0;
+ return (index.row() + hHeader) * (theModel->columnCount(rootIndex) + vHeader)
+ + (index.column() + vHeader);
}
QAccessibleTable::QAccessibleTable(QWidget *w)
@@ -113,12 +118,14 @@ QHeaderView *QAccessibleTable::verticalHeader() const
QAccessibleInterface *QAccessibleTable::cellAt(int row, int column) const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return nullptr;
Q_ASSERT(role() != QAccessible::Tree);
- QModelIndex index = view()->model()->index(row, column, view()->rootIndex());
+ QModelIndex index = theModel->index(row, column, theView->rootIndex());
if (Q_UNLIKELY(!index.isValid())) {
- qWarning() << "QAccessibleTable::cellAt: invalid index: " << index << " for " << view();
+ qWarning() << "QAccessibleTable::cellAt: invalid index: " << index << " for " << theView;
return nullptr;
}
return child(logicalIndex(index));
@@ -131,23 +138,29 @@ QAccessibleInterface *QAccessibleTable::caption() const
QString QAccessibleTable::columnDescription(int column) const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return QString();
- return view()->model()->headerData(column, Qt::Horizontal).toString();
+ return theModel->headerData(column, Qt::Horizontal).toString();
}
int QAccessibleTable::columnCount() const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return 0;
- return view()->model()->columnCount();
+ return theModel->columnCount(theView->rootIndex());
}
int QAccessibleTable::rowCount() const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return 0;
- return view()->model()->rowCount();
+ return theModel->rowCount(theView->rootIndex());
}
int QAccessibleTable::selectedCellCount() const
@@ -173,9 +186,11 @@ int QAccessibleTable::selectedRowCount() const
QString QAccessibleTable::rowDescription(int row) const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return QString();
- return view()->model()->headerData(row, Qt::Vertical).toString();
+ return theModel->headerData(row, Qt::Vertical).toString();
}
QList<QAccessibleInterface *> QAccessibleTable::selectedCells() const
@@ -237,9 +252,13 @@ bool QAccessibleTable::isRowSelected(int row) const
bool QAccessibleTable::selectRow(int row)
{
- if (!view()->model() || !view()->selectionModel())
+ QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel || !view()->selectionModel())
return false;
- QModelIndex index = view()->model()->index(row, 0, view()->rootIndex());
+
+ const QModelIndex rootIndex = theView->rootIndex();
+ const QModelIndex index = theModel->index(row, 0, rootIndex);
if (!index.isValid() || view()->selectionBehavior() == QAbstractItemView::SelectColumns)
return false;
@@ -253,9 +272,10 @@ bool QAccessibleTable::selectRow(int row)
view()->clearSelection();
break;
case QAbstractItemView::ContiguousSelection:
- if ((!row || !view()->selectionModel()->isRowSelected(row - 1, view()->rootIndex()))
- && !view()->selectionModel()->isRowSelected(row + 1, view()->rootIndex()))
- view()->clearSelection();
+ if ((!row || !theView->selectionModel()->isRowSelected(row - 1, rootIndex))
+ && !theView->selectionModel()->isRowSelected(row + 1, rootIndex)) {
+ theView->clearSelection();
+ }
break;
default:
break;
@@ -267,45 +287,55 @@ bool QAccessibleTable::selectRow(int row)
bool QAccessibleTable::selectColumn(int column)
{
- if (!view()->model() || !view()->selectionModel())
+ QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ auto *selectionModel = theView->selectionModel();
+ if (!theModel || !selectionModel)
return false;
- QModelIndex index = view()->model()->index(0, column, view()->rootIndex());
+
+ const QModelIndex rootIndex = theView->rootIndex();
+ const QModelIndex index = theModel->index(0, column, rootIndex);
if (!index.isValid() || view()->selectionBehavior() == QAbstractItemView::SelectRows)
return false;
- switch (view()->selectionMode()) {
+ switch (theView->selectionMode()) {
case QAbstractItemView::NoSelection:
return false;
case QAbstractItemView::SingleSelection:
- if (view()->selectionBehavior() != QAbstractItemView::SelectColumns && rowCount() > 1)
+ if (theView->selectionBehavior() != QAbstractItemView::SelectColumns && rowCount() > 1)
return false;
Q_FALLTHROUGH();
case QAbstractItemView::ContiguousSelection:
- if ((!column || !view()->selectionModel()->isColumnSelected(column - 1, view()->rootIndex()))
- && !view()->selectionModel()->isColumnSelected(column + 1, view()->rootIndex()))
- view()->clearSelection();
+ if ((!column || !selectionModel->isColumnSelected(column - 1, rootIndex))
+ && !selectionModel->isColumnSelected(column + 1, rootIndex)) {
+ theView->clearSelection();
+ }
break;
default:
break;
}
- view()->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Columns);
+ selectionModel->select(index, QItemSelectionModel::Select | QItemSelectionModel::Columns);
return true;
}
bool QAccessibleTable::unselectRow(int row)
{
- if (!view()->model() || !view()->selectionModel())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ auto *selectionModel = theView->selectionModel();
+ if (!theModel || !selectionModel)
return false;
- QModelIndex index = view()->model()->index(row, 0, view()->rootIndex());
+ const QModelIndex rootIndex = theView->rootIndex();
+ const QModelIndex index = view()->model()->index(row, 0, rootIndex);
if (!index.isValid())
return false;
QItemSelection selection(index, index);
- switch (view()->selectionMode()) {
+ switch (theView->selectionMode()) {
case QAbstractItemView::SingleSelection:
//In SingleSelection and ContiguousSelection once an item
//is selected, there's no way for the user to unselect all items
@@ -316,26 +346,31 @@ bool QAccessibleTable::unselectRow(int row)
if (selectedRowCount() == 1)
return false;
- if ((!row || view()->selectionModel()->isRowSelected(row - 1, view()->rootIndex()))
- && view()->selectionModel()->isRowSelected(row + 1, view()->rootIndex())) {
+ if ((!row || selectionModel->isRowSelected(row - 1, rootIndex))
+ && selectionModel->isRowSelected(row + 1, rootIndex)) {
//If there are rows selected both up the current row and down the current rown,
//the ones which are down the current row will be deselected
- selection = QItemSelection(index, view()->model()->index(rowCount() - 1, 0, view()->rootIndex()));
+ selection = QItemSelection(index, theModel->index(rowCount() - 1, 0, rootIndex));
}
+ break;
default:
break;
}
- view()->selectionModel()->select(selection, QItemSelectionModel::Deselect | QItemSelectionModel::Rows);
+ selectionModel->select(selection, QItemSelectionModel::Deselect | QItemSelectionModel::Rows);
return true;
}
bool QAccessibleTable::unselectColumn(int column)
{
- if (!view()->model() || !view()->selectionModel())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ auto *selectionModel = theView->selectionModel();
+ if (!theModel || !selectionModel)
return false;
- QModelIndex index = view()->model()->index(0, column, view()->rootIndex());
+ const QModelIndex rootIndex = theView->rootIndex();
+ const QModelIndex index = view()->model()->index(0, column, rootIndex);
if (!index.isValid())
return false;
@@ -352,17 +387,18 @@ bool QAccessibleTable::unselectColumn(int column)
if (selectedColumnCount() == 1)
return false;
- if ((!column || view()->selectionModel()->isColumnSelected(column - 1, view()->rootIndex()))
- && view()->selectionModel()->isColumnSelected(column + 1, view()->rootIndex())) {
+ if ((!column || selectionModel->isColumnSelected(column - 1, rootIndex))
+ && selectionModel->isColumnSelected(column + 1, rootIndex)) {
//If there are columns selected both at the left of the current row and at the right
//of the current rown, the ones which are at the right will be deselected
- selection = QItemSelection(index, view()->model()->index(0, columnCount() - 1, view()->rootIndex()));
+ selection = QItemSelection(index, theModel->index(0, columnCount() - 1, rootIndex));
}
+ break;
default:
break;
}
- view()->selectionModel()->select(selection, QItemSelectionModel::Deselect | QItemSelectionModel::Columns);
+ selectionModel->select(selection, QItemSelectionModel::Deselect | QItemSelectionModel::Columns);
return true;
}
@@ -481,10 +517,9 @@ QAccessibleInterface *QAccessibleTable::childAt(int x, int y) const
QPoint indexPosition = view()->mapFromGlobal(QPoint(x, y) - viewportOffset);
// FIXME: if indexPosition < 0 in one coordinate, return header
- QModelIndex index = view()->indexAt(indexPosition);
- if (index.isValid()) {
+ const QModelIndex index = view()->indexAt(indexPosition);
+ if (index.isValid())
return child(logicalIndex(index));
- }
return nullptr;
}
@@ -499,21 +534,27 @@ QAccessibleInterface *QAccessibleTable::focusChild() const
int QAccessibleTable::childCount() const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return 0;
+ const QModelIndex rootIndex = theView->rootIndex();
int vHeader = verticalHeader() ? 1 : 0;
int hHeader = horizontalHeader() ? 1 : 0;
- return (view()->model()->rowCount()+hHeader) * (view()->model()->columnCount()+vHeader);
+ return (theModel->rowCount(rootIndex) + hHeader) * (theModel->columnCount(rootIndex) + vHeader);
}
int QAccessibleTable::indexOfChild(const QAccessibleInterface *iface) const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return -1;
QAccessibleInterface *parent = iface->parent();
- if (parent->object() != view())
+ if (parent->object() != theView)
return -1;
+ const QModelIndex rootIndex = theView->rootIndex();
Q_ASSERT(iface->role() != QAccessible::TreeItem); // should be handled by tree class
if (iface->role() == QAccessible::Cell || iface->role() == QAccessible::ListItem) {
const QAccessibleTableCell* cell = static_cast<const QAccessibleTableCell*>(iface);
@@ -523,7 +564,7 @@ int QAccessibleTable::indexOfChild(const QAccessibleInterface *iface) const
return cell->index + (verticalHeader() ? 1 : 0);
} else if (iface->role() == QAccessible::RowHeader){
const QAccessibleTableHeaderCell* cell = static_cast<const QAccessibleTableHeaderCell*>(iface);
- return (cell->index + 1) * (view()->model()->columnCount() + 1);
+ return (cell->index + 1) * (theModel->columnCount(rootIndex) + 1);
} else if (iface->role() == QAccessible::Pane) {
return 0; // corner button
} else {
@@ -557,14 +598,17 @@ QAccessibleInterface *QAccessibleTable::parent() const
}
return QAccessible::queryAccessibleInterface(view()->parent());
}
- return nullptr;
+ return QAccessible::queryAccessibleInterface(qApp);
}
QAccessibleInterface *QAccessibleTable::child(int logicalIndex) const
{
- if (!view()->model())
+ QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return nullptr;
+ const QModelIndex rootIndex = theView->rootIndex();
auto id = childToId.constFind(logicalIndex);
if (id != childToId.constEnd())
return QAccessible::accessibleInterface(id.value());
@@ -572,7 +616,7 @@ QAccessibleInterface *QAccessibleTable::child(int logicalIndex) const
int vHeader = verticalHeader() ? 1 : 0;
int hHeader = horizontalHeader() ? 1 : 0;
- int columns = view()->model()->columnCount() + vHeader;
+ int columns = theModel->columnCount(rootIndex) + vHeader;
int row = logicalIndex / columns;
int column = logicalIndex % columns;
@@ -582,27 +626,27 @@ QAccessibleInterface *QAccessibleTable::child(int logicalIndex) const
if (vHeader) {
if (column == 0) {
if (hHeader && row == 0) {
- iface = new QAccessibleTableCornerButton(view());
+ iface = new QAccessibleTableCornerButton(theView);
} else {
- iface = new QAccessibleTableHeaderCell(view(), row - hHeader, Qt::Vertical);
+ iface = new QAccessibleTableHeaderCell(theView, row - hHeader, Qt::Vertical);
}
}
--column;
}
if (!iface && hHeader) {
if (row == 0) {
- iface = new QAccessibleTableHeaderCell(view(), column, Qt::Horizontal);
+ iface = new QAccessibleTableHeaderCell(theView, column, Qt::Horizontal);
}
--row;
}
if (!iface) {
- QModelIndex index = view()->model()->index(row, column, view()->rootIndex());
+ QModelIndex index = theModel->index(row, column, rootIndex);
if (Q_UNLIKELY(!index.isValid())) {
qWarning("QAccessibleTable::child: Invalid index at: %d %d", row, column);
return nullptr;
}
- iface = new QAccessibleTableCell(view(), index, cellRole());
+ iface = new QAccessibleTableCell(theView, index, cellRole());
}
QAccessible::registerAccessibleInterface(iface);
@@ -749,34 +793,39 @@ QModelIndex QAccessibleTree::indexFromLogical(int row, int column) const
QAccessibleInterface *QAccessibleTree::childAt(int x, int y) const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return nullptr;
- QPoint viewportOffset = view()->viewport()->mapTo(view(), QPoint(0,0));
- QPoint indexPosition = view()->mapFromGlobal(QPoint(x, y) - viewportOffset);
- QModelIndex index = view()->indexAt(indexPosition);
+ const QPoint viewportOffset = theView->viewport()->mapTo(view(), QPoint(0, 0));
+ const QPoint indexPosition = theView->mapFromGlobal(QPoint(x, y) - viewportOffset);
+
+ const QModelIndex index = theView->indexAt(indexPosition);
if (!index.isValid())
return nullptr;
- const QTreeView *treeView = qobject_cast<const QTreeView*>(view());
+ const QTreeView *treeView = qobject_cast<const QTreeView *>(theView);
int row = treeView->d_func()->viewIndex(index) + (horizontalHeader() ? 1 : 0);
int column = index.column();
- int i = row * view()->model()->columnCount() + column;
+ int i = row * theModel->columnCount(theView->rootIndex()) + column;
return child(i);
}
QAccessibleInterface *QAccessibleTree::focusChild() const
{
- QModelIndex index = view()->currentIndex();
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ const QModelIndex index = theView->currentIndex();
if (!index.isValid())
return nullptr;
- const QTreeView *treeView = qobject_cast<const QTreeView*>(view());
- int row = treeView->d_func()->viewIndex(index) + (horizontalHeader() ? 1 : 0);
- int column = index.column();
+ const QTreeView *treeView = qobject_cast<const QTreeView *>(theView);
+ const int row = treeView->d_func()->viewIndex(index) + (horizontalHeader() ? 1 : 0);
+ const int column = index.column();
- int i = row * view()->model()->columnCount() + column;
+ int i = row * theModel->columnCount(theView->rootIndex()) + column;
return child(i);
}
@@ -784,33 +833,37 @@ int QAccessibleTree::childCount() const
{
const QTreeView *treeView = qobject_cast<const QTreeView*>(view());
Q_ASSERT(treeView);
- if (!view()->model())
+ const QAbstractItemModel *theModel = treeView->model();
+ if (!theModel)
return 0;
int hHeader = horizontalHeader() ? 1 : 0;
- return (treeView->d_func()->viewItems.size() + hHeader)* view()->model()->columnCount();
+ return (treeView->d_func()->viewItems.size() + hHeader)
+ * theModel->columnCount(treeView->rootIndex());
}
QAccessibleInterface *QAccessibleTree::child(int logicalIndex) const
{
- if (logicalIndex < 0 || !view()->model() || !view()->model()->columnCount())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ const QModelIndex rootIndex = theView->rootIndex();
+ if (logicalIndex < 0 || !theModel || !theModel->columnCount(rootIndex))
return nullptr;
QAccessibleInterface *iface = nullptr;
int index = logicalIndex;
if (horizontalHeader()) {
- if (index < view()->model()->columnCount()) {
+ if (index < theModel->columnCount(rootIndex))
iface = new QAccessibleTableHeaderCell(view(), index, Qt::Horizontal);
- } else {
- index -= view()->model()->columnCount();
- }
+ else
+ index -= theModel->columnCount(rootIndex);
}
if (!iface) {
- int row = index / view()->model()->columnCount();
- int column = index % view()->model()->columnCount();
- QModelIndex modelIndex = indexFromLogical(row, column);
+ const int row = index / theModel->columnCount(rootIndex);
+ const int column = index % theModel->columnCount(rootIndex);
+ const QModelIndex modelIndex = indexFromLogical(row, column);
if (!modelIndex.isValid())
return nullptr;
iface = new QAccessibleTableCell(view(), modelIndex, cellRole());
@@ -829,7 +882,9 @@ int QAccessibleTree::rowCount() const
int QAccessibleTree::indexOfChild(const QAccessibleInterface *iface) const
{
- if (!view()->model())
+ const QAbstractItemView *theView = view();
+ const QAbstractItemModel *theModel = theView->model();
+ if (!theModel)
return -1;
QAccessibleInterface *parent = iface->parent();
if (parent->object() != view())
@@ -837,12 +892,12 @@ int QAccessibleTree::indexOfChild(const QAccessibleInterface *iface) const
if (iface->role() == QAccessible::TreeItem) {
const QAccessibleTableCell* cell = static_cast<const QAccessibleTableCell*>(iface);
- const QTreeView *treeView = qobject_cast<const QTreeView*>(view());
+ const QTreeView *treeView = qobject_cast<const QTreeView *>(theView);
Q_ASSERT(treeView);
int row = treeView->d_func()->viewIndex(cell->m_index) + (horizontalHeader() ? 1 : 0);
int column = cell->m_index.column();
- int index = row * view()->model()->columnCount() + column;
+ int index = row * theModel->columnCount(theView->rootIndex()) + column;
return index;
} else if (iface->role() == QAccessible::ColumnHeader){
const QAccessibleTableHeaderCell* cell = static_cast<const QAccessibleTableHeaderCell*>(iface);
@@ -1299,9 +1354,14 @@ void QAccessibleTableHeaderCell::setText(QAccessible::Text, const QString &)
bool QAccessibleTableHeaderCell::isValid() const
{
- return view && !qt_widget_private(view)->data.in_destructor
- && view->model() && (index >= 0)
- && ((orientation == Qt::Horizontal) ? (index < view->model()->columnCount()) : (index < view->model()->rowCount()));
+ const QAbstractItemModel *theModel = view && !qt_widget_private(view)->data.in_destructor
+ ? view->model() : nullptr;
+ if (!theModel)
+ return false;
+ const QModelIndex rootIndex = view->rootIndex();
+ return (index >= 0) && ((orientation == Qt::Horizontal)
+ ? (index < theModel->columnCount(rootIndex))
+ : (index < theModel->rowCount(rootIndex)));
}
QAccessibleInterface *QAccessibleTableHeaderCell::parent() const
diff --git a/src/widgets/accessible/itemviews_p.h b/src/widgets/accessible/itemviews_p.h
index ddc97baba1..077f14de1d 100644
--- a/src/widgets/accessible/itemviews_p.h
+++ b/src/widgets/accessible/itemviews_p.h
@@ -144,8 +144,6 @@ public:
private:
QModelIndex indexFromLogical(int row, int column = 0) const;
-
- inline int logicalIndex(const QModelIndex &index) const;
};
#endif
diff --git a/src/widgets/accessible/qaccessiblewidget.cpp b/src/widgets/accessible/qaccessiblewidget.cpp
index 13f7eca898..b0bb12ea86 100644
--- a/src/widgets/accessible/qaccessiblewidget.cpp
+++ b/src/widgets/accessible/qaccessiblewidget.cpp
@@ -34,22 +34,7 @@ QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
-static QList<QWidget*> childWidgets(const QWidget *widget)
-{
- QList<QWidget*> widgets;
- for (QObject *o : widget->children()) {
- QWidget *w = qobject_cast<QWidget *>(o);
- if (w && !w->isWindow()
- && !qobject_cast<QFocusFrame*>(w)
-#if QT_CONFIG(menu)
- && !qobject_cast<QMenu*>(w)
-#endif
- && w->objectName() != "qt_rubberband"_L1
- && w->objectName() != "qt_spinbox_lineedit"_L1)
- widgets.append(w);
- }
- return widgets;
-}
+QWidgetList _q_ac_childWidgets(const QWidget *widget);
static QString buddyString(const QWidget *widget)
{
@@ -276,7 +261,7 @@ QAccessibleWidget::relations(QAccessible::Relation match /*= QAccessible::AllRel
// first check for all siblings that are labels to us
// ideally we would go through all objects and check, but that
// will be too expensive
- const QList<QWidget*> kids = childWidgets(parent);
+ const QList<QWidget*> kids = _q_ac_childWidgets(parent);
for (QWidget *kid : kids) {
if (QLabel *labelSibling = qobject_cast<QLabel*>(kid)) {
if (labelSibling->buddy() == widget()) {
@@ -327,7 +312,7 @@ QAccessibleInterface *QAccessibleWidget::parent() const
QAccessibleInterface *QAccessibleWidget::child(int index) const
{
Q_ASSERT(widget());
- QWidgetList childList = childWidgets(widget());
+ QWidgetList childList = _q_ac_childWidgets(widget());
if (index >= 0 && index < childList.size())
return QAccessible::queryAccessibleInterface(childList.at(index));
return nullptr;
@@ -355,7 +340,7 @@ QAccessibleInterface *QAccessibleWidget::focusChild() const
/*! \reimp */
int QAccessibleWidget::childCount() const
{
- QWidgetList cl = childWidgets(widget());
+ QWidgetList cl = _q_ac_childWidgets(widget());
return cl.size();
}
@@ -364,7 +349,7 @@ int QAccessibleWidget::indexOfChild(const QAccessibleInterface *child) const
{
if (!child)
return -1;
- QWidgetList cl = childWidgets(widget());
+ QWidgetList cl = _q_ac_childWidgets(widget());
return cl.indexOf(qobject_cast<QWidget *>(child->object()));
}
diff --git a/src/widgets/accessible/qaccessiblewidgetfactory.cpp b/src/widgets/accessible/qaccessiblewidgetfactory.cpp
index 01ada3a5c5..664e35a6e7 100644
--- a/src/widgets/accessible/qaccessiblewidgetfactory.cpp
+++ b/src/widgets/accessible/qaccessiblewidgetfactory.cpp
@@ -84,8 +84,10 @@ QAccessibleInterface *qAccessibleFactory(const QString &classname, QObject *obje
#endif
} else if (classname == "QDialog"_L1) {
iface = new QAccessibleWidget(widget, QAccessible::Dialog);
+#if QT_CONFIG(messagebox)
} else if (classname == "QMessageBox"_L1) {
iface = new QAccessibleMessageBox(widget);
+#endif
#if QT_CONFIG(mainwindow)
} else if (classname == "QMainWindow"_L1) {
iface = new QAccessibleMainWindow(widget);
@@ -119,7 +121,6 @@ QAccessibleInterface *qAccessibleFactory(const QString &classname, QObject *obje
#if QT_CONFIG(itemviews)
} else if (classname == "QTableView"_L1 || classname == "QListView"_L1) {
iface = new QAccessibleTable(widget);
- // ### This should be cleaned up. We return the parent for the scrollarea to hide it.
#endif // QT_CONFIG(itemviews)
#if QT_CONFIG(tabbar)
} else if (classname == "QTabBar"_L1) {
diff --git a/src/widgets/accessible/qaccessiblewidgets.cpp b/src/widgets/accessible/qaccessiblewidgets.cpp
index 5d5196c703..5c2a3bd02b 100644
--- a/src/widgets/accessible/qaccessiblewidgets.cpp
+++ b/src/widgets/accessible/qaccessiblewidgets.cpp
@@ -65,7 +65,7 @@ using namespace Qt::StringLiterals;
QString qt_accStripAmp(const QString &text);
QString qt_accHotKey(const QString &text);
-QList<QWidget*> childWidgets(const QWidget *widget)
+QWidgetList _q_ac_childWidgets(const QWidget *widget)
{
QList<QWidget*> widgets;
if (!widget)
@@ -80,8 +80,10 @@ QList<QWidget*> childWidgets(const QWidget *widget)
#if QT_CONFIG(menu)
&& !qobject_cast<QMenu*>(w)
#endif
+ // Exclude widgets used as implementation details
&& objectName != "qt_rubberband"_L1
- && objectName != "qt_qmainwindow_extended_splitter"_L1) {
+ && objectName != "qt_qmainwindow_extended_splitter"_L1
+ && objectName != "qt_spinbox_lineedit"_L1) {
widgets.append(w);
}
}
@@ -93,7 +95,7 @@ QList<QWidget*> childWidgets(const QWidget *widget)
QAccessiblePlainTextEdit::QAccessiblePlainTextEdit(QWidget* o)
:QAccessibleTextWidget(o)
{
- Q_ASSERT(widget()->inherits("QPlainTextEdit"));
+ Q_ASSERT(qobject_cast<QPlainTextEdit *>(widget()));
}
QPlainTextEdit* QAccessiblePlainTextEdit::plainTextEdit() const
@@ -190,7 +192,7 @@ void QAccessiblePlainTextEdit::scrollToSubstring(int startIndex, int endIndex)
QAccessibleTextEdit::QAccessibleTextEdit(QWidget *o)
: QAccessibleTextWidget(o, QAccessible::EditableText)
{
- Q_ASSERT(widget()->inherits("QTextEdit"));
+ Q_ASSERT(qobject_cast<QTextEdit *>(widget()));
}
/*! Returns the text edit. */
@@ -837,6 +839,8 @@ QString QAccessibleTextWidget::attributes(int offset, int *startOffset, int *end
QFont::Style style = charFormatFont.style();
attrs["font-style"] = QString::fromLatin1((style == QFont::StyleItalic) ? "italic" : ((style == QFont::StyleOblique) ? "oblique": "normal"));
+ attrs["text-line-through-type"] = charFormatFont.strikeOut() ? "single"_L1 : "none"_L1;
+
QTextCharFormat::UnderlineStyle underlineStyle = charFormat.underlineStyle();
if (underlineStyle == QTextCharFormat::NoUnderline && charFormatFont.underline()) // underline could still be set in the default font
underlineStyle = QTextCharFormat::SingleUnderline;
@@ -866,7 +870,7 @@ QString QAccessibleTextWidget::attributes(int offset, int *startOffset, int *end
underlineStyleValue = QStringLiteral("wave"); // this is not correct, but provides good approximation at least
break;
default:
- qWarning() << "Unknown QTextCharFormat::​UnderlineStyle value " << underlineStyle << " could not be translated to IAccessible2 value";
+ qWarning() << "Unknown QTextCharFormat::UnderlineStyle value " << underlineStyle << " could not be translated to IAccessible2 value";
break;
}
if (!underlineStyleValue.isNull()) {
@@ -1071,7 +1075,7 @@ QAccessibleMainWindow::QAccessibleMainWindow(QWidget *widget)
QAccessibleInterface *QAccessibleMainWindow::child(int index) const
{
- QList<QWidget*> kids = childWidgets(mainWindow());
+ QList<QWidget*> kids = _q_ac_childWidgets(mainWindow());
if (index >= 0 && index < kids.size()) {
return QAccessible::queryAccessibleInterface(kids.at(index));
}
@@ -1080,13 +1084,13 @@ QAccessibleInterface *QAccessibleMainWindow::child(int index) const
int QAccessibleMainWindow::childCount() const
{
- QList<QWidget*> kids = childWidgets(mainWindow());
+ QList<QWidget*> kids = _q_ac_childWidgets(mainWindow());
return kids.size();
}
int QAccessibleMainWindow::indexOfChild(const QAccessibleInterface *iface) const
{
- QList<QWidget*> kids = childWidgets(mainWindow());
+ QList<QWidget*> kids = _q_ac_childWidgets(mainWindow());
return kids.indexOf(static_cast<QWidget*>(iface->object()));
}
@@ -1099,7 +1103,7 @@ QAccessibleInterface *QAccessibleMainWindow::childAt(int x, int y) const
if (!QRect(gp.x(), gp.y(), w->width(), w->height()).contains(x, y))
return nullptr;
- const QWidgetList kids = childWidgets(mainWindow());
+ const QWidgetList kids = _q_ac_childWidgets(mainWindow());
QPoint rp = mainWindow()->mapFromGlobal(QPoint(x, y));
for (QWidget *child : kids) {
if (!child->isWindow() && !child->isHidden() && child->geometry().contains(rp)) {
diff --git a/src/widgets/accessible/qaccessiblewidgets_p.h b/src/widgets/accessible/qaccessiblewidgets_p.h
index 69bd84ea23..6d06f294e8 100644
--- a/src/widgets/accessible/qaccessiblewidgets_p.h
+++ b/src/widgets/accessible/qaccessiblewidgets_p.h
@@ -21,7 +21,6 @@
#if QT_CONFIG(accessibility)
#include <QtCore/QPointer>
-#include <QtCore/QPair>
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/accessible/simplewidgets.cpp b/src/widgets/accessible/simplewidgets.cpp
index d3ed74979b..fbbbab857d 100644
--- a/src/widgets/accessible/simplewidgets.cpp
+++ b/src/widgets/accessible/simplewidgets.cpp
@@ -43,8 +43,9 @@
#ifndef QT_NO_PICTURE
#include <QtGui/qpicture.h>
#endif
+#if QT_CONFIG(messagebox)
#include <qmessagebox.h>
-#include <qdialogbuttonbox.h>
+#endif
#include <qstyle.h>
#include <qstyleoption.h>
#include <qtextdocument.h>
@@ -63,7 +64,7 @@ using namespace Qt::StringLiterals;
#if QT_CONFIG(accessibility)
-extern QList<QWidget*> childWidgets(const QWidget *widget);
+QWidgetList _q_ac_childWidgets(const QWidget *widget);
QString qt_accStripAmp(const QString &text);
QString qt_accHotKey(const QString &text);
@@ -215,11 +216,9 @@ QStringList QAccessibleButton::actionNames() const
names << toggleAction();
break;
default:
- if (button()->isCheckable()) {
+ if (button()->isCheckable())
names << toggleAction();
- } else {
- names << pressAction();
- }
+ names << pressAction();
break;
}
}
@@ -402,10 +401,10 @@ QAccessible::Role QAccessibleDisplay::role() const
#if QT_CONFIG(label)
QLabel *l = qobject_cast<QLabel*>(object());
if (l) {
- if (!l->pixmap(Qt::ReturnByValue).isNull())
+ if (!l->pixmap().isNull())
return QAccessible::Graphic;
#ifndef QT_NO_PICTURE
- if (!l->picture(Qt::ReturnByValue).isNull())
+ if (!l->picture().isNull())
return QAccessible::Graphic;
#endif
#if QT_CONFIG(movie)
@@ -530,7 +529,7 @@ QSize QAccessibleDisplay::imageSize() const
#endif
return QSize();
#if QT_CONFIG(label)
- return label->pixmap(Qt::ReturnByValue).size();
+ return label->pixmap().size();
#endif
}
@@ -543,7 +542,7 @@ QPoint QAccessibleDisplay::imagePosition() const
#endif
return QPoint();
#if QT_CONFIG(label)
- if (label->pixmap(Qt::ReturnByValue).isNull())
+ if (label->pixmap().isNull())
return QPoint();
return QPoint(label->mapToGlobal(label->pos()));
@@ -606,7 +605,7 @@ QAccessibleGroupBox::relations(QAccessible::Relation match /* = QAccessible::All
QAccessibleWidget::relations(match);
if ((match & QAccessible::Labelled) && (!groupBox()->title().isEmpty())) {
- const QList<QWidget*> kids = childWidgets(widget());
+ const QList<QWidget*> kids = _q_ac_childWidgets(widget());
for (QWidget *kid : kids) {
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(kid);
if (iface)
@@ -953,6 +952,7 @@ QWindowContainer *QAccessibleWindowContainer::container() const
return static_cast<QWindowContainer *>(widget());
}
+#if QT_CONFIG(messagebox)
/*!
\internal
Implements QAccessibleWidget for QMessageBox
@@ -993,6 +993,7 @@ QString QAccessibleMessageBox::text(QAccessible::Text t) const
return str;
}
+#endif
#endif // QT_CONFIG(accessibility)
diff --git a/src/widgets/accessible/simplewidgets_p.h b/src/widgets/accessible/simplewidgets_p.h
index 027d3c7bbc..c9c03b00d8 100644
--- a/src/widgets/accessible/simplewidgets_p.h
+++ b/src/widgets/accessible/simplewidgets_p.h
@@ -190,6 +190,7 @@ private:
QWindowContainer *container() const;
};
+#if QT_CONFIG(messagebox)
class QAccessibleMessageBox : public QAccessibleWidget
{
public:
@@ -199,6 +200,7 @@ public:
QMessageBox *messageBox() const;
};
+#endif
#endif // QT_CONFIG(accessibility)
diff --git a/src/widgets/compat/removed_api.cpp b/src/widgets/compat/removed_api.cpp
index f43efe36ad..5fcbdba47b 100644
--- a/src/widgets/compat/removed_api.cpp
+++ b/src/widgets/compat/removed_api.cpp
@@ -9,6 +9,7 @@ QT_USE_NAMESPACE
#if QT_WIDGETS_REMOVED_SINCE(6, 3)
+#if QT_CONFIG(menu)
#include "qmenu.h"
QAction *QMenu::addAction(const QString &text)
@@ -20,6 +21,7 @@ QAction *QMenu::addAction(const QIcon &icon, const QString &text)
{
return QWidget::addAction(icon, text);
}
+#endif
#if !QT_CONFIG(shortcut)
// the overloads taking QKeySequence as a trailing argument are deprecated, not removed,
@@ -36,6 +38,7 @@ QAction *QMenu::addAction(const QIcon &icon, const QString &text,
}
#endif
+#if QT_CONFIG(toolbar)
#include "qtoolbar.h"
QAction *QToolBar::addAction(const QString &text)
@@ -59,7 +62,9 @@ QAction *QToolBar::addAction(const QIcon &icon, const QString &text,
{
return QWidget::addAction(icon, text, receiver, member);
}
+#endif
+#if QT_CONFIG(menubar)
#include "qmenubar.h"
QAction *QMenuBar::addAction(const QString &text)
@@ -71,8 +76,28 @@ QAction *QMenuBar::addAction(const QString &text, const QObject *receiver, const
{
return QWidget::addAction(text, receiver, member);
}
+#endif
+
+#endif // QT_WIDGETS_REMOVED_SINCE(6, 3)
+
+#if QT_WIDGETS_REMOVED_SINCE(6, 7)
+
+
+#if QT_CONFIG(filedialog)
+#include "qfiledialog.h"
+
+void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::function<void(const QString &, const QByteArray &)> &fileOpenCompleted)
+{
+ QFileDialog::getOpenFileContent(nameFilter, fileOpenCompleted, nullptr);
+}
+
+void QFileDialog::saveFileContent(const QByteArray &fileContent, const QString &fileNameHint)
+{
+ saveFileContent(fileContent, fileNameHint, nullptr);
+}
+#endif
// #include <qotherheader.h>
// // implement removed functions from qotherheader.h
-#endif // QT_WIDGETS_REMOVED_SINCE(6, 3)
+#endif // QT_WIDGETS_REMOVED_SINCE(6, 7)
diff --git a/src/widgets/configure.cmake b/src/widgets/configure.cmake
index f71ebef9d9..745f2d1152 100644
--- a/src/widgets/configure.cmake
+++ b/src/widgets/configure.cmake
@@ -37,6 +37,10 @@ qt_feature("style-windowsvista" PRIVATE
LABEL "WindowsVista"
CONDITION QT_FEATURE_style_windows AND QT_FEATURE_animation AND WIN32
)
+qt_feature("style-windows11" PRIVATE
+ LABEL "Windows11"
+ CONDITION QT_FEATURE_style_windows AND QT_FEATURE_animation AND WIN32
+)
qt_feature("style-android" PRIVATE
LABEL "Android"
AUTODETECT ANDROID
diff --git a/src/widgets/dialogs/images/qtlogo-64.png b/src/widgets/dialogs/images/qtlogo-64.png
index 39a4a26f39..e40b5c6fc8 100644
--- a/src/widgets/dialogs/images/qtlogo-64.png
+++ b/src/widgets/dialogs/images/qtlogo-64.png
Binary files differ
diff --git a/src/widgets/dialogs/qcolordialog.cpp b/src/widgets/dialogs/qcolordialog.cpp
index d19635bd77..22efecedc9 100644
--- a/src/widgets/dialogs/qcolordialog.cpp
+++ b/src/widgets/dialogs/qcolordialog.cpp
@@ -43,19 +43,29 @@
#include <qpa/qplatformservices.h>
#include <private/qguiapplication_p.h>
+#include <QtCore/qpointer.h>
+
#include <algorithm>
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
-namespace {
+namespace QtPrivate {
class QColorLuminancePicker;
class QColorPicker;
class QColorShower;
class QWellArray;
+class QColorWell;
class QColorPickingEventFilter;
-} // unnamed namespace
+} // namespace QtPrivate
+
+using QColorLuminancePicker = QtPrivate::QColorLuminancePicker;
+using QColorPicker = QtPrivate::QColorPicker;
+using QColorShower = QtPrivate::QColorShower;
+using QWellArray = QtPrivate::QWellArray;
+using QColorWell = QtPrivate::QColorWell;
+using QColorPickingEventFilter = QtPrivate::QColorPickingEventFilter;
class QColorDialogPrivate : public QDialogPrivate
{
@@ -94,16 +104,16 @@ public:
void retranslateStrings();
bool supportsColorPicking() const;
- void _q_addCustom();
+ void addCustom();
void _q_setCustom(int index, QRgb color);
- void _q_newHsv(int h, int s, int v);
- void _q_newColorTypedIn(QRgb rgb);
- void _q_nextCustom(int, int);
- void _q_newCustom(int, int);
- void _q_newStandard(int, int);
- void _q_pickScreenColor();
- void _q_updateColorPicking();
+ void newHsv(int h, int s, int v);
+ void newColorTypedIn(QRgb rgb);
+ void nextCustom(int, int);
+ void newCustom(int, int);
+ void newStandard(int, int);
+ void pickScreenColor();
+ void updateColorPicking();
void updateColorLabelText(const QPoint &);
void updateColorPicking(const QPoint &pos);
void releaseColorPicking();
@@ -112,6 +122,7 @@ public:
bool handleColorPickingKeyPress(QKeyEvent *e);
bool canBeNativeDialog() const override;
+ void setVisible(bool visible) override;
QWellArray *custom;
QWellArray *standard;
@@ -127,7 +138,7 @@ public:
QPushButton *ok;
QPushButton *cancel;
QPushButton *addCusBt;
- QPushButton *screenColorPickerButton;
+ QPushButton *eyeDropperButton = nullptr;
QColor selectedQColor;
int nextCust;
bool smallDisplay;
@@ -150,7 +161,7 @@ private:
//////////// QWellArray BEGIN
-namespace {
+namespace QtPrivate {
class QWellArray : public QWidget
{
@@ -314,7 +325,7 @@ void QWellArray::paintCell(QPainter* p, int row, int col, const QRect &rect)
const QPalette & g = palette();
QStyleOptionFrame opt;
opt.initFrom(this);
- int dfw = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt);
+ int dfw = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, this);
opt.lineWidth = dfw;
opt.midLineWidth = 1;
opt.rect = rect.adjusted(b, b, -b, -b);
@@ -465,7 +476,7 @@ void QWellArray::keyPressEvent(QKeyEvent* e)
return;
}
-}
+} // namespace QtPrivate
//////////// QWellArray END
@@ -555,7 +566,7 @@ static inline void rgb2hsv(QRgb rgb, int &h, int &s, int &v)
c.getHsv(&h, &s, &v);
}
-namespace {
+namespace QtPrivate {
class QColorWell : public QWellArray
{
@@ -705,9 +716,13 @@ private:
bool crossVisible;
};
+} // namespace QtPrivate
+
static int pWidth = 220;
static int pHeight = 200;
+namespace QtPrivate {
+
class QColorLuminancePicker : public QWidget
{
Q_OBJECT
@@ -768,6 +783,10 @@ QColorLuminancePicker::~QColorLuminancePicker()
void QColorLuminancePicker::mouseMoveEvent(QMouseEvent *m)
{
+ if (m->buttons() == Qt::NoButton) {
+ m->ignore();
+ return;
+ }
setVal(y2val(m->position().toPoint().y()));
}
void QColorLuminancePicker::mousePressEvent(QMouseEvent *m)
@@ -817,11 +836,10 @@ void QColorLuminancePicker::paintEvent(QPaintEvent *)
qDrawShadePanel(&p, r, g, true);
p.setPen(g.windowText().color());
p.setBrush(g.windowText());
- QPolygon a;
- int y = val2y(val);
- a.setPoints(3, w, y, w+5, y+5, w+5, y-5);
p.eraseRect(w, 0, 5, height());
- p.drawPolygon(a);
+ const int y = val2y(val);
+ const std::array<QPoint, 3> points = {QPoint(w, y), QPoint(w + 5, y + 5), QPoint(w + 5, y - 5)};
+ p.drawPolygon(points.data(), static_cast<int>(points.size()));
}
void QColorLuminancePicker::setCol(int h, int s , int v)
@@ -902,6 +920,10 @@ void QColorPicker::setCol(int h, int s)
void QColorPicker::mouseMoveEvent(QMouseEvent *m)
{
QPoint p = m->position().toPoint() - contentsRect().topLeft();
+ if (m->buttons() == Qt::NoButton) {
+ m->ignore();
+ return;
+ }
setCol(p);
emit newCol(hue, sat);
}
@@ -1168,8 +1190,8 @@ QColorShower::QColorShower(QColorDialog *parent)
#else
gl->addWidget(lab, 0, 0, 1, -1);
#endif
- connect(lab, SIGNAL(colorDropped(QRgb)), this, SIGNAL(newCol(QRgb)));
- connect(lab, SIGNAL(colorDropped(QRgb)), this, SLOT(setRgb(QRgb)));
+ connect(lab, &QColorShowLabel::colorDropped, this, &QColorShower::newCol);
+ connect(lab, &QColorShowLabel::colorDropped, this, &QColorShower::setRgb);
hEd = new QColSpinBox(this);
hEd->setRange(0, 359);
@@ -1273,12 +1295,13 @@ QColorShower::QColorShower(QColorDialog *parent)
alphaLab->hide();
lblHtml = new QLabel(this);
htEd = new QLineEdit(this);
+ htEd->setObjectName("qt_colorname_lineedit");
#ifndef QT_NO_SHORTCUT
lblHtml->setBuddy(htEd);
#endif
#if QT_CONFIG(regularexpression)
- QRegularExpression regExp(QStringLiteral("#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})"));
+ QRegularExpression regExp(QStringLiteral("#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})"));
QRegularExpressionValidator *validator = new QRegularExpressionValidator(regExp, this);
htEd->setValidator(validator);
#else
@@ -1295,20 +1318,20 @@ QColorShower::QColorShower(QColorDialog *parent)
gl->addWidget(htEd, 5, 2, 1, /*colspan=*/ 3);
#endif
- connect(hEd, SIGNAL(valueChanged(int)), this, SLOT(hsvEd()));
- connect(sEd, SIGNAL(valueChanged(int)), this, SLOT(hsvEd()));
- connect(vEd, SIGNAL(valueChanged(int)), this, SLOT(hsvEd()));
+ connect(hEd, &QSpinBox::valueChanged, this, &QColorShower::hsvEd);
+ connect(sEd, &QSpinBox::valueChanged, this, &QColorShower::hsvEd);
+ connect(vEd, &QSpinBox::valueChanged, this, &QColorShower::hsvEd);
- connect(rEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
- connect(gEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
- connect(bEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
- connect(alphaEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
- connect(htEd, SIGNAL(textEdited(QString)), this, SLOT(htmlEd()));
+ connect(rEd, &QSpinBox::valueChanged, this, &QColorShower::rgbEd);
+ connect(gEd, &QSpinBox::valueChanged, this, &QColorShower::rgbEd);
+ connect(bEd, &QSpinBox::valueChanged, this, &QColorShower::rgbEd);
+ connect(alphaEd, &QSpinBox::valueChanged, this, &QColorShower::rgbEd);
+ connect(htEd, &QLineEdit::textEdited, this, &QColorShower::htmlEd);
retranslateStrings();
}
-} // unnamed namespace
+} // namespace QtPrivate
inline QRgb QColorDialogPrivate::currentColor() const { return cs->currentColor(); }
inline int QColorDialogPrivate::currentAlpha() const { return cs->currentAlpha(); }
@@ -1372,9 +1395,19 @@ void QColorShower::hsvEd()
void QColorShower::htmlEd()
{
QString t = htEd->text();
+ if (t.isEmpty())
+ return;
+
+ if (!t.startsWith(u"#")) {
+ t.prepend(u"#");
+ QSignalBlocker blocker(htEd);
+ htEd->setText(t);
+ }
+
QColor c = QColor::fromString(t);
if (!c.isValid())
return;
+
curCol = qRgba(c.red(), c.green(), c.blue(), currentAlpha());
rgb2hsv(curCol, hue, sat, val);
@@ -1458,7 +1491,7 @@ void QColorShower::updateQColor()
}
//sets all widgets to display h,s,v
-void QColorDialogPrivate::_q_newHsv(int h, int s, int v)
+void QColorDialogPrivate::newHsv(int h, int s, int v)
{
if (!nativeDialogInUse) {
cs->setHsv(h, s, v);
@@ -1472,7 +1505,7 @@ void QColorDialogPrivate::setCurrentRgbColor(QRgb rgb)
{
if (!nativeDialogInUse) {
cs->setRgb(rgb);
- _q_newColorTypedIn(rgb);
+ newColorTypedIn(rgb);
}
}
@@ -1505,7 +1538,7 @@ bool QColorDialogPrivate::selectColor(const QColor &col)
const int index = int(match - standardColors);
const int column = index / standardColorRows;
const int row = index % standardColorRows;
- _q_newStandard(row, column);
+ newStandard(row, column);
standard->setCurrent(row, column);
standard->setSelected(row, column);
standard->setFocus();
@@ -1521,7 +1554,7 @@ bool QColorDialogPrivate::selectColor(const QColor &col)
const int index = int(match - customColors);
const int column = index / customColorRows;
const int row = index % customColorRows;
- _q_newCustom(row, column);
+ newCustom(row, column);
custom->setCurrent(row, column);
custom->setSelected(row, column);
custom->setFocus();
@@ -1544,7 +1577,7 @@ QColor QColorDialogPrivate::grabScreenColor(const QPoint &p)
}
//sets all widgets except cs to display rgb
-void QColorDialogPrivate::_q_newColorTypedIn(QRgb rgb)
+void QColorDialogPrivate::newColorTypedIn(QRgb rgb)
{
if (!nativeDialogInUse) {
int h, s, v;
@@ -1554,12 +1587,12 @@ void QColorDialogPrivate::_q_newColorTypedIn(QRgb rgb)
}
}
-void QColorDialogPrivate::_q_nextCustom(int r, int c)
+void QColorDialogPrivate::nextCustom(int r, int c)
{
nextCust = r + customColorRows * c;
}
-void QColorDialogPrivate::_q_newCustom(int r, int c)
+void QColorDialogPrivate::newCustom(int r, int c)
{
const int i = r + customColorRows * c;
setCurrentRgbColor(QColorDialogOptions::customColor(i));
@@ -1567,14 +1600,14 @@ void QColorDialogPrivate::_q_newCustom(int r, int c)
standard->setSelected(-1,-1);
}
-void QColorDialogPrivate::_q_newStandard(int r, int c)
+void QColorDialogPrivate::newStandard(int r, int c)
{
setCurrentRgbColor(QColorDialogOptions::standardColor(r + c * 6));
if (custom)
custom->setSelected(-1,-1);
}
-void QColorDialogPrivate::_q_pickScreenColor()
+void QColorDialogPrivate::pickScreenColor()
{
Q_Q(QColorDialog);
@@ -1619,8 +1652,8 @@ void QColorDialogPrivate::_q_pickScreenColor()
addCusBt->setDisabled(true);
buttons->setDisabled(true);
- if (screenColorPickerButton) {
- screenColorPickerButton->setDisabled(true);
+ if (eyeDropperButton) {
+ eyeDropperButton->setDisabled(true);
const QPoint globalPos = QCursor::pos();
q->setCurrentColor(grabScreenColor(globalPos));
updateColorLabelText(globalPos);
@@ -1650,7 +1683,7 @@ void QColorDialogPrivate::releaseColorPicking()
lblScreenColorInfo->setText("\n"_L1);
addCusBt->setDisabled(false);
buttons->setDisabled(false);
- screenColorPickerButton->setDisabled(false);
+ eyeDropperButton->setDisabled(false);
}
void QColorDialogPrivate::init(const QColor &initial)
@@ -1707,19 +1740,21 @@ void QColorDialogPrivate::initWidgets()
#ifndef QT_NO_SHORTCUT
lblBasicColors->setBuddy(standard);
#endif
- q->connect(standard, SIGNAL(selected(int,int)), SLOT(_q_newStandard(int,int)));
+ QObjectPrivate::connect(standard, &QColorWell::selected,
+ this, &QColorDialogPrivate::newStandard);
leftLay->addWidget(lblBasicColors);
leftLay->addWidget(standard);
#if !defined(QT_SMALL_COLORDIALOG)
if (supportsColorPicking()) {
- screenColorPickerButton = new QPushButton();
- leftLay->addWidget(screenColorPickerButton);
+ eyeDropperButton = new QPushButton();
+ leftLay->addWidget(eyeDropperButton);
lblScreenColorInfo = new QLabel("\n"_L1);
leftLay->addWidget(lblScreenColorInfo);
- q->connect(screenColorPickerButton, SIGNAL(clicked()), SLOT(_q_pickScreenColor()));
+ QObjectPrivate::connect(eyeDropperButton, &QPushButton::clicked,
+ this, &QColorDialogPrivate::pickScreenColor);
} else {
- screenColorPickerButton = nullptr;
+ eyeDropperButton = nullptr;
lblScreenColorInfo = nullptr;
}
#endif
@@ -1729,10 +1764,10 @@ void QColorDialogPrivate::initWidgets()
custom = new QColorWell(q, customColorRows, colorColumns, QColorDialogOptions::customColors());
custom->setAcceptDrops(true);
- q->connect(custom, SIGNAL(selected(int,int)), SLOT(_q_newCustom(int,int)));
- q->connect(custom, SIGNAL(currentChanged(int,int)), SLOT(_q_nextCustom(int,int)));
+ QObjectPrivate::connect(custom, &QColorWell::selected, this, &QColorDialogPrivate::newCustom);
+ QObjectPrivate::connect(custom, &QColorWell::currentChanged, this, &QColorDialogPrivate::nextCustom);
- q->connect(custom, &QWellArray::colorChanged, [this] (int index, QRgb color) {
+ QObject::connect(custom, &QWellArray::colorChanged, q, [this] (int index, QRgb color) {
QColorDialogOptions::setCustomColor(index, color);
if (custom)
custom->update();
@@ -1746,7 +1781,7 @@ void QColorDialogPrivate::initWidgets()
leftLay->addWidget(custom);
addCusBt = new QPushButton(q);
- QObject::connect(addCusBt, SIGNAL(clicked()), q, SLOT(_q_addCustom()));
+ QObjectPrivate::connect(addCusBt, &QPushButton::clicked, this, &QColorDialogPrivate::addCustom);
leftLay->addWidget(addCusBt);
} else {
// better color picker size for small displays
@@ -1794,16 +1829,17 @@ void QColorDialogPrivate::initWidgets()
pickLay->addStretch();
#endif
- QObject::connect(cp, SIGNAL(newCol(int,int)), lp, SLOT(setCol(int,int)));
- QObject::connect(lp, SIGNAL(newHsv(int,int,int)), q, SLOT(_q_newHsv(int,int,int)));
+ QObject::connect(cp, &QColorPicker::newCol, lp, qOverload<int, int>(&QColorLuminancePicker::setCol));
+ QObjectPrivate::connect(lp, &QColorLuminancePicker::newHsv, this, &QColorDialogPrivate::newHsv);
rightLay->addStretch();
cs = new QColorShower(q);
pickLay->setContentsMargins(cs->gl->contentsMargins());
- QObject::connect(cs, SIGNAL(newCol(QRgb)), q, SLOT(_q_newColorTypedIn(QRgb)));
- QObject::connect(cs, SIGNAL(currentColorChanged(QColor)),
- q, SIGNAL(currentColorChanged(QColor)));
+ QObjectPrivate::connect(cs, &QColorShower::newCol,
+ this, &QColorDialogPrivate::newColorTypedIn);
+ QObject::connect(cs, &QColorShower::currentColorChanged,
+ q, &QColorDialog::currentColorChanged);
#if defined(QT_SMALL_COLORDIALOG)
topLay->addWidget(cs);
#else
@@ -1816,14 +1852,15 @@ void QColorDialogPrivate::initWidgets()
mainLay->addWidget(buttons);
ok = buttons->addButton(QDialogButtonBox::Ok);
- QObject::connect(ok, SIGNAL(clicked()), q, SLOT(accept()));
+ QObject::connect(ok, &QPushButton::clicked, q, &QColorDialog::accept);
ok->setDefault(true);
cancel = buttons->addButton(QDialogButtonBox::Cancel);
- QObject::connect(cancel, SIGNAL(clicked()), q, SLOT(reject()));
+ QObject::connect(cancel, &QPushButton::clicked, q, &QColorDialog::reject);
#ifdef Q_OS_WIN32
updateTimer = new QTimer(q);
- QObject::connect(updateTimer, SIGNAL(timeout()), q, SLOT(_q_updateColorPicking()));
+ QObjectPrivate::connect(updateTimer, &QTimer::timeout,
+ this, qOverload<>(&QColorDialogPrivate::updateColorPicking));
#endif
retranslateStrings();
}
@@ -1831,9 +1868,12 @@ void QColorDialogPrivate::initWidgets()
void QColorDialogPrivate::initHelper(QPlatformDialogHelper *h)
{
QColorDialog *d = q_func();
- QObject::connect(h, SIGNAL(currentColorChanged(QColor)), d, SIGNAL(currentColorChanged(QColor)));
- QObject::connect(h, SIGNAL(colorSelected(QColor)), d, SIGNAL(colorSelected(QColor)));
- static_cast<QPlatformColorDialogHelper *>(h)->setOptions(options);
+ auto *colorDialogHelper = static_cast<QPlatformColorDialogHelper*>(h);
+ QObject::connect(colorDialogHelper, &QPlatformColorDialogHelper::currentColorChanged,
+ d, &QColorDialog::currentColorChanged);
+ QObject::connect(colorDialogHelper, &QPlatformColorDialogHelper::colorSelected,
+ d, &QColorDialog::colorSelected);
+ colorDialogHelper->setOptions(options);
}
void QColorDialogPrivate::helperPrepareShow(QPlatformDialogHelper *)
@@ -1841,7 +1881,7 @@ void QColorDialogPrivate::helperPrepareShow(QPlatformDialogHelper *)
options->setWindowTitle(q_func()->windowTitle());
}
-void QColorDialogPrivate::_q_addCustom()
+void QColorDialogPrivate::addCustom()
{
QColorDialogOptions::setCustomColor(nextCust, cs->currentColor());
if (custom)
@@ -1859,8 +1899,8 @@ void QColorDialogPrivate::retranslateStrings()
lblCustomColors->setText(QColorDialog::tr("&Custom colors"));
addCusBt->setText(QColorDialog::tr("&Add to Custom Colors"));
#if !defined(QT_SMALL_COLORDIALOG)
- if (screenColorPickerButton)
- screenColorPickerButton->setText(QColorDialog::tr("&Pick Screen Color"));
+ if (eyeDropperButton)
+ eyeDropperButton->setText(QColorDialog::tr("&Pick Screen Color"));
#endif
}
@@ -1890,7 +1930,7 @@ bool QColorDialogPrivate::canBeNativeDialog() const
return strcmp(QColorDialog::staticMetaObject.className(), q->metaObject()->className()) == 0;
}
-static const Qt::WindowFlags DefaultWindowFlags =
+static const Qt::WindowFlags qcd_DefaultWindowFlags =
Qt::Dialog | Qt::WindowTitleHint
| Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
@@ -1950,7 +1990,7 @@ QColorDialog::QColorDialog(QWidget *parent)
\a initial color.
*/
QColorDialog::QColorDialog(const QColor &initial, QWidget *parent)
- : QDialog(*new QColorDialogPrivate, parent, DefaultWindowFlags)
+ : QDialog(*new QColorDialogPrivate, parent, qcd_DefaultWindowFlags)
{
Q_D(QColorDialog);
d->init(initial);
@@ -2056,6 +2096,8 @@ void QColorDialog::setOptions(ColorDialogOptions options)
if (!d->nativeDialogInUse) {
d->buttons->setVisible(!(options & NoButtons));
d->showAlpha(options & ShowAlphaChannel);
+ if (d->eyeDropperButton)
+ d->eyeDropperButton->setVisible(!(options & NoEyeDropperButton));
}
}
@@ -2075,6 +2117,7 @@ QColorDialog::ColorDialogOptions QColorDialog::options() const
\value ShowAlphaChannel Allow the user to select the alpha component of a color.
\value NoButtons Don't display \uicontrol{OK} and \uicontrol{Cancel} buttons. (Useful for "live dialogs".)
+ \value NoEyeDropperButton Hide the \uicontrol{Eye Dropper} button. This value was added in Qt 6.6.
\value DontUseNativeDialog Use Qt's standard color dialog instead of the operating system
native color dialog.
@@ -2105,30 +2148,37 @@ QColorDialog::ColorDialogOptions QColorDialog::options() const
*/
void QColorDialog::setVisible(bool visible)
{
- Q_D(QColorDialog);
+ // will call QColorDialogPrivate::setVisible override
+ QDialog::setVisible(visible);
+}
- if (visible){
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
- return;
- } else if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
- return;
+/*!
+ \internal
+
+ The implementation of QColorDialog::setVisible() has to live here so that the call
+ to hide() in ~QDialog calls this function; it wouldn't call the override of
+ QDialog::setVisible().
+*/
+void QColorDialogPrivate::setVisible(bool visible)
+{
+ Q_Q(QColorDialog);
if (visible)
- d->selectedQColor = QColor();
+ selectedQColor = QColor();
- if (d->nativeDialogInUse) {
- if (d->setNativeDialogVisible(visible)) {
+ if (nativeDialogInUse) {
+ if (setNativeDialogVisible(visible)) {
// Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
// updates the state correctly, but skips showing the non-native version:
- setAttribute(Qt::WA_DontShowOnScreen);
+ q->setAttribute(Qt::WA_DontShowOnScreen);
} else {
- d->initWidgets();
+ initWidgets();
}
} else {
- setAttribute(Qt::WA_DontShowOnScreen, false);
+ q->setAttribute(Qt::WA_DontShowOnScreen, false);
}
- QDialog::setVisible(visible);
+ QDialogPrivate::setVisible(visible);
}
/*!
@@ -2176,7 +2226,6 @@ QColor QColorDialog::getColor(const QColor &initial, QWidget *parent, const QStr
QColorDialog::~QColorDialog()
{
-
}
/*!
@@ -2190,7 +2239,7 @@ void QColorDialog::changeEvent(QEvent *e)
QDialog::changeEvent(e);
}
-void QColorDialogPrivate::_q_updateColorPicking()
+void QColorDialogPrivate::updateColorPicking()
{
#ifndef QT_NO_CURSOR
Q_Q(QColorDialog);
diff --git a/src/widgets/dialogs/qcolordialog.h b/src/widgets/dialogs/qcolordialog.h
index 2031c413a9..824efa8f8c 100644
--- a/src/widgets/dialogs/qcolordialog.h
+++ b/src/widgets/dialogs/qcolordialog.h
@@ -26,7 +26,8 @@ public:
enum ColorDialogOption {
ShowAlphaChannel = 0x00000001,
NoButtons = 0x00000002,
- DontUseNativeDialog = 0x00000004
+ DontUseNativeDialog = 0x00000004,
+ NoEyeDropperButton = 0x00000008,
};
Q_ENUM(ColorDialogOption)
@@ -72,15 +73,6 @@ protected:
private:
Q_DISABLE_COPY(QColorDialog)
-
- Q_PRIVATE_SLOT(d_func(), void _q_addCustom())
- Q_PRIVATE_SLOT(d_func(), void _q_newHsv(int h, int s, int v))
- Q_PRIVATE_SLOT(d_func(), void _q_newColorTypedIn(QRgb rgb))
- Q_PRIVATE_SLOT(d_func(), void _q_nextCustom(int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_newCustom(int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_newStandard(int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_pickScreenColor())
- Q_PRIVATE_SLOT(d_func(), void _q_updateColorPicking())
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QColorDialog::ColorDialogOptions)
diff --git a/src/widgets/dialogs/qdialog.cpp b/src/widgets/dialogs/qdialog.cpp
index 8adebf6050..27466d03d6 100644
--- a/src/widgets/dialogs/qdialog.cpp
+++ b/src/widgets/dialogs/qdialog.cpp
@@ -149,25 +149,6 @@ void QDialogPrivate::close(int resultCode)
resetModalitySetByOpen();
}
-/*!
- \internal
-
- Emits finished() signal with \a resultCode. If the \a dialogCode
- is equal to 0 emits rejected(), if the \a dialogCode is equal to
- 1 emits accepted().
- */
-void QDialogPrivate::finalize(int resultCode, int dialogCode)
-{
- Q_Q(QDialog);
-
- if (dialogCode == QDialog::Accepted)
- emit q->accepted();
- else if (dialogCode == QDialog::Rejected)
- emit q->rejected();
-
- emit q->finished(resultCode);
-}
-
QWindow *QDialogPrivate::transientParentWindow() const
{
Q_Q(const QDialog);
@@ -299,7 +280,8 @@ QVariant QDialogPrivate::styleHint(QPlatformDialogHelper::StyleHint hint) const
\section1 Escape Key
If the user presses the Esc key in a dialog, QDialog::reject()
- will be called. This will cause the window to close: The \l{QCloseEvent}{close event} cannot be \l{QEvent::ignore()}{ignored}.
+ will be called. This will cause the window to close:
+ The \l{QCloseEvent}{close event} cannot be \l{QEvent::ignore()}{ignored}.
\section1 Extensibility
@@ -307,9 +289,8 @@ QVariant QDialogPrivate::styleHint(QPlatformDialogHelper::StyleHint hint) const
partial dialog that shows the most commonly used options, and a
full dialog that shows all the options. Typically an extensible
dialog will initially appear as a partial dialog, but with a
- \uicontrol More toggle button. If the user presses the \uicontrol More button down,
- the dialog is expanded. The \l{Extension Example} shows how to achieve
- extensible dialogs using Qt.
+ \uicontrol More toggle button. If the user presses the
+ \uicontrol More button down, the dialog is expanded.
\target return
\section1 Return Value (Modal Dialogs)
@@ -339,7 +320,15 @@ QVariant QDialogPrivate::styleHint(QPlatformDialogHelper::StyleHint hint) const
\snippet dialogs/dialogs.cpp 0
- \sa QDialogButtonBox, QTabWidget, QWidget, QProgressDialog, {Extension Example},
+ A dialog with an extension:
+
+ \snippet dialogs/dialogs.cpp extension
+
+ By setting the \l{QLayout::}{sizeConstraint} property of the dialog's
+ layout to \l{QLayout::}{SetFixedSize}, the dialog will not be resizable
+ by the user, and will automatically shrink when the extension gets hidden.
+
+ \sa QDialogButtonBox, QTabWidget, QWidget, QProgressDialog,
{Standard Dialogs Example}
*/
@@ -612,9 +601,22 @@ int QDialog::exec()
void QDialog::done(int r)
{
+ QPointer<QDialog> guard(this);
+
Q_D(QDialog);
d->close(r);
- d->finalize(r, r);
+
+ if (!guard)
+ return;
+
+ int dialogCode = d->dialogCode();
+ if (dialogCode == QDialog::Accepted)
+ emit accepted();
+ else if (dialogCode == QDialog::Rejected)
+ emit rejected();
+
+ if (guard)
+ emit finished(r);
}
/*!
@@ -742,35 +744,42 @@ void QDialog::closeEvent(QCloseEvent *e)
void QDialog::setVisible(bool visible)
{
Q_D(QDialog);
- if (!testAttribute(Qt::WA_DontShowOnScreen) && d->canBeNativeDialog() && d->setNativeDialogVisible(visible))
+
+ if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden) != visible)
+ return;
+
+ d->setVisible(visible);
+}
+
+void QDialogPrivate::setVisible(bool visible)
+{
+ Q_Q(QDialog);
+ if (!q->testAttribute(Qt::WA_DontShowOnScreen) && canBeNativeDialog() && setNativeDialogVisible(visible))
return;
// We should not block windows by the invisible modal dialog
// if a platform-specific dialog is implemented as an in-process
// Qt window, because in this case it will also be blocked.
- const bool dontBlockWindows = testAttribute(Qt::WA_DontShowOnScreen)
- && d->styleHint(QPlatformDialogHelper::DialogIsQtWindow).toBool();
+ const bool dontBlockWindows = q->testAttribute(Qt::WA_DontShowOnScreen)
+ && styleHint(QPlatformDialogHelper::DialogIsQtWindow).toBool();
Qt::WindowModality oldModality;
bool wasModalitySet;
if (dontBlockWindows) {
- oldModality = windowModality();
- wasModalitySet = testAttribute(Qt::WA_SetWindowModality);
- setWindowModality(Qt::NonModal);
+ oldModality = q->windowModality();
+ wasModalitySet = q->testAttribute(Qt::WA_SetWindowModality);
+ q->setWindowModality(Qt::NonModal);
}
if (visible) {
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
- return;
-
- QWidget::setVisible(visible);
+ q->QWidget::setVisible(visible);
// Window activation might be prevented. We can't test isActiveWindow here,
// as the window will be activated asynchronously by the window manager.
- if (!testAttribute(Qt::WA_ShowWithoutActivating)) {
- QWidget *fw = window()->focusWidget();
+ if (!q->testAttribute(Qt::WA_ShowWithoutActivating)) {
+ QWidget *fw = q->window()->focusWidget();
if (!fw)
- fw = this;
+ fw = q;
/*
The following block is to handle a special case, and does not
@@ -783,14 +792,14 @@ void QDialog::setVisible(bool visible)
have to use [widget*]->setFocus() themselves...
*/
#if QT_CONFIG(pushbutton)
- if (d->mainDef && fw->focusPolicy() == Qt::NoFocus) {
+ if (mainDef && fw->focusPolicy() == Qt::NoFocus) {
QWidget *first = fw;
while ((first = first->nextInFocusChain()) != fw && first->focusPolicy() == Qt::NoFocus)
;
- if (first != d->mainDef && qobject_cast<QPushButton*>(first))
- d->mainDef->setFocus();
+ if (first != mainDef && qobject_cast<QPushButton*>(first))
+ mainDef->setFocus();
}
- if (!d->mainDef && isWindow()) {
+ if (!mainDef && q->isWindow()) {
QWidget *w = fw;
while ((w = w->nextInFocusChain()) != fw) {
QPushButton *pb = qobject_cast<QPushButton *>(w);
@@ -808,37 +817,35 @@ void QDialog::setVisible(bool visible)
}
#if QT_CONFIG(accessibility)
- QAccessibleEvent event(this, QAccessible::DialogStart);
+ QAccessibleEvent event(q, QAccessible::DialogStart);
QAccessible::updateAccessibility(&event);
#endif
} else {
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
- return;
#if QT_CONFIG(accessibility)
- if (isVisible()) {
- QAccessibleEvent event(this, QAccessible::DialogEnd);
+ if (q->isVisible()) {
+ QAccessibleEvent event(q, QAccessible::DialogEnd);
QAccessible::updateAccessibility(&event);
}
#endif
// Reimplemented to exit a modal event loop when the dialog is hidden.
- QWidget::setVisible(visible);
- if (d->eventLoop)
- d->eventLoop->exit();
+ q->QWidget::setVisible(visible);
+ if (eventLoop)
+ eventLoop->exit();
}
if (dontBlockWindows) {
- setWindowModality(oldModality);
- setAttribute(Qt::WA_SetWindowModality, wasModalitySet);
+ q->setWindowModality(oldModality);
+ q->setAttribute(Qt::WA_SetWindowModality, wasModalitySet);
}
#if QT_CONFIG(pushbutton)
const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme();
- if (d->mainDef && isActiveWindow()
+ if (mainDef && q->isActiveWindow()
&& theme->themeHint(QPlatformTheme::DialogSnapToDefaultButton).toBool())
- QCursor::setPos(d->mainDef->mapToGlobal(d->mainDef->rect().center()));
+ QCursor::setPos(mainDef->mapToGlobal(mainDef->rect().center()));
#endif
}
diff --git a/src/widgets/dialogs/qdialog.h b/src/widgets/dialogs/qdialog.h
index 4d11fe2d8d..22360bc358 100644
--- a/src/widgets/dialogs/qdialog.h
+++ b/src/widgets/dialogs/qdialog.h
@@ -28,6 +28,7 @@ public:
~QDialog();
enum DialogCode { Rejected, Accepted };
+ Q_ENUM(DialogCode)
int result() const;
diff --git a/src/widgets/dialogs/qdialog_p.h b/src/widgets/dialogs/qdialog_p.h
index 28b5bc16b6..bac33bdea9 100644
--- a/src/widgets/dialogs/qdialog_p.h
+++ b/src/widgets/dialogs/qdialog_p.h
@@ -51,6 +51,8 @@ public:
{}
~QDialogPrivate();
+ virtual void setVisible(bool visible);
+
QWindow *transientParentWindow() const;
bool setNativeDialogVisible(bool visible);
QVariant styleHint(QPlatformDialogHelper::StyleHint hint) const;
@@ -86,7 +88,9 @@ public:
virtual bool canBeNativeDialog() const;
void close(int resultCode);
- void finalize(int resultCode, int dialogCode);
+
+protected:
+ virtual int dialogCode() const { return rescode; }
private:
virtual void initHelper(QPlatformDialogHelper *) {}
@@ -101,7 +105,7 @@ template <typename T>
class QAutoPointer {
QPointer<T> o;
public:
- explicit QAutoPointer(T *t) noexcept : o(t) {}
+ Q_NODISCARD_CTOR explicit QAutoPointer(T *t) noexcept : o(t) {}
~QAutoPointer() { delete o; }
T *operator->() const noexcept { return get(); }
diff --git a/src/widgets/dialogs/qerrormessage.cpp b/src/widgets/dialogs/qerrormessage.cpp
index 2c36e535c7..2b5681f79b 100644
--- a/src/widgets/dialogs/qerrormessage.cpp
+++ b/src/widgets/dialogs/qerrormessage.cpp
@@ -28,17 +28,15 @@ QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
-namespace {
-struct Message {
- QString content;
- QString type;
-};
-}
-
class QErrorMessagePrivate : public QDialogPrivate
{
Q_DECLARE_PUBLIC(QErrorMessage)
public:
+ struct Message {
+ QString content;
+ QString type;
+ };
+
QPushButton * ok;
QCheckBox * again;
QTextEdit * errors;
@@ -53,6 +51,8 @@ public:
bool nextPending();
void retranslateStrings();
+ void setVisible(bool) override;
+
private:
void initHelper(QPlatformDialogHelper *) override;
void helperPrepareShow(QPlatformDialogHelper *) override;
@@ -63,9 +63,9 @@ void QErrorMessagePrivate::initHelper(QPlatformDialogHelper *helper)
{
Q_Q(QErrorMessage);
auto *messageDialogHelper = static_cast<QPlatformMessageDialogHelper *>(helper);
- QObject::connect(messageDialogHelper, &QPlatformMessageDialogHelper::supressionCheckBoxChanged, q,
- [this](bool supressionChecked) {
- again->setChecked(!supressionChecked);
+ QObject::connect(messageDialogHelper, &QPlatformMessageDialogHelper::checkBoxStateChanged, q,
+ [this](Qt::CheckState state) {
+ again->setCheckState(state);
}
);
QObject::connect(messageDialogHelper, &QPlatformMessageDialogHelper::clicked, q,
@@ -85,8 +85,8 @@ void QErrorMessagePrivate::helperPrepareShow(QPlatformDialogHelper *helper)
options->setWindowTitle(q->windowTitle());
options->setText(QErrorMessage::tr("An error occurred"));
options->setInformativeText(currentMessage);
- options->setIcon(QMessageDialogOptions::Critical);
- options->setSupressionCheckBoxEnabled(true);
+ options->setStandardIcon(QMessageDialogOptions::Critical);
+ options->setCheckBox(again->text(), again->checkState());
messageDialogHelper->setOptions(options);
}
@@ -257,7 +257,9 @@ QErrorMessage::QErrorMessage(QWidget * parent)
grid->setRowStretch(0, 42);
#if QT_CONFIG(messagebox)
- d->icon->setPixmap(style()->standardPixmap(QStyle::SP_MessageBoxInformation));
+ const auto iconSize = style()->pixelMetric(QStyle::PM_MessageBoxIconSize, nullptr, this);
+ const auto icon = style()->standardIcon(QStyle::SP_MessageBoxInformation, nullptr, this);
+ d->icon->setPixmap(icon.pixmap(QSize(iconSize, iconSize), devicePixelRatio()));
d->icon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
#endif
d->again->setChecked(true);
@@ -358,6 +360,7 @@ bool QErrorMessagePrivate::nextPending()
#endif
currentMessage = std::move(message);
currentType = std::move(type);
+ again->setChecked(true);
return true;
}
}
@@ -403,21 +406,19 @@ void QErrorMessage::showMessage(const QString &message, const QString &type)
show();
}
-void QErrorMessage::setVisible(bool visible)
+void QErrorMessagePrivate::setVisible(bool visible)
{
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden) != visible)
- return;
+ Q_Q(QErrorMessage);
- Q_D(QErrorMessage);
- if (d->canBeNativeDialog())
- d->setNativeDialogVisible(visible);
+ if (canBeNativeDialog())
+ setNativeDialogVisible(visible);
// Update WA_DontShowOnScreen based on whether the native dialog was shown,
// so that QDialog::setVisible(visible) below updates the QWidget state correctly,
// but skips showing the non-native version.
- setAttribute(Qt::WA_DontShowOnScreen, d->nativeDialogInUse);
+ q->setAttribute(Qt::WA_DontShowOnScreen, nativeDialogInUse);
- QDialog::setVisible(visible);
+ QDialogPrivate::setVisible(visible);
}
/*!
diff --git a/src/widgets/dialogs/qerrormessage.h b/src/widgets/dialogs/qerrormessage.h
index c2e68fdb51..55f0ac058e 100644
--- a/src/widgets/dialogs/qerrormessage.h
+++ b/src/widgets/dialogs/qerrormessage.h
@@ -28,8 +28,6 @@ public Q_SLOTS:
void showMessage(const QString &message);
void showMessage(const QString &message, const QString &type);
- void setVisible(bool) override;
-
protected:
void done(int) override;
void changeEvent(QEvent *e) override;
diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp
index e2f81c22a1..22e6d44e6f 100644
--- a/src/widgets/dialogs/qfiledialog.cpp
+++ b/src/widgets/dialogs/qfiledialog.cpp
@@ -58,14 +58,17 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
/*!
\class QFileDialog
- \brief The QFileDialog class provides a dialog that allow users to select files or directories.
+ \brief The QFileDialog class provides a dialog that allows users to select files or directories.
\ingroup standard-dialogs
\inmodule QtWidgets
- The QFileDialog class enables a user to traverse the file system in
- order to select one or many files or a directory.
+ The QFileDialog class enables a user to traverse the file system
+ to select one or many files or a directory.
- The easiest way to create a QFileDialog is to use the static functions.
+ \image qtquickdialogs-filedialog-gtk.png
+
+ The easiest way to create a QFileDialog is to use the static functions,
+ such as \l getOpenFileName().
\snippet code/src_gui_dialogs_qfiledialog.cpp 0
@@ -90,7 +93,7 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
AnyFile, meaning that the user can select any file, or even specify a
file that doesn't exist. This mode is useful for creating a
"Save As" file dialog. Use ExistingFile if the user must select an
- existing file, or \l Directory if only a directory may be selected.
+ existing file, or \l Directory if only a directory can be selected.
See the \l QFileDialog::FileMode enum for the complete list of modes.
The fileMode property contains the mode of operation for the dialog;
@@ -99,9 +102,9 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
\snippet code/src_gui_dialogs_qfiledialog.cpp 3
- In the above example, the filter is set to \c{"Images (*.png *.xpm *.jpg)"},
- this means that only files with the extension \c png, \c xpm,
- or \c jpg will be shown in the QFileDialog. You can apply
+ In the above example, the filter is set to \c{"Images (*.png *.xpm *.jpg)"}.
+ This means that only files with the extension \c png, \c xpm,
+ or \c jpg are shown in the QFileDialog. You can apply
several filters by using setNameFilters(). Use selectNameFilter() to select
one of the filters you've given as the file dialog's default filter.
@@ -115,7 +118,7 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
\snippet code/src_gui_dialogs_qfiledialog.cpp 4
- The last important function you will need to use when creating your
+ The last important function you need to use when creating your
own file dialog is selectedFiles().
\snippet code/src_gui_dialogs_qfiledialog.cpp 5
@@ -130,16 +133,16 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
The \l{dialogs/standarddialogs}{Standard Dialogs} example shows
how to use QFileDialog as well as other built-in Qt dialogs.
- By default, a platform-native file dialog will be used if the platform has
- one. In that case, the widgets which would otherwise be used to construct the
- dialog will not be instantiated, so related accessors such as layout() and
- itemDelegate() will return null. Also, not all platforms show file dialogs
+ By default, a platform-native file dialog is used if the platform has
+ one. In that case, the widgets that would otherwise be used to construct the
+ dialog are not instantiated, so related accessors such as layout() and
+ itemDelegate() return null. Also, not all platforms show file dialogs
with a title bar, so be aware that the caption text might not be visible to
- the user. You can set the \l DontUseNativeDialog option to ensure that the
- widget-based implementation will be used instead of the native dialog.
+ the user. You can set the \l DontUseNativeDialog option or set the
+ \l{Qt::AA_DontUseNativeDialogs}{AA_DontUseNativeDialogs} application attribute
+ to ensure that the widget-based implementation is used instead of the native dialog.
- \sa QDir, QFileInfo, QFile, QColorDialog, QFontDialog, {Standard Dialogs Example},
- {Qt Widgets - Application Example}
+ \sa QDir, QFileInfo, QFile, QColorDialog, QFontDialog, {Standard Dialogs Example}
*/
/*!
@@ -152,8 +155,8 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
/*!
\enum QFileDialog::ViewMode
- This enum describes the view mode of the file dialog; i.e. what
- information about each file will be displayed.
+ This enum describes the view mode of the file dialog; that is, what
+ information about each file is displayed.
\value Detail Displays an icon, a name, and details for each item in
the directory.
@@ -167,7 +170,7 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
\enum QFileDialog::FileMode
This enum is used to indicate what the user may select in the file
- dialog; i.e. what the dialog will return if the user clicks OK.
+ dialog; that is, what the dialog returns if the user clicks OK.
\value AnyFile The name of a file, whether it exists or not.
\value ExistingFile The name of a single existing file.
@@ -183,37 +186,43 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
/*!
\enum QFileDialog::Option
- \value ShowDirsOnly Only show directories in the file dialog. By
- default both files and directories are shown. (Valid only in the
- \l Directory file mode.)
-
- \value DontResolveSymlinks Don't resolve symlinks in the file
- dialog. By default symlinks are resolved.
+ Options that influence the behavior of the dialog.
- \value DontConfirmOverwrite Don't ask for confirmation if an
- existing file is selected. By default confirmation is requested.
+ \value ShowDirsOnly Only show directories. By
+ default, both files and directories are shown.\br
+ This option is only effective in the \l Directory file mode.
- Note: This option is not supported on macOS when using the
- native file dialog.
+ \value DontResolveSymlinks Don't resolve symlinks.
+ By default, symlinks are resolved.
- \value DontUseNativeDialog Don't use the native file dialog. By
- default, the native file dialog is used unless you use a subclass
- of QFileDialog that contains the Q_OBJECT macro, or the platform
- does not have a native dialog of the type that you require.
+ \value DontConfirmOverwrite Don't ask for confirmation if an
+ existing file is selected. By default, confirmation is requested.\br
+ This option is only effective if \l acceptMode is \l {QFileDialog::}{AcceptSave}).
+ It is furthermore not used on macOS for native file dialogs.
- \b{Note:} This option must be set before changing dialog properties
- or showing the dialog.
+ \value DontUseNativeDialog Don't use a platform-native file dialog,
+ but the widget-based one provided by Qt.\br
+ By default, a native file dialog is shown unless you use a subclass
+ of QFileDialog that contains the Q_OBJECT macro, the global
+ \l{Qt::}{AA_DontUseNativeDialogs} application attribute is set, or the platform
+ does not have a native dialog of the type that you require.\br
+ For the option to be effective, you must set it before changing
+ other properties of the dialog, or showing the dialog.
- \value ReadOnly Indicates that the model is readonly.
+ \value ReadOnly Indicates that the model is read-only.
\value HideNameFilterDetails Indicates if the file name filter details are
hidden or not.
- \value DontUseCustomDirectoryIcons Always use the default directory icon.
- Some platforms allow the user to set a different icon. Custom icon lookup
- cause a big performance impact over network or removable drives.
- Setting this will enable the QFileIconProvider::DontUseCustomDirectoryIcons
- option in the icon provider. This enum value was added in Qt 5.2.
+ \value DontUseCustomDirectoryIcons Always use the default directory icon.\br
+ Some platforms allow the user to set a different icon, but custom icon lookup
+ might cause significant performance issues over network or removable drives.\br
+ Setting this will enable the
+ \l{QAbstractFileIconProvider::}{DontUseCustomDirectoryIcons}
+ option in \l{iconProvider()}.\br
+ This enum value was added in Qt 5.2.
+
+ \sa options, testOption
*/
/*!
@@ -380,7 +389,7 @@ QFileDialog::~QFileDialog()
\snippet filedialogurls/filedialogurls.cpp 0
- The file dialog will then look like this:
+ Then the file dialog looks like this:
\image filedialogurls.png
@@ -524,13 +533,19 @@ QFileDialogPrivate::~QFileDialogPrivate()
void QFileDialogPrivate::initHelper(QPlatformDialogHelper *h)
{
- QFileDialog *d = q_func();
- QObject::connect(h, SIGNAL(fileSelected(QUrl)), d, SLOT(_q_emitUrlSelected(QUrl)));
- QObject::connect(h, SIGNAL(filesSelected(QList<QUrl>)), d, SLOT(_q_emitUrlsSelected(QList<QUrl>)));
- QObject::connect(h, SIGNAL(currentChanged(QUrl)), d, SLOT(_q_nativeCurrentChanged(QUrl)));
- QObject::connect(h, SIGNAL(directoryEntered(QUrl)), d, SLOT(_q_nativeEnterDirectory(QUrl)));
- QObject::connect(h, SIGNAL(filterSelected(QString)), d, SIGNAL(filterSelected(QString)));
- static_cast<QPlatformFileDialogHelper *>(h)->setOptions(options);
+ Q_Q(QFileDialog);
+ auto *fileDialogHelper = static_cast<QPlatformFileDialogHelper *>(h);
+ QObjectPrivate::connect(fileDialogHelper, &QPlatformFileDialogHelper::fileSelected,
+ this, &QFileDialogPrivate::emitUrlSelected);
+ QObjectPrivate::connect(fileDialogHelper, &QPlatformFileDialogHelper::filesSelected,
+ this, &QFileDialogPrivate::emitUrlsSelected);
+ QObjectPrivate::connect(fileDialogHelper, &QPlatformFileDialogHelper::currentChanged,
+ this, &QFileDialogPrivate::nativeCurrentChanged);
+ QObjectPrivate::connect(fileDialogHelper, &QPlatformFileDialogHelper::directoryEntered,
+ this, &QFileDialogPrivate::nativeEnterDirectory);
+ QObject::connect(fileDialogHelper, &QPlatformFileDialogHelper::filterSelected,
+ q, &QFileDialog::filterSelected);
+ fileDialogHelper->setOptions(options);
}
void QFileDialogPrivate::helperPrepareShow(QPlatformDialogHelper *)
@@ -651,7 +666,7 @@ void QFileDialogPrivate::retranslateStrings()
if (proxyModel)
abstractModel = proxyModel;
#endif
- int total = qMin(abstractModel->columnCount(QModelIndex()), actions.size() + 1);
+ const int total = qMin(abstractModel->columnCount(QModelIndex()), int(actions.size() + 1));
for (int i = 1; i < total; ++i) {
actions.at(i - 1)->setText(QFileDialog::tr("Show ") + abstractModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString());
}
@@ -702,7 +717,7 @@ bool QFileDialogPrivate::usingWidgets() const
Sets the given \a option to be enabled if \a on is true; otherwise,
clears the given \a option.
- Options (particularly the DontUseNativeDialogs option) should be set
+ Options (particularly the \l DontUseNativeDialog option) should be set
before changing dialog properties or showing the dialog.
Setting options while the dialog is visible is not guaranteed to have
@@ -737,12 +752,12 @@ bool QFileDialog::testOption(Option option) const
/*!
\property QFileDialog::options
- \brief the various options that affect the look and feel of the dialog
+ \brief The various options that affect the look and feel of the dialog.
\since 4.5
By default, all options are disabled.
- Options (particularly the DontUseNativeDialogs option) should be set
+ Options (particularly the \l DontUseNativeDialog option) should be set
before changing dialog properties or showing the dialog.
Setting options while the dialog is visible is not guaranteed to have
@@ -811,11 +826,11 @@ QFileDialog::Options QFileDialog::options() const
/*!
\since 4.5
- This function connects one of its signals to the slot specified by \a receiver
- and \a member. The specific signal depends is filesSelected() if fileMode is
- ExistingFiles and fileSelected() if fileMode is anything else.
+ This function shows the dialog, and connects the slot specified by \a receiver
+ and \a member to the signal that informs about selection changes. If the fileMode is
+ ExistingFiles, this is the filesSelected() signal, otherwise it is the fileSelected() signal.
- The signal will be disconnected from the slot when the dialog is closed.
+ The signal is disconnected from the slot when the dialog is closed.
*/
void QFileDialog::open(QObject *receiver, const char *member)
{
@@ -836,54 +851,61 @@ void QFileDialog::open(QObject *receiver, const char *member)
*/
void QFileDialog::setVisible(bool visible)
{
- Q_D(QFileDialog);
- if (visible){
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
- return;
- } else if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
- return;
+ // will call QFileDialogPrivate::setVisible override
+ QDialog::setVisible(visible);
+}
+
+/*!
+ \internal
+
+ The logic has to live here so that the call to hide() in ~QDialog calls
+ this function; it wouldn't call an override of QDialog::setVisible().
+*/
+void QFileDialogPrivate::setVisible(bool visible)
+{
+ Q_Q(QFileDialog);
- if (d->canBeNativeDialog()){
- if (d->setNativeDialogVisible(visible)){
- // Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
+ if (canBeNativeDialog()){
+ if (setNativeDialogVisible(visible)){
+ // Set WA_DontShowOnScreen so that QDialogPrivate::setVisible(visible) below
// updates the state correctly, but skips showing the non-native version:
- setAttribute(Qt::WA_DontShowOnScreen);
+ q->setAttribute(Qt::WA_DontShowOnScreen);
#if QT_CONFIG(fscompleter)
// So the completer doesn't try to complete and therefore show a popup
- if (!d->nativeDialogInUse)
- d->completer->setModel(nullptr);
+ if (!nativeDialogInUse)
+ completer->setModel(nullptr);
#endif
} else {
- d->createWidgets();
- setAttribute(Qt::WA_DontShowOnScreen, false);
+ createWidgets();
+ q->setAttribute(Qt::WA_DontShowOnScreen, false);
#if QT_CONFIG(fscompleter)
- if (!d->nativeDialogInUse) {
- if (d->proxyModel != nullptr)
- d->completer->setModel(d->proxyModel);
+ if (!nativeDialogInUse) {
+ if (proxyModel != nullptr)
+ completer->setModel(proxyModel);
else
- d->completer->setModel(d->model);
+ completer->setModel(model);
}
#endif
}
}
- if (visible && d->usingWidgets())
- d->qFileDialogUi->fileNameEdit->setFocus();
+ if (visible && usingWidgets())
+ qFileDialogUi->fileNameEdit->setFocus();
- QDialog::setVisible(visible);
+ QDialogPrivate::setVisible(visible);
}
/*!
\internal
set the directory to url
*/
-void QFileDialogPrivate::_q_goToUrl(const QUrl &url)
+void QFileDialogPrivate::goToUrl(const QUrl &url)
{
//The shortcut in the side bar may have a parent that is not fetched yet (e.g. an hidden file)
//so we force the fetching
QFileSystemModelPrivate::QFileSystemNode *node = model->d_func()->node(url.toLocalFile(), true);
QModelIndex idx = model->d_func()->index(node);
- _q_enterDirectory(idx);
+ enterDirectory(idx);
}
/*!
@@ -897,7 +919,7 @@ void QFileDialogPrivate::_q_goToUrl(const QUrl &url)
\note On iOS, if you set \a directory to \l{QStandardPaths::standardLocations()}
{QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).last()},
- a native image picker dialog will be used for accessing the user's photo album.
+ a native image picker dialog is used for accessing the user's photo album.
The filename returned can be loaded using QFile and related APIs.
For this to be enabled, the Info.plist assigned to QMAKE_INFO_PLIST in the
project file must contain the key \c NSPhotoLibraryUsageDescription. See
@@ -1104,43 +1126,58 @@ void QFileDialog::selectUrl(const QUrl &url)
}
#ifdef Q_OS_UNIX
+static QString homeDirFromPasswdEntry(const QString &path, const QByteArray &userName)
+{
+#if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD) && !defined(Q_OS_WASM)
+ passwd pw;
+ passwd *tmpPw;
+ long bufSize = ::sysconf(_SC_GETPW_R_SIZE_MAX);
+ if (bufSize == -1)
+ bufSize = 1024;
+ QVarLengthArray<char, 1024> buf(bufSize);
+ int err = 0;
+# if defined(Q_OS_SOLARIS) && (_POSIX_C_SOURCE - 0 < 199506L)
+ tmpPw = getpwnam_r(userName.constData(), &pw, buf.data(), buf.size());
+# else
+ err = getpwnam_r(userName.constData(), &pw, buf.data(), buf.size(), &tmpPw);
+# endif
+ if (err || !tmpPw)
+ return path;
+ return QFile::decodeName(pw.pw_dir);
+#else
+ passwd *pw = getpwnam(userName.constData());
+ if (!pw)
+ return path;
+ return QFile::decodeName(pw->pw_dir);
+#endif // defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD) && !defined(Q_OS_WASM)
+}
+
Q_AUTOTEST_EXPORT QString qt_tildeExpansion(const QString &path)
{
if (!path.startsWith(u'~'))
return path;
- int separatorPosition = path.indexOf(QDir::separator());
- if (separatorPosition < 0)
- separatorPosition = path.size();
- if (separatorPosition == 1) {
- return QDir::homePath() + QStringView{path}.mid(1);
- } else {
+
+ if (path.size() == 1) // '~'
+ return QDir::homePath();
+
+ QStringView sv(path);
+ const qsizetype sepIndex = sv.indexOf(QDir::separator());
+ if (sepIndex == 1) // '~/' or '~/a/b/c'
+ return QDir::homePath() + sv.sliced(1);
+
#if defined(Q_OS_VXWORKS) || defined(Q_OS_INTEGRITY)
- const QString homePath = QDir::homePath();
+ if (sepIndex == -1)
+ return QDir::homePath();
+ return QDir::homePath() + sv.sliced(sepIndex);
#else
- const QByteArray userName = QStringView{path}.mid(1, separatorPosition - 1).toLocal8Bit();
-# if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD) && !defined(Q_OS_WASM)
- passwd pw;
- passwd *tmpPw;
- char buf[200];
- const int bufSize = sizeof(buf);
- int err = 0;
-# if defined(Q_OS_SOLARIS) && (_POSIX_C_SOURCE - 0 < 199506L)
- tmpPw = getpwnam_r(userName.constData(), &pw, buf, bufSize);
-# else
- err = getpwnam_r(userName.constData(), &pw, buf, bufSize, &tmpPw);
-# endif
- if (err || !tmpPw)
- return path;
- const QString homePath = QString::fromLocal8Bit(pw.pw_dir);
-# else
- passwd *pw = getpwnam(userName.constData());
- if (!pw)
- return path;
- const QString homePath = QString::fromLocal8Bit(pw->pw_dir);
-# endif
-#endif
- return homePath + QStringView{path}.mid(separatorPosition);
- }
+ const qsizetype userNameLen = sepIndex != -1 ? sepIndex - strlen("~") // '~user/a/b'
+ : path.size() - strlen("~"); // '~user'
+ const QByteArray userName = sv.sliced(1, userNameLen).toLocal8Bit();
+ QString homePath = homeDirFromPasswdEntry(path, userName);
+ if (sepIndex == -1)
+ return homePath;
+ return homePath + sv.sliced(sepIndex);
+#endif // defined(Q_OS_VXWORKS) || defined(Q_OS_INTEGRITY)
}
#endif
@@ -1240,12 +1277,10 @@ QStringList QFileDialogPrivate::addDefaultSuffixToFiles(const QStringList &files
QList<QUrl> QFileDialogPrivate::addDefaultSuffixToUrls(const QList<QUrl> &urlsToFix) const
{
QList<QUrl> urls;
- const int numUrlsToFix = urlsToFix.size();
- urls.reserve(numUrlsToFix);
- for (int i = 0; i < numUrlsToFix; ++i) {
- QUrl url = urlsToFix.at(i);
- // if the filename has no suffix, add the default suffix
- const QString defaultSuffix = options->defaultSuffix();
+ urls.reserve(urlsToFix.size());
+ // if the filename has no suffix, add the default suffix
+ const QString defaultSuffix = options->defaultSuffix();
+ for (QUrl url : urlsToFix) {
if (!defaultSuffix.isEmpty()) {
const QString urlPath = url.path();
const auto idx = urlPath.lastIndexOf(u'/');
@@ -1353,11 +1388,10 @@ QStringList qt_strip_filters(const QStringList &filters)
#if QT_CONFIG(regularexpression)
QStringList strippedFilters;
static const QRegularExpression r(QString::fromLatin1(QPlatformFileDialogHelper::filterRegExp));
- const int numFilters = filters.size();
- strippedFilters.reserve(numFilters);
- for (int i = 0; i < numFilters; ++i) {
+ strippedFilters.reserve(filters.size());
+ for (const QString &filter : filters) {
QString filterName;
- auto match = r.match(filters[i]);
+ auto match = r.match(filter);
if (match.hasMatch())
filterName = match.captured(1);
strippedFilters.append(filterName.simplified());
@@ -1378,25 +1412,24 @@ QStringList qt_strip_filters(const QStringList &filters)
assumption that the file extension determines the file type is not
consistent on every operating system. It is possible to have a file with no
dot in its name (for example, \c Makefile). In a native Windows file
- dialog, \b{*.*} will match such files, while in other types of file dialogs
- it may not. So it is better to use \b{*} if you mean to select any file.
+ dialog, \b{*.*} matches such files, while in other types of file dialogs
+ it might not match. So, it's better to use \b{*} if you mean to select any file.
\snippet code/src_gui_dialogs_qfiledialog.cpp 7
\l setMimeTypeFilters() has the advantage of providing all possible name
filters for each file type. For example, JPEG images have three possible
extensions; if your application can open such files, selecting the
- \c image/jpeg mime type as a filter will allow you to open all of them.
+ \c image/jpeg mime type as a filter allows you to open all of them.
*/
void QFileDialog::setNameFilters(const QStringList &filters)
{
Q_D(QFileDialog);
QStringList cleanedFilters;
- const int numFilters = filters.size();
- cleanedFilters.reserve(numFilters);
- for (int i = 0; i < numFilters; ++i) {
- cleanedFilters << filters[i].simplified();
- }
+ cleanedFilters.reserve(filters.size());
+ for (const QString &filter : filters)
+ cleanedFilters << filter.simplified();
+
d->options->setNameFilters(cleanedFilters);
if (!d->usingWidgets())
@@ -1411,7 +1444,7 @@ void QFileDialog::setNameFilters(const QStringList &filters)
else
d->qFileDialogUi->fileTypeCombo->addItems(cleanedFilters);
- d->_q_useNameFilter(0);
+ d->useNameFilter(0);
}
/*!
@@ -1451,7 +1484,7 @@ void QFileDialog::selectNameFilter(const QString &filter)
}
if (i >= 0) {
d->qFileDialogUi->fileTypeCombo->setCurrentIndex(i);
- d->_q_useNameFilter(d->qFileDialogUi->fileTypeCombo->currentIndex());
+ d->useNameFilter(d->qFileDialogUi->fileTypeCombo->currentIndex());
}
}
@@ -1609,7 +1642,7 @@ QString QFileDialog::selectedMimeTypeFilter() const
for (const auto &mimeType: mimeTypes) {
QString filter = nameFilterForMime(mimeType);
if (testOption(HideNameFilterDetails))
- filter = qt_strip_filters({ filter }).first();
+ filter = qt_strip_filters({ filter }).constFirst();
if (filter == nameFilter) {
mimeTypeFilter = mimeType;
break;
@@ -1623,7 +1656,7 @@ QString QFileDialog::selectedMimeTypeFilter() const
/*!
\property QFileDialog::viewMode
- \brief the way files and directories are displayed in the dialog
+ \brief The way files and directories are displayed in the dialog.
By default, the \c Detail mode is used to display information about
files and directories.
@@ -1637,9 +1670,9 @@ void QFileDialog::setViewMode(QFileDialog::ViewMode mode)
if (!d->usingWidgets())
return;
if (mode == Detail)
- d->_q_showDetailsView();
+ d->showDetailsView();
else
- d->_q_showListView();
+ d->showListView();
}
QFileDialog::ViewMode QFileDialog::viewMode() const
@@ -1652,14 +1685,14 @@ QFileDialog::ViewMode QFileDialog::viewMode() const
/*!
\property QFileDialog::fileMode
- \brief the file mode of the dialog
+ \brief The file mode of the dialog.
The file mode defines the number and type of items that the user is
expected to select in the dialog.
By default, this property is set to AnyFile.
- This function will set the labels for the FileName and
+ This function sets the labels for the FileName and
\l{QFileDialog::}{Accept} \l{DialogLabel}s. It is possible to set
custom text after the call to setFileMode().
@@ -1693,7 +1726,7 @@ void QFileDialog::setFileMode(QFileDialog::FileMode mode)
d->updateFileNameLabel();
d->updateOkButtonText();
d->qFileDialogUi->fileTypeCombo->setEnabled(!testOption(ShowDirsOnly));
- d->_q_updateOkButton();
+ d->updateOkButton();
}
QFileDialog::FileMode QFileDialog::fileMode() const
@@ -1704,7 +1737,7 @@ QFileDialog::FileMode QFileDialog::fileMode() const
/*!
\property QFileDialog::acceptMode
- \brief the accept mode of the dialog
+ \brief The accept mode of the dialog.
The action mode defines whether the dialog is for opening or saving files.
@@ -1723,7 +1756,7 @@ void QFileDialog::setAcceptMode(QFileDialog::AcceptMode mode)
QDialogButtonBox::StandardButton button = (mode == AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save);
d->qFileDialogUi->buttonBox->setStandardButtons(button | QDialogButtonBox::Cancel);
d->qFileDialogUi->buttonBox->button(button)->setEnabled(false);
- d->_q_updateOkButton();
+ d->updateOkButton();
if (mode == AcceptSave) {
d->qFileDialogUi->lookInCombo->setEditable(false);
}
@@ -1732,14 +1765,14 @@ void QFileDialog::setAcceptMode(QFileDialog::AcceptMode mode)
/*!
\property QFileDialog::supportedSchemes
- \brief the URL schemes that the file dialog should allow navigating to.
+ \brief The URL schemes that the file dialog should allow navigating to.
\since 5.6
Setting this property allows to restrict the type of URLs the
- user will be able to select. It is a way for the application to declare
- the protocols it will support to fetch the file content. An empty list
+ user can select. It is a way for the application to declare
+ the protocols it supports to fetch the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled;
+ Support for local files ("file" scheme) is implicit and always enabled;
it is not necessary to include it in the restriction.
*/
@@ -1774,7 +1807,7 @@ QLineEdit *QFileDialogPrivate::lineEdit() const {
return (QLineEdit*)qFileDialogUi->fileNameEdit;
}
-int QFileDialogPrivate::maxNameLength(const QString &path)
+long QFileDialogPrivate::maxNameLength(const QString &path)
{
#if defined(Q_OS_UNIX)
return ::pathconf(QFile::encodeName(path).data(), _PC_NAME_MAX);
@@ -1821,10 +1854,10 @@ QFileDialog::AcceptMode QFileDialog::acceptMode() const
/*!
\property QFileDialog::defaultSuffix
- \brief suffix added to the filename if no other suffix was specified
+ \brief Suffix added to the filename if no other suffix was specified.
- This property specifies a string that will be added to the
- filename if it has no suffix already. The suffix is typically
+ This property specifies a string that is added to the
+ filename if it has no suffix yet. The suffix is typically
used to indicate the file type (e.g. "txt" indicates a text
file).
@@ -2027,41 +2060,41 @@ QString QFileDialog::labelText(DialogLabel label) const
\snippet code/src_gui_dialogs_qfiledialog.cpp 8
The function creates a modal file dialog with the given \a parent widget.
- If \a parent is not \nullptr, the dialog will be shown centered over the
+ If \a parent is not \nullptr, the dialog is shown centered over the
parent widget.
- The file dialog's working directory will be set to \a dir. If \a dir
- includes a file name, the file will be selected. Only files that match the
- given \a filter are shown. The filter selected is set to \a selectedFilter.
+ The file dialog's working directory is set to \a dir. If \a dir
+ includes a file name, the file is selected. Only files that match the
+ given \a filter are shown. The selected filter is set to \a selectedFilter.
The parameters \a dir, \a selectedFilter, and \a filter may be empty
strings. If you want multiple filters, separate them with ';;', for
example:
\snippet code/src_gui_dialogs_qfiledialog.cpp 14
- The \a options argument holds various options about how to run the dialog,
- see the QFileDialog::Option enum for more information on the flags you can
+ The \a options argument holds various options about how to run the dialog.
+ See the QFileDialog::Option enum for more information on the flags you can
pass.
- The dialog's caption is set to \a caption. If \a caption is not specified
+ The dialog's caption is set to \a caption. If \a caption is not specified,
then a default caption will be used.
- On Windows, and \macos, this static function will use the
+ On Windows, and \macos, this static function uses the
native file dialog and not a QFileDialog. Note that the \macos native file
dialog does not show a title bar.
- On Windows the dialog will spin a blocking modal event loop that will not
- dispatch any QTimers, and if \a parent is not \nullptr then it will position
+ On Windows the dialog spins a blocking modal event loop that does not
+ dispatch any QTimers, and if \a parent is not \nullptr then it positions
the dialog just below the parent's title bar.
On Unix/X11, the normal behavior of the file dialog is to resolve and
follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
- the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
- \a options includes DontResolveSymlinks, the file dialog will treat
+ the file dialog changes to \c{/var/tmp} after entering \c{/usr/tmp}. If
+ \a options includes DontResolveSymlinks, the file dialog treats
symlinks as regular directories.
\warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
+ want to do this, you must create the dialog yourself using one of the
QFileDialog constructors.
\sa getOpenFileNames(), getSaveFileName(), getExistingDirectory()
@@ -2089,21 +2122,21 @@ QString QFileDialog::getOpenFileName(QWidget *parent,
The function is used similarly to QFileDialog::getOpenFileName(). In
particular \a parent, \a caption, \a dir, \a filter, \a selectedFilter
- and \a options are used in the exact same way.
+ and \a options are used in exactly the same way.
The main difference with QFileDialog::getOpenFileName() comes from
the ability offered to the user to select a remote file. That's why
the return type and the type of \a dir is QUrl.
The \a supportedSchemes argument allows to restrict the type of URLs the
- user will be able to select. It is a way for the application to declare
+ user is able to select. It is a way for the application to declare
the protocols it will support to fetch the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled;
+ Support for local files ("file" scheme) is implicit and always enabled;
it is not necessary to include it in the restriction.
- When possible, this static function will use the native file dialog and
- not a QFileDialog. On platforms which don't support selecting remote
+ When possible, this static function uses the native file dialog and
+ not a QFileDialog. On platforms that don't support selecting remote
files, Qt will allow to select only local files.
\sa getOpenFileName(), getOpenFileUrls(), getSaveFileUrl(), getExistingDirectoryUrl()
@@ -2137,33 +2170,33 @@ QUrl QFileDialog::getOpenFileUrl(QWidget *parent,
}
/*!
- This is a convenience static function that will return one or more existing
+ This is a convenience static function that returns one or more existing
files selected by the user.
\snippet code/src_gui_dialogs_qfiledialog.cpp 9
This function creates a modal file dialog with the given \a parent widget.
- If \a parent is not \nullptr, the dialog will be shown centered over the
+ If \a parent is not \nullptr, the dialog is shown centered over the
parent widget.
- The file dialog's working directory will be set to \a dir. If \a dir
- includes a file name, the file will be selected. The filter is set to
+ The file dialog's working directory is set to \a dir. If \a dir
+ includes a file name, the file is selected. The filter is set to
\a filter so that only those files which match the filter are shown. The
filter selected is set to \a selectedFilter. The parameters \a dir,
- \a selectedFilter and \a filter may be empty strings. If you need multiple
+ \a selectedFilter and \a filter can be empty strings. If you need multiple
filters, separate them with ';;', for instance:
\snippet code/src_gui_dialogs_qfiledialog.cpp 14
- The dialog's caption is set to \a caption. If \a caption is not specified
- then a default caption will be used.
+ The dialog's caption is set to \a caption. If \a caption is not specified,
+ then a default caption is used.
- On Windows, and \macos, this static function will use the
+ On Windows and \macos, this static function uses the
native file dialog and not a QFileDialog. Note that the \macos native file
dialog does not show a title bar.
- On Windows the dialog will spin a blocking modal event loop that will not
- dispatch any QTimers, and if \a parent is not \nullptr then it will position
+ On Windows the dialog spins a blocking modal event loop that does not
+ dispatch any QTimers, and if \a parent is not \nullptr then it positions
the dialog just below the parent's title bar.
On Unix/X11, the normal behavior of the file dialog is to resolve and
@@ -2174,7 +2207,7 @@ QUrl QFileDialog::getOpenFileUrl(QWidget *parent,
pass.
\warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
+ want to do this, you must create the dialog yourself using one of the
QFileDialog constructors.
\sa getOpenFileName(), getSaveFileName(), getExistingDirectory()
@@ -2197,13 +2230,13 @@ QStringList QFileDialog::getOpenFileNames(QWidget *parent,
}
/*!
- This is a convenience static function that will return one or more existing
+ This is a convenience static function that returns one or more existing
files selected by the user. If the user presses Cancel, it returns an
empty list.
The function is used similarly to QFileDialog::getOpenFileNames(). In
particular \a parent, \a caption, \a dir, \a filter, \a selectedFilter
- and \a options are used in the exact same way.
+ and \a options are used in exactly the same way.
The main difference with QFileDialog::getOpenFileNames() comes from
the ability offered to the user to select remote files. That's why
@@ -2211,14 +2244,14 @@ QStringList QFileDialog::getOpenFileNames(QWidget *parent,
and QUrl.
The \a supportedSchemes argument allows to restrict the type of URLs the
- user will be able to select. It is a way for the application to declare
- the protocols it will support to fetch the file content. An empty list
+ user can select. It is a way for the application to declare
+ the protocols it supports to fetch the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled;
+ Support for local files ("file" scheme) is implicit and always enabled;
it is not necessary to include it in the restriction.
- When possible, this static function will use the native file dialog and
- not a QFileDialog. On platforms which don't support selecting remote
+ When possible, this static function uses the native file dialog and
+ not a QFileDialog. On platforms that don't support selecting remote
files, Qt will allow to select only local files.
\sa getOpenFileNames(), getOpenFileUrl(), getSaveFileUrl(), getExistingDirectoryUrl()
@@ -2252,15 +2285,16 @@ QList<QUrl> QFileDialog::getOpenFileUrls(QWidget *parent,
}
/*!
- This is a convenience static function that will return the content of a file
+ This is a convenience static function that returns the content of a file
selected by the user.
- This function is used to access local files on Qt for WebAssembly, where the web
- sandbox places restrictions on how such access may happen. Its implementation will
- make the browser display a native file dialog, where the user makes the file selection
- based on the parameter \a nameFilter.
+ Use this function to access local files on Qt for WebAssembly, if the web sandbox
+ restricts file access. Its implementation enables displaying a native file dialog in
+ the browser, where the user selects a file based on the \a nameFilter parameter.
- It can also be used on other platforms, where it will fall back to using QFileDialog.
+ \a parent is ignored on Qt for WebAssembly. Pass \a parent on other platforms, to make
+ the popup a child of another widget. If the platform doesn't support native file
+ dialogs, the function falls back to QFileDialog.
The function is asynchronous and returns immediately. The \a fileOpenCompleted
callback will be called when a file has been selected and its contents have been
@@ -2269,9 +2303,10 @@ QList<QUrl> QFileDialog::getOpenFileUrls(QWidget *parent,
\snippet code/src_gui_dialogs_qfiledialog.cpp 15
\since 5.13
*/
-void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::function<void(const QString &, const QByteArray &)> &fileOpenCompleted)
+void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::function<void(const QString &, const QByteArray &)> &fileOpenCompleted, QWidget *parent)
{
#ifdef Q_OS_WASM
+ Q_UNUSED(parent);
auto openFileImpl = std::make_shared<std::function<void(void)>>();
QString fileName;
QByteArray fileContent;
@@ -2296,14 +2331,15 @@ void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::funct
openFileImpl.reset();
};
- QWasmLocalFileAccess::openFile(qt_make_filter_list(nameFilter), fileDialogClosed, acceptFile, fileContentReady);
+ QWasmLocalFileAccess::openFile(nameFilter.toStdString(), fileDialogClosed, acceptFile, fileContentReady);
};
(*openFileImpl)();
#else
- QFileDialog *dialog = new QFileDialog();
+ QFileDialog *dialog = new QFileDialog(parent);
dialog->setFileMode(QFileDialog::ExistingFile);
dialog->setNameFilter(nameFilter);
+ dialog->setAttribute(Qt::WA_DeleteOnClose);
auto fileSelected = [=](const QString &fileName) {
QByteArray fileContent;
@@ -2315,13 +2351,7 @@ void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::funct
fileOpenCompleted(fileName, fileContent);
};
- auto dialogClosed = [=](int code) {
- Q_UNUSED(code);
- dialog->deleteLater();
- };
-
- connect(dialog, &QFileDialog::fileSelected, fileSelected);
- connect(dialog, &QFileDialog::finished, dialogClosed);
+ connect(dialog, &QFileDialog::fileSelected, dialog, fileSelected);
dialog->show();
#endif
}
@@ -2331,23 +2361,26 @@ void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::funct
a file name and location chosen by the user. \a fileNameHint can be provided to
suggest a file name to the user.
- This function is used to save files to the local file system on Qt for WebAssembly, where
- the web sandbox places restrictions on how such access may happen. Its implementation will
- make the browser display a native file dialog, where the user makes the file selection.
+ Use this function to save content to local files on Qt for WebAssembly, if the web sandbox
+ restricts file access. Its implementation enables displaying a native file dialog in the
+ browser, where the user specifies an output file based on the \a fileNameHint argument.
- It can also be used on other platforms, where it will fall back to using QFileDialog.
+ \a parent is ignored on Qt for WebAssembly. Pass \a parent on other platforms, to make
+ the popup a child of another widget. If the platform doesn't support native file
+ dialogs, the function falls back to QFileDialog.
The function is asynchronous and returns immediately.
\snippet code/src_gui_dialogs_qfiledialog.cpp 16
\since 5.14
*/
-void QFileDialog::saveFileContent(const QByteArray &fileContent, const QString &fileNameHint)
+void QFileDialog::saveFileContent(const QByteArray &fileContent, const QString &fileNameHint, QWidget *parent)
{
#ifdef Q_OS_WASM
+ Q_UNUSED(parent);
QWasmLocalFileAccess::saveFile(fileContent, fileNameHint.toStdString());
#else
- QFileDialog *dialog = new QFileDialog();
+ QFileDialog *dialog = new QFileDialog(parent);
dialog->setAcceptMode(QFileDialog::AcceptSave);
dialog->setFileMode(QFileDialog::AnyFile);
dialog->selectFile(fileNameHint);
@@ -2360,19 +2393,14 @@ void QFileDialog::saveFileContent(const QByteArray &fileContent, const QString &
}
};
- auto dialogClosed = [=](int code) {
- Q_UNUSED(code);
- dialog->deleteLater();
- };
-
- connect(dialog, &QFileDialog::fileSelected, fileSelected);
- connect(dialog, &QFileDialog::finished, dialogClosed);
+ connect(dialog, &QFileDialog::fileSelected, dialog, fileSelected);
+ dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
#endif
}
/*!
- This is a convenience static function that will return a file name selected
+ This is a convenience static function that returns a file name selected
by the user. The file does not have to exist.
It creates a modal file dialog with the given \a parent widget. If
@@ -2381,8 +2409,8 @@ void QFileDialog::saveFileContent(const QByteArray &fileContent, const QString &
\snippet code/src_gui_dialogs_qfiledialog.cpp 11
- The file dialog's working directory will be set to \a dir. If \a dir
- includes a file name, the file will be selected. Only files that match the
+ The file dialog's working directory is set to \a dir. If \a dir
+ includes a file name, the file is selected. Only files that match the
\a filter are shown. The filter selected is set to \a selectedFilter. The
parameters \a dir, \a selectedFilter, and \a filter may be empty strings.
Multiple filters are separated with ';;'. For instance:
@@ -2397,24 +2425,24 @@ void QFileDialog::saveFileContent(const QByteArray &fileContent, const QString &
desired value.
The dialog's caption is set to \a caption. If \a caption is not specified,
- a default caption will be used.
+ a default caption is used.
- On Windows, and \macos, this static function will use the
+ On Windows, and \macos, this static function uses the
native file dialog and not a QFileDialog.
- On Windows the dialog will spin a blocking modal event loop that will not
- dispatch any QTimers, and if \a parent is not \nullptr then it will
- position the dialog just below the parent's title bar. On \macos, with its
+ On Windows the dialog spins a blocking modal event loop that does not
+ dispatch any QTimers, and if \a parent is not \nullptr then it
+ positions the dialog just below the parent's title bar. On \macos, with its
native file dialog, the filter argument is ignored.
On Unix/X11, the normal behavior of the file dialog is to resolve and
follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
- the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
- \a options includes DontResolveSymlinks the file dialog will treat symlinks
+ the file dialog changes to \c{/var/tmp} after entering \c{/usr/tmp}. If
+ \a options includes DontResolveSymlinks, the file dialog treats symlinks
as regular directories.
\warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
+ want to do this, you must create the dialog yourself using one of the
QFileDialog constructors.
\sa getOpenFileName(), getOpenFileNames(), getExistingDirectory()
@@ -2442,21 +2470,21 @@ QString QFileDialog::getSaveFileName(QWidget *parent,
The function is used similarly to QFileDialog::getSaveFileName(). In
particular \a parent, \a caption, \a dir, \a filter, \a selectedFilter
- and \a options are used in the exact same way.
+ and \a options are used in exactly the same way.
The main difference with QFileDialog::getSaveFileName() comes from
the ability offered to the user to select a remote file. That's why
the return type and the type of \a dir is QUrl.
The \a supportedSchemes argument allows to restrict the type of URLs the
- user will be able to select. It is a way for the application to declare
- the protocols it will support to save the file content. An empty list
+ user can select. It is a way for the application to declare
+ the protocols it supports to save the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled;
+ Support for local files ("file" scheme) is implicit and always enabled;
it is not necessary to include it in the restriction.
- When possible, this static function will use the native file dialog and
- not a QFileDialog. On platforms which don't support selecting remote
+ When possible, this static function uses the native file dialog and
+ not a QFileDialog. On platforms that don't support selecting remote
files, Qt will allow to select only local files.
\sa getSaveFileName(), getOpenFileUrl(), getOpenFileUrls(), getExistingDirectoryUrl()
@@ -2491,44 +2519,45 @@ QUrl QFileDialog::getSaveFileUrl(QWidget *parent,
}
/*!
- This is a convenience static function that will return an existing
+ This is a convenience static function that returns an existing
directory selected by the user.
\snippet code/src_gui_dialogs_qfiledialog.cpp 12
This function creates a modal file dialog with the given \a parent widget.
- If \a parent is not \nullptr, the dialog will be shown centered over the
+ If \a parent is not \nullptr, the dialog is shown centered over the
parent widget.
The dialog's working directory is set to \a dir, and the caption is set to
- \a caption. Either of these may be an empty string in which case the
- current directory and a default caption will be used respectively.
+ \a caption. Either of these can be an empty string in which case the
+ current directory and a default caption are used respectively.
- The \a options argument holds various options about how to run the dialog,
- see the QFileDialog::Option enum for more information on the flags you can
+ The \a options argument holds various options about how to run the dialog.
+ See the QFileDialog::Option enum for more information on the flags you can
pass. To ensure a native file dialog, \l{QFileDialog::}{ShowDirsOnly} must
be set.
- On Windows and \macos, this static function will use the
+ On Windows and \macos, this static function uses the
native file dialog and not a QFileDialog. However, the native Windows file
dialog does not support displaying files in the directory chooser. You need
- to pass \l{QFileDialog::}{DontUseNativeDialog} to display files using a
+ to pass the \l{QFileDialog::}{DontUseNativeDialog} option, or set the global
+ \\l{Qt::}{AA_DontUseNativeDialogs} application attribute to display files using a
QFileDialog.
Note that the \macos native file dialog does not show a title bar.
On Unix/X11, the normal behavior of the file dialog is to resolve and
follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
- the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
- \a options includes DontResolveSymlinks, the file dialog will treat
+ the file dialog changes to \c{/var/tmp} after entering \c{/usr/tmp}. If
+ \a options includes DontResolveSymlinks, the file dialog treats
symlinks as regular directories.
- On Windows, the dialog will spin a blocking modal event loop that will not
- dispatch any QTimers, and if \a parent is not \nullptr then it will position
+ On Windows, the dialog spins a blocking modal event loop that does not
+ dispatch any QTimers, and if \a parent is not \nullptr then it positions
the dialog just below the parent's title bar.
\warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
+ want to do this, you must create the dialog yourself using one of the
QFileDialog constructors.
\sa getOpenFileName(), getOpenFileNames(), getSaveFileName()
@@ -2548,28 +2577,28 @@ QString QFileDialog::getExistingDirectory(QWidget *parent,
}
/*!
- This is a convenience static function that will return an existing
+ This is a convenience static function that returns an existing
directory selected by the user. If the user presses Cancel, it
returns an empty url.
The function is used similarly to QFileDialog::getExistingDirectory().
In particular \a parent, \a caption, \a dir and \a options are used
- in the exact same way.
+ in exactly the same way.
The main difference with QFileDialog::getExistingDirectory() comes from
the ability offered to the user to select a remote directory. That's why
the return type and the type of \a dir is QUrl.
The \a supportedSchemes argument allows to restrict the type of URLs the
- user will be able to select. It is a way for the application to declare
- the protocols it will support to fetch the file content. An empty list
+ user is able to select. It is a way for the application to declare
+ the protocols it supports to fetch the file content. An empty list
means that no restriction is applied (the default).
- Supported for local files ("file" scheme) is implicit and always enabled;
+ Support for local files ("file" scheme) is implicit and always enabled;
it is not necessary to include it in the restriction.
- When possible, this static function will use the native file dialog and
- not a QFileDialog. On platforms which don't support selecting remote
- files, Qt will allow to select only local files.
+ When possible, this static function uses the native file dialog and
+ not a QFileDialog. On platforms that don't support selecting remote
+ files, Qt allows to select only local files.
\sa getExistingDirectory(), getOpenFileUrl(), getOpenFileUrls(), getSaveFileUrl()
\since 5.2
@@ -2697,9 +2726,9 @@ void QFileDialog::accept()
const QList<QUrl> urls = selectedUrls();
if (urls.isEmpty())
return;
- d->_q_emitUrlsSelected(urls);
+ d->emitUrlsSelected(urls);
if (urls.size() == 1)
- d->_q_emitUrlSelected(urls.first());
+ d->emitUrlSelected(urls.first());
QDialog::accept();
return;
}
@@ -2711,7 +2740,7 @@ void QFileDialog::accept()
// "hidden feature" type .. and then enter, and it will move up a dir
// special case for ".."
if (lineEditText == ".."_L1) {
- d->_q_navigateToParent();
+ d->navigateToParent();
const QSignalBlocker blocker(d->qFileDialogUi->fileNameEdit);
d->lineEdit()->selectAll();
return;
@@ -2744,7 +2773,7 @@ void QFileDialog::accept()
}
if (!info.exists()) {
- int maxNameLength = d->maxNameLength(info.path());
+ const long maxNameLength = d->maxNameLength(info.path());
if (maxNameLength >= 0 && info.fileName().size() > maxNameLength)
return;
}
@@ -2880,7 +2909,7 @@ bool QFileDialogPrivate::restoreWidgetState(QStringList &history, int splitterPo
if (proxyModel)
abstractModel = proxyModel;
#endif
- int total = qMin(abstractModel->columnCount(QModelIndex()), actions.size() + 1);
+ const int total = qMin(abstractModel->columnCount(QModelIndex()), int(actions.size() + 1));
for (int i = 1; i < total; ++i)
actions.at(i - 1)->setChecked(!headerView->isSectionHidden(i));
@@ -2965,11 +2994,12 @@ void QFileDialogPrivate::createWidgets()
else
model->setNameFilterDisables(false);
model->d_func()->disableRecursiveSort = true;
- QFileDialog::connect(model, SIGNAL(fileRenamed(QString,QString,QString)), q, SLOT(_q_fileRenamed(QString,QString,QString)));
- QFileDialog::connect(model, SIGNAL(rootPathChanged(QString)),
- q, SLOT(_q_pathChanged(QString)));
- QFileDialog::connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- q, SLOT(_q_rowsInserted(QModelIndex)));
+ QObjectPrivate::connect(model, &QFileSystemModel::fileRenamed,
+ this, &QFileDialogPrivate::fileRenamed);
+ QObjectPrivate::connect(model, &QFileSystemModel::rootPathChanged,
+ this, &QFileDialogPrivate::pathChanged);
+ QObjectPrivate::connect(model, &QFileSystemModel::rowsInserted,
+ this, &QFileDialogPrivate::rowsInserted);
model->setReadOnly(false);
qFileDialogUi.reset(new Ui_QFileDialog());
@@ -2979,14 +3009,17 @@ void QFileDialogPrivate::createWidgets()
initialBookmarks << QUrl("file:"_L1)
<< QUrl::fromLocalFile(QDir::homePath());
qFileDialogUi->sidebar->setModelAndUrls(model, initialBookmarks);
- QFileDialog::connect(qFileDialogUi->sidebar, SIGNAL(goToUrl(QUrl)),
- q, SLOT(_q_goToUrl(QUrl)));
+ QObjectPrivate::connect(qFileDialogUi->sidebar, &QSidebar::goToUrl,
+ this, &QFileDialogPrivate::goToUrl);
- QObject::connect(qFileDialogUi->buttonBox, SIGNAL(accepted()), q, SLOT(accept()));
- QObject::connect(qFileDialogUi->buttonBox, SIGNAL(rejected()), q, SLOT(reject()));
+ QObject::connect(qFileDialogUi->buttonBox, &QDialogButtonBox::accepted,
+ q, &QFileDialog::accept);
+ QObject::connect(qFileDialogUi->buttonBox, &QDialogButtonBox::rejected,
+ q, &QFileDialog::reject);
qFileDialogUi->lookInCombo->setFileDialogPrivate(this);
- QObject::connect(qFileDialogUi->lookInCombo, SIGNAL(textActivated(QString)), q, SLOT(_q_goToDirectory(QString)));
+ QObjectPrivate::connect(qFileDialogUi->lookInCombo, &QComboBox::textActivated,
+ this, &QFileDialogPrivate::goToDirectory);
qFileDialogUi->lookInCombo->setInsertPolicy(QComboBox::NoInsert);
qFileDialogUi->lookInCombo->setDuplicatesEnabled(false);
@@ -3003,31 +3036,32 @@ void QFileDialogPrivate::createWidgets()
qFileDialogUi->fileNameEdit->setInputMethodHints(Qt::ImhNoPredictiveText);
- QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(textChanged(QString)),
- q, SLOT(_q_autoCompleteFileName(QString)));
- QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(textChanged(QString)),
- q, SLOT(_q_updateOkButton()));
-
- QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(returnPressed()), q, SLOT(accept()));
+ QObjectPrivate::connect(qFileDialogUi->fileNameEdit, &QLineEdit::textChanged,
+ this, &QFileDialogPrivate::autoCompleteFileName);
+ QObjectPrivate::connect(qFileDialogUi->fileNameEdit, &QLineEdit::textChanged,
+ this, &QFileDialogPrivate::updateOkButton);
+ QObject::connect(qFileDialogUi->fileNameEdit, &QLineEdit::returnPressed,
+ q, &QFileDialog::accept);
// filetype
qFileDialogUi->fileTypeCombo->setDuplicatesEnabled(false);
qFileDialogUi->fileTypeCombo->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow);
qFileDialogUi->fileTypeCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
- QObject::connect(qFileDialogUi->fileTypeCombo, SIGNAL(activated(int)),
- q, SLOT(_q_useNameFilter(int)));
- QObject::connect(qFileDialogUi->fileTypeCombo, SIGNAL(textActivated(QString)),
- q, SIGNAL(filterSelected(QString)));
+ QObjectPrivate::connect(qFileDialogUi->fileTypeCombo, &QComboBox::activated,
+ this, &QFileDialogPrivate::useNameFilter);
+ QObject::connect(qFileDialogUi->fileTypeCombo, &QComboBox::textActivated,
+ q, &QFileDialog::filterSelected);
qFileDialogUi->listView->setFileDialogPrivate(this);
qFileDialogUi->listView->setModel(model);
- QObject::connect(qFileDialogUi->listView, SIGNAL(activated(QModelIndex)),
- q, SLOT(_q_enterDirectory(QModelIndex)));
- QObject::connect(qFileDialogUi->listView, SIGNAL(customContextMenuRequested(QPoint)),
- q, SLOT(_q_showContextMenu(QPoint)));
+ QObjectPrivate::connect(qFileDialogUi->listView, &QAbstractItemView::activated,
+ this, &QFileDialogPrivate::enterDirectory);
+ QObjectPrivate::connect(qFileDialogUi->listView, &QAbstractItemView::customContextMenuRequested,
+ this, &QFileDialogPrivate::showContextMenu);
#ifndef QT_NO_SHORTCUT
QShortcut *shortcut = new QShortcut(QKeySequence::Delete, qFileDialogUi->listView);
- QObject::connect(shortcut, SIGNAL(activated()), q, SLOT(_q_deleteCurrent()));
+ QObjectPrivate::connect(shortcut, &QShortcut::activated,
+ this, &QFileDialogPrivate::deleteCurrent);
#endif
qFileDialogUi->treeView->setFileDialogPrivate(this);
@@ -3042,8 +3076,8 @@ void QFileDialogPrivate::createWidgets()
QActionGroup *showActionGroup = new QActionGroup(q);
showActionGroup->setExclusive(false);
- QObject::connect(showActionGroup, SIGNAL(triggered(QAction*)),
- q, SLOT(_q_showHeader(QAction*)));;
+ QObjectPrivate::connect(showActionGroup, &QActionGroup::triggered,
+ this, &QFileDialogPrivate::showHeader);
QAbstractItemModel *abstractModel = model;
#if QT_CONFIG(proxymodel)
@@ -3060,21 +3094,22 @@ void QFileDialogPrivate::createWidgets()
QScopedPointer<QItemSelectionModel> selModel(qFileDialogUi->treeView->selectionModel());
qFileDialogUi->treeView->setSelectionModel(qFileDialogUi->listView->selectionModel());
- QObject::connect(qFileDialogUi->treeView, SIGNAL(activated(QModelIndex)),
- q, SLOT(_q_enterDirectory(QModelIndex)));
- QObject::connect(qFileDialogUi->treeView, SIGNAL(customContextMenuRequested(QPoint)),
- q, SLOT(_q_showContextMenu(QPoint)));
+ QObjectPrivate::connect(qFileDialogUi->treeView, &QAbstractItemView::activated,
+ this, &QFileDialogPrivate::enterDirectory);
+ QObjectPrivate::connect(qFileDialogUi->treeView, &QAbstractItemView::customContextMenuRequested,
+ this, &QFileDialogPrivate::showContextMenu);
#ifndef QT_NO_SHORTCUT
shortcut = new QShortcut(QKeySequence::Delete, qFileDialogUi->treeView);
- QObject::connect(shortcut, SIGNAL(activated()), q, SLOT(_q_deleteCurrent()));
+ QObjectPrivate::connect(shortcut, &QShortcut::activated,
+ this, &QFileDialogPrivate::deleteCurrent);
#endif
// Selections
QItemSelectionModel *selections = qFileDialogUi->listView->selectionModel();
- QObject::connect(selections, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- q, SLOT(_q_selectionChanged()));
- QObject::connect(selections, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_currentChanged(QModelIndex)));
+ QObjectPrivate::connect(selections, &QItemSelectionModel::selectionChanged,
+ this, &QFileDialogPrivate::selectionChanged);
+ QObjectPrivate::connect(selections, &QItemSelectionModel::currentChanged,
+ this, &QFileDialogPrivate::currentChanged);
qFileDialogUi->splitter->setStretchFactor(qFileDialogUi->splitter->indexOf(qFileDialogUi->splitter->widget(1)), QSizePolicy::Expanding);
createToolButtons();
@@ -3113,17 +3148,18 @@ void QFileDialogPrivate::createWidgets()
for (const QUrl &url : initiallySelectedFiles)
q->selectUrl(url);
lineEdit()->selectAll();
- _q_updateOkButton();
+ updateOkButton();
retranslateStrings();
q->resize(preSize.isValid() ? preSize : q->sizeHint());
q->setWindowState(preState);
}
-void QFileDialogPrivate::_q_showHeader(QAction *action)
+void QFileDialogPrivate::showHeader(QAction *action)
{
Q_Q(QFileDialog);
QActionGroup *actionGroup = qobject_cast<QActionGroup*>(q->sender());
- qFileDialogUi->treeView->header()->setSectionHidden(actionGroup->actions().indexOf(action) + 1, !action->isChecked());
+ qFileDialogUi->treeView->header()->setSectionHidden(int(actionGroup->actions().indexOf(action) + 1),
+ !action->isChecked());
}
#if QT_CONFIG(proxymodel)
@@ -3134,8 +3170,8 @@ void QFileDialogPrivate::_q_showHeader(QAction *action)
want to modify the underlying model; for example, to add columns, filter
data or add drives.
- Any existing proxy model will be removed, but not deleted. The file dialog
- will take ownership of the \a proxyModel.
+ Any existing proxy model is removed, but not deleted. The file dialog
+ takes ownership of the \a proxyModel.
\sa proxyModel()
*/
@@ -3149,13 +3185,12 @@ void QFileDialog::setProxyModel(QAbstractProxyModel *proxyModel)
return;
QModelIndex idx = d->rootIndex();
- if (d->proxyModel) {
- disconnect(d->proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex)));
- } else {
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex)));
- }
+ if (d->proxyModel)
+ QObjectPrivate::disconnect(d->proxyModel, &QAbstractProxyModel::rowsInserted,
+ d, &QFileDialogPrivate::rowsInserted);
+ else
+ QObjectPrivate::disconnect(d->model, &QAbstractItemModel::rowsInserted,
+ d, &QFileDialogPrivate::rowsInserted);
if (proxyModel != nullptr) {
proxyModel->setParent(this);
@@ -3167,8 +3202,8 @@ void QFileDialog::setProxyModel(QAbstractProxyModel *proxyModel)
d->completer->setModel(d->proxyModel);
d->completer->proxyModel = d->proxyModel;
#endif
- connect(d->proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex)));
+ QObjectPrivate::connect(d->proxyModel, &QAbstractItemModel::rowsInserted,
+ d, &QFileDialogPrivate::rowsInserted);
} else {
d->proxyModel = nullptr;
d->qFileDialogUi->listView->setModel(d->model);
@@ -3178,8 +3213,8 @@ void QFileDialog::setProxyModel(QAbstractProxyModel *proxyModel)
d->completer->sourceModel = d->model;
d->completer->proxyModel = nullptr;
#endif
- connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex)));
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::rowsInserted,
+ d, &QFileDialogPrivate::rowsInserted);
}
QScopedPointer<QItemSelectionModel> selModel(d->qFileDialogUi->treeView->selectionModel());
d->qFileDialogUi->treeView->setSelectionModel(d->qFileDialogUi->listView->selectionModel());
@@ -3188,10 +3223,10 @@ void QFileDialog::setProxyModel(QAbstractProxyModel *proxyModel)
// reconnect selection
QItemSelectionModel *selections = d->qFileDialogUi->listView->selectionModel();
- QObject::connect(selections, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(_q_selectionChanged()));
- QObject::connect(selections, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_currentChanged(QModelIndex)));
+ QObjectPrivate::connect(selections, &QItemSelectionModel::selectionChanged,
+ d, &QFileDialogPrivate::selectionChanged);
+ QObjectPrivate::connect(selections, &QItemSelectionModel::currentChanged,
+ d, &QFileDialogPrivate::currentChanged);
}
/*!
@@ -3217,26 +3252,31 @@ void QFileDialogPrivate::createToolButtons()
qFileDialogUi->backButton->setIcon(q->style()->standardIcon(QStyle::SP_ArrowBack, nullptr, q));
qFileDialogUi->backButton->setAutoRaise(true);
qFileDialogUi->backButton->setEnabled(false);
- QObject::connect(qFileDialogUi->backButton, SIGNAL(clicked()), q, SLOT(_q_navigateBackward()));
+ QObjectPrivate::connect(qFileDialogUi->backButton, &QPushButton::clicked,
+ this, &QFileDialogPrivate::navigateBackward);
qFileDialogUi->forwardButton->setIcon(q->style()->standardIcon(QStyle::SP_ArrowForward, nullptr, q));
qFileDialogUi->forwardButton->setAutoRaise(true);
qFileDialogUi->forwardButton->setEnabled(false);
- QObject::connect(qFileDialogUi->forwardButton, SIGNAL(clicked()), q, SLOT(_q_navigateForward()));
+ QObjectPrivate::connect(qFileDialogUi->forwardButton, &QPushButton::clicked,
+ this, &QFileDialogPrivate::navigateForward);
qFileDialogUi->toParentButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogToParent, nullptr, q));
qFileDialogUi->toParentButton->setAutoRaise(true);
qFileDialogUi->toParentButton->setEnabled(false);
- QObject::connect(qFileDialogUi->toParentButton, SIGNAL(clicked()), q, SLOT(_q_navigateToParent()));
+ QObjectPrivate::connect(qFileDialogUi->toParentButton, &QPushButton::clicked,
+ this, &QFileDialogPrivate::navigateToParent);
qFileDialogUi->listModeButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogListView, nullptr, q));
qFileDialogUi->listModeButton->setAutoRaise(true);
qFileDialogUi->listModeButton->setDown(true);
- QObject::connect(qFileDialogUi->listModeButton, SIGNAL(clicked()), q, SLOT(_q_showListView()));
+ QObjectPrivate::connect(qFileDialogUi->listModeButton, &QPushButton::clicked,
+ this, &QFileDialogPrivate::showListView);
qFileDialogUi->detailModeButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogDetailedView, nullptr, q));
qFileDialogUi->detailModeButton->setAutoRaise(true);
- QObject::connect(qFileDialogUi->detailModeButton, SIGNAL(clicked()), q, SLOT(_q_showDetailsView()));
+ QObjectPrivate::connect(qFileDialogUi->detailModeButton, &QPushButton::clicked,
+ this, &QFileDialogPrivate::showDetailsView);
QSize toolSize(qFileDialogUi->fileNameEdit->sizeHint().height(), qFileDialogUi->fileNameEdit->sizeHint().height());
qFileDialogUi->backButton->setFixedSize(toolSize);
@@ -3249,7 +3289,8 @@ void QFileDialogPrivate::createToolButtons()
qFileDialogUi->newFolderButton->setFixedSize(toolSize);
qFileDialogUi->newFolderButton->setAutoRaise(true);
qFileDialogUi->newFolderButton->setEnabled(false);
- QObject::connect(qFileDialogUi->newFolderButton, SIGNAL(clicked()), q, SLOT(_q_createDirectory()));
+ QObjectPrivate::connect(qFileDialogUi->newFolderButton, &QPushButton::clicked,
+ this, &QFileDialogPrivate::createDirectory);
}
/*!
@@ -3265,7 +3306,8 @@ void QFileDialogPrivate::createMenuActions()
#ifndef QT_NO_SHORTCUT
goHomeAction->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_H);
#endif
- QObject::connect(goHomeAction, SIGNAL(triggered()), q, SLOT(_q_goHome()));
+ QObjectPrivate::connect(goHomeAction, &QAction::triggered,
+ this, &QFileDialogPrivate::goHome);
q->addAction(goHomeAction);
// ### TODO add Desktop & Computer actions
@@ -3275,30 +3317,35 @@ void QFileDialogPrivate::createMenuActions()
#ifndef QT_NO_SHORTCUT
goToParent->setShortcut(Qt::CTRL | Qt::Key_Up);
#endif
- QObject::connect(goToParent, SIGNAL(triggered()), q, SLOT(_q_navigateToParent()));
+ QObjectPrivate::connect(goToParent, &QAction::triggered,
+ this, &QFileDialogPrivate::navigateToParent);
q->addAction(goToParent);
renameAction = new QAction(q);
renameAction->setEnabled(false);
renameAction->setObjectName("qt_rename_action"_L1);
- QObject::connect(renameAction, SIGNAL(triggered()), q, SLOT(_q_renameCurrent()));
+ QObjectPrivate::connect(renameAction, &QAction::triggered,
+ this, &QFileDialogPrivate::renameCurrent);
deleteAction = new QAction(q);
deleteAction->setEnabled(false);
deleteAction->setObjectName("qt_delete_action"_L1);
- QObject::connect(deleteAction, SIGNAL(triggered()), q, SLOT(_q_deleteCurrent()));
+ QObjectPrivate::connect(deleteAction, &QAction::triggered,
+ this, &QFileDialogPrivate::deleteCurrent);
showHiddenAction = new QAction(q);
showHiddenAction->setObjectName("qt_show_hidden_action"_L1);
showHiddenAction->setCheckable(true);
- QObject::connect(showHiddenAction, SIGNAL(triggered()), q, SLOT(_q_showHidden()));
+ QObjectPrivate::connect(showHiddenAction, &QAction::triggered,
+ this, &QFileDialogPrivate::showHidden);
newFolderAction = new QAction(q);
newFolderAction->setObjectName("qt_new_folder_action"_L1);
- QObject::connect(newFolderAction, SIGNAL(triggered()), q, SLOT(_q_createDirectory()));
+ QObjectPrivate::connect(newFolderAction, &QAction::triggered,
+ this, &QFileDialogPrivate::createDirectory);
}
-void QFileDialogPrivate::_q_goHome()
+void QFileDialogPrivate::goHome()
{
Q_Q(QFileDialog);
q->setDirectory(QDir::homePath());
@@ -3321,7 +3368,7 @@ void QFileDialogPrivate::saveHistorySelection()
Update history with new path, buttons, and combo
*/
-void QFileDialogPrivate::_q_pathChanged(const QString &newPath)
+void QFileDialogPrivate::pathChanged(const QString &newPath)
{
Q_Q(QFileDialog);
qFileDialogUi->toParentButton->setEnabled(QFileInfo::exists(model->rootPath()));
@@ -3365,8 +3412,10 @@ void QFileDialogPrivate::navigate(HistoryItem &historyItem)
| QItemSelectionModel::Rows;
selectionModel->select(historyItem.selection.constFirst(),
flags | QItemSelectionModel::Clear | QItemSelectionModel::Current);
- for (int i = 1, size = historyItem.selection.size(); i < size; ++i)
- selectionModel->select(historyItem.selection.at(i), flags);
+ auto it = historyItem.selection.cbegin() + 1;
+ const auto end = historyItem.selection.cend();
+ for (; it != end; ++it)
+ selectionModel->select(*it, flags);
view->scrollTo(historyItem.selection.constFirst());
}
@@ -3376,7 +3425,7 @@ void QFileDialogPrivate::navigate(HistoryItem &historyItem)
Navigates to the last directory viewed in the dialog.
*/
-void QFileDialogPrivate::_q_navigateBackward()
+void QFileDialogPrivate::navigateBackward()
{
if (!currentHistory.isEmpty() && currentHistoryLocation > 0) {
saveHistorySelection();
@@ -3389,7 +3438,7 @@ void QFileDialogPrivate::_q_navigateBackward()
Navigates to the last directory viewed in the dialog.
*/
-void QFileDialogPrivate::_q_navigateForward()
+void QFileDialogPrivate::navigateForward()
{
if (!currentHistory.isEmpty() && currentHistoryLocation < currentHistory.size() - 1) {
saveHistorySelection();
@@ -3403,7 +3452,7 @@ void QFileDialogPrivate::_q_navigateForward()
Navigates to the parent directory of the currently displayed directory
in the dialog.
*/
-void QFileDialogPrivate::_q_navigateToParent()
+void QFileDialogPrivate::navigateToParent()
{
Q_Q(QFileDialog);
QDir dir(model->rootDirectory());
@@ -3423,7 +3472,7 @@ void QFileDialogPrivate::_q_navigateToParent()
Creates a new directory, first asking the user for a suitable name.
*/
-void QFileDialogPrivate::_q_createDirectory()
+void QFileDialogPrivate::createDirectory()
{
Q_Q(QFileDialog);
qFileDialogUi->listView->clearSelection();
@@ -3450,7 +3499,7 @@ void QFileDialogPrivate::_q_createDirectory()
}
}
-void QFileDialogPrivate::_q_showListView()
+void QFileDialogPrivate::showListView()
{
qFileDialogUi->listModeButton->setDown(true);
qFileDialogUi->detailModeButton->setDown(false);
@@ -3460,7 +3509,7 @@ void QFileDialogPrivate::_q_showListView()
qFileDialogUi->listView->doItemsLayout();
}
-void QFileDialogPrivate::_q_showDetailsView()
+void QFileDialogPrivate::showDetailsView()
{
qFileDialogUi->listModeButton->setDown(false);
qFileDialogUi->detailModeButton->setDown(true);
@@ -3475,7 +3524,7 @@ void QFileDialogPrivate::_q_showDetailsView()
Show the context menu for the file/dir under position
*/
-void QFileDialogPrivate::_q_showContextMenu(const QPoint &position)
+void QFileDialogPrivate::showContextMenu(const QPoint &position)
{
#if !QT_CONFIG(menu)
Q_UNUSED(position);
@@ -3515,7 +3564,7 @@ void QFileDialogPrivate::_q_showContextMenu(const QPoint &position)
/*!
\internal
*/
-void QFileDialogPrivate::_q_renameCurrent()
+void QFileDialogPrivate::renameCurrent()
{
Q_Q(QFileDialog);
QModelIndex index = qFileDialogUi->listView->currentIndex();
@@ -3537,14 +3586,14 @@ bool QFileDialogPrivate::removeDirectory(const QString &path)
Deletes the currently selected item in the dialog.
*/
-void QFileDialogPrivate::_q_deleteCurrent()
+void QFileDialogPrivate::deleteCurrent()
{
if (model->isReadOnly())
return;
- QModelIndexList list = qFileDialogUi->listView->selectionModel()->selectedRows();
- for (int i = list.size() - 1; i >= 0; --i) {
- QPersistentModelIndex index = list.at(i);
+ const QModelIndexList list = qFileDialogUi->listView->selectionModel()->selectedRows();
+ for (auto it = list.crbegin(), end = list.crend(); it != end; ++it) {
+ QPersistentModelIndex index = *it;
if (index == qFileDialogUi->listView->rootIndex())
continue;
@@ -3591,7 +3640,7 @@ void QFileDialogPrivate::_q_deleteCurrent()
}
}
-void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text)
+void QFileDialogPrivate::autoCompleteFileName(const QString &text)
{
if (text.startsWith("//"_L1) || text.startsWith(u'\\')) {
qFileDialogUi->listView->selectionModel()->clearSelection();
@@ -3620,7 +3669,7 @@ void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text)
/*!
\internal
*/
-void QFileDialogPrivate::_q_updateOkButton()
+void QFileDialogPrivate::updateOkButton()
{
Q_Q(QFileDialog);
QPushButton *button = qFileDialogUi->buttonBox->button((q->acceptMode() == QFileDialog::AcceptOpen)
@@ -3683,7 +3732,7 @@ void QFileDialogPrivate::_q_updateOkButton()
break;
}
if (!idx.isValid()) {
- int maxLength = maxNameLength(fileDir);
+ const long maxLength = maxNameLength(fileDir);
enableButton = maxLength < 0 || fileName.size() <= maxLength;
}
break;
@@ -3716,9 +3765,9 @@ void QFileDialogPrivate::_q_updateOkButton()
/*!
\internal
*/
-void QFileDialogPrivate::_q_currentChanged(const QModelIndex &index)
+void QFileDialogPrivate::currentChanged(const QModelIndex &index)
{
- _q_updateOkButton();
+ updateOkButton();
emit q_func()->currentChanged(index.data(QFileSystemModel::FilePathRole).toString());
}
@@ -3728,7 +3777,7 @@ void QFileDialogPrivate::_q_currentChanged(const QModelIndex &index)
This is called when the user double clicks on a file with the corresponding
model item \a index.
*/
-void QFileDialogPrivate::_q_enterDirectory(const QModelIndex &index)
+void QFileDialogPrivate::enterDirectory(const QModelIndex &index)
{
Q_Q(QFileDialog);
// My Computer or a directory
@@ -3745,8 +3794,9 @@ void QFileDialogPrivate::_q_enterDirectory(const QModelIndex &index)
}
} else {
// Do not accept when shift-clicking to multi-select a file in environments with single-click-activation (KDE)
- if (!q->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, nullptr, qFileDialogUi->treeView)
- || q->fileMode() != QFileDialog::ExistingFiles || !(QGuiApplication::keyboardModifiers() & Qt::CTRL)) {
+ if ((!q->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, nullptr, qFileDialogUi->treeView)
+ || q->fileMode() != QFileDialog::ExistingFiles || !(QGuiApplication::keyboardModifiers() & Qt::CTRL))
+ && index.model()->flags(index) & Qt::ItemIsEnabled) {
q->accept();
}
}
@@ -3758,8 +3808,10 @@ void QFileDialogPrivate::_q_enterDirectory(const QModelIndex &index)
Changes the file dialog's current directory to the one specified
by \a path.
*/
-void QFileDialogPrivate::_q_goToDirectory(const QString &path)
+void QFileDialogPrivate::goToDirectory(const QString &path)
{
+ enum { UrlRole = Qt::UserRole + 1 };
+
#if QT_CONFIG(messagebox)
Q_Q(QFileDialog);
#endif
@@ -3778,7 +3830,7 @@ void QFileDialogPrivate::_q_goToDirectory(const QString &path)
dir.setPath(getEnvironmentVariable(path2));
if (dir.exists() || path2.isEmpty() || path2 == model->myComputer().toString()) {
- _q_enterDirectory(index);
+ enterDirectory(index);
#if QT_CONFIG(messagebox)
} else {
QString message = QFileDialog::tr("%1\nDirectory not found.\nPlease verify the "
@@ -3794,7 +3846,7 @@ void QFileDialogPrivate::_q_goToDirectory(const QString &path)
Sets the current name filter to be nameFilter and
update the qFileDialogUi->fileNameEdit when in AcceptSave mode with the new extension.
*/
-void QFileDialogPrivate::_q_useNameFilter(int index)
+void QFileDialogPrivate::useNameFilter(int index)
{
QStringList nameFilters = options->nameFilters();
if (index == nameFilters.size()) {
@@ -3813,7 +3865,7 @@ void QFileDialogPrivate::_q_useNameFilter(int index)
QString fileName = lineEdit()->text();
const QString fileNameExtension = QFileInfo(fileName).suffix();
if (!fileNameExtension.isEmpty() && !newNameFilterExtension.isEmpty()) {
- const int fileNameExtensionLength = fileNameExtension.size();
+ const qsizetype fileNameExtensionLength = fileNameExtension.size();
fileName.replace(fileName.size() - fileNameExtensionLength,
fileNameExtensionLength, newNameFilterExtension);
qFileDialogUi->listView->clearSelection();
@@ -3830,7 +3882,7 @@ void QFileDialogPrivate::_q_useNameFilter(int index)
This is called when the model index corresponding to the current file is changed
from \a index to \a current.
*/
-void QFileDialogPrivate::_q_selectionChanged()
+void QFileDialogPrivate::selectionChanged()
{
const QFileDialog::FileMode fileMode = q_func()->fileMode();
const QModelIndexList indexes = qFileDialogUi->listView->selectionModel()->selectedRows();
@@ -3851,7 +3903,7 @@ void QFileDialogPrivate::_q_selectionChanged()
if (!finalFiles.isEmpty() && !lineEdit()->hasFocus() && lineEdit()->isVisible())
lineEdit()->setText(finalFiles);
else
- _q_updateOkButton();
+ updateOkButton();
}
/*!
@@ -3859,7 +3911,7 @@ void QFileDialogPrivate::_q_selectionChanged()
Includes hidden files and directories in the items displayed in the dialog.
*/
-void QFileDialogPrivate::_q_showHidden()
+void QFileDialogPrivate::showHidden()
{
Q_Q(QFileDialog);
QDir::Filters dirFilters = q->filter();
@@ -3873,7 +3925,7 @@ void QFileDialogPrivate::_q_showHidden()
When parent is root and rows have been inserted when none was there before
then select the first one.
*/
-void QFileDialogPrivate::_q_rowsInserted(const QModelIndex &parent)
+void QFileDialogPrivate::rowsInserted(const QModelIndex &parent)
{
if (!qFileDialogUi->treeView
|| parent != qFileDialogUi->treeView->rootIndex()
@@ -3883,7 +3935,7 @@ void QFileDialogPrivate::_q_rowsInserted(const QModelIndex &parent)
return;
}
-void QFileDialogPrivate::_q_fileRenamed(const QString &path, const QString &oldName, const QString &newName)
+void QFileDialogPrivate::fileRenamed(const QString &path, const QString &oldName, const QString &newName)
{
const QFileDialog::FileMode fileMode = q_func()->fileMode();
if (fileMode == QFileDialog::Directory) {
@@ -3892,7 +3944,7 @@ void QFileDialogPrivate::_q_fileRenamed(const QString &path, const QString &oldN
}
}
-void QFileDialogPrivate::_q_emitUrlSelected(const QUrl &file)
+void QFileDialogPrivate::emitUrlSelected(const QUrl &file)
{
Q_Q(QFileDialog);
emit q->urlSelected(file);
@@ -3900,7 +3952,7 @@ void QFileDialogPrivate::_q_emitUrlSelected(const QUrl &file)
emit q->fileSelected(file.toLocalFile());
}
-void QFileDialogPrivate::_q_emitUrlsSelected(const QList<QUrl> &files)
+void QFileDialogPrivate::emitUrlsSelected(const QList<QUrl> &files)
{
Q_Q(QFileDialog);
emit q->urlsSelected(files);
@@ -3912,7 +3964,7 @@ void QFileDialogPrivate::_q_emitUrlsSelected(const QList<QUrl> &files)
emit q->filesSelected(localFiles);
}
-void QFileDialogPrivate::_q_nativeCurrentChanged(const QUrl &file)
+void QFileDialogPrivate::nativeCurrentChanged(const QUrl &file)
{
Q_Q(QFileDialog);
emit q->currentUrlChanged(file);
@@ -3920,7 +3972,7 @@ void QFileDialogPrivate::_q_nativeCurrentChanged(const QUrl &file)
emit q->currentChanged(file.toLocalFile());
}
-void QFileDialogPrivate::_q_nativeEnterDirectory(const QUrl &directory)
+void QFileDialogPrivate::nativeEnterDirectory(const QUrl &directory)
{
Q_Q(QFileDialog);
emit q->directoryUrlEntered(directory);
@@ -3949,7 +4001,7 @@ bool QFileDialogPrivate::itemViewKeyboardEvent(QKeyEvent *event) {
#endif
switch (event->key()) {
case Qt::Key_Backspace:
- _q_navigateToParent();
+ navigateToParent();
return true;
case Qt::Key_Back:
#ifdef QT_KEYPAD_NAVIGATION
@@ -3958,7 +4010,7 @@ bool QFileDialogPrivate::itemViewKeyboardEvent(QKeyEvent *event) {
#endif
case Qt::Key_Left:
if (event->key() == Qt::Key_Back || event->modifiers() == Qt::AltModifier) {
- _q_navigateBackward();
+ navigateBackward();
return true;
}
break;
diff --git a/src/widgets/dialogs/qfiledialog.h b/src/widgets/dialogs/qfiledialog.h
index 970bddb359..d59392753a 100644
--- a/src/widgets/dialogs/qfiledialog.h
+++ b/src/widgets/dialogs/qfiledialog.h
@@ -213,8 +213,20 @@ public:
const QStringList &supportedSchemes = QStringList());
static void getOpenFileContent(const QString &nameFilter,
+ const std::function<void(const QString &, const QByteArray &)> &fileContentsReady,
+ QWidget *parent= nullptr);
+
+ static void saveFileContent(const QByteArray &fileContent,
+ const QString &fileNameHint,
+ QWidget *parent = nullptr);
+
+#if QT_WIDGETS_REMOVED_SINCE(6, 7)
+ static void getOpenFileContent(const QString &nameFilter,
const std::function<void(const QString &, const QByteArray &)> &fileContentsReady);
- static void saveFileContent(const QByteArray &fileContent, const QString &fileNameHint = QString());
+ static void saveFileContent(const QByteArray &fileContent,
+ const QString &fileNameHint = QString());
+#endif
+
protected:
QFileDialog(const QFileDialogArgs &args);
@@ -226,36 +238,6 @@ private:
Q_DECLARE_PRIVATE(QFileDialog)
Q_DISABLE_COPY(QFileDialog)
- Q_PRIVATE_SLOT(d_func(), void _q_pathChanged(const QString &))
-
- Q_PRIVATE_SLOT(d_func(), void _q_navigateBackward())
- Q_PRIVATE_SLOT(d_func(), void _q_navigateForward())
- Q_PRIVATE_SLOT(d_func(), void _q_navigateToParent())
- Q_PRIVATE_SLOT(d_func(), void _q_createDirectory())
- Q_PRIVATE_SLOT(d_func(), void _q_showListView())
- Q_PRIVATE_SLOT(d_func(), void _q_showDetailsView())
- Q_PRIVATE_SLOT(d_func(), void _q_showContextMenu(const QPoint &))
- Q_PRIVATE_SLOT(d_func(), void _q_renameCurrent())
- Q_PRIVATE_SLOT(d_func(), void _q_deleteCurrent())
- Q_PRIVATE_SLOT(d_func(), void _q_showHidden())
- Q_PRIVATE_SLOT(d_func(), void _q_updateOkButton())
- Q_PRIVATE_SLOT(d_func(), void _q_currentChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_enterDirectory(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitUrlSelected(const QUrl &))
- Q_PRIVATE_SLOT(d_func(), void _q_emitUrlsSelected(const QList<QUrl> &))
- Q_PRIVATE_SLOT(d_func(), void _q_nativeCurrentChanged(const QUrl &))
- Q_PRIVATE_SLOT(d_func(), void _q_nativeEnterDirectory(const QUrl&))
- Q_PRIVATE_SLOT(d_func(), void _q_goToDirectory(const QString &path))
- Q_PRIVATE_SLOT(d_func(), void _q_useNameFilter(int index))
- Q_PRIVATE_SLOT(d_func(), void _q_selectionChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_goToUrl(const QUrl &url))
- Q_PRIVATE_SLOT(d_func(), void _q_goHome())
- Q_PRIVATE_SLOT(d_func(), void _q_showHeader(QAction *))
- Q_PRIVATE_SLOT(d_func(), void _q_autoCompleteFileName(const QString &text))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsInserted(const QModelIndex & parent))
- Q_PRIVATE_SLOT(d_func(), void _q_fileRenamed(const QString &path,
- const QString &oldName,
- const QString &newName))
friend class QPlatformDialogHelper;
};
diff --git a/src/widgets/dialogs/qfiledialog_p.h b/src/widgets/dialogs/qfiledialog_p.h
index 9a12574a78..d5ee1c537b 100644
--- a/src/widgets/dialogs/qfiledialog_p.h
+++ b/src/widgets/dialogs/qfiledialog_p.h
@@ -74,8 +74,6 @@ struct QFileDialogArgs
QFileDialog::Options options = {};
};
-#define UrlRole (Qt::UserRole + 1)
-
class Q_WIDGETS_EXPORT QFileDialogPrivate : public QDialogPrivate
{
Q_DECLARE_PUBLIC(QFileDialog)
@@ -122,11 +120,11 @@ public:
QLineEdit *lineEdit() const;
- static int maxNameLength(const QString &path);
+ static long maxNameLength(const QString &path);
QString basename(const QString &path) const
{
- int separator = QDir::toNativeSeparators(path).lastIndexOf(QDir::separator());
+ const qsizetype separator = QDir::toNativeSeparators(path).lastIndexOf(QDir::separator());
if (separator != -1)
return path.mid(separator + 1);
return path;
@@ -165,34 +163,34 @@ public:
void emitFilesSelected(const QStringList &files);
void saveHistorySelection();
- void _q_goHome();
- void _q_pathChanged(const QString &);
+ void goHome();
+ void pathChanged(const QString &);
void navigate(HistoryItem &);
- void _q_navigateBackward();
- void _q_navigateForward();
- void _q_navigateToParent();
- void _q_createDirectory();
- void _q_showListView();
- void _q_showDetailsView();
- void _q_showContextMenu(const QPoint &position);
- void _q_renameCurrent();
- void _q_deleteCurrent();
- void _q_showHidden();
- void _q_showHeader(QAction *);
- void _q_updateOkButton();
- void _q_currentChanged(const QModelIndex &index);
- void _q_enterDirectory(const QModelIndex &index);
- void _q_emitUrlSelected(const QUrl &file);
- void _q_emitUrlsSelected(const QList<QUrl> &files);
- void _q_nativeCurrentChanged(const QUrl &file);
- void _q_nativeEnterDirectory(const QUrl &directory);
- void _q_goToDirectory(const QString &);
- void _q_useNameFilter(int index);
- void _q_selectionChanged();
- void _q_goToUrl(const QUrl &url);
- void _q_autoCompleteFileName(const QString &);
- void _q_rowsInserted(const QModelIndex & parent);
- void _q_fileRenamed(const QString &path, const QString &oldName, const QString &newName);
+ void navigateBackward();
+ void navigateForward();
+ void navigateToParent();
+ void createDirectory();
+ void showListView();
+ void showDetailsView();
+ void showContextMenu(const QPoint &position);
+ void renameCurrent();
+ void deleteCurrent();
+ void showHidden();
+ void showHeader(QAction *);
+ void updateOkButton();
+ void currentChanged(const QModelIndex &index);
+ void enterDirectory(const QModelIndex &index);
+ void emitUrlSelected(const QUrl &file);
+ void emitUrlsSelected(const QList<QUrl> &files);
+ void nativeCurrentChanged(const QUrl &file);
+ void nativeEnterDirectory(const QUrl &directory);
+ void goToDirectory(const QString &);
+ void useNameFilter(int index);
+ void selectionChanged();
+ void goToUrl(const QUrl &url);
+ void autoCompleteFileName(const QString &);
+ void rowsInserted(const QModelIndex & parent);
+ void fileRenamed(const QString &path, const QString &oldName, const QString &newName);
// layout
#if QT_CONFIG(proxymodel)
@@ -223,6 +221,7 @@ public:
// dialog. Returning false means that a non-native dialog must be
// used instead.
bool canBeNativeDialog() const override;
+ void setVisible(bool visible) override;
inline bool usingWidgets() const;
inline void setDirectory_sys(const QUrl &directory);
diff --git a/src/widgets/dialogs/qfontdialog.cpp b/src/widgets/dialogs/qfontdialog.cpp
index 8792e18d6f..628297d22b 100644
--- a/src/widgets/dialogs/qfontdialog.cpp
+++ b/src/widgets/dialogs/qfontdialog.cpp
@@ -69,7 +69,7 @@ QFontListView::QFontListView(QWidget *parent)
setEditTriggers(NoEditTriggers);
}
-static const Qt::WindowFlags DefaultWindowFlags =
+static const Qt::WindowFlags qfd_DefaultWindowFlags =
Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
QFontDialogPrivate::QFontDialogPrivate()
@@ -119,7 +119,7 @@ QFontDialogPrivate::~QFontDialogPrivate()
\sa getFont()
*/
QFontDialog::QFontDialog(QWidget *parent)
- : QDialog(*new QFontDialogPrivate, parent, DefaultWindowFlags)
+ : QDialog(*new QFontDialogPrivate, parent, qfd_DefaultWindowFlags)
{
Q_D(QFontDialog);
d->init();
@@ -208,14 +208,21 @@ void QFontDialogPrivate::init()
size = 0;
smoothScalable = false;
- QObject::connect(writingSystemCombo, SIGNAL(activated(int)), q, SLOT(_q_writingSystemHighlighted(int)));
- QObject::connect(familyList, SIGNAL(highlighted(int)), q, SLOT(_q_familyHighlighted(int)));
- QObject::connect(styleList, SIGNAL(highlighted(int)), q, SLOT(_q_styleHighlighted(int)));
- QObject::connect(sizeList, SIGNAL(highlighted(int)), q, SLOT(_q_sizeHighlighted(int)));
- QObject::connect(sizeEdit, SIGNAL(textChanged(QString)), q, SLOT(_q_sizeChanged(QString)));
-
- QObject::connect(strikeout, SIGNAL(clicked()), q, SLOT(_q_updateSample()));
- QObject::connect(underline, SIGNAL(clicked()), q, SLOT(_q_updateSample()));
+ QObjectPrivate::connect(writingSystemCombo, &QComboBox::activated,
+ this, &QFontDialogPrivate::writingSystemHighlighted);
+ QObjectPrivate::connect(familyList, &QFontListView::highlighted,
+ this, &QFontDialogPrivate::familyHighlighted);
+ QObjectPrivate::connect(styleList, &QFontListView::highlighted,
+ this, &QFontDialogPrivate::styleHighlighted);
+ QObjectPrivate::connect(sizeList, &QFontListView::highlighted,
+ this, &QFontDialogPrivate::sizeHighlighted);
+ QObjectPrivate::connect(sizeEdit, &QLineEdit::textChanged,
+ this, &QFontDialogPrivate::sizeChanged);
+
+ QObjectPrivate::connect(strikeout, &QCheckBox::clicked,
+ this, &QFontDialogPrivate::updateSample);
+ QObjectPrivate::connect(underline, &QCheckBox::clicked, this,
+ &QFontDialogPrivate::updateSample);
for (int i = 0; i < QFontDatabase::WritingSystemsCount; ++i) {
QFontDatabase::WritingSystem ws = QFontDatabase::WritingSystem(i);
@@ -277,11 +284,11 @@ void QFontDialogPrivate::init()
QPushButton *button
= static_cast<QPushButton *>(buttonBox->addButton(QDialogButtonBox::Ok));
- QObject::connect(buttonBox, SIGNAL(accepted()), q, SLOT(accept()));
+ QObject::connect(buttonBox, &QDialogButtonBox::accepted, q, &QDialog::accept);
button->setDefault(true);
buttonBox->addButton(QDialogButtonBox::Cancel);
- QObject::connect(buttonBox, SIGNAL(rejected()), q, SLOT(reject()));
+ QObject::connect(buttonBox, &QDialogButtonBox::rejected, q, &QDialog::reject);
q->resize(500, 360);
@@ -390,7 +397,7 @@ bool QFontDialog::eventFilter(QObject *o , QEvent *e)
{
Q_D(QFontDialog);
if (e->type() == QEvent::KeyPress) {
- QKeyEvent *k = (QKeyEvent *)e;
+ QKeyEvent *k = static_cast<QKeyEvent *>(e);
if (o == d->sizeEdit &&
(k->key() == Qt::Key_Up ||
k->key() == Qt::Key_Down ||
@@ -430,8 +437,10 @@ void QFontDialogPrivate::initHelper(QPlatformDialogHelper *h)
auto *fontDialogHelper = static_cast<QPlatformFontDialogHelper *>(h);
fontDialogHelper->setOptions(options);
fontDialogHelper->setCurrentFont(q->currentFont());
- QObject::connect(h, SIGNAL(currentFontChanged(QFont)), q, SIGNAL(currentFontChanged(QFont)));
- QObject::connect(h, SIGNAL(fontSelected(QFont)), q, SIGNAL(fontSelected(QFont)));
+ QObject::connect(fontDialogHelper, &QPlatformFontDialogHelper::currentFontChanged,
+ q, &QFontDialog::currentFontChanged);
+ QObject::connect(fontDialogHelper, &QPlatformFontDialogHelper::fontSelected,
+ q, &QFontDialog::fontSelected);
}
void QFontDialogPrivate::helperPrepareShow(QPlatformDialogHelper *)
@@ -500,9 +509,9 @@ void QFontDialogPrivate::updateFamilies()
//and try some fall backs
match_t type = MATCH_NONE;
- if (bestFamilyType <= MATCH_NONE && familyName2 == QStringLiteral("helvetica"))
+ if (bestFamilyType <= MATCH_NONE && familyName2 == "helvetica"_L1)
type = MATCH_LAST_RESORT;
- if (bestFamilyType <= MATCH_LAST_RESORT && familyName2 == f.families().first())
+ if (bestFamilyType <= MATCH_LAST_RESORT && familyName2 == f.families().constFirst())
type = MATCH_APP;
// ### add fallback for writingSystem
if (type != MATCH_NONE) {
@@ -622,10 +631,10 @@ void QFontDialogPrivate::updateSizes()
sizeEdit->clear();
}
- _q_updateSample();
+ updateSample();
}
-void QFontDialogPrivate::_q_updateSample()
+void QFontDialogPrivate::updateSample()
{
// compute new font
int pSize = sizeEdit->text().toInt();
@@ -651,7 +660,7 @@ void QFontDialogPrivate::updateSampleFont(const QFont &newFont)
/*!
\internal
*/
-void QFontDialogPrivate::_q_writingSystemHighlighted(int index)
+void QFontDialogPrivate::writingSystemHighlighted(int index)
{
writingSystem = QFontDatabase::WritingSystem(index);
sampleEdit->setText(QFontDatabase::writingSystemSample(writingSystem));
@@ -661,7 +670,7 @@ void QFontDialogPrivate::_q_writingSystemHighlighted(int index)
/*!
\internal
*/
-void QFontDialogPrivate::_q_familyHighlighted(int i)
+void QFontDialogPrivate::familyHighlighted(int i)
{
Q_Q(QFontDialog);
family = familyList->text(i);
@@ -678,7 +687,7 @@ void QFontDialogPrivate::_q_familyHighlighted(int i)
\internal
*/
-void QFontDialogPrivate::_q_styleHighlighted(int index)
+void QFontDialogPrivate::styleHighlighted(int index)
{
Q_Q(QFontDialog);
QString s = styleList->text(index);
@@ -697,7 +706,7 @@ void QFontDialogPrivate::_q_styleHighlighted(int index)
\internal
*/
-void QFontDialogPrivate::_q_sizeHighlighted(int index)
+void QFontDialogPrivate::sizeHighlighted(int index)
{
Q_Q(QFontDialog);
QString s = sizeList->text(index);
@@ -707,7 +716,7 @@ void QFontDialogPrivate::_q_sizeHighlighted(int index)
sizeEdit->selectAll();
size = s.toInt();
- _q_updateSample();
+ updateSample();
}
/*!
@@ -716,7 +725,7 @@ void QFontDialogPrivate::_q_sizeHighlighted(int index)
The size is passed in the \a s argument as a \e string.
*/
-void QFontDialogPrivate::_q_sizeChanged(const QString &s)
+void QFontDialogPrivate::sizeChanged(const QString &s)
{
// no need to check if the conversion is valid, since we have an QIntValidator in the size edit
int size = s.toInt();
@@ -736,7 +745,7 @@ void QFontDialogPrivate::_q_sizeChanged(const QString &s)
else
sizeList->clearSelection();
}
- _q_updateSample();
+ updateSample();
}
void QFontDialogPrivate::retranslateStrings()
@@ -960,19 +969,31 @@ void QFontDialog::open(QObject *receiver, const char *member)
*/
void QFontDialog::setVisible(bool visible)
{
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden) != visible)
- return;
- Q_D(QFontDialog);
- if (d->canBeNativeDialog())
- d->setNativeDialogVisible(visible);
- if (d->nativeDialogInUse) {
+ // will call QFontDialogPrivate::setVisible
+ QDialog::setVisible(visible);
+}
+
+/*!
+ \internal
+
+ The implementation of QFontDialog::setVisible() has to live here so that the call
+ to hide() in ~QDialog calls this function; it wouldn't call the override of
+ QDialog::setVisible().
+*/
+void QFontDialogPrivate::setVisible(bool visible)
+{
+ Q_Q(QFontDialog);
+
+ if (canBeNativeDialog())
+ setNativeDialogVisible(visible);
+ if (nativeDialogInUse) {
// Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
// updates the state correctly, but skips showing the non-native version:
- setAttribute(Qt::WA_DontShowOnScreen, true);
+ q->setAttribute(Qt::WA_DontShowOnScreen, true);
} else {
- setAttribute(Qt::WA_DontShowOnScreen, false);
+ q->setAttribute(Qt::WA_DontShowOnScreen, false);
}
- QDialog::setVisible(visible);
+ QDialogPrivate::setVisible(visible);
}
/*!
diff --git a/src/widgets/dialogs/qfontdialog.h b/src/widgets/dialogs/qfontdialog.h
index 56f719796b..b2900d6a6b 100644
--- a/src/widgets/dialogs/qfontdialog.h
+++ b/src/widgets/dialogs/qfontdialog.h
@@ -70,13 +70,6 @@ protected:
private:
Q_DISABLE_COPY(QFontDialog)
-
- Q_PRIVATE_SLOT(d_func(), void _q_sizeChanged(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_familyHighlighted(int))
- Q_PRIVATE_SLOT(d_func(), void _q_writingSystemHighlighted(int))
- Q_PRIVATE_SLOT(d_func(), void _q_styleHighlighted(int))
- Q_PRIVATE_SLOT(d_func(), void _q_sizeHighlighted(int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSample())
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QFontDialog::FontDialogOptions)
diff --git a/src/widgets/dialogs/qfontdialog_p.h b/src/widgets/dialogs/qfontdialog_p.h
index 4b3b45a9be..89b795f35e 100644
--- a/src/widgets/dialogs/qfontdialog_p.h
+++ b/src/widgets/dialogs/qfontdialog_p.h
@@ -21,6 +21,8 @@
#include "qfontdatabase.h"
#include "qfontdialog.h"
#include <qpa/qplatformdialoghelper.h>
+
+#include <QtCore/qpointer.h>
#include "qsharedpointer.h"
QT_REQUIRE_CONFIG(fontdialog);
@@ -55,12 +57,12 @@ public:
const QString &title, QFontDialog::FontDialogOptions options);
void init();
- void _q_sizeChanged(const QString &);
- void _q_familyHighlighted(int);
- void _q_writingSystemHighlighted(int);
- void _q_styleHighlighted(int);
- void _q_sizeHighlighted(int);
- void _q_updateSample();
+ void sizeChanged(const QString &);
+ void familyHighlighted(int);
+ void writingSystemHighlighted(int);
+ void styleHighlighted(int);
+ void sizeHighlighted(int);
+ void updateSample();
void updateSampleFont(const QFont &newFont);
void retranslateStrings();
@@ -105,6 +107,7 @@ public:
QByteArray memberToDisconnectOnClose;
bool canBeNativeDialog() const override;
+ void setVisible(bool visible) override;
void _q_runNativeAppModalPanel();
private:
diff --git a/src/widgets/dialogs/qinputdialog.cpp b/src/widgets/dialogs/qinputdialog.cpp
index 89ea6e6746..6d1a0b2873 100644
--- a/src/widgets/dialogs/qinputdialog.cpp
+++ b/src/widgets/dialogs/qinputdialog.cpp
@@ -18,6 +18,8 @@
#include "qevent.h"
#include "qdialog_p.h"
+#include <QtCore/qpointer.h>
+
QT_USE_NAMESPACE
enum CandidateSignal {
@@ -68,8 +70,10 @@ class QInputDialogSpinBox : public QSpinBox
public:
QInputDialogSpinBox(QWidget *parent)
: QSpinBox(parent) {
- connect(lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(notifyTextChanged()));
- connect(this, SIGNAL(editingFinished()), this, SLOT(notifyTextChanged()));
+ connect(lineEdit(), &QLineEdit::textChanged,
+ this, &QInputDialogSpinBox::notifyTextChanged);
+ connect(this, &QInputDialogSpinBox::editingFinished,
+ this, &QInputDialogSpinBox::notifyTextChanged);
}
signals:
@@ -101,8 +105,10 @@ class QInputDialogDoubleSpinBox : public QDoubleSpinBox
public:
QInputDialogDoubleSpinBox(QWidget *parent = nullptr)
: QDoubleSpinBox(parent) {
- connect(lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(notifyTextChanged()));
- connect(this, SIGNAL(editingFinished()), this, SLOT(notifyTextChanged()));
+ connect(lineEdit(), &QLineEdit::textChanged,
+ this, &QInputDialogDoubleSpinBox::notifyTextChanged);
+ connect(this, &QInputDialogDoubleSpinBox::editingFinished,
+ this, &QInputDialogDoubleSpinBox::notifyTextChanged);
}
signals:
@@ -161,9 +167,9 @@ public:
QString listViewText() const;
void ensureLayout() const { const_cast<QInputDialogPrivate *>(this)->ensureLayout(); }
bool useComboBoxOrListView() const { return comboBox && comboBox->count() > 0; }
- void _q_textChanged(const QString &text);
- void _q_plainTextEditTextChanged();
- void _q_currentRowChanged(const QModelIndex &newIndex, const QModelIndex &oldIndex);
+ void textChanged(const QString &text);
+ void plainTextEditTextChanged();
+ void currentRowChanged(const QModelIndex &newIndex, const QModelIndex &oldIndex);
mutable QLabel *label;
mutable QDialogButtonBox *buttonBox;
@@ -207,8 +213,8 @@ void QInputDialogPrivate::ensureLayout()
label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, q);
- QObject::connect(buttonBox, SIGNAL(accepted()), q, SLOT(accept()));
- QObject::connect(buttonBox, SIGNAL(rejected()), q, SLOT(reject()));
+ QObject::connect(buttonBox, &QDialogButtonBox::accepted, q, &QDialog::accept);
+ QObject::connect(buttonBox, &QDialogButtonBox::rejected, q, &QDialog::reject);
mainLayout = new QVBoxLayout(q);
mainLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
@@ -228,8 +234,8 @@ void QInputDialogPrivate::ensureLineEdit()
qt_widget_private(lineEdit)->inheritsInputMethodHints = 1;
#endif
lineEdit->hide();
- QObject::connect(lineEdit, SIGNAL(textChanged(QString)),
- q, SLOT(_q_textChanged(QString)));
+ QObjectPrivate::connect(lineEdit, &QLineEdit::textChanged,
+ this, &QInputDialogPrivate::textChanged);
}
}
@@ -243,8 +249,8 @@ void QInputDialogPrivate::ensurePlainTextEdit()
qt_widget_private(plainTextEdit)->inheritsInputMethodHints = 1;
#endif
plainTextEdit->hide();
- QObject::connect(plainTextEdit, SIGNAL(textChanged()),
- q, SLOT(_q_plainTextEditTextChanged()));
+ QObjectPrivate::connect(plainTextEdit, &QPlainTextEdit::textChanged,
+ this, &QInputDialogPrivate::plainTextEditTextChanged);
}
}
@@ -257,10 +263,10 @@ void QInputDialogPrivate::ensureComboBox()
qt_widget_private(comboBox)->inheritsInputMethodHints = 1;
#endif
comboBox->hide();
- QObject::connect(comboBox, SIGNAL(editTextChanged(QString)),
- q, SLOT(_q_textChanged(QString)));
- QObject::connect(comboBox, SIGNAL(currentTextChanged(QString)),
- q, SLOT(_q_textChanged(QString)));
+ QObjectPrivate::connect(comboBox, &QComboBox::editTextChanged,
+ this, &QInputDialogPrivate::textChanged);
+ QObjectPrivate::connect(comboBox, &QComboBox::currentTextChanged,
+ this, &QInputDialogPrivate::textChanged);
}
}
@@ -275,9 +281,9 @@ void QInputDialogPrivate::ensureListView()
listView->setSelectionMode(QAbstractItemView::SingleSelection);
listView->setModel(comboBox->model());
listView->setCurrentIndex(QModelIndex()); // ###
- QObject::connect(listView->selectionModel(),
- SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_currentRowChanged(QModelIndex,QModelIndex)));
+ QObjectPrivate::connect(listView->selectionModel(),
+ &QItemSelectionModel::currentRowChanged,
+ this, &QInputDialogPrivate::currentRowChanged);
}
}
@@ -287,8 +293,8 @@ void QInputDialogPrivate::ensureIntSpinBox()
if (!intSpinBox) {
intSpinBox = new QInputDialogSpinBox(q);
intSpinBox->hide();
- QObject::connect(intSpinBox, SIGNAL(valueChanged(int)),
- q, SIGNAL(intValueChanged(int)));
+ QObject::connect(intSpinBox, &QInputDialogSpinBox::valueChanged,
+ q, &QInputDialog::intValueChanged);
}
}
@@ -298,8 +304,8 @@ void QInputDialogPrivate::ensureDoubleSpinBox()
if (!doubleSpinBox) {
doubleSpinBox = new QInputDialogDoubleSpinBox(q);
doubleSpinBox->hide();
- QObject::connect(doubleSpinBox, SIGNAL(valueChanged(double)),
- q, SIGNAL(doubleValueChanged(double)));
+ QObject::connect(doubleSpinBox, &QInputDialogDoubleSpinBox::valueChanged,
+ q, &QInputDialog::doubleValueChanged);
}
}
@@ -374,9 +380,9 @@ void QInputDialogPrivate::chooseRightTextInputWidget()
setInputWidget(widget);
if (inputWidget == comboBox) {
- _q_textChanged(comboBox->currentText());
+ textChanged(comboBox->currentText());
} else if (inputWidget == listView) {
- _q_textChanged(listViewText());
+ textChanged(listViewText());
}
}
@@ -410,7 +416,7 @@ QString QInputDialogPrivate::listViewText() const
}
}
-void QInputDialogPrivate::_q_textChanged(const QString &text)
+void QInputDialogPrivate::textChanged(const QString &text)
{
Q_Q(QInputDialog);
if (textValue != text) {
@@ -419,7 +425,7 @@ void QInputDialogPrivate::_q_textChanged(const QString &text)
}
}
-void QInputDialogPrivate::_q_plainTextEditTextChanged()
+void QInputDialogPrivate::plainTextEditTextChanged()
{
Q_Q(QInputDialog);
QString text = plainTextEdit->toPlainText();
@@ -429,10 +435,10 @@ void QInputDialogPrivate::_q_plainTextEditTextChanged()
}
}
-void QInputDialogPrivate::_q_currentRowChanged(const QModelIndex &newIndex,
- const QModelIndex & /* oldIndex */)
+void QInputDialogPrivate::currentRowChanged(const QModelIndex &newIndex,
+ const QModelIndex & /* oldIndex */)
{
- _q_textChanged(comboBox->model()->data(newIndex).toString());
+ textChanged(comboBox->model()->data(newIndex).toString());
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
}
diff --git a/src/widgets/dialogs/qinputdialog.h b/src/widgets/dialogs/qinputdialog.h
index 51264af76f..bbf757e6e6 100644
--- a/src/widgets/dialogs/qinputdialog.h
+++ b/src/widgets/dialogs/qinputdialog.h
@@ -161,9 +161,6 @@ public:
private:
Q_DISABLE_COPY(QInputDialog)
- Q_PRIVATE_SLOT(d_func(), void _q_textChanged(const QString&))
- Q_PRIVATE_SLOT(d_func(), void _q_plainTextEditTextChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_currentRowChanged(const QModelIndex&, const QModelIndex&))
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QInputDialog::InputDialogOptions)
diff --git a/src/widgets/dialogs/qmessagebox.cpp b/src/widgets/dialogs/qmessagebox.cpp
index e38826534a..bf56b17f55 100644
--- a/src/widgets/dialogs/qmessagebox.cpp
+++ b/src/widgets/dialogs/qmessagebox.cpp
@@ -30,11 +30,18 @@
#include "private/qabstractbutton_p.h"
#include <QtGui/qpa/qplatformtheme.h>
+#include <QtCore/qanystringview.h>
+#include <QtCore/qdebug.h>
+#include <QtCore/qpointer.h>
+#include <QtCore/qversionnumber.h>
+
#ifdef Q_OS_WIN
# include <QtCore/qt_windows.h>
#include <qpa/qplatformnativeinterface.h>
#endif
+#include <optional>
+
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
@@ -49,6 +56,20 @@ HMENU qt_getWindowsSystemMenu(const QWidget *w)
}
#endif
+static_assert(qToUnderlying(QMessageBox::ButtonRole::NRoles) ==
+ qToUnderlying(QDialogButtonBox::ButtonRole::NRoles),
+ "QMessageBox::ButtonRole and QDialogButtonBox::ButtonRole out of sync!");
+
+static_assert(std::is_same_v<std::underlying_type_t<QMessageBox::ButtonRole>,
+ std::underlying_type_t<QDialogButtonBox::ButtonRole>>);
+
+// StandardButton enums have different underlying types
+// => qToUnderlying and std::is_same_v won't work
+// ### Qt 7: make them have the same underlying type
+static_assert(static_cast<int>(QMessageBox::StandardButton::LastButton) ==
+ static_cast<int>(QDialogButtonBox::StandardButton::LastButton),
+ "QMessageBox::StandardButton and QDialogButtonBox::StandardButton out of sync!");
+
enum Button { Old_Ok = 1, Old_Cancel = 2, Old_Yes = 3, Old_No = 4, Old_Abort = 5, Old_Retry = 6,
Old_Ignore = 7, Old_YesAll = 8, Old_NoAll = 9, Old_ButtonMask = 0xFF,
NewButtonMask = 0xFFFFFC00 };
@@ -91,8 +112,8 @@ public:
layout->addWidget(textEdit);
setLayout(layout);
- connect(textEdit, SIGNAL(copyAvailable(bool)),
- this, SLOT(textCopyAvailable(bool)));
+ connect(textEdit, &TextEdit::copyAvailable,
+ this, &QMessageBoxDetailsText::textCopyAvailable);
}
void setText(const QString &text) { textEdit->setPlainText(text); }
QString text() const { return textEdit->toPlainText(); }
@@ -171,8 +192,8 @@ public:
void init(const QString &title = QString(), const QString &text = QString());
void setupLayout();
- void _q_buttonClicked(QAbstractButton *);
- void _q_clicked(QPlatformDialogHelper::StandardButton button, QPlatformDialogHelper::ButtonRole role);
+ void buttonClicked(QAbstractButton *);
+ void helperClicked(QPlatformDialogHelper::StandardButton button, QPlatformDialogHelper::ButtonRole role);
void setClickedButton(QAbstractButton *button);
QAbstractButton *findButton(int button0, int button1, int button2, int flags);
@@ -181,13 +202,14 @@ public:
QAbstractButton *abstractButtonForId(int id) const;
int execReturnCode(QAbstractButton *button);
- int dialogCodeForButton(QAbstractButton *button) const;
-
void detectEscapeButton();
void updateSize();
int layoutMinimumWidth();
void retranslateStrings();
+ void setVisible(bool visible) override;
+ bool canBeNativeDialog() const override;
+
static int showOldMessageBox(QWidget *parent, QMessageBox::Icon icon,
const QString &title, const QString &text,
int button0, int button1, int button2);
@@ -230,7 +252,7 @@ public:
private:
void initHelper(QPlatformDialogHelper *) override;
void helperPrepareShow(QPlatformDialogHelper *) override;
- void helperDone(QDialog::DialogCode, QPlatformDialogHelper *) override;
+ int dialogCode() const override;
};
void QMessageBoxPrivate::init(const QString &title, const QString &text)
@@ -249,8 +271,8 @@ void QMessageBoxPrivate::init(const QString &title, const QString &text)
buttonBox = new QDialogButtonBox;
buttonBox->setObjectName("qt_msgbox_buttonbox"_L1);
buttonBox->setCenterButtons(q->style()->styleHint(QStyle::SH_MessageBox_CenterButtons, nullptr, q));
- QObject::connect(buttonBox, SIGNAL(clicked(QAbstractButton*)),
- q, SLOT(_q_buttonClicked(QAbstractButton*)));
+ QObjectPrivate::connect(buttonBox, &QDialogButtonBox::clicked,
+ this, &QMessageBoxPrivate::buttonClicked);
setupLayout();
if (!title.isEmpty() || !text.isEmpty()) {
q->setWindowTitle(title);
@@ -270,7 +292,7 @@ void QMessageBoxPrivate::setupLayout()
Q_Q(QMessageBox);
delete q->layout();
QGridLayout *grid = new QGridLayout;
- bool hasIcon = !iconLabel->pixmap(Qt::ReturnByValue).isNull();
+ const bool hasIcon = !iconLabel->pixmap().isNull();
if (hasIcon)
grid->addWidget(iconLabel, 0, 0, 2, 1, Qt::AlignTop);
@@ -425,37 +447,50 @@ static int oldButton(int button)
int QMessageBoxPrivate::execReturnCode(QAbstractButton *button)
{
- int ret = buttonBox->standardButton(button);
- if (ret == QMessageBox::NoButton) {
- ret = customButtonList.indexOf(button); // if button == 0, correctly sets ret = -1
- } else if (compatMode) {
- ret = oldButton(ret);
+ if (int standardButton = buttonBox->standardButton(button)) {
+ // When using a QMessageBox with standard buttons, the return
+ // code is a StandardButton value indicating the standard button
+ // that was clicked.
+ if (compatMode)
+ return oldButton(standardButton);
+ else
+ return standardButton;
+ } else {
+ // When using QMessageBox with custom buttons, the return code
+ // is an opaque value, and the user is expected to use clickedButton()
+ // to determine which button was clicked. We make sure to keep the opaque
+ // value out of the QDialog::DialogCode range, so we can distinguish them.
+ auto customButtonIndex = customButtonList.indexOf(button);
+ if (customButtonIndex >= 0)
+ return QDialog::DialogCode::Accepted + customButtonIndex + 1;
+ else
+ return customButtonIndex; // Not found, return -1
}
- return ret;
}
-/*!
- \internal
-
- Returns 0 for RejectedRole and NoRole, 1 for AcceptedRole and YesRole, -1 otherwise
- */
-int QMessageBoxPrivate::dialogCodeForButton(QAbstractButton *button) const
+int QMessageBoxPrivate::dialogCode() const
{
Q_Q(const QMessageBox);
- switch (q->buttonRole(button)) {
- case QMessageBox::AcceptRole:
- case QMessageBox::YesRole:
- return QDialog::Accepted;
- case QMessageBox::RejectRole:
- case QMessageBox::NoRole:
- return QDialog::Rejected;
- default:
- return -1;
+ if (rescode <= QDialog::Accepted) {
+ return rescode;
+ } else if (clickedButton) {
+ switch (q->buttonRole(clickedButton)) {
+ case QMessageBox::AcceptRole:
+ case QMessageBox::YesRole:
+ return QDialog::Accepted;
+ case QMessageBox::RejectRole:
+ case QMessageBox::NoRole:
+ return QDialog::Rejected;
+ default:
+ ;
+ }
}
+
+ return QDialogPrivate::dialogCode();
}
-void QMessageBoxPrivate::_q_buttonClicked(QAbstractButton *button)
+void QMessageBoxPrivate::buttonClicked(QAbstractButton *button)
{
Q_Q(QMessageBox);
#if QT_CONFIG(textedit)
@@ -486,23 +521,26 @@ void QMessageBoxPrivate::setClickedButton(QAbstractButton *button)
emit q->buttonClicked(clickedButton);
auto resultCode = execReturnCode(button);
- close(resultCode);
- finalize(resultCode, dialogCodeForButton(button));
+ q->done(resultCode);
}
-void QMessageBoxPrivate::_q_clicked(QPlatformDialogHelper::StandardButton button, QPlatformDialogHelper::ButtonRole role)
+void QMessageBoxPrivate::helperClicked(QPlatformDialogHelper::StandardButton helperButton, QPlatformDialogHelper::ButtonRole role)
{
+ Q_UNUSED(role);
Q_Q(QMessageBox);
- if (button > QPlatformDialogHelper::LastButton) {
- // It's a custom button, and the QPushButton in options is just a proxy
- // for the button on the platform dialog. Simulate the user clicking it.
- clickedButton = static_cast<QAbstractButton *>(options->customButton(button)->button);
- Q_ASSERT(clickedButton);
- clickedButton->click();
- q->done(role);
- } else {
- q->done(button);
- }
+
+ // Map back to QAbstractButton, so that the message box behaves the same from
+ // the outside, regardless of whether it's backed by a native helper or not.
+ QAbstractButton *dialogButton = helperButton > QPlatformDialogHelper::LastButton ?
+ static_cast<QAbstractButton *>(options->customButton(helperButton)->button) :
+ q->button(QMessageBox::StandardButton(helperButton));
+
+ Q_ASSERT(dialogButton);
+
+ // Simulate click by explicitly clicking the button. This will ensure that
+ // any logic of the button that responds to the click is respected, including
+ // plumbing back to buttonClicked above based on the clicked() signal.
+ dialogButton->click();
}
/*!
@@ -712,7 +750,7 @@ void QMessageBoxPrivate::_q_clicked(QPlatformDialogHelper::StandardButton button
When an escape button can't be determined using these rules,
pressing \uicontrol Esc has no effect.
- \sa QDialogButtonBox, {Standard Dialogs Example}, {Qt Widgets - Application Example}
+ \sa QDialogButtonBox, {Standard Dialogs Example}
*/
/*!
@@ -768,6 +806,12 @@ void QMessageBoxPrivate::_q_clicked(QPlatformDialogHelper::StandardButton button
*/
/*!
+ \enum QMessageBox::Option
+ \since 6.6
+ \value DontUseNativeDialog Don't use the native message dialog.
+*/
+
+/*!
\fn void QMessageBox::buttonClicked(QAbstractButton *button)
This signal is emitted whenever a button is clicked inside the QMessageBox.
@@ -862,12 +906,6 @@ void QMessageBox::addButton(QAbstractButton *button, ButtonRole role)
}
}
- // Add button to native dialog helper, unless it's the details button,
- // since we don't do any plumbing for the button's action in that case.
- if (button != d->detailsButton) {
- d->options->addButton(button->text(),
- static_cast<QPlatformDialogHelper::ButtonRole>(role), button);
- }
d->buttonBox->addButton(button, (QDialogButtonBox::ButtonRole)role);
d->customButtonList.append(button);
d->autoAddOkButton = false;
@@ -992,6 +1030,12 @@ QMessageBox::StandardButton QMessageBox::standardButton(QAbstractButton *button)
Returns a pointer corresponding to the standard button \a which,
or \nullptr if the standard button doesn't exist in this message box.
+ \note Modifying the properties of the returned button may not be reflected
+ in native implementations of the message dialog. To customize dialog
+ buttons add a \l{addButton(QAbstractButton *button, QMessageBox::ButtonRole role)}
+ {custom button} or \l{addButton(const QString &text, QMessageBox::ButtonRole role)}
+ {button title} instead, or set the \l Option::DontUseNativeDialog option.
+
\sa standardButtons, standardButton()
*/
QAbstractButton *QMessageBox::button(StandardButton which) const
@@ -1223,6 +1267,78 @@ QCheckBox* QMessageBox::checkBox() const
}
/*!
+ \since 6.6
+ Sets the given \a option to be enabled if \a on is true; otherwise,
+ clears the given \a option.
+
+ Options (particularly the \l Option::DontUseNativeDialog option) should be set
+ before showing the dialog.
+
+ Setting options while the dialog is visible is not guaranteed to have
+ an immediate effect on the dialog.
+
+ Setting options after changing other properties may cause these
+ values to have no effect.
+
+ \sa options, testOption()
+*/
+void QMessageBox::setOption(QMessageBox::Option option, bool on)
+{
+ const QMessageBox::Options previousOptions = options();
+ if (!(previousOptions & option) != !on)
+ setOptions(previousOptions ^ option);
+}
+
+/*!
+ \since 6.6
+
+ Returns \c true if the given \a option is enabled; otherwise, returns
+ false.
+
+ \sa options, setOption()
+*/
+bool QMessageBox::testOption(QMessageBox::Option option) const
+{
+ Q_D(const QMessageBox);
+ return d->options->testOption(static_cast<QMessageDialogOptions::Option>(option));
+}
+
+void QMessageBox::setOptions(QMessageBox::Options options)
+{
+ Q_D(QMessageBox);
+
+ if (QMessageBox::options() == options)
+ return;
+
+ d->options->setOptions(QMessageDialogOptions::Option(int(options)));
+}
+
+QMessageBox::Options QMessageBox::options() const
+{
+ Q_D(const QMessageBox);
+ return QMessageBox::Options(int(d->options->options()));
+}
+
+/*!
+ \property QMessageBox::options
+ \brief Options that affect the look and feel of the dialog.
+ \since 6.6
+
+ By default, these options are disabled.
+
+ The option \l Option::DontUseNativeDialog should be set
+ before changing dialog properties or showing the dialog.
+
+ Setting options while the dialog is visible is not guaranteed to have
+ an immediate effect on the dialog.
+
+ Setting options after changing other properties may cause these
+ values to have no effect.
+
+ \sa setOption(), testOption()
+*/
+
+/*!
\property QMessageBox::text
\brief the message box text to be displayed.
@@ -1327,7 +1443,7 @@ void QMessageBox::setIcon(Icon icon)
QPixmap QMessageBox::iconPixmap() const
{
Q_D(const QMessageBox);
- return d->iconLabel->pixmap(Qt::ReturnByValue);
+ return d->iconLabel->pixmap();
}
void QMessageBox::setIconPixmap(const QPixmap &pixmap)
@@ -1361,6 +1477,8 @@ void QMessageBox::setTextFormat(Qt::TextFormat format)
d->label->setTextFormat(format);
d->label->setWordWrap(format == Qt::RichText
|| (format == Qt::AutoText && Qt::mightBeRichText(d->label->text())));
+ if (d->informativeLabel)
+ d->informativeLabel->setTextFormat(format);
d->updateSize();
}
@@ -1563,21 +1681,24 @@ void QMessageBox::open(QObject *receiver, const char *member)
QDialog::open();
}
-void QMessageBox::setVisible(bool visible)
+void QMessageBoxPrivate::setVisible(bool visible)
{
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden) != visible)
- return;
+ Q_Q(QMessageBox);
- Q_D(QMessageBox);
- if (d->canBeNativeDialog())
- d->setNativeDialogVisible(visible);
+ // Last minute setup
+ if (autoAddOkButton)
+ q->addButton(QMessageBox::Ok);
+ detectEscapeButton();
+
+ if (canBeNativeDialog())
+ setNativeDialogVisible(visible);
// Update WA_DontShowOnScreen based on whether the native dialog was shown,
// so that QDialog::setVisible(visible) below updates the QWidget state correctly,
// but skips showing the non-native version.
- setAttribute(Qt::WA_DontShowOnScreen, d->nativeDialogInUse);
+ q->setAttribute(Qt::WA_DontShowOnScreen, nativeDialogInUse);
- QDialog::setVisible(visible);
+ QDialogPrivate::setVisible(visible);
}
/*!
@@ -1613,13 +1734,7 @@ QMessageBox::ButtonRole QMessageBox::buttonRole(QAbstractButton *button) const
void QMessageBox::showEvent(QShowEvent *e)
{
Q_D(QMessageBox);
- if (d->autoAddOkButton) {
- addButton(Ok);
- }
- if (d->detailsButton)
- addButton(d->detailsButton, QMessageBox::ActionRole);
d->clickedButton = nullptr;
- d->detectEscapeButton();
d->updateSize();
#if QT_CONFIG(accessibility)
@@ -1644,11 +1759,14 @@ static QMessageBox::StandardButton showNewMessageBox(QWidget *parent,
{
// necessary for source compatibility with Qt 4.0 and 4.1
// handles (Yes, No) and (Yes|Default, No)
- if (defaultButton && !(buttons & defaultButton))
- return (QMessageBox::StandardButton)
- QMessageBoxPrivate::showOldMessageBox(parent, icon, title,
- text, int(buttons),
- int(defaultButton), 0);
+ if (defaultButton && !(buttons & defaultButton)) {
+ const int defaultButtons = defaultButton | QMessageBox::Default;
+ const int otherButtons = buttons.toInt();
+ const int ret = QMessageBoxPrivate::showOldMessageBox(parent, icon, title,
+ text, otherButtons,
+ defaultButtons, 0);
+ return static_cast<QMessageBox::StandardButton>(ret);
+ }
QMessageBox msgBox(icon, title, text, QMessageBox::NoButton, parent);
QDialogButtonBox *buttonBox = msgBox.findChild<QDialogButtonBox*>();
@@ -1817,9 +1935,10 @@ QMessageBox::StandardButton QMessageBox::critical(QWidget *parent, const QString
\li As a last resort it uses the Information icon.
\endlist
- The about box has a single button labelled "OK". On \macos, the
- about box is popped up as a modeless window; on other platforms,
- it is currently application modal.
+ The about box has a single button labelled "OK".
+
+ On \macos, the about box is popped up as a modeless window; on
+ other platforms, it is currently application modal.
\sa QWidget::windowIcon(), QApplication::activeWindow()
*/
@@ -1849,13 +1968,13 @@ void QMessageBox::about(QWidget *parent, const QString &title, const QString &te
// should perhaps be a style hint
#ifdef Q_OS_MAC
oldMsgBox = msgBox;
-#if 0
- // ### doesn't work until close button is enabled in title bar
- msgBox->d_func()->autoAddOkButton = false;
+ auto *d = msgBox->d_func();
+ d->buttonBox->setCenterButtons(true);
+#ifdef Q_OS_IOS
+ msgBox->setModal(true);
#else
- msgBox->d_func()->buttonBox->setCenterButtons(true);
-#endif
msgBox->setModal(false);
+#endif
msgBox->show();
#else
msgBox->exec();
@@ -1872,7 +1991,7 @@ void QMessageBox::about(QWidget *parent, const QString &title, const QString &te
QApplication provides this functionality as a slot.
- On \macos, the about box is popped up as a modeless window; on
+ On \macos, the aboutQt box is popped up as a modeless window; on
other platforms, it is currently application modal.
\sa QApplication::aboutQt()
@@ -1912,15 +2031,14 @@ void QMessageBox::aboutQt(QWidget *parent, const QString &title)
"<p>Qt licensed under GNU (L)GPL is appropriate for the "
"development of Qt&nbsp;applications provided you can comply with the terms "
"and conditions of the respective licenses.</p>"
- "<p>Please see <a href=\"http://%2/\">%2</a> "
+ "<p>Please see <a href=\"https://%2/\">%2</a> "
"for an overview of Qt licensing.</p>"
- "<p>Copyright (C) %1 The Qt Company Ltd and other "
+ "<p>Copyright (C) The Qt Company Ltd. and other "
"contributors.</p>"
"<p>Qt and the Qt logo are trademarks of The Qt Company Ltd.</p>"
- "<p>Qt is The Qt Company Ltd product developed as an open source "
- "project. See <a href=\"http://%3/\">%3</a> for more information.</p>"
- ).arg(QStringLiteral("2022"),
- QStringLiteral("qt.io/licensing"),
+ "<p>Qt is The Qt Company Ltd. product developed as an open source "
+ "project. See <a href=\"https://%3/\">%3</a> for more information.</p>"
+ ).arg(QStringLiteral("qt.io/licensing"),
QStringLiteral("qt.io"));
QMessageBox *msgBox = new QMessageBox(parent);
msgBox->setAttribute(Qt::WA_DeleteOnClose);
@@ -1935,13 +2053,13 @@ void QMessageBox::aboutQt(QWidget *parent, const QString &title)
// should perhaps be a style hint
#ifdef Q_OS_MAC
oldMsgBox = msgBox;
-#if 0
- // ### doesn't work until close button is enabled in title bar
- msgBox->d_func()->autoAddOkButton = false;
+ auto *d = msgBox->d_func();
+ d->buttonBox->setCenterButtons(true);
+#ifdef Q_OS_IOS
+ msgBox->setModal(true);
#else
- msgBox->d_func()->buttonBox->setCenterButtons(true);
-#endif
msgBox->setModal(false);
+#endif
msgBox->show();
#else
msgBox->exec();
@@ -2163,7 +2281,7 @@ int QMessageBox::information(QWidget *parent, const QString &title, const QStrin
}
/*!
- \deprecated since 6.2. Use the overload taking StandardButtons instead.
+ \deprecated [6.2] Use the overload taking StandardButtons instead.
\overload
Displays an information message box with the given \a title and
@@ -2462,7 +2580,7 @@ int QMessageBox::critical(QWidget *parent, const QString &title, const QString&
/*!
- \deprecated
+ \deprecated [6.2]
Returns the text of the message box button \a button, or
an empty string if the message box does not contain the button.
@@ -2483,7 +2601,7 @@ QString QMessageBox::buttonText(int button) const
}
/*!
- \deprecated
+ \deprecated [6.2]
Sets the text of the message box button \a button to \a text.
Setting the text of a button that is not in the message box is
@@ -2566,9 +2684,14 @@ void QMessageBox::setDetailedText(const QString &text)
information to the user, for example describing the consequences of
the situation, or suggestion alternative solutions.
+ The text will be interpreted either as a plain text or as rich text,
+ depending on the text format setting (\l QMessageBox::textFormat).
+ The default setting is Qt::AutoText, i.e., the message box will try
+ to auto-detect the format of the text.
+
By default, this property contains an empty string.
- \sa QMessageBox::text, QMessageBox::detailedText
+ \sa textFormat, QMessageBox::text, QMessageBox::detailedText
*/
QString QMessageBox::informativeText() const
{
@@ -2592,12 +2715,12 @@ void QMessageBox::setInformativeText(const QString &text)
label->setTextInteractionFlags(Qt::TextInteractionFlags(style()->styleHint(QStyle::SH_MessageBox_TextInteractionFlags, nullptr, this)));
label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
label->setOpenExternalLinks(true);
- label->setWordWrap(true);
#ifdef Q_OS_MAC
// apply a smaller font the information label on the mac
label->setFont(qt_app_fonts_hash()->value("QTipLabel"));
#endif
label->setWordWrap(true);
+ label->setTextFormat(d->label->textFormat());
d->informativeLabel = label;
}
d->informativeLabel->setText(text);
@@ -2665,6 +2788,7 @@ QPixmap QMessageBoxPrivate::standardIcon(QMessageBox::Icon icon, QMessageBox *mb
break;
case QMessageBox::Question:
tmpIcon = style->standardIcon(QStyle::SP_MessageBoxQuestion, nullptr, mb);
+ break;
default:
break;
}
@@ -2677,13 +2801,21 @@ QPixmap QMessageBoxPrivate::standardIcon(QMessageBox::Icon icon, QMessageBox *mb
void QMessageBoxPrivate::initHelper(QPlatformDialogHelper *h)
{
- Q_Q(QMessageBox);
- QObject::connect(h, SIGNAL(clicked(QPlatformDialogHelper::StandardButton,QPlatformDialogHelper::ButtonRole)),
- q, SLOT(_q_clicked(QPlatformDialogHelper::StandardButton,QPlatformDialogHelper::ButtonRole)));
- static_cast<QPlatformMessageDialogHelper *>(h)->setOptions(options);
+ auto *messageDialogHelper = static_cast<QPlatformMessageDialogHelper *>(h);
+ QObjectPrivate::connect(messageDialogHelper, &QPlatformMessageDialogHelper::clicked,
+ this, &QMessageBoxPrivate::helperClicked);
+ // Forward state via lambda, so that we can handle addition and removal
+ // of checkbox via setCheckBox() after initializing helper.
+ QObject::connect(messageDialogHelper, &QPlatformMessageDialogHelper::checkBoxStateChanged,
+ q_ptr, [this](Qt::CheckState state) {
+ if (checkbox)
+ checkbox->setCheckState(state);
+ }
+ );
+ messageDialogHelper->setOptions(options);
}
-static QMessageDialogOptions::Icon helperIcon(QMessageBox::Icon i)
+static QMessageDialogOptions::StandardIcon helperIcon(QMessageBox::Icon i)
{
switch (i) {
case QMessageBox::NoIcon:
@@ -2706,6 +2838,36 @@ static QPlatformDialogHelper::StandardButtons helperStandardButtons(QMessageBox
return buttons;
}
+bool QMessageBoxPrivate::canBeNativeDialog() const
+{
+ // Don't use Q_Q here! This function is called from ~QDialog,
+ // so Q_Q calling q_func() invokes undefined behavior (invalid cast in q_func()).
+ const QDialog * const q = static_cast<const QMessageBox*>(q_ptr);
+ if (nativeDialogInUse)
+ return true;
+ if (QCoreApplication::testAttribute(Qt::AA_DontUseNativeDialogs)
+ || q->testAttribute(Qt::WA_DontShowOnScreen)
+ || q->testAttribute(Qt::WA_StyleSheet)
+ || (options->options() & QMessageDialogOptions::Option::DontUseNativeDialog)) {
+ return false;
+ }
+
+ if (strcmp(QMessageBox::staticMetaObject.className(), q->metaObject()->className()) != 0)
+ return false;
+
+#if QT_CONFIG(menu)
+ for (auto *customButton : buttonBox->buttons()) {
+ if (QPushButton *pushButton = qobject_cast<QPushButton *>(customButton)) {
+ // We can't support buttons with menus in native dialogs (yet)
+ if (pushButton->menu())
+ return false;
+ }
+ }
+#endif
+
+ return QDialogPrivate::canBeNativeDialog();
+}
+
void QMessageBoxPrivate::helperPrepareShow(QPlatformDialogHelper *)
{
Q_Q(QMessageBox);
@@ -2715,24 +2877,80 @@ void QMessageBoxPrivate::helperPrepareShow(QPlatformDialogHelper *)
#if QT_CONFIG(textedit)
options->setDetailedText(q->detailedText());
#endif
- options->setIcon(helperIcon(q->icon()));
+ options->setStandardIcon(helperIcon(q->icon()));
options->setIconPixmap(q->iconPixmap());
- options->setStandardButtons(helperStandardButtons(q));
+
+ // Clear up front, since we might have prepared earlier
+ options->clearCustomButtons();
+
+ // Add standard buttons and resolve default/escape button
+ auto standardButtons = helperStandardButtons(q);
+ for (int button = QDialogButtonBox::StandardButton::FirstButton;
+ button <= QDialogButtonBox::StandardButton::LastButton; button <<= 1) {
+ auto *standardButton = buttonBox->button(QDialogButtonBox::StandardButton(button));
+ if (!standardButton)
+ continue;
+
+ if (auto *platformTheme = QGuiApplicationPrivate::platformTheme()) {
+ if (standardButton->text() != platformTheme->standardButtonText(button)) {
+ // The standard button has been customized, so add it as
+ // a custom button instead.
+ const auto buttonRole = buttonBox->buttonRole(standardButton);
+ options->addButton(standardButton->text(),
+ static_cast<QPlatformDialogHelper::ButtonRole>(buttonRole),
+ standardButton, button);
+ standardButtons &= ~QPlatformDialogHelper::StandardButton(button);
+ }
+ }
+
+ if (standardButton == defaultButton)
+ options->setDefaultButton(button);
+ else if (standardButton == detectedEscapeButton)
+ options->setEscapeButton(button);
+ }
+ options->setStandardButtons(standardButtons);
+
+ // Add custom buttons and resolve default/escape button
+ for (auto *customButton : customButtonList) {
+ // Unless it's the details button, since we don't do any
+ // plumbing for the button's action in that case.
+ if (customButton == detailsButton)
+ continue;
+
+ const auto buttonRole = buttonBox->buttonRole(customButton);
+ const int buttonId = options->addButton(customButton->text(),
+ static_cast<QPlatformDialogHelper::ButtonRole>(buttonRole),
+ customButton);
+
+ if (customButton == defaultButton)
+ options->setDefaultButton(buttonId);
+ else if (customButton == detectedEscapeButton)
+ options->setEscapeButton(buttonId);
+ }
+
+ if (checkbox)
+ options->setCheckBox(checkbox->text(), checkbox->checkState());
}
-void QMessageBoxPrivate::helperDone(QDialog::DialogCode code, QPlatformDialogHelper *)
+void qRequireVersion(int argc, char *argv[], QAnyStringView req)
{
- Q_Q(QMessageBox);
- QAbstractButton *button = q->button(QMessageBox::StandardButton(code));
- // If it was a custom button, a custom ID was used, so we won't get a valid pointer here.
- // In that case, clickedButton has already been set in _q_buttonClicked.
- if (button)
- clickedButton = button;
+ const auto required = QVersionNumber::fromString(req).normalized();
+ const auto current = QVersionNumber::fromString(qVersion()).normalized();
+ if (current >= required)
+ return;
+ std::optional<QApplication> application;
+ if (!qApp)
+ application.emplace(argc, argv);
+ const QString message = QApplication::tr("Application \"%1\" requires Qt %2, found Qt %3.")
+ .arg(qAppName(), required.toString(), current.toString());
+ QMessageBox::critical(nullptr, QApplication::tr("Incompatible Qt Library Error"),
+ message, QMessageBox::Abort);
+ qFatal("%ls", qUtf16Printable(message));
}
#if QT_DEPRECATED_SINCE(6,2)
/*!
- \deprecated
+ \deprecated [6.2]
Returns the pixmap used for a standard icon. This allows the
pixmaps to be used in more complex message boxes. \a icon
@@ -2798,7 +3016,7 @@ QPixmap QMessageBox::standardIcon(Icon icon)
/*!
\macro QT_REQUIRE_VERSION(int argc, char **argv, const char *version)
- \relates <QMessageBox>
+ \relates QMessageBox
This macro can be used to ensure that the application is run
with a recent enough version of Qt. This is especially useful
diff --git a/src/widgets/dialogs/qmessagebox.h b/src/widgets/dialogs/qmessagebox.h
index 5d75ffd842..751674466c 100644
--- a/src/widgets/dialogs/qmessagebox.h
+++ b/src/widgets/dialogs/qmessagebox.h
@@ -5,13 +5,14 @@
#define QMESSAGEBOX_H
#include <QtWidgets/qtwidgetsglobal.h>
-
#include <QtWidgets/qdialog.h>
+#include <QtWidgets/qdialogbuttonbox.h>
QT_REQUIRE_CONFIG(messagebox);
QT_BEGIN_NAMESPACE
+class QAnyStringView;
class QLabel;
class QMessageBoxPrivate;
class QAbstractButton;
@@ -31,10 +32,16 @@ class Q_WIDGETS_EXPORT QMessageBox : public QDialog
Q_PROPERTY(QString informativeText READ informativeText WRITE setInformativeText)
Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags
WRITE setTextInteractionFlags)
-
+ Q_PROPERTY(Options options READ options WRITE setOptions)
public:
+ // Keep in sync with MessageBoxOption in qplatformdialoghelper.h
+ enum class Option {
+ DontUseNativeDialog = 0x00000001
+ };
+ Q_FLAG(Option)
+
enum Icon {
- // keep this in sync with QMessageDialogOptions::Icon
+ // keep this in sync with QMessageDialogOptions::StandardIcon
NoIcon = 0,
Information = 1,
Warning = 2,
@@ -58,6 +65,7 @@ public:
NRoles
};
+ Q_ENUM(ButtonRole)
enum StandardButton {
// keep this in sync with QDialogButtonBox::StandardButton and QPlatformDialogHelper::StandardButton
@@ -92,11 +100,14 @@ public:
FlagMask = 0x00000300, // obsolete
ButtonMask = ~FlagMask // obsolete
};
+ Q_ENUM(StandardButton)
+
#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
typedef StandardButton Button;
#endif
-
+ Q_DECLARE_FLAGS(Options, Option)
Q_DECLARE_FLAGS(StandardButtons, StandardButton)
+
Q_FLAG(StandardButtons)
explicit QMessageBox(QWidget *parent = nullptr);
@@ -113,8 +124,6 @@ public:
using QDialog::open;
void open(QObject *receiver, const char *member);
- void setVisible(bool visible) override;
-
QList<QAbstractButton *> buttons() const;
ButtonRole buttonRole(QAbstractButton *button) const;
@@ -151,6 +160,11 @@ public:
void setCheckBox(QCheckBox *cb);
QCheckBox* checkBox() const;
+ void setOption(Option option, bool on = true);
+ bool testOption(Option option) const;
+ void setOptions(Options options);
+ Options options() const;
+
static StandardButton information(QWidget *parent, const QString &title,
const QString &text, StandardButtons buttons = Ok,
StandardButton defaultButton = NoButton);
@@ -293,29 +307,15 @@ protected:
void changeEvent(QEvent *event) override;
private:
- Q_PRIVATE_SLOT(d_func(), void _q_buttonClicked(QAbstractButton *))
- Q_PRIVATE_SLOT(d_func(), void _q_clicked(QPlatformDialogHelper::StandardButton, QPlatformDialogHelper::ButtonRole))
-
Q_DISABLE_COPY(QMessageBox)
Q_DECLARE_PRIVATE(QMessageBox)
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QMessageBox::StandardButtons)
-#define QT_REQUIRE_VERSION(argc, argv, str) { QString s = QString::fromLatin1(str);\
-QString sq = QString::fromLatin1(qVersion()); \
-if ((sq.section(QChar::fromLatin1('.'),0,0).toInt()<<16)+\
-(sq.section(QChar::fromLatin1('.'),1,1).toInt()<<8)+\
-sq.section(QChar::fromLatin1('.'),2,2).toInt()<(s.section(QChar::fromLatin1('.'),0,0).toInt()<<16)+\
-(s.section(QChar::fromLatin1('.'),1,1).toInt()<<8)+\
-s.section(QChar::fromLatin1('.'),2,2).toInt()) { \
-if (!qApp){ \
- new QApplication(argc,argv); \
-} \
-QString s = QApplication::tr("Executable '%1' requires Qt "\
- "%2, found Qt %3.").arg(qAppName()).arg(QString::fromLatin1(\
-str)).arg(QString::fromLatin1(qVersion())); QMessageBox::critical(0, QApplication::tr(\
-"Incompatible Qt Library Error"), s, QMessageBox::Abort, 0); qFatal("%s", s.toLatin1().data()); }}
+Q_WIDGETS_EXPORT void qRequireVersion(int argc, char *argv[], QAnyStringView req);
+
+#define QT_REQUIRE_VERSION(argc, argv, str) qRequireVersion(argc, argv, str);
QT_END_NAMESPACE
diff --git a/src/widgets/dialogs/qprogressdialog.cpp b/src/widgets/dialogs/qprogressdialog.cpp
index d3a714c686..9761bcc828 100644
--- a/src/widgets/dialogs/qprogressdialog.cpp
+++ b/src/widgets/dialogs/qprogressdialog.cpp
@@ -17,15 +17,20 @@
#include "qelapsedtimer.h"
#include "qscopedvaluerollback.h"
#include <private/qdialog_p.h>
+
+#include <QtCore/qpointer.h>
+
#include <limits.h>
+using namespace std::chrono_literals;
+
QT_BEGIN_NAMESPACE
// If the operation is expected to take this long (as predicted by
// progress time), show the progress dialog.
-static const int defaultShowTime = 4000;
+static constexpr auto defaultShowTime = 4000ms;
// Wait at least this long before attempting to make a prediction.
-static const int minWaitTime = 50;
+static constexpr auto minWaitTime = 50ms;
class QProgressDialogPrivate : public QDialogPrivate
{
@@ -52,7 +57,7 @@ public:
QPointer<QObject> receiverToDisconnectOnClose;
QElapsedTimer starttime;
QByteArray memberToDisconnectOnClose;
- int showTime = defaultShowTime;
+ std::chrono::milliseconds showTime = defaultShowTime;
bool processingEvents = false;
bool shownOnce = false;
bool autoClose = true;
@@ -192,10 +197,11 @@ void QProgressDialogPrivate::_q_disconnectOnClose()
A modeless progress dialog is suitable for operations that take
place in the background, where the user is able to interact with the
- application. Such operations are typically based on QTimer (or
- QObject::timerEvent()) or QSocketNotifier; or performed
- in a separate thread. A QProgressBar in the status bar of your main window
- is often an alternative to a modeless progress dialog.
+ application. Such operations are typically based on a timer class,
+ such as QChronoTimer (or the more low-level QObject::timerEvent()) or
+ QSocketNotifier; or performed in a separate thread. A QProgressBar in
+ the status bar of your main window is often an alternative to a modeless
+ progress dialog.
You need to have an event loop to be running, connect the
canceled() signal to a slot that stops the operation, and call \l
@@ -215,7 +221,7 @@ void QProgressDialogPrivate::_q_disconnectOnClose()
\image fusion-progressdialog.png A progress dialog shown in the Fusion widget style.
- \sa QDialog, QProgressBar, {Find Files Example}, {Pixelator Example}
+ \sa QDialog, QProgressBar
*/
@@ -625,23 +631,22 @@ void QProgressDialog::setValue(int progress)
return;
} else {
d->setValueCalled = true;
- bool need_show;
- int elapsed = d->starttime.elapsed();
+ bool need_show = false;
+ using namespace std::chrono;
+ nanoseconds elapsed = d->starttime.durationElapsed();
if (elapsed >= d->showTime) {
need_show = true;
} else {
if (elapsed > minWaitTime) {
- int estimate;
- int totalSteps = maximum() - minimum();
- int myprogress = progress - minimum();
- if (myprogress == 0) myprogress = 1;
- if ((totalSteps - myprogress) >= INT_MAX / elapsed)
- estimate = (totalSteps - myprogress) / myprogress * elapsed;
+ const int totalSteps = maximum() - minimum();
+ const int myprogress = std::max(progress - minimum(), 1);
+ const int remainingSteps = totalSteps - myprogress;
+ nanoseconds estimate;
+ if (remainingSteps >= INT_MAX / elapsed.count())
+ estimate = (remainingSteps / myprogress) * elapsed;
else
- estimate = elapsed * (totalSteps - myprogress) / myprogress;
+ estimate = (elapsed * remainingSteps) / myprogress;
need_show = estimate >= d->showTime;
- } else {
- need_show = false;
}
}
if (need_show) {
@@ -717,17 +722,18 @@ void QProgressDialog::changeEvent(QEvent *ev)
void QProgressDialog::setMinimumDuration(int ms)
{
Q_D(QProgressDialog);
- d->showTime = ms;
+ std::chrono::milliseconds msecs{ms};
+ d->showTime = msecs;
if (d->bar->value() == d->bar->minimum()) {
d->forceTimer->stop();
- d->forceTimer->start(ms);
+ d->forceTimer->start(msecs);
}
}
int QProgressDialog::minimumDuration() const
{
Q_D(const QProgressDialog);
- return d->showTime;
+ return int(d->showTime.count());
}
@@ -743,7 +749,7 @@ void QProgressDialog::closeEvent(QCloseEvent *e)
/*!
\property QProgressDialog::autoReset
- \brief whether the progress dialog calls reset() as soon as value() equals maximum()
+ \brief whether the progress dialog calls reset() as soon as value() equals maximum().
The default is true.
diff --git a/src/widgets/dialogs/qsidebar.cpp b/src/widgets/dialogs/qsidebar.cpp
index 8fb160ab65..581e659a44 100644
--- a/src/widgets/dialogs/qsidebar.cpp
+++ b/src/widgets/dialogs/qsidebar.cpp
@@ -43,6 +43,12 @@ QUrlModel::QUrlModel(QObject *parent) : QStandardItemModel(parent), showFullPath
{
}
+QUrlModel::~QUrlModel()
+{
+ for (const auto &conn : std::as_const(modelConnections))
+ disconnect(conn);
+}
+
/*!
\reimp
*/
@@ -177,11 +183,14 @@ void QUrlModel::setUrl(const QModelIndex &index, const QUrl &url, const QModelIn
setData(index, true, EnabledRole);
}
+ // newIcon could be null if fileSystemModel->iconProvider() returns null
+ if (!newIcon.isNull()) {
// Make sure that we have at least 32x32 images
- const QSize size = newIcon.actualSize(QSize(32,32));
- if (size.width() < 32) {
- QPixmap smallPixmap = newIcon.pixmap(QSize(32, 32));
- newIcon.addPixmap(smallPixmap.scaledToWidth(32, Qt::SmoothTransformation));
+ const QSize size = newIcon.actualSize(QSize(32,32));
+ if (size.width() < 32) {
+ QPixmap smallPixmap = newIcon.pixmap(QSize(32, 32));
+ newIcon.addPixmap(smallPixmap.scaledToWidth(32, Qt::SmoothTransformation));
+ }
}
if (index.data().toString() != newName)
@@ -211,8 +220,9 @@ void QUrlModel::addUrls(const QList<QUrl> &list, int row, bool move)
if (row == -1)
row = rowCount();
row = qMin(row, rowCount());
- for (int i = list.size() - 1; i >= 0; --i) {
- QUrl url = list.at(i);
+ const auto rend = list.crend();
+ for (auto it = list.crbegin(); it != rend; ++it) {
+ QUrl url = *it;
if (!url.isValid() || url.scheme() != "file"_L1)
continue;
//this makes sure the url is clean
@@ -265,21 +275,19 @@ void QUrlModel::setFileSystemModel(QFileSystemModel *model)
if (model == fileSystemModel)
return;
if (fileSystemModel != nullptr) {
- disconnect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(dataChanged(QModelIndex,QModelIndex)));
- disconnect(model, SIGNAL(layoutChanged()),
- this, SLOT(layoutChanged()));
- disconnect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(layoutChanged()));
+ for (const auto &conn : std::as_const(modelConnections))
+ disconnect(conn);
}
fileSystemModel = model;
if (fileSystemModel != nullptr) {
- connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(dataChanged(QModelIndex,QModelIndex)));
- connect(model, SIGNAL(layoutChanged()),
- this, SLOT(layoutChanged()));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(layoutChanged()));
+ modelConnections = {
+ connect(model, &QFileSystemModel::dataChanged,
+ this, &QUrlModel::dataChanged),
+ connect(model, &QFileSystemModel::layoutChanged,
+ this, &QUrlModel::layoutChanged),
+ connect(model, &QFileSystemModel::rowsRemoved,
+ this, &QUrlModel::layoutChanged),
+ };
}
clear();
insertColumns(0, 1);
@@ -312,13 +320,11 @@ void QUrlModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &botto
void QUrlModel::layoutChanged()
{
QStringList paths;
- const int numPaths = watching.size();
- paths.reserve(numPaths);
- for (int i = 0; i < numPaths; ++i)
- paths.append(watching.at(i).path);
+ paths.reserve(watching.size());
+ for (const WatchItem &item : std::as_const(watching))
+ paths.append(item.path);
watching.clear();
- for (int i = 0; i < numPaths; ++i) {
- QString path = paths.at(i);
+ for (const auto &path : paths) {
QModelIndex newIndex = fileSystemModel->index(path);
watching.append({newIndex, path});
if (newIndex.isValid())
@@ -353,14 +359,16 @@ void QSidebar::setModelAndUrls(QFileSystemModel *model, const QList<QUrl> &newUr
setModel(urlModel);
setItemDelegate(new QSideBarDelegate(this));
- connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(clicked(QModelIndex)));
+ connect(selectionModel(), &QItemSelectionModel::currentChanged,
+ this, &QSidebar::clicked);
#if QT_CONFIG(draganddrop)
setDragDropMode(QAbstractItemView::DragDrop);
#endif
+#if QT_CONFIG(menu)
setContextMenuPolicy(Qt::CustomContextMenu);
- connect(this, SIGNAL(customContextMenuRequested(QPoint)),
- this, SLOT(showContextMenu(QPoint)));
+ connect(this, &QSidebar::customContextMenuRequested,
+ this, &QSidebar::showContextMenu);
+#endif
urlModel->setUrls(newUrls);
setCurrentIndex(this->model()->index(0,0));
}
@@ -386,8 +394,8 @@ QSize QSidebar::sizeHint() const
void QSidebar::selectUrl(const QUrl &url)
{
- disconnect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(clicked(QModelIndex)));
+ disconnect(selectionModel(), &QItemSelectionModel::currentChanged,
+ this, &QSidebar::clicked);
selectionModel()->clear();
for (int i = 0; i < model()->rowCount(); ++i) {
@@ -397,8 +405,8 @@ void QSidebar::selectUrl(const QUrl &url)
}
}
- connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(clicked(QModelIndex)));
+ connect(selectionModel(), &QItemSelectionModel::currentChanged,
+ this, &QSidebar::clicked);
}
#if QT_CONFIG(menu)
@@ -414,7 +422,7 @@ void QSidebar::showContextMenu(const QPoint &position)
QAction *action = new QAction(QFileDialog::tr("Remove"), this);
if (indexAt(position).data(QUrlModel::UrlRole).toUrl().path().isEmpty())
action->setEnabled(false);
- connect(action, SIGNAL(triggered()), this, SLOT(removeEntry()));
+ connect(action, &QAction::triggered, this, &QSidebar::removeEntry);
actions.append(action);
}
if (actions.size() > 0)
@@ -429,16 +437,13 @@ void QSidebar::showContextMenu(const QPoint &position)
*/
void QSidebar::removeEntry()
{
- QList<QModelIndex> idxs = selectionModel()->selectedIndexes();
- QList<QPersistentModelIndex> indexes;
- const int numIndexes = idxs.size();
- indexes.reserve(numIndexes);
- for (int i = 0; i < numIndexes; i++)
- indexes.append(idxs.at(i));
-
- for (int i = 0; i < numIndexes; ++i) {
- if (!indexes.at(i).data(QUrlModel::UrlRole).toUrl().path().isEmpty())
- model()->removeRow(indexes.at(i).row());
+ const QList<QModelIndex> idxs = selectionModel()->selectedIndexes();
+ // Create a list of QPersistentModelIndex as the removeRow() calls below could
+ // invalidate the indexes in "idxs"
+ const QList<QPersistentModelIndex> persIndexes(idxs.cbegin(), idxs.cend());
+ for (const QPersistentModelIndex &persistent : persIndexes) {
+ if (!persistent.data(QUrlModel::UrlRole).toUrl().path().isEmpty())
+ model()->removeRow(persistent.row());
}
}
@@ -470,7 +475,7 @@ void QSidebar::focusInEvent(QFocusEvent *event)
bool QSidebar::event(QEvent * event)
{
if (event->type() == QEvent::KeyRelease) {
- QKeyEvent* ke = (QKeyEvent*) event;
+ QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_Delete) {
removeEntry();
return true;
diff --git a/src/widgets/dialogs/qsidebar_p.h b/src/widgets/dialogs/qsidebar_p.h
index 74805e4f2d..ed17a2ff31 100644
--- a/src/widgets/dialogs/qsidebar_p.h
+++ b/src/widgets/dialogs/qsidebar_p.h
@@ -47,6 +47,7 @@ public:
};
QUrlModel(QObject *parent = nullptr);
+ ~QUrlModel();
QStringList mimeTypes() const override;
QMimeData *mimeData(const QModelIndexList &indexes) const override;
@@ -80,6 +81,7 @@ private:
QList<WatchItem> watching;
QList<QUrl> invalidUrls;
+ std::array<QMetaObject::Connection, 3> modelConnections;
};
Q_DECLARE_TYPEINFO(QUrlModel::WatchItem, Q_RELOCATABLE_TYPE);
diff --git a/src/widgets/dialogs/qwizard.cpp b/src/widgets/dialogs/qwizard.cpp
index 7cb2831411..ec082b9a85 100644
--- a/src/widgets/dialogs/qwizard.cpp
+++ b/src/widgets/dialogs/qwizard.cpp
@@ -29,9 +29,8 @@
#include "qstyleoption.h"
#include "qvarlengtharray.h"
#if defined(Q_OS_MACOS)
-#include <QtCore/QMetaMethod>
-#include <QtGui/QGuiApplication>
-#include <qpa/qplatformnativeinterface.h>
+#include <AppKit/AppKit.h>
+#include <QtGui/private/qcoregraphics_p.h>
#elif QT_CONFIG(style_windowsvista)
#include "qwizard_win_p.h"
#include "qtimer.h"
@@ -328,8 +327,7 @@ void QWizardHeader::setup(const QWizardLayoutInfo &info, const QString &title,
{
bool modern = ((info.wizStyle == QWizard::ModernStyle)
#if QT_CONFIG(style_windowsvista)
- || ((info.wizStyle == QWizard::AeroStyle
- && QVistaHelper::vistaState() == QVistaHelper::Classic) || vistaDisabled())
+ || vistaDisabled()
#endif
);
@@ -416,8 +414,8 @@ public:
}
QSize minimumSizeHint() const override {
- if (!pixmap(Qt::ReturnByValue).isNull())
- return pixmap(Qt::ReturnByValue).deviceIndependentSize().toSize();
+ if (!pixmap().isNull())
+ return pixmap().deviceIndependentSize().toSize();
return QFrame::minimumSizeHint();
}
@@ -535,7 +533,6 @@ public:
void updatePixmap(QWizard::WizardPixmap which);
#if QT_CONFIG(style_windowsvista)
bool vistaDisabled() const;
- bool isVistaThemeEnabled(QVistaHelper::VistaState state) const;
bool handleAeroStyleChange();
#endif
bool isVistaThemeEnabled() const;
@@ -604,7 +601,7 @@ public:
QPointer<QShortcut> vistaNextShortcut;
# endif
bool vistaInitPending = true;
- QVistaHelper::VistaState vistaState = QVistaHelper::Dirty;
+ bool vistaDirty = true;
bool vistaStateChanged = false;
bool inHandleAeroStyleChange = false;
#endif
@@ -694,8 +691,9 @@ void QWizardPrivate::reset()
if (current != -1) {
q->currentPage()->hide();
cleanupPagesNotInHistory();
- for (int i = history.size() - 1; i >= 0; --i)
- q->cleanupPage(history.at(i));
+ const auto end = history.crend();
+ for (auto it = history.crbegin(); it != end; ++it)
+ q->cleanupPage(*it);
history.clear();
for (QWizardPage *page : std::as_const(pageMap))
page->d_func()->initialized = false;
@@ -865,7 +863,7 @@ QWizardLayoutInfo QWizardPrivate::layoutInfoForCurrentPage()
QStyleOption option;
option.initFrom(q);
- const int layoutHorizontalSpacing = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing, &option);
+ const int layoutHorizontalSpacing = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing, &option, q);
info.topLevelMarginLeft = style->pixelMetric(QStyle::PM_LayoutLeftMargin, nullptr, q);
info.topLevelMarginRight = style->pixelMetric(QStyle::PM_LayoutRightMargin, nullptr, q);
info.topLevelMarginTop = style->pixelMetric(QStyle::PM_LayoutTopMargin, nullptr, q);
@@ -877,7 +875,7 @@ QWizardLayoutInfo QWizardPrivate::layoutInfoForCurrentPage()
info.hspacing = (layoutHorizontalSpacing == -1)
? style->layoutSpacing(QSizePolicy::DefaultType, QSizePolicy::DefaultType, Qt::Horizontal)
: layoutHorizontalSpacing;
- info.vspacing = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing, &option);
+ info.vspacing = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing, &option, q);
info.buttonSpacing = (layoutHorizontalSpacing == -1)
? style->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal)
: layoutHorizontalSpacing;
@@ -888,7 +886,7 @@ QWizardLayoutInfo QWizardPrivate::layoutInfoForCurrentPage()
info.wizStyle = wizStyle;
if (info.wizStyle == QWizard::AeroStyle
#if QT_CONFIG(style_windowsvista)
- && (QVistaHelper::vistaState() == QVistaHelper::Classic || vistaDisabled())
+ && vistaDisabled()
#endif
)
info.wizStyle = QWizard::ModernStyle;
@@ -1423,10 +1421,9 @@ void QWizardPrivate::updateButtonTexts()
void QWizardPrivate::updateButtonLayout()
{
if (buttonsHaveCustomLayout) {
- QVarLengthArray<QWizard::WizardButton, QWizard::NButtons> array(buttonsCustomLayout.size());
- for (int i = 0; i < buttonsCustomLayout.size(); ++i)
- array[i] = buttonsCustomLayout.at(i);
- setButtonLayout(array.constData(), array.size());
+ QVarLengthArray<QWizard::WizardButton, QWizard::NButtons> array{
+ buttonsCustomLayout.cbegin(), buttonsCustomLayout.cend()};
+ setButtonLayout(array.constData(), int(array.size()));
} else {
// Positions:
// Help Stretch Custom1 Custom2 Custom3 Cancel Back Next Commit Finish Cancel Help
@@ -1520,13 +1517,6 @@ bool QWizardPrivate::vistaDisabled() const
return v.isValid() && v.toBool();
}
-bool QWizardPrivate::isVistaThemeEnabled(QVistaHelper::VistaState state) const
-{
- return wizStyle == QWizard::AeroStyle
- && QVistaHelper::vistaState() == state
- && !vistaDisabled();
-}
-
bool QWizardPrivate::handleAeroStyleChange()
{
Q_Q(QWizard);
@@ -1550,25 +1540,17 @@ bool QWizardPrivate::handleAeroStyleChange()
if (isVistaThemeEnabled()) {
const int topOffset = vistaHelper->topOffset(q);
const int topPadding = vistaHelper->topPadding(q);
- if (isVistaThemeEnabled(QVistaHelper::VistaAero)) {
- if (isWindow) {
- vistaHelper->setDWMTitleBar(QVistaHelper::ExtendedTitleBar);
- q->installEventFilter(vistaHelper);
- }
- q->setMouseTracking(true);
- antiFlickerWidget->move(0, vistaHelper->titleBarSize() + topOffset);
- vistaHelper->backButton()->move(
- 0, topOffset // ### should ideally work without the '+ 1'
- - qMin(topOffset, topPadding + 1));
- vistaMargins = true;
- vistaHelper->backButton()->show();
- } else {
- if (isWindow)
- vistaHelper->setDWMTitleBar(QVistaHelper::NormalTitleBar);
- q->setMouseTracking(true);
- antiFlickerWidget->move(0, topOffset);
- vistaHelper->backButton()->move(0, -1); // ### should ideally work with (0, 0)
+ if (isWindow) {
+ vistaHelper->setDWMTitleBar(QVistaHelper::ExtendedTitleBar);
+ q->installEventFilter(vistaHelper);
}
+ q->setMouseTracking(true);
+ antiFlickerWidget->move(0, vistaHelper->titleBarSize() + topOffset);
+ vistaHelper->backButton()->move(
+ 0, topOffset // ### should ideally work without the '+ 1'
+ - qMin(topOffset, topPadding + 1));
+ vistaMargins = true;
+ vistaHelper->backButton()->show();
if (isWindow)
vistaHelper->setTitleBarIconAndCaptionVisible(false);
QObject::connect(
@@ -1597,8 +1579,7 @@ bool QWizardPrivate::handleAeroStyleChange()
bool QWizardPrivate::isVistaThemeEnabled() const
{
#if QT_CONFIG(style_windowsvista)
- return isVistaThemeEnabled(QVistaHelper::VistaAero)
- || isVistaThemeEnabled(QVistaHelper::VistaBasic);
+ return wizStyle == QWizard::AeroStyle && !vistaDisabled();
#else
return false;
#endif
@@ -1723,23 +1704,19 @@ void QWizardPrivate::setStyle(QStyle *style)
}
#ifdef Q_OS_MACOS
-
QPixmap QWizardPrivate::findDefaultBackgroundPixmap()
{
- QGuiApplication *app = qobject_cast<QGuiApplication *>(QCoreApplication::instance());
- if (!app)
- return QPixmap();
- QPlatformNativeInterface *platformNativeInterface = app->platformNativeInterface();
- int at = platformNativeInterface->metaObject()->indexOfMethod("defaultBackgroundPixmapForQWizard()");
- if (at == -1)
- return QPixmap();
- QMetaMethod defaultBackgroundPixmapForQWizard = platformNativeInterface->metaObject()->method(at);
- QPixmap result;
- if (!defaultBackgroundPixmapForQWizard.invoke(platformNativeInterface, Q_RETURN_ARG(QPixmap, result)))
- return QPixmap();
- return result;
-}
+ auto *keyboardAssistantURL = [NSWorkspace.sharedWorkspace
+ URLForApplicationWithBundleIdentifier:@"com.apple.KeyboardSetupAssistant"];
+ auto *keyboardAssistantBundle = [NSBundle bundleWithURL:keyboardAssistantURL];
+ auto *assistantBackground = [keyboardAssistantBundle imageForResource:@"Background"];
+ auto size = QSizeF::fromCGSize(assistantBackground.size);
+ static const QSizeF expectedSize(242, 414);
+ if (size == expectedSize)
+ return qt_mac_toQPixmap(assistantBackground, size);
+ return QPixmap();
+}
#endif
#if QT_CONFIG(style_windowsvista)
@@ -1755,13 +1732,6 @@ void QWizardAntiFlickerWidget::paintEvent(QPaintEvent *)
painter.fillRect(0, buttonLayoutTop, width(), height() - buttonLayoutTop, brush);
painter.setPen(QPen(QBrush(QColor(223, 223, 223)), 0)); // ### hardcoded for now
painter.drawLine(0, buttonLayoutTop, width(), buttonLayoutTop);
- if (wizardPrivate->isVistaThemeEnabled(QVistaHelper::VistaBasic)) {
- if (window()->isActiveWindow())
- painter.setPen(QPen(QBrush(QColor(169, 191, 214)), 0)); // ### hardcoded for now
- else
- painter.setPen(QPen(QBrush(QColor(182, 193, 204)), 0)); // ### hardcoded for now
- painter.drawLine(0, 0, width(), 0);
- }
}
}
#endif
@@ -1791,9 +1761,8 @@ void QWizardAntiFlickerWidget::paintEvent(QPaintEvent *)
\section1 A Trivial Example
The following example illustrates how to create wizard pages and
- add them to a wizard. For more advanced examples, see
- \l{dialogs/classwizard}{Class Wizard} and \l{dialogs/licensewizard}{License
- Wizard}.
+ add them to a wizard. For more advanced examples, see the
+ \l{dialogs/licensewizard}{License Wizard}.
\snippet dialogs/trivialwizard/trivialwizard.cpp 1
\snippet dialogs/trivialwizard/trivialwizard.cpp 3
@@ -1922,12 +1891,7 @@ void QWizardAntiFlickerWidget::paintEvent(QPaintEvent *)
To register a field, call QWizardPage::registerField() field.
For example:
- \snippet dialogs/classwizard/classwizard.cpp 8
- \dots
- \snippet dialogs/classwizard/classwizard.cpp 10
- \snippet dialogs/classwizard/classwizard.cpp 11
- \dots
- \snippet dialogs/classwizard/classwizard.cpp 13
+ \snippet dialogs/licensewizard/licensewizard.cpp 21
The above code registers three fields, \c className, \c
baseClass, and \c qobjectMacro, which are associated with three
@@ -1938,11 +1902,11 @@ void QWizardAntiFlickerWidget::paintEvent(QPaintEvent *)
The fields of any page are accessible from any other page. For
example:
- \snippet dialogs/classwizard/classwizard.cpp 17
+ \snippet dialogs/licensewizard/licensewizard.cpp 27
Here, we call QWizardPage::field() to access the contents of the
- \c className field (which was defined in the \c ClassInfoPage)
- and use it to initialize the \c OutputFilePage. The field's
+ \c details.email field (which was defined in the \c DetailsPage)
+ and use it to initialize the \c ConclusionPage. The field's
contents is returned as a QVariant.
When we create a field using QWizardPage::registerField(), we
@@ -1985,15 +1949,13 @@ void QWizardAntiFlickerWidget::paintEvent(QPaintEvent *)
\section1 Creating Linear Wizards
Most wizards have a linear structure, with page 1 followed by
- page 2 and so on until the last page. The \l{dialogs/classwizard}{Class
- Wizard} example is such a wizard. With QWizard, linear wizards
+ page 2 and so on until the last page. The \l{dialogs/trivialwizard}
+ {Trivial Wizard} example is such a wizard. With QWizard, linear wizards
are created by instantiating the \l{QWizardPage}s and inserting
them using addPage(). By default, the pages are shown in the
order in which they were added. For example:
- \snippet dialogs/classwizard/classwizard.cpp 0
- \dots
- \snippet dialogs/classwizard/classwizard.cpp 2
+ \snippet dialogs/trivialwizard/trivialwizard.cpp linearAddPage
When a page is about to be shown, QWizard calls initializePage()
(which in turn calls QWizardPage::initializePage()) to fill the
@@ -2063,7 +2025,7 @@ void QWizardAntiFlickerWidget::paintEvent(QPaintEvent *)
\snippet dialogs/licensewizard/licensewizard.cpp 27
- \sa QWizardPage, {Class Wizard Example}, {License Wizard Example}
+ \sa QWizardPage, {Trivial Wizard Example}, {License Wizard Example}
*/
/*!
@@ -2226,8 +2188,8 @@ void QWizard::setPage(int theid, QWizardPage *page)
page->setParent(d->pageFrame);
QList<QWizardField> &pendingFields = page->d_func()->pendingFields;
- for (int i = 0; i < pendingFields.size(); ++i)
- d->addField(pendingFields.at(i));
+ for (const auto &field : std::as_const(pendingFields))
+ d->addField(field);
pendingFields.clear();
connect(page, SIGNAL(completeChanged()), this, SLOT(_q_updateButtonStates()));
@@ -2845,7 +2807,7 @@ void QWizard::setPixmap(WizardPixmap which, const QPixmap &pixmap)
Returns the pixmap set for role \a which.
By default, the only pixmap that is set is the BackgroundPixmap on
- \macos version 10.13 and earlier.
+ \macos.
\sa QWizardPage::pixmap(), {Elements of a Wizard Page}
*/
@@ -3171,12 +3133,7 @@ bool QWizard::event(QEvent *event)
#if QT_CONFIG(style_windowsvista)
else if (event->type() == QEvent::Show && d->vistaInitPending) {
d->vistaInitPending = false;
- // Do not force AeroStyle when in Classic theme.
- // Note that d->handleAeroStyleChange() needs to be called in any case as it does some
- // necessary initialization, like ensures that the Aero specific back button is hidden if
- // Aero theme isn't active.
- if (QVistaHelper::vistaState() != QVistaHelper::Classic)
- d->wizStyle = AeroStyle;
+ d->wizStyle = AeroStyle;
d->handleAeroStyleChange();
}
else if (d->isVistaThemeEnabled()) {
@@ -3206,8 +3163,7 @@ void QWizard::resizeEvent(QResizeEvent *event)
#if QT_CONFIG(style_windowsvista)
if (d->isVistaThemeEnabled()) {
heightOffset = d->vistaHelper->topOffset(this);
- if (d->isVistaThemeEnabled(QVistaHelper::VistaAero))
- heightOffset += d->vistaHelper->titleBarSize();
+ heightOffset += d->vistaHelper->titleBarSize();
}
#endif
d->antiFlickerWidget->resize(event->size().width(), event->size().height() - heightOffset);
@@ -3234,11 +3190,6 @@ void QWizard::paintEvent(QPaintEvent * event)
}
#if QT_CONFIG(style_windowsvista)
else if (d->isVistaThemeEnabled()) {
- if (d->isVistaThemeEnabled(QVistaHelper::VistaBasic)) {
- QPainter painter(this);
- QColor color = d->vistaHelper->basicWindowFrameColor();
- painter.fillRect(0, 0, width(), QVistaHelper::topOffset(this), color);
- }
d->vistaHelper->paintEvent(event);
}
#else
@@ -3257,12 +3208,12 @@ bool QWizard::nativeEvent(const QByteArray &eventType, void *message, qintptr *r
if (d->isVistaThemeEnabled() && eventType == "windows_generic_MSG") {
MSG *windowsMessage = static_cast<MSG *>(message);
const bool winEventResult = d->vistaHelper->handleWinEvent(windowsMessage, result);
- if (QVistaHelper::vistaState() != d->vistaState) {
+ if (d->vistaDirty) {
// QTBUG-78300: When Qt::AA_NativeWindows is set, delay further
// window creation until after the platform window creation events.
if (windowsMessage->message == WM_GETICON) {
d->vistaStateChanged = true;
- d->vistaState = QVistaHelper::vistaState();
+ d->vistaDirty = false;
setWizardStyle(AeroStyle);
}
}
@@ -3448,7 +3399,7 @@ int QWizard::nextId() const
using registerField() and can be accessed at any time using
field() and setField().
- \sa QWizard, {Class Wizard Example}, {License Wizard Example}
+ \sa QWizard, {Trivial Wizard Example}, {License Wizard Example}
*/
/*!
@@ -3591,7 +3542,7 @@ QPixmap QWizardPage::pixmap(QWizard::WizardPixmap which) const
fields are properly initialized based on fields from previous
pages. For example:
- \snippet dialogs/classwizard/classwizard.cpp 17
+ \snippet dialogs/licensewizard/licensewizard.cpp 27
The default implementation does nothing.
@@ -3668,8 +3619,9 @@ bool QWizardPage::isComplete() const
return true;
const QList<QWizardField> &wizardFields = d->wizard->d_func()->fields;
- for (int i = wizardFields.size() - 1; i >= 0; --i) {
- const QWizardField &field = wizardFields.at(i);
+ const auto end = wizardFields.crend();
+ for (auto it = wizardFields.crbegin(); it != end; ++it) {
+ const QWizardField &field = *it;
if (field.page == this && field.mandatory) {
QVariant value = field.object->property(field.property);
if (value == field.initialValue)
@@ -3895,7 +3847,7 @@ void QWizardPage::setField(const QString &name, const QVariant &value)
Example:
- \snippet dialogs/classwizard/classwizard.cpp 17
+ \snippet dialogs/licensewizard/licensewizard.cpp accessField
\sa QWizard::field(), setField(), registerField()
*/
diff --git a/src/widgets/dialogs/qwizard_win.cpp b/src/widgets/dialogs/qwizard_win.cpp
index e95f0e3b7b..2c4f049e88 100644
--- a/src/widgets/dialogs/qwizard_win.cpp
+++ b/src/widgets/dialogs/qwizard_win.cpp
@@ -33,9 +33,7 @@ Q_DECLARE_METATYPE(QMargins)
QT_BEGIN_NAMESPACE
-int QVistaHelper::instanceCount = 0;
-int QVistaHelper::m_devicePixelRatio = 1;
-QVistaHelper::VistaState QVistaHelper::cachedVistaState = QVistaHelper::Dirty;
+qreal QVistaHelper::m_devicePixelRatio = 1.0;
/******************************************************************************
** QVistaBackButton
@@ -84,7 +82,7 @@ void QVistaBackButton::paintEvent(QPaintEvent *)
RECT clipRect;
int xoffset = origin.x() + QWidget::mapToParent(r.topLeft()).x() - 1;
int yoffset = origin.y() + QWidget::mapToParent(r.topLeft()).y() - 1;
- const int dpr = devicePixelRatio();
+ const qreal dpr = devicePixelRatio();
const QRect rDp = QRect(r.topLeft() * dpr, r.size() * dpr);
const int xoffsetDp = xoffset * dpr;
const int yoffsetDp = yoffset * dpr;
@@ -118,18 +116,14 @@ QVistaHelper::QVistaHelper(QWizard *wizard)
, backButton_(0)
{
QVistaHelper::m_devicePixelRatio = wizard->devicePixelRatio();
- if (instanceCount++ == 0)
- cachedVistaState = Dirty;
+
backButton_ = new QVistaBackButton(wizard);
backButton_->hide();
iconSpacing = QStyleHelper::dpiScaled(7, wizard);
}
-QVistaHelper::~QVistaHelper()
-{
- --instanceCount;
-}
+QVistaHelper::~QVistaHelper() = default;
void QVistaHelper::updateCustomMargins(bool vistaMargins)
{
@@ -150,24 +144,6 @@ void QVistaHelper::updateCustomMargins(bool vistaMargins)
}
}
-bool QVistaHelper::isCompositionEnabled()
-{
- return true;
-}
-
-bool QVistaHelper::isThemeActive()
-{
- return IsThemeActive();
-}
-
-QVistaHelper::VistaState QVistaHelper::vistaState()
-{
- if (instanceCount == 0 || cachedVistaState == Dirty)
- cachedVistaState =
- isCompositionEnabled() ? VistaAero : isThemeActive() ? VistaBasic : Classic;
- return cachedVistaState;
-}
-
void QVistaHelper::disconnectBackButton()
{
if (backButton_) // Leave QStyleSheetStyle's connections on destroyed() intact.
@@ -188,18 +164,16 @@ QColor QVistaHelper::basicWindowFrameColor()
bool QVistaHelper::setDWMTitleBar(TitleBarChangeType type)
{
- bool value = false;
- if (vistaState() == VistaAero) {
- MARGINS mar = {0, 0, 0, 0};
- if (type == NormalTitleBar)
- mar.cyTopHeight = 0;
- else
- mar.cyTopHeight = (titleBarSize() + topOffset(wizard)) * QVistaHelper::m_devicePixelRatio;
- if (const HWND wizardHandle = wizardHWND())
- if (SUCCEEDED(DwmExtendFrameIntoClientArea(wizardHandle, &mar)))
- value = true;
+ MARGINS mar = {0, 0, 0, 0};
+ if (type == NormalTitleBar)
+ mar.cyTopHeight = 0;
+ else
+ mar.cyTopHeight = (titleBarSize() + topOffset(wizard)) * QVistaHelper::m_devicePixelRatio;
+ if (const HWND wizardHandle = wizardHWND()) {
+ if (SUCCEEDED(DwmExtendFrameIntoClientArea(wizardHandle, &mar)))
+ return true;
}
- return value;
+ return false;
}
Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &);
@@ -235,7 +209,7 @@ void QVistaHelper::drawTitleBar(QPainter *painter)
const bool isWindow = wizard->isWindow();
const HDC hdc = QVistaHelper::backingStoreDC(wizard, &origin);
- if (vistaState() == VistaAero && isWindow)
+ if (isWindow)
drawBlackRect(QRect(0, 0, wizard->width(),
titleBarSize() + topOffset(wizard)), hdc);
// The button is positioned in QWizardPrivate::handleAeroStyleChange(),
@@ -250,15 +224,9 @@ void QVistaHelper::drawTitleBar(QPainter *painter)
font = QApplication::font("QMdiSubWindowTitleBar");
const QFontMetrics fontMetrics(font);
const QRect brect = fontMetrics.boundingRect(text);
- int textHeight = brect.height();
- int textWidth = brect.width();
- int glowOffset = 0;
-
- if (vistaState() == VistaAero) {
- glowOffset = glowSize(wizard);
- textHeight += 2 * glowOffset;
- textWidth += 2 * glowOffset;
- }
+ const int glowOffset = glowSize(wizard);
+ int textHeight = brect.height() + 2 * glowOffset;
+ int textWidth = brect.width() + 2 * glowOffset;
const int titleLeft = (wizard->layoutDirection() == Qt::LeftToRight
? titleOffset() - glowOffset
@@ -365,11 +333,8 @@ void QVistaHelper::mouseEvent(QEvent *event)
bool QVistaHelper::handleWinEvent(MSG *message, qintptr *result)
{
- if (message->message == WM_THEMECHANGED || message->message == WM_DWMCOMPOSITIONCHANGED)
- cachedVistaState = Dirty;
-
bool status = false;
- if (wizard->wizardStyle() == QWizard::AeroStyle && vistaState() == VistaAero) {
+ if (wizard->wizardStyle() == QWizard::AeroStyle) {
status = winEvent(message, result);
if (message->message == WM_NCPAINT)
wizard->update();
@@ -382,8 +347,6 @@ void QVistaHelper::resizeEvent(QResizeEvent * event)
Q_UNUSED(event);
rtTop = QRect (0, 0, wizard->width(), frameSize());
int height = captionSize() + topOffset(wizard);
- if (vistaState() == VistaBasic)
- height -= titleBarSize();
rtTitle = QRect (0, frameSize(), wizard->width(), height);
}
@@ -422,7 +385,7 @@ void QVistaHelper::mouseMoveEvent(QMouseEvent *event)
}
wizard->setGeometry(rect);
- } else if (vistaState() == VistaAero) {
+ } else {
setMouseCursor(event->pos());
}
event->ignore();
@@ -440,11 +403,10 @@ void QVistaHelper::mousePressEvent(QMouseEvent *event)
if (rtTitle.contains(event->pos())) {
change = movePosition;
} else if (rtTop.contains(event->pos()))
- change = (vistaState() == VistaAero) ? resizeTop : movePosition;
+ change = resizeTop;
if (change != noChange) {
- if (vistaState() == VistaAero)
- setMouseCursor(event->pos());
+ setMouseCursor(event->pos());
pressed = true;
pressedPos = event->pos();
} else {
@@ -458,8 +420,7 @@ void QVistaHelper::mouseReleaseEvent(QMouseEvent *event)
if (pressed) {
pressed = false;
wizard->releaseMouse();
- if (vistaState() == VistaAero)
- setMouseCursor(event->pos());
+ setMouseCursor(event->pos());
}
event->ignore();
}
@@ -547,95 +508,88 @@ HWND QVistaHelper::wizardHWND() const
return 0;
}
-bool QVistaHelper::drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc)
+void QVistaHelper::drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc)
{
- bool value = false;
- if (vistaState() == VistaAero) {
- const QRect rectDp = QRect(rect.topLeft() * QVistaHelper::m_devicePixelRatio,
- rect.size() * QVistaHelper::m_devicePixelRatio);
- const HANDLE hTheme = OpenThemeData(GetDesktopWindow(), L"WINDOW");
- if (!hTheme) return false;
- // Set up a memory DC and bitmap that we'll draw into
- HDC dcMem;
- HBITMAP bmp;
- BITMAPINFO dib;
- ZeroMemory(&dib, sizeof(dib));
- dcMem = CreateCompatibleDC(hdc);
-
- dib.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- dib.bmiHeader.biWidth = rectDp.width();
- dib.bmiHeader.biHeight = -rectDp.height();
- dib.bmiHeader.biPlanes = 1;
- dib.bmiHeader.biBitCount = 32;
- dib.bmiHeader.biCompression = BI_RGB;
-
- bmp = CreateDIBSection(hdc, &dib, DIB_RGB_COLORS, NULL, NULL, 0);
-
- // Set up the DC
- const LOGFONT captionLogFont = getCaptionLogFont(hTheme);
- const HFONT hCaptionFont = CreateFontIndirect(&captionLogFont);
- auto hOldBmp = reinterpret_cast<HBITMAP>(SelectObject(dcMem, (HGDIOBJ) bmp));
- auto hOldFont = reinterpret_cast<HFONT>(SelectObject(dcMem, (HGDIOBJ) hCaptionFont));
-
- // Draw the text!
- DTTOPTS dto;
- memset(&dto, 0, sizeof(dto));
- dto.dwSize = sizeof(dto);
- const UINT uFormat = DT_SINGLELINE|DT_CENTER|DT_VCENTER|DT_NOPREFIX;
- RECT rctext ={0,0, rectDp.width(), rectDp.height()};
-
- dto.dwFlags = DTT_COMPOSITED|DTT_GLOWSIZE;
- dto.iGlowSize = glowSize(wizard);
-
- DrawThemeTextEx(hTheme, dcMem, 0, 0, reinterpret_cast<LPCWSTR>(text.utf16()), -1, uFormat, &rctext, &dto );
- BitBlt(hdc, rectDp.left(), rectDp.top(), rectDp.width(), rectDp.height(), dcMem, 0, 0, SRCCOPY);
- SelectObject(dcMem, (HGDIOBJ) hOldBmp);
- SelectObject(dcMem, (HGDIOBJ) hOldFont);
- DeleteObject(bmp);
- DeleteObject(hCaptionFont);
- DeleteDC(dcMem);
- //ReleaseDC(hwnd, hdc);
- } else if (vistaState() == VistaBasic) {
- painter->drawText(rect, text);
- }
- return value;
-}
+ Q_UNUSED(painter);
-bool QVistaHelper::drawBlackRect(const QRect &rect, HDC hdc)
-{
- bool value = false;
- if (vistaState() == VistaAero) {
- // Set up a memory DC and bitmap that we'll draw into
- const QRect rectDp = QRect(rect.topLeft() * QVistaHelper::m_devicePixelRatio,
+ const QRect rectDp = QRect(rect.topLeft() * QVistaHelper::m_devicePixelRatio,
+ rect.size() * QVistaHelper::m_devicePixelRatio);
+ const HANDLE hTheme = OpenThemeData(GetDesktopWindow(), L"WINDOW");
+ if (!hTheme)
+ return;
+ // Set up a memory DC and bitmap that we'll draw into
+ HDC dcMem;
+ HBITMAP bmp;
+ BITMAPINFO dib;
+ ZeroMemory(&dib, sizeof(dib));
+ dcMem = CreateCompatibleDC(hdc);
+
+ dib.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ dib.bmiHeader.biWidth = rectDp.width();
+ dib.bmiHeader.biHeight = -rectDp.height();
+ dib.bmiHeader.biPlanes = 1;
+ dib.bmiHeader.biBitCount = 32;
+ dib.bmiHeader.biCompression = BI_RGB;
+
+ bmp = CreateDIBSection(hdc, &dib, DIB_RGB_COLORS, NULL, NULL, 0);
+
+ // Set up the DC
+ const LOGFONT captionLogFont = getCaptionLogFont(hTheme);
+ const HFONT hCaptionFont = CreateFontIndirect(&captionLogFont);
+ auto hOldBmp = reinterpret_cast<HBITMAP>(SelectObject(dcMem, (HGDIOBJ) bmp));
+ auto hOldFont = reinterpret_cast<HFONT>(SelectObject(dcMem, (HGDIOBJ) hCaptionFont));
+
+ // Draw the text!
+ DTTOPTS dto;
+ memset(&dto, 0, sizeof(dto));
+ dto.dwSize = sizeof(dto);
+ const UINT uFormat = DT_SINGLELINE|DT_CENTER|DT_VCENTER|DT_NOPREFIX;
+ RECT rctext ={0,0, rectDp.width(), rectDp.height()};
+
+ dto.dwFlags = DTT_COMPOSITED|DTT_GLOWSIZE;
+ dto.iGlowSize = glowSize(wizard);
+
+ DrawThemeTextEx(hTheme, dcMem, 0, 0, reinterpret_cast<LPCWSTR>(text.utf16()), -1, uFormat, &rctext, &dto );
+ BitBlt(hdc, rectDp.left(), rectDp.top(), rectDp.width(), rectDp.height(), dcMem, 0, 0, SRCCOPY);
+ SelectObject(dcMem, (HGDIOBJ) hOldBmp);
+ SelectObject(dcMem, (HGDIOBJ) hOldFont);
+ DeleteObject(bmp);
+ DeleteObject(hCaptionFont);
+ DeleteDC(dcMem);
+ //ReleaseDC(hwnd, hdc);
+}
+
+void QVistaHelper::drawBlackRect(const QRect &rect, HDC hdc)
+{
+ // Set up a memory DC and bitmap that we'll draw into
+ const QRect rectDp = QRect(rect.topLeft() * QVistaHelper::m_devicePixelRatio,
rect.size() * QVistaHelper::m_devicePixelRatio);
- HDC dcMem;
- HBITMAP bmp;
- BITMAPINFO dib;
- ZeroMemory(&dib, sizeof(dib));
- dcMem = CreateCompatibleDC(hdc);
-
- dib.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- dib.bmiHeader.biWidth = rectDp.width();
- dib.bmiHeader.biHeight = -rectDp.height();
- dib.bmiHeader.biPlanes = 1;
- dib.bmiHeader.biBitCount = 32;
- dib.bmiHeader.biCompression = BI_RGB;
-
- bmp = CreateDIBSection(hdc, &dib, DIB_RGB_COLORS, NULL, NULL, 0);
- auto hOldBmp = reinterpret_cast<HBITMAP>(SelectObject(dcMem, (HGDIOBJ) bmp));
-
- BitBlt(hdc, rectDp.left(), rectDp.top(), rectDp.width(), rectDp.height(), dcMem, 0, 0, SRCCOPY);
- SelectObject(dcMem, (HGDIOBJ) hOldBmp);
-
- DeleteObject(bmp);
- DeleteDC(dcMem);
- }
- return value;
+ HDC dcMem;
+ HBITMAP bmp;
+ BITMAPINFO dib;
+ ZeroMemory(&dib, sizeof(dib));
+ dcMem = CreateCompatibleDC(hdc);
+
+ dib.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ dib.bmiHeader.biWidth = rectDp.width();
+ dib.bmiHeader.biHeight = -rectDp.height();
+ dib.bmiHeader.biPlanes = 1;
+ dib.bmiHeader.biBitCount = 32;
+ dib.bmiHeader.biCompression = BI_RGB;
+
+ bmp = CreateDIBSection(hdc, &dib, DIB_RGB_COLORS, NULL, NULL, 0);
+ auto hOldBmp = reinterpret_cast<HBITMAP>(SelectObject(dcMem, (HGDIOBJ) bmp));
+
+ BitBlt(hdc, rectDp.left(), rectDp.top(), rectDp.width(), rectDp.height(), dcMem, 0, 0, SRCCOPY);
+ SelectObject(dcMem, (HGDIOBJ) hOldBmp);
+
+ DeleteObject(bmp);
+ DeleteDC(dcMem);
}
int QVistaHelper::frameSizeDp()
{
- return GetSystemMetrics(SM_CYSIZEFRAME);
+ return GetSystemMetrics(SM_CXSIZEFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER);
}
int QVistaHelper::captionSizeDp()
@@ -661,8 +615,6 @@ int QVistaHelper::glowSize(const QPaintDevice *device)
int QVistaHelper::topOffset(const QPaintDevice *device)
{
- if (vistaState() != VistaAero)
- return titleBarSize() + 3;
static const int aeroOffset = QStyleHelper::dpiScaled(13, device);
return aeroOffset + titleBarSize();
}
diff --git a/src/widgets/dialogs/qwizard_win_p.h b/src/widgets/dialogs/qwizard_win_p.h
index 71dfc15b4d..ce0f7b85b3 100644
--- a/src/widgets/dialogs/qwizard_win_p.h
+++ b/src/widgets/dialogs/qwizard_win_p.h
@@ -64,8 +64,6 @@ public:
void disconnectBackButton();
void hideBackButton() { if (backButton_) backButton_->hide(); }
QColor basicWindowFrameColor();
- enum VistaState { VistaAero, VistaBasic, Classic, Dirty };
- static VistaState vistaState();
static int titleBarSize() { return QVistaHelper::titleBarSizeDp() / QVistaHelper::m_devicePixelRatio; }
static int titleBarSizeDp() { return QVistaHelper::frameSizeDp() + QVistaHelper::captionSizeDp(); }
static int topPadding(const QPaintDevice *device) { // padding under text
@@ -77,8 +75,8 @@ public:
private:
HWND wizardHWND() const;
- bool drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc);
- static bool drawBlackRect(const QRect &rect, HDC hdc);
+ void drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc);
+ static void drawBlackRect(const QRect &rect, HDC hdc);
static int frameSize() { return QVistaHelper::frameSizeDp() / QVistaHelper::m_devicePixelRatio; }
static int frameSizeDp();
@@ -102,10 +100,6 @@ private:
void mouseReleaseEvent(QMouseEvent *event);
bool eventFilter(QObject *obj, QEvent *event) override;
- static int instanceCount;
- static VistaState cachedVistaState;
- static bool isCompositionEnabled();
- static bool isThemeActive();
enum Changes { resizeTop, movePosition, noChange } change;
QPoint pressedPos;
bool pressed;
@@ -116,7 +110,7 @@ private:
int titleBarOffset; // Extra spacing above the text
int iconSpacing; // Space between button and icon
- static int m_devicePixelRatio;
+ static qreal m_devicePixelRatio;
};
diff --git a/src/widgets/doc/images/addressbook-tutorial-part1-labeled-layout.png b/src/widgets/doc/images/addressbook-tutorial-part1-labeled-layout.png
deleted file mode 100644
index b19cb360a1..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part1-labeled-layout.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part1-labeled-screenshot.png b/src/widgets/doc/images/addressbook-tutorial-part1-labeled-screenshot.png
deleted file mode 100644
index f9b91eebe6..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part1-labeled-screenshot.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part1-screenshot.png b/src/widgets/doc/images/addressbook-tutorial-part1-screenshot.png
deleted file mode 100644
index 454b0959e6..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part1-screenshot.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part2-add-contact.png b/src/widgets/doc/images/addressbook-tutorial-part2-add-contact.png
deleted file mode 100644
index 6f2b947b21..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part2-add-contact.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part2-add-flowchart.png b/src/widgets/doc/images/addressbook-tutorial-part2-add-flowchart.png
deleted file mode 100644
index ca9af3720d..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part2-add-flowchart.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part2-add-successful.png b/src/widgets/doc/images/addressbook-tutorial-part2-add-successful.png
deleted file mode 100644
index 99a2154007..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part2-add-successful.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part2-labeled-layout.png b/src/widgets/doc/images/addressbook-tutorial-part2-labeled-layout.png
deleted file mode 100644
index 1e000c8f31..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part2-labeled-layout.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part2-signals-and-slots.png b/src/widgets/doc/images/addressbook-tutorial-part2-signals-and-slots.png
deleted file mode 100644
index e49f8dc262..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part2-signals-and-slots.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part2-stretch-effects.png b/src/widgets/doc/images/addressbook-tutorial-part2-stretch-effects.png
deleted file mode 100644
index d9f7f31227..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part2-stretch-effects.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part3-labeled-layout.png b/src/widgets/doc/images/addressbook-tutorial-part3-labeled-layout.png
deleted file mode 100644
index 1981ba8cb6..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part3-labeled-layout.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part3-linkedlist.png b/src/widgets/doc/images/addressbook-tutorial-part3-linkedlist.png
deleted file mode 100644
index e7f4725dce..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part3-linkedlist.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part3-screenshot.png b/src/widgets/doc/images/addressbook-tutorial-part3-screenshot.png
deleted file mode 100644
index 75159b4045..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part3-screenshot.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part4-remove.png b/src/widgets/doc/images/addressbook-tutorial-part4-remove.png
deleted file mode 100644
index 8eb259ef02..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part4-remove.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part5-finddialog.png b/src/widgets/doc/images/addressbook-tutorial-part5-finddialog.png
deleted file mode 100644
index 743d92ef6f..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part5-finddialog.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part5-notfound.png b/src/widgets/doc/images/addressbook-tutorial-part5-notfound.png
deleted file mode 100644
index 2d35766ab5..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part5-notfound.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part5-screenshot.png b/src/widgets/doc/images/addressbook-tutorial-part5-screenshot.png
deleted file mode 100644
index 3abe2775c2..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part5-screenshot.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part5-signals-and-slots.png b/src/widgets/doc/images/addressbook-tutorial-part5-signals-and-slots.png
deleted file mode 100644
index 1771e7bbbf..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part5-signals-and-slots.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part6-load.png b/src/widgets/doc/images/addressbook-tutorial-part6-load.png
deleted file mode 100644
index a027a1decb..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part6-load.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part6-save.png b/src/widgets/doc/images/addressbook-tutorial-part6-save.png
deleted file mode 100644
index 757feeb9ac..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part6-save.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part6-screenshot.png b/src/widgets/doc/images/addressbook-tutorial-part6-screenshot.png
deleted file mode 100644
index 7bb2f749bf..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part6-screenshot.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-part7-screenshot.png b/src/widgets/doc/images/addressbook-tutorial-part7-screenshot.png
deleted file mode 100644
index 3e7b3ca522..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-part7-screenshot.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/addressbook-tutorial-screenshot.png b/src/widgets/doc/images/addressbook-tutorial-screenshot.png
deleted file mode 100644
index 3fba6e849e..0000000000
--- a/src/widgets/doc/images/addressbook-tutorial-screenshot.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/collapsed_combobox.png b/src/widgets/doc/images/collapsed_combobox.png
new file mode 100644
index 0000000000..1400090f42
--- /dev/null
+++ b/src/widgets/doc/images/collapsed_combobox.png
Binary files differ
diff --git a/src/widgets/doc/images/cuberhiwidget-example.jpg b/src/widgets/doc/images/cuberhiwidget-example.jpg
new file mode 100644
index 0000000000..70baab8beb
--- /dev/null
+++ b/src/widgets/doc/images/cuberhiwidget-example.jpg
Binary files differ
diff --git a/src/widgets/doc/images/expanded_combobox.png b/src/widgets/doc/images/expanded_combobox.png
new file mode 100644
index 0000000000..6df0cecbbd
--- /dev/null
+++ b/src/widgets/doc/images/expanded_combobox.png
Binary files differ
diff --git a/src/widgets/doc/images/qrhiwidget-intro.jpg b/src/widgets/doc/images/qrhiwidget-intro.jpg
new file mode 100644
index 0000000000..20f931a723
--- /dev/null
+++ b/src/widgets/doc/images/qrhiwidget-intro.jpg
Binary files differ
diff --git a/src/widgets/doc/images/qtquickdialogs-filedialog-gtk.png b/src/widgets/doc/images/qtquickdialogs-filedialog-gtk.png
new file mode 100644
index 0000000000..9360d747a2
--- /dev/null
+++ b/src/widgets/doc/images/qtquickdialogs-filedialog-gtk.png
Binary files differ
diff --git a/src/widgets/doc/images/simplerhiwidget-example.jpg b/src/widgets/doc/images/simplerhiwidget-example.jpg
new file mode 100644
index 0000000000..3f0a1b355c
--- /dev/null
+++ b/src/widgets/doc/images/simplerhiwidget-example.jpg
Binary files differ
diff --git a/src/widgets/doc/images/spinboxdelegate-example.png b/src/widgets/doc/images/spinboxdelegate-example.png
deleted file mode 100644
index 5e57a9c12b..0000000000
--- a/src/widgets/doc/images/spinboxdelegate-example.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/spinboxdelegate-example.webp b/src/widgets/doc/images/spinboxdelegate-example.webp
new file mode 100644
index 0000000000..35b5770394
--- /dev/null
+++ b/src/widgets/doc/images/spinboxdelegate-example.webp
Binary files differ
diff --git a/src/widgets/doc/images/stylesheet-coffee-cleanlooks.png b/src/widgets/doc/images/stylesheet-coffee-cleanlooks.png
deleted file mode 100644
index e75df0d80a..0000000000
--- a/src/widgets/doc/images/stylesheet-coffee-cleanlooks.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/stylesheet-pagefold-mac.png b/src/widgets/doc/images/stylesheet-pagefold-mac.png
deleted file mode 100644
index 5c061b9cfd..0000000000
--- a/src/widgets/doc/images/stylesheet-pagefold-mac.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/system-tray.png b/src/widgets/doc/images/system-tray.png
deleted file mode 100644
index 298b193cf7..0000000000
--- a/src/widgets/doc/images/system-tray.png
+++ /dev/null
Binary files differ
diff --git a/src/widgets/doc/images/system-tray.webp b/src/widgets/doc/images/system-tray.webp
new file mode 100644
index 0000000000..ae509ccad3
--- /dev/null
+++ b/src/widgets/doc/images/system-tray.webp
Binary files differ
diff --git a/src/widgets/doc/qtwidgets.qdocconf b/src/widgets/doc/qtwidgets.qdocconf
index a63a2f5f2d..5f68179a36 100644
--- a/src/widgets/doc/qtwidgets.qdocconf
+++ b/src/widgets/doc/qtwidgets.qdocconf
@@ -26,7 +26,21 @@ qhp.QtWidgets.subprojects.classes.sortPages = true
tagfile = ../../../doc/qtwidgets/qtwidgets.tags
-depends += qtcore qtgui qtdoc qtsql qtdesigner qtquick qmake qtcmake qtsvg qtlinguist qthelp
+depends += \
+ qtcore \
+ qtgui \
+ qtdoc \
+ qtsql \
+ qtdesigner \
+ qtquick \
+ qmake \
+ qtcmake \
+ qtsvg \
+ qtlinguist \
+ qthelp \
+ qtopengl \
+ qtshadertools \
+ qttestlib
headerdirs += ..
@@ -60,7 +74,16 @@ imagedirs += images \
navigation.landingpage = "Qt Widgets"
navigation.cppclassespage = "Qt Widgets C++ Classes"
-manifestmeta.highlighted.names = "QtWidgets/Qt Widgets - Application Example"
-# Fail the documentation build if there are more warnings than the limit
+# Highlighted examples for User Interface Components category
+manifestmeta.highlighted.names = \
+ "QtWidgets/Editable Tree Model Example" \
+ "QtWidgets/Menus Example"
+
+# Highlighted examples for Desktop category
+manifestmeta.highlighted.names += \
+ "QtWidgets/System Tray Icon Example" \
+ "QtWidgets/Taking a Screenshot"
+
+# Enforce zero documentation warnings
warninglimit = 0
diff --git a/src/widgets/doc/snippets/CMakeLists.txt b/src/widgets/doc/snippets/CMakeLists.txt
index b1a89e1f66..6274244db0 100644
--- a/src/widgets/doc/snippets/CMakeLists.txt
+++ b/src/widgets/doc/snippets/CMakeLists.txt
@@ -1,5 +1,5 @@
# Copyright (C) 2022 The Qt Company Ltd.
-# SPDX-License-Identifier: BSD-3-Clause
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#! [cmake_use]
find_package(Qt6 REQUIRED COMPONENTS Widgets)
diff --git a/src/widgets/doc/snippets/cmake-macros/examples.cmake b/src/widgets/doc/snippets/cmake-macros/examples.cmake
index d18f2fffb8..3c58509fdf 100644
--- a/src/widgets/doc/snippets/cmake-macros/examples.cmake
+++ b/src/widgets/doc/snippets/cmake-macros/examples.cmake
@@ -1,8 +1,8 @@
# Copyright (C) 2022 The Qt Company Ltd.
-# SPDX-License-Identifier: BSD-3-Clause
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#! [qt_wrap_ui]
set(SOURCES mainwindow.cpp main.cpp)
qt_wrap_ui(SOURCES mainwindow.ui)
-add_executable(myapp ${SOURCES})
+qt_add_executable(myapp ${SOURCES})
#! [qt_wrap_ui]
diff --git a/src/widgets/doc/snippets/code/doc_src_qt4-mainwindow.cpp b/src/widgets/doc/snippets/code/doc_src_qt4-mainwindow.cpp
index 7ac3577648..2c8a892511 100644
--- a/src/widgets/doc/snippets/code/doc_src_qt4-mainwindow.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_qt4-mainwindow.cpp
@@ -26,48 +26,3 @@ setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
QWidget *centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
//! [3]
-
-
-//! [4]
-QPopupMenu *fileMenu = new QPopupMenu(this);
-openAction->addTo(fileMenu);
-saveAction->addTo(fileMenu);
-...
-menuBar()->insertItem(tr("&File"), fileMenu);
-//! [4]
-
-
-//! [5]
-QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
-fileMenu->addAction(openAction);
-fileMenu->addAction(saveAction);
-...
-//! [5]
-
-
-//! [6]
-QToolBar *fileTools = new QToolBar(this, "file toolbar");
-openAction->addTo(fileTools);
-saveAction->addTo(fileTools);
-...
-//! [6]
-
-
-//! [7]
-QToolBar *fileTools = addToolBar(tr("File Tool Bar"));
-fileTools->addAction(openAction);
-fileTools->addAction(saveAction);
-...
-//! [7]
-
-
-//! [8]
-QDockWidget *dockWidget = new QDockWidget(this);
-mainWin->moveDockWidget(dockWidget, Qt::DockLeft);
-//! [8]
-
-
-//! [9]
-QDockWidget *dockWidget = new QDockWidget(mainWindow);
-mainWindow->addDockWidget(Qt::LeftDockWidgetArea, dockWidget);
-//! [9]
diff --git a/src/widgets/doc/snippets/code/doc_src_qt4-styles.cpp b/src/widgets/doc/snippets/code/doc_src_qt4-styles.cpp
index 3620c261a5..2ec3afba01 100644
--- a/src/widgets/doc/snippets/code/doc_src_qt4-styles.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_qt4-styles.cpp
@@ -24,22 +24,3 @@ void MyWidget::paintEvent(QPaintEvent *event)
this);
}
//! [1]
-
-
-//! [2]
-void drawControl(ControlElement element,
- QPainter *painter,
- const QWidget *widget,
- const QRect &rect,
- const QColorGroup &colorGroup,
- SFlags how = Style_Default,
- const QStyleOption &option = QStyleOption::Default) const;
-//! [2]
-
-
-//! [3]
-void drawControl(ControlElement element,
- const QStyleOption *option,
- QPainter *painter,
- const QWidget *widget = nullptr) const;
-//! [3]
diff --git a/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp b/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp
index 7fbcc493de..91851f8f07 100644
--- a/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp
@@ -51,7 +51,7 @@ qApp->setStyleSheet("ns--MyPushButton { background: yellow; }");
void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
- opt.init(this);
+ opt.initFrom(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
diff --git a/src/widgets/doc/snippets/code/doc_src_stylesheet.qdoc b/src/widgets/doc/snippets/code/doc_src_stylesheet.qdoc
index d505040590..388e9d1f7c 100644
--- a/src/widgets/doc/snippets/code/doc_src_stylesheet.qdoc
+++ b/src/widgets/doc/snippets/code/doc_src_stylesheet.qdoc
@@ -1,5 +1,5 @@
// Copyright (C) 2016 The Qt Company Ltd.
-// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
//! [0]
QLineEdit { background: yellow }
@@ -450,32 +450,48 @@ QDialog { etch-disabled-text: 1 }
//! [82]
-QLabel { border-color: red } /* red red red red */
-QLabel { border-color: red blue } /* red blue red blue */
-QLabel { border-color: red blue green } /* red blue green blue */
-QLabel { border-color: red blue green yellow }
+/* red red red red */
+QLabel { border-color: red }
+/* red blue red blue */
+QLabel { border-color: red blue }
+/* red blue green blue */
+QLabel { border-color: red blue green }
/* red blue green yellow */
+QLabel { border-color: red blue green yellow }
//! [82]
//! [83]
-QLabel { border-width: 1px } /* 1px 1px 1px 1px */
-QLabel { border-width: 1px 2px } /* 1px 2px 1px 2px */
-QLabel { border-width: 1px 2px 3px } /* 1px 2px 3px 2px */
-QLabel { border-width: 1px 2px 3px 4px } /* 1px 2px 3px 4px */
+/* 1px 1px 1px 1px */
+QLabel { border-width: 1px }
+/* 1px 2px 1px 2px */
+QLabel { border-width: 1px 2px }
+/* 1px 2px 3px 2px */
+QLabel { border-width: 1px 2px 3px }
+/* 1px 2px 3px 4px */
+QLabel { border-width: 1px 2px 3px 4px }
//! [83]
//! [84]
-QLabel { border-color: red } /* opaque red */
-QLabel { border-color: #FF0000 } /* opaque red */
-QLabel { border-color: rgba(255, 0, 0, 75%) } /* 75% opaque red */
-QLabel { border-color: rgb(255, 0, 0) } /* opaque red */
-QLabel { border-color: rgb(100%, 0%, 0%) } /* opaque red */
-QLabel { border-color: hsv(60, 100%, 100%) } /* opaque yellow */
-QLabel { border-color: hsva(240, 255, 255, 75%) } /* 75% blue */
-QLabel { border-color: hsl(60, 100%, 50%) } /* opaque yellow */
-QLabel { border-color: hsla(240, 255, 50%, 75%) } /* 75% blue */
+/* opaque red */
+QLabel { border-color: red }
+/* opaque red */
+QLabel { border-color: #FF0000 }
+/* 75% opaque red */
+QLabel { border-color: rgba(255, 0, 0, 75%) }
+/* opaque red */
+QLabel { border-color: rgb(255, 0, 0) }
+/* opaque red */
+QLabel { border-color: rgb(100%, 0%, 0%) }
+/* opaque yellow */
+QLabel { border-color: hsv(60, 100%, 100%) }
+/* 75% blue */
+QLabel { border-color: hsva(240, 255, 255, 75%) }
+/* opaque yellow */
+QLabel { border-color: hsl(60, 100%, 50%) }
+/* 75% blue */
+QLabel { border-color: hsla(240, 255, 50%, 75%) }
//! [84]
@@ -1223,7 +1239,7 @@ QScrollBar::sub-line:horizontal {
//! [135]
-QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
+QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
border: 2px solid grey;
width: 3px;
height: 3px;
@@ -1267,7 +1283,7 @@ QScrollBar::sub-line:horizontal {
right: 20px;
}
-QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
+QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
width: 3px;
height: 3px;
background: pink;
diff --git a/src/widgets/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp b/src/widgets/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp
index 014a9dfeb0..ebc07025ec 100644
--- a/src/widgets/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp
@@ -11,23 +11,6 @@ int ret = QMessageBox::warning(this, tr("My Application"),
//! [0]
-//! [1]
-QMessageBox msgBox;
-msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
-switch (msgBox.exec()) {
-case QMessageBox::Yes:
- // yes was clicked
- break;
-case QMessageBox::No:
- // no was clicked
- break;
-default:
- // should never be reached
- break;
-}
-//! [1]
-
-
//! [2]
QMessageBox msgBox;
QPushButton *connectButton = msgBox.addButton(tr("Connect"), QMessageBox::ActionRole);
@@ -100,12 +83,3 @@ switch (ret) {
break;
}
//! [7]
-
-//! [9]
-QMessageBox msgBox(this);
-msgBox.setText(tr("The document has been modified.\n"
- "Do you want to save your changes?"));
-msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard
- | QMessageBox::Cancel);
-msgBox.setDefaultButton(QMessageBox::Save);
-//! [9]
diff --git a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp
index e9e8b95847..bcf675d8af 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp
@@ -71,24 +71,6 @@ rect.deviceTransform(view->viewportTransform()).inverted().map(QPointF(100, 100)
//! [5]
-//! [6]
-// Rotate an item 45 degrees around (0, 0).
-item->rotate(45);
-
-// Rotate an item 45 degrees around (x, y).
-item->setTransform(QTransform().translate(x, y).rotate(45).translate(-x, -y));
-//! [6]
-
-
-//! [7]
-// Scale an item by 3x2 from its origin
-item->scale(3, 2);
-
-// Scale an item by 3x2 from (x, y)
-item->setTransform(QTransform().translate(x, y).scale(3, 2).translate(-x, -y));
-//! [7]
-
-
//! [8]
QRectF CircleItem::boundingRect() const
{
@@ -223,19 +205,3 @@ QTransform xform = item->deviceTransform(view->viewportTransform());
QRect deviceRect = xform.mapRect(rect).toAlignedRect();
view->viewport()->scroll(dx, dy, deviceRect);
//! [19]
-
-//! [20]
-item->setTransform(QTransform().rotate(angle), true);
-//! [20]
-
-//! [21]
-setTransform(QTransform::fromScale(sx, sy), true);
-//! [21]
-
-//! [22]
-setTransform(QTransform().shear(sh, sv), true);
-//! [22]
-
-//! [23]
-setTransform(QTransform::fromTranslate(dx, dy), true);
-//! [23]
diff --git a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsview.cpp b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsview.cpp
index 9f48c4e06b..0b757cf0a2 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsview.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsview.cpp
@@ -27,16 +27,6 @@ view.setCacheMode(QGraphicsView::CacheBackground);
//! [2]
-//! [3]
-QGraphicsScene scene;
-scene.addText("GraphicsView rotated clockwise");
-
-QGraphicsView view(&scene);
-view.rotate(90); // the text is rendered with a 90 degree clockwise rotation
-view.show();
-//! [3]
-
-
//! [4]
QGraphicsScene scene;
scene.addItem(...
diff --git a/src/widgets/doc/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp b/src/widgets/doc/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp
index d314c88fd9..1a311015c4 100644
--- a/src/widgets/doc/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp
@@ -14,12 +14,16 @@ QItemEditorFactory *factory = new QItemEditorFactory;
//! [1]
+//! [setDefaultFactory]
//! [2]
QItemEditorFactory *editorFactory = new QItemEditorFactory;
QItemEditorCreatorBase *creator = new QStandardItemEditorCreator<MyFancyDateTimeEdit>();
editorFactory->registerEditor(QMetaType::QDateTime, creator);
//! [2]
+QItemEditorFactory::setDefaultFactory(editorFactory);
+//! [setDefaultFactory]
+
//! [3]
Q_PROPERTY(QColor color READ color WRITE setColor USER true)
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp
index a31e720fb1..0d14b086cc 100644
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp
@@ -31,26 +31,6 @@ QApplication::setStyle(QStyleFactory::create("Fusion"));
//! [1]
-// ### fixme: Qt 6: Remove [2]
-//! [2]
-int main(int argc, char *argv[])
-{
- QApplication::setColorSpec(QApplication::ManyColor);
- QApplication app(argc, argv);
- ...
- return app.exec();
-}
-//! [2]
-
-
-//! [3]
-QSize MyWidget::sizeHint() const
-{
- return QSize(80, 25);
-}
-//! [3]
-
-
//! [4]
void showAllHiddenTopLevelWidgets()
{
@@ -73,82 +53,8 @@ void updateAllWidgets()
//! [5]
-//! [6]
-int main(int argc, char *argv[])
-{
- QApplication::setDesktopSettingsAware(false);
- QApplication app(argc, argv);
- ...
- return app.exec();
-}
-//! [6]
-
-
//! [7]
if ((startPos - currentPos).manhattanLength() >=
QApplication::startDragDistance())
startTheDrag();
//! [7]
-
-
-//! [8]
-void MyApplication::commitData(QSessionManager& manager)
-{
- if (manager.allowsInteraction()) {
- int ret = QMessageBox::warning(
- mainWindow,
- tr("My Application"),
- tr("Save changes to document?"),
- QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
-
- switch (ret) {
- case QMessageBox::Save:
- manager.release();
- if (!saveDocument())
- manager.cancel();
- break;
- case QMessageBox::Discard:
- break;
- case QMessageBox::Cancel:
- default:
- manager.cancel();
- }
- } else {
- // we did not get permission to interact, then
- // do something reasonable instead
- }
-}
-//! [8]
-
-
-//! [9]
-appname -session id
-//! [9]
-
-
-//! [10]
-const QStringList commands = mySession.restartCommand();
-for (const QString &command : commands)
- do_something(command);
-//! [10]
-
-
-//! [11]
-const QStringList commands = mySession.discardCommand();
-for (const QString &command : commands)
- do_something(command);
-//! [11]
-
-
-//! [12]
-QWidget *widget = QApplication::widgetAt(x, y);
-if (widget)
- widget = widget->window();
-//! [12]
-
-
-//! [13]
-QWidget *widget = QApplication::widgetAt(point);
-if (widget)
- widget = widget->window();
-//! [13]
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qformlayout.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qformlayout.cpp
index ab20b9da2e..cb90436462 100644
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qformlayout.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_kernel_qformlayout.cpp
@@ -1,6 +1,8 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+#include <QtCore/qpointer.h>
+
//! [0]
QFormLayout *formLayout = new QFormLayout(this);
formLayout->addRow(tr("&Name:"), nameLineEdit);
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp
index 8f0c296873..21703c7395 100644
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp
@@ -22,19 +22,6 @@ aWidget->window()->setWindowTitle("New Window Title");
//! [3]
-//! [4]
-QFont font("Helvetica", 12, QFont::Bold);
-setFont(font);
-//! [4]
-
-
-//! [5]
-QFont font;
-font.setBold(false);
-setFont(font);
-//! [5]
-
-
//! [6]
setCursor(Qt::IBeamCursor);
//! [6]
@@ -61,6 +48,11 @@ setTabOrder(c, d); // a to b to c to d
//! [9]
+//! [9.list]
+setTabOrder({a, b, c, d}); // a to b to c to d
+//! [9.list]
+
+
//! [10]
// WRONG
setTabOrder(c, d); // c to d
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qgroupbox.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qgroupbox.cpp
index 1298147de1..cff537c862 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qgroupbox.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qgroupbox.cpp
@@ -4,3 +4,20 @@
//! [0]
g->setTitle("&User information");
//! [0]
+
+//! [Set up QGroupBox with layout]
+QGroupBox *groupBox = new QGroupBox(tr("Group Box with Layout"));
+
+QRadioButton *radio1 = new QRadioButton(tr("&Radio button 1"));
+QRadioButton *radio2 = new QRadioButton(tr("R&adio button 2"));
+QRadioButton *radio3 = new QRadioButton(tr("Ra&dio button 3"));
+
+radio1->setChecked(true);
+
+QVBoxLayout *vbox = new QVBoxLayout;
+vbox->addWidget(radio1);
+vbox->addWidget(radio2);
+vbox->addWidget(radio3);
+vbox->addStretch(1);
+groupBox->setLayout(vbox);
+//! [Set up QGroupBox with layout]
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp
index b0b0500fab..eb0897d5c5 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp
@@ -12,7 +12,7 @@ exec(somewidget.mapToGlobal(QPoint(0,0)));
//! [2]
-exec(e->globalPos());
+exec(e->globalPosition().toPoint());
//! [2]
@@ -27,7 +27,7 @@ exec(somewidget.mapToGlobal(QPoint(0, 0)));
//! [5]
-exec(e->globalPos());
+exec(e->globalPosition().toPoint());
//! [5]
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qspinbox.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qspinbox.cpp
index d660d605a1..ec4b5bf27f 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qspinbox.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qspinbox.cpp
@@ -41,3 +41,23 @@ setRange(minimum, maximum);
setMinimum(minimum);
setMaximum(maximum);
//! [7]
+
+//! [8]
+int IconSizeSpinBox::valueFromText(const QString &text) const
+{
+ static const QRegularExpression regExp(tr("(\\d+)(\\s*[xx]\\s*\\d+)?"));
+ Q_ASSERT(regExp.isValid());
+
+ const QRegularExpressionMatch match = regExp.match(text);
+ if (match.isValid())
+ return match.captured(1).toInt();
+ return 0;
+}
+//! [8]
+
+//! [9]
+QString IconSizeSpinBox::textFromValue(int value) const
+{
+ return tr("%1 x %1").arg(value);
+}
+//! [9]
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qstatusbar.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qstatusbar.cpp
index 8f5db27c9f..e05d27353a 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qstatusbar.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qstatusbar.cpp
@@ -4,3 +4,11 @@
//! [0]
statusBar()->addWidget(new MyReadWriteIndication);
//! [0]
+
+//! [1]
+statusBar()->showMessage(tr("Ready"));
+//! [1]
+
+//! [2]
+statusBar()->showMessage(tr("Ready"), 2000);
+//! [2]
diff --git a/src/widgets/doc/snippets/code/src_widgets_util_qscroller.cpp b/src/widgets/doc/snippets/code/src_widgets_util_qscroller.cpp
index 03e2a710a4..36e77bf371 100644
--- a/src/widgets/doc/snippets/code/src_widgets_util_qscroller.cpp
+++ b/src/widgets/doc/snippets/code/src_widgets_util_qscroller.cpp
@@ -1,5 +1,5 @@
// Copyright (C) 2018 The Qt Company Ltd.
-// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QWidget *w = ...;
diff --git a/src/widgets/doc/snippets/code/src_widgets_widgets_qmainwindow.cpp b/src/widgets/doc/snippets/code/src_widgets_widgets_qmainwindow.cpp
index f9f9c6c338..9734f2fed0 100644
--- a/src/widgets/doc/snippets/code/src_widgets_widgets_qmainwindow.cpp
+++ b/src/widgets/doc/snippets/code/src_widgets_widgets_qmainwindow.cpp
@@ -1,5 +1,5 @@
// Copyright (C) 2018 The Qt Company Ltd.
-// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void MainWindow::createMenus()
diff --git a/src/widgets/doc/snippets/customviewstyle/CMakeLists.txt b/src/widgets/doc/snippets/customviewstyle/CMakeLists.txt
index d424b583a4..f37de58edc 100644
--- a/src/widgets/doc/snippets/customviewstyle/CMakeLists.txt
+++ b/src/widgets/doc/snippets/customviewstyle/CMakeLists.txt
@@ -1,5 +1,5 @@
# Copyright (C) 2022 The Qt Company Ltd.
-# SPDX-License-Identifier: BSD-3-Clause
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
add_library(widgets_customviewstyle_snippets OBJECT
../customstyle/customstyle.h
@@ -12,3 +12,5 @@ target_link_libraries(widgets_customviewstyle_snippets PRIVATE
Qt::Gui
Qt::Widgets
)
+
+set_target_properties(widgets_customviewstyle_snippets PROPERTIES UNITY_BUILD OFF)
diff --git a/src/widgets/doc/snippets/dialogs/dialogs.cpp b/src/widgets/doc/snippets/dialogs/dialogs.cpp
index 441ca8f795..0990d7d7c4 100644
--- a/src/widgets/doc/snippets/dialogs/dialogs.cpp
+++ b/src/widgets/doc/snippets/dialogs/dialogs.cpp
@@ -227,6 +227,35 @@ void Operation::cancel()
}
//! [6]
+void extension()
+{
+ using ExtendedControls = QWidget;
+ QPushButton *findButton;
+ QPushButton *moreButton;
+ QWidget *extension;
+ QVBoxLayout *mainLayout;
+
+//! [extension]
+ mainLayout->setSizeConstraint(QLayout::SetFixedSize);
+
+ findButton = new QPushButton(tr("&Find"));
+ moreButton = new QPushButton(tr("&More..."));
+ moreButton->setCheckable(true);
+
+ extension = new ExtendedControls;
+ mainLayout->addWidget(extension);
+ extension->hide();
+
+ connect(moreButton, &QAbstractButton::toggled, extension, &QWidget::setVisible);
+//! [extension]
+
+//! [buttonbox]
+ QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Vertical);
+ buttonBox->addButton(findButton, QDialogButtonBox::ActionRole);
+ buttonBox->addButton(moreButton, QDialogButtonBox::ActionRole);
+//! [buttonbox]
+}
+
int main()
{
}
diff --git a/src/widgets/doc/snippets/filedialogurls/CMakeLists.txt b/src/widgets/doc/snippets/filedialogurls/CMakeLists.txt
index ed50d801c4..4c64ff3288 100644
--- a/src/widgets/doc/snippets/filedialogurls/CMakeLists.txt
+++ b/src/widgets/doc/snippets/filedialogurls/CMakeLists.txt
@@ -1,5 +1,5 @@
# Copyright (C) 2022 The Qt Company Ltd.
-# SPDX-License-Identifier: BSD-3-Clause
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
add_library(widgets_filedialogurl_snippets OBJECT
filedialogurls.cpp
diff --git a/src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt b/src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt
index ffb67a71d1..a2d391d629 100644
--- a/src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt
+++ b/src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt
@@ -1,5 +1,5 @@
# Copyright (C) 2022 The Qt Company Ltd.
-# SPDX-License-Identifier: BSD-3-Clause
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
add_library(widgets_graphicssceneadditem_snippets OBJECT
graphicssceneadditemsnippet.cpp
diff --git a/src/widgets/doc/snippets/graphicsview/CMakeLists.txt b/src/widgets/doc/snippets/graphicsview/CMakeLists.txt
index cb1e67068a..e395eda045 100644
--- a/src/widgets/doc/snippets/graphicsview/CMakeLists.txt
+++ b/src/widgets/doc/snippets/graphicsview/CMakeLists.txt
@@ -1,5 +1,5 @@
# Copyright (C) 2022 The Qt Company Ltd.
-# SPDX-License-Identifier: BSD-3-Clause
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
add_library(widgets_graphicsview_snippets OBJECT
graphicsview.cpp
diff --git a/src/widgets/doc/snippets/mdiarea/CMakeLists.txt b/src/widgets/doc/snippets/mdiarea/CMakeLists.txt
index 8185b1dbd3..3edb2d1b36 100644
--- a/src/widgets/doc/snippets/mdiarea/CMakeLists.txt
+++ b/src/widgets/doc/snippets/mdiarea/CMakeLists.txt
@@ -1,5 +1,5 @@
# Copyright (C) 2022 The Qt Company Ltd.
-# SPDX-License-Identifier: BSD-3-Clause
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
add_library(widgets_mdiarea_snippets OBJECT
mdiareasnippets.cpp
diff --git a/src/widgets/doc/snippets/myscrollarea/CMakeLists.txt b/src/widgets/doc/snippets/myscrollarea/CMakeLists.txt
index c6e13d533a..9e7e14dc8d 100644
--- a/src/widgets/doc/snippets/myscrollarea/CMakeLists.txt
+++ b/src/widgets/doc/snippets/myscrollarea/CMakeLists.txt
@@ -1,5 +1,5 @@
# Copyright (C) 2022 The Qt Company Ltd.
-# SPDX-License-Identifier: BSD-3-Clause
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
add_library(widgets_myscrollarea_snippets OBJECT
myscrollarea.cpp
diff --git a/src/widgets/doc/snippets/qitemdelegate/CMakeLists.txt b/src/widgets/doc/snippets/qitemdelegate/CMakeLists.txt
new file mode 100644
index 0000000000..9aad7026c7
--- /dev/null
+++ b/src/widgets/doc/snippets/qitemdelegate/CMakeLists.txt
@@ -0,0 +1,12 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+add_library(widgets_qitemdelegate_snippets OBJECT
+ spinbox-delegate.cpp
+)
+
+target_link_libraries(widgets_qitemdelegate_snippets PRIVATE
+ Qt::Core
+ Qt::Gui
+ Qt::Widgets
+)
diff --git a/src/widgets/doc/snippets/qitemdelegate/spinbox-delegate.cpp b/src/widgets/doc/snippets/qitemdelegate/spinbox-delegate.cpp
new file mode 100644
index 0000000000..efe8a16733
--- /dev/null
+++ b/src/widgets/doc/snippets/qitemdelegate/spinbox-delegate.cpp
@@ -0,0 +1,79 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QStyledItemDelegate>
+#include <QSpinBox>
+
+//! [declaration]
+class SpinBoxDelegate : public QStyledItemDelegate
+{
+ Q_OBJECT
+
+public:
+ SpinBoxDelegate(QObject *parent = nullptr);
+
+ QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
+ const QModelIndex &index) const override;
+
+ void setEditorData(QWidget *editor, const QModelIndex &index) const override;
+ void setModelData(QWidget *editor, QAbstractItemModel *model,
+ const QModelIndex &index) const override;
+
+ void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
+ const QModelIndex &index) const override;
+};
+//! [declaration]
+
+//! [constructor]
+SpinBoxDelegate::SpinBoxDelegate(QObject *parent)
+ : QStyledItemDelegate(parent)
+{
+}
+//! [constructor]
+
+//! [createEditor]
+QWidget *SpinBoxDelegate::createEditor(QWidget *parent,
+ const QStyleOptionViewItem &/* option */,
+ const QModelIndex &/* index */) const
+{
+ QSpinBox *editor = new QSpinBox(parent);
+ editor->setFrame(false);
+ editor->setMinimum(0);
+ editor->setMaximum(100);
+
+ return editor;
+}
+//! [createEditor]
+
+//! [setEditorData]
+void SpinBoxDelegate::setEditorData(QWidget *editor,
+ const QModelIndex &index) const
+{
+ int value = index.model()->data(index, Qt::EditRole).toInt();
+
+ QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
+ spinBox->setValue(value);
+}
+//! [setEditorData]
+
+//! [setModelData]
+void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
+ const QModelIndex &index) const
+{
+ QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
+ spinBox->interpretText();
+ int value = spinBox->value();
+
+ model->setData(index, value, Qt::EditRole);
+}
+//! [setModelData]
+
+//! [updateEditorGeometry]
+void SpinBoxDelegate::updateEditorGeometry(QWidget *editor,
+ const QStyleOptionViewItem &option,
+ const QModelIndex &/* index */) const
+{
+ editor->setGeometry(option.rect);
+}
+//! [updateEditorGeometry]
+
diff --git a/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.cpp b/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.cpp
new file mode 100644
index 0000000000..1cd583e294
--- /dev/null
+++ b/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.cpp
@@ -0,0 +1,109 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QRhiWidget>
+#include <QFile>
+#include <rhi/qrhi.h>
+
+//![0]
+class ExampleRhiWidget : public QRhiWidget
+{
+public:
+ ExampleRhiWidget(QWidget *parent = nullptr) : QRhiWidget(parent) { }
+ void initialize(QRhiCommandBuffer *cb) override;
+ void render(QRhiCommandBuffer *cb) override;
+private:
+ QRhi *m_rhi = nullptr;
+ std::unique_ptr<QRhiBuffer> m_vbuf;
+ std::unique_ptr<QRhiBuffer> m_ubuf;
+ std::unique_ptr<QRhiShaderResourceBindings> m_srb;
+ std::unique_ptr<QRhiGraphicsPipeline> m_pipeline;
+ QMatrix4x4 m_viewProjection;
+ float m_rotation = 0.0f;
+};
+
+float vertexData[] = {
+ 0.0f, 0.5f, 1.0f, 0.0f, 0.0f,
+ -0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
+ 0.5f, -0.5f, 0.0f, 0.0f, 1.0f,
+};
+
+QShader getShader(const QString &name)
+{
+ QFile f(name);
+ return f.open(QIODevice::ReadOnly) ? QShader::fromSerialized(f.readAll()) : QShader();
+}
+
+void ExampleRhiWidget::initialize(QRhiCommandBuffer *cb)
+{
+ if (m_rhi != rhi()) {
+ m_pipeline.reset();
+ m_rhi = rhi();
+ }
+
+ if (!m_pipeline) {
+ m_vbuf.reset(m_rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData)));
+ m_vbuf->create();
+
+ m_ubuf.reset(m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 64));
+ m_ubuf->create();
+
+ m_srb.reset(m_rhi->newShaderResourceBindings());
+ m_srb->setBindings({
+ QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage, m_ubuf.get()),
+ });
+ m_srb->create();
+
+ m_pipeline.reset(m_rhi->newGraphicsPipeline());
+ m_pipeline->setShaderStages({
+ { QRhiShaderStage::Vertex, getShader(QLatin1String(":/shader_assets/color.vert.qsb")) },
+ { QRhiShaderStage::Fragment, getShader(QLatin1String(":/shader_assets/color.frag.qsb")) }
+ });
+ QRhiVertexInputLayout inputLayout;
+ inputLayout.setBindings({
+ { 5 * sizeof(float) }
+ });
+ inputLayout.setAttributes({
+ { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
+ { 0, 1, QRhiVertexInputAttribute::Float3, 2 * sizeof(float) }
+ });
+ m_pipeline->setVertexInputLayout(inputLayout);
+ m_pipeline->setShaderResourceBindings(m_srb.get());
+ m_pipeline->setRenderPassDescriptor(renderTarget()->renderPassDescriptor());
+ m_pipeline->create();
+
+ QRhiResourceUpdateBatch *resourceUpdates = m_rhi->nextResourceUpdateBatch();
+ resourceUpdates->uploadStaticBuffer(m_vbuf.get(), vertexData);
+ cb->resourceUpdate(resourceUpdates);
+ }
+
+ const QSize outputSize = colorTexture()->pixelSize();
+ m_viewProjection = m_rhi->clipSpaceCorrMatrix();
+ m_viewProjection.perspective(45.0f, outputSize.width() / (float) outputSize.height(), 0.01f, 1000.0f);
+ m_viewProjection.translate(0, 0, -4);
+}
+
+void ExampleRhiWidget::render(QRhiCommandBuffer *cb)
+{
+ QRhiResourceUpdateBatch *resourceUpdates = m_rhi->nextResourceUpdateBatch();
+ m_rotation += 1.0f;
+ QMatrix4x4 modelViewProjection = m_viewProjection;
+ modelViewProjection.rotate(m_rotation, 0, 1, 0);
+ resourceUpdates->updateDynamicBuffer(m_ubuf.get(), 0, 64, modelViewProjection.constData());
+
+ const QColor clearColor = QColor::fromRgbF(0.4f, 0.7f, 0.0f, 1.0f);
+ cb->beginPass(renderTarget(), clearColor, { 1.0f, 0 }, resourceUpdates);
+
+ cb->setGraphicsPipeline(m_pipeline.get());
+ const QSize outputSize = colorTexture()->pixelSize();
+ cb->setViewport(QRhiViewport(0, 0, outputSize.width(), outputSize.height()));
+ cb->setShaderResources();
+ const QRhiCommandBuffer::VertexInput vbufBinding(m_vbuf.get(), 0);
+ cb->setVertexInput(0, 1, &vbufBinding);
+ cb->draw(3);
+
+ cb->endPass();
+
+ update();
+}
+//![0]
diff --git a/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.frag b/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.frag
new file mode 100644
index 0000000000..d86bcf7386
--- /dev/null
+++ b/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.frag
@@ -0,0 +1,10 @@
+//![0]
+#version 440
+layout(location = 0) in vec3 v_color;
+layout(location = 0) out vec4 fragColor;
+
+void main()
+{
+ fragColor = vec4(v_color, 1.0);
+}
+//![0]
diff --git a/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.vert b/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.vert
new file mode 100644
index 0000000000..610df304b1
--- /dev/null
+++ b/src/widgets/doc/snippets/qrhiwidget/rhiwidgetintro.vert
@@ -0,0 +1,15 @@
+//![0]
+#version 440
+layout(location = 0) in vec4 position;
+layout(location = 1) in vec3 color;
+layout(location = 0) out vec3 v_color;
+layout(std140, binding = 0) uniform buf {
+ mat4 mvp;
+};
+
+void main()
+{
+ v_color = color;
+ gl_Position = mvp * position;
+}
+//![0]
diff --git a/src/widgets/doc/snippets/splitter/splitter.cpp b/src/widgets/doc/snippets/splitter/splitter.cpp
index c3a36ba4c0..662ac30eda 100644
--- a/src/widgets/doc/snippets/splitter/splitter.cpp
+++ b/src/widgets/doc/snippets/splitter/splitter.cpp
@@ -37,11 +37,5 @@ int main()
//! [2]
}
-//! [3]
- QListIterator<int> it(splitter->sizes());
- while (it.hasNext())
- processSize(it.next());
-//! [3]
-
return 0;
}
diff --git a/src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp b/src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp
index 8a3a8555eb..67dedb147c 100644
--- a/src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp
+++ b/src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp
@@ -1,5 +1,5 @@
// Copyright (C) 2016 The Qt Company Ltd.
-// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "qcustompixmapstyle.h"
diff --git a/src/widgets/doc/snippets/tooltips/main.cpp b/src/widgets/doc/snippets/tooltips/main.cpp
new file mode 100644
index 0000000000..94cc71f711
--- /dev/null
+++ b/src/widgets/doc/snippets/tooltips/main.cpp
@@ -0,0 +1,74 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QtWidgets>
+
+using SearchBar = QWidget;
+using Element = QWidget;
+
+class Window : public QMainWindow
+{
+public:
+ Window(QWidget *parent = nullptr);
+
+protected:
+ bool event(QEvent *event) override;
+
+private:
+ Element *elementAt(QPoint pos) const {
+ return nullptr;
+ }
+
+ QToolBar *fileToolBar;
+ QMenu *fileMenu;
+
+ SearchBar *searchBar;
+};
+
+
+Window::Window(QWidget *parent)
+ : QMainWindow(parent)
+{
+//! [action_tooltip]
+ QAction *openAction = new QAction(tr("&Open..."));
+ openAction->setToolTip(tr("Open an existing file"));
+
+ fileMenu = menuBar()->addMenu(tr("&File"));
+ fileToolBar = addToolBar(tr("&File"));
+
+ fileMenu->addAction(openAction);
+ fileToolBar->addAction(openAction);
+//! [action_tooltip]
+
+//! [static_tooltip]
+ searchBar = new SearchBar;
+ searchBar->setToolTip(tr("Search in the current document"));
+//! [static_tooltip]
+
+ fileToolBar->addWidget(searchBar);
+}
+
+//! [dynamic_tooltip]
+bool Window::event(QEvent *event)
+{
+ if (event->type() == QEvent::ToolTip) {
+ QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
+ if (Element *element = elementAt(helpEvent->pos())) {
+ QToolTip::showText(helpEvent->globalPos(), element->toolTip());
+ } else {
+ QToolTip::hideText();
+ event->ignore();
+ }
+
+ return true;
+ }
+ return QWidget::event(event);
+}
+//! [dynamic_tooltip]
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+ Window w;
+ return 0;
+}
diff --git a/src/widgets/doc/src/cmake-macros.qdoc b/src/widgets/doc/src/cmake-macros.qdoc
index 34bc254962..13bdcca67b 100644
--- a/src/widgets/doc/src/cmake-macros.qdoc
+++ b/src/widgets/doc/src/cmake-macros.qdoc
@@ -6,7 +6,7 @@
\ingroup cmake-macros-qtwidgets
\title qt_wrap_ui
-\target qt6_wrap_ui
+\keyword qt6_wrap_ui
\summary {Creates sources for .ui files.}
diff --git a/src/widgets/doc/src/model-view-programming.qdoc b/src/widgets/doc/src/model-view-programming.qdoc
index 5c09fd0445..5461619a4d 100644
--- a/src/widgets/doc/src/model-view-programming.qdoc
+++ b/src/widgets/doc/src/model-view-programming.qdoc
@@ -686,12 +686,8 @@
implementations of these functions.
Editors for delegates can be implemented either by using widgets to manage
- the editing process or by handling events directly.
- The first approach is covered later in this section, and it is also
- shown in the \l{Spin Box Delegate Example}{Spin Box Delegate} example.
-
- The \l{Pixelator Example}{Pixelator} example shows how to create a
- custom delegate that performs specialized rendering for a table view.
+ the editing process or by handling events directly. The first approach is
+ covered later in this section.
\section2 Using an existing delegate
@@ -721,13 +717,15 @@
data entry. We construct a table view to display the contents of
the model, and this will use the custom delegate for editing.
- \image spinboxdelegate-example.png
+ \image spinboxdelegate-example.webp
We subclass the delegate from \l QStyledItemDelegate because we do not want
to write custom display functions. However, we must still provide
functions to manage the editor widget:
- \snippet itemviews/spinboxdelegate/delegate.h 0
+ \snippet qitemdelegate/spinbox-delegate.cpp declaration
+ \codeline
+ \snippet qitemdelegate/spinbox-delegate.cpp constructor
Note that no editor widgets are set up when the delegate is
constructed. We only construct an editor widget when it is needed.
@@ -741,7 +739,7 @@
supplied with everything that the delegate needs to be able to set up
a suitable widget:
- \snippet itemviews/spinboxdelegate/delegate.cpp 1
+ \snippet qitemdelegate/spinbox-delegate.cpp createEditor
Note that we do not need to keep a pointer to the editor widget because
the view takes responsibility for destroying it when it is no longer
@@ -765,7 +763,7 @@
\l{Qt::ItemDataRole}{display role}, and set the value in the
spin box accordingly.
- \snippet itemviews/spinboxdelegate/delegate.cpp 2
+ \snippet qitemdelegate/spinbox-delegate.cpp setEditorData
In this example, we know that the editor widget is a spin box, but we
could have provided different editors for different types of data in
@@ -778,7 +776,7 @@
asks the delegate to store the edited value in the model by calling the
\l{QAbstractItemDelegate::setModelData()}{setModelData()} function.
- \snippet itemviews/spinboxdelegate/delegate.cpp 3
+ \snippet qitemdelegate/spinbox-delegate.cpp setModelData
Since the view manages the editor widgets for the delegate, we only
need to update the model with the contents of the editor supplied.
@@ -789,8 +787,8 @@
finished editing by emitting the
\l{QAbstractItemDelegate::closeEditor()}{closeEditor()} signal.
The view ensures that the editor widget is closed and destroyed. In
- this example, we only provide simple editing facilities, so we need
- never emit this signal.
+ this example, we only provide simple editing facilities, so we never
+ need to emit this signal.
All the operations on data are performed through the interface
provided by \l QAbstractItemModel. This makes the delegate mostly
@@ -809,7 +807,7 @@
the view provides all the necessary geometry information inside a
\l{QStyleOptionViewItem}{view option} object.
- \snippet itemviews/spinboxdelegate/delegate.cpp 4
+ \snippet qitemdelegate/spinbox-delegate.cpp updateEditorGeometry
In this case, we just use the geometry information provided by the
view option in the item rectangle. A delegate that renders items with
@@ -1818,8 +1816,6 @@
Note that the model will typically need to provide implementations of the
QAbstractItemModel::insertRows() and QAbstractItemModel::setData() functions.
- \sa {itemviews/puzzle}{Item Views Puzzle Example}
-
\section1 Proxy Models
In the model/view framework, items of data supplied by a single model can be shared
@@ -2313,10 +2309,6 @@
\section1 Related Examples
\list
- \li \l{itemviews/dirview}{Dir View}
- \li \l{itemviews/spinboxdelegate}{Spin Box Delegate}
- \li \l{itemviews/pixelator}{Pixelator}
\li \l{itemviews/simpletreemodel}{Simple Tree Model}
- \li \l{itemviews/chart}{Chart}
\endlist
*/
diff --git a/src/widgets/doc/src/modelview.qdoc b/src/widgets/doc/src/modelview.qdoc
index 6ae62ce7cd..7dd7503d29 100644
--- a/src/widgets/doc/src/modelview.qdoc
+++ b/src/widgets/doc/src/modelview.qdoc
@@ -534,7 +534,7 @@
Other references to delegates in Qt Documentation:
\list
- \li \l{Spin Box Delegate Example}
+ \li \l{Delegate Classes}
\li \l{QAbstractItemDelegate}{QAbstractItemDelegate Class Reference}
\li \l{QSqlRelationalDelegate}{QSqlRelationalDelegate Class Reference}
\li \l{QStyledItemDelegate}{QStyledItemDelegate Class Reference}
@@ -827,11 +827,6 @@
\li QStandardItemModel
\li Basic QDataWidgetMapper usage
\row
- \li Spin Box Delegate
- \li QTableView
- \li QStandardItemModel
- \li Custom delegate that uses a spin box as a cell editor
- \row
\li Spreadsheet
\li {2, 1} QTableView
\li Custom delegates
diff --git a/src/widgets/doc/src/qt6-changes.qdoc b/src/widgets/doc/src/qt6-changes.qdoc
index a334fd948c..c4d757fe6d 100644
--- a/src/widgets/doc/src/qt6-changes.qdoc
+++ b/src/widgets/doc/src/qt6-changes.qdoc
@@ -5,7 +5,7 @@
\page widgets-changes-qt6.html
\title Changes to Qt Widgets
\ingroup changes-qt-5-to-6
- \brief Migrate Qt Widgets to Qt 6.
+ \brief Changes in Kernel classes, Widgets, ItemViews, and Utility Classes.
Qt 6 is a result of the conscious effort to make the framework more
efficient and easy to use.
diff --git a/src/widgets/doc/src/qtwidgets-index.qdoc b/src/widgets/doc/src/qtwidgets-index.qdoc
index cbdd4b2a44..3894467ccf 100644
--- a/src/widgets/doc/src/qtwidgets-index.qdoc
+++ b/src/widgets/doc/src/qtwidgets-index.qdoc
@@ -22,11 +22,10 @@ interfaces
\image parent-child-widgets.png A parent widget containing various child widgets.
The QWidget class provides the basic capability to render to the
- screen, and to handle user input events. All UI elements that Qt
- provides are either subclasses of QWidget, or are used in connection
- with a QWidget subclass. Creating custom widgets is done by
- subclassing QWidget or a suitable subclass and reimplementing the
- virtual event handlers.
+ screen and to handle user input events. All UI elements that Qt
+ provides are either subclasses of QWidget or are used in connection
+ with a QWidget subclass. To create custom widgets, subclass QWidget or a
+ suitable subclass and reimplement the virtual event handlers.
\list
\li \l{Window and Dialog Widgets}
@@ -49,8 +48,9 @@ interfaces
\li \image macos-tabwidget.png
\endtable
- \l{Qt Style Sheets} are a powerful mechanism that allows you to customize the
- appearance of widgets, in addition to what is already possible by subclassing QStyle.
+ \l{Qt Style Sheets} are a powerful mechanism that lets you customize
+ the appearance of widgets, in addition to what is already possible by
+ subclassing QStyle.
\section1 Layouts
@@ -67,7 +67,7 @@ interfaces
\li \image qformlayout-with-6-children.png
\endtable
- \l {Qt Designer} is a powerful tool for interactively creating and
+ \l {Qt Widgets Designer} is a powerful tool for interactively creating and
arranging widgets in layouts.
@@ -115,6 +115,7 @@ interfaces
\list
\li \l{Qt Widgets Examples}
\li \l{Layout Examples}
+ \li \l{Tools Examples}
\endlist
\section1 API Reference
diff --git a/src/widgets/doc/src/widgets-and-layouts/focus.qdoc b/src/widgets/doc/src/widgets-and-layouts/focus.qdoc
index 4214f025f1..b49fc89993 100644
--- a/src/widgets/doc/src/widgets-and-layouts/focus.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/focus.qdoc
@@ -9,7 +9,7 @@
\keyword keyboard focus
- Qt's widgets handle keyboard focus in the ways that have become
+ Qt's widgets handle keyboard focus in ways that have become
customary in GUIs.
The basic issue is that the user's key strokes can be directed at any
@@ -22,7 +22,7 @@
\section1 Focus Motion
- The customs which have evolved for directing keyboard focus to a
+ The customs that have evolved for directing keyboard focus to a
particular widget are these:
\list 1
@@ -54,7 +54,7 @@
You can customize the tab order using QWidget::setTabOrder(). (If
you don't, \uicontrol Tab generally moves focus in the order of widget
- construction.) Qt Designer provides a means of visually
+ construction.) \QD provides a means of visually
changing the tab order.
Since pressing \uicontrol Tab is so common, most widgets that can have focus
@@ -63,7 +63,7 @@
handler that moves the focus.
For example, in a data entry dialog, there might be a field that
- is only necessary in one per cent of all cases. In such a dialog,
+ is only necessary in one percent of all cases. In such a dialog,
\uicontrol Tab could skip this field, and the dialog could use one of
these mechanisms:
@@ -126,14 +126,17 @@
explicitly using focus accelerators such as those provided by
QLabel::setBuddy(), QGroupBox, and QTabBar.
- We advise supporting shortcut focus for all widgets that the user
+ Your application can support shortcut focus for all widgets that the user
may want to jump to. For example, a tab dialog can have keyboard
shortcuts for each of its pages, so the user can press e.g. \uicontrol
- Alt+P to step to the \underline{P}rinting page. It is easy to
- overdo this: there are only a few keys, and it's also important
- to provide keyboard shortcuts for commands. \uicontrol Alt+P is also
- used for Paste, Play, Print, and Print Here in the \l{Standard
- Accelerator Keys} list, for example.
+ Alt+P to step to the \underline{P}rinting page. Keep in mind that it's easy
+ to overdo this, as there are only a few keys, and also important to provide
+ keyboard shortcuts for commands. Refer to the design guidelines for the
+ platform you target, for example Microsoft's \l
+ {https://learn.microsoft.com/en-us/previous-versions/windows/desktop/dnacc/guidelines-for-keyboard-user-interface-design}
+ {guidelines for keyboard user interface design} or Apple's \l
+ {https://developer.apple.com/design/human-interface-guidelines/inputs/focus-and-selection/}
+ {focus and selection} guidelines.
\section2 The User Rotates the Mouse Wheel
diff --git a/src/widgets/doc/src/widgets-and-layouts/gallery.qdoc b/src/widgets/doc/src/widgets-and-layouts/gallery.qdoc
index 851461af1f..822cf1efff 100644
--- a/src/widgets/doc/src/widgets-and-layouts/gallery.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/gallery.qdoc
@@ -15,21 +15,18 @@
integrating to the platform theme. Thus, the final appearance varies
depending on the active theme.
- \table
- \row
- \li The Windows style ("windows") is provided by QWindowsStyle.
- \li \image windows-style.png Windows Style
- \row
- \li \image windows-vista-style.png Windows Vista Style
- \li The Windows Vista style ("windowsvista") is provided by
- QWindowsVistaStyle.
- \row
- \li The macOS style ("macOS") is provided by QMacStyle.
- \li \image macos-style.png \macos Style
- \row
- \li \image fusion-style.png Fusion Style
- \li The Fusion style ("fusion") is provided by QFusionStyle.
- \endtable
+ \image windows-style.png Windows Style
+ \caption The Windows style ("windows") is provided by QWindowsStyle.
+
+ \image windows-vista-style.png Windows Vista Style
+ \caption The Windows Vista style ("windowsvista") is provided by
+ QWindowsVistaStyle.
+
+ \image macos-style.png \macos Style
+ \caption The macOS style ("macOS") is provided by QMacStyle.
+
+ \image fusion-style.png Fusion Style
+ \caption The Fusion style ("fusion") is provided by QFusionStyle.
The Styles example displays the following widgets:
diff --git a/src/widgets/doc/src/widgets-and-layouts/layout.qdoc b/src/widgets/doc/src/widgets-and-layouts/layout.qdoc
index 4a3ded1cb8..5f1d5a7ea9 100644
--- a/src/widgets/doc/src/widgets-and-layouts/layout.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/layout.qdoc
@@ -48,8 +48,8 @@
Qt's layout classes were designed for hand-written C++ code, allowing
measurements to be specified in pixels for simplicity, so they are easy to
- understand and use. The code generated for forms created using Qt Designer also
- uses the layout classes. Qt Designer is useful to use when experimenting with the
+ understand and use. The code generated for forms created using \QD also
+ uses the layout classes. \QD is useful to use when experimenting with the
design of a form since it avoids the compile, link and run cycle usually
involved in user interface development.
@@ -263,8 +263,8 @@
\section1 How to Write A Custom Layout Manager
An alternative to manual layout is to write your own layout manager by
- subclassing QLayout. The \l{layouts/borderlayout}{Border Layout} and
- \l{layouts/flowlayout}{Flow Layout} examples show how to do this.
+ subclassing QLayout. The
+ \l{layouts/flowlayout}{Flow Layout} example shows how to do this.
Here we present an example in detail. The \c CardLayout class is inspired
by the Java layout manager of the same name. It lays out the items (widgets
diff --git a/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc b/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
index fc7193c7bd..05000024e1 100644
--- a/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
@@ -28,7 +28,7 @@
\list
\li \l{Overview}
\li \l{The Style Sheet Syntax}
- \li \l{Qt Designer Integration}
+ \li \l{Qt Widgets Designer Integration}
\li \l{Customizing Qt Widgets Using Style Sheets}
\li \l{Qt Style Sheets Reference}
\li \l{Qt Style Sheets Examples}
@@ -75,7 +75,7 @@
consideration. Unlike palette fiddling, style sheets offer
guarantees: If you set the background color of a QPushButton to be
red, you can be assured that the button will have a red background
- in all styles, on all platforms. In addition, Qt Designer
+ in all styles, on all platforms. In addition, \QD
provides style sheet integration, making it easy to view the effects
of a style sheet in different \l{QStyle}{widget styles}.
@@ -85,22 +85,7 @@
buttons and check boxes to make them stand out. Using this
technique, you can also achieve minor customizations that would
normally require subclassing several style classes, such as
- specifying a \l{QStyle::styleHint()}{style hint}. The
- \l{widgets/stylesheet}{Style Sheet} example depicted below defines
- two distinctive style sheets that you can try out and modify at
- will.
-
- \table
- \row \li \inlineimage stylesheet-pagefold.png
- \row \li Pagefold theme running on Windows
- \endtable
-
- \table
- \row \li \inlineimage stylesheet-coffee-cleanlooks.png
- \li \inlineimage stylesheet-pagefold-mac.png
- \row \li Coffee theme running on Ubuntu Linux
- \li Pagefold theme running on \macos
- \endtable
+ specifying a \l{QStyle::styleHint()}{style hint}.
When a style sheet is active, the QStyle returned by QWidget::style()
is a wrapper "style sheet" style, \e not the platform-specific style. The
@@ -115,7 +100,7 @@
/*!
\page stylesheet-syntax.html
\previouspage Qt Style Sheets
- \nextpage Qt Designer Integration
+ \nextpage Qt Widgets Designer Integration
\title The Style Sheet Syntax
Qt Style Sheet terminology and syntactic rules are almost
@@ -495,11 +480,20 @@
\snippet code/doc_src_stylesheet.cpp 96
When the widget-style font and palette propagation is enabled, font and
- palette changes made through Qt Style Sheets will behave as though the
- user had manually called the corresponding QWidget::setPalette() and
+ palette changes made through Qt Style Sheets will behave as if the user
+ had manually called the corresponding QWidget::setPalette() and
QWidget::setFont() methods on all of the QWidgets targeted by the style
- sheet. If this would have caused propagation in C++, it will cause
- propagation in style sheets and vice versa.
+ sheet.
+
+ \list
+ \li Changes made by a style sheet are propagated.
+ They are pushed to all widgets matching the style sheet once, at the time
+ the change is made.
+ \li Changes made by calling QWidget::setPalette() or QWidget::setFont() are
+ inherited.
+ They are inherited by all existing and future children, where the respective
+ brush or font hasn't been explicitly set.
+ \endlist
\section1 Widgets Inside C++ Namespaces
@@ -525,8 +519,8 @@
For example,
\snippet code/doc_src_stylesheet.qdoc 28
- If the property references an enum declared with Q_ENUMS, you should
- reference its constants by name, i.e., not their numeric value.
+ If the property references an enum declared with Q_ENUM, you should
+ reference its constants by name, not their numeric value.
\note Use the qproperty syntax with care, as it modifies the
widget that is being painted. Also, the qproperty syntax is evaluated only
@@ -538,22 +532,22 @@
\page stylesheet-designer.html
\previouspage The Style Sheet Syntax
\nextpage Customizing Qt Widgets Using Style Sheets
- \title Qt Designer Integration
+ \title Qt Widgets Designer Integration
- Qt Designer{Qt Designer} is an excellent tool
+ \l{Qt Widgets Designer Manual}{\QD} is an excellent tool
to preview style sheets. You can right-click on any widget in Designer
and select \uicontrol{Change styleSheet...} to set the style sheet.
\image designer-stylesheet-options.png
- In Qt 4.2 and later, Qt Designer also includes a
+ In Qt 4.2 and later, \QD also includes a
style sheet syntax highlighter and validator. The validator indicates
if the syntax is valid or invalid, at the bottom left of the \uicontrol{Edit
Style Sheet} dialog.
\image designer-validator-highlighter.png
- When you click \uicontrol{OK} or \uicontrol{Apply}, Qt Designer will automatically display
+ When you click \uicontrol{OK} or \uicontrol{Apply}, \QD will automatically display
the widget with its new stylesheet.
\image designer-stylesheet-usage.png
@@ -561,7 +555,7 @@
/*!
\page stylesheet-customizing.html
- \previouspage Qt Designer Integration
+ \previouspage Qt Widgets Designer Integration
\nextpage Qt Style Sheets Reference
\title Customizing Qt Widgets Using Style Sheets
@@ -687,7 +681,8 @@
\row
\li QAbstractScrollArea \target qabstractscrollarea-widget
\li Supports the \l{box model}.
-
+ \br
+ \br
All derivatives of QAbstractScrollArea, including QTextEdit,
and QAbstractItemView (all item view classes), support
scrollable backgrounds using
@@ -696,7 +691,8 @@
\c{fixed} provides a background-image that does not scroll with the
viewport. Setting the background-attachment to \c{scroll}, scrolls
the background-image when the scroll bars move.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QAbstractScrollArea}
{Customizing QAbstractScrollArea} for an example.
@@ -706,17 +702,21 @@
styled using the \l{#indicator-sub}{::indicator}
subcontrol. By default, the indicator is placed in the Top
Left corner of the Contents rectangle of the widget.
-
+ \br
+ \br
The \l{#spacing-prop}{spacing} property
specifies the spacing between the check indicator and
the text.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QCheckBox}
{Customizing QCheckBox} for an example.
\row
\li QColumnView \target qcolumnview-widget
- \li The grip can be styled be using the \l{image-prop}{image} property.
+ \li The grip can be styled by using the \l{image-prop}{image} property.
+ \br
+ \br
The arrow indicators can by styled using the
\l{left-arrow-sub}{::left-arrow} subcontrol and the
\l{right-arrow-sub}{::right-arrow} subcontrol.
@@ -724,17 +724,25 @@
\row
\li QComboBox \target qcombobox-widget
\li The frame around the combobox can be styled using the
- \l{box model}. The drop-down button can be styled using
+ \l{box model}.
+ \br
+ \br
+ The drop-down button can be styled using
the \l{#drop-down-sub}{::drop-down} subcontrol. By default, the
drop-down button is placed in the top right corner of the padding
- rectangle of the widget. The arrow mark inside the drop-down button
+ rectangle of the widget.
+ \br
+ \br
+ The arrow mark inside the drop-down button
can be styled using the \l{#down-arrow-sub}{::down-arrow}
subcontrol. By default, the arrow is placed in the center of the
contents rectangle of the drop-down subcontrol.
-
+ \br
+ \br
The color of the placeholder text can be set using the
\l{#placeholder-text-color-prop}{placeholder-text-color} property.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QComboBox}{Customizing QComboBox}
for an example.
@@ -763,14 +771,16 @@
\row
\li QDockWidget \target qdockwidget-widget
\li Supports styling of the title bar and the title bar buttons when docked.
-
+ \br
+ \br
The dock widget border can be styled using the \l{#border-prop}{border}
property. The \l{#title-sub}{::title} subcontrol can be used to customize
the title bar. The close and float buttons are positioned with respect
to the \l{title-sub}{::title} subcontrol using the
\l{#close-button-sub}{::close-button} and
\l{#float-button-sub}{::float-button} respectively.
-
+ \br
+ \br
When the title bar is vertical, the \l{#vertical-ps}{:vertical} pseudo
class is set. In addition, depending on QDockWidget::DockWidgetFeature,
the \l{#closable-ps}{:closable}, \l{#floatable-ps}{:floatable} and
@@ -791,31 +801,41 @@
\row
\li QFrame \target qframe-widget
\li Supports the \l{box model}.
-
+ \br
+ \br
Since 4.3, setting a stylesheet on a QLabel automatically
sets the QFrame::frameStyle property to QFrame::StyledPanel.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame}
for an example.
\row
\li QGroupBox \target qgroupbox-widget
- \li Supports the \l{box model}. The title can be styled using the
+ \li Supports the \l{box model}.
+ \br
+ \br
+ The title can be styled using the
\l{#title-sub}{::title} subcontrol. By default, the title is placed
depending on QGroupBox::textAlignment.
-
+ \br
+ \br
In the case of a checkable QGroupBox, the title includes the
check indicator. The indicator is styled using the
\l{#indicator-sub}{::indicator} subcontrol. The
\l{#spacing-prop}{spacing} property can be used to control
the spacing between the text and indicator.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QGroupBox}{Customizing QGroupBox}
for an example.
\row
\li QHeaderView \target qheaderview-widget
- \li Supports the \l{box model}. The sections of the header view are
+ \li Supports the \l{box model}.
+ \br
+ \br
+ The sections of the header view are
styled using the \l{#section-sub}{::section} sub control. The
\c{section} Sub-control supports the \l{#middle-ps}{:middle},
\l{#first-ps}{:first}, \l{#last-ps}{:last},
@@ -823,11 +843,13 @@
\l{#previous-selected-ps}{:previous-selected},
\l{#selected-ps}{:selected},
and \l{#checked-ps}{:checked} pseudo states.
-
+ \br
+ \br
The sort indicator can be styled using the
\l{#up-arrow-sub}{::up-arrow} and the
\l{#down-arrow-sub}{::down-arrow} Sub-control.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QHeaderView}{Customizing QHeaderView}
for an example.
@@ -835,57 +857,72 @@
\li QLabel \target qlabel-widget
\li Supports the \l{box model}. Does not support the
\l{#hover-ps}{:hover} pseudo-state.
-
+ \br
+ \br
Since 4.3, setting a stylesheet on a QLabel automatically
sets the QFrame::frameStyle property to QFrame::StyledPanel.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame} for an
example (a QLabel derives from QFrame).
\row
\li QLineEdit \target qlineedit-widget
\li Supports the \l{box model}.
-
+ \br
+ \br
The color and background of the selected item is styled using
\l{#selection-color-prop}{selection-color} and
\l{#selection-background-color-prop}{selection-background-color}
respectively.
-
+ \br
+ \br
The color of the placeholder text can be set using the
\l{#placeholder-text-color-prop}{placeholder-text-color} property.
-
+ \br
+ \br
The password character can be styled using the
\l{#lineedit-password-character-prop}{lineedit-password-character}
property.
-
+ \br
+ \br
The password mask delay can be changed using the
\l{#lineedit-password-mask-delay-prop}{lineedit-password-mask-delay}
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QLineEdit}{Customizing QLineEdit}
for an example.
\row
\li QListView \target qlistview-widget
- \li Supports the \l{box model}. When
+ \li Supports the \l{box model}.
+ \br
+ \br
+ When
\l{QAbstractItemView::alternatingRowColors}{alternating row colors}
is enabled, the alternating colors can be styled using the
\l{#alternate-background-color-prop}{alternate-background-color}
property.
-
+ \br
+ \br
The color and background of the selected item is styled using
\l{#selection-color-prop}{selection-color} and
\l{#selection-background-color-prop}{selection-background-color}
respectively.
-
+ \br
+ \br
The selection behavior is controlled by the
\l{#show-decoration-selected-prop}{show-decoration-selected} property.
-
+ \br
+ \br
Use the \l{#item-sub}{::item} subcontrol for more fine grained
control over the items in the QListView.
-
+ \br
+ \br
See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to
style scrollable backgrounds.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QListView}
{Customzing QListView} for an example.
@@ -895,45 +932,57 @@
\row
\li QMainWindow \target qmainwindow-widget
- \li Supports styling of the separator
-
+ \li Supports styling of the separator.
+ \br
+ \br
The separator in a QMainWindow when using QDockWidget is styled
using the \l{#separator-sub}{::separator} subcontrol.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QMainWindow}{Customizing QMainWindow}
for an example.
\row
\li QMenu \target qmenu-widget
\li Supports the \l{box model}.
-
+ \br
+ \br
Individual items are styled using the \l{#item-sub}{::item}
subcontrol. In addition to the usually supported pseudo states,
\c{item} subcontrol supports the
\l{#selected-ps}{:selected}, \l{#default-ps}{:default},
\l{#exclusive-ps}{:exclusive} and the
\l{#non-exclusive-ps}{non-exclusive} pseudo states.
-
+ \br
+ \br
The indicator of checkable menu items is styled using the
\l{#indicator-sub}{::indicator} subcontrol.
-
+ \br
+ \br
The separator is styled using the \l{#separator-sub}{::separator}
subcontrol.
-
+ \br
+ \br
For items with a sub menu, the arrow marks are styled using the
\l{right-arrow-sub}{right-arrow} and
\l{left-arrow-sub}{left-arrow}.
-
+ \br
+ \br
The scroller is styled using the \l{#scroller-sub}{::scroller}.
-
+ \br
+ \br
The tear-off is styled using the \l{#tearoff-sub}{::tearoff}.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QMenu}{Customizing QMenu}
for an example.
\row
\li QMenuBar \target qmenubar-widget
- \li Supports the \l{box model}. The \l{#spacing-prop}{spacing}
+ \li Supports the \l{box model}.
+ \br
+ \br
+ The \l{#spacing-prop}{spacing}
property specifies the spacing between menu items.
Individual items are styled using the \l{#item-sub}{::item}
subcontrol.
@@ -952,27 +1001,38 @@
\row
\li QProgressBar \target qprogressbar-widget
- \li Supports the \l{box model}. The chunks of the progress bar
+ \li Supports the \l{box model}.
+ \br
+ \br
+ The chunks of the progress bar
can be styled using the \l{#chunk-sub}{::chunk} subcontrol.
The chunk is displayed on the Contents rectangle of the widget.
-
+ \br
+ \br
If the progress bar displays text, use the \l{text-align-prop}{text-align}
property to position the text.
-
+ \br
+ \br
Indeterminate progress bars have the
\l{#indeterminate-ps}{:indeterminate} pseudo state set.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QProgressBar}{Customizing QProgressBar}
for an example.
\row
\li QPushButton \target qpushbutton-widget
- \li Supports the \l{box model}. Supports the \l{#default-ps}{:default},
+ \li Supports the \l{box model}.
+ \br
+ \br
+ Supports the \l{#default-ps}{:default},
\l{#flat-ps}{:flat}, \l{#checked-ps}{:checked} pseudo states.
-
+ \br
+ \br
Since 5.15, the \l{#icon-prop}{icon} property can be set to
override the button icon.
-
+ \br
+ \br
For QPushButton with a menu, the menu indicator is styled
using the \l{#menu-indicator-sub}{::menu-indicator}
subcontrol. Appearance of checkable push buttons can be
@@ -991,50 +1051,63 @@
\row
\li QRadioButton \target qradiobutton-widget
- \li Supports the \l{box model}. The check indicator can be
+ \li Supports the \l{box model}.
+ \br
+ \br
+ The check indicator can be
styled using the \l{#indicator-sub}{::indicator}
subcontrol. By default, the indicator is placed in the Top
Left corner of the Contents rectangle of the widget.
-
+ \br
+ \br
The \l{#spacing-prop}{spacing} property
specifies the spacing between the check indicator and
the text.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QRadioButton}
{Customizing QRadioButton} for an example.
\row
\li QScrollBar \target qscrollbar-widget
- \li Supports the \l{box model}. The Contents rectangle of the widget
+ \li Supports the \l{box model}.
+ \br
+ \br
+ The Contents rectangle of the widget
is considered to be the groove over which the slider moves. The extent
of the QScrollBar (i.e the width or the height depending on the orientation)
is set using the \l{#width-prop}{width} or \l{#height-prop}{height} property
respectively. To determine the orientation, use the
\l{#horizontal-ps}{:horizontal} and the \l{vertical-ps}{:vertical}
pseudo states.
-
+ \br
+ \br
The slider can be styled using the \l{#handle-sub}{::handle} subcontrol.
Setting the \l{#min-width-prop}{min-width} or \l{#min-height-prop}{min-height}
provides size constraints for the slider depending on the orientation.
-
+ \br
+ \br
The \l{add-line-sub}{::add-line} subcontrol can be used to style the
button to add a line. By default, the add-line subcontrol is placed in
top right corner of the Border rectangle of the widget. Depending on the
orientation the \l{#right-arrow-sub}{::right-arrow} or
\l{#down-arrow-sub}{::down-arrow}. By default, the arrows are placed in
the center of the Contents rectangle of the add-line subcontrol.
-
+ \br
+ \br
The \l{sub-line-sub}{::sub-line} subcontrol can be used to style the
button to subtract a line. By default, the sub-line subcontrol is placed in
bottom right corner of the Border rectangle of the widget. Depending on the
orientation the \l{#left-arrow-sub}{::left-arrow} or
\l{#up-arrow-sub}{::up-arrow}. By default, the arrows are placed in
the center of the Contents rectangle of the sub-line subcontrol.
-
+ \br
+ \br
The \l{sub-page-sub}{::sub-page} subcontrol can be used to style the
region of the slider that subtracts a page. The \l{add-page-sub}{::add-page}
subcontrol can be used to style the region of the slider that adds a page.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QScrollBar}{Customizing QScrollBar}
for an example.
@@ -1043,25 +1116,31 @@
\li Supports the \l{#width-prop}{width},
\l{#height-prop}{height}, and \l{#image-prop}{image}
properties.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QSizeGrip}{Customizing QSizeGrip}
for an example.
\row
\li QSlider \target qslider-widget
- \li Supports the \l{box model}. For horizontal slides, the
+ \li Supports the \l{box model}.
+ \br
+ \br
+ For horizontal slides, the
\l{min-width-prop}{min-width} and \l{height-prop}{height}
properties must be provided. For vertical sliders, the
\l{min-height-prop}{min-height} and \l{width-prop}{width}
properties must be provided.
-
+ \br
+ \br
The groove of the slider is styled
using the \l{#groove-sub}{::groove}. The groove is
positioned by default in the Contents rectangle of the widget.
The thumb of the slider is styled using \l{#handle-sub}{::handle}
subcontrol. The subcontrol moves in the Contents rectangle of
the groove subcontrol.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QSlider}{Customizing QSlider}
for an example.
@@ -1069,7 +1148,8 @@
\li QSpinBox \target qspinbox-widget
\li The frame of the spin box can be styled using the \l{box
model}.
-
+ \br
+ \br
The up button and arrow can be styled using the
\l{#up-button-sub}{::up-button} and
\l{#up-arrow-sub}{::up-arrow} subcontrols. By default,
@@ -1078,7 +1158,8 @@
it occupies half the height of its reference rectangle.
The up-arrow is placed in the center of the Contents
rectangle of the up-button.
-
+ \br
+ \br
The down button and arrow can be styled using the
\l{#down-button-sub}{::down-button} and
\l{#down-arrow-sub}{::down-arrow} subcontrols. By default,
@@ -1087,7 +1168,8 @@
it occupies half the height of its reference rectangle.
The bottom-arrow is placed in the center of the Contents
rectangle of the bottom-button.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QSpinBox}{Customizing QSpinBox}
for an example.
@@ -1095,7 +1177,8 @@
\li QSplitter \target qsplitter-widget
\li Supports the \l{box model}. The handle of the splitter
is styled using the \l{#handle-sub}{::handle} subcontrol.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QSplitter}{Customizing QSplitter}
for an example.
@@ -1105,39 +1188,46 @@
{background} property.
The frame for individual items can be style using the
\l{#item-sub}{::item} subcontrol.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QStatusBar}{Customizing QStatusBar}
for an example.
\row
\li QTabBar \target qtabbar-widget
\li Individual tabs may be styled using the \l{#tab-sub}{::tab} subcontrol.
- Close buttons using the \l{#close-button-sub}{::close-button}
+ Close buttons using the \l{#close-button-sub}{::close-button}.
The tabs support the
\l{#only-one-ps}{:only-one}, \l{#first-ps}{:first},
\l{#last-ps}{:last}, \l{#middle-ps}{:middle},
\l{#previous-selected-ps}{:previous--selected},
\l{#next-selected-ps}{:next-selected},
\l{#selected-ps}{:selected} pseudo states.
-
+ \br
+ \br
The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right},
\l{#bottom-ps}{:bottom} pseudo states depending on the orientation
of the tabs.
-
+ \br
+ \br
Overlapping tabs for the selected state are created by using
negative margins or using the \c{absolute} position scheme.
-
+ \br
+ \br
The tear indicator of the QTabBar is styled using the
\l{#tear-sub}{::tear} subcontrol.
-
+ \br
+ \br
QTabBar used two QToolButtons for its scrollers that can be styled
using the \c{QTabBar QToolButton} selector. To specify the width
of the scroll button use the \l{#scroller-sub}{::scroller}
subcontrol.
-
+ \br
+ \br
The alignment of the tabs within the QTabBar is styled
- using the \l{#Alignment}{alignment} property. \warning
-
+ using the \l{#Alignment}{alignment} property.
+ \br
+ \warning
To change the position of the QTabBar within a QTabWidget, use the
\l{#tab-bar-sub}{tab-bar} subcontrol (and set subcontrol-position).
@@ -1152,15 +1242,18 @@
and \l{#right-corner-sub}{::right-corner} respectively.
The position of the tab bar is controlled using the
\l{#tab-bar-sub}{::tab-bar} subcontrol.
-
+ \br
+ \br
By default, the subcontrols have positions of a QTabWidget in
the QWindowsStyle. To place the QTabBar in the center, set the
subcontrol-position of the tab-bar subcontrol.
-
+ \br
+ \br
The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right},
\l{#bottom-ps}{:bottom} pseudo states depending on the orientation
of the tabs.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QTabWidget and QTabBar}
{Customizing QTabWidget} for an example.
@@ -1171,27 +1264,32 @@
is enabled, the alternating colors can be styled using the
\l{#alternate-background-color-prop}{alternate-background-color}
property.
-
+ \br
+ \br
The color and background of the selected item is styled using
\l{#selection-color-prop}{selection-color} and
\l{#selection-background-color-prop}{selection-background-color}
respectively.
-
+ \br
+ \br
The corner widget in a QTableView is implemented as a QAbstractButton
and can be styled using the "QTableView QTableCornerButton::section"
selector.
-
+ \br
\warning If you only set a background-color on a QTableCornerButton,
the background may not appear unless you set the border property to
some value. This is because, by default, the QTableCornerButton draws a
native border which completely overlaps the background-color.
+ \br
The color of the grid can be specified using the
\l{#gridline-color-prop}{gridline-color} property.
-
+ \br
+ \br
See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to
style scrollable backgrounds.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QTableView}
{Customzing QTableView} for an example.
@@ -1202,15 +1300,18 @@
\row
\li QTextEdit \target qtextedit-widget
\li Supports the \l{box model}.
-
+ \br
+ \br
The color and background of selected text is styled using
\l{#selection-color-prop}{selection-color} and
\l{#selection-background-color-prop}{selection-background-color}
respectively.
-
+ \br
+ \br
The color of the placeholder text can be set using the
\l{#placeholder-text-color-prop}{placeholder-text-color} property.
-
+ \br
+ \br
See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to
style scrollable backgrounds.
@@ -1221,45 +1322,53 @@
\row
\li QToolBar \target qtoolbar-widget
\li Supports the \l{box model}.
-
+ \br
+ \br
The \l{#top-ps}{:top}, \l{#left-ps}{:left}, \l{#right-ps}{:right},
\l{#bottom-ps}{:bottom} pseudo states depending on the area in
which the tool bar is grouped.
-
+ \br
+ \br
The \l{#first-ps}{:first}, \l{#last-ps}{:last}, \l{#middle-ps}{:middle},
\l{#only-one-ps}{:only-one} pseudo states indicator the position
of the tool bar within a line group (See
QStyleOptionToolBar::positionWithinLine).
-
+ \br
+ \br
The separator of a QToolBar is styled using the
\l{#separator-sub}{::separator} subcontrol.
-
+ \br
+ \br
The handle (to move the toolbar) is styled using the
\l{#handle-sub}{::handle} subcontrol.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QToolBar}{Customizing QToolBar}
for an example.
\row
\li QToolButton \target qtoolbutton-widget
\li Supports the \l{box model}.
-
+ \br
+ \br
If the QToolButton has a menu, is
\l{#menu-indicator-sub}{::menu-indicator} subcontrol can be used to
style the indicator. By default, the menu-indicator is positioned
at the bottom right of the Padding rectangle of the widget.
-
+ \br
+ \br
If the QToolButton is in QToolButton::MenuButtonPopup mode,
the \l{#menu-button-sub}{::menu-button} subcontrol is used to draw the
menu button. \l{#menu-arrow-sub}{::menu-arrow} subcontrol is used to
draw the menu arrow inside the menu-button. By default, it is
positioned in the center of the Contents rectangle of the
menu-button subcontrol.
-
+ \br
+ \br
When the QToolButton displays arrows, the \l{#up-arrow-sub}{::up-arrow},
\l{#down-arrow-sub}{::down-arrow}, \l{#left-arrow-sub}{::left-arrow}
and \l{#right-arrow-sub}{::right-arrow} subcontrols are used.
-
+ \br
\warning If you only set a background-color on a QToolButton, the background
will not appear unless you set the border property to some value. This is
because, by default, the QToolButton draws a native border which completely
@@ -1273,7 +1382,8 @@
\row
\li QToolBox \target qtoolbox-widget
\li Supports the \l{box model}.
-
+ \br
+ \br
The individual tabs can by styled using the
\l{#tab-sub}{::tab} subcontrol. The tabs support the
\l{#only-one-ps}{:only-one}, \l{#first-ps}{:first},
@@ -1286,7 +1396,8 @@
\li QToolTip \target qtooltip-widget
\li Supports the \l{box model}. The \l{#opacity-prop}{opacity}
property controls the opacity of the tooltip.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QFrame}{Customizing QFrame}
for an example (a QToolTip is a QFrame).
@@ -1297,27 +1408,33 @@
is enabled, the alternating colors can be styled using the
\l{#alternate-background-color-prop}{alternate-background-color}
property.
-
+ \br
+ \br
The color and background of the selected item is styled using
\l{#selection-color-prop}{selection-color} and
\l{#selection-background-color-prop}{selection-background-color}
respectively.
-
+ \br
+ \br
The selection behavior is controlled by the
\l{#show-decoration-selected-prop}{show-decoration-selected} property.
-
+ \br
+ \br
The branches of the tree view can be styled using the
\l{#branch-sub}{::branch} subcontrol. The
::branch Sub-control supports the \l{open-ps}{:open},
\l{closed-ps}{:closed}, \l{has-siblings-ps}{:has-sibling} and
\l{has-children-ps}{:has-children} pseudo states.
-
+ \br
+ \br
Use the \l{#item-sub}{::item} subcontrol for more fine grained
control over the items in the QTreeView.
-
+ \br
+ \br
See \l{qabstractscrollarea-widget}{QAbsractScrollArea} to
style scrollable backgrounds.
-
+ \br
+ \br
See \l{Qt Style Sheets Examples#Customizing QTreeView}{Customizing QTreeView}
for an example to style the branches.
@@ -1330,7 +1447,8 @@
\li Supports only the \l{Qt Style Sheets Reference#background-prop}{background},
\l{#background-clip-prop}{background-clip} and
\l{#background-origin-prop}{background-origin} properties.
-
+ \br
+ \br
If you subclass from QWidget, you need to provide a paintEvent for your
custom QWidget as below:
\snippet code/doc_src_stylesheet.cpp 32
@@ -1344,23 +1462,44 @@
\section1 List of Properties
- The table below lists all the properties supported by Qt Style
- Sheets. Which values can be given to an property depend on the
+ This section lists all the properties supported by Qt Style
+ Sheets. Which values can be given to a property depend on the
\l{List of Property Types}{property's type}. Unless otherwise
- specified, properties below apply to all widgets. Properties
+ specified, the following properties apply to all widgets. Properties
marked with an asterisk * are specific to Qt and have no equivalent
- in CSS2 or CSS3.
+ in CSS2 or CSS3. The Qt-specific properties are the following:
+ \list
+ \li \l{#gridline-color*}{gridline-color*}
+ \li \l{#image*}{image*}
+ \li \l{#lineedit-password-character*}{lineedit-password-character*}
+ \li \l{#lineedit-password-mask-delay*}{lineedit-password-mask-delay*}
+ \li \l{#messagebox-text-interaction-flags*}{messagebox-text-interaction-flags*}
+ \li \l{#opacity*}{opacity*}
+ \li \l{#placeholder-text-color*}{placeholder-text-color*}
+ \li \l{#selection-background-color*}{selection-background-color*}
+ \li \l{#selection-color*}{selection-color*}
+ \li \l{#show-decoration-selected*}{show-decoration-selected*}
+ \li \l{#spacing*}{spacing*}
+ \li \l{#subcontrol-origin*}{subcontrol-origin*}
+ \li \l{#subcontrol-position*}{subcontrol-position*}
+ \li \l{#widget-animation-duration*}{widget-animation-duration*}
+ \endlist
- \table 100%
- \header
- \li Property
- \li Type
- \li Description
+ \section2 accent-color
- \row
- \li \b{\c alternate-background-color} \target alternate-background-color-prop
- \li \l{#Brush}{Brush} \br
- \li The \l{QAbstractItemView::alternatingRowColors}
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush}
+ \endtable
+
+ The property sets the \c Accent, which is used to emphasize
+ interactive UI elements. If this property is not set, it defaults to the \c highlight color.
+
+ \section2 alternate-background-color
+ \target alternate-background-color-prop
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush}
+ \endtable
+ The \l{QAbstractItemView::alternatingRowColors}
{alternate background color} used in QAbstractItemView subclasses.
If this property is not set, the default value is
@@ -1374,10 +1513,12 @@
See also \l{Qt Style Sheets Reference#background-prop}{background} and
\l{#selection-background-color-prop}{selection-background-color}.
- \row
- \li \b{\c background} \target background-prop
- \li \l{#Background}{Background}
- \li Shorthand notation for setting the background. Equivalent
+ \section2 background
+ \target background-prop
+ \table
+ \row \li \b Type \li \l{#Background}{Background}
+ \endtable
+ Shorthand notation for setting the background. Equivalent
to specifying \c background-color, \c background-image, \c
background-repeat, and/or \c background-position.
@@ -1408,19 +1549,23 @@
\l{#background-attachment-prop}{background-attachment}
and \l{#alternate-background-color-prop}{alternate-background-color}.
- \row
- \li \c background-color \target background-color-prop
- \li \l{#Brush}{Brush} \br
- \li The background color used for the widget.
+ \section2 background-color
+ \target background-color-prop
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush}
+ \endtable
+ The background color used for the widget.
Examples:
\snippet code/doc_src_stylesheet.qdoc 36
- \row
- \li \c background-image \target background-image-prop
- \li \l{#Url}{Url}
- \li The background image used for the widget. Semi-transparent
+ \section2 background-image
+ \target background-image-prop
+ \table
+ \row \li \b Type \li \l{#Url}{Url}
+ \endtable
+ The background image used for the widget. Semi-transparent
parts of the image let the \c background-color shine
through.
@@ -1428,10 +1573,13 @@
\snippet code/doc_src_stylesheet.qdoc 37
- \row
- \li \c background-repeat \target background-repeat-prop
- \li \l{#Repeat}{Repeat}
- \li Whether and how the background image is repeated to fill
+
+ \section2 background-repeat
+ \target background-repeat-prop
+ \table
+ \row \li \b Type \li \l{#Repeat}{Repeat}
+ \endtable
+ Whether and how the background image is repeated to fill
the \c background-origin rectangle.
If this property is not specified, the background image
@@ -1441,10 +1589,11 @@
\snippet code/doc_src_stylesheet.qdoc 38
- \row
- \li \c background-position
- \li \l{#Alignment}{Alignment}
- \li The alignment of the background image within the \c
+ \section2 background-position
+ \table
+ \row \li \b Type \li \l{#Alignment}{Alignment}
+ \endtable
+ The alignment of the background image within the \c
background-origin rectangle.
If this property is not specified, the alignment is \c
@@ -1454,10 +1603,12 @@
\snippet code/doc_src_stylesheet.qdoc 39
- \row
- \li \b{\c background-attachment} \target background-attachment-prop
- \li \l{#Attachment}{Attachment}
- \li Determines whether the background-image in a QAbstractScrollArea
+ \section2 background-attachment
+ \target background-attachment-prop
+ \table
+ \row \li \b Type \li \l{#Attachment}{Attachment}
+ \endtable
+ Determines whether the background-image in a QAbstractScrollArea
is scrolled or fixed with respect to the viewport.
By default, the background-image scrolls with the viewport.
@@ -1467,10 +1618,12 @@
See also \l{Qt Style Sheets Reference#background-prop}{background}
- \row
- \li \b{\c background-clip} \target background-clip-prop
- \li \l{#Origin}{Origin}
- \li The widget's rectangle, in which the \c background is drawn.
+ \section2 background-clip
+ \target background-clip-prop
+ \table
+ \row \li \b Type \li \l{#Origin}{Origin}
+ \endtable
+ The widget's rectangle, in which the \c background is drawn.
This property specifies the rectangle to which the \c background-color
and \c background-image are clipped.
@@ -1491,10 +1644,13 @@
See also \l{Qt Style Sheets Reference#background-prop}{background},
\l{#background-origin-prop}{background-origin} and \l{The Box Model}.
- \row
- \li \b{\c background-origin} \target background-origin-prop
- \li \l{#Origin}{Origin}
- \li The widget's background rectangle, to use in conjunction
+ \section2 background-origin
+ \target background-origin-prop
+ \table
+ \row \li \b Type \li \l{#Origin}{Origin}
+ \endtable
+
+ The widget's background rectangle, to use in conjunction
with \c background-position and \c background-image.
This property is supported by QAbstractItemView
@@ -1513,10 +1669,13 @@
See also \l{Qt Style Sheets Reference#background-prop}{background} and
\l{The Box Model}.
- \row
- \li \b{\c border} \target border-prop
- \li \l{#Border}{Border}
- \li Shorthand notation for setting the widget's border. Equivalent
+ \section2 border
+ \target border-prop
+ \table
+ \row \li \b Type \li \l{#Border}{Border}
+ \endtable
+
+ Shorthand notation for setting the widget's border. Equivalent
to specifying \c border-color, \c border-style, and/or
\c border-width.
@@ -1530,39 +1689,52 @@
\snippet code/doc_src_stylesheet.qdoc 43
- \row
- \li \c border-top
- \li \l{#Border}{Border}
- \li Shorthand notation for setting the widget's top border.
+ \section2 border-top
+
+ \table
+ \row \li \b Type \li \l{#Border}{Border}
+ \endtable
+
+ Shorthand notation for setting the widget's top border.
Equivalent to specifying \c border-top-color, \c
border-top-style, and/or \c border-top-width.
- \row
- \li \c border-right
- \li \l{#Border}{Border}
- \li Shorthand notation for setting the widget's right border.
+ \section2 border-right
+ \table
+ \row \li \b Type \li \l{#Border}{Border}
+ \endtable
+
+ Shorthand notation for setting the widget's right border.
Equivalent to specifying \c border-right-color, \c
border-right-style, and/or \c border-right-width.
- \row
- \li \c border-bottom
- \li \l{#Border}{Border}
- \li Shorthand notation for setting the widget's bottom border.
+ \section2 border-bottom
+ \table
+ \row \li \b Type \li \l{#Border}{Border}
+ \endtable
+
+ Shorthand notation for setting the widget's bottom border.
Equivalent to specifying \c border-bottom-color, \c
border-bottom-style, and/or \c border-bottom-width.
- \row
- \li \c border-left
- \li \l{#Border}{Border}
- \li Shorthand notation for setting the widget's left border.
+ \section2 border-left
+ \table
+ \row \li \b Type \li \l{#Border}{Border}
+ \endtable
+
+ Shorthand notation for setting the widget's left border.
Equivalent to specifying \c border-left-color, \c
border-left-style, and/or \c border-left-width.
- \row
- \li \b{\c border-color} \target border-attrs
- \target border-color-prop
- \li \l{#Box Colors}{Box Colors}
- \li The color of all the border's edges. Equivalent to
+
+ \section2 border-color
+ \target border-attrs
+ \target border-color-prop
+ \table
+ \row \li \b Type \li \l{#Box Colors}{Box Colors}
+ \endtable
+
+ The color of all the border's edges. Equivalent to
specifying \c border-top-color, \c border-right-color, \c
border-bottom-color, and \c border-left-color.
@@ -1584,30 +1756,41 @@
\l{Qt Style Sheets Reference#border-width-prop}{border-width},
\l{#border-image-prop}{border-image}, and \l{The Box Model}.
- \row
- \li \c border-top-color
- \li \l{#Brush}{Brush} \br
- \li The color of the border's top edge.
+ \section2 border-top-color
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush}
+ \endtable
- \row
- \li \c border-right-color
- \li \l{#Brush}{Brush} \br
- \li The color of the border's right edge.
+ The color of the border's top edge.
- \row
- \li \c border-bottom-color
- \li \l{#Brush}{Brush} \br
- \li The color of the border's bottom edge.
+ \section2 border-right-color
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush}
+ \endtable
- \row
- \li \c border-left-color
- \li \l{#Brush}{Brush} \br
- \li The color of the border's left edge.
+ The color of the border's right edge.
- \row
- \li \b{\c border-image} \target border-image-prop
- \li \l{#Border Image}{Border Image}
- \li The image used to fill the border. The image is cut into
+ \section2 border-bottom-color
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush}
+ \endtable
+
+ The color of the border's bottom edge.
+
+ \section2 border-left-color
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush}
+ \endtable
+
+ The color of the border's left edge.
+
+ \section2 border-image
+ \target border-image-prop
+ \table
+ \row \li \b Type \li \l{#Border Image}{Border Image}
+ \endtable
+
+ The image used to fill the border. The image is cut into
nine parts and stretched appropriately if necessary. See
\l{#Border Image}{Border Image} for details.
@@ -1622,10 +1805,13 @@
\l{Qt Style Sheets Reference#border-width-prop}{border-width}, and
\l{The Box Model}.
- \row
- \li \b{\c border-radius} \target border-radius-prop
- \li \l{#Radius}{Radius}
- \li The radius of the border's corners. Equivalent to
+ \section2 border-radius
+ \target border-radius-prop
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
+
+ The radius of the border's corners. Equivalent to
specifying \c border-top-left-radius, \c
border-top-right-radius, \c border-bottom-right-radius,
and \c border-bottom-left-radius.
@@ -1648,33 +1834,44 @@
See also \l{Qt Style Sheets Reference#border-width-prop}{border-width} and
\l{The Box Model}.
- \row
- \li \c border-top-left-radius
- \li \l{#Radius}{Radius}
- \li The radius of the border's top-left corner.
+ \section2 border-top-left-radius
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
- \row
- \li \c border-top-right-radius
- \li \l{#Radius}{Radius}
- \li The radius of the border's top-right corner.
+ The radius of the border's top-left corner.
- \row
- \li \c border-bottom-right-radius
- \li \l{#Radius}{Radius}
- \li The radius of the border's bottom-right corner. Setting
+ \section2 border-top-right-radius
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
+
+ The radius of the border's top-right corner.
+
+ \section2 border-bottom-right-radius
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
+
+ The radius of the border's bottom-right corner. Setting
this property to a positive value results in a rounded
corner.
- \row
- \li \c border-bottom-left-radius
- \li \l{#Radius}{Radius}
- \li The radius of the border's bottom-left corner. Setting this
+ \section2 border-bottom-left-radius
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
+
+ The radius of the border's bottom-left corner. Setting this
property to a positive value results in a rounded corner.
- \row
- \li \b{\c border-style} \target border-style-prop
- \li \l {Border Style}
- \li The style of all the border's edges.
+ \section2 border-style
+ \target border-style-prop
+ \table
+ \row \li \b Type \li \l{#Border Style}{Border Style}
+ \endtable
+
+ The style of all the border's edges.
This property is supported by QAbstractItemView
subclasses, QAbstractSpinBox subclasses, QCheckBox,
@@ -1692,30 +1889,41 @@
\l{Qt Style Sheets Reference#border-style-prop}{border-style},
\l{#border-image-prop}{border-image}, and \l{The Box Model}.
- \row
- \li \c border-top-style
- \li \l{#Border Style}{Border Style}
- \li The style of the border's top edge.
+ \section2 border-top-style
+ \table
+ \row \li \b Type \li \l{#Border Style}{Border Style}}
+ \endtable
- \row
- \li \c border-right-style
- \li \l{#Border Style}{Border Style}
- \li The style of the border's right edge/
+ The style of the border's top edge.
- \row
- \li \c border-bottom-style
- \li \l{#Border Style}{Border Style}
- \li The style of the border's bottom edge.
+ \section2 border-right-style
+ \table
+ \row \li \b Type \li \l{#Border Style}{Border Style}
+ \endtable
- \row
- \li \c border-left-style
- \li \l{#Border Style}{Border Style}
- \li The style of the border's left edge.
+ The style of the border's right edge.
- \row
- \li \b{\c border-width} \target border-width-prop
- \li \l{#Box Lengths}{Box Lengths}
- \li The width of the border. Equivalent to setting \c
+ \section2 border-bottom-style
+ \table
+ \row \li \b Type \li \l{#Border Style}{Border Style}
+ \endtable
+
+ The style of the border's bottom edge.
+
+ \section2 border-left-style
+ \table
+ \row \li \b Type \li \l{#Border Style}{Border Style}
+ \endtable
+
+ The style of the border's left edge.
+
+ \section2 border-width
+ \target border-width-prop
+ \table
+ \row \li \b Type \li \l{#Box Lengths}{Box Lengths}
+ \endtable
+
+ The width of the border. Equivalent to setting \c
border-top-width, \c border-right-width, \c
border-bottom-width, and \c border-left-width.
@@ -1735,30 +1943,41 @@
\l{#border-image-prop}{border-image}, and
\l{The Box Model}.
- \row
- \li \c border-top-width
- \li \l{#Length}{Length}
- \li The width of the border's top edge.
+ \section2 border-top-width
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
- \row
- \li \c border-right-width
- \li \l{#Length}{Length}
- \li The width of the border's right edge.
+ The width of the border's top edge.
- \row
- \li \c border-bottom-width
- \li \l{#Length}{Length}
- \li The width of the border's bottom edge.
+ \section2 border-right-width
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
- \row
- \li \c border-left-width
- \li \l{#Length}{Length}
- \li The width of the border's left edge.
+ The width of the border's right edge.
- \row
- \li \b{\c bottom} \target bottom-prop
- \li \l{#Length}{Length}
- \li If \l{#position-prop}{position} is \c relative (the
+ \section2 border-bottom-width
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The width of the border's bottom edge.
+
+ \section2 border-left-width
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The width of the border's left edge.
+
+ \section2 bottom
+ \target bottom-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ If \l{#position-prop}{position} is \c relative (the
default), moves a subcontrol by a certain offset up;
specifying \tt{bottom: \e{y}} is then equivalent to
specifying \tt{\l{Qt Style Sheets Reference#top-prop}{top}: -\e{y}}.
@@ -1776,10 +1995,14 @@
See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{#right-prop}{right}, and
\l{Qt Style Sheets Reference#top-prop}{top}.
- \row
- \li \b{\c button-layout} \target button-layout-prop
- \li \l{#Number}{Number}
- \li The layout of buttons in a QDialogButtonBox or
+
+ \section2 button-layout
+ \target button-layout-prop
+ \table
+ \row \li \b Type \li \l{#Number}{Number}
+ \endtable
+
+ The layout of buttons in a QDialogButtonBox or
a QMessageBox. The possible values are 0
(\l{QDialogButtonBox::}{WinLayout}), 1
(\l{QDialogButtonBox::}{MacLayout}), 2
@@ -1795,10 +2018,14 @@
\snippet code/doc_src_stylesheet.qdoc 49
- \row
- \li \b{\c color} \target color-prop
- \li \l{#Brush}{Brush} \br
- \li The color used to render text.
+
+ \section2 color
+ \target color-prop
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush} \br
+ \endtable
+
+ The color used to render text.
This property is supported by all widgets that respect
the \l QWidget::palette.
@@ -1814,10 +2041,12 @@
See also \l{Qt Style Sheets Reference#background-prop}{background} and
\l{#selection-color-prop}{selection-color}.
- \row
- \li \b{\c dialogbuttonbox-buttons-have-icons}
- \li \l{#Boolean}{Boolean}
- \li Whether the buttons in a QDialogButtonBox show icons
+ \section2 dialogbuttonbox-buttons-have-icons
+ \table
+ \row \li \b Type \li \l{#Boolean}{Boolean}
+ \endtable
+
+ Whether the buttons in a QDialogButtonBox show icons
If this property is set to 1, the buttons of a QDialogButtonBox
show icons; if it is set to 0, the icons are not shown.
@@ -1846,10 +2075,13 @@
\snippet code/doc_src_stylesheet.qdoc 52
\endomit
- \row
- \li \b{\c font} \target font-prop
- \li \l{#Font}{Font}
- \li Shorthand notation for setting the text's font. Equivalent
+ \section2 font
+ \target font-prop
+ \table
+ \row \li \b Type \li \l{#Font}{Font}
+ \endtable
+
+ Shorthand notation for setting the text's font. Equivalent
to specifying \c font-family, \c font-size, \c font-style,
and/or \c font-weight.
@@ -1863,43 +2095,54 @@
\snippet code/doc_src_stylesheet.qdoc 53
- \row
- \li \c font-family
- \li String
- \li The font family.
+ \section2 font-family
+ \table
+ \row \li \b Type \li String
+ \endtable
+
+ The font family.
Example:
\snippet code/doc_src_stylesheet.qdoc 54
- \row
- \li \c font-size
- \li \l{#Font Size}{Font Size}
- \li The font size. In this version of Qt, only pt and px metrics are
+ \section2 font-size
+ \table
+ \row \li \b Type \li \l{#Font Size}{Font Size}
+ \endtable
+
+ The font size. In this version of Qt, only pt and px metrics are
supported.
Example:
\snippet code/doc_src_stylesheet.qdoc 55
- \row
- \li \c font-style
- \li \l {Font Style}
- \li The font style.
+ \section2 font-style
+ \table
+ \row \li \b Type \li \l {#Font Style} {Font Style}
+ \endtable
+
+ The font style.
Example:
\snippet code/doc_src_stylesheet.qdoc 56
- \row
- \li \c font-weight
- \li \l{#Font Weight}{Font Weight}
- \li The weight of the font.
+ \section2 font-weight
+ \table
+ \row \li \b Type \li \l{#Font Weight}{Font Weight}
+ \endtable
- \row
- \li \b{\c gridline-color}* \target gridline-color-prop
- \li \l{#Color}{Color} \br
- \li The color of the grid line in a QTableView.
+ The weight of the font.
+
+ \section2 gridline-color*
+ \target gridline-color-prop
+ \table
+ \row \li \b Type \li \l{#Color}{Color}
+ \endtable
+
+ The color of the grid line in a QTableView.
If this property is not specified, it defaults to the
value specified by the current style for the
@@ -1909,10 +2152,14 @@
\snippet code/doc_src_stylesheet.qdoc 57
- \row
- \li \b{\c height} \target height-prop
- \li \l{#Length}{Length}
- \li The height of a subcontrol (or in some case, a widget).
+
+ \section2 height
+ \target height-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The height of a subcontrol (or in some case, a widget).
If this property is not specified, it defaults to a value
that depends on the subcontrol/widget and on the current style.
@@ -1928,10 +2175,13 @@
See also \l{#width-prop}{width}.
- \row
- \li \b{\c icon} \target icon-prop
- \li \l{#Url}{Url}+
- \li The icon that is used, for widgets that have an icon.
+ \section2 icon
+ \target icon-prop
+ \table
+ \row \li \b Type \li \l{#Url}{Url}+
+ \endtable
+
+ The icon that is used, for widgets that have an icon.
The only widget currently supporting this property is QPushButton.
@@ -1942,10 +2192,13 @@
Available since 5.15.
- \row
- \li \b{\c icon-size} \target icon-size-prop
- \li \l{#Length}{Length}
- \li The width and height of the icon in a widget.
+ \section2 icon-size
+ \target icon-size-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The width and height of the icon in a widget.
The icon size of the following widgets can be set using this
property.
@@ -1960,10 +2213,13 @@
\li QTreeView
\endlist
- \row
- \li \b{\c image}* \target image-prop
- \li \l{#Url}{Url}+
- \li The image that is drawn in the contents rectangle of a
+ \section2 image*
+ \target image-prop
+ \table
+ \row \li \b Type \li \l{#Url}{Url}+
+ \endtable
+
+ The image that is drawn in the contents rectangle of a
subcontrol.
The image property accepts a list of \l{#Url}{Url}s or
@@ -1988,16 +2244,23 @@
\snippet code/doc_src_stylesheet.qdoc 59
- \row
- \li \b{\c image-position} \target image-position-prop
- \li \l{#Alignment}{alignment}
- \li In Qt 4.3 and later, the alignment of the image image's position can be specified
+
+ \section2 image-position
+ \target image-position-prop
+ \table
+ \row \li \b Type \li \l{#Alignment}{alignment}
+ \endtable
+
+ In Qt 4.3 and later, the alignment of the image image's position can be specified
using relative or absolute position.
- \row
- \li \b{\c left} \target left-prop
- \li \l{#Length}{Length}
- \li If \l{#position-prop}{position} is \c relative (the
+ \section2 left
+ \target left-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ If \l{#position-prop}{position} is \c relative (the
default), moves a subcontrol by a certain offset to
the right.
@@ -2015,10 +2278,13 @@
See also \l{#right-prop}{right}, \l{Qt Style Sheets Reference#top-prop}{top}, and
\l{#bottom-prop}{bottom}.
- \row
- \li \b{\c lineedit-password-character*} \target lineedit-password-character-prop
- \li \l{#Number}{Number}
- \li The QLineEdit password character as a Unicode number.
+ \section2 lineedit-password-character*
+ \target lineedit-password-character-prop
+ \table
+ \row \li \b Type \li \l{#Number}{Number}
+ \endtable
+
+ The QLineEdit password character as a Unicode number.
If this property is not specified, it defaults to the
value specified by the current style for the
@@ -2028,27 +2294,33 @@
\snippet code/doc_src_stylesheet.qdoc 61
- \row
- \li \b{\c lineedit-password-mask-delay*} \target lineedit-password-mask-delay-prop
- \li \l{#Number}{Number}
- \li The QLineEdit password mask delay in milliseconds before
+
+ \section2 lineedit-password-mask-delay*
+ \target lineedit-password-mask-delay-prop
+ \table
+ \row \li \b Type \li \l{#Number}{Number}
+ \endtable
+
+ The QLineEdit password mask delay in milliseconds before
\l{#lineedit-password-character-prop}{lineedit-password-character} is applied to visible character.
If this property is not specified, it defaults to the
value specified by the current style for the
\l{QStyle::}{SH_LineEdit_PasswordMaskDelay} style hint.
- \b{This property was added in Qt 5.4.}
+ Available since Qt 5.4.
Example:
\snippet code/doc_src_stylesheet.qdoc 160
+ \section2 margin
+ \target margin-prop
+ \table
+ \row \li \b Type \li \l {#Box Lengths}{Box Lengths}
+ \endtable
- \row
- \li \b{\c margin} \target margin-prop
- \li \l {Box Lengths}
- \li The widget's margins. Equivalent to specifying \c
+ The widget's margins. Equivalent to specifying \c
margin-top, \c margin-right, \c margin-bottom, and \c
margin-left.
@@ -2067,30 +2339,37 @@
See also \l{Qt Style Sheets Reference#padding-prop}{padding},
\l{#spacing-prop}{spacing}, and \l{The Box Model}.
- \row
- \li \c margin-top
- \li \l{#Length}{Length}
- \li The widget's top margin.
+ \section2 margin-top
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+ The widget's top margin.
- \row
- \li \c margin-right
- \li \l{#Length}{Length}
- \li The widget's right margin.
+ \section2 margin-right
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+ The widget's right margin.
- \row
- \li \c margin-bottom
- \li \l{#Length}{Length}
- \li The widget's bottom margin.
+ \section2 margin-bottom
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+ The widget's bottom margin.
- \row
- \li \c margin-left
- \li \l{#Length}{Length}
- \li The widget's left margin.
+ \section2 margin-left
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+ The widget's left margin.
- \row
- \li \b{\c max-height} \target max-height-prop
- \li \l{#Length}{Length}
- \li The widget's or a subcontrol's maximum height.
+ \section2 max-height
+ \target max-height-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The widget's or a subcontrol's maximum height.
This property is supported by QAbstractItemView
subclasses, QAbstractSpinBox subclasses, QCheckBox,
@@ -2107,10 +2386,13 @@
See also \l{#max-width-prop}{max-width}.
- \row
- \li \b{\c max-width} \target max-width-prop
- \li \l{#Length}{Length}
- \li The widget's or a subcontrol's maximum width.
+ \section2 max-width
+ \target max-width-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The widget's or a subcontrol's maximum width.
This property is supported by QAbstractItemView
subclasses, QAbstractSpinBox subclasses, QCheckBox,
@@ -2127,11 +2409,13 @@
See also \l{#max-height-prop}{max-height}.
+ \section2 messagebox-text-interaction-flags*
+ \target messagebox-text-interaction-flags-prop
+ \table
+ \row \li \b Type \li \l{#Number}{Number}
+ \endtable
- \row
- \li \b{\c messagebox-text-interaction-flags*} \target messagebox-text-interaction-flags-prop
- \li \l{#Number}{Number}
- \li The interaction behavior for text in a message box.
+ The interaction behavior for text in a message box.
Possible values are based on Qt::TextInteractionFlags.
If this property is not specified, it defaults to the
@@ -2143,10 +2427,13 @@
\snippet code/doc_src_stylesheet.qdoc 65
- \row
- \li \b{\c min-height} \target min-height-prop
- \li \l{#Length}{Length}
- \li The widget's or a subcontrol's minimum height.
+ \section2 min-height
+ \target min-height-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The widget's or a subcontrol's minimum height.
This property is supported by QAbstractItemView
subclasses, QAbstractSpinBox subclasses, QCheckBox,
@@ -2169,10 +2456,13 @@
See also \l{#min-width-prop}{min-width}.
- \row
- \li \b{\c min-width} \target min-width-prop
- \li \l{#Length}{Length}
- \li The widget's or a subcontrol's minimum width.
+ \section2 min-width
+ \target min-width-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The widget's or a subcontrol's minimum width.
This property is supported by QAbstractItemView
subclasses, QAbstractSpinBox subclasses, QCheckBox,
@@ -2195,10 +2485,13 @@
See also \l{#min-height-prop}{min-height}.
- \row
- \li \b{\c opacity*} \target opacity-prop
- \li \l{#Number}{Number}
- \li The opacity for a widget. Possible values are from 0
+ \section2 opacity*
+ \target opacity-prop
+ \table
+ \row \li \b Type \li \l{#Number}{Number}
+ \endtable
+
+ The opacity for a widget. Possible values are from 0
(transparent) to 255 (opaque). For the moment, this is
only supported for \l{QToolTip}{tooltips}.
@@ -2210,58 +2503,69 @@
\snippet code/doc_src_stylesheet.qdoc 68
- \row
- \li \b outline
- \li
- \li The outline drawn around the object's border.
+ \section2 outline
- \row
- \li \b outline-color
- \li \l{#Color}{Color}
- \li The color of the outline.
+ The outline drawn around the object's border.
+
+ \section2 outline-color
+ \table
+ \row \li \b Type \li \l{#Color}{Color}
+ \endtable
+
+ The color of the outline.
See also \l{Qt Style Sheets Reference#border-color-prop}{border-color}
- \row
- \li \b outline-offset
- \li \l{#Length}{Length}
- \li The outline's offset from the border of the widget.
+ \section2 outline-offset
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
- \row
- \li \b outline-style
- \li
- \li Specifies the pattern used to draw the outline.
- See also \l{Qt Style Sheets Reference#border-style-prop}{border-style}
+ The outline's offset from the border of the widget.
- \row
- \li \b outline-radius
- \li
- \li Adds rounded corners to the outline
+ \section2 outline-style
- \row
- \li \b outline-bottom-left-radius
- \li \l{#Radius}{Radius}
- \li The radius for the bottom-left rounded corner of the outline.
+ Specifies the pattern used to draw the outline.
+ See also \l{Qt Style Sheets Reference#border-style-prop}{border-style}
- \row
- \li \b outline-bottom-right-radius
- \li \l{#Radius}{Radius}
- \li The radius for the bottom-right rounded corner of the outline.
+ \section2 outline-radius
- \row
- \li \b outline-top-left-radius
- \li \l{#Radius}{Radius}
- \li The radius for the top-left corner of the outline.
+ Adds rounded corners to the outline.
- \row
- \li \b outline-top-right-radius
- \li \l{#Radius}{Radius}
- \li The radius for the top-right rounded corner of the outline.
+ \section2 outline-bottom-left-radius
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
+ The radius for the bottom-left rounded corner of the outline.
- \row
- \li \b{\c padding} \target padding-prop
- \li \l{#Box Lengths}{Box Lengths}
- \li The widget's padding. Equivalent to specifying \c
+ \section2 outline-bottom-right-radius
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
+
+ The radius for the bottom-right rounded corner of the outline.
+
+ \section2 outline-top-left-radius
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
+
+ The radius for the top-left corner of the outline.
+
+ \section2 outline-top-right-radius
+ \table
+ \row \li \b Type \li \l{#Radius}{Radius}
+ \endtable
+
+ The radius for the top-right rounded corner of the outline.
+
+ \section2 padding
+ \target padding-prop
+ \table
+ \row \li \b Type \li \l{#Box Lengths}{Box Lengths}
+ \endtable
+
+ The widget's padding. Equivalent to specifying \c
padding-top, \c padding-right, \c padding-bottom, and \c
padding-left.
@@ -2280,37 +2584,50 @@
See also \l{#margin-prop}{margin},
\l{#spacing-prop}{spacing}, and \l{The Box Model}.
- \row
- \li \c padding-top
- \li \l{#Length}{Length}
- \li The widget's top padding.
+ \section2 padding-top
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
- \row
- \li \c padding-right
- \li \l{#Length}{Length}
- \li The widget's right padding.
+ The widget's top padding.
- \row
- \li \c padding-bottom
- \li \l{#Length}{Length}
- \li The widget's bottom padding.
+ \section2 padding-right
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
- \row
- \li \c padding-left
- \li \l{#Length}{Length}
- \li The widget's left padding.
+ The widget's right padding.
- \row
- \li \b{\c paint-alternating-row-colors-for-empty-area}
- \target paint-alternating-row-colors-for-empty-area-prop
- \li \c bool
- \li Whether the QTreeView paints alternating row colors for the empty
+ \section2 padding-bottom
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The widget's bottom padding.
+
+ \section2 padding-left
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The widget's left padding.
+
+ \section2 paint-alternating-row-colors-for-empty-area
+ \target paint-alternating-row-colors-for-empty-area-prop
+ \table
+ \row \li \b Type \li \c bool
+ \endtable
+
+ Whether the QTreeView paints alternating row colors for the empty
area (i.e the area where there are no items)
- \row
- \li \b{\c placeholder-text-color*} \target placeholder-text-color-prop
- \li \l{#Brush}{Brush} \br
- \li The color used for the placeholder text of text editing widgets.
+ \section2 placeholder-text-color*
+ \target placeholder-text-color-prop
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush} \br
+ \endtable
+
+ The color used for the placeholder text of text editing widgets.
If this property is not set, the default value is whatever
is set for the palette's \l{QPalette::}{PlaceholderText}
@@ -2322,11 +2639,14 @@
Available since 6.5.
- \row
- \li \b{\c position} \target position-prop
- \li \c relative \br
- | \c absolute
- \li Whether offsets specified using \l{Qt Style Sheets Reference#left-prop}{left},
+ \section2 position
+ \target position-prop
+ \table
+ \row \li \b Type \li \c relative \br
+ | \c absolute
+ \endtable
+
+ Whether offsets specified using \l{Qt Style Sheets Reference#left-prop}{left},
\l{#right-prop}{right}, \l{Qt Style Sheets Reference#top-prop}{top}, and
\l{#bottom-prop}{bottom} are relative or absolute
coordinates.
@@ -2334,10 +2654,13 @@
If this property is not specified, it defaults to \c
relative.
- \row
- \li \b{\c right} \target right-prop
- \li \l{#Length}{Length}
- \li If \l{#position-prop}{position} is \c relative (the
+ \section2 right
+ \target right-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ If \l{#position-prop}{position} is \c relative (the
default), moves a subcontrol by a certain offset to
the left; specifying \tt{right: \e{x}} is then equivalent
to specifying \tt{\l{Qt Style Sheets Reference#left-prop}{left}: -\e{x}}.
@@ -2354,10 +2677,13 @@
See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{Qt Style Sheets Reference#top-prop}{top}, and
\l{#bottom-prop}{bottom}.
- \row
- \li \b{\c selection-background-color*} \target selection-background-color-prop
- \li \l{#Brush}{Brush} \br
- \li The background of selected text or items.
+ \section2 selection-background-color*
+ \target selection-background-color-prop
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush}
+ \endtable
+
+ The background of selected text or items.
This property is supported by all widgets that respect
the \l QWidget::palette and that show selection text.
@@ -2373,10 +2699,14 @@
See also \l{#selection-color-prop}{selection-color} and
\l{Qt Style Sheets Reference#background-prop}{background}.
- \row
- \li \b{\c selection-color*} \target selection-color-prop
- \li \l{#Brush}{Brush} \br
- \li The foreground of selected text or items.
+
+ \section2 selection-color*
+ \target selection-color-prop
+ \table
+ \row \li \b Type \li \l{#Brush}{Brush} \br
+ \endtable
+
+ The foreground of selected text or items.
This property is supported by all widgets that respect
the \l QWidget::palette and that show selection text.
@@ -2393,10 +2723,14 @@
\l{#selection-background-color-prop}{selection-background-color}
and \l{#color-prop}{color}.
- \row
- \li \b{\c show-decoration-selected*} \target show-decoration-selected-prop
- \li \l{#Boolean}{Boolean}
- \li Controls whether selections in a QListView cover the
+
+ \section2 show-decoration-selected*
+ \target show-decoration-selected-prop
+ \table
+ \row \li \b Type \li \l{#Boolean}{Boolean}
+ \endtable
+
+ Controls whether selections in a QListView cover the
entire row or just the extent of the text.
If this property is not specified, it defaults to the
@@ -2408,10 +2742,13 @@
\snippet code/doc_src_stylesheet.qdoc 73
- \row
- \li \b{\c spacing*} \target spacing-prop
- \li \l{#Length}{Length}
- \li Internal spacing in the widget.
+ \section2 spacing*
+ \target spacing-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ Internal spacing in the widget.
This property is supported by QCheckBox, checkable
\l{QGroupBox}es, QMenuBar, and QRadioButton.
@@ -2426,10 +2763,14 @@
See also \l{Qt Style Sheets Reference#padding-prop}{padding} and
\l{#margin-prop}{margin}.
- \row
- \li \b{\c subcontrol-origin*} \target subcontrol-origin-prop
- \li \l{#Origin}{Origin}
- \li The origin rectangle of the subcontrol within the
+
+ \section2 subcontrol-origin*
+ \target subcontrol-origin-prop
+ \table
+ \row \li \b Type \li \l{#Origin}{Origin}
+ \endtable
+
+ The origin rectangle of the subcontrol within the
parent element.
If this property is not specified, the default is \c
@@ -2442,10 +2783,13 @@
See also
\l{Qt Style Sheets Reference#subcontrol-position-prop}{subcontrol-position}.
- \row
- \li \b{\c subcontrol-position*} \target subcontrol-position-prop
- \li \l{#Alignment}{Alignment}
- \li The alignment of the subcontrol within the origin
+ \section2 subcontrol-position*
+ \target subcontrol-position-prop
+ \table
+ \row \li \b Type \li \l{#Alignment}{Alignment}
+ \endtable
+
+ The alignment of the subcontrol within the origin
rectangle specified by \l{Qt Style Sheets Reference#subcontrol-origin-prop}
{subcontrol-origin}.
@@ -2459,32 +2803,41 @@
See also
\l{Qt Style Sheets Reference#subcontrol-origin-prop}{subcontrol-origin}.
- \row
- \li \b{\c titlebar-show-tooltips-on-buttons}}
- \target titlebar-show-tooltips-on-buttons-prop
- \li \c bool
- \li Whether tool tips are shown on window title bar buttons.
+ \section2 titlebar-show-tooltips-on-buttons
+ \target titlebar-show-tooltips-on-buttons-prop
+ \table
+ \row \li \b Type \li \c bool
+ \endtable
- \row
- \li \b{\c widget-animation-duration*} \target widget-animation-duration
- \li \l{#Number}{Number}
- \li How much an animation should last (in milliseconds).
+ Whether tool tips are shown on window title bar buttons.
+
+
+ \section2 widget-animation-duration*
+ \target widget-animation-duration
+ \table
+ \row \li \b Type \li \l{#Number}{Number}
+ \endtable
+
+ How much an animation should last (in milliseconds).
A value equal to zero means that the animations will be disabled.
If this property is not specified, it defaults to the
value specified by the current style for the
\l{QStyle::}{SH_Widget_Animation_Duration} style hint.
- \b{This property was added in Qt 5.10.}
+ Available since Qt 5.10.
Example:
\snippet code/doc_src_stylesheet.qdoc 162
- \row
- \li \b{\c text-align} \target text-align-prop
- \li \l{#Alignment}{Alignment}
- \li The alignment of text and icon within the contents of the widget.
+ \section2 text-align
+ \target text-align-prop
+ \table
+ \row \li \b Type \li \l{#Alignment}{Alignment}
+ \endtable
+
+ The alignment of text and icon within the contents of the widget.
If this value is not specified, it defaults to the value
that depends on the native style.
@@ -2496,18 +2849,25 @@
This property is currently supported only by QPushButton
and QProgressBar.
- \row
- \li \b{\c text-decoration}
- \li \c none \br
+ \section2 text-decoration
+ \table
+ \row \li \b Type
+ \li \c none \br
\c underline \br
\c overline \br
\c line-through
- \li Additional text effects
+ \endtable
- \row
- \li \b{\c top} \target top-prop
- \li \l{#Length}{Length}
- \li If \l{#position-prop}{position} is \c relative (the
+ Additional text effects.
+
+
+ \section2 top
+ \target top-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ If \l{#position-prop}{position} is \c relative (the
default), moves a subcontrol by a certain offset
down.
@@ -2525,10 +2885,13 @@
See also \l{Qt Style Sheets Reference#left-prop}{left}, \l{#right-prop}{right}, and
\l{#bottom-prop}{bottom}.
- \row
- \li \b{\c width} \target width-prop
- \li \l{#Length}{Length}
- \li The width of a subcontrol (or a widget in some cases).
+ \section2 width
+ \target width-prop
+ \table
+ \row \li \b Type \li \l{#Length}{Length}
+ \endtable
+
+ The width of a subcontrol (or a widget in some cases).
If this property is not specified, it defaults to a value
that depends on the subcontrol/widget and on the current style.
@@ -2544,19 +2907,24 @@
See also \l{#height-prop}{height}.
- \row
- \li \b -qt-background-role
- \li \l{#paletterole}{PaletteRole}
- \li The \c{background-color} for the subcontrol or widget based on the
+
+ \section2 -qt-background-role
+ \table
+ \row \li \b Type \li \l{#paletterole}{PaletteRole}
+ \endtable
+
+ The \c{background-color} for the subcontrol or widget based on the
chosen role.
- \row
- \li \b -qt-style-features
- \li \c list
- \li The list of CSS properties that you want to apply Qt-specific styles on.
+ \section2 -qt-style-features
+ \table
+ \row \li \b Type \li \c list
+ \endtable
+
+ The list of CSS properties that you want to apply Qt-specific styles on.
\note The \c list can only include properties that are not pixmap-based.
- \endtable
+
\target list of icons
\section1 List of Icons
@@ -3064,6 +3432,7 @@
\row
\li \b{PaletteRole} \target PaletteRole
\li \c alternate-base \br
+ | \c accent \br
| \c base \br
| \c bright-text \br
| \c button \br
@@ -4065,7 +4434,7 @@
\image stylesheet-treeview.png
- \sa {Style Sheet Example}, {Supported HTML Subset}, QStyle
+ \sa {Supported HTML Subset}, QStyle
\section1 Common Mistakes
diff --git a/src/widgets/doc/src/widgets-tutorial.qdoc b/src/widgets/doc/src/widgets-tutorial.qdoc
index c223340079..e0ad4d850c 100644
--- a/src/widgets/doc/src/widgets-tutorial.qdoc
+++ b/src/widgets/doc/src/widgets-tutorial.qdoc
@@ -101,6 +101,7 @@
/*!
\example tutorials/widgets/toplevel
\title Widgets Tutorial - Creating a Window
+ \examplecategory {User Interface Components}
If a widget is created without a parent, it is treated as a window, or
\e{top-level widget}, when it is shown. Since it has no parent object to
@@ -127,6 +128,7 @@
/*!
\example tutorials/widgets/childwidget
\title Widgets Tutorial - Child Widgets
+ \examplecategory {User Interface Components}
We can add a child widget to the window created in the previous example by
passing \c window as the parent to its constructor. In this case, we add a
@@ -149,6 +151,7 @@
/*!
\example tutorials/widgets/windowlayout
\title Widgets Tutorial - Using Layouts
+ \examplecategory {User Interface Components}
Usually, child widgets are arranged inside a window using layout objects
rather than by specifying positions and sizes explicitly. Here, we
@@ -183,6 +186,7 @@
/*!
\example tutorials/widgets/nestedlayouts
\title Widgets Tutorial - Nested Layouts
+ \examplecategory {User Interface Components}
Just as widgets can contain other widgets, layouts can be used to provide
different levels of grouping for widgets. Here, we want to display a
@@ -211,7 +215,7 @@
As well as QHBoxLayout and QVBoxLayout, Qt also provides QGridLayout
and QFormLayout classes to help with more complex user interfaces.
- These can be seen if you run Qt Designer.
+ These can be seen if you run \QD.
\section1 Setting up the Model
diff --git a/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc b/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
index 192d05aff7..6b0315f10a 100644
--- a/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
+++ b/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
@@ -6,18 +6,20 @@
\brief Windows and Dialogs in Qt.
\ingroup qt-gui-concepts
- A \l{Widgets Tutorial}{widget} that is not embedded in a parent widget is called a window.
- (Usually, windows have a frame and a title bar, although it is also possible to create
- windows without such decoration using suitable window flags). In Qt, QMainWindow
- and the various subclasses of QDialog are the most common window types.
+ A \l{Widgets Tutorial}{widget} that is not embedded in a parent widget is
+ called a window. Usually, windows have a frame and a title bar, although it
+ is also possible to create windows without such decoration using suitable
+ window flags. In Qt, QMainWindow and the various subclasses of QDialog are
+ the most common window types.
In applications, windows provide the screen space upon which the user
interface is built. Windows separate applications visually from each other
- and usually provide a window decoration that allows the user to resize and
- position the applications according to his preferences. Windows are typically
- integrated into the desktop environment and to some degree managed by the
- window management system that the desktop environment provides. For instance,
- selected windows of an application are represented in the task bar.
+ and usually provide a window decoration that allows you to resize and
+ position the applications according to your preferences. Windows are
+ typically integrated into the desktop environment and to some degree managed
+ by the window management system that the desktop environment provides. For
+ instance, selected windows of an application are represented in the task
+ bar.
\section1 Primary and Secondary Windows
@@ -27,8 +29,8 @@
In addition, a QWidget that has a parent can become a window by setting the
Qt::Window flag. Depending on the window management system
- such \e{secondary windows} are usually stacked on top of their respective parent
- window, and not have a task bar entry of their own.
+ such \e{secondary windows} are usually stacked on top of their respective
+ parent window and do not have a task bar entry of their own.
The QMainWindow class sets the Qt::Window flag in its constructor,
as it is designed to be used as a window and provides facilities that are
@@ -37,20 +39,21 @@
\section1 Main Windows and Dialogs
The \l{Application Main Window} provides the framework for building the
- application's main user interface, and are created by subclassing QMainWindow.
+ application's main user interface and are created by subclassing
+ QMainWindow.
QMainWindow has its own layout to which you can add a \l{QMenuBar}{menu bar},
\l{QToolBar}{tool bars}, \l{QDockWidget}{dockable widgets} and a
\l{QStatusBar}{status bar}. The center area can be occupied by any kind of
QWidget.
- \l{Dialog Windows} are used as secondary windows that present the user with
+ \l{Dialog Windows} are used as secondary windows that present you with
options and choices. Dialogs are created by subclassing QDialog and using
\l{Widgets and Layouts}{widgets and layouts} to implement the user interface.
In addition, Qt provides a number of ready-made standard dialogs that can be
used for standard tasks like file or font selection.
- Both main windows and dialogs can be created with Qt Designer, Qt's visual design tool.
- Using Qt Designer is a lot faster than hand-coding, and makes it easy to test different
+ Both main windows and dialogs can be created with \QD, Qt's visual design tool.
+ Using \QD is a lot faster than hand-coding, and makes it easy to test different
design ideas. Creating designs visually and reading the code generated by
\l{uic} is a great way to learn Qt!
@@ -59,8 +62,8 @@
QWidget provides several functions that deal with a widget's
geometry. Some of these functions operate on the pure client area
- (i.e. the window excluding the window frame), others include the
- window frame. The differentiation is done in a way that covers the
+ (that is, the window excluding the window frame), others include the
+ window frame. QWidget differentiates in a way that covers the
most common usage transparently.
\list
@@ -99,9 +102,9 @@
Furthermore, a toolkit cannot simply place windows on the screen. All
Qt can do is to send certain hints to the window manager. The window
- manager, a separate process, may either obey, ignore or misunderstand
+ manager, a separate process, may either obey, ignore, or misunderstand
them. Due to the partially unclear Inter-Client Communication
- Conventions Manual (ICCCM), window placement is handled quite
+ Conventions Manual (ICCCM), window placement is handled
differently in existing window managers.
X11 provides no standard or easy way to get the frame geometry
@@ -115,6 +118,15 @@
depends on the result of QWidget::frameGeometry() and the
capability of the window manager to do proper window placement,
neither of which can be guaranteed.
+
+ \section2 Wayland Peculiarities
+
+ On Wayland, programmatically setting or getting the position of a top-level window from the
+ client-side is typically not supported. Technically speaking, it depends on the shell
+ interface. For typical desktop compositors, however, the default shell interface will be
+ \c{XDG Shell}, which does not support manual positioning of windows. In such cases, Qt will
+ ignore calls to set the top-level position of a window, and, when queried, the window position
+ will always be returned as QPoint(0, 0).
*/
/*!
@@ -128,8 +140,8 @@
\section1 Overview of the Main Window Classes
These classes provide everything you need for a typical modern main
- application window, like the main window itself, menu and tool bars,
- a status bar, etc.
+ application window, such as the main window itself, menu and tool bars,
+ and a status bar.
\annotatedlist mainwindow-classes
@@ -139,8 +151,8 @@
associated user interface components:
\list
- \li QMainWindow is the central class around which applications
- can be built. Along with the companion QDockWidget and QToolBar
+ \li QMainWindow is the central class around which applications can be
+ built. Along with the companion QDockWidget and QToolBar
classes, it represents the top-level user interface of the application.
\li QDockWidget provides a widget that can be used to create
@@ -157,11 +169,11 @@
\section1 Example Code
- Using QMainWindow is straightforward. Generally, we subclass
+ Using QMainWindow is straightforward. Generally, you subclass
QMainWindow and set up menus, toolbars, and dock widgets inside
the QMainWindow constructor.
- To add a menu bar to the main window, we simply create the menus, and
+ To add a menu bar to the main window, create the menus, and
add them to the main window's menu bar. Note that the
QMainWindow::menuBar() function will automatically create the menu bar
the first time it is called. You can also call
@@ -172,8 +184,8 @@
\snippet mainwindows/menus/mainwindow.cpp 5
\dots
- Once actions have been created, we can add them to the main window
- components. To begin with, we add them to the pop-up menus:
+ Once actions have been created, you can add them to the main window
+ components. To begin with, add them to the pop-up menus:
\snippet mainwindows/menus/mainwindow.cpp 10
\dots
@@ -186,7 +198,7 @@
provides this function, making it easy to reuse actions in different
parts of the main window. This avoids unnecessary duplication of work.
- We create a toolbar as a child of the main window, and add the desired
+ Create a toolbar as a child of the main window, and add the desired
actions to it:
\code
@@ -203,7 +215,7 @@
newAct and \c openAct will be displayed both on the toolbar and in
the file menu.
- QDockWidget is used in a similar way to QToolBar. We create a
+ QDockWidget is used in a similar way to QToolBar. You create a
dock widget as a child of the main window, and add widgets as children
of the dock widget:
@@ -212,7 +224,7 @@
In this example, the dock widget can only be placed in the left and
right dock areas, and it is initially placed in the left dock area.
- The QMainWindow API allows the programmer to customize which dock
+ The QMainWindow API lets you customize which dock
widget areas occupy the four corners of the dock widget area. If
required, the default can be changed with the
QMainWindow::setCorner() function:
@@ -225,7 +237,7 @@
\image mainwindow-docks-example.png
- Once all of the main window components have been set up, the central widget
+ Once all the main window components have been set up, the central widget
is created and installed by using code similar to the following:
\snippet code/doc_src_qt4-mainwindow.cpp 3
diff --git a/src/widgets/effects/qgraphicseffect_p.h b/src/widgets/effects/qgraphicseffect_p.h
index 4f9313e2b7..378258148c 100644
--- a/src/widgets/effects/qgraphicseffect_p.h
+++ b/src/widgets/effects/qgraphicseffect_p.h
@@ -121,6 +121,7 @@ public:
QGraphicsEffect::ChangeFlags flags;
if (source) {
flags |= QGraphicsEffect::SourceDetached;
+ source->d_func()->effectBoundingRectChanged();
source->d_func()->invalidateCache();
source->d_func()->detach();
delete source;
diff --git a/src/widgets/effects/qpixmapfilter.cpp b/src/widgets/effects/qpixmapfilter.cpp
index b433d49afc..fc3ea8bba3 100644
--- a/src/widgets/effects/qpixmapfilter.cpp
+++ b/src/widgets/effects/qpixmapfilter.cpp
@@ -15,7 +15,6 @@
#include "private/qpaintengine_raster_p.h"
#include "qmath.h"
#include "private/qmath_p.h"
-#include "private/qmemrotate_p.h"
#include "private/qdrawhelper_p.h"
#include <memory>
@@ -363,7 +362,7 @@ static void convolute(
(((cr*(255-a) >> 8)+r) << 16)+
(((cg*(255-a) >> 8)+g) << 8)+
(((cb*(255-a) >> 8)+b));
- *output++ = color;;
+ *output++ = color;
}
xk++;
}
@@ -555,314 +554,10 @@ QRectF QPixmapBlurFilter::boundingRectFor(const QRectF &rect) const
return rect.adjusted(-delta, -delta, delta, delta);
}
-template <int shift>
-inline int qt_static_shift(int value)
-{
- if (shift == 0)
- return value;
- else if (shift > 0)
- return value << (uint(shift) & 0x1f);
- else
- return value >> (uint(-shift) & 0x1f);
-}
-
-template<int aprec, int zprec>
-inline void qt_blurinner(uchar *bptr, int &zR, int &zG, int &zB, int &zA, int alpha)
-{
- QRgb *pixel = (QRgb *)bptr;
-
-#define Z_MASK (0xff << zprec)
- const int A_zprec = qt_static_shift<zprec - 24>(*pixel) & Z_MASK;
- const int R_zprec = qt_static_shift<zprec - 16>(*pixel) & Z_MASK;
- const int G_zprec = qt_static_shift<zprec - 8>(*pixel) & Z_MASK;
- const int B_zprec = qt_static_shift<zprec>(*pixel) & Z_MASK;
-#undef Z_MASK
-
- const int zR_zprec = zR >> aprec;
- const int zG_zprec = zG >> aprec;
- const int zB_zprec = zB >> aprec;
- const int zA_zprec = zA >> aprec;
-
- zR += alpha * (R_zprec - zR_zprec);
- zG += alpha * (G_zprec - zG_zprec);
- zB += alpha * (B_zprec - zB_zprec);
- zA += alpha * (A_zprec - zA_zprec);
-
-#define ZA_MASK (0xff << (zprec + aprec))
- *pixel =
- qt_static_shift<24 - zprec - aprec>(zA & ZA_MASK)
- | qt_static_shift<16 - zprec - aprec>(zR & ZA_MASK)
- | qt_static_shift<8 - zprec - aprec>(zG & ZA_MASK)
- | qt_static_shift<-zprec - aprec>(zB & ZA_MASK);
-#undef ZA_MASK
-}
-
-const int alphaIndex = (QSysInfo::ByteOrder == QSysInfo::BigEndian ? 0 : 3);
-
-template<int aprec, int zprec>
-inline void qt_blurinner_alphaOnly(uchar *bptr, int &z, int alpha)
-{
- const int A_zprec = int(*(bptr)) << zprec;
- const int z_zprec = z >> aprec;
- z += alpha * (A_zprec - z_zprec);
- *(bptr) = z >> (zprec + aprec);
-}
-
-template<int aprec, int zprec, bool alphaOnly>
-inline void qt_blurrow(QImage & im, int line, int alpha)
-{
- uchar *bptr = im.scanLine(line);
-
- int zR = 0, zG = 0, zB = 0, zA = 0;
-
- if (alphaOnly && im.format() != QImage::Format_Indexed8)
- bptr += alphaIndex;
-
- const int stride = im.depth() >> 3;
- const int im_width = im.width();
- for (int index = 0; index < im_width; ++index) {
- if (alphaOnly)
- qt_blurinner_alphaOnly<aprec, zprec>(bptr, zA, alpha);
- else
- qt_blurinner<aprec, zprec>(bptr, zR, zG, zB, zA, alpha);
- bptr += stride;
- }
-
- bptr -= stride;
-
- for (int index = im_width - 2; index >= 0; --index) {
- bptr -= stride;
- if (alphaOnly)
- qt_blurinner_alphaOnly<aprec, zprec>(bptr, zA, alpha);
- else
- qt_blurinner<aprec, zprec>(bptr, zR, zG, zB, zA, alpha);
- }
-}
-
-/*
-* expblur(QImage &img, int radius)
-*
-* Based on exponential blur algorithm by Jani Huhtanen
-*
-* In-place blur of image 'img' with kernel
-* of approximate radius 'radius'.
-*
-* Blurs with two sided exponential impulse
-* response.
-*
-* aprec = precision of alpha parameter
-* in fixed-point format 0.aprec
-*
-* zprec = precision of state parameters
-* zR,zG,zB and zA in fp format 8.zprec
-*/
-template <int aprec, int zprec, bool alphaOnly>
-void expblur(QImage &img, qreal radius, bool improvedQuality = false, int transposed = 0)
-{
- // halve the radius if we're using two passes
- if (improvedQuality)
- radius *= qreal(0.5);
-
- Q_ASSERT(img.format() == QImage::Format_ARGB32_Premultiplied
- || img.format() == QImage::Format_RGB32
- || img.format() == QImage::Format_Indexed8
- || img.format() == QImage::Format_Grayscale8);
-
- // choose the alpha such that pixels at radius distance from a fully
- // saturated pixel will have an alpha component of no greater than
- // the cutOffIntensity
- const qreal cutOffIntensity = 2;
- int alpha = radius <= qreal(1e-5)
- ? ((1 << aprec)-1)
- : qRound((1<<aprec)*(1 - qPow(cutOffIntensity * (1 / qreal(255)), 1 / radius)));
-
- int img_height = img.height();
- for (int row = 0; row < img_height; ++row) {
- for (int i = 0; i <= int(improvedQuality); ++i)
- qt_blurrow<aprec, zprec, alphaOnly>(img, row, alpha);
- }
-
- QImage temp(img.height(), img.width(), img.format());
- temp.setDevicePixelRatio(img.devicePixelRatio());
- if (transposed >= 0) {
- if (img.depth() == 8) {
- qt_memrotate270(reinterpret_cast<const quint8*>(img.bits()),
- img.width(), img.height(), img.bytesPerLine(),
- reinterpret_cast<quint8*>(temp.bits()),
- temp.bytesPerLine());
- } else {
- qt_memrotate270(reinterpret_cast<const quint32*>(img.bits()),
- img.width(), img.height(), img.bytesPerLine(),
- reinterpret_cast<quint32*>(temp.bits()),
- temp.bytesPerLine());
- }
- } else {
- if (img.depth() == 8) {
- qt_memrotate90(reinterpret_cast<const quint8*>(img.bits()),
- img.width(), img.height(), img.bytesPerLine(),
- reinterpret_cast<quint8*>(temp.bits()),
- temp.bytesPerLine());
- } else {
- qt_memrotate90(reinterpret_cast<const quint32*>(img.bits()),
- img.width(), img.height(), img.bytesPerLine(),
- reinterpret_cast<quint32*>(temp.bits()),
- temp.bytesPerLine());
- }
- }
-
- img_height = temp.height();
- for (int row = 0; row < img_height; ++row) {
- for (int i = 0; i <= int(improvedQuality); ++i)
- qt_blurrow<aprec, zprec, alphaOnly>(temp, row, alpha);
- }
-
- if (transposed == 0) {
- if (img.depth() == 8) {
- qt_memrotate90(reinterpret_cast<const quint8*>(temp.bits()),
- temp.width(), temp.height(), temp.bytesPerLine(),
- reinterpret_cast<quint8*>(img.bits()),
- img.bytesPerLine());
- } else {
- qt_memrotate90(reinterpret_cast<const quint32*>(temp.bits()),
- temp.width(), temp.height(), temp.bytesPerLine(),
- reinterpret_cast<quint32*>(img.bits()),
- img.bytesPerLine());
- }
- } else {
- img = temp;
- }
-}
-#define AVG(a,b) ( ((((a)^(b)) & 0xfefefefeUL) >> 1) + ((a)&(b)) )
-#define AVG16(a,b) ( ((((a)^(b)) & 0xf7deUL) >> 1) + ((a)&(b)) )
-
-Q_WIDGETS_EXPORT QImage qt_halfScaled(const QImage &source)
-{
- if (source.width() < 2 || source.height() < 2)
- return QImage();
-
- QImage srcImage = source;
-
- if (source.format() == QImage::Format_Indexed8 || source.format() == QImage::Format_Grayscale8) {
- // assumes grayscale
- QImage dest(source.width() / 2, source.height() / 2, srcImage.format());
- dest.setDevicePixelRatio(source.devicePixelRatio());
-
- const uchar *src = reinterpret_cast<const uchar*>(const_cast<const QImage &>(srcImage).bits());
- qsizetype sx = srcImage.bytesPerLine();
- qsizetype sx2 = sx << 1;
-
- uchar *dst = reinterpret_cast<uchar*>(dest.bits());
- qsizetype dx = dest.bytesPerLine();
- int ww = dest.width();
- int hh = dest.height();
-
- for (int y = hh; y; --y, dst += dx, src += sx2) {
- const uchar *p1 = src;
- const uchar *p2 = src + sx;
- uchar *q = dst;
- for (int x = ww; x; --x, ++q, p1 += 2, p2 += 2)
- *q = ((int(p1[0]) + int(p1[1]) + int(p2[0]) + int(p2[1])) + 2) >> 2;
- }
-
- return dest;
- } else if (source.format() == QImage::Format_ARGB8565_Premultiplied) {
- QImage dest(source.width() / 2, source.height() / 2, srcImage.format());
- dest.setDevicePixelRatio(source.devicePixelRatio());
-
- const uchar *src = reinterpret_cast<const uchar*>(const_cast<const QImage &>(srcImage).bits());
- qsizetype sx = srcImage.bytesPerLine();
- qsizetype sx2 = sx << 1;
-
- uchar *dst = reinterpret_cast<uchar*>(dest.bits());
- qsizetype dx = dest.bytesPerLine();
- int ww = dest.width();
- int hh = dest.height();
-
- for (int y = hh; y; --y, dst += dx, src += sx2) {
- const uchar *p1 = src;
- const uchar *p2 = src + sx;
- uchar *q = dst;
- for (int x = ww; x; --x, q += 3, p1 += 6, p2 += 6) {
- // alpha
- q[0] = AVG(AVG(p1[0], p1[3]), AVG(p2[0], p2[3]));
- // rgb
- const quint16 p16_1 = (p1[2] << 8) | p1[1];
- const quint16 p16_2 = (p1[5] << 8) | p1[4];
- const quint16 p16_3 = (p2[2] << 8) | p2[1];
- const quint16 p16_4 = (p2[5] << 8) | p2[4];
- const quint16 result = AVG16(AVG16(p16_1, p16_2), AVG16(p16_3, p16_4));
- q[1] = result & 0xff;
- q[2] = result >> 8;
- }
- }
-
- return dest;
- } else if (source.format() != QImage::Format_ARGB32_Premultiplied
- && source.format() != QImage::Format_RGB32)
- {
- srcImage = source.convertToFormat(QImage::Format_ARGB32_Premultiplied);
- }
-
- QImage dest(source.width() / 2, source.height() / 2, srcImage.format());
- dest.setDevicePixelRatio(source.devicePixelRatio());
-
- const quint32 *src = reinterpret_cast<const quint32*>(const_cast<const QImage &>(srcImage).bits());
- qsizetype sx = srcImage.bytesPerLine() >> 2;
- qsizetype sx2 = sx << 1;
-
- quint32 *dst = reinterpret_cast<quint32*>(dest.bits());
- qsizetype dx = dest.bytesPerLine() >> 2;
- int ww = dest.width();
- int hh = dest.height();
-
- for (int y = hh; y; --y, dst += dx, src += sx2) {
- const quint32 *p1 = src;
- const quint32 *p2 = src + sx;
- quint32 *q = dst;
- for (int x = ww; x; --x, q++, p1 += 2, p2 += 2)
- *q = AVG(AVG(p1[0], p1[1]), AVG(p2[0], p2[1]));
- }
-
- return dest;
-}
-
-Q_WIDGETS_EXPORT void qt_blurImage(QPainter *p, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0)
-{
- if (blurImage.format() != QImage::Format_ARGB32_Premultiplied
- && blurImage.format() != QImage::Format_RGB32)
- {
- blurImage = blurImage.convertToFormat(QImage::Format_ARGB32_Premultiplied);
- }
-
- qreal scale = 1;
- if (radius >= 4 && blurImage.width() >= 2 && blurImage.height() >= 2) {
- blurImage = qt_halfScaled(blurImage);
- scale = 2;
- radius *= qreal(0.5);
- }
-
- if (alphaOnly)
- expblur<12, 10, true>(blurImage, radius, quality, transposed);
- else
- expblur<12, 10, false>(blurImage, radius, quality, transposed);
-
- if (p) {
- p->scale(scale, scale);
- p->setRenderHint(QPainter::SmoothPixmapTransform);
- p->drawImage(QRect(QPoint(0, 0), blurImage.deviceIndependentSize().toSize()), blurImage);
- }
-}
-
-Q_WIDGETS_EXPORT void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed = 0)
-{
- if (blurImage.format() == QImage::Format_Indexed8 || blurImage.format() == QImage::Format_Grayscale8)
- expblur<12, 10, true>(blurImage, radius, quality, transposed);
- else
- expblur<12, 10, false>(blurImage, radius, quality, transposed);
-}
-
Q_GUI_EXPORT extern bool qt_scaleForTransform(const QTransform &transform, qreal *scale);
+Q_GUI_EXPORT extern void qt_blurImage(QPainter *p, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0);
+
/*!
\internal
*/
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
index 7b2e3fe734..8a5280d44c 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
@@ -459,9 +459,7 @@ void SequentialAnchorData::updateChildrenSizes()
// "from" or "to", that _contains_ one of them.
AnchorVertex *prev = from;
- for (int i = 0; i < m_edges.size(); ++i) {
- AnchorData *e = m_edges.at(i);
-
+ for (AnchorData *e : m_edges) {
const bool edgeIsForward = (e->from == prev);
if (edgeIsForward) {
e->sizeAtMinimum = interpolate(minFactor, e->minSize, e->minPrefSize,
@@ -496,9 +494,7 @@ void SequentialAnchorData::calculateSizeHints()
AnchorVertex *prev = from;
- for (int i = 0; i < m_edges.size(); ++i) {
- AnchorData *edge = m_edges.at(i);
-
+ for (AnchorData *edge : m_edges) {
const bool edgeIsForward = (edge->from == prev);
if (edgeIsForward) {
minSize += edge->minSize;
@@ -532,12 +528,10 @@ void AnchorData::dump(int indent) {
p->firstEdge->dump(indent+2);
p->secondEdge->dump(indent+2);
} else if (type == Sequential) {
- SequentialAnchorData *s = static_cast<SequentialAnchorData *>(this);
- int kids = s->m_edges.count();
- qDebug("%*s type: sequential(%d):", indent, "", kids);
- for (int i = 0; i < kids; ++i) {
- s->m_edges.at(i)->dump(indent+2);
- }
+ const auto *s = static_cast<SequentialAnchorData *>(this);
+ qDebug("%*s type: sequential(%lld):", indent, "", qint64(s->m_edges.size()));
+ for (AnchorData *e : s->m_edges)
+ e->dump(indent + 2);
} else {
qDebug("%*s type: Normal:", indent, "");
}
@@ -1153,12 +1147,10 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge)
g.createEdge(edge->from, edge->to, edge);
} else if (edge->type == AnchorData::Sequential) {
- SequentialAnchorData *sequence = static_cast<SequentialAnchorData *>(edge);
+ const auto *sequence = static_cast<SequentialAnchorData *>(edge);
- for (int i = 0; i < sequence->m_edges.size(); ++i) {
- AnchorData *data = sequence->m_edges.at(i);
+ for (AnchorData *data : sequence->m_edges)
restoreSimplifiedAnchor(data);
- }
delete sequence;
@@ -2554,7 +2546,7 @@ void QGraphicsAnchorLayoutPrivate::identifyNonFloatItems_helper(const AnchorData
nonFloatingItemsIdentifiedSoFar->insert(ad->item);
break;
case AnchorData::Sequential:
- foreach (const AnchorData *d, static_cast<const SequentialAnchorData *>(ad)->m_edges)
+ for (const AnchorData *d : static_cast<const SequentialAnchorData *>(ad)->m_edges)
identifyNonFloatItems_helper(d, nonFloatingItemsIdentifiedSoFar);
break;
case AnchorData::Parallel:
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.h b/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
index 987d3847fd..880e262d34 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
@@ -155,20 +155,21 @@ inline QString AnchorData::toString() const
struct SequentialAnchorData : public AnchorData
{
SequentialAnchorData(const QList<AnchorVertex *> &vertices, const QList<AnchorData *> &edges)
- : AnchorData(), m_children(vertices), m_edges(edges)
+ : AnchorData(), m_edges(edges)
{
type = AnchorData::Sequential;
isVertical = m_edges.at(0)->isVertical;
#ifdef QT_DEBUG
name = QString::fromLatin1("%1 -- %2").arg(vertices.first()->toString(), vertices.last()->toString());
+#else
+ Q_UNUSED(vertices);
#endif
}
virtual void updateChildrenSizes() override;
void calculateSizeHints();
- QList<AnchorVertex *> m_children; // list of vertices in the sequence
- QList<AnchorData *> m_edges; // keep the list of edges too.
+ const QList<AnchorData *> m_edges; // keep the list of edges too.
};
struct ParallelAnchorData : public AnchorData
diff --git a/src/widgets/graphicsview/qgraphicsgridlayout.cpp b/src/widgets/graphicsview/qgraphicsgridlayout.cpp
index 139ccf3af8..e4599d20bb 100644
--- a/src/widgets/graphicsview/qgraphicsgridlayout.cpp
+++ b/src/widgets/graphicsview/qgraphicsgridlayout.cpp
@@ -146,7 +146,7 @@ void QGraphicsGridLayout::addItem(QGraphicsLayoutItem *item, int row, int column
}
/*!
- \fn QGraphicsGridLayout::addItem(QGraphicsLayoutItem *item, int row, int column, Qt::Alignment alignment = 0)
+ \fn QGraphicsGridLayout::addItem(QGraphicsLayoutItem *item, int row, int column, Qt::Alignment alignment)
Adds \a item to the grid on \a row and \a column. You can specify
an optional \a alignment for \a item.
diff --git a/src/widgets/graphicsview/qgraphicsitem.cpp b/src/widgets/graphicsview/qgraphicsitem.cpp
index f622670aff..17ea830cab 100644
--- a/src/widgets/graphicsview/qgraphicsitem.cpp
+++ b/src/widgets/graphicsview/qgraphicsitem.cpp
@@ -904,7 +904,6 @@ QGraphicsItemPrivate::QGraphicsItemPrivate()
scenePosDescendants(false),
pendingPolish(false),
mayHaveChildWithGraphicsEffect(false),
- isDeclarativeItem(false),
sendParentChangeNotification(false),
dirtyChildrenBoundingRect(true),
globalStackingOrder(-1),
@@ -6502,7 +6501,7 @@ void QGraphicsItem::setData(int key, const QVariant &value)
}
/*!
- \fn T qgraphicsitem_cast(QGraphicsItem *item)
+ \fn template <class T> qgraphicsitem_cast(QGraphicsItem *item)
\relates QGraphicsItem
\since 4.2
@@ -7650,66 +7649,6 @@ void QGraphicsObject::updateMicroFocus()
QGraphicsItem::updateMicroFocus();
}
-void QGraphicsItemPrivate::children_append(QDeclarativeListProperty<QGraphicsObject> *list, QGraphicsObject *item)
-{
- if (item) {
- QGraphicsObject *graphicsObject = static_cast<QGraphicsObject *>(list->object);
- if (QGraphicsItemPrivate::get(graphicsObject)->sendParentChangeNotification) {
- item->setParentItem(graphicsObject);
- } else {
- QGraphicsItemPrivate::get(item)->setParentItemHelper(graphicsObject, nullptr, nullptr);
- }
- }
-}
-
-int QGraphicsItemPrivate::children_count(QDeclarativeListProperty<QGraphicsObject> *list)
-{
- QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object));
- return d->children.size();
-}
-
-QGraphicsObject *QGraphicsItemPrivate::children_at(QDeclarativeListProperty<QGraphicsObject> *list, int index)
-{
- QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object));
- if (index >= 0 && index < d->children.size())
- return d->children.at(index)->toGraphicsObject();
- else
- return nullptr;
-}
-
-void QGraphicsItemPrivate::children_clear(QDeclarativeListProperty<QGraphicsObject> *list)
-{
- QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object));
- int childCount = d->children.size();
- if (d->sendParentChangeNotification) {
- for (int index = 0; index < childCount; index++)
- d->children.at(0)->setParentItem(nullptr);
- } else {
- for (int index = 0; index < childCount; index++)
- QGraphicsItemPrivate::get(d->children.at(0))->setParentItemHelper(nullptr, nullptr, nullptr);
- }
-}
-
-/*!
- Returns a list of this item's children.
-
- The items are sorted by stacking order. This takes into account both the
- items' insertion order and their Z-values.
-
-*/
-QDeclarativeListProperty<QGraphicsObject> QGraphicsItemPrivate::childrenList()
-{
- Q_Q(QGraphicsItem);
- if (isObject) {
- QGraphicsObject *that = static_cast<QGraphicsObject *>(q);
- return QDeclarativeListProperty<QGraphicsObject>(that, &children, children_append,
- children_count, children_at, children_clear);
- } else {
- //QGraphicsItem is not supported for this property
- return QDeclarativeListProperty<QGraphicsObject>();
- }
-}
-
/*!
\internal
Returns the width of the item
diff --git a/src/widgets/graphicsview/qgraphicsitem.h b/src/widgets/graphicsview/qgraphicsitem.h
index f8257b6bb2..f82c600b3a 100644
--- a/src/widgets/graphicsview/qgraphicsitem.h
+++ b/src/widgets/graphicsview/qgraphicsitem.h
@@ -500,13 +500,10 @@ class Q_WIDGETS_EXPORT QGraphicsObject : public QObject, public QGraphicsItem
#if QT_CONFIG(graphicseffect)
Q_PROPERTY(QGraphicsEffect *effect READ graphicsEffect WRITE setGraphicsEffect)
#endif
- Q_PRIVATE_PROPERTY(QGraphicsItem::d_func(), QDeclarativeListProperty<QGraphicsObject> children
- READ childrenList DESIGNABLE false NOTIFY childrenChanged)
Q_PRIVATE_PROPERTY(QGraphicsItem::d_func(), qreal width READ width WRITE setWidth
NOTIFY widthChanged RESET resetWidth FINAL)
Q_PRIVATE_PROPERTY(QGraphicsItem::d_func(), qreal height READ height WRITE setHeight
NOTIFY heightChanged RESET resetHeight FINAL)
- Q_CLASSINFO("DefaultProperty", "children")
Q_INTERFACES(QGraphicsItem)
public:
explicit QGraphicsObject(QGraphicsItem *parent = nullptr);
diff --git a/src/widgets/graphicsview/qgraphicsitem_p.h b/src/widgets/graphicsview/qgraphicsitem_p.h
index 6b30d2663a..bf6ebb96a2 100644
--- a/src/widgets/graphicsview/qgraphicsitem_p.h
+++ b/src/widgets/graphicsview/qgraphicsitem_p.h
@@ -31,63 +31,6 @@ QT_BEGIN_NAMESPACE
class QGraphicsItemPrivate;
-#ifndef QDECLARATIVELISTPROPERTY
-#define QDECLARATIVELISTPROPERTY
-template<typename T>
-class QDeclarativeListProperty {
-public:
- typedef void (*AppendFunction)(QDeclarativeListProperty<T> *, T*);
- typedef int (*CountFunction)(QDeclarativeListProperty<T> *);
- typedef T *(*AtFunction)(QDeclarativeListProperty<T> *, int);
- typedef void (*ClearFunction)(QDeclarativeListProperty<T> *);
-
- QDeclarativeListProperty()
- : object(nullptr), data(nullptr), append(nullptr), count(nullptr), at(nullptr), clear(nullptr), dummy1(nullptr), dummy2(nullptr) {}
- QDeclarativeListProperty(QObject *o, QList<T *> &list)
- : object(o), data(&list), append(qlist_append), count(qlist_count), at(qlist_at),
- clear(qlist_clear), dummy1(nullptr), dummy2(nullptr) {}
- QDeclarativeListProperty(QObject *o, void *d, AppendFunction a, CountFunction c = nullptr, AtFunction t = nullptr,
- ClearFunction r = nullptr)
- : object(o), data(d), append(a), count(c), at(t), clear(r), dummy1(nullptr), dummy2(nullptr) {}
-
- bool operator==(const QDeclarativeListProperty &o) const {
- return object == o.object &&
- data == o.data &&
- append == o.append &&
- count == o.count &&
- at == o.at &&
- clear == o.clear;
- }
-
- QObject *object;
- void *data;
-
- AppendFunction append;
-
- CountFunction count;
- AtFunction at;
-
- ClearFunction clear;
-
- void *dummy1;
- void *dummy2;
-
-private:
- static void qlist_append(QDeclarativeListProperty *p, T *v) {
- ((QList<T *> *)p->data)->append(v);
- }
- static int qlist_count(QDeclarativeListProperty *p) {
- return ((QList<T *> *)p->data)->count();
- }
- static T *qlist_at(QDeclarativeListProperty *p, int idx) {
- return ((QList<T *> *)p->data)->at(idx);
- }
- static void qlist_clear(QDeclarativeListProperty *p) {
- return ((QList<T *> *)p->data)->clear();
- }
-};
-#endif
-
class QGraphicsItemCache
{
public:
@@ -190,7 +133,6 @@ public:
void resolveDepth();
void addChild(QGraphicsItem *child);
void removeChild(QGraphicsItem *child);
- QDeclarativeListProperty<QGraphicsObject> childrenList();
void setParentItemHelper(QGraphicsItem *parent, const QVariant *newParentVariant,
const QVariant *thisPointerVariant);
void childrenBoundingRectHelper(QTransform *x, QRectF *rect, QGraphicsItem *topMostEffectItem);
@@ -378,11 +320,6 @@ public:
virtual void subFocusItemChange();
virtual void focusScopeItemChange(bool isSubFocusItem);
- static void children_append(QDeclarativeListProperty<QGraphicsObject> *list, QGraphicsObject *item);
- static int children_count(QDeclarativeListProperty<QGraphicsObject> *list);
- static QGraphicsObject *children_at(QDeclarativeListProperty<QGraphicsObject> *list, int);
- static void children_clear(QDeclarativeListProperty<QGraphicsObject> *list);
-
inline QTransform transformToParent() const;
inline void ensureSortedChildren();
static inline bool insertionOrder(QGraphicsItem *a, QGraphicsItem *b);
@@ -478,10 +415,9 @@ public:
quint32 scenePosDescendants : 1;
quint32 pendingPolish : 1;
quint32 mayHaveChildWithGraphicsEffect : 1;
- quint32 isDeclarativeItem : 1;
quint32 sendParentChangeNotification : 1;
quint32 dirtyChildrenBoundingRect : 1;
- quint32 padding : 19;
+ quint32 padding : 20;
// Optional stacking order
int globalStackingOrder;
@@ -588,7 +524,6 @@ public:
return item->type() == QGraphicsPixmapItem::Type
&& !(item->flags() & QGraphicsItem::ItemIsSelectable)
&& item->d_ptr->children.size() == 0;
- //|| (item->d_ptr->isObject && qobject_cast<QDeclarativeImage *>(q_func()));
}
const QStyleOption *styleOption() const override
diff --git a/src/widgets/graphicsview/qgraphicslayout_p.h b/src/widgets/graphicsview/qgraphicslayout_p.h
index 2528949569..06eab2ba50 100644
--- a/src/widgets/graphicsview/qgraphicslayout_p.h
+++ b/src/widgets/graphicsview/qgraphicslayout_p.h
@@ -51,8 +51,8 @@ public:
Q_ASSERT(style);
if (widget) //###
m_styleOption.initFrom(widget);
- m_defaultSpacing[0] = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing, &m_styleOption);
- m_defaultSpacing[1] = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing, &m_styleOption);
+ m_defaultSpacing[0] = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing, &m_styleOption, widget);
+ m_defaultSpacing[1] = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing, &m_styleOption, widget);
}
inline void invalidate() { m_valid = false; m_style = nullptr; m_widget = nullptr; }
diff --git a/src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp b/src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp
index e1e71dfe85..6bd57470f3 100644
--- a/src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp
+++ b/src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp
@@ -46,7 +46,7 @@ qreal QGraphicsLayoutStyleInfo::spacing(Qt::Orientation orientation) const
Q_ASSERT(style());
return style()->pixelMetric(orientation == Qt::Horizontal
? QStyle::PM_LayoutHorizontalSpacing : QStyle::PM_LayoutVerticalSpacing,
- &m_styleOption);
+ &m_styleOption, widget());
}
qreal QGraphicsLayoutStyleInfo::windowMargin(Qt::Orientation orientation) const
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget.cpp b/src/widgets/graphicsview/qgraphicsproxywidget.cpp
index 60d62c084b..1ff4814142 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget.cpp
+++ b/src/widgets/graphicsview/qgraphicsproxywidget.cpp
@@ -340,10 +340,10 @@ QWidget *QGraphicsProxyWidgetPrivate::findFocusChild(QWidget *child, bool next)
// Run around the focus chain until we find a widget that can take tab focus.
if (!child) {
- child = next ? (QWidget *)widget : widget->d_func()->focus_prev;
+ child = next ? widget.data() : widget->previousInFocusChain();
} else {
- child = next ? child->d_func()->focus_next : child->d_func()->focus_prev;
- if ((next && child == widget) || (!next && child == widget->d_func()->focus_prev)) {
+ child = next ? child->nextInFocusChain() : child->previousInFocusChain();
+ if ((next && child == widget) || (!next && child == widget->previousInFocusChain())) {
return nullptr;
}
}
@@ -360,8 +360,8 @@ QWidget *QGraphicsProxyWidgetPrivate::findFocusChild(QWidget *child, bool next)
&& !(child->d_func()->extra && child->d_func()->extra->focus_proxy)) {
return child;
}
- child = next ? child->d_func()->focus_next : child->d_func()->focus_prev;
- } while (child != oldChild && !(next && child == widget) && !(!next && child == widget->d_func()->focus_prev));
+ child = next ? child->nextInFocusChain() : child->previousInFocusChain();
+ } while (child != oldChild && !(next && child == widget) && !(!next && child == widget->previousInFocusChain()));
return nullptr;
}
@@ -522,7 +522,7 @@ QGraphicsProxyWidget::~QGraphicsProxyWidget()
/*!
Embeds \a widget into this proxy widget. The embedded widget must reside
exclusively either inside or outside of Graphics View. You cannot embed a
- widget as long as it is is visible elsewhere in the UI, at the same time.
+ widget as long as it is visible elsewhere in the UI, at the same time.
\a widget must be a top-level widget whose parent is \nullptr.
@@ -1401,7 +1401,7 @@ void QGraphicsProxyWidget::focusOutEvent(QFocusEvent *event)
if (QWidget *focusWidget = d->widget->focusWidget()) {
// QTBUG-88016 proxyWidget set QTextEdit(QLineEdit etc.) when input preview text,
// inputMethod should be reset when proxyWidget lost focus
- if (focusWidget && focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
+ if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
QApplication::inputMethod()->reset();
d->removeSubFocusHelper(focusWidget, event->reason());
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget_p.h b/src/widgets/graphicsview/qgraphicsproxywidget_p.h
index 902a66ee68..328faad0be 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget_p.h
+++ b/src/widgets/graphicsview/qgraphicsproxywidget_p.h
@@ -19,6 +19,8 @@
#include "qgraphicsproxywidget.h"
#include "private/qgraphicswidget_p.h"
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(graphicsview);
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/graphicsview/qgraphicsscene.cpp b/src/widgets/graphicsview/qgraphicsscene.cpp
index dbe6ed9b02..c022af6fc0 100644
--- a/src/widgets/graphicsview/qgraphicsscene.cpp
+++ b/src/widgets/graphicsview/qgraphicsscene.cpp
@@ -216,6 +216,8 @@
#include <private/qgesturemanager_p.h>
#include <private/qpathclipper_p.h>
+#include <QtCore/qpointer.h>
+
// #define GESTURE_DEBUG
#ifndef GESTURE_DEBUG
# define DEBUG if (0) qDebug
@@ -1004,7 +1006,7 @@ void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
void QGraphicsScenePrivate::clearMouseGrabber()
{
if (!mouseGrabberItems.isEmpty())
- mouseGrabberItems.first()->ungrabMouse();
+ mouseGrabberItems.constFirst()->ungrabMouse();
lastMouseGrabberItem = nullptr;
}
@@ -2417,16 +2419,12 @@ void QGraphicsScene::addItem(QGraphicsItem *item)
return;
}
- // QDeclarativeItems do not rely on initial itemChanged message, as the componentComplete
- // function allows far more opportunity for delayed-construction optimization.
- if (!item->d_ptr->isDeclarativeItem) {
- if (d->unpolishedItems.isEmpty()) {
- QMetaMethod method = metaObject()->method(d->polishItemsIndex);
- method.invoke(this, Qt::QueuedConnection);
- }
- d->unpolishedItems.append(item);
- item->d_ptr->pendingPolish = true;
+ if (d->unpolishedItems.isEmpty()) {
+ QMetaMethod method = metaObject()->method(d->polishItemsIndex);
+ method.invoke(this, Qt::QueuedConnection);
}
+ d->unpolishedItems.append(item);
+ item->d_ptr->pendingPolish = true;
// Detach this item from its parent if the parent's scene is different
// from this scene.
@@ -2888,7 +2886,7 @@ void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReas
/*!
Returns \c true if the scene has focus; otherwise returns \c false. If the scene
- has focus, it will will forward key events from QKeyEvent to any item that
+ has focus, it will forward key events from QKeyEvent to any item that
has focus.
\sa setFocus(), setFocusItem()
@@ -3255,6 +3253,7 @@ bool QGraphicsScene::event(QEvent *event)
// ### this should only be cleared if we received a new mouse move event,
// which relies on us fixing the replay mechanism in QGraphicsView.
d->cachedItemsUnderMouse.clear();
+ break;
default:
break;
}
diff --git a/src/widgets/graphicsview/qgraphicsview.cpp b/src/widgets/graphicsview/qgraphicsview.cpp
index f9502b938a..9505e2529a 100644
--- a/src/widgets/graphicsview/qgraphicsview.cpp
+++ b/src/widgets/graphicsview/qgraphicsview.cpp
@@ -483,8 +483,8 @@ void QGraphicsViewPrivate::centerView(QGraphicsView::ViewportAnchor anchor)
if (q->underMouse()) {
// Last scene pos: lastMouseMoveScenePoint
// Current mouse pos:
- QPointF transformationDiff = q->mapToScene(viewport->rect().center())
- - q->mapToScene(viewport->mapFromGlobal(QCursor::pos()));
+ QPointF transformationDiff = mapToScene(viewport->rect().toRectF().center())
+ - mapToScene(viewport->mapFromGlobal(QCursor::pos().toPointF()));
q->centerOn(lastMouseMoveScenePoint + transformationDiff);
} else {
q->centerOn(lastCenterPoint);
@@ -504,8 +504,7 @@ void QGraphicsViewPrivate::centerView(QGraphicsView::ViewportAnchor anchor)
*/
void QGraphicsViewPrivate::updateLastCenterPoint()
{
- Q_Q(QGraphicsView);
- lastCenterPoint = q->mapToScene(viewport->rect().center());
+ lastCenterPoint = mapToScene(viewport->rect().toRectF().center());
}
/*!
@@ -1559,7 +1558,7 @@ void QGraphicsView::setRubberBandSelectionMode(Qt::ItemSelectionMode mode)
is currently doing an itemselection with rubber band. When the user is not using the
rubber band this functions returns (a null) QRectF().
- Notice that part of this QRect can be outise the visual viewport. It can e.g
+ Notice that part of this QRect can be outside the visual viewport. It can e.g
contain negative values.
\sa rubberBandSelectionMode, rubberBandChanged()
@@ -1892,14 +1891,14 @@ void QGraphicsView::centerOn(const QPointF &pos)
qint64 horizontal = 0;
horizontal += horizontalScrollBar()->minimum();
horizontal += horizontalScrollBar()->maximum();
- horizontal -= int(viewPoint.x() - width / 2.0);
+ horizontal -= qRound(viewPoint.x() - width / 2.0);
horizontalScrollBar()->setValue(horizontal);
} else {
- horizontalScrollBar()->setValue(int(viewPoint.x() - width / 2.0));
+ horizontalScrollBar()->setValue(qRound(viewPoint.x() - width / 2.0));
}
}
if (!d->topIndent)
- verticalScrollBar()->setValue(int(viewPoint.y() - height / 2.0));
+ verticalScrollBar()->setValue(qRound(viewPoint.y() - height / 2.0));
d->lastCenterPoint = oldCenterPoint;
}
@@ -2343,7 +2342,7 @@ QGraphicsItem *QGraphicsView::itemAt(const QPoint &pos) const
if (!d->scene)
return nullptr;
const QList<QGraphicsItem *> itemsAtPos = items(pos);
- return itemsAtPos.isEmpty() ? 0 : itemsAtPos.first();
+ return itemsAtPos.isEmpty() ? nullptr : itemsAtPos.first();
}
/*!
@@ -3844,7 +3843,7 @@ bool QGraphicsView::isTransformed() const
a view coordinate to a floating point scene coordinate, or mapFromScene()
to map from floating point scene coordinates to view coordinates.
- \sa transform(), rotate(), scale(), shear(), translate()
+ \sa transform(), resetTransform(), rotate(), scale(), shear(), translate()
*/
void QGraphicsView::setTransform(const QTransform &matrix, bool combine )
{
diff --git a/src/widgets/graphicsview/qgraphicsview_p.h b/src/widgets/graphicsview/qgraphicsview_p.h
index a15defe621..7f1682beca 100644
--- a/src/widgets/graphicsview/qgraphicsview_p.h
+++ b/src/widgets/graphicsview/qgraphicsview_p.h
@@ -25,6 +25,8 @@
#include <private/qabstractscrollarea_p.h>
#include <private/qapplication_p.h>
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(graphicsview);
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/itemviews/qabstractitemdelegate.cpp b/src/widgets/itemviews/qabstractitemdelegate.cpp
index 73af3b6b1d..23e8ef0901 100644
--- a/src/widgets/itemviews/qabstractitemdelegate.cpp
+++ b/src/widgets/itemviews/qabstractitemdelegate.cpp
@@ -81,7 +81,7 @@ QT_BEGIN_NAMESPACE
The second approach is to handle user events directly by reimplementing
editorEvent().
- \sa {model-view-programming}{Model/View Programming}, {Pixelator Example},
+ \sa {model-view-programming}{Model/View Programming},
QStyledItemDelegate, QStyle
*/
@@ -514,6 +514,14 @@ bool QAbstractItemDelegatePrivate::tryFixup(QWidget *editor)
return e->hasAcceptableInput();
}
}
+#endif
+#if QT_CONFIG(spinbox)
+ // Give a chance to the spinbox to interpret the text and emit
+ // the appropriate signals before committing data.
+ if (QAbstractSpinBox *sb = qobject_cast<QAbstractSpinBox *>(editor)) {
+ if (!sb->keyboardTracking())
+ sb->interpretText();
+ }
#else
Q_UNUSED(editor);
#endif // QT_CONFIG(lineedit)
diff --git a/src/widgets/itemviews/qabstractitemview.cpp b/src/widgets/itemviews/qabstractitemview.cpp
index 7a7b5c4753..85e478a71e 100644
--- a/src/widgets/itemviews/qabstractitemview.cpp
+++ b/src/widgets/itemviews/qabstractitemview.cpp
@@ -102,15 +102,16 @@ void QAbstractItemViewPrivate::init()
vbar->setRange(0, 0);
hbar->setRange(0, 0);
- QObject::connect(vbar, SIGNAL(actionTriggered(int)),
- q, SLOT(verticalScrollbarAction(int)));
- QObject::connect(hbar, SIGNAL(actionTriggered(int)),
- q, SLOT(horizontalScrollbarAction(int)));
- QObject::connect(vbar, SIGNAL(valueChanged(int)),
- q, SLOT(verticalScrollbarValueChanged(int)));
- QObject::connect(hbar, SIGNAL(valueChanged(int)),
- q, SLOT(horizontalScrollbarValueChanged(int)));
-
+ scrollbarConnections = {
+ QObject::connect(vbar, &QScrollBar::actionTriggered,
+ q, &QAbstractItemView::verticalScrollbarAction),
+ QObject::connect(hbar, &QScrollBar::actionTriggered,
+ q, &QAbstractItemView::horizontalScrollbarAction),
+ QObject::connect(vbar, &QScrollBar::valueChanged,
+ q, &QAbstractItemView::verticalScrollbarValueChanged),
+ QObject::connect(hbar, &QScrollBar::valueChanged,
+ q, &QAbstractItemView::horizontalScrollbarValueChanged)
+ };
viewport->setBackgroundRole(QPalette::Base);
q->setAttribute(Qt::WA_InputMethodEnabled);
@@ -129,8 +130,8 @@ void QAbstractItemViewPrivate::setHoverIndex(const QPersistentModelIndex &index)
q->update(hover); //update the old one
q->update(index); //update the new one
} else {
- QRect oldHoverRect = q->visualRect(hover);
- QRect newHoverRect = q->visualRect(index);
+ const QRect oldHoverRect = visualRect(hover);
+ const QRect newHoverRect = visualRect(index);
viewport->update(QRect(0, newHoverRect.y(), viewport->width(), newHoverRect.height()));
viewport->update(QRect(0, oldHoverRect.y(), viewport->width(), oldHoverRect.height()));
}
@@ -172,7 +173,7 @@ void QAbstractItemViewPrivate::checkMouseMove(const QPersistentModelIndex &index
#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
// stores and restores the selection and current item when flicking
-void QAbstractItemViewPrivate::_q_scrollerStateChanged()
+void QAbstractItemViewPrivate::scrollerStateChanged()
{
Q_Q(QAbstractItemView);
@@ -208,7 +209,7 @@ void QAbstractItemViewPrivate::_q_scrollerStateChanged()
#endif // QT_NO_GESTURES
-void QAbstractItemViewPrivate::_q_delegateSizeHintChanged(const QModelIndex &index)
+void QAbstractItemViewPrivate::delegateSizeHintChanged(const QModelIndex &index)
{
Q_Q(QAbstractItemView);
if (model) {
@@ -218,6 +219,63 @@ void QAbstractItemViewPrivate::_q_delegateSizeHintChanged(const QModelIndex &ind
QMetaObject::invokeMethod(q, &QAbstractItemView::doItemsLayout, Qt::QueuedConnection);
}
+void QAbstractItemViewPrivate::connectDelegate(QAbstractItemDelegate *delegate)
+{
+ if (!delegate)
+ return;
+ Q_Q(QAbstractItemView);
+ QObject::connect(delegate, &QAbstractItemDelegate::closeEditor,
+ q, &QAbstractItemView::closeEditor);
+ QObject::connect(delegate, &QAbstractItemDelegate::commitData,
+ q, &QAbstractItemView::commitData);
+ QObjectPrivate::connect(delegate, &QAbstractItemDelegate::sizeHintChanged,
+ this, &QAbstractItemViewPrivate::delegateSizeHintChanged);
+}
+
+void QAbstractItemViewPrivate::disconnectDelegate(QAbstractItemDelegate *delegate)
+{
+ if (!delegate)
+ return;
+ Q_Q(QAbstractItemView);
+ QObject::disconnect(delegate, &QAbstractItemDelegate::closeEditor,
+ q, &QAbstractItemView::closeEditor);
+ QObject::disconnect(delegate, &QAbstractItemDelegate::commitData,
+ q, &QAbstractItemView::commitData);
+ QObjectPrivate::disconnect(delegate, &QAbstractItemDelegate::sizeHintChanged,
+ this, &QAbstractItemViewPrivate::delegateSizeHintChanged);
+}
+
+void QAbstractItemViewPrivate::disconnectAll()
+{
+ Q_Q(QAbstractItemView);
+ for (const QMetaObject::Connection &connection : modelConnections)
+ QObject::disconnect(connection);
+ for (const QMetaObject::Connection &connection : scrollbarConnections)
+ QObject::disconnect(connection);
+ disconnectDelegate(itemDelegate);
+ for (QAbstractItemDelegate *delegate : std::as_const(rowDelegates))
+ disconnectDelegate(delegate);
+ for (QAbstractItemDelegate *delegate : std::as_const(columnDelegates))
+ disconnectDelegate(delegate);
+ if (model && selectionModel) {
+ QObject::disconnect(model, &QAbstractItemModel::destroyed,
+ selectionModel, &QItemSelectionModel::deleteLater);
+ }
+ if (selectionModel) {
+ QObject::disconnect(selectionModel, &QItemSelectionModel::selectionChanged,
+ q, &QAbstractItemView::selectionChanged);
+ QObject::disconnect(selectionModel, &QItemSelectionModel::currentChanged,
+ q, &QAbstractItemView::currentChanged);
+ }
+ for (const auto &info : std::as_const(indexEditorHash)) {
+ if (!info.isStatic && info.widget)
+ QObject::disconnect(info.widget, &QWidget::destroyed, q, &QAbstractItemView::editorDestroyed);
+ }
+#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
+ QObject::disconnect(scollerConnection);
+#endif
+}
+
/*!
\class QAbstractItemView
@@ -318,7 +376,7 @@ void QAbstractItemViewPrivate::_q_delegateSizeHintChanged(const QModelIndex &ind
\l{QWidget::update()}{update()} as all painting operations take place on the
viewport.
- \sa {View Classes}, {Model/View Programming}, QAbstractItemModel, {Chart Example}
+ \sa {View Classes}, {Model/View Programming}, QAbstractItemModel
*/
/*!
@@ -631,6 +689,7 @@ QAbstractItemView::~QAbstractItemView()
d->autoScrollTimer.stop();
d->delayedLayout.stop();
d->fetchMoreTimer.stop();
+ d->disconnectAll();
}
/*!
@@ -659,68 +718,47 @@ void QAbstractItemView::setModel(QAbstractItemModel *model)
if (model == d->model)
return;
if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- disconnect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QList<int>)), this,
- SLOT(dataChanged(QModelIndex, QModelIndex, QList<int>)));
- disconnect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(_q_headerDataChanged()));
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(rowsInserted(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_rowsMoved(QModelIndex,int,int,QModelIndex,int)));
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_columnsAboutToBeRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_columnsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_columnsInserted(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_columnsMoved(QModelIndex,int,int,QModelIndex,int)));
-
- disconnect(d->model, SIGNAL(modelReset()), this, SLOT(reset()));
- disconnect(d->model, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));
+ for (const QMetaObject::Connection &connection : d->modelConnections)
+ disconnect(connection);
}
d->model = (model ? model : QAbstractItemModelPrivate::staticEmptyModel());
if (d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- connect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- connect(d->model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QList<int>)), this,
- SLOT(dataChanged(QModelIndex, QModelIndex, QList<int>)));
- connect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(_q_headerDataChanged()));
- connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(rowsInserted(QModelIndex,int,int)));
- connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- connect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int)));
- connect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- connect(d->model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_rowsMoved(QModelIndex,int,int,QModelIndex,int)));
- connect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_columnsAboutToBeRemoved(QModelIndex,int,int)));
- connect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_columnsRemoved(QModelIndex,int,int)));
- connect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_columnsInserted(QModelIndex,int,int)));
- connect(d->model, SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_columnsMoved(QModelIndex,int,int,QModelIndex,int)));
-
- connect(d->model, SIGNAL(modelReset()), this, SLOT(reset()));
- connect(d->model, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));
+ d->modelConnections = {
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::destroyed,
+ d, &QAbstractItemViewPrivate::modelDestroyed),
+ QObject::connect(d->model, &QAbstractItemModel::dataChanged,
+ this, &QAbstractItemView::dataChanged),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::headerDataChanged,
+ d, &QAbstractItemViewPrivate::headerDataChanged),
+ QObject::connect(d->model, &QAbstractItemModel::rowsInserted,
+ this, &QAbstractItemView::rowsInserted),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::rowsInserted,
+ d, &QAbstractItemViewPrivate::rowsInserted),
+ QObject::connect(d->model, &QAbstractItemModel::rowsAboutToBeRemoved,
+ this, &QAbstractItemView::rowsAboutToBeRemoved),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::rowsRemoved,
+ d, &QAbstractItemViewPrivate::rowsRemoved),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::rowsMoved,
+ d, &QAbstractItemViewPrivate::rowsMoved),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::columnsAboutToBeRemoved,
+ d, &QAbstractItemViewPrivate::columnsAboutToBeRemoved),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::columnsRemoved,
+ d, &QAbstractItemViewPrivate::columnsRemoved),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::columnsInserted,
+ d, &QAbstractItemViewPrivate::columnsInserted),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::columnsMoved,
+ d, &QAbstractItemViewPrivate::columnsMoved),
+ QObject::connect(d->model, &QAbstractItemModel::modelReset,
+ this, &QAbstractItemView::reset),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::layoutChanged,
+ d, &QAbstractItemViewPrivate::layoutChanged),
+ };
}
QItemSelectionModel *selection_model = new QItemSelectionModel(d->model, this);
- connect(d->model, SIGNAL(destroyed()), selection_model, SLOT(deleteLater()));
+ connect(d->model, &QAbstractItemModel::destroyed,
+ selection_model, &QItemSelectionModel::deleteLater);
setSelectionModel(selection_model);
reset(); // kill editors, set new root and do layout
@@ -770,20 +808,19 @@ void QAbstractItemView::setSelectionModel(QItemSelectionModel *selectionModel)
oldSelection = d->selectionModel->selection();
oldCurrentIndex = d->selectionModel->currentIndex();
}
-
- disconnect(d->selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
- disconnect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(currentChanged(QModelIndex,QModelIndex)));
+ disconnect(d->selectionModel, &QItemSelectionModel::selectionChanged,
+ this, &QAbstractItemView::selectionChanged);
+ disconnect(d->selectionModel, &QItemSelectionModel::currentChanged,
+ this, &QAbstractItemView::currentChanged);
}
d->selectionModel = selectionModel;
if (d->selectionModel) {
- connect(d->selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
- connect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(currentChanged(QModelIndex,QModelIndex)));
+ connect(d->selectionModel, &QItemSelectionModel::selectionChanged,
+ this, &QAbstractItemView::selectionChanged);
+ connect(d->selectionModel, &QItemSelectionModel::currentChanged,
+ this, &QAbstractItemView::currentChanged);
selectionChanged(d->selectionModel->selection(), oldSelection);
currentChanged(d->selectionModel->currentIndex(), oldCurrentIndex);
@@ -823,21 +860,13 @@ void QAbstractItemView::setItemDelegate(QAbstractItemDelegate *delegate)
return;
if (d->itemDelegate) {
- if (d->delegateRefCount(d->itemDelegate) == 1) {
- disconnect(d->itemDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- disconnect(d->itemDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- disconnect(d->itemDelegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(_q_delegateSizeHintChanged(QModelIndex)));
- }
+ if (d->delegateRefCount(d->itemDelegate) == 1)
+ d->disconnectDelegate(delegate);
}
if (delegate) {
- if (d->delegateRefCount(delegate) == 0) {
- connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- connect(delegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(_q_delegateSizeHintChanged(QModelIndex)));
- }
+ if (d->delegateRefCount(delegate) == 0)
+ d->connectDelegate(delegate);
}
d->itemDelegate = delegate;
viewport()->update();
@@ -907,21 +936,13 @@ void QAbstractItemView::setItemDelegateForRow(int row, QAbstractItemDelegate *de
{
Q_D(QAbstractItemView);
if (QAbstractItemDelegate *rowDelegate = d->rowDelegates.value(row, nullptr)) {
- if (d->delegateRefCount(rowDelegate) == 1) {
- disconnect(rowDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- disconnect(rowDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- disconnect(rowDelegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(_q_delegateSizeHintChanged(QModelIndex)));
- }
+ if (d->delegateRefCount(rowDelegate) == 1)
+ d->disconnectDelegate(rowDelegate);
d->rowDelegates.remove(row);
}
if (delegate) {
- if (d->delegateRefCount(delegate) == 0) {
- connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- connect(delegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(_q_delegateSizeHintChanged(QModelIndex)));
- }
+ if (d->delegateRefCount(delegate) == 0)
+ d->connectDelegate(delegate);
d->rowDelegates.insert(row, delegate);
}
viewport()->update();
@@ -967,21 +988,13 @@ void QAbstractItemView::setItemDelegateForColumn(int column, QAbstractItemDelega
{
Q_D(QAbstractItemView);
if (QAbstractItemDelegate *columnDelegate = d->columnDelegates.value(column, nullptr)) {
- if (d->delegateRefCount(columnDelegate) == 1) {
- disconnect(columnDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- disconnect(columnDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- disconnect(columnDelegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(_q_delegateSizeHintChanged(QModelIndex)));
- }
+ if (d->delegateRefCount(columnDelegate) == 1)
+ d->disconnectDelegate(columnDelegate);
d->columnDelegates.remove(column);
}
if (delegate) {
- if (d->delegateRefCount(delegate) == 0) {
- connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- connect(delegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(_q_delegateSizeHintChanged(QModelIndex)));
- }
+ if (d->delegateRefCount(delegate) == 0)
+ d->connectDelegate(delegate);
d->columnDelegates.insert(column, delegate);
}
viewport()->update();
@@ -1119,7 +1132,11 @@ void QAbstractItemView::reset()
{
Q_D(QAbstractItemView);
d->delayedReset.stop(); //make sure we stop the timer
- foreach (const QEditorInfo &info, d->indexEditorHash) {
+ // Taking a copy because releaseEditor() eventurally calls deleteLater() on the
+ // editor, which calls QCoreApplication::postEvent(), the latter may invoke unknown
+ // code that may modify d->indexEditorHash.
+ const auto copy = d->indexEditorHash;
+ for (const auto &[index, info] : copy.asKeyValueRange()) {
if (info.widget)
d->releaseEditor(info.widget.data(), d->indexForEditor(info.widget.data()));
}
@@ -1153,6 +1170,12 @@ void QAbstractItemView::setRootIndex(const QModelIndex &index)
return;
}
d->root = index;
+#if QT_CONFIG(accessibility)
+ if (QAccessible::isActive()) {
+ QAccessibleTableModelChangeEvent accessibleEvent(this, QAccessibleTableModelChangeEvent::ModelReset);
+ QAccessible::updateAccessibility(&accessibleEvent);
+ }
+#endif
d->doDelayedItemsLayout();
d->updateGeometry();
}
@@ -1545,7 +1568,7 @@ QAbstractItemView::DragDropMode QAbstractItemView::dragDropMode() const
/*!
\property QAbstractItemView::defaultDropAction
- \brief the drop action that will be used by default in QAbstractItemView::drag()
+ \brief the drop action that will be used by default in QAbstractItemView::drag().
If the property is not set, the drop action is CopyAction when the supported
actions support CopyAction.
@@ -1638,7 +1661,7 @@ Qt::TextElideMode QAbstractItemView::textElideMode() const
bool QAbstractItemView::focusNextPrevChild(bool next)
{
Q_D(QAbstractItemView);
- if (d->tabKeyNavigation && isEnabled() && d->viewport->isEnabled()) {
+ if (d->tabKeyNavigation && isVisible() && isEnabled() && d->viewport->isEnabled()) {
QKeyEvent event(QEvent::KeyPress, next ? Qt::Key_Tab : Qt::Key_Backtab, Qt::NoModifier);
keyPressEvent(&event);
if (event.isAccepted())
@@ -1709,6 +1732,12 @@ bool QAbstractItemView::viewportEvent(QEvent *event)
{
Q_D(QAbstractItemView);
switch (event->type()) {
+ case QEvent::Paint:
+ // Similar to pre-painting in QAbstractItemView::event to update scrollbar
+ // visibility, make sure that all pending layout requests have been executed
+ // so that the view's data structures are up-to-date before rendering.
+ d->executePostedLayout();
+ break;
case QEvent::HoverMove:
case QEvent::HoverEnter:
d->setHoverIndex(indexAt(static_cast<QHoverEvent*>(event)->position().toPoint()));
@@ -1756,7 +1785,10 @@ bool QAbstractItemView::viewportEvent(QEvent *event)
case QEvent::ScrollPrepare:
executeDelayedItemsLayout();
#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
- connect(QScroller::scroller(d->viewport), SIGNAL(stateChanged(QScroller::State)), this, SLOT(_q_scrollerStateChanged()), Qt::UniqueConnection);
+ d->scollerConnection = QObjectPrivate::connect(
+ QScroller::scroller(d->viewport), &QScroller::stateChanged,
+ d, &QAbstractItemViewPrivate::scrollerStateChanged,
+ Qt::UniqueConnection);
#endif
break;
@@ -1793,9 +1825,11 @@ void QAbstractItemView::mousePressEvent(QMouseEvent *event)
QPoint offset = d->offset();
d->draggedPosition = pos + offset;
+#if QT_CONFIG(draganddrop)
// update the pressed position when drag was enable
if (d->dragEnabled)
d->pressedPosition = d->draggedPosition;
+#endif
if (!(command & QItemSelectionModel::Current)) {
d->pressedPosition = pos + offset;
@@ -1849,7 +1883,6 @@ void QAbstractItemView::mousePressEvent(QMouseEvent *event)
void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
{
Q_D(QAbstractItemView);
- QPoint topLeft;
QPoint bottomRight = event->position().toPoint();
d->draggedPosition = bottomRight + d->offset();
@@ -1859,13 +1892,7 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
#if QT_CONFIG(draganddrop)
if (state() == DraggingState) {
- topLeft = d->pressedPosition - d->offset();
- if ((topLeft - bottomRight).manhattanLength() > QApplication::startDragDistance()) {
- d->pressedIndex = QModelIndex();
- startDrag(d->model->supportedDragActions());
- setState(NoState); // the startDrag will return when the dnd operation is done
- stopAutoScroll();
- }
+ d->maybeStartDrag(bottomRight);
return;
}
#endif // QT_CONFIG(draganddrop)
@@ -1876,10 +1903,8 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
|| edit(index, NoEditTriggers, event))
return;
- if (d->selectionMode != SingleSelection)
- topLeft = d->pressedPosition - d->offset();
- else
- topLeft = bottomRight;
+ const QPoint topLeft =
+ d->selectionMode != SingleSelection ? d->pressedPosition - d->offset() : bottomRight;
d->checkMouseMove(index);
@@ -1890,6 +1915,7 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
&& (event->buttons() != Qt::NoButton)
&& !d->selectedDraggableIndexes().isEmpty()) {
setState(DraggingState);
+ d->maybeStartDrag(bottomRight);
return;
}
#endif
@@ -1939,7 +1965,9 @@ void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event)
}
bool click = (index == d->pressedIndex && index.isValid() && !releaseFromDoubleClick);
- bool selectedClicked = click && (event->button() == Qt::LeftButton) && d->pressedAlreadySelected;
+ bool selectedClicked = click && d->pressedAlreadySelected
+ && (event->button() == Qt::LeftButton)
+ && (event->modifiers() == Qt::NoModifier);
EditTrigger trigger = (selectedClicked ? SelectedClicked : NoEditTriggers);
const bool edited = click && !d->pressClosedEditor ? edit(index, trigger, event) : false;
@@ -1947,7 +1975,7 @@ void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event)
if (d->selectionModel && d->noSelectionOnMousePress) {
d->noSelectionOnMousePress = false;
- if (!edited && !d->pressClosedEditor)
+ if (!d->pressClosedEditor)
d->selectionModel->select(index, selectionCommand(index, event));
}
@@ -2366,11 +2394,12 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
#if !defined(QT_NO_CLIPBOARD) && !defined(QT_NO_SHORTCUT)
if (event == QKeySequence::Copy) {
- QVariant variant;
- if (d->model)
- variant = d->model->data(currentIndex(), Qt::DisplayRole);
- if (variant.canConvert<QString>())
- QGuiApplication::clipboard()->setText(variant.toString());
+ const QModelIndex index = currentIndex();
+ if (index.isValid() && d->model) {
+ const QVariant variant = d->model->data(index, Qt::DisplayRole);
+ if (variant.canConvert<QString>())
+ QGuiApplication::clipboard()->setText(variant.toString());
+ }
event->accept();
}
#endif
@@ -2907,41 +2936,50 @@ void QAbstractItemView::closeEditor(QWidget *editor, QAbstractItemDelegate::EndE
// Close the editor
if (editor) {
- bool isPersistent = d->persistent.contains(editor);
- bool hadFocus = editor->hasFocus();
- QModelIndex index = d->indexForEditor(editor);
+ const bool isPersistent = d->persistent.contains(editor);
+ const QModelIndex index = d->indexForEditor(editor);
if (!index.isValid()) {
- qWarning("QAbstractItemView::closeEditor called with an editor that does not belong to this view");
- return; // the editor was not registered
- }
-
- // start a timer that expires immediately when we return to the event loop
- // to identify whether this close was triggered by a mousepress-initiated
- // focus event
- d->pressClosedEditorWatcher.start(0, this);
- d->lastEditedIndex = index;
-
- if (!isPersistent) {
- setState(NoState);
- QModelIndex index = d->indexForEditor(editor);
- editor->removeEventFilter(itemDelegateForIndex(index));
- d->removeEditor(editor);
- }
- if (hadFocus) {
- if (focusPolicy() != Qt::NoFocus)
- setFocus(); // this will send a focusLost event to the editor
- else
- editor->clearFocus();
+ if (!editor->isVisible()) {
+ // The commit might have removed the index (e.g. it might get filtered), in
+ // which case the editor is already hidden and scheduled for deletion. We
+ // don't have to do anything, except reset the state, and continue with
+ // EndEditHint processing.
+ if (!isPersistent)
+ setState(NoState);
+ } else {
+ qWarning("QAbstractItemView::closeEditor called with an editor that does not belong to this view");
+ return;
+ }
} else {
- d->checkPersistentEditorFocus();
- }
+ const bool hadFocus = editor->hasFocus();
+ // start a timer that expires immediately when we return to the event loop
+ // to identify whether this close was triggered by a mousepress-initiated
+ // focus event
+ d->pressClosedEditorWatcher.start(0, this);
+ d->lastEditedIndex = index;
+
+ if (!isPersistent) {
+ setState(NoState);
+ QModelIndex index = d->indexForEditor(editor);
+ editor->removeEventFilter(itemDelegateForIndex(index));
+ d->removeEditor(editor);
+ }
+ if (hadFocus) {
+ if (focusPolicy() != Qt::NoFocus)
+ setFocus(); // this will send a focusLost event to the editor
+ else
+ editor->clearFocus();
+ } else {
+ d->checkPersistentEditorFocus();
+ }
- QPointer<QWidget> ed = editor;
- QCoreApplication::sendPostedEvents(editor, 0);
- editor = ed;
+ QPointer<QWidget> ed = editor;
+ QCoreApplication::sendPostedEvents(editor, 0);
+ editor = ed;
- if (!isPersistent && editor)
- d->releaseEditor(editor, index);
+ if (!isPersistent && editor)
+ d->releaseEditor(editor, index);
+ }
}
// The EndEditHint part
@@ -3343,7 +3381,7 @@ void QAbstractItemView::update(const QModelIndex &index)
{
Q_D(QAbstractItemView);
if (index.isValid()) {
- const QRect rect = visualRect(index);
+ const QRect rect = d->visualRect(index);
//this test is important for performance reason
//For example in dataChanged we simply update all the cells without checking
//it can be a major bottleneck to update rects that aren't even part of the viewport
@@ -3494,10 +3532,21 @@ void QAbstractItemView::rowsAboutToBeRemoved(const QModelIndex &parent, int star
}
// Remove all affected editors; this is more efficient than waiting for updateGeometries() to clean out editors for invalid indexes
+ const auto findDirectChildOf = [](const QModelIndex &parent, QModelIndex child)
+ {
+ while (child.isValid()) {
+ const auto parentIndex = child.parent();
+ if (parentIndex == parent)
+ return child;
+ child = parentIndex;
+ }
+ return QModelIndex();
+ };
QEditorIndexHash::iterator i = d->editorIndexHash.begin();
while (i != d->editorIndexHash.end()) {
const QModelIndex index = i.value();
- if (index.row() >= start && index.row() <= end && d->model->parent(index) == parent) {
+ const QModelIndex directChild = findDirectChildOf(parent, index);
+ if (directChild.isValid() && directChild.row() >= start && directChild.row() <= end) {
QWidget *editor = i.key();
QEditorInfo info = d->indexEditorHash.take(index);
i = d->editorIndexHash.erase(i);
@@ -3516,7 +3565,7 @@ void QAbstractItemView::rowsAboutToBeRemoved(const QModelIndex &parent, int star
rows are those under the given \a parent from \a start to \a end
inclusive.
*/
-void QAbstractItemViewPrivate::_q_rowsRemoved(const QModelIndex &index, int start, int end)
+void QAbstractItemViewPrivate::rowsRemoved(const QModelIndex &index, int start, int end)
{
Q_UNUSED(index);
Q_UNUSED(start);
@@ -3544,7 +3593,7 @@ void QAbstractItemViewPrivate::_q_rowsRemoved(const QModelIndex &index, int star
columns are those under the given \a parent from \a start to \a end
inclusive.
*/
-void QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void QAbstractItemViewPrivate::columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
{
Q_Q(QAbstractItemView);
@@ -3607,7 +3656,7 @@ void QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &par
rows are those under the given \a parent from \a start to \a end
inclusive.
*/
-void QAbstractItemViewPrivate::_q_columnsRemoved(const QModelIndex &index, int start, int end)
+void QAbstractItemViewPrivate::columnsRemoved(const QModelIndex &index, int start, int end)
{
Q_UNUSED(index);
Q_UNUSED(start);
@@ -3634,7 +3683,7 @@ void QAbstractItemViewPrivate::_q_columnsRemoved(const QModelIndex &index, int s
This slot is called when rows have been inserted.
*/
-void QAbstractItemViewPrivate::_q_rowsInserted(const QModelIndex &index, int start, int end)
+void QAbstractItemViewPrivate::rowsInserted(const QModelIndex &index, int start, int end)
{
Q_UNUSED(index);
Q_UNUSED(start);
@@ -3657,7 +3706,7 @@ void QAbstractItemViewPrivate::_q_rowsInserted(const QModelIndex &index, int sta
This slot is called when columns have been inserted.
*/
-void QAbstractItemViewPrivate::_q_columnsInserted(const QModelIndex &index, int start, int end)
+void QAbstractItemViewPrivate::columnsInserted(const QModelIndex &index, int start, int end)
{
Q_UNUSED(index);
Q_UNUSED(start);
@@ -3680,7 +3729,7 @@ void QAbstractItemViewPrivate::_q_columnsInserted(const QModelIndex &index, int
/*!
\internal
*/
-void QAbstractItemViewPrivate::_q_modelDestroyed()
+void QAbstractItemViewPrivate::modelDestroyed()
{
model = QAbstractItemModelPrivate::staticEmptyModel();
doDelayedReset();
@@ -3691,7 +3740,7 @@ void QAbstractItemViewPrivate::_q_modelDestroyed()
This slot is called when the layout is changed.
*/
-void QAbstractItemViewPrivate::_q_layoutChanged()
+void QAbstractItemViewPrivate::layoutChanged()
{
doDelayedItemsLayout();
#if QT_CONFIG(accessibility)
@@ -3703,14 +3752,14 @@ void QAbstractItemViewPrivate::_q_layoutChanged()
#endif
}
-void QAbstractItemViewPrivate::_q_rowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)
+void QAbstractItemViewPrivate::rowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)
{
- _q_layoutChanged();
+ layoutChanged();
}
-void QAbstractItemViewPrivate::_q_columnsMoved(const QModelIndex &, int, int, const QModelIndex &, int)
+void QAbstractItemViewPrivate::columnsMoved(const QModelIndex &, int, int, const QModelIndex &, int)
{
- _q_layoutChanged();
+ layoutChanged();
}
QRect QAbstractItemViewPrivate::intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const
@@ -4091,8 +4140,12 @@ QItemSelectionModel::SelectionFlags QAbstractItemView::selectionCommand(const QM
if (d->pressedAlreadySelected)
return QItemSelectionModel::NoUpdate;
break;
- case QEvent::KeyPress:
case QEvent::MouseButtonRelease:
+ // clicking into area with no items does nothing
+ if (!index.isValid())
+ return QItemSelectionModel::NoUpdate;
+ Q_FALLTHROUGH();
+ case QEvent::KeyPress:
// ctrl-release on selected item deselects
if ((keyModifiers & Qt::ControlModifier) && d->selectionModel->isSelected(index))
return QItemSelectionModel::Deselect | d->selectionBehaviorFlags();
@@ -4127,13 +4180,21 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::multiSelectionComm
case QEvent::MouseButtonPress:
if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton) {
// since the press might start a drag, deselect only on release
- if (!pressedAlreadySelected || !dragEnabled || !isIndexDragEnabled(index))
+ if (!pressedAlreadySelected
+#if QT_CONFIG(draganddrop)
+ || !dragEnabled || !isIndexDragEnabled(index)
+#endif
+ )
return QItemSelectionModel::Toggle|selectionBehaviorFlags(); // toggle
}
break;
case QEvent::MouseButtonRelease:
if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton) {
- if (pressedAlreadySelected && dragEnabled && isIndexDragEnabled(index) && index == pressedIndex)
+ if (pressedAlreadySelected
+#if QT_CONFIG(draganddrop)
+ && dragEnabled && isIndexDragEnabled(index)
+#endif
+ && index == pressedIndex)
return QItemSelectionModel::Toggle|selectionBehaviorFlags();
return QItemSelectionModel::NoUpdate|selectionBehaviorFlags(); // finalize
}
@@ -4181,7 +4242,10 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionC
return QItemSelectionModel::NoUpdate;
// since the press might start a drag, deselect only on release
if (controlKeyPressed && !rightButtonPressed && pressedAlreadySelected
- && dragEnabled && isIndexDragEnabled(index)) {
+#if QT_CONFIG(draganddrop)
+ && dragEnabled && isIndexDragEnabled(index)
+#endif
+ ) {
return QItemSelectionModel::NoUpdate;
}
break;
@@ -4197,7 +4261,10 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionC
&& !shiftKeyPressed && !controlKeyPressed && (!rightButtonPressed || !index.isValid()))
return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
if (index == pressedIndex && controlKeyPressed && !rightButtonPressed
- && dragEnabled && isIndexDragEnabled(index)) {
+#if QT_CONFIG(draganddrop)
+ && dragEnabled && isIndexDragEnabled(index)
+#endif
+ ) {
break;
}
return QItemSelectionModel::NoUpdate;
@@ -4234,6 +4301,7 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionC
default:
break;
}
+ break;
}
default:
break;
@@ -4402,7 +4470,7 @@ QWidget *QAbstractItemViewPrivate::editor(const QModelIndex &index,
w = delegate->createEditor(viewport, options, index);
if (w) {
w->installEventFilter(delegate);
- QObject::connect(w, SIGNAL(destroyed(QObject*)), q, SLOT(editorDestroyed(QObject*)));
+ QObject::connect(w, &QWidget::destroyed, q, &QAbstractItemView::editorDestroyed);
delegate->updateEditorGeometry(w, options, index);
delegate->setEditorData(w, index);
addEditor(index, w, false);
@@ -4539,6 +4607,9 @@ QModelIndex QAbstractItemViewPrivate::indexForEditor(QWidget *editor) const
void QAbstractItemViewPrivate::removeEditor(QWidget *editor)
{
+ Q_Q(QAbstractItemView);
+ if (editor)
+ QObject::disconnect(editor, &QWidget::destroyed, q, &QAbstractItemView::editorDestroyed);
const auto it = editorIndexHash.constFind(editor);
if (it != editorIndexHash.cend()) {
indexEditorHash.remove(it.value());
@@ -4661,6 +4732,7 @@ void QAbstractItemViewPrivate::selectAll(QItemSelectionModel::SelectionFlags com
selectionModel->select(selection, command);
}
+#if QT_CONFIG(draganddrop)
QModelIndexList QAbstractItemViewPrivate::selectedDraggableIndexes() const
{
Q_Q(const QAbstractItemView);
@@ -4672,6 +4744,21 @@ QModelIndexList QAbstractItemViewPrivate::selectedDraggableIndexes() const
return indexes;
}
+void QAbstractItemViewPrivate::maybeStartDrag(QPoint eventPosition)
+{
+ Q_Q(QAbstractItemView);
+
+ const QPoint topLeft = pressedPosition - offset();
+ if ((topLeft - eventPosition).manhattanLength() > QApplication::startDragDistance()) {
+ pressedIndex = QModelIndex();
+ q->startDrag(model->supportedDragActions());
+ q->setState(QAbstractItemView::NoState); // the startDrag will return when the dnd operation
+ // is done
+ q->stopAutoScroll();
+ }
+}
+#endif
+
/*!
\reimp
*/
diff --git a/src/widgets/itemviews/qabstractitemview.h b/src/widgets/itemviews/qabstractitemview.h
index d5a433943a..837419100a 100644
--- a/src/widgets/itemviews/qabstractitemview.h
+++ b/src/widgets/itemviews/qabstractitemview.h
@@ -326,20 +326,6 @@ protected:
private:
Q_DECLARE_PRIVATE(QAbstractItemView)
Q_DISABLE_COPY(QAbstractItemView)
- Q_PRIVATE_SLOT(d_func(), void _q_columnsAboutToBeRemoved(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_columnsRemoved(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_columnsInserted(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsInserted(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsRemoved(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_columnsMoved(const QModelIndex&, int, int, const QModelIndex&, int))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsMoved(const QModelIndex&, int, int, const QModelIndex&, int))
- Q_PRIVATE_SLOT(d_func(), void _q_modelDestroyed())
- Q_PRIVATE_SLOT(d_func(), void _q_layoutChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_headerDataChanged())
-#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
- Q_PRIVATE_SLOT(d_func(), void _q_scrollerStateChanged())
-#endif
- Q_PRIVATE_SLOT(d_func(), void _q_delegateSizeHintChanged(const QModelIndex&))
friend class ::tst_QAbstractItemView;
friend class ::tst_QTreeView;
diff --git a/src/widgets/itemviews/qabstractitemview_p.h b/src/widgets/itemviews/qabstractitemview_p.h
index 257e368175..433429f48b 100644
--- a/src/widgets/itemviews/qabstractitemview_p.h
+++ b/src/widgets/itemviews/qabstractitemview_p.h
@@ -16,17 +16,22 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "qabstractitemview.h"
#include "private/qabstractscrollarea_p.h"
#include "private/qabstractitemmodel_p.h"
#include "QtWidgets/qapplication.h"
#include "QtGui/qevent.h"
#include "QtCore/qmimedata.h"
#include "QtGui/qpainter.h"
-#include "QtCore/qpair.h"
#include "QtGui/qregion.h"
+
#include "QtCore/qdebug.h"
#include "QtCore/qbasictimer.h"
#include "QtCore/qelapsedtimer.h"
+#include <QtCore/qpointer.h>
+
+
+#include <array>
QT_REQUIRE_CONFIG(itemviews);
@@ -63,20 +68,20 @@ public:
void init();
- virtual void _q_rowsRemoved(const QModelIndex &parent, int start, int end);
- virtual void _q_rowsInserted(const QModelIndex &parent, int start, int end);
- virtual void _q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
- virtual void _q_columnsRemoved(const QModelIndex &parent, int start, int end);
- virtual void _q_columnsInserted(const QModelIndex &parent, int start, int end);
- virtual void _q_modelDestroyed();
- virtual void _q_layoutChanged();
- virtual void _q_rowsMoved(const QModelIndex &source, int sourceStart, int sourceEnd, const QModelIndex &destination, int destinationStart);
- virtual void _q_columnsMoved(const QModelIndex &source, int sourceStart, int sourceEnd, const QModelIndex &destination, int destinationStart);
+ virtual void rowsRemoved(const QModelIndex &parent, int start, int end);
+ virtual void rowsInserted(const QModelIndex &parent, int start, int end);
+ virtual void columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
+ virtual void columnsRemoved(const QModelIndex &parent, int start, int end);
+ virtual void columnsInserted(const QModelIndex &parent, int start, int end);
+ virtual void modelDestroyed();
+ virtual void layoutChanged();
+ virtual void rowsMoved(const QModelIndex &source, int sourceStart, int sourceEnd, const QModelIndex &destination, int destinationStart);
+ virtual void columnsMoved(const QModelIndex &source, int sourceStart, int sourceEnd, const QModelIndex &destination, int destinationStart);
virtual QRect intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const;
- void _q_headerDataChanged() { doDelayedItemsLayout(); }
- void _q_scrollerStateChanged();
- void _q_delegateSizeHintChanged(const QModelIndex &index);
+ void headerDataChanged() { doDelayedItemsLayout(); }
+ void scrollerStateChanged();
+ void delegateSizeHintChanged(const QModelIndex &index);
void fetchMore();
@@ -178,8 +183,8 @@ public:
inline void releaseEditor(QWidget *editor, const QModelIndex &index = QModelIndex()) const {
if (editor) {
Q_Q(const QAbstractItemView);
- QObject::disconnect(editor, SIGNAL(destroyed(QObject*)),
- q_func(), SLOT(editorDestroyed(QObject*)));
+ QObject::disconnect(editor, &QWidget::destroyed,
+ q, &QAbstractItemView::editorDestroyed);
editor->removeEventFilter(itemDelegate);
editor->hide();
QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
@@ -252,12 +257,14 @@ public:
inline bool isIndexEnabled(const QModelIndex &index) const {
return (model->flags(index) & Qt::ItemIsEnabled);
}
+#if QT_CONFIG(draganddrop)
inline bool isIndexDropEnabled(const QModelIndex &index) const {
return (model->flags(index) & Qt::ItemIsDropEnabled);
}
inline bool isIndexDragEnabled(const QModelIndex &index) const {
return (model->flags(index) & Qt::ItemIsDragEnabled);
}
+#endif
virtual bool selectionAllowed(const QModelIndex &index) const {
// in some views we want to go ahead with selections, even if the index is invalid
@@ -304,13 +311,16 @@ public:
return static_cast<QAbstractItemModelPrivate *>(model->d_ptr.data())->persistent.indexes.contains(index);
}
+#if QT_CONFIG(draganddrop)
QModelIndexList selectedDraggableIndexes() const;
+ void maybeStartDrag(QPoint eventPoint);
+#endif
void doDelayedReset()
{
//we delay the reset of the timer because some views (QTableView)
//with headers can't handle the fact that the model has been destroyed
- //all _q_modelDestroyed slots must have been called
+ //all modelDestroyed() slots must have been called
if (!delayedReset.isActive())
delayedReset.start(0, q_func());
}
@@ -411,7 +421,18 @@ public:
bool verticalScrollModeSet;
bool horizontalScrollModeSet;
+ virtual QRect visualRect(const QModelIndex &index) const { return q_func()->visualRect(index); }
+
+ std::array<QMetaObject::Connection, 14> modelConnections;
+ std::array<QMetaObject::Connection, 4> scrollbarConnections;
+#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
+ QMetaObject::Connection scollerConnection;
+#endif
+
private:
+ void connectDelegate(QAbstractItemDelegate *delegate);
+ void disconnectDelegate(QAbstractItemDelegate *delegate);
+ void disconnectAll();
inline QAbstractItemDelegate *delegateForIndex(const QModelIndex &index) const {
QMap<int, QPointer<QAbstractItemDelegate> >::ConstIterator it;
diff --git a/src/widgets/itemviews/qcolumnview.cpp b/src/widgets/itemviews/qcolumnview.cpp
index 040bddb311..04bc8f5f88 100644
--- a/src/widgets/itemviews/qcolumnview.cpp
+++ b/src/widgets/itemviews/qcolumnview.cpp
@@ -68,7 +68,9 @@ void QColumnViewPrivate::initialize()
Q_Q(QColumnView);
q->setTextElideMode(Qt::ElideMiddle);
#if QT_CONFIG(animation)
- QObject::connect(&currentAnimation, SIGNAL(finished()), q, SLOT(_q_changeCurrentColumn()));
+ animationConnection =
+ QObjectPrivate::connect(&currentAnimation, &QPropertyAnimation::finished,
+ this, &QColumnViewPrivate::changeCurrentColumn);
currentAnimation.setTargetObject(hbar);
currentAnimation.setPropertyName("value");
currentAnimation.setEasingCurve(QEasingCurve::InOutQuad);
@@ -77,11 +79,26 @@ void QColumnViewPrivate::initialize()
q->setItemDelegate(new QColumnViewDelegate(q));
}
+void QColumnViewPrivate::clearConnections()
+{
+#if QT_CONFIG(animation)
+ QObject::disconnect(animationConnection);
+#endif
+ for (const QMetaObject::Connection &connection : gripConnections)
+ QObject::disconnect(connection);
+ const auto copy = viewConnections; // disconnectView modifies this container
+ for (auto it = copy.keyBegin(); it != copy.keyEnd(); ++it)
+ disconnectView(*it);
+}
+
+
/*!
Destroys the column view.
*/
QColumnView::~QColumnView()
{
+ Q_D(QColumnView);
+ d->clearConnections();
}
/*!
@@ -98,12 +115,15 @@ void QColumnView::setResizeGripsVisible(bool visible)
if (d->showResizeGrips == visible)
return;
d->showResizeGrips = visible;
- for (int i = 0; i < d->columns.size(); ++i) {
- QAbstractItemView *view = d->columns[i];
+ d->gripConnections.clear();
+ for (QAbstractItemView *view : std::as_const(d->columns)) {
if (visible) {
QColumnViewGrip *grip = new QColumnViewGrip(view);
view->setCornerWidget(grip);
- connect(grip, SIGNAL(gripMoved(int)), this, SLOT(_q_gripMoved(int)));
+ d->gripConnections.push_back(
+ QObjectPrivate::connect(grip, &QColumnViewGrip::gripMoved,
+ d, &QColumnViewPrivate::gripMoved)
+ );
} else {
QWidget *widget = view->cornerWidget();
view->setCornerWidget(nullptr);
@@ -267,7 +287,7 @@ void QColumnView::scrollTo(const QModelIndex &index, ScrollHint hint)
if (leftEdge > -horizontalOffset()
&& rightEdge <= ( -horizontalOffset() + viewport()->size().width())) {
d->columns.at(indexColumn)->scrollTo(index);
- d->_q_changeCurrentColumn();
+ d->changeCurrentColumn();
return;
}
@@ -486,7 +506,7 @@ QSize QColumnView::sizeHint() const
\internal
Move all widgets from the corner grip and to the right
*/
-void QColumnViewPrivate::_q_gripMoved(int offset)
+void QColumnViewPrivate::gripMoved(int offset)
{
Q_Q(QColumnView);
@@ -578,8 +598,10 @@ void QColumnViewPrivate::closeColumns(const QModelIndex &parent, bool build)
QAbstractItemView* notShownAnymore = columns.at(i);
columns.removeAt(i);
notShownAnymore->setVisible(false);
- if (notShownAnymore != previewColumn)
+ if (notShownAnymore != previewColumn) {
notShownAnymore->deleteLater();
+ disconnectView(notShownAnymore);
+ }
}
if (columns.isEmpty()) {
@@ -598,7 +620,17 @@ void QColumnViewPrivate::closeColumns(const QModelIndex &parent, bool build)
createColumn(parent, false);
}
-void QColumnViewPrivate::_q_clicked(const QModelIndex &index)
+void QColumnViewPrivate::disconnectView(QAbstractItemView *view)
+{
+ const auto it = viewConnections.find(view);
+ if (it == viewConnections.end())
+ return;
+ for (const QMetaObject::Connection &connection : it.value())
+ QObject::disconnect(connection);
+ viewConnections.erase(it);
+}
+
+void QColumnViewPrivate::clicked(const QModelIndex &index)
{
Q_Q(QColumnView);
QModelIndex parent = index.parent();
@@ -631,10 +663,11 @@ QAbstractItemView *QColumnViewPrivate::createColumn(const QModelIndex &index, bo
{
Q_Q(QColumnView);
QAbstractItemView *view = nullptr;
+ QMetaObject::Connection clickedConnection;
if (model->hasChildren(index)) {
view = q->createColumn(index);
- q->connect(view, SIGNAL(clicked(QModelIndex)),
- q, SLOT(_q_clicked(QModelIndex)));
+ clickedConnection = QObjectPrivate::connect(view, &QAbstractItemView::clicked,
+ this, &QColumnViewPrivate::clicked);
} else {
if (!previewColumn)
setPreviewWidget(new QWidget(q));
@@ -642,16 +675,14 @@ QAbstractItemView *QColumnViewPrivate::createColumn(const QModelIndex &index, bo
view->setMinimumWidth(qMax(view->minimumWidth(), previewWidget->minimumWidth()));
}
- q->connect(view, SIGNAL(activated(QModelIndex)),
- q, SIGNAL(activated(QModelIndex)));
- q->connect(view, SIGNAL(clicked(QModelIndex)),
- q, SIGNAL(clicked(QModelIndex)));
- q->connect(view, SIGNAL(doubleClicked(QModelIndex)),
- q, SIGNAL(doubleClicked(QModelIndex)));
- q->connect(view, SIGNAL(entered(QModelIndex)),
- q, SIGNAL(entered(QModelIndex)));
- q->connect(view, SIGNAL(pressed(QModelIndex)),
- q, SIGNAL(pressed(QModelIndex)));
+ viewConnections[view] = {
+ QObject::connect(view, &QAbstractItemView::activated, q, &QColumnView::activated),
+ QObject::connect(view, &QAbstractItemView::clicked, q, &QColumnView::clicked),
+ QObject::connect(view, &QAbstractItemView::doubleClicked, q, &QColumnView::doubleClicked),
+ QObject::connect(view, &QAbstractItemView::entered, q, &QColumnView::entered),
+ QObject::connect(view, &QAbstractItemView::pressed, q, &QColumnView::pressed),
+ clickedConnection
+ };
view->setFocusPolicy(Qt::NoFocus);
view->setParent(viewport);
@@ -661,7 +692,10 @@ QAbstractItemView *QColumnViewPrivate::createColumn(const QModelIndex &index, bo
if (showResizeGrips) {
QColumnViewGrip *grip = new QColumnViewGrip(view);
view->setCornerWidget(grip);
- q->connect(grip, SIGNAL(gripMoved(int)), q, SLOT(_q_gripMoved(int)));
+ gripConnections.push_back(
+ QObjectPrivate::connect(grip, &QColumnViewGrip::gripMoved,
+ this, &QColumnViewPrivate::gripMoved)
+ );
}
if (columnSizes.size() > columns.size()) {
@@ -915,7 +949,7 @@ void QColumnView::currentChanged(const QModelIndex &current, const QModelIndex &
We have change the current column and need to update focus and selection models
on the new current column.
*/
-void QColumnViewPrivate::_q_changeCurrentColumn()
+void QColumnViewPrivate::changeCurrentColumn()
{
Q_Q(QColumnView);
if (columns.isEmpty())
@@ -1022,9 +1056,9 @@ QColumnViewPrivate::~QColumnViewPrivate()
\internal
*/
-void QColumnViewPrivate::_q_columnsInserted(const QModelIndex &parent, int start, int end)
+void QColumnViewPrivate::columnsInserted(const QModelIndex &parent, int start, int end)
{
- QAbstractItemViewPrivate::_q_columnsInserted(parent, start, end);
+ QAbstractItemViewPrivate::columnsInserted(parent, start, end);
checkColumnCreation(parent);
}
diff --git a/src/widgets/itemviews/qcolumnview.h b/src/widgets/itemviews/qcolumnview.h
index 25b15b5273..c0c1398692 100644
--- a/src/widgets/itemviews/qcolumnview.h
+++ b/src/widgets/itemviews/qcolumnview.h
@@ -67,9 +67,6 @@ protected:
private:
Q_DECLARE_PRIVATE(QColumnView)
Q_DISABLE_COPY(QColumnView)
- Q_PRIVATE_SLOT(d_func(), void _q_gripMoved(int))
- Q_PRIVATE_SLOT(d_func(), void _q_changeCurrentColumn())
- Q_PRIVATE_SLOT(d_func(), void _q_clicked(const QModelIndex &))
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qcolumnview_p.h b/src/widgets/itemviews/qcolumnview_p.h
index 7c68ab2314..f9b2f3baa4 100644
--- a/src/widgets/itemviews/qcolumnview_p.h
+++ b/src/widgets/itemviews/qcolumnview_p.h
@@ -31,6 +31,8 @@
#include <qevent.h>
#include <qscrollbar.h>
+#include <vector>
+
QT_REQUIRE_CONFIG(columnview);
QT_BEGIN_NAMESPACE
@@ -116,20 +118,22 @@ public:
QColumnViewPrivate();
~QColumnViewPrivate();
void initialize();
+ void clearConnections();
QAbstractItemView *createColumn(const QModelIndex &index, bool show);
void updateScrollbars();
void closeColumns(const QModelIndex &parent = QModelIndex(), bool build = false);
+ void disconnectView(QAbstractItemView *view);
void doLayout();
void setPreviewWidget(QWidget *widget);
void checkColumnCreation(const QModelIndex &parent);
- void _q_gripMoved(int offset);
- void _q_changeCurrentColumn();
- void _q_clicked(const QModelIndex &index);
- void _q_columnsInserted(const QModelIndex &parent, int start, int end) override;
+ void gripMoved(int offset);
+ void changeCurrentColumn();
+ void clicked(const QModelIndex &index);
+ void columnsInserted(const QModelIndex &parent, int start, int end) override;
QList<QAbstractItemView*> columns;
QList<int> columnSizes; // used during init and corner moving
@@ -137,7 +141,12 @@ public:
int offset;
#if QT_CONFIG(animation)
QPropertyAnimation currentAnimation;
+ QMetaObject::Connection animationConnection;
#endif
+ std::vector<QMetaObject::Connection> gripConnections;
+ using ViewConnections = std::vector<QMetaObject::Connection>;
+ QHash<QAbstractItemView *, ViewConnections> viewConnections;
+
QWidget *previewWidget;
QAbstractItemView *previewColumn;
};
diff --git a/src/widgets/itemviews/qdatawidgetmapper.cpp b/src/widgets/itemviews/qdatawidgetmapper.cpp
index 5160d06519..3b7e97eed9 100644
--- a/src/widgets/itemviews/qdatawidgetmapper.cpp
+++ b/src/widgets/itemviews/qdatawidgetmapper.cpp
@@ -4,13 +4,15 @@
#include "qdatawidgetmapper.h"
#include "qabstractitemmodel.h"
-#include "qitemdelegate.h"
#include "qmetaobject.h"
#include "qwidget.h"
#include "qstyleditemdelegate.h"
+
#include "private/qobject_p.h"
#include "private/qabstractitemmodel_p.h"
+#include <QtCore/qpointer.h>
+#include <array>
#include <iterator>
QT_BEGIN_NAMESPACE
@@ -67,11 +69,22 @@ public:
void populate();
// private slots
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
- const QList<int> &);
- void _q_commitData(QWidget *);
- void _q_closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint);
- void _q_modelDestroyed();
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &);
+ void commitData(QWidget *);
+ void closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint);
+ void modelDestroyed();
+
+ void disconnectModel()
+ {
+ for (const QMetaObject::Connection &connection : modelConnections)
+ QObject::disconnect(connection);
+ }
+ void disconnectDelegate()
+ {
+ for (const QMetaObject::Connection &connection : delegateConnections)
+ QObject::disconnect(connection);
+ }
struct WidgetMapper
{
@@ -87,6 +100,8 @@ public:
bool commit(const WidgetMapper &m);
std::vector<WidgetMapper> widgetMap;
+ std::array<QMetaObject::Connection, 2> modelConnections;
+ std::array<QMetaObject::Connection, 2> delegateConnections;
};
Q_DECLARE_TYPEINFO(QDataWidgetMapperPrivate::WidgetMapper, Q_RELOCATABLE_TYPE);
@@ -142,8 +157,8 @@ static bool qContainsIndex(const QModelIndex &idx, const QModelIndex &topLeft,
&& idx.column() >= topLeft.column() && idx.column() <= bottomRight.column();
}
-void QDataWidgetMapperPrivate::_q_dataChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight, const QList<int> &)
+void QDataWidgetMapperPrivate::dataChanged(const QModelIndex &topLeft,
+ const QModelIndex &bottomRight, const QList<int> &)
{
if (topLeft.parent() != rootIndex)
return; // not in our hierarchy
@@ -154,7 +169,7 @@ void QDataWidgetMapperPrivate::_q_dataChanged(const QModelIndex &topLeft,
}
}
-void QDataWidgetMapperPrivate::_q_commitData(QWidget *w)
+void QDataWidgetMapperPrivate::commitData(QWidget *w)
{
if (submitPolicy == QDataWidgetMapper::ManualSubmit)
return;
@@ -166,7 +181,7 @@ void QDataWidgetMapperPrivate::_q_commitData(QWidget *w)
commit(widgetMap[idx]);
}
-void QDataWidgetMapperPrivate::_q_closeEditor(QWidget *w, QAbstractItemDelegate::EndEditHint hint)
+void QDataWidgetMapperPrivate::closeEditor(QWidget *w, QAbstractItemDelegate::EndEditHint hint)
{
int idx = findWidget(w);
if (idx == -1)
@@ -189,7 +204,7 @@ void QDataWidgetMapperPrivate::_q_closeEditor(QWidget *w, QAbstractItemDelegate:
}
}
-void QDataWidgetMapperPrivate::_q_modelDestroyed()
+void QDataWidgetMapperPrivate::modelDestroyed()
{
Q_Q(QDataWidgetMapper);
@@ -220,7 +235,7 @@ void QDataWidgetMapperPrivate::_q_modelDestroyed()
instead of the default user property.
It is possible to set an item delegate to support custom widgets. By default,
- a QItemDelegate is used to synchronize the model with the widgets.
+ a QStyledItemDelegate is used to synchronize the model with the widgets.
Let us assume that we have an item model named \c{model} with the following contents:
@@ -299,6 +314,9 @@ QDataWidgetMapper::QDataWidgetMapper(QObject *parent)
*/
QDataWidgetMapper::~QDataWidgetMapper()
{
+ Q_D(QDataWidgetMapper);
+ d->disconnectModel();
+ d->disconnectDelegate();
}
/*!
@@ -314,21 +332,19 @@ void QDataWidgetMapper::setModel(QAbstractItemModel *model)
if (d->model == model)
return;
- if (d->model) {
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QList<int>)), this,
- SLOT(_q_dataChanged(QModelIndex, QModelIndex, QList<int>)));
- disconnect(d->model, SIGNAL(destroyed()), this,
- SLOT(_q_modelDestroyed()));
- }
+ d->disconnectModel();
clearMapping();
d->rootIndex = QModelIndex();
d->currentTopLeft = QModelIndex();
d->model = model;
- connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QList<int>)),
- SLOT(_q_dataChanged(QModelIndex, QModelIndex, QList<int>)));
- connect(model, SIGNAL(destroyed()), SLOT(_q_modelDestroyed()));
+ d->modelConnections = {
+ QObjectPrivate::connect(model, &QAbstractItemModel::dataChanged,
+ d, &QDataWidgetMapperPrivate::dataChanged),
+ QObjectPrivate::connect(model, &QAbstractItemModel::destroyed,
+ d, &QDataWidgetMapperPrivate::modelDestroyed)
+ };
}
/*!
@@ -364,18 +380,17 @@ void QDataWidgetMapper::setItemDelegate(QAbstractItemDelegate *delegate)
{
Q_D(QDataWidgetMapper);
QAbstractItemDelegate *oldDelegate = d->delegate;
- if (oldDelegate) {
- disconnect(oldDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(_q_commitData(QWidget*)));
- disconnect(oldDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(_q_closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- }
+ d->disconnectDelegate();
d->delegate = delegate;
if (delegate) {
- connect(delegate, SIGNAL(commitData(QWidget*)), SLOT(_q_commitData(QWidget*)));
- connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- SLOT(_q_closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
+ d->delegateConnections = {
+ QObjectPrivate::connect(delegate, &QAbstractItemDelegate::commitData,
+ d, &QDataWidgetMapperPrivate::commitData),
+ QObjectPrivate::connect(delegate, &QAbstractItemDelegate::closeEditor,
+ d, &QDataWidgetMapperPrivate::closeEditor)
+ };
}
d->flipEventFilters(oldDelegate, delegate);
diff --git a/src/widgets/itemviews/qdatawidgetmapper.h b/src/widgets/itemviews/qdatawidgetmapper.h
index 56243f1190..6c7beff7fc 100644
--- a/src/widgets/itemviews/qdatawidgetmapper.h
+++ b/src/widgets/itemviews/qdatawidgetmapper.h
@@ -72,12 +72,6 @@ Q_SIGNALS:
private:
Q_DECLARE_PRIVATE(QDataWidgetMapper)
Q_DISABLE_COPY(QDataWidgetMapper)
- Q_PRIVATE_SLOT(d_func(),
- void _q_dataChanged(const QModelIndex &, const QModelIndex &,
- const QList<int> &))
- Q_PRIVATE_SLOT(d_func(), void _q_commitData(QWidget *))
- Q_PRIVATE_SLOT(d_func(), void _q_closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint))
- Q_PRIVATE_SLOT(d_func(), void _q_modelDestroyed())
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qheaderview.cpp b/src/widgets/itemviews/qheaderview.cpp
index b5b0f17f4a..9ce09dbacc 100644
--- a/src/widgets/itemviews/qheaderview.cpp
+++ b/src/widgets/itemviews/qheaderview.cpp
@@ -295,6 +295,8 @@ QHeaderView::QHeaderView(QHeaderViewPrivate &dd,
QHeaderView::~QHeaderView()
{
+ Q_D(QHeaderView);
+ d->disconnectModel();
}
/*!
@@ -322,68 +324,35 @@ void QHeaderView::setModel(QAbstractItemModel *model)
return;
Q_D(QHeaderView);
d->layoutChangePersistentSections.clear();
- if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- if (d->orientation == Qt::Horizontal) {
- QObject::disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(sectionsInserted(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_sectionsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)));
- QObject::disconnect(d->model, SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_sectionsMoved(QModelIndex,int,int,QModelIndex,int)));
- } else {
- QObject::disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(sectionsInserted(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_sectionsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)));
- QObject::disconnect(d->model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_sectionsMoved(QModelIndex,int,int,QModelIndex,int)));
- }
- QObject::disconnect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(headerDataChanged(Qt::Orientation,int,int)));
- QObject::disconnect(d->model, SIGNAL(layoutAboutToBeChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)),
- this, SLOT(_q_sectionsAboutToBeChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)));
- QObject::disconnect(d->model, SIGNAL(layoutChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)),
- this, SLOT(_q_sectionsChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)));
- }
+ if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel())
+ d->disconnectModel();
if (model && model != QAbstractItemModelPrivate::staticEmptyModel()) {
- if (d->orientation == Qt::Horizontal) {
- QObject::connect(model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(sectionsInserted(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_sectionsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)));
- QObject::connect(model, SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_sectionsMoved(QModelIndex,int,int,QModelIndex,int)));
- } else {
- QObject::connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(sectionsInserted(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_sectionsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)));
- QObject::connect(model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
- this, SLOT(_q_sectionsMoved(QModelIndex,int,int,QModelIndex,int)));
- }
- QObject::connect(model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(headerDataChanged(Qt::Orientation,int,int)));
- QObject::connect(model, SIGNAL(layoutAboutToBeChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)),
- this, SLOT(_q_sectionsAboutToBeChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)));
- QObject::connect(model, SIGNAL(layoutChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)),
- this, SLOT(_q_sectionsChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)));
+ const bool hor = d->orientation == Qt::Horizontal;
+ d->modelConnections = {
+ QObject::connect(model, hor ? &QAbstractItemModel::columnsInserted
+ : &QAbstractItemModel::rowsInserted,
+ this, &QHeaderView::sectionsInserted),
+ QObject::connect(model, hor ? &QAbstractItemModel::columnsAboutToBeRemoved
+ : &QAbstractItemModel::rowsAboutToBeRemoved,
+ this, &QHeaderView::sectionsAboutToBeRemoved),
+ QObjectPrivate::connect(model, hor ? &QAbstractItemModel::columnsRemoved
+ : &QAbstractItemModel::rowsRemoved,
+ d, &QHeaderViewPrivate::sectionsRemoved),
+ QObjectPrivate::connect(model, hor ? &QAbstractItemModel::columnsAboutToBeMoved
+ : &QAbstractItemModel::rowsAboutToBeMoved,
+ d, &QHeaderViewPrivate::sectionsAboutToBeMoved),
+ QObjectPrivate::connect(model, hor ? &QAbstractItemModel::columnsMoved
+ : &QAbstractItemModel::rowsMoved,
+ d, &QHeaderViewPrivate::sectionsMoved),
+
+ QObject::connect(model, &QAbstractItemModel::headerDataChanged,
+ this, &QHeaderView::headerDataChanged),
+ QObjectPrivate::connect(model, &QAbstractItemModel::layoutAboutToBeChanged,
+ d, &QHeaderViewPrivate::sectionsAboutToBeChanged),
+ QObjectPrivate::connect(model, &QAbstractItemModel::layoutChanged,
+ d, &QHeaderViewPrivate::sectionsChanged)
+ };
}
d->state = QHeaderViewPrivate::NoClear;
@@ -418,7 +387,7 @@ Qt::Orientation QHeaderView::orientation() const
int QHeaderView::offset() const
{
Q_D(const QHeaderView);
- return d->offset;
+ return d->headerOffset;
}
/*!
@@ -432,10 +401,10 @@ int QHeaderView::offset() const
void QHeaderView::setOffset(int newOffset)
{
Q_D(QHeaderView);
- if (d->offset == (int)newOffset)
+ if (d->headerOffset == newOffset)
return;
- int ndelta = d->offset - newOffset;
- d->offset = newOffset;
+ int ndelta = d->headerOffset - newOffset;
+ d->headerOffset = newOffset;
if (d->orientation == Qt::Horizontal)
d->viewport->scroll(isRightToLeft() ? -ndelta : ndelta, 0);
else
@@ -591,7 +560,7 @@ int QHeaderView::visualIndexAt(int position) const
if (d->reverse())
vposition = d->viewport->width() - vposition - 1;
- vposition += d->offset;
+ vposition += d->headerOffset;
if (vposition > d->length)
return -1;
@@ -681,7 +650,7 @@ int QHeaderView::sectionViewportPosition(int logicalIndex) const
int position = sectionPosition(logicalIndex);
if (position < 0)
return position; // the section was hidden
- int offsetPosition = position - d->offset;
+ int offsetPosition = position - d->headerOffset;
if (d->reverse())
return d->viewport->width() - (offsetPosition + sectionSize(logicalIndex));
return offsetPosition;
@@ -1087,19 +1056,22 @@ int QHeaderView::logicalIndex(int visualIndex) const
}
/*!
- \since 5.0
+ \property QHeaderView::sectionsMovable
- If \a movable is true, the header sections may be moved by the user;
+ If \a sectionsMovable is true, the header sections may be moved by the user;
otherwise they are fixed in place.
When used in combination with QTreeView, the first column is not
movable (since it contains the tree structure), by default.
You can make it movable with setFirstSectionMovable(true).
- \sa sectionsMovable(), sectionMoved()
+ \sa sectionMoved()
\sa setFirstSectionMovable()
*/
+/*!
+ Sets \l sectionsMovable to \a movable.
+ */
void QHeaderView::setSectionsMovable(bool movable)
{
Q_D(QHeaderView);
@@ -1107,17 +1079,8 @@ void QHeaderView::setSectionsMovable(bool movable)
}
/*!
- \since 5.0
-
- Returns \c true if the header can be moved by the user; otherwise returns
- false.
-
- By default, sections are movable in QTreeView (except for the first one),
- and not movable in QTableView.
-
- \sa setSectionsMovable()
+ Returns \l sectionsMovable.
*/
-
bool QHeaderView::sectionsMovable() const
{
Q_D(const QHeaderView);
@@ -1137,6 +1100,11 @@ bool QHeaderView::sectionsMovable() const
In such a scenario, it is recommended to call QTreeView::setRootIsDecorated(false)
as well.
+ \code
+ treeView->setRootIsDecorated(false);
+ treeView->header()->setFirstSectionMovable(true);
+ \endcode
+
Setting it to true has no effect unless setSectionsMovable(true) is called
as well.
@@ -1156,14 +1124,17 @@ bool QHeaderView::isFirstSectionMovable() const
}
/*!
- \since 5.0
+ \property QHeaderView::sectionsClickable
- If \a clickable is true, the header will respond to single clicks.
+ Holds \c true if the header is clickable; otherwise \c false. A
+ clickable header could be set up to allow the user to change the
+ representation of the data in the view related to the header.
- \sa sectionsClickable(), sectionClicked(), sectionPressed(),
- setSortIndicatorShown()
+ \sa sectionPressed(), setSortIndicatorShown()
+*/
+/*!
+ Set \l sectionsClickable to \a clickable.
*/
-
void QHeaderView::setSectionsClickable(bool clickable)
{
Q_D(QHeaderView);
@@ -1171,15 +1142,8 @@ void QHeaderView::setSectionsClickable(bool clickable)
}
/*!
- \since 5.0
-
- Returns \c true if the header is clickable; otherwise returns \c false. A
- clickable header could be set up to allow the user to change the
- representation of the data in the view related to the header.
-
- \sa setSectionsClickable()
+ Returns \l sectionsClickable.
*/
-
bool QHeaderView::sectionsClickable() const
{
Q_D(const QHeaderView);
@@ -1880,8 +1844,9 @@ void QHeaderView::sectionsInserted(const QModelIndex &parent,
int logicalFirst, int logicalLast)
{
Q_D(QHeaderView);
- if (parent != d->root)
- return; // we only handle changes in the root level
+ // only handle root level changes and return on no-op
+ if (parent != d->root || d->modelSectionCount() == d->sectionCount())
+ return;
int oldCount = d->sectionCount();
d->invalidateCachedSizeHint();
@@ -2004,8 +1969,8 @@ void QHeaderViewPrivate::updateHiddenSections(int logicalFirst, int logicalLast)
hiddenSectionSize = newHiddenSectionSize;
}
-void QHeaderViewPrivate::_q_sectionsRemoved(const QModelIndex &parent,
- int logicalFirst, int logicalLast)
+void QHeaderViewPrivate::sectionsRemoved(const QModelIndex &parent,
+ int logicalFirst, int logicalLast)
{
Q_Q(QHeaderView);
if (parent != root)
@@ -2090,28 +2055,32 @@ void QHeaderViewPrivate::_q_sectionsRemoved(const QModelIndex &parent,
viewport->update();
}
-void QHeaderViewPrivate::_q_sectionsAboutToBeMoved(const QModelIndex &sourceParent, int logicalStart, int logicalEnd, const QModelIndex &destinationParent, int logicalDestination)
+void QHeaderViewPrivate::sectionsAboutToBeMoved(const QModelIndex &sourceParent, int logicalStart,
+ int logicalEnd, const QModelIndex &destinationParent,
+ int logicalDestination)
{
if (sourceParent != root || destinationParent != root)
return; // we only handle changes in the root level
Q_UNUSED(logicalStart);
Q_UNUSED(logicalEnd);
Q_UNUSED(logicalDestination);
- _q_sectionsAboutToBeChanged();
+ sectionsAboutToBeChanged();
}
-void QHeaderViewPrivate::_q_sectionsMoved(const QModelIndex &sourceParent, int logicalStart, int logicalEnd, const QModelIndex &destinationParent, int logicalDestination)
+void QHeaderViewPrivate::sectionsMoved(const QModelIndex &sourceParent, int logicalStart,
+ int logicalEnd, const QModelIndex &destinationParent,
+ int logicalDestination)
{
if (sourceParent != root || destinationParent != root)
return; // we only handle changes in the root level
Q_UNUSED(logicalStart);
Q_UNUSED(logicalEnd);
Q_UNUSED(logicalDestination);
- _q_sectionsChanged();
+ sectionsChanged();
}
-void QHeaderViewPrivate::_q_sectionsAboutToBeChanged(const QList<QPersistentModelIndex> &,
- QAbstractItemModel::LayoutChangeHint hint)
+void QHeaderViewPrivate::sectionsAboutToBeChanged(const QList<QPersistentModelIndex> &,
+ QAbstractItemModel::LayoutChangeHint hint)
{
if ((hint == QAbstractItemModel::VerticalSortHint && orientation == Qt::Horizontal) ||
(hint == QAbstractItemModel::HorizontalSortHint && orientation == Qt::Vertical))
@@ -2156,8 +2125,8 @@ void QHeaderViewPrivate::_q_sectionsAboutToBeChanged(const QList<QPersistentMode
}
}
-void QHeaderViewPrivate::_q_sectionsChanged(const QList<QPersistentModelIndex> &,
- QAbstractItemModel::LayoutChangeHint hint)
+void QHeaderViewPrivate::sectionsChanged(const QList<QPersistentModelIndex> &,
+ QAbstractItemModel::LayoutChangeHint hint)
{
if ((hint == QAbstractItemModel::VerticalSortHint && orientation == Qt::Horizontal) ||
(hint == QAbstractItemModel::HorizontalSortHint && orientation == Qt::Vertical))
@@ -2187,7 +2156,7 @@ void QHeaderViewPrivate::_q_sectionsChanged(const QList<QPersistentModelIndex> &
}
// Though far from perfect we here try to retain earlier/existing behavior
- // ### See QHeaderViewPrivate::_q_layoutAboutToBeChanged()
+ // ### See QHeaderViewPrivate::layoutAboutToBeChanged()
// When we don't have valid hasPersistantIndexes it can be due to
// - all sections are default sections
// - the row/column 0 which is used for persistent indexes is gone
@@ -2513,9 +2482,9 @@ void QHeaderView::paintEvent(QPaintEvent *e)
for (int a = 0, i = 0; i < d->sectionItems.count(); ++i) {
QColor color((i & 4 ? 255 : 0), (i & 2 ? 255 : 0), (i & 1 ? 255 : 0));
if (d->orientation == Qt::Horizontal)
- painter.fillRect(a - d->offset, 0, d->sectionItems.at(i).size, 4, color);
+ painter.fillRect(a - d->headerOffset, 0, d->sectionItems.at(i).size, 4, color);
else
- painter.fillRect(0, a - d->offset, 4, d->sectionItems.at(i).size, color);
+ painter.fillRect(0, a - d->headerOffset, 4, d->sectionItems.at(i).size, color);
a += d->sectionItems.at(i).size;
}
@@ -2574,7 +2543,7 @@ void QHeaderView::mousePressEvent(QMouseEvent *e)
void QHeaderView::mouseMoveEvent(QMouseEvent *e)
{
Q_D(QHeaderView);
- int pos = d->orientation == Qt::Horizontal ? e->position().toPoint().x() : e->position().toPoint().y();
+ const int pos = d->orientation == Qt::Horizontal ? e->position().toPoint().x() : e->position().toPoint().y();
if (pos < 0 && d->state != QHeaderViewPrivate::SelectSections)
return;
if (e->buttons() == Qt::NoButton) {
@@ -2602,8 +2571,10 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
return;
}
case QHeaderViewPrivate::MoveSection: {
- if (d->shouldAutoScroll(e->position().toPoint()))
+ if (d->shouldAutoScroll(e->position().toPoint())) {
+ d->draggedPosition = e->pos() + d->offset();
d->startAutoScroll();
+ }
if (qAbs(pos - d->firstPos) >= QApplication::startDragDistance()
#if QT_CONFIG(label)
|| !d->sectionIndicator->isHidden()
@@ -2615,7 +2586,7 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
if (visual == 0 && logicalIndex(0) == 0 && !d->allowUserMoveOfSection0)
return;
- const int posThreshold = d->headerSectionPosition(visual) - d->offset + d->headerSectionSize(visual) / 2;
+ const int posThreshold = d->headerSectionPosition(visual) - d->headerOffset + d->headerSectionSize(visual) / 2;
const int checkPos = d->reverse() ? d->viewport->width() - pos : pos;
int moving = visualIndex(d->section);
int oldTarget = d->target;
@@ -2639,7 +2610,7 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
return;
}
case QHeaderViewPrivate::SelectSections: {
- int logical = logicalIndexAt(qMax(-d->offset, pos));
+ int logical = logicalIndexAt(qMax(-d->headerOffset, pos));
if (logical == -1 && pos > 0)
logical = logicalIndex(d->lastVisibleVisualIndex());
if (logical == d->pressed)
@@ -3061,7 +3032,7 @@ int QHeaderView::horizontalOffset() const
{
Q_D(const QHeaderView);
if (d->orientation == Qt::Horizontal)
- return d->offset;
+ return d->headerOffset;
return 0;
}
@@ -3076,7 +3047,7 @@ int QHeaderView::verticalOffset() const
{
Q_D(const QHeaderView);
if (d->orientation == Qt::Vertical)
- return d->offset;
+ return d->headerOffset;
return 0;
}
@@ -3800,12 +3771,9 @@ void QHeaderViewPrivate::cascadingResize(int visual, int newSize)
if (currentSectionSize <= minimumSize)
continue;
int newSectionSize = qMax(currentSectionSize - delta, minimumSize);
- //qDebug() << "### cascading to" << i << newSectionSize - currentSectionSize << delta;
resizeSectionItem(i, currentSectionSize, newSectionSize);
saveCascadingSectionSize(i, currentSectionSize);
delta = delta - (currentSectionSize - newSectionSize);
- //qDebug() << "new delta" << delta;
- //if (newSectionSize != minimumSize)
if (delta <= 0)
break;
}
@@ -3823,7 +3791,6 @@ void QHeaderViewPrivate::cascadingResize(int visual, int newSize)
int newSectionSize = currentSectionSize - delta;
resizeSectionItem(i, currentSectionSize, newSectionSize);
if (newSectionSize >= originalSectionSize && false) {
- //qDebug() << "section" << i << "restored to" << originalSectionSize;
cascadingSectionSize.remove(i); // the section is now restored
}
sectionResized = true;
diff --git a/src/widgets/itemviews/qheaderview.h b/src/widgets/itemviews/qheaderview.h
index 6118faa868..bd0050df5e 100644
--- a/src/widgets/itemviews/qheaderview.h
+++ b/src/widgets/itemviews/qheaderview.h
@@ -19,6 +19,8 @@ class Q_WIDGETS_EXPORT QHeaderView : public QAbstractItemView
Q_OBJECT
Q_PROPERTY(bool firstSectionMovable READ isFirstSectionMovable WRITE setFirstSectionMovable)
Q_PROPERTY(bool showSortIndicator READ isSortIndicatorShown WRITE setSortIndicatorShown)
+ Q_PROPERTY(bool sectionsMovable READ sectionsMovable WRITE setSectionsMovable)
+ Q_PROPERTY(bool sectionsClickable READ sectionsClickable WRITE setSectionsClickable)
Q_PROPERTY(bool highlightSections READ highlightSections WRITE setHighlightSections)
Q_PROPERTY(bool stretchLastSection READ stretchLastSection WRITE setStretchLastSection)
Q_PROPERTY(bool cascadingSectionResizes READ cascadingSectionResizes
@@ -211,14 +213,6 @@ protected:
private:
void initStyleOption(QStyleOptionFrame *option) const override;
- // ### Qt6: make them protected slots in QHeaderViewPrivate
- Q_PRIVATE_SLOT(d_func(), void _q_sectionsRemoved(const QModelIndex &parent, int logicalFirst, int logicalLast))
- Q_PRIVATE_SLOT(d_func(), void _q_sectionsAboutToBeMoved(const QModelIndex &sourceParent, int logicalStart, int logicalEnd, const QModelIndex &destinationParent, int logicalDestination))
- Q_PRIVATE_SLOT(d_func(), void _q_sectionsMoved(const QModelIndex &sourceParent, int logicalStart, int logicalEnd, const QModelIndex &destinationParent, int logicalDestination))
- Q_PRIVATE_SLOT(d_func(), void _q_sectionsAboutToBeChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(),
- QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint))
- Q_PRIVATE_SLOT(d_func(), void _q_sectionsChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(),
- QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint))
Q_DECLARE_PRIVATE(QHeaderView)
Q_DISABLE_COPY(QHeaderView)
};
diff --git a/src/widgets/itemviews/qheaderview_p.h b/src/widgets/itemviews/qheaderview_p.h
index c599aeff8d..8b214e1d03 100644
--- a/src/widgets/itemviews/qheaderview_p.h
+++ b/src/widgets/itemviews/qheaderview_p.h
@@ -16,6 +16,7 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "qheaderview.h"
#include "private/qabstractitemview_p.h"
#include "QtCore/qbitarray.h"
@@ -24,6 +25,8 @@
#include "QtWidgets/qlabel.h"
#endif
+#include <array>
+
QT_REQUIRE_CONFIG(itemviews);
QT_BEGIN_NAMESPACE
@@ -37,7 +40,7 @@ public:
QHeaderViewPrivate()
: state(NoState),
- offset(0),
+ headerOffset(0),
sortIndicatorOrder(Qt::DescendingOrder),
sortIndicatorSection(0),
sortIndicatorShown(false),
@@ -85,13 +88,17 @@ public:
void updateSectionIndicator(int section, int position);
void updateHiddenSections(int logicalFirst, int logicalLast);
void resizeSections(QHeaderView::ResizeMode globalMode, bool useGlobalMode = false);
- void _q_sectionsRemoved(const QModelIndex &,int,int);
- void _q_sectionsAboutToBeMoved(const QModelIndex &sourceParent, int logicalStart, int logicalEnd, const QModelIndex &destinationParent, int logicalDestination);
- void _q_sectionsMoved(const QModelIndex &sourceParent, int logicalStart, int logicalEnd, const QModelIndex &destinationParent, int logicalDestination);
- void _q_sectionsAboutToBeChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(),
- QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint);
- void _q_sectionsChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(),
- QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint);
+ void sectionsRemoved(const QModelIndex &,int,int);
+ void sectionsAboutToBeMoved(const QModelIndex &sourceParent, int logicalStart,
+ int logicalEnd, const QModelIndex &destinationParent,
+ int logicalDestination);
+ void sectionsMoved(const QModelIndex &sourceParent, int logicalStart,
+ int logicalEnd, const QModelIndex &destinationParent,
+ int logicalDestination);
+ void sectionsAboutToBeChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(),
+ QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint);
+ void sectionsChanged(const QList<QPersistentModelIndex> &parents = QList<QPersistentModelIndex>(),
+ QAbstractItemModel::LayoutChangeHint hint = QAbstractItemModel::NoLayoutChangeHint);
bool isSectionSelected(int section) const;
bool isFirstVisibleSection(int section) const;
@@ -212,6 +219,12 @@ public:
}
}
+ inline void disconnectModel()
+ {
+ for (const QMetaObject::Connection &connection : modelConnections)
+ QObject::disconnect(connection);
+ }
+
void clear();
void flipSortIndicator(int section);
Qt::SortOrder defaultSortOrderForSection(int section) const;
@@ -219,7 +232,7 @@ public:
enum State { NoState, ResizeSection, MoveSection, SelectSections, NoClear } state;
- int offset;
+ int headerOffset;
Qt::Orientation orientation;
Qt::SortOrder sortIndicatorOrder;
int sortIndicatorSection;
@@ -304,6 +317,7 @@ public:
SectionItem section;
};
QList<LayoutChangeItem> layoutChangePersistentSections;
+ std::array<QMetaObject::Connection, 8> modelConnections;
void createSectionItems(int start, int end, int sectionSize, QHeaderView::ResizeMode mode);
void removeSectionsFromSectionItems(int start, int end);
diff --git a/src/widgets/itemviews/qitemdelegate.cpp b/src/widgets/itemviews/qitemdelegate.cpp
index 79ee203aca..d1c7bb3d58 100644
--- a/src/widgets/itemviews/qitemdelegate.cpp
+++ b/src/widgets/itemviews/qitemdelegate.cpp
@@ -257,17 +257,27 @@ QSizeF QItemDelegatePrivate::doTextLayout(int lineWidth) const
When subclassing QItemDelegate to create a delegate that displays items
using a custom renderer, it is important to ensure that the delegate can
- render items suitably for all the required states; e.g. selected,
+ render items suitably for all the required states; such as selected,
disabled, checked. The documentation for the paint() function contains
some hints to show how this can be achieved.
- You can provide custom editors by using a QItemEditorFactory. The
- \l{Color Editor Factory Example} shows how a custom editor can be
- made available to delegates with the default item editor
- factory. This way, there is no need to subclass QItemDelegate. An
- alternative is to reimplement createEditor(), setEditorData(),
- setModelData(), and updateEditorGeometry(). This process is
- described in the \l{Spin Box Delegate Example}.
+ You can provide custom editors by using a QItemEditorFactory. The following
+ code shows how a custom editor can be made available to delegates with the
+ default item editor factory.
+
+ \snippet code/src_gui_itemviews_qitemeditorfactory.cpp setDefaultFactory
+
+ After the default factory has been set, all standard item delegates
+ will use it (also the delegates that were created before setting the
+ default factory).
+
+ This way, you can avoid subclassing QItemDelegate, and all values of the
+ specified type (for example QMetaType::QDateTime) will be edited using the
+ provided editor (like \c{MyFancyDateTimeEdit} in the above example).
+
+ An alternative is to reimplement createEditor(), setEditorData(),
+ setModelData(), and updateEditorGeometry(). This process is described
+ in the \l{A simple delegate}{Model/View Programming overview documentation}.
\section1 QStyledItemDelegate vs. QItemDelegate
@@ -281,9 +291,7 @@ QSizeF QItemDelegatePrivate::doTextLayout(int lineWidth) const
for either class should be equal unless the custom delegate needs to use
the style for drawing.
- \sa {Delegate Classes}, QStyledItemDelegate, QAbstractItemDelegate,
- {Spin Box Delegate Example}, {Settings Editor Example},
- {Icons Example}
+ \sa {Delegate Classes}, QStyledItemDelegate, QAbstractItemDelegate
*/
/*!
@@ -343,8 +351,10 @@ QString QItemDelegatePrivate::valueToText(const QVariant &value, const QStyleOpt
For example, a selected item may need to be displayed differently to
unselected items, as shown in the following code:
- \snippet itemviews/pixelator/pixeldelegate.cpp 2
- \dots
+ \code
+ if (option.state & QStyle::State_Selected)
+ painter->fillRect(option.rect, option.palette.highlight());
+ \endcode
After painting, you should ensure that the painter is returned to its
the state it was supplied in when this function was called. For example,
diff --git a/src/widgets/itemviews/qitemeditorfactory.cpp b/src/widgets/itemviews/qitemeditorfactory.cpp
index 609df364cf..70d11e1b38 100644
--- a/src/widgets/itemviews/qitemeditorfactory.cpp
+++ b/src/widgets/itemviews/qitemeditorfactory.cpp
@@ -120,7 +120,7 @@ Q_SIGNALS:
Additional editors can be registered with the registerEditor() function.
- \sa QStyledItemDelegate, {Model/View Programming}, {Color Editor Factory Example}
+ \sa QStyledItemDelegate, {Model/View Programming}
*/
/*!
@@ -363,7 +363,7 @@ void QItemEditorFactory::setDefaultFactory(QItemEditorFactory *factory)
to register widgets without the need to subclass QItemEditorCreatorBase.
\sa QStandardItemEditorCreator, QItemEditorFactory,
- {Model/View Programming}, {Color Editor Factory Example}
+ {Model/View Programming}
*/
/*!
@@ -432,7 +432,7 @@ QItemEditorCreatorBase::~QItemEditorCreatorBase()
property, you should use QStandardItemEditorCreator instead.
\sa QItemEditorCreatorBase, QStandardItemEditorCreator,
- QItemEditorFactory, {Color Editor Factory Example}
+ QItemEditorFactory
*/
/*!
@@ -488,7 +488,7 @@ QItemEditorCreatorBase::~QItemEditorCreatorBase()
\snippet code/src_gui_itemviews_qitemeditorfactory.cpp 3
\sa QItemEditorCreatorBase, QItemEditorCreator,
- QItemEditorFactory, QStyledItemDelegate, {Color Editor Factory Example}
+ QItemEditorFactory, QStyledItemDelegate
*/
/*!
diff --git a/src/widgets/itemviews/qlistview.cpp b/src/widgets/itemviews/qlistview.cpp
index b03c1a47f5..a7f1931947 100644
--- a/src/widgets/itemviews/qlistview.cpp
+++ b/src/widgets/itemviews/qlistview.cpp
@@ -88,7 +88,7 @@ extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
that can be taken for views that are intended to display items with equal sizes
is to set the \l uniformItemSizes property to true.
- \sa {View Classes}, {Item Views Puzzle Example}, QTreeView, QTableView, QListWidget
+ \sa {View Classes}, QTreeView, QTableView, QListWidget
*/
/*!
@@ -352,7 +352,7 @@ int QListView::spacing() const
/*!
\property QListView::batchSize
\brief the number of items laid out in each batch if \l layoutMode is
- set to \l Batched
+ set to \l Batched.
The default value is 100.
@@ -755,7 +755,10 @@ void QListView::mouseMoveEvent(QMouseEvent *e)
&& d->selectionMode != NoSelection) {
QRect rect(d->pressedPosition, e->position().toPoint() + QPoint(horizontalOffset(), verticalOffset()));
rect = rect.normalized();
- d->viewport->update(d->mapToViewport(rect.united(d->elasticBand)));
+ const int margin = 2 * style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+ const QRect viewPortRect = rect.united(d->elasticBand)
+ .adjusted(-margin, -margin, margin, margin);
+ d->viewport->update(d->mapToViewport(viewPortRect));
d->elasticBand = rect;
}
}
@@ -769,7 +772,9 @@ void QListView::mouseReleaseEvent(QMouseEvent *e)
QAbstractItemView::mouseReleaseEvent(e);
// #### move this implementation into a dynamic class
if (d->showElasticBand && d->elasticBand.isValid()) {
- d->viewport->update(d->mapToViewport(d->elasticBand));
+ const int margin = 2 * style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+ const QRect viewPortRect = d->elasticBand.adjusted(-margin, -margin, margin, margin);
+ d->viewport->update(d->mapToViewport(viewPortRect));
d->elasticBand = QRect();
}
}
@@ -910,7 +915,8 @@ void QListView::dropEvent(QDropEvent *event)
bool dataMoved = false;
for (int i = 0; i < persIndexes.size(); ++i) {
const QPersistentModelIndex &pIndex = persIndexes.at(i);
- if (r != pIndex.row()) {
+ // only generate a move when not same row or behind itself
+ if (r != pIndex.row() && r != pIndex.row() + 1) {
// try to move (preserves selection)
dataMoved |= model()->moveRow(QModelIndex(), pIndex.row(), QModelIndex(), r);
if (!dataMoved) // can't move - abort and let QAbstractItemView handle this
@@ -1621,6 +1627,12 @@ void QListView::setModelColumn(int column)
return;
d->column = column;
d->doDelayedItemsLayout();
+#if QT_CONFIG(accessibility)
+ if (QAccessible::isActive()) {
+ QAccessibleTableModelChangeEvent event(this, QAccessibleTableModelChangeEvent::ModelReset);
+ QAccessible::updateAccessibility(&event);
+ }
+#endif
}
int QListView::modelColumn() const
@@ -1790,7 +1802,7 @@ void QListViewPrivate::prepareItemsLayout()
if (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents)) {
QStyleOption option;
option.initFrom(q);
- frameAroundContents = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &option) * 2;
+ frameAroundContents = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &option, q) * 2;
}
// maximumViewportSize() already takes scrollbar into account if policy is
@@ -3401,7 +3413,7 @@ void QListView::currentChanged(const QModelIndex &current, const QModelIndex &pr
QAbstractItemView::currentChanged(current, previous);
#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
- if (current.isValid()) {
+ if (current.isValid() && hasFocus()) {
int entry = visualIndex(current);
QAccessibleEvent event(this, QAccessible::Focus);
event.setChild(entry);
diff --git a/src/widgets/itemviews/qlistview_p.h b/src/widgets/itemviews/qlistview_p.h
index de928bbb28..40dabf5656 100644
--- a/src/widgets/itemviews/qlistview_p.h
+++ b/src/widgets/itemviews/qlistview_p.h
@@ -16,6 +16,7 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "qlistview.h"
#include "private/qabstractitemview_p.h"
#include "qbitarray.h"
#include "qbsptree_p.h"
diff --git a/src/widgets/itemviews/qlistwidget.cpp b/src/widgets/itemviews/qlistwidget.cpp
index cc0ccf84da..a91902813a 100644
--- a/src/widgets/itemviews/qlistwidget.cpp
+++ b/src/widgets/itemviews/qlistwidget.cpp
@@ -3,7 +3,6 @@
#include "qlistwidget.h"
-#include <qitemdelegate.h>
#include <private/qlistview_p.h>
#include <private/qwidgetitemdata_p.h>
#include <private/qlistwidget_p.h>
@@ -308,7 +307,7 @@ void QListModel::sort(int column, Qt::SortOrder order)
}
const auto compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
- std::sort(sorting.begin(), sorting.end(), compare);
+ std::stable_sort(sorting.begin(), sorting.end(), compare);
QModelIndexList fromIndexes;
QModelIndexList toIndexes;
const int sortingCount = sorting.size();
@@ -328,76 +327,34 @@ void QListModel::sort(int column, Qt::SortOrder order)
/**
* This function assumes that all items in the model except the items that are between
* (inclusive) start and end are sorted.
- * With these assumptions, this function can ensure that the model is sorted in a
- * much more efficient way than doing a naive 'sort everything'.
- * (provided that the range is relatively small compared to the total number of items)
*/
void QListModel::ensureSorted(int column, Qt::SortOrder order, int start, int end)
{
if (column != 0)
return;
- const int count = end - start + 1;
- QList<QPair<QListWidgetItem *, int>> sorting(count);
- for (int i = 0; i < count; ++i) {
- sorting[i].first = items.at(start + i);
- sorting[i].second = start + i;
- }
+ const auto compareLt = [](const QListWidgetItem *left, const QListWidgetItem *right) -> bool {
+ return *left < *right;
+ };
- const auto compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
- std::sort(sorting.begin(), sorting.end(), compare);
-
- QModelIndexList oldPersistentIndexes = persistentIndexList();
- QModelIndexList newPersistentIndexes = oldPersistentIndexes;
- QList<QListWidgetItem*> tmp = items;
- QList<QListWidgetItem*>::iterator lit = tmp.begin();
- bool changed = false;
- for (int i = 0; i < count; ++i) {
- int oldRow = sorting.at(i).second;
- int tmpitepos = lit - tmp.begin();
- QListWidgetItem *item = tmp.takeAt(oldRow);
- if (tmpitepos > tmp.size())
- --tmpitepos;
- lit = tmp.begin() + tmpitepos;
- lit = sortedInsertionIterator(lit, tmp.end(), order, item);
- int newRow = qMax<qsizetype>(lit - tmp.begin(), 0);
- lit = tmp.insert(lit, item);
- if (newRow != oldRow) {
- if (!changed) {
- emit layoutAboutToBeChanged({}, QAbstractItemModel::VerticalSortHint);
- oldPersistentIndexes = persistentIndexList();
- newPersistentIndexes = oldPersistentIndexes;
- changed = true;
- }
- for (int j = i + 1; j < count; ++j) {
- int otherRow = sorting.at(j).second;
- if (oldRow < otherRow && newRow >= otherRow)
- --sorting[j].second;
- else if (oldRow > otherRow && newRow <= otherRow)
- ++sorting[j].second;
- }
- for (int k = 0; k < newPersistentIndexes.size(); ++k) {
- QModelIndex pi = newPersistentIndexes.at(k);
- int oldPersistentRow = pi.row();
- int newPersistentRow = oldPersistentRow;
- if (oldPersistentRow == oldRow)
- newPersistentRow = newRow;
- else if (oldRow < oldPersistentRow && newRow >= oldPersistentRow)
- newPersistentRow = oldPersistentRow - 1;
- else if (oldRow > oldPersistentRow && newRow <= oldPersistentRow)
- newPersistentRow = oldPersistentRow + 1;
- if (newPersistentRow != oldPersistentRow)
- newPersistentIndexes[k] = createIndex(newPersistentRow,
- pi.column(), pi.internalPointer());
- }
- }
- }
+ const auto compareGt = [](const QListWidgetItem *left, const QListWidgetItem *right) -> bool {
+ return *right < *left;
+ };
- if (changed) {
- items = tmp;
- changePersistentIndexList(oldPersistentIndexes, newPersistentIndexes);
- emit layoutChanged({}, QAbstractItemModel::VerticalSortHint);
- }
+ /** Check if range [start,end] is already in sorted position in list.
+ * Take for this the assumption, that outside [start,end] the list
+ * is already sorted. Therefore the sorted check has to be extended
+ * to the first element that is known to be sorted before the range
+ * [start, end], which is (start-1) and the first element after the
+ * range [start, end], which is (end+2) due to end being included.
+ */
+ const auto beginChangedIterator = items.constBegin() + qMax(start - 1, 0);
+ const auto endChangedIterator = items.constBegin() + qMin(end + 2, items.size());
+ const bool needsSorting = !std::is_sorted(beginChangedIterator, endChangedIterator,
+ order == Qt::AscendingOrder ? compareLt : compareGt);
+
+ if (needsSorting)
+ sort(column, order);
}
bool QListModel::itemLessThan(const QPair<QListWidgetItem*,int> &left,
@@ -1126,57 +1083,71 @@ void QListWidgetPrivate::setup()
Q_Q(QListWidget);
q->QListView::setModel(new QListModel(q));
// view signals
- QObject::connect(q, SIGNAL(pressed(QModelIndex)), q, SLOT(_q_emitItemPressed(QModelIndex)));
- QObject::connect(q, SIGNAL(clicked(QModelIndex)), q, SLOT(_q_emitItemClicked(QModelIndex)));
- QObject::connect(q, SIGNAL(doubleClicked(QModelIndex)),
- q, SLOT(_q_emitItemDoubleClicked(QModelIndex)));
- QObject::connect(q, SIGNAL(activated(QModelIndex)),
- q, SLOT(_q_emitItemActivated(QModelIndex)));
- QObject::connect(q, SIGNAL(entered(QModelIndex)), q, SLOT(_q_emitItemEntered(QModelIndex)));
- QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitItemChanged(QModelIndex)));
- QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)), q, SLOT(_q_sort()));
-}
-
-void QListWidgetPrivate::_q_emitItemPressed(const QModelIndex &index)
+ connections = {
+ QObjectPrivate::connect(q, &QListWidget::pressed,
+ this, &QListWidgetPrivate::emitItemPressed),
+ QObjectPrivate::connect(q, &QListWidget::clicked,
+ this, &QListWidgetPrivate::emitItemClicked),
+ QObjectPrivate::connect(q, &QListWidget::doubleClicked,
+ this, &QListWidgetPrivate::emitItemDoubleClicked),
+ QObjectPrivate::connect(q, &QListWidget::activated,
+ this, &QListWidgetPrivate::emitItemActivated),
+ QObjectPrivate::connect(q, &QListWidget::entered,
+ this, &QListWidgetPrivate::emitItemEntered),
+ QObjectPrivate::connect(model, &QAbstractItemModel::dataChanged,
+ this, &QListWidgetPrivate::emitItemChanged),
+ QObjectPrivate::connect(model, &QAbstractItemModel::dataChanged,
+ this, &QListWidgetPrivate::dataChanged),
+ QObjectPrivate::connect(model, &QAbstractItemModel::columnsRemoved,
+ this, &QListWidgetPrivate::sort)
+ };
+}
+
+void QListWidgetPrivate::clearConnections()
+{
+ for (const QMetaObject::Connection &connection : connections)
+ QObject::disconnect(connection);
+ for (const QMetaObject::Connection &connection : selectionModelConnections)
+ QObject::disconnect(connection);
+}
+
+void QListWidgetPrivate::emitItemPressed(const QModelIndex &index)
{
Q_Q(QListWidget);
emit q->itemPressed(listModel()->at(index.row()));
}
-void QListWidgetPrivate::_q_emitItemClicked(const QModelIndex &index)
+void QListWidgetPrivate::emitItemClicked(const QModelIndex &index)
{
Q_Q(QListWidget);
emit q->itemClicked(listModel()->at(index.row()));
}
-void QListWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index)
+void QListWidgetPrivate::emitItemDoubleClicked(const QModelIndex &index)
{
Q_Q(QListWidget);
emit q->itemDoubleClicked(listModel()->at(index.row()));
}
-void QListWidgetPrivate::_q_emitItemActivated(const QModelIndex &index)
+void QListWidgetPrivate::emitItemActivated(const QModelIndex &index)
{
Q_Q(QListWidget);
emit q->itemActivated(listModel()->at(index.row()));
}
-void QListWidgetPrivate::_q_emitItemEntered(const QModelIndex &index)
+void QListWidgetPrivate::emitItemEntered(const QModelIndex &index)
{
Q_Q(QListWidget);
emit q->itemEntered(listModel()->at(index.row()));
}
-void QListWidgetPrivate::_q_emitItemChanged(const QModelIndex &index)
+void QListWidgetPrivate::emitItemChanged(const QModelIndex &index)
{
Q_Q(QListWidget);
emit q->itemChanged(listModel()->at(index.row()));
}
-void QListWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
+void QListWidgetPrivate::emitCurrentItemChanged(const QModelIndex &current,
const QModelIndex &previous)
{
Q_Q(QListWidget);
@@ -1194,14 +1165,14 @@ void QListWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
emit q->currentRowChanged(persistentCurrent.row());
}
-void QListWidgetPrivate::_q_sort()
+void QListWidgetPrivate::sort()
{
if (sortingEnabled)
model->sort(0, sortOrder);
}
-void QListWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight)
+void QListWidgetPrivate::dataChanged(const QModelIndex &topLeft,
+ const QModelIndex &bottomRight)
{
if (sortingEnabled && topLeft.isValid() && bottomRight.isValid())
listModel()->ensureSorted(topLeft.column(), sortOrder,
@@ -1407,6 +1378,8 @@ QListWidget::QListWidget(QWidget *parent)
QListWidget::~QListWidget()
{
+ Q_D(QListWidget);
+ d->clearConnections();
}
/*!
@@ -1417,20 +1390,18 @@ void QListWidget::setSelectionModel(QItemSelectionModel *selectionModel)
{
Q_D(QListWidget);
- if (d->selectionModel) {
- QObject::disconnect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_emitCurrentItemChanged(QModelIndex,QModelIndex)));
- QObject::disconnect(d->selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SIGNAL(itemSelectionChanged()));
- }
+ for (const QMetaObject::Connection &connection : d->selectionModelConnections)
+ disconnect(connection);
QListView::setSelectionModel(selectionModel);
if (d->selectionModel) {
- QObject::connect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_emitCurrentItemChanged(QModelIndex,QModelIndex)));
- QObject::connect(d->selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SIGNAL(itemSelectionChanged()));
+ d->selectionModelConnections = {
+ QObjectPrivate::connect(d->selectionModel, &QItemSelectionModel::currentChanged,
+ d, &QListWidgetPrivate::emitCurrentItemChanged),
+ QObject::connect(d->selectionModel, &QItemSelectionModel::selectionChanged,
+ this, &QListWidget::itemSelectionChanged)
+ };
}
}
diff --git a/src/widgets/itemviews/qlistwidget.h b/src/widgets/itemviews/qlistwidget.h
index 516553b71b..c6ba714c43 100644
--- a/src/widgets/itemviews/qlistwidget.h
+++ b/src/widgets/itemviews/qlistwidget.h
@@ -258,16 +258,6 @@ private:
Q_DECLARE_PRIVATE(QListWidget)
Q_DISABLE_COPY(QListWidget)
-
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemPressed(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemDoubleClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemActivated(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemEntered(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current))
- Q_PRIVATE_SLOT(d_func(), void _q_sort())
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight))
};
inline void QListWidget::removeItemWidget(QListWidgetItem *aItem)
diff --git a/src/widgets/itemviews/qlistwidget_p.h b/src/widgets/itemviews/qlistwidget_p.h
index edcacf0436..1007542ddc 100644
--- a/src/widgets/itemviews/qlistwidget_p.h
+++ b/src/widgets/itemviews/qlistwidget_p.h
@@ -18,10 +18,11 @@
#include <QtCore/qabstractitemmodel.h>
#include <QtWidgets/qabstractitemview.h>
#include <QtWidgets/qlistwidget.h>
-#include <qitemdelegate.h>
#include <private/qlistview_p.h>
#include <private/qwidgetitemdata_p.h>
+#include <array>
+
QT_REQUIRE_CONFIG(listwidget);
QT_BEGIN_NAMESPACE
@@ -113,17 +114,21 @@ public:
QListWidgetPrivate() : QListViewPrivate(), sortOrder(Qt::AscendingOrder), sortingEnabled(false) {}
inline QListModel *listModel() const { return qobject_cast<QListModel*>(model); }
void setup();
- void _q_emitItemPressed(const QModelIndex &index);
- void _q_emitItemClicked(const QModelIndex &index);
- void _q_emitItemDoubleClicked(const QModelIndex &index);
- void _q_emitItemActivated(const QModelIndex &index);
- void _q_emitItemEntered(const QModelIndex &index);
- void _q_emitItemChanged(const QModelIndex &index);
- void _q_emitCurrentItemChanged(const QModelIndex &current, const QModelIndex &previous);
- void _q_sort();
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+ void clearConnections();
+ void emitItemPressed(const QModelIndex &index);
+ void emitItemClicked(const QModelIndex &index);
+ void emitItemDoubleClicked(const QModelIndex &index);
+ void emitItemActivated(const QModelIndex &index);
+ void emitItemEntered(const QModelIndex &index);
+ void emitItemChanged(const QModelIndex &index);
+ void emitCurrentItemChanged(const QModelIndex &current, const QModelIndex &previous);
+ void sort();
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
Qt::SortOrder sortOrder;
bool sortingEnabled;
+
+ std::array<QMetaObject::Connection, 8> connections;
+ std::array<QMetaObject::Connection, 2> selectionModelConnections;
};
class QListWidgetItemPrivate
diff --git a/src/widgets/itemviews/qstyleditemdelegate.cpp b/src/widgets/itemviews/qstyleditemdelegate.cpp
index 7442fc58c8..54c1fb4f52 100644
--- a/src/widgets/itemviews/qstyleditemdelegate.cpp
+++ b/src/widgets/itemviews/qstyleditemdelegate.cpp
@@ -137,12 +137,17 @@ public:
instance provided by QItemEditorFactory is installed on all item
delegates. You can set a custom factory using
setItemEditorFactory() or set a new default factory with
- QItemEditorFactory::setDefaultFactory(). It is the data stored in
- the item model with the \l{Qt::}{EditRole} that is edited. See the
- QItemEditorFactory class for a more high-level introduction to
- item editor factories. The \l{Color Editor Factory Example}{Color
- Editor Factory} example shows how to create custom editors with a
- factory.
+ QItemEditorFactory::setDefaultFactory().
+
+ \snippet code/src_gui_itemviews_qitemeditorfactory.cpp setDefaultFactory
+
+ After the new factory has been set, all standard item delegates
+ will use it (i.e, also delegates that were created before the new
+ default factory was set).
+
+ It is the data stored in the item model with the \l{Qt::}{EditRole}
+ that is edited. See the QItemEditorFactory class for a more
+ high-level introduction to item editor factories.
\section1 Subclassing QStyledItemDelegate
@@ -204,8 +209,7 @@ public:
documentation for details.
\sa {Delegate Classes}, QItemDelegate, QAbstractItemDelegate, QStyle,
- {Spin Box Delegate Example}, {Star Delegate Example}, {Color
- Editor Factory Example}
+ {Star Delegate Example}
*/
@@ -285,6 +289,10 @@ void QStyledItemDelegate::initStyleOption(QStyleOptionViewItem *option,
switch (value->userType()) {
case QMetaType::QIcon: {
option->icon = qvariant_cast<QIcon>(*value);
+ if (option->icon.isNull()) {
+ option->features &= ~QStyleOptionViewItem::HasDecoration;
+ break;
+ }
QIcon::Mode mode;
if (!(option->state & QStyle::State_Enabled))
mode = QIcon::Disabled;
@@ -473,15 +481,7 @@ void QStyledItemDelegate::updateEditorGeometry(QWidget *editor,
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
- // let the editor take up all available space
- //if the editor is not a QLineEdit
- //or it is in a QTableView
-#if QT_CONFIG(tableview) && QT_CONFIG(lineedit)
- if (qobject_cast<QExpandingLineEdit*>(editor) && !qobject_cast<const QTableView*>(widget))
- opt.showDecorationSelected = editor->style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, nullptr, editor);
- else
-#endif
- opt.showDecorationSelected = true;
+ opt.showDecorationSelected = editor->style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, nullptr, editor);
QStyle *style = widget ? widget->style() : QApplication::style();
QRect geom = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);
diff --git a/src/widgets/itemviews/qtableview.cpp b/src/widgets/itemviews/qtableview.cpp
index cfde93a477..5726348bc5 100644
--- a/src/widgets/itemviews/qtableview.cpp
+++ b/src/widgets/itemviews/qtableview.cpp
@@ -4,7 +4,7 @@
#include "qtableview.h"
#include <qheaderview.h>
-#include <qitemdelegate.h>
+#include <qabstractitemdelegate.h>
#include <qapplication.h>
#include <qpainter.h>
#include <qstyle.h>
@@ -170,6 +170,13 @@ QDebug operator<<(QDebug str, const QSpanCollection::Span &span)
str << '(' << span.top() << ',' << span.left() << ',' << span.bottom() << ',' << span.right() << ')';
return str;
}
+
+QDebug operator<<(QDebug debug, const QSpanCollection::SpanList &spans)
+{
+ for (const auto *span : spans)
+ debug << span << *span;
+ return debug;
+}
#endif
/** \internal
@@ -200,8 +207,7 @@ void QSpanCollection::updateInsertedRows(int start, int end)
#ifdef DEBUG_SPAN_UPDATE
qDebug("After");
- foreach (QSpanCollection::Span *span, spans)
- qDebug() << span << *span;
+ qDebug() << spans;
#endif
for (Index::iterator it_y = index.begin(); it_y != index.end(); ) {
@@ -247,8 +253,7 @@ void QSpanCollection::updateInsertedColumns(int start, int end)
#ifdef DEBUG_SPAN_UPDATE
qDebug("After");
- foreach (QSpanCollection::Span *span, spans)
- qDebug() << span << *span;
+ qDebug() << spans;
#endif
for (Index::iterator it_y = index.begin(); it_y != index.end(); ++it_y) {
@@ -352,8 +357,7 @@ void QSpanCollection::updateRemovedRows(int start, int end)
#ifdef DEBUG_SPAN_UPDATE
qDebug("After");
- foreach (QSpanCollection::Span *span, spans)
- qDebug() << span << *span;
+ qDebug() << spans;
#endif
if (spans.empty()) {
qDeleteAll(spansToBeDeleted);
@@ -420,8 +424,7 @@ void QSpanCollection::updateRemovedRows(int start, int end)
#ifdef DEBUG_SPAN_UPDATE
qDebug() << index;
qDebug("Deleted");
- foreach (QSpanCollection::Span *span, spansToBeDeleted)
- qDebug() << span << *span;
+ qDebug() << spansToBeDeleted;
#endif
qDeleteAll(spansToBeDeleted);
}
@@ -479,8 +482,7 @@ void QSpanCollection::updateRemovedColumns(int start, int end)
#ifdef DEBUG_SPAN_UPDATE
qDebug("After");
- foreach (QSpanCollection::Span *span, spans)
- qDebug() << span << *span;
+ qDebug() << spans;
#endif
if (spans.empty()) {
qDeleteAll(toBeDeleted);
@@ -499,8 +501,7 @@ void QSpanCollection::updateRemovedColumns(int start, int end)
#ifdef DEBUG_SPAN_UPDATE
qDebug() << index;
qDebug("Deleted");
- foreach (QSpanCollection::Span *span, toBeDeleted)
- qDebug() << span << *span;
+ qDebug() << toBeDeleted;
#endif
qDeleteAll(toBeDeleted);
}
@@ -592,7 +593,25 @@ void QTableViewPrivate::init()
#if QT_CONFIG(abstractbutton)
cornerWidget = new QTableCornerButton(q);
cornerWidget->setFocusPolicy(Qt::NoFocus);
- QObject::connect(cornerWidget, SIGNAL(clicked()), q, SLOT(selectAll()));
+ cornerWidgetConnection = QObject::connect(
+ cornerWidget, &QTableCornerButton::clicked,
+ q, &QTableView::selectAll);
+#endif
+}
+
+void QTableViewPrivate::clearConnections()
+{
+ for (const QMetaObject::Connection &connection : modelConnections)
+ QObject::disconnect(connection);
+ for (const QMetaObject::Connection &connection : verHeaderConnections)
+ QObject::disconnect(connection);
+ for (const QMetaObject::Connection &connection : horHeaderConnections)
+ QObject::disconnect(connection);
+ for (const QMetaObject::Connection &connection : dynHorHeaderConnections)
+ QObject::disconnect(connection);
+ QObject::disconnect(selectionmodelConnection);
+#if QT_CONFIG(abstractbutton)
+ QObject::disconnect(cornerWidgetConnection);
#endif
}
@@ -956,7 +975,7 @@ void QTableViewPrivate::drawAndClipSpans(const QRegion &area, QPainter *painter,
\internal
Updates spans after row insertion.
*/
-void QTableViewPrivate::_q_updateSpanInsertedRows(const QModelIndex &parent, int start, int end)
+void QTableViewPrivate::updateSpanInsertedRows(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent);
spans.updateInsertedRows(start, end);
@@ -966,7 +985,7 @@ void QTableViewPrivate::_q_updateSpanInsertedRows(const QModelIndex &parent, int
\internal
Updates spans after column insertion.
*/
-void QTableViewPrivate::_q_updateSpanInsertedColumns(const QModelIndex &parent, int start, int end)
+void QTableViewPrivate::updateSpanInsertedColumns(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent);
spans.updateInsertedColumns(start, end);
@@ -976,7 +995,7 @@ void QTableViewPrivate::_q_updateSpanInsertedColumns(const QModelIndex &parent,
\internal
Updates spans after row removal.
*/
-void QTableViewPrivate::_q_updateSpanRemovedRows(const QModelIndex &parent, int start, int end)
+void QTableViewPrivate::updateSpanRemovedRows(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent);
spans.updateRemovedRows(start, end);
@@ -986,7 +1005,7 @@ void QTableViewPrivate::_q_updateSpanRemovedRows(const QModelIndex &parent, int
\internal
Updates spans after column removal.
*/
-void QTableViewPrivate::_q_updateSpanRemovedColumns(const QModelIndex &parent, int start, int end)
+void QTableViewPrivate::updateSpanRemovedColumns(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent);
spans.updateRemovedColumns(start, end);
@@ -996,7 +1015,7 @@ void QTableViewPrivate::_q_updateSpanRemovedColumns(const QModelIndex &parent, i
\internal
Sort the model when the header sort indicator changed
*/
-void QTableViewPrivate::_q_sortIndicatorChanged(int column, Qt::SortOrder order)
+void QTableViewPrivate::sortIndicatorChanged(int column, Qt::SortOrder order)
{
model->sort(column, order);
}
@@ -1188,7 +1207,7 @@ int QTableViewPrivate::heightHintForIndex(const QModelIndex &index, int hint, QS
operations between x-coordinates and column indexes.
\sa QTableWidget, {View Classes}, QAbstractItemModel, QAbstractItemView,
- {Chart Example}, {Pixelator Example}, {Table Model Example}
+ {Table Model Example}
*/
/*!
@@ -1219,6 +1238,8 @@ QTableView::QTableView(QTableViewPrivate &dd, QWidget *parent)
*/
QTableView::~QTableView()
{
+ Q_D(QTableView);
+ d->clearConnections();
}
/*!
@@ -1242,28 +1263,23 @@ void QTableView::setModel(QAbstractItemModel *model)
return;
//let's disconnect from the old model
if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanInsertedRows(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanInsertedColumns(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanRemovedRows(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanRemovedColumns(QModelIndex,int,int)));
+ for (const QMetaObject::Connection &connection : d->modelConnections)
+ disconnect(connection);
}
if (d->selectionModel) { // support row editing
- disconnect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
+ disconnect(d->selectionmodelConnection);
}
if (model) { //and connect to the new one
- connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanInsertedRows(QModelIndex,int,int)));
- connect(model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanInsertedColumns(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanRemovedRows(QModelIndex,int,int)));
- connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanRemovedColumns(QModelIndex,int,int)));
+ d->modelConnections = {
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsInserted,
+ d, &QTableViewPrivate::updateSpanInsertedRows),
+ QObjectPrivate::connect(model, &QAbstractItemModel::columnsInserted,
+ d, &QTableViewPrivate::updateSpanInsertedColumns),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsRemoved,
+ d, &QTableViewPrivate::updateSpanRemovedRows),
+ QObjectPrivate::connect(model, &QAbstractItemModel::columnsRemoved,
+ d, &QTableViewPrivate::updateSpanRemovedColumns)
+ };
}
d->verticalHeader->setModel(model);
d->horizontalHeader->setModel(model);
@@ -1305,8 +1321,7 @@ void QTableView::setSelectionModel(QItemSelectionModel *selectionModel)
Q_ASSERT(selectionModel);
if (d->selectionModel) {
// support row editing
- disconnect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
+ disconnect(d->selectionmodelConnection);
}
d->verticalHeader->setSelectionModel(selectionModel);
@@ -1315,8 +1330,9 @@ void QTableView::setSelectionModel(QItemSelectionModel *selectionModel)
if (d->selectionModel) {
// support row editing
- connect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
+ d->selectionmodelConnection =
+ connect(d->selectionModel, &QItemSelectionModel::currentRowChanged,
+ d->model, &QAbstractItemModel::submit);
}
}
@@ -1353,6 +1369,8 @@ void QTableView::setHorizontalHeader(QHeaderView *header)
if (!header || header == d->horizontalHeader)
return;
+ for (const QMetaObject::Connection &connection : d->horHeaderConnections)
+ disconnect(connection);
if (d->horizontalHeader && d->horizontalHeader->parent() == this)
delete d->horizontalHeader;
d->horizontalHeader = header;
@@ -1364,18 +1382,18 @@ void QTableView::setHorizontalHeader(QHeaderView *header)
d->horizontalHeader->setSelectionModel(d->selectionModel);
}
- connect(d->horizontalHeader,SIGNAL(sectionResized(int,int,int)),
- this, SLOT(columnResized(int,int,int)));
- connect(d->horizontalHeader, SIGNAL(sectionMoved(int,int,int)),
- this, SLOT(columnMoved(int,int,int)));
- connect(d->horizontalHeader, SIGNAL(sectionCountChanged(int,int)),
- this, SLOT(columnCountChanged(int,int)));
- connect(d->horizontalHeader, SIGNAL(sectionPressed(int)), this, SLOT(selectColumn(int)));
- connect(d->horizontalHeader, SIGNAL(sectionEntered(int)), this, SLOT(_q_selectColumn(int)));
- connect(d->horizontalHeader, SIGNAL(sectionHandleDoubleClicked(int)),
- this, SLOT(resizeColumnToContents(int)));
- connect(d->horizontalHeader, SIGNAL(geometriesChanged()), this, SLOT(updateGeometries()));
-
+ d->horHeaderConnections = {
+ connect(d->horizontalHeader,&QHeaderView::sectionResized,
+ this, &QTableView::columnResized),
+ connect(d->horizontalHeader, &QHeaderView::sectionMoved,
+ this, &QTableView::columnMoved),
+ connect(d->horizontalHeader, &QHeaderView::sectionCountChanged,
+ this, &QTableView::columnCountChanged),
+ connect(d->horizontalHeader, &QHeaderView::sectionHandleDoubleClicked,
+ this, &QTableView::resizeColumnToContents),
+ connect(d->horizontalHeader, &QHeaderView::geometriesChanged,
+ this, &QTableView::updateGeometries),
+ };
//update the sorting enabled states on the new header
setSortingEnabled(d->sortingEnabled);
}
@@ -1391,6 +1409,8 @@ void QTableView::setVerticalHeader(QHeaderView *header)
if (!header || header == d->verticalHeader)
return;
+ for (const QMetaObject::Connection &connection : d->verHeaderConnections)
+ disconnect(connection);
if (d->verticalHeader && d->verticalHeader->parent() == this)
delete d->verticalHeader;
d->verticalHeader = header;
@@ -1402,17 +1422,22 @@ void QTableView::setVerticalHeader(QHeaderView *header)
d->verticalHeader->setSelectionModel(d->selectionModel);
}
- connect(d->verticalHeader, SIGNAL(sectionResized(int,int,int)),
- this, SLOT(rowResized(int,int,int)));
- connect(d->verticalHeader, SIGNAL(sectionMoved(int,int,int)),
- this, SLOT(rowMoved(int,int,int)));
- connect(d->verticalHeader, SIGNAL(sectionCountChanged(int,int)),
- this, SLOT(rowCountChanged(int,int)));
- connect(d->verticalHeader, SIGNAL(sectionPressed(int)), this, SLOT(selectRow(int)));
- connect(d->verticalHeader, SIGNAL(sectionEntered(int)), this, SLOT(_q_selectRow(int)));
- connect(d->verticalHeader, SIGNAL(sectionHandleDoubleClicked(int)),
- this, SLOT(resizeRowToContents(int)));
- connect(d->verticalHeader, SIGNAL(geometriesChanged()), this, SLOT(updateGeometries()));
+ d->verHeaderConnections = {
+ connect(d->verticalHeader, &QHeaderView::sectionResized,
+ this, &QTableView::rowResized),
+ connect(d->verticalHeader, &QHeaderView::sectionMoved,
+ this, &QTableView::rowMoved),
+ connect(d->verticalHeader, &QHeaderView::sectionCountChanged,
+ this, &QTableView::rowCountChanged),
+ connect(d->verticalHeader, &QHeaderView::sectionPressed,
+ this, &QTableView::selectRow),
+ connect(d->verticalHeader, &QHeaderView::sectionHandleDoubleClicked,
+ this, &QTableView::resizeRowToContents),
+ connect(d->verticalHeader, &QHeaderView::geometriesChanged,
+ this, &QTableView::updateGeometries),
+ connect(d->verticalHeader, &QHeaderView::sectionEntered,
+ this, [d](int row) { d->selectRow(row, false); })
+ };
}
/*!
@@ -2407,12 +2432,12 @@ int QTableView::sizeHintForRow(int row) const
break;
}
- int actualRight = d->model->columnCount(d->root) - 1;
+ const int actualRight = d->model->columnCount(d->root) - 1;
int idxLeft = left;
int idxRight = column - 1;
- if (maximumProcessCols == 0)
- columnsProcessed = 0; // skip the while loop
+ if (maximumProcessCols == 0 || actualRight < idxLeft)
+ columnsProcessed = maximumProcessCols; // skip the while loop
while (columnsProcessed != maximumProcessCols && (idxLeft > 0 || idxRight < actualRight)) {
int logicalIdx = -1;
@@ -2436,11 +2461,10 @@ int QTableView::sizeHintForRow(int row) const
break;
}
}
- if (logicalIdx < 0)
- continue;
-
- index = d->model->index(row, logicalIdx, d->root);
- hint = d->heightHintForIndex(index, hint, option);
+ if (logicalIdx >= 0) {
+ index = d->model->index(row, logicalIdx, d->root);
+ hint = d->heightHintForIndex(index, hint, option);
+ }
++columnsProcessed;
}
@@ -2496,12 +2520,12 @@ int QTableView::sizeHintForColumn(int column) const
break;
}
- int actualBottom = d->model->rowCount(d->root) - 1;
+ const int actualBottom = d->model->rowCount(d->root) - 1;
int idxTop = top;
int idxBottom = row - 1;
- if (maximumProcessRows == 0)
- rowsProcessed = 0; // skip the while loop
+ if (maximumProcessRows == 0 || actualBottom < idxTop)
+ rowsProcessed = maximumProcessRows; // skip the while loop
while (rowsProcessed != maximumProcessRows && (idxTop > 0 || idxBottom < actualBottom)) {
int logicalIdx = -1;
@@ -2525,11 +2549,10 @@ int QTableView::sizeHintForColumn(int column) const
break;
}
}
- if (logicalIdx < 0)
- continue;
-
- index = d->model->index(logicalIdx, column, d->root);
- hint = d->widthHintForIndex(index, hint, option);
+ if (logicalIdx >= 0) {
+ index = d->model->index(logicalIdx, column, d->root);
+ hint = d->widthHintForIndex(index, hint, option);
+ }
++rowsProcessed;
}
@@ -2704,24 +2727,25 @@ void QTableView::setSortingEnabled(bool enable)
{
Q_D(QTableView);
horizontalHeader()->setSortIndicatorShown(enable);
+ for (const QMetaObject::Connection &connection : d->dynHorHeaderConnections)
+ disconnect(connection);
+ d->dynHorHeaderConnections.clear();
if (enable) {
- disconnect(d->horizontalHeader, SIGNAL(sectionEntered(int)),
- this, SLOT(_q_selectColumn(int)));
- disconnect(horizontalHeader(), SIGNAL(sectionPressed(int)),
- this, SLOT(selectColumn(int)));
//sortByColumn has to be called before we connect or set the sortingEnabled flag
// because otherwise it will not call sort on the model.
- sortByColumn(horizontalHeader()->sortIndicatorSection(),
- horizontalHeader()->sortIndicatorOrder());
- connect(horizontalHeader(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
- this, SLOT(_q_sortIndicatorChanged(int,Qt::SortOrder)), Qt::UniqueConnection);
+ sortByColumn(d->horizontalHeader->sortIndicatorSection(),
+ d->horizontalHeader->sortIndicatorOrder());
+ d->dynHorHeaderConnections = {
+ QObjectPrivate::connect(d->horizontalHeader, &QHeaderView::sortIndicatorChanged,
+ d, &QTableViewPrivate::sortIndicatorChanged)
+ };
} else {
- connect(d->horizontalHeader, SIGNAL(sectionEntered(int)),
- this, SLOT(_q_selectColumn(int)), Qt::UniqueConnection);
- connect(horizontalHeader(), SIGNAL(sectionPressed(int)),
- this, SLOT(selectColumn(int)), Qt::UniqueConnection);
- disconnect(horizontalHeader(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
- this, SLOT(_q_sortIndicatorChanged(int,Qt::SortOrder)));
+ d->dynHorHeaderConnections = {
+ connect(d->horizontalHeader, &QHeaderView::sectionPressed,
+ this, &QTableView::selectColumn),
+ connect(d->horizontalHeader, &QHeaderView::sectionEntered,
+ this, [d](int column) {d->selectColumn(column, false); })
+ };
}
d->sortingEnabled = enable;
}
@@ -3381,16 +3405,6 @@ void QTableView::clearSpans()
d->viewport->update();
}
-void QTableViewPrivate::_q_selectRow(int row)
-{
- selectRow(row, false);
-}
-
-void QTableViewPrivate::_q_selectColumn(int column)
-{
- selectColumn(column, false);
-}
-
void QTableViewPrivate::selectRow(int row, bool anchor)
{
Q_Q(QTableView);
@@ -3478,7 +3492,7 @@ void QTableView::currentChanged(const QModelIndex &current, const QModelIndex &p
{
#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
- if (current.isValid()) {
+ if (current.isValid() && hasFocus()) {
Q_D(QTableView);
int entry = d->accessibleTable2Index(current);
QAccessibleEvent event(this, QAccessible::Focus);
diff --git a/src/widgets/itemviews/qtableview.h b/src/widgets/itemviews/qtableview.h
index 955b29995c..eff0ea3502 100644
--- a/src/widgets/itemviews/qtableview.h
+++ b/src/widgets/itemviews/qtableview.h
@@ -145,13 +145,6 @@ private:
Q_DECLARE_PRIVATE(QTableView)
Q_DISABLE_COPY(QTableView)
- Q_PRIVATE_SLOT(d_func(), void _q_selectRow(int))
- Q_PRIVATE_SLOT(d_func(), void _q_selectColumn(int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSpanInsertedRows(QModelIndex,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSpanInsertedColumns(QModelIndex,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSpanRemovedRows(QModelIndex,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSpanRemovedColumns(QModelIndex,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_sortIndicatorChanged(int column, Qt::SortOrder order))
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qtableview_p.h b/src/widgets/itemviews/qtableview_p.h
index 582330c7b5..862a016d5f 100644
--- a/src/widgets/itemviews/qtableview_p.h
+++ b/src/widgets/itemviews/qtableview_p.h
@@ -16,13 +16,18 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "qtableview.h"
+#include "qheaderview.h"
+
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QSet>
#include <QtCore/QDebug>
#include "private/qabstractitemview_p.h"
+#include <array>
#include <list>
+#include <vector>
QT_REQUIRE_CONFIG(tableview);
@@ -93,7 +98,9 @@ private:
Q_DECLARE_TYPEINFO ( QSpanCollection::Span, Q_RELOCATABLE_TYPE);
-
+#if QT_CONFIG(abstractbutton)
+class QTableCornerButton;
+#endif
class Q_AUTOTEST_EXPORT QTableViewPrivate : public QAbstractItemViewPrivate
{
Q_DECLARE_PUBLIC(QTableView)
@@ -111,6 +118,7 @@ public:
#endif
}
void init();
+ void clearConnections();
void trimHiddenSelections(QItemSelectionRange *range) const;
QRect intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const override;
@@ -156,8 +164,15 @@ public:
QHeaderView *horizontalHeader;
QHeaderView *verticalHeader;
#if QT_CONFIG(abstractbutton)
- QWidget *cornerWidget;
+ QTableCornerButton *cornerWidget;
+ QMetaObject::Connection cornerWidgetConnection;
#endif
+ QMetaObject::Connection selectionmodelConnection;
+ std::array<QMetaObject::Connection, 4> modelConnections;
+ std::array<QMetaObject::Connection, 7> verHeaderConnections;
+ std::array<QMetaObject::Connection, 5> horHeaderConnections;
+ std::vector<QMetaObject::Connection> dynHorHeaderConnections;
+
bool sortingEnabled;
bool geometryRecursionBlock;
QPoint visualCursor; // (Row,column) cell coordinates to track through span navigation.
@@ -210,17 +225,14 @@ public:
QRect visualSpanRect(const QSpanCollection::Span &span) const;
- void _q_selectRow(int row);
- void _q_selectColumn(int column);
-
void selectRow(int row, bool anchor);
void selectColumn(int column, bool anchor);
- void _q_updateSpanInsertedRows(const QModelIndex &parent, int start, int end);
- void _q_updateSpanInsertedColumns(const QModelIndex &parent, int start, int end);
- void _q_updateSpanRemovedRows(const QModelIndex &parent, int start, int end);
- void _q_updateSpanRemovedColumns(const QModelIndex &parent, int start, int end);
- void _q_sortIndicatorChanged(int column, Qt::SortOrder order);
+ void updateSpanInsertedRows(const QModelIndex &parent, int start, int end);
+ void updateSpanInsertedColumns(const QModelIndex &parent, int start, int end);
+ void updateSpanRemovedRows(const QModelIndex &parent, int start, int end);
+ void updateSpanRemovedColumns(const QModelIndex &parent, int start, int end);
+ void sortIndicatorChanged(int column, Qt::SortOrder order);
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qtablewidget.cpp b/src/widgets/itemviews/qtablewidget.cpp
index 67886be94f..6dd812f6fb 100644
--- a/src/widgets/itemviews/qtablewidget.cpp
+++ b/src/widgets/itemviews/qtablewidget.cpp
@@ -3,7 +3,6 @@
#include "qtablewidget.h"
-#include <qitemdelegate.h>
#include <qpainter.h>
#include <private/qtablewidget_p.h>
@@ -248,7 +247,7 @@ void QTableModel::setHorizontalHeaderItem(int section, QTableWidgetItem *item)
if (item) {
item->view = view;
- item->itemFlags = Qt::ItemFlags(int(item->itemFlags)|ItemIsHeaderItem);
+ item->d->headerItem = true;
}
horizontalHeaderItems[section] = item;
emit headerDataChanged(Qt::Horizontal, section, section);
@@ -270,7 +269,7 @@ void QTableModel::setVerticalHeaderItem(int section, QTableWidgetItem *item)
if (item) {
item->view = view;
- item->itemFlags = Qt::ItemFlags(int(item->itemFlags)|ItemIsHeaderItem);
+ item->d->headerItem = true;
}
verticalHeaderItems[section] = item;
emit headerDataChanged(Qt::Vertical, section, section);
@@ -283,7 +282,7 @@ QTableWidgetItem *QTableModel::takeHorizontalHeaderItem(int section)
QTableWidgetItem *itm = horizontalHeaderItems.at(section);
if (itm) {
itm->view = nullptr;
- itm->itemFlags &= ~ItemIsHeaderItem;
+ itm->d->headerItem = false;
horizontalHeaderItems[section] = 0;
}
return itm;
@@ -296,7 +295,7 @@ QTableWidgetItem *QTableModel::takeVerticalHeaderItem(int section)
QTableWidgetItem *itm = verticalHeaderItems.at(section);
if (itm) {
itm->view = nullptr;
- itm->itemFlags &= ~ItemIsHeaderItem;
+ itm->d->headerItem = false;
verticalHeaderItems[section] = 0;
}
return itm;
@@ -761,7 +760,7 @@ void QTableModel::itemChanged(QTableWidgetItem *item, const QList<int> &roles)
{
if (!item)
return;
- if (item->flags() & ItemIsHeaderItem) {
+ if (item->d->headerItem) {
int row = verticalHeaderItems.indexOf(item);
if (row >= 0) {
emit headerDataChanged(Qt::Vertical, row, row);
@@ -1592,28 +1591,41 @@ QTableWidgetItem &QTableWidgetItem::operator=(const QTableWidgetItem &other)
void QTableWidgetPrivate::setup()
{
Q_Q(QTableWidget);
- // view signals
- QObject::connect(q, SIGNAL(pressed(QModelIndex)), q, SLOT(_q_emitItemPressed(QModelIndex)));
- QObject::connect(q, SIGNAL(clicked(QModelIndex)), q, SLOT(_q_emitItemClicked(QModelIndex)));
- QObject::connect(q, SIGNAL(doubleClicked(QModelIndex)),
- q, SLOT(_q_emitItemDoubleClicked(QModelIndex)));
- QObject::connect(q, SIGNAL(activated(QModelIndex)), q, SLOT(_q_emitItemActivated(QModelIndex)));
- QObject::connect(q, SIGNAL(entered(QModelIndex)), q, SLOT(_q_emitItemEntered(QModelIndex)));
- // model signals
- QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitItemChanged(QModelIndex)));
- // selection signals
- QObject::connect(q->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitCurrentItemChanged(QModelIndex,QModelIndex)));
- QObject::connect(q->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- q, SIGNAL(itemSelectionChanged()));
- // sorting
- QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)), q, SLOT(_q_sort()));
-}
-
-void QTableWidgetPrivate::_q_emitItemPressed(const QModelIndex &index)
+ connections = {
+ // view signals
+ QObjectPrivate::connect(q, &QTableWidget::pressed,
+ this, &QTableWidgetPrivate::emitItemPressed),
+ QObjectPrivate::connect(q, &QTableWidget::clicked,
+ this, &QTableWidgetPrivate::emitItemClicked),
+ QObjectPrivate::connect(q, &QTableWidget::doubleClicked,
+ this, &QTableWidgetPrivate::emitItemDoubleClicked),
+ QObjectPrivate::connect(q, &QTableWidget::activated,
+ this, &QTableWidgetPrivate::emitItemActivated),
+ QObjectPrivate::connect(q, &QTableWidget::entered,
+ this, &QTableWidgetPrivate::emitItemEntered),
+ // model signals
+ QObjectPrivate::connect(model, &QAbstractItemModel::dataChanged,
+ this, &QTableWidgetPrivate::emitItemChanged),
+ // selection signals
+ QObjectPrivate::connect(q->selectionModel(), &QItemSelectionModel::currentChanged,
+ this, &QTableWidgetPrivate::emitCurrentItemChanged),
+ QObject::connect(q->selectionModel(), &QItemSelectionModel::selectionChanged,
+ q, &QTableWidget::itemSelectionChanged),
+ // sorting
+ QObjectPrivate::connect(model, &QAbstractItemModel::dataChanged,
+ this, &QTableWidgetPrivate::dataChanged),
+ QObjectPrivate::connect(model, &QAbstractItemModel::columnsRemoved,
+ this, &QTableWidgetPrivate::sort)
+ };
+}
+
+void QTableWidgetPrivate::clearConnections()
+{
+ for (const QMetaObject::Connection &connection : connections)
+ QObject::disconnect(connection);
+}
+
+void QTableWidgetPrivate::emitItemPressed(const QModelIndex &index)
{
Q_Q(QTableWidget);
if (QTableWidgetItem *item = tableModel()->item(index))
@@ -1621,7 +1633,7 @@ void QTableWidgetPrivate::_q_emitItemPressed(const QModelIndex &index)
emit q->cellPressed(index.row(), index.column());
}
-void QTableWidgetPrivate::_q_emitItemClicked(const QModelIndex &index)
+void QTableWidgetPrivate::emitItemClicked(const QModelIndex &index)
{
Q_Q(QTableWidget);
if (QTableWidgetItem *item = tableModel()->item(index))
@@ -1629,7 +1641,7 @@ void QTableWidgetPrivate::_q_emitItemClicked(const QModelIndex &index)
emit q->cellClicked(index.row(), index.column());
}
-void QTableWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index)
+void QTableWidgetPrivate::emitItemDoubleClicked(const QModelIndex &index)
{
Q_Q(QTableWidget);
if (QTableWidgetItem *item = tableModel()->item(index))
@@ -1637,7 +1649,7 @@ void QTableWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index)
emit q->cellDoubleClicked(index.row(), index.column());
}
-void QTableWidgetPrivate::_q_emitItemActivated(const QModelIndex &index)
+void QTableWidgetPrivate::emitItemActivated(const QModelIndex &index)
{
Q_Q(QTableWidget);
if (QTableWidgetItem *item = tableModel()->item(index))
@@ -1645,7 +1657,7 @@ void QTableWidgetPrivate::_q_emitItemActivated(const QModelIndex &index)
emit q->cellActivated(index.row(), index.column());
}
-void QTableWidgetPrivate::_q_emitItemEntered(const QModelIndex &index)
+void QTableWidgetPrivate::emitItemEntered(const QModelIndex &index)
{
Q_Q(QTableWidget);
if (QTableWidgetItem *item = tableModel()->item(index))
@@ -1653,7 +1665,7 @@ void QTableWidgetPrivate::_q_emitItemEntered(const QModelIndex &index)
emit q->cellEntered(index.row(), index.column());
}
-void QTableWidgetPrivate::_q_emitItemChanged(const QModelIndex &index)
+void QTableWidgetPrivate::emitItemChanged(const QModelIndex &index)
{
Q_Q(QTableWidget);
if (QTableWidgetItem *item = tableModel()->item(index))
@@ -1661,7 +1673,7 @@ void QTableWidgetPrivate::_q_emitItemChanged(const QModelIndex &index)
emit q->cellChanged(index.row(), index.column());
}
-void QTableWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
+void QTableWidgetPrivate::emitCurrentItemChanged(const QModelIndex &current,
const QModelIndex &previous)
{
Q_Q(QTableWidget);
@@ -1672,7 +1684,7 @@ void QTableWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
emit q->currentCellChanged(current.row(), current.column(), previous.row(), previous.column());
}
-void QTableWidgetPrivate::_q_sort()
+void QTableWidgetPrivate::sort()
{
if (sortingEnabled) {
int column = horizontalHeader->sortIndicatorSection();
@@ -1681,8 +1693,8 @@ void QTableWidgetPrivate::_q_sort()
}
}
-void QTableWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight)
+void QTableWidgetPrivate::dataChanged(const QModelIndex &topLeft,
+ const QModelIndex &bottomRight)
{
if (sortingEnabled && topLeft.isValid() && bottomRight.isValid()) {
int column = horizontalHeader->sortIndicatorSection();
@@ -1880,6 +1892,8 @@ QTableWidget::QTableWidget(int rows, int columns, QWidget *parent)
*/
QTableWidget::~QTableWidget()
{
+ Q_D(QTableWidget);
+ d->clearConnections();
}
/*!
diff --git a/src/widgets/itemviews/qtablewidget.h b/src/widgets/itemviews/qtablewidget.h
index c7545f13dd..303f4d5f5b 100644
--- a/src/widgets/itemviews/qtablewidget.h
+++ b/src/widgets/itemviews/qtablewidget.h
@@ -23,8 +23,10 @@ public:
friend bool operator==(const QTableWidgetSelectionRange &lhs,
const QTableWidgetSelectionRange &rhs) noexcept
- { return lhs.m_top == rhs.m_top && lhs.m_left == rhs.m_left
- && lhs.m_bottom == rhs.m_bottom && lhs.m_right == rhs.m_right; };
+ {
+ return lhs.m_top == rhs.m_top && lhs.m_left == rhs.m_left && lhs.m_bottom == rhs.m_bottom
+ && lhs.m_right == rhs.m_right;
+ }
friend bool operator!=(const QTableWidgetSelectionRange &lhs,
const QTableWidgetSelectionRange &rhs) noexcept
{ return !(lhs == rhs); }
@@ -310,16 +312,6 @@ private:
Q_DECLARE_PRIVATE(QTableWidget)
Q_DISABLE_COPY(QTableWidget)
-
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemPressed(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemDoubleClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemActivated(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemEntered(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current))
- Q_PRIVATE_SLOT(d_func(), void _q_sort())
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight))
};
inline void QTableWidget::removeCellWidget(int arow, int acolumn)
diff --git a/src/widgets/itemviews/qtablewidget_p.h b/src/widgets/itemviews/qtablewidget_p.h
index 1d893224c0..210910fc52 100644
--- a/src/widgets/itemviews/qtablewidget_p.h
+++ b/src/widgets/itemviews/qtablewidget_p.h
@@ -22,6 +22,8 @@
#include <private/qtableview_p.h>
#include <private/qwidgetitemdata_p.h>
+#include <array>
+
QT_REQUIRE_CONFIG(tablewidget);
QT_BEGIN_NAMESPACE
@@ -53,10 +55,6 @@ class QTableModel : public QAbstractTableModel
friend class QTableWidget;
public:
- enum ItemFlagsExtension {
- ItemIsHeaderItem = 128
- }; // we need this to separate header items from other items
-
QTableModel(int rows, int columns, QTableWidget *parent);
~QTableModel();
@@ -154,28 +152,32 @@ public:
QTableWidgetPrivate() : QTableViewPrivate() {}
inline QTableModel *tableModel() const { return qobject_cast<QTableModel*>(model); }
void setup();
+ void clearConnections();
// view signals
- void _q_emitItemPressed(const QModelIndex &index);
- void _q_emitItemClicked(const QModelIndex &index);
- void _q_emitItemDoubleClicked(const QModelIndex &index);
- void _q_emitItemActivated(const QModelIndex &index);
- void _q_emitItemEntered(const QModelIndex &index);
+ void emitItemPressed(const QModelIndex &index);
+ void emitItemClicked(const QModelIndex &index);
+ void emitItemDoubleClicked(const QModelIndex &index);
+ void emitItemActivated(const QModelIndex &index);
+ void emitItemEntered(const QModelIndex &index);
// model signals
- void _q_emitItemChanged(const QModelIndex &index);
+ void emitItemChanged(const QModelIndex &index);
// selection signals
- void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current);
+ void emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current);
// sorting
- void _q_sort();
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+ void sort();
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+
+ std::array<QMetaObject::Connection, 10> connections;
};
class QTableWidgetItemPrivate
{
public:
- QTableWidgetItemPrivate(QTableWidgetItem *item) : q(item), id(-1) {}
+ QTableWidgetItemPrivate(QTableWidgetItem *item) : q(item), id(-1), headerItem(false) {}
QTableWidgetItem *q;
int id;
+ bool headerItem; // Qt 7 TODO: inline this stuff in the public class.
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qtreeview.cpp b/src/widgets/itemviews/qtreeview.cpp
index 065c42d6b7..744f29ca17 100644
--- a/src/widgets/itemviews/qtreeview.cpp
+++ b/src/widgets/itemviews/qtreeview.cpp
@@ -3,7 +3,7 @@
#include "qtreeview.h"
#include <qheaderview.h>
-#include <qitemdelegate.h>
+#include <qabstractitemdelegate.h>
#include <qapplication.h>
#include <qscrollbar.h>
#include <qpainter.h>
@@ -124,8 +124,7 @@ QT_BEGIN_NAMESPACE
that can be taken for views that are intended to display items with equal heights
is to set the \l uniformRowHeights property to true.
- \sa QListView, QTreeWidget, {View Classes}, QAbstractItemModel, QAbstractItemView,
- {Dir View Example}
+ \sa QListView, QTreeWidget, {View Classes}, QAbstractItemModel, QAbstractItemView
*/
@@ -170,6 +169,8 @@ QTreeView::QTreeView(QTreeViewPrivate &dd, QWidget *parent)
*/
QTreeView::~QTreeView()
{
+ Q_D(QTreeView);
+ d->clearConnections();
}
/*!
@@ -181,18 +182,12 @@ void QTreeView::setModel(QAbstractItemModel *model)
if (model == d->model)
return;
if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(rowsRemoved(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(modelAboutToBeReset()), this, SLOT(_q_modelAboutToBeReset()));
+ for (const QMetaObject::Connection &connection : d->modelConnections)
+ QObject::disconnect(connection);
}
if (d->selectionModel) { // support row editing
- disconnect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(rowsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(modelAboutToBeReset()), this, SLOT(_q_modelAboutToBeReset()));
+ QObject::disconnect(d->selectionmodelConnection);
}
d->viewItems.clear();
d->expandedIndexes.clear();
@@ -202,20 +197,24 @@ void QTreeView::setModel(QAbstractItemModel *model)
d->geometryRecursionBlock = false;
QAbstractItemView::setModel(model);
- // QAbstractItemView connects to a private slot
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- // do header layout after the tree
- disconnect(d->model, SIGNAL(layoutChanged()),
- d->header, SLOT(_q_layoutChanged()));
- // QTreeView has a public slot for this
- connect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(rowsRemoved(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(modelAboutToBeReset()), SLOT(_q_modelAboutToBeReset()));
-
+ if (d->model) {
+ // QAbstractItemView connects to a private slot
+ QObjectPrivate::disconnect(d->model, &QAbstractItemModel::rowsRemoved,
+ d, &QAbstractItemViewPrivate::rowsRemoved);
+ // do header layout after the tree
+ QObjectPrivate::disconnect(d->model, &QAbstractItemModel::layoutChanged,
+ d->header->d_func(), &QAbstractItemViewPrivate::layoutChanged);
+
+ d->modelConnections = {
+ // QTreeView has a public slot for this
+ QObject::connect(d->model, &QAbstractItemModel::rowsRemoved,
+ this, &QTreeView::rowsRemoved),
+ QObjectPrivate::connect(d->model, &QAbstractItemModel::modelAboutToBeReset,
+ d, &QTreeViewPrivate::modelAboutToBeReset)
+ };
+ }
if (d->sortingEnabled)
- d->_q_sortIndicatorChanged(header()->sortIndicatorSection(), header()->sortIndicatorOrder());
+ d->sortIndicatorChanged(header()->sortIndicatorSection(), header()->sortIndicatorOrder());
}
/*!
@@ -237,8 +236,7 @@ void QTreeView::setSelectionModel(QItemSelectionModel *selectionModel)
Q_ASSERT(selectionModel);
if (d->selectionModel) {
// support row editing
- disconnect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
+ QObject::disconnect(d->selectionmodelConnection);
}
d->header->setSelectionModel(selectionModel);
@@ -246,8 +244,9 @@ void QTreeView::setSelectionModel(QItemSelectionModel *selectionModel)
if (d->selectionModel) {
// support row editing
- connect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
+ d->selectionmodelConnection =
+ connect(d->selectionModel, &QItemSelectionModel::currentRowChanged,
+ d->model, &QAbstractItemModel::submit);
}
}
@@ -287,16 +286,18 @@ void QTreeView::setHeader(QHeaderView *header)
d->header->setSelectionModel(d->selectionModel);
}
- connect(d->header, SIGNAL(sectionResized(int,int,int)),
- this, SLOT(columnResized(int,int,int)));
- connect(d->header, SIGNAL(sectionMoved(int,int,int)),
- this, SLOT(columnMoved()));
- connect(d->header, SIGNAL(sectionCountChanged(int,int)),
- this, SLOT(columnCountChanged(int,int)));
- connect(d->header, SIGNAL(sectionHandleDoubleClicked(int)),
- this, SLOT(resizeColumnToContents(int)));
- connect(d->header, SIGNAL(geometriesChanged()),
- this, SLOT(updateGeometries()));
+ d->headerConnections = {
+ connect(d->header, &QHeaderView::sectionResized,
+ this, &QTreeView::columnResized),
+ connect(d->header, &QHeaderView::sectionMoved,
+ this, &QTreeView::columnMoved),
+ connect(d->header, &QHeaderView::sectionCountChanged,
+ this, &QTreeView::columnCountChanged),
+ connect(d->header, &QHeaderView::sectionHandleDoubleClicked,
+ this, &QTreeView::resizeColumnToContents),
+ connect(d->header, &QHeaderView::geometriesChanged,
+ this, &QTreeView::updateGeometries)
+ };
setSortingEnabled(d->sortingEnabled);
d->updateGeometry();
@@ -840,11 +841,12 @@ void QTreeView::setSortingEnabled(bool enable)
//sortByColumn has to be called before we connect or set the sortingEnabled flag
// because otherwise it will not call sort on the model.
sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder());
- connect(header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
- this, SLOT(_q_sortIndicatorChanged(int,Qt::SortOrder)), Qt::UniqueConnection);
+ d->sortHeaderConnection =
+ QObjectPrivate::connect(header(), &QHeaderView::sortIndicatorChanged,
+ d, &QTreeViewPrivate::sortIndicatorChanged,
+ Qt::UniqueConnection);
} else {
- disconnect(header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
- this, SLOT(_q_sortIndicatorChanged(int,Qt::SortOrder)));
+ QObject::disconnect(d->sortHeaderConnection);
}
d->sortingEnabled = enable;
}
@@ -1068,33 +1070,64 @@ void QTreeView::keyboardSearch(const QString &search)
QRect QTreeView::visualRect(const QModelIndex &index) const
{
Q_D(const QTreeView);
+ return d->visualRect(index, QTreeViewPrivate::SingleSection);
+}
+
+/*!
+ \internal
+ \return the visual rectangle at \param index, according to \param rule.
+ \list
+ \li SingleSection
+ The return value matches the section, which \a index points to.
+ \li FullRow
+ Return the rectangle of the entire row, no matter which section
+ \a index points to.
+ \li AddRowIndicatorToFirstSection
+ Like SingleSection. If \index points to the first section, add the
+ row indicator and its margins.
+ \endlist
+ */
+QRect QTreeViewPrivate::visualRect(const QModelIndex &index, RectRule rule) const
+{
+ Q_Q(const QTreeView);
- if (!d->isIndexValid(index) || isIndexHidden(index))
+ if (!isIndexValid(index))
return QRect();
- d->executePostedLayout();
+ // Calculate the entire row's rectangle, even if one of the elements is hidden
+ if (q->isIndexHidden(index) && rule != FullRow)
+ return QRect();
+
+ executePostedLayout();
- int vi = d->viewIndex(index);
- if (vi < 0)
+ const int viewIndex = this->viewIndex(index);
+ if (viewIndex < 0)
return QRect();
- bool spanning = d->viewItems.at(vi).spanning;
+ const bool spanning = viewItems.at(viewIndex).spanning;
+ const int column = index.column();
// if we have a spanning item, make the selection stretch from left to right
- int x = (spanning ? 0 : columnViewportPosition(index.column()));
- int w = (spanning ? d->header->length() : columnWidth(index.column()));
- // handle indentation
- if (d->isTreePosition(index.column())) {
- int i = d->indentationForItem(vi);
- w -= i;
- if (!isRightToLeft())
- x += i;
+ int x = (spanning ? 0 : q->columnViewportPosition(column));
+ int width = (spanning ? header->length() : q->columnWidth(column));
+
+ const bool addIndentation = isTreePosition(column) && (column > 0 || rule == SingleSection);
+
+ if (rule == FullRow) {
+ x = 0;
+ width = q->viewport()->width();
+ } else if (addIndentation) {
+ // calculate indentation
+ const int indentation = indentationForItem(viewIndex);
+ width -= indentation;
+ if (!q->isRightToLeft())
+ x += indentation;
}
- int y = d->coordinateForItem(vi);
- int h = d->itemHeight(vi);
+ const int y = coordinateForItem(viewIndex);
+ const int height = itemHeight(viewIndex);
- return QRect(x, y, w, h);
+ return QRect(x, y, width, height);
}
/*!
@@ -1277,16 +1310,13 @@ bool QTreeView::viewportEvent(QEvent *event)
case QEvent::HoverLeave:
case QEvent::HoverMove: {
QHoverEvent *he = static_cast<QHoverEvent*>(event);
- int oldBranch = d->hoverBranch;
+ const int oldBranch = d->hoverBranch;
d->hoverBranch = d->itemDecorationAt(he->position().toPoint());
QModelIndex newIndex = indexAt(he->position().toPoint());
if (d->hover != newIndex || d->hoverBranch != oldBranch) {
// Update the whole hovered over row. No need to update the old hovered
// row, that is taken care in superclass hover handling.
- QRect rect = visualRect(newIndex);
- rect.setX(0);
- rect.setWidth(viewport()->width());
- viewport()->update(rect);
+ viewport()->update(d->visualRect(newIndex, QTreeViewPrivate::FullRow));
}
break; }
default:
@@ -1369,18 +1399,16 @@ bool QTreeViewPrivate::expandOrCollapseItemAtPos(const QPoint &pos)
return false;
}
-void QTreeViewPrivate::_q_modelDestroyed()
+void QTreeViewPrivate::modelDestroyed()
{
//we need to clear the viewItems because it contains QModelIndexes to
//the model currently being destroyed
viewItems.clear();
- QAbstractItemViewPrivate::_q_modelDestroyed();
+ QAbstractItemViewPrivate::modelDestroyed();
}
QRect QTreeViewPrivate::intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const
{
- Q_Q(const QTreeView);
-
const auto parentIdx = topLeft.parent();
executePostedLayout();
QRect updateRect;
@@ -1389,7 +1417,7 @@ QRect QTreeViewPrivate::intersectedRect(const QRect rect, const QModelIndex &top
continue;
for (int c = topLeft.column(); c <= bottomRight.column(); ++c) {
const QModelIndex idx(model->index(r, c, parentIdx));
- updateRect |= q->visualRect(idx);
+ updateRect |= visualRect(idx, SingleSection);
}
}
return rect.intersected(updateRect);
@@ -1496,8 +1524,9 @@ void QTreeView::drawTree(QPainter *painter, const QRegion &region) const
// paint the visible rows
for (; i < viewItems.size() && y <= area.bottom(); ++i) {
+ const QModelIndex &index = viewItems.at(i).index;
const int itemHeight = d->itemHeight(i);
- option.rect.setRect(0, y, viewportWidth, itemHeight);
+ option.rect = d->visualRect(index, QTreeViewPrivate::FullRow);
option.state = state | (viewItems.at(i).expanded ? QStyle::State_Open : QStyle::State_None)
| (viewItems.at(i).hasChildren ? QStyle::State_Children : QStyle::State_None)
| (viewItems.at(i).hasMoreSiblings ? QStyle::State_Sibling : QStyle::State_None);
@@ -2116,6 +2145,7 @@ void QTreeView::doItemsLayout()
}
QAbstractItemView::doItemsLayout();
d->header->doItemsLayout();
+ d->updateAccessibility();
}
/*!
@@ -2192,9 +2222,8 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
}
return QModelIndex();
}
- int vi = -1;
- if (vi < 0)
- vi = qMax(0, d->viewIndex(current));
+
+ const int vi = qMax(0, d->viewIndex(current));
if (isRightToLeft()) {
if (cursorAction == MoveRight)
@@ -2368,7 +2397,7 @@ QRegion QTreeView::visualRegionForSelection(const QItemSelection &selection) con
}
if (!leftIndex.isValid())
continue;
- const QRect leftRect = visualRect(leftIndex);
+ const QRect leftRect = d->visualRect(leftIndex, QTreeViewPrivate::SingleSection);
int top = leftRect.top();
QModelIndex rightIndex = range.bottomRight();
while (rightIndex.isValid() && isIndexHidden(rightIndex)) {
@@ -2379,7 +2408,7 @@ QRegion QTreeView::visualRegionForSelection(const QItemSelection &selection) con
}
if (!rightIndex.isValid())
continue;
- const QRect rightRect = visualRect(rightIndex);
+ const QRect rightRect = d->visualRect(rightIndex, QTreeViewPrivate::SingleSection);
int bottom = rightRect.bottom();
if (top > bottom)
qSwap<int>(top, bottom);
@@ -2555,7 +2584,7 @@ void QTreeView::rowsRemoved(const QModelIndex &parent, int start, int end)
d->viewItems.clear();
d->doDelayedItemsLayout();
d->hasRemovedItems = true;
- d->_q_rowsRemoved(parent, start, end);
+ d->rowsRemoved(parent, start, end);
}
/*!
@@ -2646,7 +2675,8 @@ QSize QTreeView::viewportSizeHint() const
return QAbstractItemView::viewportSizeHint();
// Get rect for last item
- const QRect deepestRect = visualRect(d->viewItems.last().index);
+ const QRect deepestRect = d->visualRect(d->viewItems.last().index,
+ QTreeViewPrivate::SingleSection);
if (!deepestRect.isValid())
return QAbstractItemView::viewportSizeHint();
@@ -2679,6 +2709,7 @@ void QTreeView::expandAll()
d->layout(-1, true);
updateGeometries();
d->viewport->update();
+ d->updateAccessibility();
}
/*!
@@ -2802,6 +2833,7 @@ void QTreeView::expandToDepth(int depth)
updateGeometries();
d->viewport->update();
+ d->updateAccessibility();
}
/*!
@@ -3062,10 +3094,25 @@ void QTreeViewPrivate::initialize()
q->setHeader(header);
#if QT_CONFIG(animation)
animationsEnabled = q->style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, q) > 0;
- QObject::connect(&animatedOperation, SIGNAL(finished()), q, SLOT(_q_endAnimatedOperation()));
+ animationConnection =
+ QObjectPrivate::connect(&animatedOperation, &QVariantAnimation::finished,
+ this, &QTreeViewPrivate::endAnimatedOperation);
#endif // animation
}
+void QTreeViewPrivate::clearConnections()
+{
+ for (const QMetaObject::Connection &connection : modelConnections)
+ QObject::disconnect(connection);
+ for (const QMetaObject::Connection &connection : headerConnections)
+ QObject::disconnect(connection);
+ QObject::disconnect(selectionmodelConnection);
+ QObject::disconnect(sortHeaderConnection);
+#if QT_CONFIG(animation)
+ QObject::disconnect(animationConnection);
+#endif
+}
+
void QTreeViewPrivate::expand(int item, bool emitSignal)
{
Q_Q(QTreeView);
@@ -3098,6 +3145,7 @@ void QTreeViewPrivate::expand(int item, bool emitSignal)
beginAnimatedOperation();
#endif // animation
}
+ updateAccessibility();
}
void QTreeViewPrivate::insertViewItems(int pos, int count, const QTreeViewItem &viewItem)
@@ -3258,7 +3306,7 @@ QPixmap QTreeViewPrivate::renderTreeToPixmapForAnimation(const QRect &rect) cons
for (QEditorIndexHash::const_iterator it = editorIndexHash.constBegin(); it != editorIndexHash.constEnd(); ++it) {
QWidget *editor = it.key();
const QModelIndex &index = it.value();
- option.rect = q->visualRect(index);
+ option.rect = visualRect(index, SingleSection);
if (option.rect.isValid()) {
if (QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index))
@@ -3278,7 +3326,7 @@ QPixmap QTreeViewPrivate::renderTreeToPixmapForAnimation(const QRect &rect) cons
return pixmap;
}
-void QTreeViewPrivate::_q_endAnimatedOperation()
+void QTreeViewPrivate::endAnimatedOperation()
{
Q_Q(QTreeView);
q->setState(stateBeforeAnimation);
@@ -3287,25 +3335,40 @@ void QTreeViewPrivate::_q_endAnimatedOperation()
}
#endif // animation
-void QTreeViewPrivate::_q_modelAboutToBeReset()
+void QTreeViewPrivate::modelAboutToBeReset()
{
viewItems.clear();
}
-void QTreeViewPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void QTreeViewPrivate::columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
{
if (start <= 0 && 0 <= end)
viewItems.clear();
- QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(parent, start, end);
+ QAbstractItemViewPrivate::columnsAboutToBeRemoved(parent, start, end);
}
-void QTreeViewPrivate::_q_columnsRemoved(const QModelIndex &parent, int start, int end)
+void QTreeViewPrivate::columnsRemoved(const QModelIndex &parent, int start, int end)
{
if (start <= 0 && 0 <= end)
doDelayedItemsLayout();
- QAbstractItemViewPrivate::_q_columnsRemoved(parent, start, end);
+ QAbstractItemViewPrivate::columnsRemoved(parent, start, end);
+}
+
+void QTreeViewPrivate::updateAccessibility()
+{
+#if QT_CONFIG(accessibility)
+ Q_Q(QTreeView);
+ if (pendingAccessibilityUpdate) {
+ pendingAccessibilityUpdate = false;
+ if (QAccessible::isActive()) {
+ QAccessibleTableModelChangeEvent event(q, QAccessibleTableModelChangeEvent::ModelReset);
+ QAccessible::updateAccessibility(&event);
+ }
+ }
+#endif
}
+
/** \internal
creates and initialize the viewItem structure of the children of the element \li
@@ -3326,6 +3389,15 @@ void QTreeViewPrivate::layout(int i, bool recursiveExpanding, bool afterIsUninit
return;
}
+#if QT_CONFIG(accessibility)
+ // QAccessibleTree's rowCount implementation uses viewItems.size(), so
+ // we need to invalidate any cached accessibility data structures if
+ // that value changes during the run of this function.
+ const auto resetModelIfNeeded = qScopeGuard([oldViewItemsSize = viewItems.size(), this]{
+ pendingAccessibilityUpdate |= oldViewItemsSize != viewItems.size();
+ });
+#endif
+
int count = 0;
if (model->hasChildren(parent)) {
if (model->canFetchMore(parent)) {
@@ -3964,7 +4036,7 @@ bool QTreeViewPrivate::hasVisibleChildren(const QModelIndex& parent) const
return false;
}
-void QTreeViewPrivate::_q_sortIndicatorChanged(int column, Qt::SortOrder order)
+void QTreeViewPrivate::sortIndicatorChanged(int column, Qt::SortOrder order)
{
model->sort(column, order);
}
@@ -3988,24 +4060,17 @@ void QTreeViewPrivate::updateIndentationFromStyle()
*/
void QTreeView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
+ Q_D(QTreeView);
QAbstractItemView::currentChanged(current, previous);
if (allColumnsShowFocus()) {
- if (previous.isValid()) {
- QRect previousRect = visualRect(previous);
- previousRect.setX(0);
- previousRect.setWidth(viewport()->width());
- viewport()->update(previousRect);
- }
- if (current.isValid()) {
- QRect currentRect = visualRect(current);
- currentRect.setX(0);
- currentRect.setWidth(viewport()->width());
- viewport()->update(currentRect);
- }
+ if (previous.isValid())
+ viewport()->update(d->visualRect(previous, QTreeViewPrivate::FullRow));
+ if (current.isValid())
+ viewport()->update(d->visualRect(current, QTreeViewPrivate::FullRow));
}
#if QT_CONFIG(accessibility)
- if (QAccessible::isActive() && current.isValid()) {
+ if (QAccessible::isActive() && current.isValid() && hasFocus()) {
Q_D(QTreeView);
QAccessibleEvent event(this, QAccessible::Focus);
diff --git a/src/widgets/itemviews/qtreeview.h b/src/widgets/itemviews/qtreeview.h
index d73ca5e2cd..1dd4650c5d 100644
--- a/src/widgets/itemviews/qtreeview.h
+++ b/src/widgets/itemviews/qtreeview.h
@@ -195,11 +195,6 @@ private:
Q_DECLARE_PRIVATE(QTreeView)
Q_DISABLE_COPY(QTreeView)
-#if QT_CONFIG(animation)
- Q_PRIVATE_SLOT(d_func(), void _q_endAnimatedOperation())
-#endif // animation
- Q_PRIVATE_SLOT(d_func(), void _q_modelAboutToBeReset())
- Q_PRIVATE_SLOT(d_func(), void _q_sortIndicatorChanged(int column, Qt::SortOrder order))
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qtreeview_p.h b/src/widgets/itemviews/qtreeview_p.h
index 22f6eaec22..d0afdf1223 100644
--- a/src/widgets/itemviews/qtreeview_p.h
+++ b/src/widgets/itemviews/qtreeview_p.h
@@ -23,6 +23,8 @@
#include <QtCore/qvariantanimation.h>
#endif
+#include <array>
+
QT_REQUIRE_CONFIG(treeview);
QT_BEGIN_NAMESPACE
@@ -62,6 +64,7 @@ public:
~QTreeViewPrivate() {}
void initialize();
+ void clearConnections();
int logicalIndexForTree() const;
inline bool isTreePosition(int logicalIndex) const
{
@@ -88,17 +91,17 @@ public:
void beginAnimatedOperation();
void drawAnimatedOperation(QPainter *painter) const;
QPixmap renderTreeToPixmapForAnimation(const QRect &rect) const;
- void _q_endAnimatedOperation();
+ void endAnimatedOperation();
#endif // animation
void expand(int item, bool emitSignal);
void collapse(int item, bool emitSignal);
- void _q_columnsAboutToBeRemoved(const QModelIndex &, int, int) override;
- void _q_columnsRemoved(const QModelIndex &, int, int) override;
- void _q_modelAboutToBeReset();
- void _q_sortIndicatorChanged(int column, Qt::SortOrder order);
- void _q_modelDestroyed() override;
+ void columnsAboutToBeRemoved(const QModelIndex &, int, int) override;
+ void columnsRemoved(const QModelIndex &, int, int) override;
+ void modelAboutToBeReset();
+ void sortIndicatorChanged(int column, Qt::SortOrder order);
+ void modelDestroyed() override;
QRect intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const override;
void layout(int item, bool recusiveExpanding = false, bool afterIsUninitialized = false);
@@ -150,6 +153,21 @@ public:
QList<QStyleOptionViewItem::ViewItemPosition> *itemPositions, int left,
int right) const;
int widthHintForIndex(const QModelIndex &index, int hint, const QStyleOptionViewItem &option, int i) const;
+
+ enum RectRule {
+ FullRow,
+ SingleSection,
+ AddRowIndicatorToFirstSection
+ };
+
+ // Base class will get the first visual rect including row indicator
+ QRect visualRect(const QModelIndex &index) const override
+ {
+ return visualRect(index, AddRowIndicatorToFirstSection);
+ }
+
+ QRect visualRect(const QModelIndex &index, RectRule rule) const;
+
QHeaderView *header;
int indent;
@@ -239,6 +257,18 @@ public:
// tree position
int treePosition;
+
+ // pending accessibility update
+#if QT_CONFIG(accessibility)
+ bool pendingAccessibilityUpdate = false;
+#endif
+ void updateAccessibility();
+
+ QMetaObject::Connection animationConnection;
+ QMetaObject::Connection selectionmodelConnection;
+ std::array<QMetaObject::Connection, 2> modelConnections;
+ std::array<QMetaObject::Connection, 5> headerConnections;
+ QMetaObject::Connection sortHeaderConnection;
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qtreewidget.cpp b/src/widgets/itemviews/qtreewidget.cpp
index 3fa8a7e1b9..8e46a0efbe 100644
--- a/src/widgets/itemviews/qtreewidget.cpp
+++ b/src/widgets/itemviews/qtreewidget.cpp
@@ -5,7 +5,6 @@
#include <qheaderview.h>
#include <qpainter.h>
-#include <qitemdelegate.h>
#include <qstack.h>
#include <qdebug.h>
#include <private/qtreewidget_p.h>
@@ -2301,37 +2300,43 @@ QDataStream &operator>>(QDataStream &in, QTreeWidgetItem &item)
#endif // QT_NO_DATASTREAM
-void QTreeWidgetPrivate::_q_emitItemPressed(const QModelIndex &index)
+void QTreeWidgetPrivate::clearConnections()
+{
+ for (const QMetaObject::Connection &connection : connections)
+ QObject::disconnect(connection);
+}
+
+void QTreeWidgetPrivate::emitItemPressed(const QModelIndex &index)
{
Q_Q(QTreeWidget);
emit q->itemPressed(item(index), index.column());
}
-void QTreeWidgetPrivate::_q_emitItemClicked(const QModelIndex &index)
+void QTreeWidgetPrivate::emitItemClicked(const QModelIndex &index)
{
Q_Q(QTreeWidget);
emit q->itemClicked(item(index), index.column());
}
-void QTreeWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index)
+void QTreeWidgetPrivate::emitItemDoubleClicked(const QModelIndex &index)
{
Q_Q(QTreeWidget);
emit q->itemDoubleClicked(item(index), index.column());
}
-void QTreeWidgetPrivate::_q_emitItemActivated(const QModelIndex &index)
+void QTreeWidgetPrivate::emitItemActivated(const QModelIndex &index)
{
Q_Q(QTreeWidget);
emit q->itemActivated(item(index), index.column());
}
-void QTreeWidgetPrivate::_q_emitItemEntered(const QModelIndex &index)
+void QTreeWidgetPrivate::emitItemEntered(const QModelIndex &index)
{
Q_Q(QTreeWidget);
emit q->itemEntered(item(index), index.column());
}
-void QTreeWidgetPrivate::_q_emitItemChanged(const QModelIndex &index)
+void QTreeWidgetPrivate::emitItemChanged(const QModelIndex &index)
{
Q_Q(QTreeWidget);
QTreeWidgetItem *indexItem = item(index);
@@ -2339,19 +2344,19 @@ void QTreeWidgetPrivate::_q_emitItemChanged(const QModelIndex &index)
emit q->itemChanged(indexItem, index.column());
}
-void QTreeWidgetPrivate::_q_emitItemExpanded(const QModelIndex &index)
+void QTreeWidgetPrivate::emitItemExpanded(const QModelIndex &index)
{
Q_Q(QTreeWidget);
emit q->itemExpanded(item(index));
}
-void QTreeWidgetPrivate::_q_emitItemCollapsed(const QModelIndex &index)
+void QTreeWidgetPrivate::emitItemCollapsed(const QModelIndex &index)
{
Q_Q(QTreeWidget);
emit q->itemCollapsed(item(index));
}
-void QTreeWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
+void QTreeWidgetPrivate::emitCurrentItemChanged(const QModelIndex &current,
const QModelIndex &previous)
{
Q_Q(QTreeWidget);
@@ -2360,7 +2365,7 @@ void QTreeWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
emit q->currentItemChanged(currentItem, previousItem);
}
-void QTreeWidgetPrivate::_q_sort()
+void QTreeWidgetPrivate::sort()
{
if (sortingEnabled) {
int column = header->sortIndicatorSection();
@@ -2369,7 +2374,7 @@ void QTreeWidgetPrivate::_q_sort()
}
}
-void QTreeWidgetPrivate::_q_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
+void QTreeWidgetPrivate::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_Q(QTreeWidget);
QModelIndexList indices = selected.indexes();
@@ -2389,8 +2394,8 @@ void QTreeWidgetPrivate::_q_selectionChanged(const QItemSelection &selected, con
emit q->itemSelectionChanged();
}
-void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight)
+void QTreeWidgetPrivate::dataChanged(const QModelIndex &topLeft,
+ const QModelIndex &bottomRight)
{
if (sortingEnabled && topLeft.isValid() && bottomRight.isValid()
&& !treeModel()->sortPendingTimer.isActive()) {
@@ -2448,7 +2453,7 @@ void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
whether sorting is enabled.
\sa QTreeWidgetItem, QTreeWidgetItemIterator, QTreeView,
- {Model/View Programming}, {Settings Editor Example}
+ {Model/View Programming}
*/
/*!
@@ -2570,31 +2575,34 @@ void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
QTreeWidget::QTreeWidget(QWidget *parent)
: QTreeView(*new QTreeWidgetPrivate(), parent)
{
+ Q_D(QTreeWidget);
QTreeView::setModel(new QTreeModel(1, this));
- connect(this, SIGNAL(pressed(QModelIndex)),
- SLOT(_q_emitItemPressed(QModelIndex)));
- connect(this, SIGNAL(clicked(QModelIndex)),
- SLOT(_q_emitItemClicked(QModelIndex)));
- connect(this, SIGNAL(doubleClicked(QModelIndex)),
- SLOT(_q_emitItemDoubleClicked(QModelIndex)));
- connect(this, SIGNAL(activated(QModelIndex)),
- SLOT(_q_emitItemActivated(QModelIndex)));
- connect(this, SIGNAL(entered(QModelIndex)),
- SLOT(_q_emitItemEntered(QModelIndex)));
- connect(this, SIGNAL(expanded(QModelIndex)),
- SLOT(_q_emitItemExpanded(QModelIndex)));
- connect(this, SIGNAL(collapsed(QModelIndex)),
- SLOT(_q_emitItemCollapsed(QModelIndex)));
- connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_emitCurrentItemChanged(QModelIndex,QModelIndex)));
- connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_emitItemChanged(QModelIndex)));
- connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- connect(model(), SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sort()));
- connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(_q_selectionChanged(QItemSelection,QItemSelection)));
+ d->connections = {
+ QObjectPrivate::connect(this, &QTreeWidget::pressed,
+ d, &QTreeWidgetPrivate::emitItemPressed),
+ QObjectPrivate::connect(this, &QTreeWidget::clicked,
+ d, &QTreeWidgetPrivate::emitItemClicked),
+ QObjectPrivate::connect(this, &QTreeWidget::doubleClicked,
+ d, &QTreeWidgetPrivate::emitItemDoubleClicked),
+ QObjectPrivate::connect(this, &QTreeWidget::activated,
+ d, &QTreeWidgetPrivate::emitItemActivated),
+ QObjectPrivate::connect(this, &QTreeWidget::entered,
+ d, &QTreeWidgetPrivate::emitItemEntered),
+ QObjectPrivate::connect(this, &QTreeWidget::expanded,
+ d, &QTreeWidgetPrivate::emitItemExpanded),
+ QObjectPrivate::connect(this, &QTreeWidget::collapsed,
+ d, &QTreeWidgetPrivate::emitItemCollapsed),
+ QObjectPrivate::connect(model(), &QAbstractItemModel::dataChanged,
+ d, &QTreeWidgetPrivate::emitItemChanged),
+ QObjectPrivate::connect(model(), &QAbstractItemModel::dataChanged,
+ d, &QTreeWidgetPrivate::dataChanged),
+ QObjectPrivate::connect(model(), &QAbstractItemModel::columnsRemoved,
+ d, &QTreeWidgetPrivate::sort),
+ QObjectPrivate::connect(selectionModel(), &QItemSelectionModel::currentChanged,
+ d, &QTreeWidgetPrivate::emitCurrentItemChanged),
+ QObjectPrivate::connect(selectionModel(), &QItemSelectionModel::selectionChanged,
+ d, &QTreeWidgetPrivate::selectionChanged)
+ };
header()->setSectionsClickable(false);
}
@@ -2604,6 +2612,8 @@ QTreeWidget::QTreeWidget(QWidget *parent)
QTreeWidget::~QTreeWidget()
{
+ Q_D(QTreeWidget);
+ d->clearConnections();
}
/*
@@ -3119,7 +3129,7 @@ void QTreeWidget::setSelectionModel(QItemSelectionModel *selectionModel)
QTreeView::setSelectionModel(selectionModel);
QItemSelection newSelection = selectionModel->selection();
if (!newSelection.isEmpty())
- d->_q_selectionChanged(newSelection, QItemSelection());
+ d->selectionChanged(newSelection, QItemSelection());
}
/*!
diff --git a/src/widgets/itemviews/qtreewidget.h b/src/widgets/itemviews/qtreewidget.h
index f83cf421ed..992f6cdb1c 100644
--- a/src/widgets/itemviews/qtreewidget.h
+++ b/src/widgets/itemviews/qtreewidget.h
@@ -323,19 +323,6 @@ private:
Q_DECLARE_PRIVATE(QTreeWidget)
Q_DISABLE_COPY(QTreeWidget)
-
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemPressed(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemDoubleClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemActivated(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemEntered(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemExpanded(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemCollapsed(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current))
- Q_PRIVATE_SLOT(d_func(), void _q_sort())
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight))
- Q_PRIVATE_SLOT(d_func(), void _q_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected))
};
inline void QTreeWidget::removeItemWidget(QTreeWidgetItem *item, int column)
diff --git a/src/widgets/itemviews/qtreewidget_p.h b/src/widgets/itemviews/qtreewidget_p.h
index fd7560ffd6..53fdea3ca8 100644
--- a/src/widgets/itemviews/qtreewidget_p.h
+++ b/src/widgets/itemviews/qtreewidget_p.h
@@ -23,6 +23,8 @@
#include <private/qtreeview_p.h>
#include <QtWidgets/qheaderview.h>
+#include <array>
+
QT_REQUIRE_CONFIG(treewidget);
QT_BEGIN_NAMESPACE
@@ -186,26 +188,29 @@ class QTreeWidgetPrivate : public QTreeViewPrivate
Q_DECLARE_PUBLIC(QTreeWidget)
public:
QTreeWidgetPrivate() : QTreeViewPrivate(), explicitSortColumn(-1) {}
+ void clearConnections();
inline QTreeModel *treeModel() const { return qobject_cast<QTreeModel*>(model); }
inline QModelIndex index(const QTreeWidgetItem *item, int column = 0) const
{ return treeModel()->index(item, column); }
inline QTreeWidgetItem *item(const QModelIndex &index) const
{ return treeModel()->item(index); }
- void _q_emitItemPressed(const QModelIndex &index);
- void _q_emitItemClicked(const QModelIndex &index);
- void _q_emitItemDoubleClicked(const QModelIndex &index);
- void _q_emitItemActivated(const QModelIndex &index);
- void _q_emitItemEntered(const QModelIndex &index);
- void _q_emitItemChanged(const QModelIndex &index);
- void _q_emitItemExpanded(const QModelIndex &index);
- void _q_emitItemCollapsed(const QModelIndex &index);
- void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &index);
- void _q_sort();
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void _q_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
+ void emitItemPressed(const QModelIndex &index);
+ void emitItemClicked(const QModelIndex &index);
+ void emitItemDoubleClicked(const QModelIndex &index);
+ void emitItemActivated(const QModelIndex &index);
+ void emitItemEntered(const QModelIndex &index);
+ void emitItemChanged(const QModelIndex &index);
+ void emitItemExpanded(const QModelIndex &index);
+ void emitItemCollapsed(const QModelIndex &index);
+ void emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &index);
+ void sort();
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+ void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
// used by QTreeWidgetItem::sortChildren to make sure the column argument is used
int explicitSortColumn;
+
+ std::array<QMetaObject::Connection, 12> connections;
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qwidgetitemdata_p.h b/src/widgets/itemviews/qwidgetitemdata_p.h
index 0fbaae34bd..f8c2d47085 100644
--- a/src/widgets/itemviews/qwidgetitemdata_p.h
+++ b/src/widgets/itemviews/qwidgetitemdata_p.h
@@ -6,6 +6,7 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtCore/qdatastream.h>
+#include <QtCore/qvariant.h>
//
// W A R N I N G
diff --git a/src/widgets/kernel/qaction_widgets.cpp b/src/widgets/kernel/qaction_widgets.cpp
index 53b6e13b2d..ad282ab104 100644
--- a/src/widgets/kernel/qaction_widgets.cpp
+++ b/src/widgets/kernel/qaction_widgets.cpp
@@ -28,8 +28,9 @@ void QtWidgetsActionPrivate::destroy()
{
Q_Q(QAction);
const auto objects = associatedObjects;
- for (int i = objects.size()-1; i >= 0; --i) {
- QObject *object = objects.at(i);
+ const auto end = objects.crend();
+ for (auto it = objects.crbegin(); it != end; ++it) {
+ QObject *object = *it;
if (QWidget *widget = qobject_cast<QWidget*>(object))
widget->removeAction(q);
#if QT_CONFIG(graphicsview)
diff --git a/src/widgets/kernel/qaction_widgets_p.h b/src/widgets/kernel/qaction_widgets_p.h
index bc24ce3df1..77c3d8a680 100644
--- a/src/widgets/kernel/qaction_widgets_p.h
+++ b/src/widgets/kernel/qaction_widgets_p.h
@@ -20,6 +20,8 @@
#include <QtWidgets/qmenu.h>
#endif
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(action);
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp
index 13897e1218..de7d93ce20 100644
--- a/src/widgets/kernel/qapplication.cpp
+++ b/src/widgets/kernel/qapplication.cpp
@@ -100,6 +100,13 @@ QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
+Q_TRACE_PREFIX(qtwidgets,
+ "#include <qcoreevent.h>"
+);
+Q_TRACE_METADATA(qtwidgets, "ENUM { AUTO, RANGE User ... MaxUser } QEvent::Type;");
+Q_TRACE_POINT(qtwidgets, QApplication_notify_entry, QObject *receiver, QEvent *event, QEvent::Type type);
+Q_TRACE_POINT(qtwidgets, QApplication_notify_exit, bool consumed, bool filtered);
+
// Helper macro for static functions to check on the existence of the application class.
#define CHECK_QAPP_INSTANCE(...) \
if (Q_LIKELY(QCoreApplication::instance())) { \
@@ -303,7 +310,6 @@ QWidget *QApplication::topLevelAt(const QPoint &pos)
*/
void qt_init_tooltip_palette();
-void qt_cleanup();
QStyle *QApplicationPrivate::app_style = nullptr; // default application style
#ifndef QT_NO_STYLE_STYLESHEET
@@ -489,8 +495,11 @@ void QApplicationPrivate::init()
void qt_init_tooltip_palette()
{
#if QT_CONFIG(tooltip)
- if (const QPalette *toolTipPalette = QGuiApplicationPrivate::platformTheme()->palette(QPlatformTheme::ToolTipPalette))
- QToolTip::setPalette(*toolTipPalette);
+ if (const QPalette *toolTipPalette = QGuiApplicationPrivate::platformTheme()->palette(QPlatformTheme::ToolTipPalette)) {
+ QPalette toolTipPal = *toolTipPalette;
+ toolTipPal.setResolveMask(0);
+ QToolTip::setPalette(toolTipPal);
+ }
#endif
}
@@ -520,6 +529,8 @@ void QApplicationPrivate::initialize()
qWarning("QApplication: invalid style override '%s' passed, ignoring it.\n"
"\tAvailable styles: %s", qPrintable(styleOverride),
qPrintable(QStyleFactory::keys().join(", "_L1)));
+ // Clear styleOverride so it is not picked by Qt Quick Controls (QTBUG-100563)
+ styleOverride.clear();
}
}
@@ -696,7 +707,10 @@ QApplication::~QApplication()
d->cleanupMultitouch();
- qt_cleanup();
+ QPixmapCache::clear();
+ QColormap::cleanup();
+
+ QApplicationPrivate::active_window = nullptr; //### this should not be necessary
if (QApplicationPrivate::widgetCount)
qDebug("Widgets left: %i Max widgets: %i \n", QWidgetPrivate::instanceCounter, QWidgetPrivate::maxInstances);
@@ -707,14 +721,6 @@ QApplication::~QApplication()
QApplicationPrivate::widgetCount = false;
}
-void qt_cleanup()
-{
- QPixmapCache::clear();
- QColormap::cleanup();
-
- QApplicationPrivate::active_window = nullptr; //### this should not be necessary
-}
-
/*!
\fn QWidget *QApplication::widgetAt(const QPoint &point)
@@ -776,35 +782,54 @@ QWidget *QApplication::widgetAt(const QPoint &p)
*/
bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
{
- if ((event->type() == QEvent::UpdateRequest
- || event->type() == QEvent::LayoutRequest
- || event->type() == QEvent::Resize
- || event->type() == QEvent::Move
- || event->type() == QEvent::LanguageChange)) {
- for (QPostEventList::const_iterator it = postedEvents->constBegin(); it != postedEvents->constEnd(); ++it) {
- const QPostEvent &cur = *it;
- if (cur.receiver != receiver || cur.event == nullptr || cur.event->type() != event->type())
- continue;
- if (cur.event->type() == QEvent::LayoutRequest
- || cur.event->type() == QEvent::UpdateRequest) {
- ;
- } else if (cur.event->type() == QEvent::Resize) {
- static_cast<QResizeEvent *>(cur.event)->m_size =
- static_cast<const QResizeEvent *>(event)->size();
- } else if (cur.event->type() == QEvent::Move) {
- static_cast<QMoveEvent *>(cur.event)->m_pos =
- static_cast<const QMoveEvent *>(event)->pos();
- } else if (cur.event->type() == QEvent::LanguageChange) {
- ;
- } else {
- continue;
- }
- delete event;
- return true;
+ // Only compress the following events:
+ const QEvent::Type type = event->type();
+ switch (type) {
+ case QEvent::UpdateRequest:
+ case QEvent::UpdateLater:
+ case QEvent::LayoutRequest:
+ case QEvent::Resize:
+ case QEvent::Move:
+ case QEvent::LanguageChange:
+ break;
+ default:
+ return QGuiApplication::compressEvent(event, receiver, postedEvents);
+ }
+
+ for (const auto &postedEvent : std::as_const(*postedEvents)) {
+
+ // Continue, unless a valid event of the same type exists for the same receiver
+ if (postedEvent.receiver != receiver
+ || !postedEvent.event
+ || postedEvent.event->type() != type) {
+ continue;
}
- return false;
+
+ // Handle type specific compression
+ switch (type) {
+ case QEvent::Resize:
+ static_cast<QResizeEvent *>(postedEvent.event)->m_size =
+ static_cast<const QResizeEvent *>(event)->size();
+ break;
+ case QEvent::Move:
+ static_cast<QMoveEvent *>(postedEvent.event)->m_pos =
+ static_cast<const QMoveEvent *>(event)->pos();
+ break;
+ case QEvent::UpdateLater:
+ static_cast<QUpdateLaterEvent *>(postedEvent.event)->m_region +=
+ static_cast<const QUpdateLaterEvent *>(event)->region();
+ break;
+ case QEvent::UpdateRequest:
+ case QEvent::LanguageChange:
+ case QEvent::LayoutRequest:
+ break;
+ default:
+ continue;
+ }
+ delete event;
+ return true;
}
- return QGuiApplication::compressEvent(event, receiver, postedEvents);
+ return false;
}
/*!
@@ -1750,9 +1775,8 @@ void QApplicationPrivate::notifyLayoutDirectionChange()
}
/*!
- \internal
-
\fn void QApplication::setActiveWindow(QWidget* active)
+ \deprecated [6.5] Use QWidget::activateWindow() instead.
Sets the active window to the \a active widget in response to a system
event. The function is called from the platform specific event handlers.
@@ -1769,7 +1793,7 @@ void QApplicationPrivate::notifyLayoutDirectionChange()
\sa activeWindow(), QWidget::activateWindow()
*/
-#if QT_DEPRECATED_SINCE(6,4)
+#if QT_DEPRECATED_SINCE(6,5)
void QApplication::setActiveWindow(QWidget* act)
{
QApplicationPrivate::setActiveWindow(act);
@@ -1945,7 +1969,7 @@ QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool
f = toplevel;
QWidget *w = f;
- QWidget *test = f->d_func()->focus_next;
+ QWidget *test = f->nextInFocusChain();
bool seenWindow = false;
bool focusWidgetAfterWindow = false;
while (test && test != f) {
@@ -1976,7 +2000,7 @@ QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool
if (next)
break;
}
- test = test->d_func()->focus_next;
+ test = test->nextInFocusChain();
}
if (wrappingOccurred != nullptr)
@@ -2001,19 +2025,6 @@ QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool
*/
void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, const QPointF &globalPosF)
{
-#if 0
- if (leave) {
- QEvent e(QEvent::Leave);
- QCoreApplication::sendEvent(leave, & e);
- }
- if (enter) {
- const QPoint windowPos = enter->window()->mapFromGlobal(globalPos);
- QEnterEvent e(enter->mapFromGlobal(globalPos), windowPos, globalPos);
- QCoreApplication::sendEvent(enter, & e);
- }
- return;
-#endif
-
if ((!enter && !leave) || (enter == leave))
return;
@@ -2463,7 +2474,7 @@ void QApplication::setStartDragTime(int ms)
The default value is 500 ms.
- \sa startDragDistance(), {Drag and Drop}
+ \sa startDragDistance(), {Drag and Drop in Qt}{Drag and Drop}
*/
int QApplication::startDragTime()
@@ -2502,7 +2513,7 @@ void QApplication::setStartDragDistance(int l)
The default value (if the platform doesn't provide a different default)
is 10 pixels.
- \sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop}
+ \sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop in Qt}{Drag and Drop}
*/
int QApplication::startDragDistance()
@@ -2524,8 +2535,9 @@ int QApplication::startDragDistance()
exec(), because modal widgets call exec() to start a local event loop.
To make your application perform idle processing, i.e., executing a special
- function whenever there are no pending events, use a QTimer with 0 timeout.
- More advanced idle processing schemes can be achieved using processEvents().
+ function whenever there are no pending events, use a QChronoTimer with 0ns
+ timeout. More advanced idle processing schemes can be achieved using
+ processEvents().
We recommend that you connect clean-up code to the
\l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your
@@ -2634,6 +2646,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
Q_FALLTHROUGH();
case QEvent::Leave:
d->toolTipWakeUp.stop();
+ break;
default:
break;
}
@@ -2658,6 +2671,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
|| key == Qt::Key_Up
|| key == Qt::Key_Right
|| key == Qt::Key_Down);
+ break;
}
default:
break;
@@ -2919,6 +2933,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
tablet->tangentialPressure(), tablet->rotation(), tablet->z(),
tablet->modifiers(), tablet->button(), tablet->buttons());
te.m_spont = e->spontaneous();
+ te.setTimestamp(tablet->timestamp());
te.setAccepted(false);
res = d->notify_helper(w, w == receiver ? tablet : &te);
eventAccepted = ((w == receiver) ? tablet : &te)->isAccepted();
@@ -3014,8 +3029,16 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
#endif
w = qobject_cast<QWidget *>(QDragManager::self()->currentTarget());
- if (!w)
- break;
+ if (!w) {
+ // The widget that received DragEnter didn't accept the event, so we have no
+ // current drag target in the QDragManager. But DragLeave still needs to be
+ // dispatched so that enter/leave events are in balance (and so that UnderMouse
+ // gets cleared).
+ if (e->type() == QEvent::DragLeave)
+ w = static_cast<QWidget *>(receiver);
+ else
+ break;
+ }
if (e->type() == QEvent::DragMove || e->type() == QEvent::Drop) {
QDropEvent *dragEvent = static_cast<QDropEvent *>(e);
QWidget *origReceiver = static_cast<QWidget *>(receiver);
@@ -3032,15 +3055,16 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
)
QDragManager::self()->setCurrentTarget(nullptr, e->type() == QEvent::Drop);
break;
-#endif
}
+#endif // QT_CONFIG(draganddrop)
case QEvent::TouchBegin: {
// Note: TouchUpdate and TouchEnd events are never propagated
QMutableTouchEvent *touchEvent = QMutableTouchEvent::from(static_cast<QTouchEvent *>(e));
bool eventAccepted = touchEvent->isAccepted();
bool acceptTouchEvents = w->testAttribute(Qt::WA_AcceptTouchEvents);
- if (acceptTouchEvents && e->spontaneous()) {
+ if (acceptTouchEvents && e->spontaneous()
+ && touchEvent->device()->type() != QInputDevice::DeviceType::TouchPad) {
const QPoint localPos = touchEvent->points()[0].position().toPoint();
QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, localPos);
}
diff --git a/src/widgets/kernel/qapplication.h b/src/widgets/kernel/qapplication.h
index d60e83a643..fd698fb69f 100644
--- a/src/widgets/kernel/qapplication.h
+++ b/src/widgets/kernel/qapplication.h
@@ -79,8 +79,8 @@ public:
static QWidget *activeWindow();
-#if QT_DEPRECATED_SINCE(6,4)
- QT_DEPRECATED_VERSION_X_6_4("Use QWidget::activateWindow() instead.")
+#if QT_DEPRECATED_SINCE(6, 5)
+ QT_DEPRECATED_VERSION_X_6_5("Use QWidget::activateWindow() instead.")
static void setActiveWindow(QWidget* act);
#endif
@@ -129,12 +129,12 @@ Q_SIGNALS:
public:
QString styleSheet() const;
+ bool autoSipEnabled() const;
public Q_SLOTS:
#ifndef QT_NO_STYLE_STYLESHEET
void setStyleSheet(const QString& sheet);
#endif
void setAutoSipEnabled(const bool enabled);
- bool autoSipEnabled() const;
static void closeAllWindows();
static void aboutQt();
diff --git a/src/widgets/kernel/qapplication_p.h b/src/widgets/kernel/qapplication_p.h
index 4be35320d9..21b1605dfc 100644
--- a/src/widgets/kernel/qapplication_p.h
+++ b/src/widgets/kernel/qapplication_p.h
@@ -145,9 +145,7 @@ public:
static QWidget *main_widget;
static QWidget *focus_widget;
static QWidget *hidden_focus_widget;
- static QWidget *active_window;
#if QT_CONFIG(wheelevent)
- static int wheel_scroll_lines;
static QPointer<QWidget> wheel_widget;
#endif
@@ -228,6 +226,7 @@ private:
static void giveFocusAccordingToFocusPolicy(QWidget *w, QEvent *event, QPoint localPos);
static bool shouldSetFocus(QWidget *w, Qt::FocusPolicy policy);
+ static QWidget *active_window;
static bool isAlien(QWidget *);
};
diff --git a/src/widgets/kernel/qformlayout.cpp b/src/widgets/kernel/qformlayout.cpp
index e924c71997..01097b6123 100644
--- a/src/widgets/kernel/qformlayout.cpp
+++ b/src/widgets/kernel/qformlayout.cpp
@@ -13,7 +13,7 @@
QT_BEGIN_NAMESPACE
-namespace {
+namespace QtPrivate {
// Fixed column matrix, stores items as [i11, i12, i21, i22...],
// with FORTRAN-style index operator(r, c).
template <class T, int NumColumns>
@@ -68,8 +68,6 @@ void FixedColumnMatrix<T, NumColumns>::storageIndexToPosition(int idx, int *rowP
const uint DefaultFieldGrowthPolicy = 255;
const uint DefaultRowWrapPolicy = 255;
-enum { ColumnCount = 2 };
-
// -- our data structure for our items
// This owns the QLayoutItem
struct QFormLayoutItem
@@ -152,7 +150,7 @@ class QFormLayoutPrivate : public QLayoutPrivate
Q_DECLARE_PUBLIC(QFormLayout)
public:
- typedef FixedColumnMatrix<QFormLayoutItem *, ColumnCount> ItemMatrix;
+ using ItemMatrix = QtPrivate::FixedColumnMatrix<QFormLayoutItem *, 2>;
QFormLayoutPrivate();
~QFormLayoutPrivate() { }
@@ -480,6 +478,7 @@ void QFormLayoutPrivate::recalcHFW(int w)
void QFormLayoutPrivate::setupHfwLayoutData()
{
+ Q_Q(QFormLayout);
// setupVerticalLayoutData must be called before this
// setupHorizontalLayoutData must also be called before this
// copies non hfw data into hfw
@@ -504,6 +503,10 @@ void QFormLayoutPrivate::setupHfwLayoutData()
QFormLayoutItem *label = m_matrix(i, 0);
QFormLayoutItem *field = m_matrix(i, 1);
+ // ignore rows with only hidden items
+ if (!q->isRowVisible(i))
+ continue;
+
if (label && label->vLayoutIndex > -1) {
if (label->isHfw) {
// We don't check sideBySide here, since a label is only
@@ -681,9 +684,15 @@ void QFormLayoutPrivate::setupVerticalLayoutData(int width)
QFormLayoutItem *label = m_matrix(i, 0);
QFormLayoutItem *field = m_matrix(i, 1);
- // Totally ignore empty rows or rows with only hidden items
- if (!q->isRowVisible(i))
+ // Ignore empty rows or rows with only hidden items,
+ // and invalidate their position in the layout.
+ if (!q->isRowVisible(i)) {
+ if (label)
+ label->vLayoutIndex = -1;
+ if (field)
+ field->vLayoutIndex = -1;
continue;
+ }
QSize min1;
QSize min2;
@@ -2190,6 +2199,9 @@ void QFormLayoutPrivate::arrangeWidgets(const QList<QLayoutStruct> &layouts, QRe
QFormLayoutItem *label = m_matrix(i, 0);
QFormLayoutItem *field = m_matrix(i, 1);
+ if (!q->isRowVisible(i))
+ continue;
+
if (label && label->vLayoutIndex > -1) {
int height = layouts.at(label->vLayoutIndex).size;
if ((label->expandingDirections() & Qt::Vertical) == 0) {
diff --git a/src/widgets/kernel/qgesturemanager.cpp b/src/widgets/kernel/qgesturemanager.cpp
index 0108e01e5f..edb159bbbf 100644
--- a/src/widgets/kernel/qgesturemanager.cpp
+++ b/src/widgets/kernel/qgesturemanager.cpp
@@ -50,7 +50,7 @@ static inline int panTouchPoints()
#endif
QGestureManager::QGestureManager(QObject *parent)
- : QObject(parent), state(NotGesture), m_lastCustomGestureId(Qt::CustomGesture)
+ : QObject(parent), m_lastCustomGestureId(Qt::CustomGesture)
{
qRegisterMetaType<Qt::GestureState>();
@@ -98,25 +98,23 @@ void QGestureManager::unregisterGestureRecognizer(Qt::GestureType type)
{
QList<QGestureRecognizer *> list = m_recognizers.values(type);
m_recognizers.remove(type);
- foreach (QGesture *g, m_gestureToRecognizer.keys()) {
- QGestureRecognizer *recognizer = m_gestureToRecognizer.value(g);
+ for (const auto &[g, recognizer] : std::as_const(m_gestureToRecognizer).asKeyValueRange()) {
if (list.contains(recognizer)) {
m_deletedRecognizers.insert(g, recognizer);
}
}
- QMap<ObjectGesture, QList<QGesture *> >::const_iterator iter = m_objectGestures.constBegin();
- while (iter != m_objectGestures.constEnd()) {
- ObjectGesture objectGesture = iter.key();
+ for (const auto &[objectGesture, gestures] : std::as_const(m_objectGestures).asKeyValueRange()) {
if (objectGesture.gesture == type) {
- foreach (QGesture *g, iter.value()) {
- if (QGestureRecognizer *recognizer = m_gestureToRecognizer.value(g)) {
- m_gestureToRecognizer.remove(g);
+ for (QGesture *g : gestures) {
+ auto it = m_gestureToRecognizer.constFind(g);
+ if (it != m_gestureToRecognizer.cend() && it.value()) {
+ QGestureRecognizer *recognizer = it.value();
+ m_gestureToRecognizer.erase(it);
m_obsoleteGestures[recognizer].insert(g);
}
}
}
- ++iter;
}
}
@@ -282,18 +280,18 @@ bool QGestureManager::filterEventThroughContexts(const QMultiMap<QObject *,
}
if (!triggeredGestures.isEmpty() || !finishedGestures.isEmpty()
|| !newMaybeGestures.isEmpty() || !notGestures.isEmpty()) {
- QSet<QGesture *> startedGestures = triggeredGestures - m_activeGestures;
+ const QSet<QGesture *> startedGestures = triggeredGestures - m_activeGestures;
triggeredGestures &= m_activeGestures;
// check if a running gesture switched back to maybe state
- QSet<QGesture *> activeToMaybeGestures = m_activeGestures & newMaybeGestures;
+ const QSet<QGesture *> activeToMaybeGestures = m_activeGestures & newMaybeGestures;
// check if a maybe gesture switched to canceled - reset it but don't send an event
QSet<QGesture *> maybeToCanceledGestures = m_maybeGestures & notGestures;
// check if a running gesture switched back to not gesture state,
// i.e. were canceled
- QSet<QGesture *> canceledGestures = m_activeGestures & notGestures;
+ const QSet<QGesture *> canceledGestures = m_activeGestures & notGestures;
// new gestures in maybe state
m_maybeGestures += newMaybeGestures;
@@ -311,11 +309,11 @@ bool QGestureManager::filterEventThroughContexts(const QMultiMap<QObject *,
Q_ASSERT((finishedGestures & canceledGestures).isEmpty());
Q_ASSERT((canceledGestures & newMaybeGestures).isEmpty());
- QSet<QGesture *> notStarted = finishedGestures - m_activeGestures;
+ const QSet<QGesture *> notStarted = finishedGestures - m_activeGestures;
if (!notStarted.isEmpty()) {
// there are some gestures that claim to be finished, but never started.
// probably those are "singleshot" gestures so we'll fake the started state.
- foreach (QGesture *gesture, notStarted)
+ for (QGesture *gesture : notStarted)
gesture->d_func()->state = Qt::GestureStarted;
QSet<QGesture *> undeliveredGestures;
deliverEvents(notStarted, &undeliveredGestures);
@@ -330,15 +328,15 @@ bool QGestureManager::filterEventThroughContexts(const QMultiMap<QObject *,
m_activeGestures -= canceledGestures;
// set the proper gesture state on each gesture
- foreach (QGesture *gesture, startedGestures)
+ for (QGesture *gesture : startedGestures)
gesture->d_func()->state = Qt::GestureStarted;
- foreach (QGesture *gesture, triggeredGestures)
+ for (QGesture *gesture : std::as_const(triggeredGestures))
gesture->d_func()->state = Qt::GestureUpdated;
- foreach (QGesture *gesture, finishedGestures)
+ for (QGesture *gesture : std::as_const(finishedGestures))
gesture->d_func()->state = Qt::GestureFinished;
- foreach (QGesture *gesture, canceledGestures)
+ for (QGesture *gesture : canceledGestures)
gesture->d_func()->state = Qt::GestureCanceled;
- foreach (QGesture *gesture, activeToMaybeGestures)
+ for (QGesture *gesture : activeToMaybeGestures)
gesture->d_func()->state = Qt::GestureFinished;
if (!m_activeGestures.isEmpty() || !m_maybeGestures.isEmpty() ||
@@ -358,7 +356,7 @@ bool QGestureManager::filterEventThroughContexts(const QMultiMap<QObject *,
deliverEvents(startedGestures+triggeredGestures+finishedGestures+canceledGestures,
&undeliveredGestures);
- foreach (QGesture *g, startedGestures) {
+ for (QGesture *g : startedGestures) {
if (undeliveredGestures.contains(g))
continue;
if (g->gestureCancelPolicy() == QGesture::CancelAllInContext) {
@@ -371,9 +369,9 @@ bool QGestureManager::filterEventThroughContexts(const QMultiMap<QObject *,
m_activeGestures -= undeliveredGestures;
// reset gestures that ended
- QSet<QGesture *> endedGestures =
+ const QSet<QGesture *> endedGestures =
finishedGestures + canceledGestures + undeliveredGestures + maybeToCanceledGestures;
- foreach (QGesture *gesture, endedGestures) {
+ for (QGesture *gesture : endedGestures) {
recycle(gesture);
m_gestureTargets.remove(gesture);
}
@@ -550,7 +548,7 @@ void QGestureManager::getGestureTargets(const QSet<QGesture*> &gestures,
GestureByTypes gestureByTypes;
// sort gestures by types
- foreach (QGesture *gesture, gestures) {
+ for (QGesture *gesture : gestures) {
QWidget *receiver = m_gestureTargets.value(gesture, nullptr);
Q_ASSERT(receiver);
if (receiver)
@@ -612,7 +610,8 @@ void QGestureManager::deliverEvents(const QSet<QGesture *> &gestures,
QWidget *child = topLevel->childAt(topLevel->mapFromGlobal(pt));
target = child ? child : topLevel;
}
- } else {
+ }
+ if (!target) {
// or use the context of the gesture
QObject *context = m_gestureOwners.value(gesture, 0);
if (context->isWidgetType())
@@ -651,7 +650,7 @@ void QGestureManager::deliverEvents(const QSet<QGesture *> &gestures,
for (GesturesPerWidget::const_iterator it = conflictedGestures.constBegin(),
e = conflictedGestures.constEnd(); it != e; ++it) {
QWidget *receiver = it.key();
- QList<QGesture *> gestures = it.value();
+ const QList<QGesture *> &gestures = it.value();
qCDebug(lcGestureManager) << "QGestureManager::deliverEvents: sending GestureOverride to"
<< receiver
<< "gestures:" << gestures;
@@ -659,7 +658,7 @@ void QGestureManager::deliverEvents(const QSet<QGesture *> &gestures,
event.t = QEvent::GestureOverride;
// mark event and individual gestures as ignored
event.ignore();
- foreach(QGesture *g, gestures)
+ for (QGesture *g : gestures)
event.setAccepted(g, false);
QCoreApplication::sendEvent(receiver, &event);
diff --git a/src/widgets/kernel/qgesturemanager_p.h b/src/widgets/kernel/qgesturemanager_p.h
index 1bf1358b13..02beb024f9 100644
--- a/src/widgets/kernel/qgesturemanager_p.h
+++ b/src/widgets/kernel/qgesturemanager_p.h
@@ -21,6 +21,8 @@
#include "private/qwidget_p.h"
#include "qgesturerecognizer.h"
+#include <QtCore/qpointer.h>
+
#ifndef QT_NO_GESTURES
#include <functional>
@@ -64,14 +66,6 @@ private:
QSet<QGesture *> m_activeGestures;
QSet<QGesture *> m_maybeGestures;
- enum State {
- Gesture,
- NotGesture,
- MaybeGesture // this means timers are up and waiting for some
- // more events, and input events are handled by
- // gesture recognizer explicitly
- } state;
-
struct ObjectGesture
{
QObject* object;
diff --git a/src/widgets/kernel/qlayout.cpp b/src/widgets/kernel/qlayout.cpp
index 7639803c8b..a826ea75bc 100644
--- a/src/widgets/kernel/qlayout.cpp
+++ b/src/widgets/kernel/qlayout.cpp
@@ -57,14 +57,13 @@ static int menuBarHeightForWidth(QWidget *menubar, int w)
resized to zero size if there is too little space. To support
children whose heights depend on their widths, implement
hasHeightForWidth() and heightForWidth(). See the
- \l{layouts/borderlayout}{Border Layout} and
- \l{layouts/flowlayout}{Flow Layout} examples for
+ \l{layouts/flowlayout}{Flow Layout} example for
more information about implementing custom layout managers.
Geometry management stops when the layout manager is deleted.
\sa QLayoutItem, {Layout Management}, {Basic Layouts Example},
- {Border Layout Example}, {Flow Layout Example}
+ {Flow Layout Example}
*/
@@ -521,10 +520,11 @@ void QLayoutPrivate::doResize()
void QLayout::widgetEvent(QEvent *e)
{
Q_D(QLayout);
- if (!d->enabled)
+ const QEvent::Type type = e->type();
+ if (!d->enabled && type != QEvent::ChildRemoved)
return;
- switch (e->type()) {
+ switch (type) {
case QEvent::Resize:
if (d->activated)
d->doResize();
@@ -773,7 +773,7 @@ void QLayoutPrivate::reparentChildWidgets(QWidget *mw)
w->metaObject()->className(), qUtf16Printable(w->objectName()));
}
#endif
- bool needShow = mwVisible && !(w->isHidden() && w->testAttribute(Qt::WA_WState_ExplicitShowHide));
+ bool needShow = mwVisible && !QWidgetPrivate::get(w)->isExplicitlyHidden();
if (pw != mw)
w->setParent(mw);
if (needShow)
@@ -859,7 +859,7 @@ void QLayout::addChildWidget(QWidget *w)
#endif
pw = nullptr;
}
- bool needShow = mw && mw->isVisible() && !(w->isHidden() && w->testAttribute(Qt::WA_WState_ExplicitShowHide));
+ bool needShow = mw && mw->isVisible() && !QWidgetPrivate::get(w)->isExplicitlyHidden();
if (!pw && mw)
w->setParent(mw);
w->setAttribute(Qt::WA_LaidOut);
@@ -1259,7 +1259,7 @@ QLayout::SizeConstraint QLayout::sizeConstraint() const
this layout is set to \a r, provided that this layout supports
setAlignment().
- The result is derived from sizeHint() and expanding(). It is never
+ The result is derived from sizeHint() and expandingDirections(). It is never
larger than \a r.
*/
QRect QLayout::alignmentRect(const QRect &r) const
diff --git a/src/widgets/kernel/qlayoutitem.cpp b/src/widgets/kernel/qlayoutitem.cpp
index eb53a3a120..246d090828 100644
--- a/src/widgets/kernel/qlayoutitem.cpp
+++ b/src/widgets/kernel/qlayoutitem.cpp
@@ -52,7 +52,7 @@ inline static QSize toLayoutItemSize(QWidgetPrivate *priv, const QSize &size)
Pure virtual functions are provided to return information about
the layout, including, sizeHint(), minimumSize(), maximumSize()
- and expanding().
+ and expandingDirections().
The layout's geometry can be set and retrieved with setGeometry()
and geometry(), and its alignment with setAlignment() and
diff --git a/src/widgets/kernel/qrhiwidget.cpp b/src/widgets/kernel/qrhiwidget.cpp
new file mode 100644
index 0000000000..bf56263113
--- /dev/null
+++ b/src/widgets/kernel/qrhiwidget.cpp
@@ -0,0 +1,1309 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#include "qrhiwidget_p.h"
+#include <private/qguiapplication_p.h>
+#include <qpa/qplatformintegration.h>
+#include <private/qwidgetrepaintmanager_p.h>
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QRhiWidget
+ \inmodule QtWidgets
+ \since 6.7
+
+ \brief The QRhiWidget class is a widget for rendering 3D graphics via an
+ accelerated grapics API, such as Vulkan, Metal, or Direct 3D.
+
+ \preliminary
+
+ \note QRhiWidget is in tech preview in Qt 6.7. \b {The API is under
+ development and subject to change.}
+
+ QRhiWidget provides functionality for displaying 3D content rendered
+ through the \l QRhi APIs within a QWidget-based application. In many ways
+ it is the portable equivalent of \l QOpenGLWidget that is not tied to a
+ single 3D graphics API, but rather can function with all the APIs QRhi
+ supports (such as, Direct 3D 11/12, Vulkan, Metal, and OpenGL).
+
+ QRhiWidget is expected to be subclassed. To render into the 2D texture that
+ is implicitly created and managed by the QRhiWidget, subclasses should
+ reimplement the virtual functions initialize() and render().
+
+ The size of the texture will by default adapt to the size of the widget. If
+ a fixed size is preferred, set a fixed size specified in pixels by calling
+ setFixedColorBufferSize().
+
+ In addition to the texture serving as the color buffer, a depth/stencil
+ buffer and a render target binding these together is maintained implicitly
+ as well.
+
+ The QRhi for the widget's top-level window is configured to use a
+ platform-specific backend and graphics API by default: Metal on macOS and
+ iOS, Direct 3D 11 on Windows, OpenGL otherwise. Call setApi() to override
+ this.
+
+ \note A single widget window can only use one QRhi backend, and so one
+ single 3D graphics API. If two QRhiWidget or QQuickWidget widgets in the
+ window's widget hierarchy request different APIs, only one of them will
+ function correctly.
+
+ \note While QRhiWidget is a public Qt API, the QRhi family of classes in
+ the Qt Gui module, including QRhi, QShader and QShaderDescription, offer
+ limited compatibility guarantees. There are no source or binary
+ compatibility guarantees for these classes, meaning the API is only
+ guaranteed to work with the Qt version the application was developed
+ against. Source incompatible changes are however aimed to be kept at a
+ minimum and will only be made in minor releases (6.7, 6.8, and so on).
+ \c{qrhiwidget.h} does not directly include any QRhi-related headers. To use
+ those classes when implementing a QRhiWidget subclass, link to
+ \c{Qt::GuiPrivate} (if using CMake), and include the appropriate headers
+ with the \c rhi prefix, for example \c{#include <rhi/qrhi.h>}.
+
+ An example of a simple QRhiWidget subclass rendering a triangle is the
+ following:
+
+ \snippet qrhiwidget/rhiwidgetintro.cpp 0
+
+ This is a widget that continuously requests updates, throttled by the
+ presentation rate (vsync, depending on the screen refresh rate). If
+ rendering continuously is not desired, the update() call in render() should
+ be removed, and rather issued only when updating the rendered content is
+ necessary. For example, if the rotation of the cube should be tied to the
+ value of a QSlider, then connecting the slider's value change signal to a
+ slot or lambda that forwards the new value and calls update() is
+ sufficient.
+
+ The vertex and fragment shaders are provided as Vulkan-style GLSL and must
+ be processed first by the Qt shader infrastructure first. This is achieved
+ either by running the \c qsb command-line tool manually, or by using the
+ \l{Qt Shader Tools Build System Integration}{qt_add_shaders()} function in
+ CMake. The QRhiWidget implementation loads these pre-processed \c{.qsb}
+ files that are shipped with the application. See \l{Qt Shader Tools} for
+ more information about Qt's shader translation infrastructure.
+
+ The source code for these shaders could be the following:
+
+ \c{color.vert}
+
+ \snippet qrhiwidget/rhiwidgetintro.vert 0
+
+ \c{color.frag}
+
+ \snippet qrhiwidget/rhiwidgetintro.frag 0
+
+ The result is a widget that shows the following:
+
+ \image qrhiwidget-intro.jpg
+
+ For a complete, minimal, introductory example check out the \l{Simple RHI
+ Widget Example}.
+
+ For an example with more functionality and demonstration of further
+ concepts, see the \l{Cube RHI Widget Example}.
+
+ QRhiWidget always involves rendering into a backing texture, not
+ directly to the window (the surface or layer provided by the windowing
+ system for the native window). This allows properly compositing the content
+ with the rest of the widget-based UI, and offering a simple and compact
+ API, making it easy to get started. All this comes at the expense of
+ additional resources and a potential effect on performance. This is often
+ perfectly acceptable in practice, but advanced users should keep in mind
+ the pros and cons of the different approaches. Refer to the \l{RHI Window
+ Example} and compare it with the \l{Simple RHI Widget Example} for details
+ about the two approaches.
+
+ Reparenting a QRhiWidget into a widget hierarchy that belongs to a
+ different window (top-level widget), or making the QRhiWidget itself a
+ top-level (by setting the parent to \nullptr), involves changing the
+ associated QRhi (and potentially destroying the old one) while the
+ QRhiWidget continues to stay alive and well. To support this, robust
+ QRhiWidget implementations are expected to reimplement the
+ releaseResources() virtual function as well, and drop their QRhi resources
+ just as they do in the destructor. The \l{Cube RHI Widget Example}
+ demonstrates this in practice.
+
+ While not a primary use case, QRhiWidget also allows incorporating
+ rendering code that directly uses a 3D graphics API such as Vulkan, Metal,
+ Direct 3D, or OpenGL. See \l QRhiCommandBuffer::beginExternal() for details
+ on recording native commands within a QRhi render pass, as well as
+ \l QRhiTexture::createFrom() for a way to wrap an existing native texture and
+ then use it with QRhi in a subsequent render pass. Note however that the
+ configurability of the underlying graphics API (its device or context
+ features, layers, extensions, etc.) is going to be limited since
+ QRhiWidget's primary goal is to provide an environment suitable for
+ QRhi-based rendering code, not to enable arbitrary, potentially complex,
+ foreign rendering engines.
+
+ \since 6.7
+
+ \sa QRhi, QShader, QOpenGLWidget, {Simple RHI Widget Example}, {Cube RHI Widget Example}
+ */
+
+/*!
+ \enum QRhiWidget::Api
+ Specifies the 3D API and QRhi backend to use
+
+ \value Null
+ \value OpenGL
+ \value Metal
+ \value Vulkan
+ \value Direct3D11
+ \value Direct3D12
+
+ \sa QRhi
+ */
+
+/*!
+ \enum QRhiWidget::TextureFormat
+ Specifies the format of the texture to which the QRhiWidget renders.
+
+ \value RGBA8 See QRhiTexture::RGBA8.
+ \value RGBA16F See QRhiTexture::RGBA16F.
+ \value RGBA32F See QRhiTexture::RGBA32F.
+ \value RGB10A2 See QRhiTexture::RGB10A2.
+
+ \sa QRhiTexture
+ */
+
+/*!
+ Constructs a widget which is a child of \a parent, with widget flags set to \a f.
+ */
+QRhiWidget::QRhiWidget(QWidget *parent, Qt::WindowFlags f)
+ : QWidget(*(new QRhiWidgetPrivate), parent, f)
+{
+ Q_D(QRhiWidget);
+ if (Q_UNLIKELY(!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RhiBasedRendering)))
+ qWarning("QRhiWidget: QRhi is not supported on this platform.");
+ else
+ d->setRenderToTexture();
+
+ d->config.setEnabled(true);
+#if defined(Q_OS_DARWIN)
+ d->config.setApi(QPlatformBackingStoreRhiConfig::Metal);
+#elif defined(Q_OS_WIN)
+ d->config.setApi(QPlatformBackingStoreRhiConfig::D3D11);
+#else
+ d->config.setApi(QPlatformBackingStoreRhiConfig::OpenGL);
+#endif
+}
+
+/*!
+ Destructor.
+ */
+QRhiWidget::~QRhiWidget()
+{
+ Q_D(QRhiWidget);
+
+ if (d->rhi) {
+ d->rhi->removeCleanupCallback(this);
+ // rhi resources must be destroyed here, due to how QWidget teardown works;
+ // it should not be left to the private object's destruction.
+ d->resetRenderTargetObjects();
+ d->resetColorBufferObjects();
+ qDeleteAll(d->pendingDeletes);
+ }
+
+ d->offscreenRenderer.reset();
+}
+
+/*!
+ Handles resize events that are passed in the \a e event parameter. Calls
+ the virtual function initialize().
+
+ \note Avoid overriding this function in derived classes. If that is not
+ feasible, make sure that QRhiWidget's implementation is invoked too.
+ Otherwise the underlying texture object and related resources will not get
+ resized properly and will lead to incorrect rendering.
+ */
+void QRhiWidget::resizeEvent(QResizeEvent *e)
+{
+ Q_D(QRhiWidget);
+
+ if (e->size().isEmpty()) {
+ d->noSize = true;
+ return;
+ }
+ d->noSize = false;
+
+ d->sendPaintEvent(QRect(QPoint(0, 0), size()));
+}
+
+/*!
+ Handles paint events.
+
+ Calling QWidget::update() will lead to sending a paint event \a e, and thus
+ invoking this function. The sending of the event is asynchronous and will
+ happen at some point after returning from update(). This function will
+ then, after some preparation, call the virtual render() to update the
+ contents of the QRhiWidget's associated texture. The widget's top-level
+ window will then composite the texture with the rest of the window.
+ */
+void QRhiWidget::paintEvent(QPaintEvent *)
+{
+ Q_D(QRhiWidget);
+ if (!updatesEnabled() || d->noSize)
+ return;
+
+ d->ensureRhi();
+ if (!d->rhi) {
+ qWarning("QRhiWidget: No QRhi");
+ emit renderFailed();
+ return;
+ }
+
+ QRhiCommandBuffer *cb = nullptr;
+ if (d->rhi->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess)
+ return;
+
+ bool needsInit = false;
+ d->ensureTexture(&needsInit);
+ if (d->colorTexture || d->msaaColorBuffer) {
+ bool canRender = true;
+ if (needsInit)
+ canRender = d->invokeInitialize(cb);
+ if (canRender)
+ render(cb);
+ }
+
+ d->rhi->endOffscreenFrame();
+}
+
+/*!
+ \reimp
+*/
+bool QRhiWidget::event(QEvent *e)
+{
+ Q_D(QRhiWidget);
+ switch (e->type()) {
+ case QEvent::WindowAboutToChangeInternal:
+ // The QRhi will almost certainly change, prevent texture() from
+ // returning the existing QRhiTexture in the meantime.
+ d->textureInvalid = true;
+
+ if (d->rhi && d->rhi != d->offscreenRenderer.rhi()) {
+ // Drop the cleanup callback registered to the toplevel's rhi and
+ // do the early-release, there may not be another chance to do
+ // this, and the QRhi we have currently set may be destroyed by the
+ // time we get to ensureRhi() again.
+ d->rhi->removeCleanupCallback(this);
+ releaseResources(); // notify the user code about the early-release
+ d->releaseResources();
+ // must _not_ null out d->rhi here, for proper interaction with ensureRhi()
+ }
+
+ break;
+
+ case QEvent::Show:
+ if (isVisible())
+ d->sendPaintEvent(QRect(QPoint(0, 0), size()));
+ break;
+ default:
+ break;
+ }
+ return QWidget::event(e);
+}
+
+QWidgetPrivate::TextureData QRhiWidgetPrivate::texture() const
+{
+ // This is the only safe place to clear pendingDeletes, due to the
+ // possibility of the texture returned in the previous invocation of this
+ // function having been added to pendingDeletes, meaning the object then
+ // needs to be valid until the next (this) invocation of this function.
+ // (the exact object lifetime requirements depend on the
+ // QWidget/RepaintManager internal implementation; for now avoid relying on
+ // such details by clearing pendingDeletes only here, not in endCompose())
+ qDeleteAll(pendingDeletes);
+ pendingDeletes.clear();
+
+ TextureData td;
+ if (!textureInvalid)
+ td.textureLeft = resolveTexture ? resolveTexture : colorTexture;
+ return td;
+}
+
+QPlatformTextureList::Flags QRhiWidgetPrivate::textureListFlags()
+{
+ QPlatformTextureList::Flags flags = QWidgetPrivate::textureListFlags();
+ if (mirrorVertically)
+ flags |= QPlatformTextureList::MirrorVertically;
+ return flags;
+}
+
+QPlatformBackingStoreRhiConfig QRhiWidgetPrivate::rhiConfig() const
+{
+ return config;
+}
+
+void QRhiWidgetPrivate::endCompose()
+{
+ // This function is called by QWidgetRepaintManager right after the
+ // backingstore's QRhi-based flush returns. In practice that means after
+ // the begin-endFrame() on the top-level window's swapchain.
+
+ if (rhi) {
+ Q_Q(QRhiWidget);
+ emit q->frameSubmitted();
+ }
+}
+
+// This is reimplemented to enable calling QWidget::grab() on the widget or an
+// ancestor of it. At the same time, QRhiWidget provides its own
+// grabFramebuffer() as well, mirroring QQuickWidget and QOpenGLWidget for
+// consistency. In both types of grabs we end up in here.
+QImage QRhiWidgetPrivate::grabFramebuffer()
+{
+ Q_Q(QRhiWidget);
+ if (noSize)
+ return QImage();
+
+ ensureRhi();
+ if (!rhi) {
+ // The widget (and its parent chain, if any) may not be shown at
+ // all, yet one may still want to use it for grabs. This is
+ // ridiculous of course because the rendering infrastructure is
+ // tied to the top-level widget that initializes upon expose, but
+ // it has to be supported.
+ offscreenRenderer.setConfig(config);
+ // no window passed in, so no swapchain, but we get a functional QRhi which we own
+ offscreenRenderer.create();
+ rhi = offscreenRenderer.rhi();
+ if (!rhi) {
+ qWarning("QRhiWidget: Failed to create dedicated QRhi for grabbing");
+ emit q->renderFailed();
+ return QImage();
+ }
+ }
+
+ QRhiCommandBuffer *cb = nullptr;
+ if (rhi->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess)
+ return QImage();
+
+ QRhiReadbackResult readResult;
+ bool readCompleted = false;
+ bool needsInit = false;
+ ensureTexture(&needsInit);
+
+ if (colorTexture || msaaColorBuffer) {
+ bool canRender = true;
+ if (needsInit)
+ canRender = invokeInitialize(cb);
+ if (canRender)
+ q->render(cb);
+
+ QRhiResourceUpdateBatch *readbackBatch = rhi->nextResourceUpdateBatch();
+ readResult.completed = [&readCompleted] { readCompleted = true; };
+ readbackBatch->readBackTexture(resolveTexture ? resolveTexture : colorTexture, &readResult);
+ cb->resourceUpdate(readbackBatch);
+ }
+
+ rhi->endOffscreenFrame();
+
+ if (readCompleted) {
+ QImage::Format imageFormat = QImage::Format_RGBA8888;
+ switch (widgetTextureFormat) {
+ case QRhiWidget::TextureFormat::RGBA8:
+ break;
+ case QRhiWidget::TextureFormat::RGBA16F:
+ imageFormat = QImage::Format_RGBA16FPx4;
+ break;
+ case QRhiWidget::TextureFormat::RGBA32F:
+ imageFormat = QImage::Format_RGBA32FPx4;
+ break;
+ case QRhiWidget::TextureFormat::RGB10A2:
+ imageFormat = QImage::Format_BGR30;
+ break;
+ }
+ QImage wrapperImage(reinterpret_cast<const uchar *>(readResult.data.constData()),
+ readResult.pixelSize.width(), readResult.pixelSize.height(),
+ imageFormat);
+ QImage result;
+ if (rhi->isYUpInFramebuffer())
+ result = wrapperImage.mirrored();
+ else
+ result = wrapperImage.copy();
+ result.setDevicePixelRatio(q->devicePixelRatio());
+ return result;
+ } else {
+ Q_UNREACHABLE();
+ }
+
+ return QImage();
+}
+
+void QRhiWidgetPrivate::resetColorBufferObjects()
+{
+ if (colorTexture) {
+ pendingDeletes.append(colorTexture);
+ colorTexture = nullptr;
+ }
+ if (msaaColorBuffer) {
+ pendingDeletes.append(msaaColorBuffer);
+ msaaColorBuffer = nullptr;
+ }
+ if (resolveTexture) {
+ pendingDeletes.append(resolveTexture);
+ resolveTexture = nullptr;
+ }
+}
+
+void QRhiWidgetPrivate::resetRenderTargetObjects()
+{
+ if (renderTarget) {
+ renderTarget->deleteLater();
+ renderTarget = nullptr;
+ }
+ if (renderPassDescriptor) {
+ renderPassDescriptor->deleteLater();
+ renderPassDescriptor = nullptr;
+ }
+ if (depthStencilBuffer) {
+ depthStencilBuffer->deleteLater();
+ depthStencilBuffer = nullptr;
+ }
+}
+
+void QRhiWidgetPrivate::releaseResources()
+{
+ resetRenderTargetObjects();
+ resetColorBufferObjects();
+ qDeleteAll(pendingDeletes);
+ pendingDeletes.clear();
+}
+
+void QRhiWidgetPrivate::ensureRhi()
+{
+ Q_Q(QRhiWidget);
+ QRhi *currentRhi = QWidgetPrivate::rhi();
+ if (currentRhi && currentRhi->backend() != QBackingStoreRhiSupport::apiToRhiBackend(config.api())) {
+ qWarning("The top-level window is already using another graphics API for composition, "
+ "'%s' is not compatible with this widget",
+ currentRhi->backendName());
+ return;
+ }
+
+ // NB the rhi member may be an invalid object, the pointer can be used, but no deref
+ if (currentRhi && rhi != currentRhi) {
+ if (rhi) {
+ // if previously we created our own but now get a QRhi from the
+ // top-level, then drop what we have and start using the top-level's
+ if (rhi == offscreenRenderer.rhi()) {
+ q->releaseResources(); // notify the user code about the early-release
+ releaseResources();
+ offscreenRenderer.reset();
+ } else {
+ // rhi resources created by us all belong to the old rhi, drop them;
+ // due to nulling out colorTexture this is also what ensures that
+ // initialize() is going to be called again eventually
+ resetRenderTargetObjects();
+ resetColorBufferObjects();
+ }
+ }
+
+ // Normally the widget gets destroyed before the QRhi (which is managed by
+ // the top-level's backingstore). When reparenting between top-levels is
+ // involved, that is not always the case. Therefore we use a per-widget rhi
+ // cleanup callback to get notified when the QRhi is about to be destroyed
+ // while the QRhiWidget is still around.
+ currentRhi->addCleanupCallback(q, [q, this](QRhi *regRhi) {
+ if (!QWidgetPrivate::get(q)->data.in_destructor && this->rhi == regRhi) {
+ q->releaseResources(); // notify the user code about the early-release
+ releaseResources();
+ // must null out our ref, the QRhi object is going to be invalid
+ this->rhi = nullptr;
+ }
+ });
+ }
+
+ rhi = currentRhi;
+}
+
+void QRhiWidgetPrivate::ensureTexture(bool *changed)
+{
+ Q_Q(QRhiWidget);
+
+ QSize newSize = fixedSize;
+ if (newSize.isEmpty())
+ newSize = q->size() * q->devicePixelRatio();
+
+ const int minTexSize = rhi->resourceLimit(QRhi::TextureSizeMin);
+ const int maxTexSize = rhi->resourceLimit(QRhi::TextureSizeMax);
+ newSize.setWidth(qMin(maxTexSize, qMax(minTexSize, newSize.width())));
+ newSize.setHeight(qMin(maxTexSize, qMax(minTexSize, newSize.height())));
+
+ if (colorTexture) {
+ if (colorTexture->format() != rhiTextureFormat || colorTexture->sampleCount() != samples) {
+ resetColorBufferObjects();
+ // sample count change needs new depth-stencil, possibly a new
+ // render target; format change needs new renderpassdescriptor;
+ // therefore must drop the rest too
+ resetRenderTargetObjects();
+ }
+ }
+
+ if (msaaColorBuffer) {
+ if (msaaColorBuffer->backingFormat() != rhiTextureFormat || msaaColorBuffer->sampleCount() != samples) {
+ resetColorBufferObjects();
+ // sample count change needs new depth-stencil, possibly a new
+ // render target; format change needs new renderpassdescriptor;
+ // therefore must drop the rest too
+ resetRenderTargetObjects();
+ }
+ }
+
+ if (!colorTexture && samples <= 1) {
+ if (changed)
+ *changed = true;
+ if (!rhi->isTextureFormatSupported(rhiTextureFormat)) {
+ qWarning("QRhiWidget: The requested texture format (%d) is not supported by the "
+ "underlying 3D graphics API implementation", int(rhiTextureFormat));
+ }
+ colorTexture = rhi->newTexture(rhiTextureFormat, newSize, samples, QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource);
+ if (!colorTexture->create()) {
+ qWarning("Failed to create backing texture for QRhiWidget");
+ delete colorTexture;
+ colorTexture = nullptr;
+ return;
+ }
+ }
+
+ if (samples > 1) {
+ if (!msaaColorBuffer) {
+ if (changed)
+ *changed = true;
+ if (!rhi->isFeatureSupported(QRhi::MultisampleRenderBuffer)) {
+ qWarning("QRhiWidget: Multisample renderbuffers are reported as unsupported; "
+ "sample count %d will not work as expected", samples);
+ }
+ if (!rhi->isTextureFormatSupported(rhiTextureFormat)) {
+ qWarning("QRhiWidget: The requested texture format (%d) is not supported by the "
+ "underlying 3D graphics API implementation", int(rhiTextureFormat));
+ }
+ msaaColorBuffer = rhi->newRenderBuffer(QRhiRenderBuffer::Color, newSize, samples, {}, rhiTextureFormat);
+ if (!msaaColorBuffer->create()) {
+ qWarning("Failed to create multisample color buffer for QRhiWidget");
+ delete msaaColorBuffer;
+ msaaColorBuffer = nullptr;
+ return;
+ }
+ }
+ if (!resolveTexture) {
+ if (changed)
+ *changed = true;
+ resolveTexture = rhi->newTexture(rhiTextureFormat, newSize, 1, QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource);
+ if (!resolveTexture->create()) {
+ qWarning("Failed to create resolve texture for QRhiWidget");
+ delete resolveTexture;
+ resolveTexture = nullptr;
+ return;
+ }
+ }
+ } else if (resolveTexture) {
+ resolveTexture->deleteLater();
+ resolveTexture = nullptr;
+ }
+
+ if (colorTexture && colorTexture->pixelSize() != newSize) {
+ if (changed)
+ *changed = true;
+ colorTexture->setPixelSize(newSize);
+ if (!colorTexture->create())
+ qWarning("Failed to rebuild texture for QRhiWidget after resizing");
+ }
+
+ if (msaaColorBuffer && msaaColorBuffer->pixelSize() != newSize) {
+ if (changed)
+ *changed = true;
+ msaaColorBuffer->setPixelSize(newSize);
+ if (!msaaColorBuffer->create())
+ qWarning("Failed to rebuild multisample color buffer for QRhiWidget after resizing");
+ }
+
+ if (resolveTexture && resolveTexture->pixelSize() != newSize) {
+ if (changed)
+ *changed = true;
+ resolveTexture->setPixelSize(newSize);
+ if (!resolveTexture->create())
+ qWarning("Failed to rebuild resolve texture for QRhiWidget after resizing");
+ }
+
+ textureInvalid = false;
+}
+
+bool QRhiWidgetPrivate::invokeInitialize(QRhiCommandBuffer *cb)
+{
+ Q_Q(QRhiWidget);
+ if (!colorTexture && !msaaColorBuffer)
+ return false;
+
+ if (autoRenderTarget) {
+ const QSize pixelSize = colorTexture ? colorTexture->pixelSize() : msaaColorBuffer->pixelSize();
+ if (!depthStencilBuffer) {
+ depthStencilBuffer = rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, pixelSize, samples);
+ if (!depthStencilBuffer->create()) {
+ qWarning("Failed to create depth-stencil buffer for QRhiWidget");
+ resetRenderTargetObjects();
+ return false;
+ }
+ } else if (depthStencilBuffer->pixelSize() != pixelSize) {
+ depthStencilBuffer->setPixelSize(pixelSize);
+ if (!depthStencilBuffer->create()) {
+ qWarning("Failed to rebuild depth-stencil buffer for QRhiWidget with new size");
+ return false;
+ }
+ }
+
+ if (!renderTarget) {
+ QRhiColorAttachment color0;
+ if (colorTexture)
+ color0.setTexture(colorTexture);
+ else
+ color0.setRenderBuffer(msaaColorBuffer);
+ if (samples > 1)
+ color0.setResolveTexture(resolveTexture);
+ QRhiTextureRenderTargetDescription rtDesc(color0, depthStencilBuffer);
+ renderTarget = rhi->newTextureRenderTarget(rtDesc);
+ renderPassDescriptor = renderTarget->newCompatibleRenderPassDescriptor();
+ renderTarget->setRenderPassDescriptor(renderPassDescriptor);
+ if (!renderTarget->create()) {
+ qWarning("Failed to create render target for QRhiWidget");
+ resetRenderTargetObjects();
+ return false;
+ }
+ }
+ } else {
+ resetRenderTargetObjects();
+ }
+
+ q->initialize(cb);
+
+ return true;
+}
+
+/*!
+ \return the currently set graphics API (QRhi backend).
+
+ \sa setApi()
+ */
+QRhiWidget::Api QRhiWidget::api() const
+{
+ Q_D(const QRhiWidget);
+ switch (d->config.api()) {
+ case QPlatformBackingStoreRhiConfig::OpenGL:
+ return Api::OpenGL;
+ case QPlatformBackingStoreRhiConfig::Metal:
+ return Api::Metal;
+ case QPlatformBackingStoreRhiConfig::Vulkan:
+ return Api::Vulkan;
+ case QPlatformBackingStoreRhiConfig::D3D11:
+ return Api::Direct3D11;
+ case QPlatformBackingStoreRhiConfig::D3D12:
+ return Api::Direct3D12;
+ case QPlatformBackingStoreRhiConfig::Null:
+ return Api::Null;
+ }
+ Q_UNREACHABLE_RETURN(Api::Null);
+}
+
+/*!
+ Sets the graphics API and QRhi backend to use to \a api.
+
+ \warning This function must be called early enough, before the widget is
+ added to a widget hierarchy and displayed on screen. For example, aim to
+ call the function for the subclass constructor. If called too late, the
+ function will have no effect.
+
+ The default value depends on the platform: Metal on macOS and iOS, Direct
+ 3D 11 on Windows, OpenGL otherwise.
+
+ The \a api can only be set once for the widget and its top-level window,
+ once it is done and takes effect, the window can only use that API and QRhi
+ backend to render. Attempting to set another value, or to add another
+ QRhiWidget with a different \a api will not function as expected.
+
+ \sa setColorBufferFormat(), setDebugLayerEnabled(), api()
+ */
+void QRhiWidget::setApi(Api api)
+{
+ Q_D(QRhiWidget);
+ switch (api) {
+ case Api::OpenGL:
+ d->config.setApi(QPlatformBackingStoreRhiConfig::OpenGL);
+ break;
+ case Api::Metal:
+ d->config.setApi(QPlatformBackingStoreRhiConfig::Metal);
+ break;
+ case Api::Vulkan:
+ d->config.setApi(QPlatformBackingStoreRhiConfig::Vulkan);
+ break;
+ case Api::Direct3D11:
+ d->config.setApi(QPlatformBackingStoreRhiConfig::D3D11);
+ break;
+ case Api::Direct3D12:
+ d->config.setApi(QPlatformBackingStoreRhiConfig::D3D12);
+ break;
+ case Api::Null:
+ d->config.setApi(QPlatformBackingStoreRhiConfig::Null);
+ break;
+ }
+}
+
+/*!
+ \return true if a debug or validation layer will be requested if applicable
+ to the graphics API in use.
+
+ \sa setDebugLayerEnabled()
+ */
+bool QRhiWidget::isDebugLayerEnabled() const
+{
+ Q_D(const QRhiWidget);
+ return d->config.isDebugLayerEnabled();
+}
+
+/*!
+ Requests the debug or validation layer of the underlying graphics API
+ when \a enable is true.
+
+ \warning This function must be called early enough, before the widget is added
+ to a widget hierarchy and displayed on screen. For example, aim to call the
+ function for the subclass constructor. If called too late, the function
+ will have no effect.
+
+ Applicable for Vulkan and Direct 3D.
+
+ By default this is disabled.
+
+ \sa setApi(), isDebugLayerEnabled()
+ */
+void QRhiWidget::setDebugLayerEnabled(bool enable)
+{
+ Q_D(QRhiWidget);
+ d->config.setDebugLayer(enable);
+}
+
+/*!
+ \property QRhiWidget::colorBufferFormat
+
+ This property controls the texture format of the texture (or renderbuffer)
+ used as the color buffer. The default value is TextureFormat::RGBA8.
+ QRhiWidget supports rendering to a subset of the formats supported by \l
+ QRhiTexture. Only formats that are reported as supported from \l
+ QRhi::isTextureFormatSupported() should be specified, rendering will not be
+ functional otherwise.
+
+ \note Setting a new format when the widget is already initialized and has
+ rendered implies that all QRhiGraphicsPipeline objects created by the
+ renderer may become unusable, if the associated QRhiRenderPassDescriptor is
+ now incompatible due to the different texture format. Similarly to changing
+ \l sampleCount dynamically, this means that initialize() or render()
+ implementations must then take care of releasing the existing pipelines and
+ creating new ones.
+ */
+
+QRhiWidget::TextureFormat QRhiWidget::colorBufferFormat() const
+{
+ Q_D(const QRhiWidget);
+ return d->widgetTextureFormat;
+}
+
+void QRhiWidget::setColorBufferFormat(TextureFormat format)
+{
+ Q_D(QRhiWidget);
+ if (d->widgetTextureFormat != format) {
+ d->widgetTextureFormat = format;
+ switch (format) {
+ case TextureFormat::RGBA8:
+ d->rhiTextureFormat = QRhiTexture::RGBA8;
+ break;
+ case TextureFormat::RGBA16F:
+ d->rhiTextureFormat = QRhiTexture::RGBA16F;
+ break;
+ case TextureFormat::RGBA32F:
+ d->rhiTextureFormat = QRhiTexture::RGBA32F;
+ break;
+ case TextureFormat::RGB10A2:
+ d->rhiTextureFormat = QRhiTexture::RGB10A2;
+ break;
+ }
+ emit colorBufferFormatChanged(format);
+ update();
+ }
+}
+
+/*!
+ \property QRhiWidget::sampleCount
+
+ This property controls for sample count for multisample antialiasing.
+ By default the value is \c 1 which means MSAA is disabled.
+
+ Valid values are 1, 4, 8, and sometimes 16 and 32.
+ \l QRhi::supportedSampleCounts() can be used to query the supported sample
+ counts at run time, but typically applications should request 1 (no MSAA),
+ 4x (normal MSAA) or 8x (high MSAA).
+
+ \note Setting a new value implies that all QRhiGraphicsPipeline objects
+ created by the renderer must use the same sample count from then on.
+ Existing QRhiGraphicsPipeline objects created with a different sample count
+ must not be used anymore. When the value changes, all color and
+ depth-stencil buffers are destroyed and recreated automatically, and
+ initialize() is invoked again. However, when
+ \l autoRenderTarget is \c false, it will be up to the application to
+ manage this with regards to the depth-stencil buffer or additional color
+ buffers.
+
+ Changing the sample count from the default 1 to a higher value implies that
+ colorTexture() becomes \nullptr and msaaColorBuffer() starts returning a
+ valid object. Switching back to 1 (or 0), implies the opposite: in the next
+ call to initialize() msaaColorBuffer() is going to return \nullptr, whereas
+ colorTexture() becomes once again valid. In addition, resolveTexture()
+ returns a valid (non-multisample) QRhiTexture whenever the sample count is
+ greater than 1 (i.e., MSAA is in use).
+
+ \sa msaaColorBuffer(), resolveTexture()
+ */
+
+int QRhiWidget::sampleCount() const
+{
+ Q_D(const QRhiWidget);
+ return d->samples;
+}
+
+void QRhiWidget::setSampleCount(int samples)
+{
+ Q_D(QRhiWidget);
+ if (d->samples != samples) {
+ d->samples = samples;
+ emit sampleCountChanged(samples);
+ update();
+ }
+}
+
+/*!
+ \property QRhiWidget::fixedColorBufferSize
+
+ The fixed size, in pixels, of the QRhiWidget's associated texture. Relevant
+ when a fixed texture size is desired that does not depend on the widget's
+ size. This size has no effect on the geometry of the widget (its size and
+ placement within the top-level window), which means the texture's content
+ will appear stretched (scaled up) or scaled down onto the widget's area.
+
+ For example, setting a size that is exactly twice the widget's (pixel) size
+ effectively performs 2x supersampling (rendering at twice the resolution
+ and then implicitly scaling down when texturing the quad corresponding to
+ the widget in the window).
+
+ By default the value is a null QSize. A null or empty QSize means that the
+ texture's size follows the QRhiWidget's size. (\c{texture size} = \c{widget
+ size} * \c{device pixel ratio}).
+ */
+
+QSize QRhiWidget::fixedColorBufferSize() const
+{
+ Q_D(const QRhiWidget);
+ return d->fixedSize;
+}
+
+void QRhiWidget::setFixedColorBufferSize(QSize pixelSize)
+{
+ Q_D(QRhiWidget);
+ if (d->fixedSize != pixelSize) {
+ d->fixedSize = pixelSize;
+ emit fixedColorBufferSizeChanged(pixelSize);
+ update();
+ }
+}
+
+/*!
+ \property QRhiWidget::mirrorVertically
+
+ When enabled, flips the image around the X axis when compositing the
+ QRhiWidget's backing texture with the rest of the widget content in the
+ top-level window.
+
+ The default value is \c false.
+ */
+
+bool QRhiWidget::isMirrorVerticallyEnabled() const
+{
+ Q_D(const QRhiWidget);
+ return d->mirrorVertically;
+}
+
+void QRhiWidget::setMirrorVertically(bool enabled)
+{
+ Q_D(QRhiWidget);
+ if (d->mirrorVertically != enabled) {
+ d->mirrorVertically = enabled;
+ emit mirrorVerticallyChanged(enabled);
+ update();
+ }
+}
+
+/*!
+ \property QRhiWidget::autoRenderTarget
+
+ The current setting for automatic depth-stencil buffer and render
+ target maintenance.
+
+ By default the value is \c true.
+ */
+bool QRhiWidget::isAutoRenderTargetEnabled() const
+{
+ Q_D(const QRhiWidget);
+ return d->autoRenderTarget;
+}
+
+/*!
+ Controls if a depth-stencil QRhiRenderBuffer and a QRhiTextureRenderTarget
+ is created and maintained automatically by the widget. The default value is
+ \c true.
+
+ In automatic mode, the size and sample count of the depth-stencil buffer
+ follows the color buffer texture's settings. In non-automatic mode,
+ renderTarget() and depthStencilBuffer() always return \nullptr and it is
+ then up to the application's implementation of initialize() to take care of
+ setting up and managing these objects.
+
+ Call this function with \a enabled set to \c false early on, for example in
+ the derived class' constructor, to disable the automatic mode.
+ */
+void QRhiWidget::setAutoRenderTarget(bool enabled)
+{
+ Q_D(QRhiWidget);
+ if (d->autoRenderTarget != enabled) {
+ d->autoRenderTarget = enabled;
+ update();
+ }
+}
+
+/*!
+ Renders a new frame, reads the contents of the texture back, and returns it
+ as a QImage.
+
+ When an error occurs, a null QImage is returned.
+
+ The returned QImage will have a format of QImage::Format_RGBA8888,
+ QImage::Format_RGBA16FPx4, QImage::Format_RGBA32FPx4, or
+ QImage::Format_BGR30, depending on colorBufferFormat().
+
+ QRhiWidget does not know the renderer's approach to blending and
+ composition, and therefore cannot know if the output has alpha
+ premultiplied in the RGB color values. Thus \c{_Premultiplied} QImage
+ formats are never used for the returned QImage, even when it would be
+ appropriate. It is up to the caller to reinterpret the resulting data as it
+ sees fit.
+
+ \note This function can also be called when the QRhiWidget is not added to
+ a widget hierarchy belonging to an on-screen top-level window. This allows
+ generating an image from a 3D rendering off-screen.
+
+ The function is named grabFramebuffer() for consistency with QOpenGLWidget
+ and QQuickWidget. It is not the only way to get CPU-side image data out of
+ the QRhiWidget's content: calling \l QWidget::grab() on a QRhiWidget, or an
+ ancestor of it, is functional as well (returning a QPixmap). Besides
+ working directly with QImage, another advantage of grabFramebuffer() is
+ that it may be slightly more performant, simply because it does not have to
+ go through the rest of QWidget infrastructure but can right away trigger
+ rendering a new frame and then do the readback.
+
+ \sa setColorBufferFormat()
+ */
+QImage QRhiWidget::grabFramebuffer() const
+{
+ return const_cast<QRhiWidgetPrivate *>(d_func())->grabFramebuffer();
+}
+
+/*!
+ Called when the widget is initialized for the first time, when the
+ associated texture's size, format, or sample count changes, or when the
+ QRhi and texture change for any reason. The function is expected to
+ maintain (create if not yet created, adjust and rebuild if the size has
+ changed) the graphics resources used by the rendering code in render().
+
+ To query the QRhi, QRhiTexture, and other related objects, call rhi(),
+ colorTexture(), depthStencilBuffer(), and renderTarget().
+
+ When the widget size changes, the QRhi object, the color buffer texture,
+ and the depth stencil buffer objects are all the same instances (so the
+ getters return the same pointers) as before, but the color and
+ depth/stencil buffers will likely have been rebuilt, meaning the
+ \l{QRhiTexture::pixelSize()}{size} and the underlying native texture
+ resource may be different than in the last invocation.
+
+ Reimplementations should also be prepared that the QRhi object and the
+ color buffer texture may change between invocations of this function. One
+ special case where the objects will be different is when performing a
+ grabFramebuffer() with a widget that is not yet shown, and then making the
+ widget visible on-screen within a top-level widget. There the grab will
+ happen with a dedicated QRhi that is then replaced with the top-level
+ window's associated QRhi in subsequent initialize() and render()
+ invocations. Another, more common case is when the widget is reparented so
+ that it belongs to a new top-level window. In this case the QRhi and all
+ related resources managed by the QRhiWidget will be different instances
+ than before in the subsequent call to this function. Is is then important
+ that all existing QRhi resources previously created by the subclass are
+ destroyed because they belong to the previous QRhi that should not be used
+ by the widget anymore.
+
+ When \l autoRenderTarget is \c true, which is the default, a
+ depth-stencil QRhiRenderBuffer and a QRhiTextureRenderTarget associated
+ with colorTexture() (or msaaColorBuffer()) and the depth-stencil buffer are
+ created and managed automatically. Reimplementations of initialize() and
+ render() can query those objects via depthStencilBuffer() and
+ renderTarget(). When \l autoRenderTarget is set to \c false, these
+ objects are no longer created and managed automatically. Rather, it will be
+ up the the initialize() implementation to create buffers and set up the
+ render target as it sees fit. When manually managing additional color or
+ depth-stencil attachments for the render target, their size and sample
+ count must always follow the size and sample count of colorTexture() /
+ msaaColorBuffer(), otherwise rendering or 3D API validation errors may
+ occur.
+
+ The subclass-created graphics resources are expected to be released in the
+ destructor implementation of the subclass.
+
+ \a cb is the QRhiCommandBuffer for the current frame of the widget. The
+ function is called with a frame being recorded, but without an active
+ render pass. The command buffer is provided primarily to allow enqueuing
+ \l{QRhiCommandBuffer::resourceUpdate()}{resource updates} without deferring
+ to render().
+
+ \sa render()
+ */
+void QRhiWidget::initialize(QRhiCommandBuffer *cb)
+{
+ Q_UNUSED(cb);
+}
+
+/*!
+ Called when the widget contents (i.e. the contents of the texture) need
+ updating.
+
+ There is always at least one call to initialize() before this function is
+ called.
+
+ To request updates, call QWidget::update(). Calling update() from within
+ render() will lead to updating continuously, throttled by vsync.
+
+ \a cb is the QRhiCommandBuffer for the current frame of the widget. The
+ function is called with a frame being recorded, but without an active
+ render pass.
+
+ \sa initialize()
+ */
+void QRhiWidget::render(QRhiCommandBuffer *cb)
+{
+ Q_UNUSED(cb);
+}
+
+/*!
+ Called when the need to early-release the graphics resources arises.
+
+ This normally does not happen for a QRhiWidget that is added to a top-level
+ widget's child hierarchy and it then stays there for the rest of its and
+ the top-level's lifetime. Thus in many cases there is no need to
+ reimplement this function, e.g. because the application only ever has a
+ single top-level widget (native window). However, when reparenting of the
+ widget (or an ancestor of it) is involved, reimplementing this function
+ will become necessary in robust, well-written QRhiWidget subclasses.
+
+ When this function is called, the implementation is expected to destroy all
+ QRhi resources (QRhiBuffer, QRhiTexture, etc. objects), similarly to how it
+ is expected to do this in the destructor. Nulling out, using a smart
+ pointer, or setting a \c{resources-invalid} flag is going to be required as
+ well, because initialize() will eventually get called afterwards. Note
+ however that deferring the releasing of resources to the subsequent
+ initialize() is wrong. If this function is called, the resource must be
+ dropped before returning. Also note that implementing this function does
+ not replace the class destructor (or smart pointers): the graphics
+ resources must still be released in both.
+
+ See the \l{Cube RHI Widget Example} for an example of this in action. There
+ the button that toggles the QRhiWidget between being a child widget (due to
+ having a parent widget) and being a top-level widget (due to having no
+ parent widget), will trigger invoking this function since the associated
+ top-level widget, native window, and QRhi all change during the lifetime of
+ the QRhiWidget, with the previously used QRhi getting destroyed which
+ implies an early-release of the associated resources managed by the
+ still-alive QRhiWidget.
+
+ Another case when this function is called is when grabFramebuffer() is used
+ with a QRhiWidget that is not added to a visible window, i.e. the rendering
+ is performed offscreen. If later on this QRhiWidget is made visible, or
+ added to a visible widget hierarchy, the associated QRhi will change from
+ the temporary one used for offscreen rendering to the window's dedicated
+ one, thus triggering this function as well.
+
+ \sa initialize()
+ */
+void QRhiWidget::releaseResources()
+{
+}
+
+/*!
+ \return the current QRhi object.
+
+ Must only be called from initialize() and render().
+ */
+QRhi *QRhiWidget::rhi() const
+{
+ Q_D(const QRhiWidget);
+ return d->rhi;
+}
+
+/*!
+ \return the texture serving as the color buffer for the widget.
+
+ Must only be called from initialize() and render().
+
+ Unlike the depth-stencil buffer and the QRhiRenderTarget, this texture is
+ always available and is managed by the QRhiWidget, independent of the value
+ of \l autoRenderTarget.
+
+ \note When \l sampleCount is larger than 1, and so multisample antialiasing
+ is enabled, the return value is \nullptr. Instead, query the
+ \l QRhiRenderBuffer by calling msaaColorBuffer().
+
+ \note The backing texture size and sample count can also be queried via the
+ QRhiRenderTarget returned from renderTarget(). This can be more convenient
+ and compact than querying from the QRhiTexture or QRhiRenderBuffer, because
+ it works regardless of multisampling is in use or not.
+
+ \sa msaaColorBuffer(), depthStencilBuffer(), renderTarget(), resolveTexture()
+ */
+QRhiTexture *QRhiWidget::colorTexture() const
+{
+ Q_D(const QRhiWidget);
+ return d->colorTexture;
+}
+
+/*!
+ \return the renderbuffer serving as the multisample color buffer for the widget.
+
+ Must only be called from initialize() and render().
+
+ When \l sampleCount is larger than 1, and so multisample antialising is
+ enabled, the returned QRhiRenderBuffer has a matching sample count and
+ serves as the color buffer. Graphics pipelines used to render into this
+ buffer must be created with the same sample count, and the depth-stencil
+ buffer's sample count must match as well. The multisample content is
+ expected to be resolved into the texture returned from resolveTexture().
+ When \l autoRenderTarget is
+ \c true, renderTarget() is set up automatically to do this, by setting up
+ msaaColorBuffer() as the \l{QRhiColorAttachment::renderBuffer()}{renderbuffer} of
+ color attachment 0 and resolveTexture() as its
+ \l{QRhiColorAttachment::resolveTexture()}{resolveTexture}.
+
+ When MSAA is not in use, the return value is \nullptr. Use colorTexture()
+ instead then.
+
+ Depending on the underlying 3D graphics API, there may be no practical
+ difference between multisample textures and color renderbuffers with a
+ sample count larger than 1 (QRhi may just map both to the same native
+ resource type). Some older APIs however may differentiate between textures
+ and renderbuffers. In order to support OpenGL ES 3.0, where multisample
+ renderbuffers are available, but multisample textures are not, QRhiWidget
+ always performs MSAA by using a multisample QRhiRenderBuffer as the color
+ attachment (and never a multisample QRhiTexture).
+
+ \note The backing texture size and sample count can also be queried via the
+ QRhiRenderTarget returned from renderTarget(). This can be more convenient
+ and compact than querying from the QRhiTexture or QRhiRenderBuffer, because
+ it works regardless of multisampling is in use or not.
+
+ \sa colorTexture(), depthStencilBuffer(), renderTarget(), resolveTexture()
+ */
+QRhiRenderBuffer *QRhiWidget::msaaColorBuffer() const
+{
+ Q_D(const QRhiWidget);
+ return d->msaaColorBuffer;
+}
+
+/*!
+ \return the non-multisample texture to which the multisample content is resolved.
+
+ The result is \nullptr when multisample antialiasing is not enabled.
+
+ Must only be called from initialize() and render().
+
+ With MSAA enabled, this is the texture that gets composited with the rest
+ of the QWidget content on-screen. However, the QRhiWidget's rendering must
+ target the (multisample) QRhiRenderBuffer returned from
+ msaaColorBuffer(). When
+ \l autoRenderTarget is \c true, this is taken care of by the
+ QRhiRenderTarget returned from renderTarget(). Otherwise, it is up to the
+ subclass code to correctly configure a render target object with both the
+ color buffer and resolve textures.
+
+ \sa colorTexture()
+ */
+QRhiTexture *QRhiWidget::resolveTexture() const
+{
+ Q_D(const QRhiWidget);
+ return d->resolveTexture;
+}
+
+/*!
+ \return the depth-stencil buffer used by the widget's rendering.
+
+ Must only be called from initialize() and render().
+
+ Available only when \l autoRenderTarget is \c true. Otherwise the
+ returned value is \nullptr and it is up the reimplementation of
+ initialize() to create and manage a depth-stencil buffer and a
+ QRhiTextureRenderTarget.
+
+ \sa colorTexture(), renderTarget()
+ */
+QRhiRenderBuffer *QRhiWidget::depthStencilBuffer() const
+{
+ Q_D(const QRhiWidget);
+ return d->depthStencilBuffer;
+}
+
+/*!
+ \return the render target object that must be used with
+ \l QRhiCommandBuffer::beginPass() in reimplementations of render().
+
+ Must only be called from initialize() and render().
+
+ Available only when \l autoRenderTarget is \c true. Otherwise the
+ returned value is \nullptr and it is up the reimplementation of
+ initialize() to create and manage a depth-stencil buffer and a
+ QRhiTextureRenderTarget.
+
+ When creating \l{QRhiGraphicsPipeline}{graphics pipelines}, a
+ QRhiRenderPassDescriptor is needed. This can be queried from the returned
+ QRhiTextureRenderTarget by calling
+ \l{QRhiTextureRenderTarget::renderPassDescriptor()}{renderPassDescriptor()}.
+
+ \sa colorTexture(), depthStencilBuffer()
+ */
+QRhiRenderTarget *QRhiWidget::renderTarget() const
+{
+ Q_D(const QRhiWidget);
+ return d->renderTarget;
+}
+
+/*!
+ \fn void QRhiWidget::frameSubmitted()
+
+ This signal is emitted after the widget's top-level window has finished
+ composition and has \l{QRhi::endFrame()}{submitted a frame}.
+*/
+
+/*!
+ \fn void QRhiWidget::renderFailed()
+
+ This signal is emitted whenever the widget is supposed to render to its
+ backing texture (either due to a \l{QWidget::update()}{widget update} or
+ due to a call to grabFramebuffer()), but there is no \l QRhi for the widget to
+ use, likely due to issues related to graphics configuration.
+
+ This signal may be emitted multiple times when a problem arises. Do not
+ assume it is emitted only once. Connect with Qt::SingleShotConnection if
+ the error handling code is to be notified only once.
+*/
+
+QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qrhiwidget.h b/src/widgets/kernel/qrhiwidget.h
new file mode 100644
index 0000000000..45fe7b7482
--- /dev/null
+++ b/src/widgets/kernel/qrhiwidget.h
@@ -0,0 +1,101 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QRHIWIDGET_H
+#define QRHIWIDGET_H
+
+#include <QtWidgets/qwidget.h>
+
+QT_BEGIN_NAMESPACE
+
+class QRhiWidgetPrivate;
+class QRhi;
+class QRhiTexture;
+class QRhiRenderBuffer;
+class QRhiRenderTarget;
+class QRhiCommandBuffer;
+
+class Q_WIDGETS_EXPORT QRhiWidget : public QWidget
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QRhiWidget)
+ Q_PROPERTY(int sampleCount READ sampleCount WRITE setSampleCount NOTIFY sampleCountChanged)
+ Q_PROPERTY(TextureFormat colorBufferFormat READ colorBufferFormat WRITE setColorBufferFormat NOTIFY colorBufferFormatChanged)
+ Q_PROPERTY(QSize fixedColorBufferSize READ fixedColorBufferSize WRITE setFixedColorBufferSize NOTIFY fixedColorBufferSizeChanged)
+ Q_PROPERTY(bool mirrorVertically READ isMirrorVerticallyEnabled WRITE setMirrorVertically NOTIFY mirrorVerticallyChanged)
+ QDOC_PROPERTY(bool autoRenderTarget READ isAutoRenderTargetEnabled WRITE setAutoRenderTarget)
+
+public:
+ explicit QRhiWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
+ ~QRhiWidget() override;
+
+ enum class Api {
+ Null,
+ OpenGL,
+ Metal,
+ Vulkan,
+ Direct3D11,
+ Direct3D12,
+ };
+ Q_ENUM(Api)
+
+ enum class TextureFormat {
+ RGBA8,
+ RGBA16F,
+ RGBA32F,
+ RGB10A2,
+ };
+ Q_ENUM(TextureFormat)
+
+ Api api() const;
+ void setApi(Api api);
+
+ bool isDebugLayerEnabled() const;
+ void setDebugLayerEnabled(bool enable);
+
+ int sampleCount() const;
+ void setSampleCount(int samples);
+
+ TextureFormat colorBufferFormat() const;
+ void setColorBufferFormat(TextureFormat format);
+
+ QSize fixedColorBufferSize() const;
+ void setFixedColorBufferSize(QSize pixelSize);
+ void setFixedColorBufferSize(int w, int h) { setFixedColorBufferSize(QSize(w, h)); }
+
+ bool isMirrorVerticallyEnabled() const;
+ void setMirrorVertically(bool enabled);
+
+ QImage grabFramebuffer() const;
+
+protected:
+ bool isAutoRenderTargetEnabled() const;
+ void setAutoRenderTarget(bool enabled);
+
+ virtual void initialize(QRhiCommandBuffer *cb);
+ virtual void render(QRhiCommandBuffer *cb);
+ virtual void releaseResources();
+
+ QRhi *rhi() const;
+ QRhiTexture *colorTexture() const;
+ QRhiRenderBuffer *msaaColorBuffer() const;
+ QRhiTexture *resolveTexture() const;
+ QRhiRenderBuffer *depthStencilBuffer() const;
+ QRhiRenderTarget *renderTarget() const;
+
+ void resizeEvent(QResizeEvent *e) override;
+ void paintEvent(QPaintEvent *e) override;
+ bool event(QEvent *e) override;
+
+Q_SIGNALS:
+ void frameSubmitted();
+ void renderFailed();
+ void sampleCountChanged(int samples);
+ void colorBufferFormatChanged(TextureFormat format);
+ void fixedColorBufferSizeChanged(const QSize &pixelSize);
+ void mirrorVerticallyChanged(bool enabled);
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/widgets/kernel/qrhiwidget_p.h b/src/widgets/kernel/qrhiwidget_p.h
new file mode 100644
index 0000000000..b594b67ec8
--- /dev/null
+++ b/src/widgets/kernel/qrhiwidget_p.h
@@ -0,0 +1,64 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QRHIWIDGET_P_H
+#define QRHIWIDGET_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.
+//
+
+#include "qrhiwidget.h"
+#include <rhi/qrhi.h>
+#include <private/qwidget_p.h>
+#include <private/qbackingstorerhisupport_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QRhiWidgetPrivate : public QWidgetPrivate
+{
+ Q_DECLARE_PUBLIC(QRhiWidget)
+public:
+ TextureData texture() const override;
+ QPlatformTextureList::Flags textureListFlags() override;
+ QPlatformBackingStoreRhiConfig rhiConfig() const override;
+ void endCompose() override;
+ QImage grabFramebuffer() override;
+
+ void ensureRhi();
+ void ensureTexture(bool *changed);
+ bool invokeInitialize(QRhiCommandBuffer *cb);
+ void resetColorBufferObjects();
+ void resetRenderTargetObjects();
+ void releaseResources();
+
+ QRhi *rhi = nullptr;
+ bool noSize = false;
+ QPlatformBackingStoreRhiConfig config;
+ QRhiWidget::TextureFormat widgetTextureFormat = QRhiWidget::TextureFormat::RGBA8;
+ QRhiTexture::Format rhiTextureFormat = QRhiTexture::RGBA8;
+ int samples = 1;
+ QSize fixedSize;
+ bool autoRenderTarget = true;
+ bool mirrorVertically = false;
+ QBackingStoreRhiSupport offscreenRenderer;
+ bool textureInvalid = false;
+ QRhiTexture *colorTexture = nullptr;
+ QRhiRenderBuffer *msaaColorBuffer = nullptr;
+ QRhiTexture *resolveTexture = nullptr;
+ QRhiRenderBuffer *depthStencilBuffer = nullptr;
+ QRhiTextureRenderTarget *renderTarget = nullptr;
+ QRhiRenderPassDescriptor *renderPassDescriptor = nullptr;
+ mutable QVector<QRhiResource *> pendingDeletes;
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/widgets/kernel/qshortcut_widgets.cpp b/src/widgets/kernel/qshortcut_widgets.cpp
index cb184ef07d..6e25d79bd6 100644
--- a/src/widgets/kernel/qshortcut_widgets.cpp
+++ b/src/widgets/kernel/qshortcut_widgets.cpp
@@ -65,9 +65,6 @@ bool qWidgetShortcutContextMatcher(QObject *object, Qt::ShortcutContext context)
}
}
- if (!active_window)
- return false;
-
#if QT_CONFIG(action)
if (auto a = qobject_cast<QAction *>(object))
return correctActionContext(context, a, active_window);
@@ -95,14 +92,17 @@ bool qWidgetShortcutContextMatcher(QObject *object, Qt::ShortcutContext context)
}
}
- if (!w)
- return false;
+ if (w)
+ return correctWidgetContext(context, w, active_window);
- return correctWidgetContext(context, w, active_window);
+ return QShortcutPrivate::simpleContextMatcher(object, context);
}
static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidget *active_window)
{
+ if (!active_window)
+ return false;
+
bool visible = w->isVisible();
#if QT_CONFIG(menubar)
if (auto menuBar = qobject_cast<QMenuBar *>(w)) {
@@ -188,6 +188,9 @@ static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidge
#if QT_CONFIG(graphicsview)
static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsWidget *w, QWidget *active_window)
{
+ if (!active_window)
+ return false;
+
bool visible = w->isVisible();
#if defined(Q_OS_DARWIN) && QT_CONFIG(menubar)
if (!QCoreApplication::testAttribute(Qt::AA_DontUseNativeMenuBar) && qobject_cast<QMenuBar *>(w))
@@ -247,6 +250,9 @@ static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsW
#if QT_CONFIG(action)
static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidget *active_window)
{
+ if (!active_window)
+ return false;
+
const QObjectList associatedObjects = a->associatedObjects();
#if defined(DEBUG_QSHORTCUTMAP)
if (associatedObjects.isEmpty())
diff --git a/src/widgets/kernel/qstackedlayout.cpp b/src/widgets/kernel/qstackedlayout.cpp
index aca470fe1c..04eacf1d41 100644
--- a/src/widgets/kernel/qstackedlayout.cpp
+++ b/src/widgets/kernel/qstackedlayout.cpp
@@ -8,6 +8,8 @@
#include "private/qwidget_p.h"
#include "private/qlayoutengine_p.h"
+#include <QtCore/qpointer.h>
+
#include <memory>
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/kernel/qtestsupport_widgets.cpp b/src/widgets/kernel/qtestsupport_widgets.cpp
index 1141fcea0a..f7b25b6643 100644
--- a/src/widgets/kernel/qtestsupport_widgets.cpp
+++ b/src/widgets/kernel/qtestsupport_widgets.cpp
@@ -16,8 +16,8 @@
QT_BEGIN_NAMESPACE
-template <typename FunctorWindowGetter, typename FunctorPredicate>
-static bool qWaitForWidgetWindow(FunctorWindowGetter windowGetter, FunctorPredicate predicate, int timeout)
+template <typename FunctorWindowGetter, typename FunctorPredicate, typename Timeout>
+static bool qWaitForWidgetWindow(FunctorWindowGetter windowGetter, FunctorPredicate predicate, Timeout timeout)
{
if (!windowGetter())
return false;
@@ -60,6 +60,32 @@ Q_WIDGETS_EXPORT bool QTest::qWaitForWindowActive(QWidget *widget, int timeout)
timeout);
}
+
+/*!
+ \since 6.7
+
+ Returns \c true, if \a widget is the focus window within \a timeout. Otherwise returns \c false.
+
+ The method is useful in tests that call QWidget::show() and rely on the widget
+ having focus (for receiving keyboard events e.g.) before proceeding.
+
+ \note The method will time out and return \c false if another window prevents \a widget from
+ becoming focused.
+
+ \note Since focus is an exclusive property, \a widget may loose its focus to another window at
+ any time - even after the method has returned \c true.
+
+ \sa qWaitForWindowExposed(), qWaitForWindowActive(), QGuiApplication::focusWindow()
+*/
+Q_WIDGETS_EXPORT bool QTest::qWaitForWindowFocused(QWidget *widget, QDeadlineTimer timeout)
+{
+ return qWaitForWidgetWindow([&]() {
+ return widget->window()->windowHandle();
+ }, [&](QWindow *window) {
+ return qGuiApp->focusWindow() == window;
+ }, timeout);
+}
+
/*!
\since 5.0
@@ -123,7 +149,7 @@ bool QTouchEventWidgetSequence::commit(bool processEvents)
bool ret = false;
if (points.isEmpty())
return ret;
- QThread::msleep(1);
+ QThread::sleep(std::chrono::milliseconds{1});
if (targetWindow) {
ret = qt_handleTouchEventv2(targetWindow, device, points.values());
} else if (targetWidget) {
diff --git a/src/widgets/kernel/qtestsupport_widgets.h b/src/widgets/kernel/qtestsupport_widgets.h
index 84b529ae31..b49e68db65 100644
--- a/src/widgets/kernel/qtestsupport_widgets.h
+++ b/src/widgets/kernel/qtestsupport_widgets.h
@@ -15,6 +15,7 @@ class QWidget;
namespace QTest {
[[nodiscard]] Q_WIDGETS_EXPORT bool qWaitForWindowActive(QWidget *widget, int timeout = 5000);
+[[nodiscard]] Q_WIDGETS_EXPORT bool qWaitForWindowFocused(QWidget *widget, QDeadlineTimer timeout = std::chrono::seconds{5});
[[nodiscard]] Q_WIDGETS_EXPORT bool qWaitForWindowExposed(QWidget *widget, int timeout = 5000);
class Q_WIDGETS_EXPORT QTouchEventWidgetSequence : public QTouchEventSequence
diff --git a/src/widgets/kernel/qtooltip.cpp b/src/widgets/kernel/qtooltip.cpp
index 3166613199..35eaa8042a 100644
--- a/src/widgets/kernel/qtooltip.cpp
+++ b/src/widgets/kernel/qtooltip.cpp
@@ -45,15 +45,24 @@ using namespace Qt::StringLiterals;
Rich text displayed in a tool tip is implicitly word-wrapped unless
specified differently with \c{<p style='white-space:pre'>}.
- The simplest and most common way to set a widget's tool tip is by
- calling its QWidget::setToolTip() function.
+ UI elements that are created via \l{QAction} use the tooltip property
+ of the QAction, so for most interactive UI elements, setting that
+ property is the easiest way to provide tool tips.
+
+ \snippet tooltips/main.cpp action_tooltip
+
+ For any other widgets, the simplest and most common way to set
+ a widget's tool tip is by calling its QWidget::setToolTip() function.
+
+ \snippet tooltips/main.cpp static_tooltip
It is also possible to show different tool tips for different
regions of a widget, by using a QHelpEvent of type
QEvent::ToolTip. Intercept the help event in your widget's \l
{QWidget::}{event()} function and call QToolTip::showText() with
- the text you want to display. The \l{widgets/tooltips}{Tooltips}
- example illustrates this technique.
+ the text you want to display.
+
+ \snippet tooltips/main.cpp dynamic_tooltip
If you are calling QToolTip::hideText(), or QToolTip::showText()
with an empty string, as a result of a \l{QEvent::}{ToolTip}-event you
@@ -75,7 +84,7 @@ using namespace Qt::StringLiterals;
\note Tool tips use the inactive color group of QPalette, because tool
tips are not active windows.
- \sa QWidget::toolTip, QAction::toolTip, {Tool Tips Example}
+ \sa QWidget::toolTip, QAction::toolTip
*/
class QTipLabel : public QLabel
@@ -157,7 +166,9 @@ QTipLabel::QTipLabel(const QString &text, const QPoint &pos, QWidget *w, int mse
void QTipLabel::restartExpireTimer(int msecDisplayTime)
{
- int time = 10000 + 40 * qMax(0, text().size()-100);
+ Q_D(const QLabel);
+ const qsizetype textLength = d->needTextControl() ? d->control->toPlainText().size() : text().size();
+ qsizetype time = 10000 + 40 * qMax(0, textLength - 100);
if (msecDisplayTime > 0)
time = msecDisplayTime;
expireTimer.start(time, this);
@@ -168,8 +179,8 @@ void QTipLabel::reuseTip(const QString &text, int msecDisplayTime, const QPoint
{
#ifndef QT_NO_STYLE_STYLESHEET
if (styleSheetParent){
- disconnect(styleSheetParent, SIGNAL(destroyed()),
- QTipLabel::instance, SLOT(styleSheetParentDestroyed()));
+ disconnect(styleSheetParent, &QWidget::destroyed,
+ this, &QTipLabel::styleSheetParentDestroyed);
styleSheetParent = nullptr;
}
#endif
@@ -318,6 +329,7 @@ bool QTipLabel::eventFilter(QObject *o, QEvent *e)
case QEvent::MouseMove:
if (o == widget && !rect.isNull() && !rect.contains(static_cast<QMouseEvent*>(e)->position().toPoint()))
hideTip();
+ break;
default:
break;
}
@@ -343,12 +355,14 @@ void QTipLabel::placeTip(const QPoint &pos, QWidget *w)
// Set up for cleaning up this later...
QTipLabel::instance->styleSheetParent = w;
if (w) {
- connect(w, SIGNAL(destroyed()),
- QTipLabel::instance, SLOT(styleSheetParentDestroyed()));
- // QTBUG-64550: A font inherited by the style sheet might change the size,
- // particular on Windows, where the tip is not parented on a window.
- QTipLabel::instance->updateSize(pos);
+ connect(w, &QWidget::destroyed,
+ QTipLabel::instance, &QTipLabel::styleSheetParentDestroyed);
}
+ // QTBUG-64550: A font inherited by the style sheet might change the size,
+ // particular on Windows, where the tip is not parented on a window.
+ // The updatesSize() also makes sure that the content size be updated with
+ // correct content margin.
+ QTipLabel::instance->updateSize(pos);
}
#endif //QT_NO_STYLE_STYLESHEET
diff --git a/src/widgets/kernel/qwhatsthis.cpp b/src/widgets/kernel/qwhatsthis.cpp
index 9f8656b3fb..c80f37267f 100644
--- a/src/widgets/kernel/qwhatsthis.cpp
+++ b/src/widgets/kernel/qwhatsthis.cpp
@@ -97,8 +97,6 @@ QT_BEGIN_NAMESPACE
\sa QToolTip
*/
-Q_CORE_EXPORT void qDeleteInEventHandler(QObject *o);
-
class QWhatsThat : public QWidget
{
Q_OBJECT
@@ -110,7 +108,6 @@ public:
static QWhatsThat *instance;
protected:
- void showEvent(QShowEvent *e) override;
void mousePressEvent(QMouseEvent*) override;
void mouseReleaseEvent(QMouseEvent*) override;
void mouseMoveEvent(QMouseEvent*) override;
@@ -123,7 +120,6 @@ private:
QString text;
QTextDocument* doc;
QString anchor;
- QPixmap background;
};
QWhatsThat *QWhatsThat::instance = nullptr;
@@ -197,11 +193,6 @@ QWhatsThat::~QWhatsThat()
delete doc;
}
-void QWhatsThat::showEvent(QShowEvent *)
-{
- background = QGuiApplication::primaryScreen()->grabWindow(0, x(), y(), width(), height());
-}
-
void QWhatsThat::mousePressEvent(QMouseEvent* e)
{
pressed = true;
@@ -261,7 +252,6 @@ void QWhatsThat::paintEvent(QPaintEvent*)
if (drawShadow)
r.adjust(0, 0, -shadowWidth, -shadowWidth);
QPainter p(this);
- p.drawPixmap(0, 0, background);
p.setPen(QPen(palette().toolTipText(), 0));
p.setBrush(palette().toolTipBase());
p.drawRect(r);
@@ -428,7 +418,7 @@ bool QWhatsThisPrivate::eventFilter(QObject *o, QEvent *e)
break;
case QEvent::KeyPress:
{
- QKeyEvent* kev = (QKeyEvent*)e;
+ QKeyEvent *kev = static_cast<QKeyEvent *>(e);
#if QT_CONFIG(shortcut)
if (kev->matches(QKeySequence::Cancel)) {
QWhatsThis::leaveWhatsThisMode();
@@ -472,7 +462,7 @@ QWhatsThisAction::QWhatsThisAction(QObject *parent) : QAction(tr("What's This?")
setIcon(p);
#endif
setCheckable(true);
- connect(this, SIGNAL(triggered()), this, SLOT(actionTriggered()));
+ connect(this, &QWhatsThisAction::triggered, this, &QWhatsThisAction::actionTriggered);
#ifndef QT_NO_SHORTCUT
setShortcut(Qt::ShiftModifier | Qt::Key_F1);
#endif
@@ -618,7 +608,7 @@ void QWhatsThis::showText(const QPoint &pos, const QString &text, QWidget *w)
*/
void QWhatsThis::hideText()
{
- qDeleteInEventHandler(QWhatsThat::instance);
+ delete QWhatsThat::instance;
}
/*!
diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp
index 55bed86080..b302b32b88 100644
--- a/src/widgets/kernel/qwidget.cpp
+++ b/src/widgets/kernel/qwidget.cpp
@@ -6,6 +6,7 @@
#include "qapplication_p.h"
#include "qbrush.h"
#include "qcursor.h"
+#include "private/qduplicatetracker_p.h"
#include "qevent.h"
#include "qlayout.h"
#if QT_CONFIG(menu)
@@ -82,6 +83,16 @@ using namespace QNativeInterface::Private;
using namespace Qt::StringLiterals;
Q_LOGGING_CATEGORY(lcWidgetPainting, "qt.widgets.painting", QtWarningMsg);
+Q_LOGGING_CATEGORY(lcWidgetShowHide, "qt.widgets.showhide", QtWarningMsg);
+Q_LOGGING_CATEGORY(lcWidgetWindow, "qt.widgets.window", QtWarningMsg);
+Q_LOGGING_CATEGORY(lcWidgetFocus, "qt.widgets.focus")
+
+#ifndef QT_NO_DEBUG_STREAM
+namespace {
+ struct WidgetAttributes { const QWidget *widget; };
+ QDebug operator<<(QDebug debug, const WidgetAttributes &attributes);
+}
+#endif
static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
{
@@ -357,14 +368,14 @@ void QWidget::setAutoFillBackground(bool enabled)
If not, it will be a child of \e parent, and be constrained by
\e parent's geometry (unless you specify Qt::Window as window flag).
\li \c{Qt::WindowFlags f = { }} (where available) sets the window flags;
- the default is suitable for almost all widgets, but to get, for
+ the default is suitable for most widgets, but to get, for
example, a window without a window system frame, you must use
special flags.
\endlist
QWidget has many member functions, but some of them have little direct
functionality; for example, QWidget has a font property, but never uses
- this itself. There are many subclasses which provide real functionality,
+ this itself. There are many subclasses that provide real functionality,
such as QLabel, QPushButton, QListWidget, and QTabWidget.
@@ -372,7 +383,7 @@ void QWidget::setAutoFillBackground(bool enabled)
A widget without a parent widget is always an independent window (top-level
widget). For these widgets, setWindowTitle() and setWindowIcon() set the
- title bar and icon respectively.
+ title bar and icon, respectively.
Non-window widgets are child widgets, displayed within their parent
widgets. Most widgets in Qt are mainly useful as child widgets. For
@@ -385,7 +396,7 @@ void QWidget::setAutoFillBackground(bool enabled)
widgets in a layout provided by QGridLayout. The QLabel child widgets have
been outlined to indicate their full sizes.
- If you want to use a QWidget to hold child widgets you will usually want to
+ If you want to use a QWidget to hold child widgets, you will usually want to
add a layout to the parent QWidget. See \l{Layout Management} for more
information.
@@ -395,14 +406,13 @@ void QWidget::setAutoFillBackground(bool enabled)
When a widget is used as a container to group a number of child widgets, it
is known as a composite widget. These can be created by constructing a
widget with the required visual properties - a QFrame, for example - and
- adding child widgets to it, usually managed by a layout. The above diagram
- shows such a composite widget that was created using Qt Designer.
+ adding child widgets to it, usually managed by a layout.
Composite widgets can also be created by subclassing a standard widget,
such as QWidget or QFrame, and adding the necessary layout and child
widgets in the constructor of the subclass. Many of the \l{Qt Widgets Examples}
{examples provided with Qt} use this approach, and it is also covered in
- the Qt \l{Tutorials}.
+ the Qt \l{Widgets Tutorial}.
\section1 Custom Widgets and Painting
@@ -416,7 +426,7 @@ void QWidget::setAutoFillBackground(bool enabled)
Each widget performs all painting operations from within its paintEvent()
function. This is called whenever the widget needs to be redrawn, either
- as a result of some external change or when requested by the application.
+ because of some external change or when requested by the application.
The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
can handle paint events.
@@ -428,7 +438,7 @@ void QWidget::setAutoFillBackground(bool enabled)
sizeHint() to provide a reasonable default size for the widget and to set
the correct size policy with setSizePolicy().
- By default, composite widgets which do not provide a size hint will be
+ By default, composite widgets that do not provide a size hint will be
sized according to the space requirements of their child widgets.
The size policy lets you supply good default behavior for the layout
@@ -448,9 +458,9 @@ void QWidget::setAutoFillBackground(bool enabled)
delivers events to widgets by calling specific event handler functions with
instances of QEvent subclasses containing information about each event.
- If your widget only contains child widgets, you probably do not need to
+ If your widget only contains child widgets, you probably don't need to
implement any event handlers. If you want to detect a mouse click in a
- child widget call the child's underMouse() function inside the widget's
+ child widget, call the child's underMouse() function inside the widget's
mousePressEvent().
The \l{widgets/scribble}{Scribble example} implements a wider set of
@@ -515,7 +525,7 @@ void QWidget::setAutoFillBackground(bool enabled)
button is held down. This can be useful during drag and drop
operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
you get mouse move events even when no buttons are held down.
- (See also the \l{Drag and Drop} guide.)
+ (See also the \l{Drag and Drop in Qt}{Drag and Drop} guide.)
\li keyReleaseEvent() is called whenever a key is released and while it
is held down (if the key is auto-repeating). In that case, the
widget will receive a pair of key release and key press event for
@@ -529,7 +539,7 @@ void QWidget::setAutoFillBackground(bool enabled)
space. (This excludes screen space owned by any of the widget's
children.)
\li leaveEvent() is called when the mouse leaves the widget's screen
- space. If the mouse enters a child widget it will not cause a
+ space. If the mouse enters a child widget, it will not cause a
leaveEvent().
\li moveEvent() is called when the widget has been moved relative to
its parent.
@@ -667,11 +677,11 @@ void QWidget::setAutoFillBackground(bool enabled)
\section1 Transparency and Double Buffering
- Since Qt 4.0, QWidget automatically double-buffers its painting, so there
+ QWidget automatically double-buffers its painting, so there
is no need to write double-buffering code in paintEvent() to avoid
flicker.
- Since Qt 4.1, the contents of parent widgets are propagated by
+ The contents of parent widgets are propagated by
default to each of their children as long as Qt::WA_PaintOnScreen is not
set. Custom widgets can be written to take advantage of this feature by
updating irregular regions (to create non-rectangular child widgets), or
@@ -688,7 +698,7 @@ void QWidget::setAutoFillBackground(bool enabled)
\list
\li The left widget has no additional properties or widget attributes
- set. This default state suits most custom widgets using
+ set. This default state suits most custom widgets that have
transparency, are irregularly-shaped, or do not paint over their
entire area with an opaque brush.
\li The center widget has the \l autoFillBackground property set. This
@@ -699,10 +709,7 @@ void QWidget::setAutoFillBackground(bool enabled)
set. This indicates that the widget will paint over its entire area
with opaque colors. The widget's area will initially be
\e{uninitialized}, represented in the diagram with a red diagonal
- grid pattern that shines through the overpainted area. The
- Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
- paint their own specialized contents quickly and do not need a
- default filled background.
+ grid pattern that shines through the overpainted area.
\endlist
To rapidly update custom widgets with simple background colors, such as
@@ -712,19 +719,18 @@ void QWidget::setAutoFillBackground(bool enabled)
implement the necessary drawing functionality in the widget's paintEvent().
To rapidly update custom widgets that constantly paint over their entire
- areas with opaque content, e.g., video streaming widgets, it is better to
- set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
- associated with repainting the widget's background.
+ areas with opaque content, for example, video streaming widgets, it is
+ better to set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary
+ overhead associated with repainting the widget's background.
If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
attribute takes precedence. Depending on your requirements, you should
choose either one of them.
- Since Qt 4.1, the contents of parent widgets are also propagated to
- standard Qt widgets. This can lead to some unexpected results if the
- parent widget is decorated in a non-standard way, as shown in the diagram
- below.
+ The contents of parent widgets are also propagated to standard Qt widgets.
+ This can lead to some unexpected results if the parent widget is decorated
+ in a non-standard way, as shown in the diagram below.
\image propagation-standard.png
@@ -736,8 +742,8 @@ void QWidget::setAutoFillBackground(bool enabled)
\section1 Creating Translucent Windows
- Since Qt 4.5, it has been possible to create windows with translucent regions
- on window systems that support compositing.
+ You can create windows with translucent regions on window systems that
+ support compositing.
To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
attribute with setAttribute() and ensure that its background is painted with
@@ -757,19 +763,19 @@ void QWidget::setAutoFillBackground(bool enabled)
\section1 Native Widgets vs Alien Widgets
- Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
- system. They do not have a native window handle associated with them. This
- feature significantly speeds up widget painting, resizing, and removes flicker.
+ Alien widgets are widgets unknown to the windowing system. They do not have
+ a native window handle associated with them. This feature significantly
+ speeds up widget painting, resizing, and removes flicker.
- Should you require the old behavior with native windows, you can choose
- one of the following options:
+ Should you require the old behavior with native windows, choose one of the
+ following options:
\list 1
\li Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
\li Set the Qt::AA_NativeWindows attribute on your application. All
widgets will be native widgets.
\li Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
- and all of its ancestors will become native (unless
+ and all its ancestors will become native (unless
Qt::WA_DontCreateNativeAncestors is set).
\li Call QWidget::winId to enforce a native window (this implies 3).
\li Set the Qt::WA_PaintOnScreen attribute to enforce a native window
@@ -814,12 +820,7 @@ struct QWidgetExceptionCleaner
Q_UNUSED(d);
#else
QWidgetPrivate::allWidgets->remove(that);
- if (d->focus_next != that) {
- if (d->focus_next)
- d->focus_next->d_func()->focus_prev = d->focus_prev;
- if (d->focus_prev)
- d->focus_prev->d_func()->focus_next = d->focus_next;
- }
+ d->removeFromFocusChain();
#endif
}
};
@@ -987,7 +988,7 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
//give potential windows a bigger "pre-initial" size; create() will give them a new size later
data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
- focus_next = focus_prev = q;
+ initFocusChain();
if ((f & Qt::WindowType_Mask) == Qt::Desktop)
q->create();
@@ -1026,6 +1027,31 @@ void QWidgetPrivate::createRecursively()
}
}
+QRhi *QWidgetPrivate::rhi() const
+{
+ if (QWidgetRepaintManager *repaintManager = maybeRepaintManager())
+ return repaintManager->rhi();
+ else
+ return nullptr;
+}
+
+/*!
+ \internal
+ Returns the closest parent widget that has a QWindow window handle
+
+ \note This behavior is different from nativeParentWidget(), which
+ returns the closest parent that has a QWindow window handle with
+ a created QPlatformWindow, and hence native window (winId).
+*/
+QWidget *QWidgetPrivate::closestParentWidgetWithWindowHandle() const
+{
+ Q_Q(const QWidget);
+ QWidget *parent = q->parentWidget();
+ while (parent && !parent->windowHandle())
+ parent = parent->parentWidget();
+ return parent;
+}
+
QWindow *QWidgetPrivate::windowHandle(WindowHandleMode mode) const
{
if (mode == WindowHandleMode::Direct || mode == WindowHandleMode::Closest) {
@@ -1035,6 +1061,7 @@ QWindow *QWidgetPrivate::windowHandle(WindowHandleMode mode) const
}
}
if (mode == WindowHandleMode::Closest) {
+ // FIXME: Use closestParentWidgetWithWindowHandle instead
if (auto nativeParent = q_func()->nativeParentWidget()) {
if (auto window = nativeParent->windowHandle())
return window;
@@ -1262,7 +1289,7 @@ void QWidgetPrivate::create()
Qt::WindowFlags &flags = data.window_flags;
-#if defined(Q_OS_IOS) || defined(Q_OS_TVOS)
+#if defined(QT_PLATFORM_UIKIT)
if (q->testAttribute(Qt::WA_ContentsMarginsRespectsSafeArea))
flags |= Qt::MaximizeUsingFullscreenGeometryHint;
#endif
@@ -1271,7 +1298,6 @@ void QWidgetPrivate::create()
win->setProperty("_q_showWithoutActivating", QVariant(true));
if (q->testAttribute(Qt::WA_MacAlwaysShowToolWindow))
win->setProperty("_q_macAlwaysShowToolWindow", QVariant(true));
- setNetWmWindowTypes(true); // do nothing if none of WA_X11NetWmWindowType* is set
win->setFlags(flags);
fixPosIncludesFrame();
if (q->testAttribute(Qt::WA_Moved)
@@ -1319,8 +1345,6 @@ void QWidgetPrivate::create()
}
data.window_flags = win->flags();
- if (!win->isTopLevel()) // In a Widget world foreign windows can only be top level
- data.window_flags &= ~Qt::ForeignWindow;
#if QT_CONFIG(xcb)
if (!topData()->role.isNull()) {
@@ -1355,6 +1379,7 @@ void QWidgetPrivate::create()
Q_ASSERT(id != WId(0));
setWinId(id);
}
+ setNetWmWindowTypes(true); // do nothing if none of WA_X11NetWmWindowType* is set
// Check children and create windows for them if necessary
q_createNativeChildrenAndSetParent(q);
@@ -1449,17 +1474,9 @@ QWidget::~QWidget()
// delete layout while we still are a valid widget
delete d->layout;
d->layout = nullptr;
- // Remove myself from focus list
-
- Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
- Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
-
- if (d->focus_next != this) {
- d->focus_next->d_func()->focus_prev = d->focus_prev;
- d->focus_prev->d_func()->focus_next = d->focus_next;
- d->focus_next = d->focus_prev = nullptr;
- }
+ // Remove this from focus list
+ d->removeFromFocusChain(QWidgetPrivate::FocusChainRemovalRule::AssertConsistency);
QT_TRY {
#if QT_CONFIG(graphicsview)
@@ -1659,10 +1676,9 @@ void QWidgetPrivate::deleteExtra()
if (QStyleSheetStyle *proxy = qt_styleSheet(extra->style))
proxy->deref();
#endif
- if (extra->topextra) {
+ if (extra->topextra)
deleteTLSysExtra();
- // extra->topextra->backingStore destroyed in QWidgetPrivate::deleteTLSysExtra()
- }
+
// extra->xic destroyed in QWidget::destroy()
extra.reset();
}
@@ -1672,34 +1688,11 @@ void QWidgetPrivate::deleteSysExtra()
{
}
-static void deleteBackingStore(QWidgetPrivate *d)
-{
- QTLWExtra *topData = d->topData();
-
- delete topData->backingStore;
- topData->backingStore = nullptr;
-}
-
void QWidgetPrivate::deleteTLSysExtra()
{
if (extra && extra->topextra) {
- //the qplatformbackingstore may hold a reference to the window, so the backingstore
- //needs to be deleted first.
-
- extra->topextra->repaintManager.reset(nullptr);
- deleteBackingStore(this);
- extra->topextra->widgetTextures.clear();
-
- //the toplevel might have a context with a "qglcontext associated with it. We need to
- //delete the qglcontext before we delete the qplatformopenglcontext.
- //One unfortunate thing about this is that we potentially create a glContext just to
- //delete it straight afterwards.
- if (extra->topextra->window) {
- extra->topextra->window->destroy();
- }
delete extra->topextra->window;
extra->topextra->window = nullptr;
-
}
}
@@ -2925,7 +2918,7 @@ void QWidget::overrideWindowState(Qt::WindowStates newstate)
\snippet code/src_gui_kernel_qwidget.cpp 0
- In order to restore and activate a minimized window (while
+ To restore and activate a minimized window (while
preserving its maximized and/or full-screen state), use the following:
\snippet code/src_gui_kernel_qwidget.cpp 1
@@ -3001,7 +2994,7 @@ bool QWidget::isFullScreen() const
ICCCM protocol that specifies the communication between X11
clients and the window manager. ICCCM simply does not understand
the concept of non-decorated full-screen windows. Therefore, the
- best we can do is to request a borderless window and place and
+ best you can do is to request a borderless window and place and
resize it to fill the entire screen. Depending on the window
manager, this may or may not work. The borderless window is
requested using MOTIF hints, which are at least partially
@@ -3009,7 +3002,7 @@ bool QWidget::isFullScreen() const
An alternative would be to bypass the window manager entirely and
create a window with the Qt::X11BypassWindowManagerHint flag. This
- has other severe problems though, like totally broken keyboard focus
+ has other severe problems though, like broken keyboard focus
and very strange effects on desktop changes or when the user raises
other windows.
@@ -3109,7 +3102,7 @@ bool QWidget::isEnabledTo(const QWidget *ancestor) const
/*!
Appends the action \a action to this widget's list of actions.
- All QWidgets have a list of \l{QAction}s, however they can be
+ All QWidgets have a list of \l{QAction}s. However, they can be
represented graphically in many different ways. The default use of
the QAction list (as returned by actions()) is to create a context
QMenu.
@@ -3247,6 +3240,7 @@ QAction *QWidget::addAction(const QIcon &icon, const QString &text)
return ret;
}
+#if QT_CONFIG(shortcut)
QAction *QWidget::addAction(const QString &text, const QKeySequence &shortcut)
{
QAction *ret = addAction(text);
@@ -3260,6 +3254,7 @@ QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QKeySe
ret->setShortcut(shortcut);
return ret;
}
+#endif
/*!
\fn QAction *QWidget::addAction(const QString &text, const QObject *receiver, const char* member, Qt::ConnectionType type)
@@ -3317,10 +3312,10 @@ QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QKeySe
#endif // QT_CONFIG(shortcut)
/*!
- \fn template<typename...Args> QAction *QWidget::addAction(const QString &text, Args&&...args)
- \fn template<typename...Args> QAction *QWidget::addAction(const QString &text, const QKeySequence &shortcut, Args&&...args)
- \fn template<typename...Args> QAction *QWidget::addAction(const QIcon &icon, const QString &text, Args&&...args)
- \fn template<typename...Args> QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut, Args&&...args)
+ \fn template<typename...Args, typename = compatible_action_slot_args<Args...>> QAction *QWidget::addAction(const QString &text, Args&&...args)
+ \fn template<typename...Args, typename = compatible_action_slot_args<Args...>> QAction *QWidget::addAction(const QString &text, const QKeySequence &shortcut, Args&&...args)
+ \fn template<typename...Args, typename = compatible_action_slot_args<Args...>> QAction *QWidget::addAction(const QIcon &icon, const QString &text, Args&&...args)
+ \fn template<typename...Args, typename = compatible_action_slot_args<Args...>> QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut, Args&&...args)
\since 6.3
\overload
@@ -3431,7 +3426,7 @@ void QWidgetPrivate::setEnabled_helper(bool enable)
By default, this property is \c false.
- \sa {Drag and Drop}
+ \sa {Drag and Drop in Qt}{Drag and Drop}
*/
bool QWidget::acceptDrops() const
{
@@ -3545,6 +3540,10 @@ int QWidget::y() const
See the \l{Window Geometry} documentation for an overview of geometry
issues with windows.
+ \note Not all windowing systems support setting or querying top level window positions.
+ On such a system, programmatically moving windows may not have any effect, and artificial
+ values may be returned for the current positions, such as \c QPoint(0, 0).
+
\sa frameGeometry, size, x(), y()
*/
QPoint QWidget::pos() const
@@ -3742,7 +3741,7 @@ QRegion QWidget::childrenRegion() const
the current size is smaller.
The minimum size set by this function will override the minimum size
- defined by QLayout. In order to unset the minimum size, use a
+ defined by QLayout. To unset the minimum size, use a
value of \c{QSize(0, 0)}.
By default, this property contains a size with zero width and height.
@@ -4353,7 +4352,7 @@ QWidget *QWidget::nativeParentWidget() const
The background role defines the brush from the widget's \l palette that
is used to render the background.
- If no explicit background role is set, the widget inherts its parent
+ If no explicit background role is set, the widget inherits its parent
widget's background role.
\sa setBackgroundRole(), foregroundRole()
@@ -4497,7 +4496,7 @@ void QWidget::setForegroundRole(QPalette::ColorRole role)
QWidget's palette propagation is similar to its font propagation.
The current style, which is used to render the content of all standard Qt
- widgets, is free to choose colors and brushes from the widget palette, or
+ widgets, is free to choose colors and brushes from the widget palette, or,
in some cases, to ignore the palette (partially, or completely). In
particular, certain styles like GTK style, Mac style, and Windows Vista
style, depend on third party APIs to render the content of widgets,
@@ -6396,16 +6395,19 @@ void QWidget::setFocusProxy(QWidget * w)
break;
}
Q_ASSERT(firstChild); // can't be nullptr since w is a child
- QWidget *oldNext = d->focus_next;
- QWidget *oldPrev = d->focus_prev;
- oldNext->d_func()->focus_prev = oldPrev;
- oldPrev->d_func()->focus_next = oldNext;
-
- oldPrev = firstChild->d_func()->focus_prev;
- d->focus_next = firstChild;
- d->focus_prev = oldPrev;
- oldPrev->d_func()->focus_next = this;
- firstChild->d_func()->focus_prev = this;
+ d->insertIntoFocusChainBefore(firstChild);
+ } else if (w && w->isAncestorOf(this)) {
+ // If the focus proxy is a parent, 'this' has to be inserted directly after its parent in the focus chain
+ // remove it from the chain and insert this into the focus chain after its parent
+
+ // is this the case already?
+ QWidget *parentsNext = w->nextInFocusChain();
+ if (parentsNext == this) {
+ // nothing to do.
+ Q_ASSERT(previousInFocusChain() == w);
+ } else {
+ d->QWidgetPrivate::insertIntoFocusChainAfter(w);
+ }
}
if (moveFocusToProxy)
@@ -6614,7 +6616,9 @@ void QWidgetPrivate::setFocus_sys()
{
Q_Q(QWidget);
// Embedded native widget may have taken the focus; get it back to toplevel
- // if that is the case (QTBUG-25852)
+ // if that is the case (QTBUG-25852), unless widget is a window container.
+ if (extra && extra->hasWindowContainer)
+ return;
// Do not activate in case the popup menu opens another application (QTBUG-70810)
// unless the application is embedded (QTBUG-71991).
if (QWindow *nativeWindow = q->testAttribute(Qt::WA_WState_Created) ? q->window()->windowHandle() : nullptr) {
@@ -6666,8 +6670,8 @@ void QWidgetPrivate::updateFocusChild()
If the widget has active focus, a \l{focusOutEvent()}{focus out event} is sent to this widget to tell it that it has
lost the focus.
- This widget must enable focus setting in order to get the keyboard
- input focus, i.e. it must call setFocusPolicy().
+ This widget must enable focus setting to get the keyboard
+ input focus; that is, it must call setFocusPolicy().
\sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
setFocusPolicy(), QApplication::focusWidget()
@@ -6823,6 +6827,13 @@ QWidget *QWidget::focusWidget() const
return const_cast<QWidget *>(d_func()->focus_child);
}
+QObject *QWidgetPrivate::focusObject()
+{
+ Q_Q(QWidget);
+ QWidget *proxy = deepestFocusProxy();
+ return proxy ? proxy : q;
+}
+
/*!
Returns the next widget in this widget's focus chain.
@@ -6830,7 +6841,8 @@ QWidget *QWidget::focusWidget() const
*/
QWidget *QWidget::nextInFocusChain() const
{
- return const_cast<QWidget *>(d_func()->focus_next);
+ Q_D(const QWidget);
+ return d->nextPrevElementInFocusChain(QWidgetPrivate::FocusDirection::Next);
}
/*!
@@ -6843,7 +6855,8 @@ QWidget *QWidget::nextInFocusChain() const
*/
QWidget *QWidget::previousInFocusChain() const
{
- return const_cast<QWidget *>(d_func()->focus_prev);
+ Q_D(const QWidget);
+ return d->nextPrevElementInFocusChain(QWidgetPrivate::FocusDirection::Previous);
}
/*!
@@ -6913,6 +6926,30 @@ bool QWidget::isActiveWindow() const
}
/*!
+ \fn void QWidget::setTabOrder(std::initializer_list<QWidget *> widgets)
+ \overload
+ \since 6.6
+
+ Sets the tab order for the widgets in the \a widgets list by calling
+ \l{QWidget::setTabOrder(QWidget *, QWidget *)} for each consecutive
+ pair of widgets.
+
+ Instead of setting up each pair manually like this:
+
+ \snippet code/src_gui_kernel_qwidget.cpp 9
+
+ you can call:
+
+ \snippet code/src_gui_kernel_qwidget.cpp 9.list
+
+ The call does not create a closed tab focus loop. If there are more widgets
+ with \l{Qt::TabFocus} focus policy, tabbing on \c{d} will move focus to one
+ of those widgets, not back to \c{a}.
+
+ \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus in Widgets}
+*/
+
+/*!
Puts the \a second widget after the \a first widget in the focus order.
It effectively removes the \a second widget from its focus chain and
@@ -6950,16 +6987,16 @@ void QWidget::setTabOrder(QWidget* first, QWidget *second)
return;
}
- auto determineLastFocusChild = [](QWidget *target, QWidget *&lastFocusChild)
+ const auto determineLastFocusChild = [](QWidget *target, QWidget *noFurtherThan)
{
// Since we need to repeat the same logic for both 'first' and 'second', we add a function that
// determines the last focus child for a widget, taking proxies and compound widgets into account.
// If the target is not a compound widget (it doesn't have a focus proxy that points to a child),
// 'lastFocusChild' will be set to the target itself.
- lastFocusChild = target;
+ QWidget *lastFocusChild = target;
QWidget *focusProxy = target->d_func()->deepestFocusProxy();
- if (!focusProxy || !target->isAncestorOf(focusProxy)) {
+ if (!focusProxy) {
// QTBUG-81097: Another case is possible here. We can have a child
// widget, that sets its focusProxy() to the parent (target).
// An example of such widget is a QLineEdit, nested into
@@ -6972,55 +7009,52 @@ void QWidget::setTabOrder(QWidget* first, QWidget *second)
break;
}
}
- return;
- }
-
- lastFocusChild = focusProxy;
-
- for (QWidget *focusNext = lastFocusChild->d_func()->focus_next;
- focusNext != focusProxy && target->isAncestorOf(focusNext) && focusNext->window() == focusProxy->window();
- focusNext = focusNext->d_func()->focus_next) {
- if (focusNext->focusPolicy() != Qt::NoFocus)
- lastFocusChild = focusNext;
+ } else if (target->isAncestorOf(focusProxy)) {
+ lastFocusChild = focusProxy;
+ for (QWidget *focusNext = lastFocusChild->nextInFocusChain();
+ focusNext != focusProxy && target->isAncestorOf(focusNext) && focusNext->window() == focusProxy->window();
+ focusNext = focusNext->nextInFocusChain()) {
+ if (focusNext == noFurtherThan)
+ break;
+ if (focusNext->focusPolicy() != Qt::NoFocus)
+ lastFocusChild = focusNext;
+ }
}
+ return lastFocusChild;
};
- auto setPrev = [](QWidget *w, QWidget *prev)
- {
- w->d_func()->focus_prev = prev;
- };
- auto setNext = [](QWidget *w, QWidget *next)
- {
- w->d_func()->focus_next = next;
- };
-
- // remove the second widget from the chain
- QWidget *lastFocusChildOfSecond;
- determineLastFocusChild(second, lastFocusChildOfSecond);
- {
- QWidget *oldPrev = second->d_func()->focus_prev;
- QWidget *prevWithFocus = oldPrev;
- while (prevWithFocus->focusPolicy() == Qt::NoFocus)
- prevWithFocus = prevWithFocus->d_func()->focus_prev;
- // only widgets between first and second -> all is fine
- if (prevWithFocus == first)
- return;
- QWidget *oldNext = lastFocusChildOfSecond->d_func()->focus_next;
- setPrev(oldNext, oldPrev);
- setNext(oldPrev, oldNext);
- }
+ // detect inflection in case we have compound widgets
+ QWidget *lastFocusChildOfFirst = determineLastFocusChild(first, second);
+ if (lastFocusChildOfFirst == second)
+ lastFocusChildOfFirst = first;
+ QWidget *lastFocusChildOfSecond = determineLastFocusChild(second, first);
+ if (lastFocusChildOfSecond == first)
+ lastFocusChildOfSecond = second;
+
+ // Return if only NoFocus widgets are between first and second
+ QWidget *oldPrev = second->previousInFocusChain();
+ QWidget *prevWithFocus = oldPrev;
+ while (prevWithFocus->focusPolicy() == Qt::NoFocus)
+ prevWithFocus = prevWithFocus->previousInFocusChain();
+ if (prevWithFocus == first)
+ return;
+ const QWidgetList chain = QWidgetPrivate::takeFromFocusChain(second, lastFocusChildOfSecond);
+ QWidgetPrivate::insertIntoFocusChain(chain, QWidgetPrivate::FocusDirection::Next, lastFocusChildOfFirst);
+}
- // insert the second widget into the chain
- QWidget *lastFocusChildOfFirst;
- determineLastFocusChild(first, lastFocusChildOfFirst);
- {
- QWidget *oldNext = lastFocusChildOfFirst->d_func()->focus_next;
- setPrev(second, lastFocusChildOfFirst);
- setNext(lastFocusChildOfFirst, second);
- setPrev(oldNext, lastFocusChildOfSecond);
- setNext(lastFocusChildOfSecond, oldNext);
+void QWidget::setTabOrder(std::initializer_list<QWidget *> widgets)
+{
+ QWidget *prev = nullptr;
+ for (const auto &widget : widgets) {
+ if (!prev) {
+ prev = widget;
+ } else {
+ QWidget::setTabOrder(prev, widget);
+ prev = widget;
+ }
}
}
+
/*!\internal
Moves the relevant subwidgets of this widget from the \a oldtlw's
@@ -7042,67 +7076,8 @@ void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
if (focus_child)
focus_child->clearFocus();
- // separate the focus chain into new (children of myself) and old (the rest)
- QWidget *firstOld = nullptr;
- //QWidget *firstNew = q; //invariant
- QWidget *o = nullptr; // last in the old list
- QWidget *n = q; // last in the new list
-
- bool prevWasNew = true;
- QWidget *w = focus_next;
-
- //Note: for efficiency, we do not maintain the list invariant inside the loop
- //we append items to the relevant list, and we optimize by not changing pointers
- //when subsequent items are going into the same list.
- while (w != q) {
- bool currentIsNew = q->isAncestorOf(w);
- if (currentIsNew) {
- if (!prevWasNew) {
- //prev was old -- append to new list
- n->d_func()->focus_next = w;
- w->d_func()->focus_prev = n;
- }
- n = w;
- } else {
- if (prevWasNew) {
- //prev was new -- append to old list, if there is one
- if (o) {
- o->d_func()->focus_next = w;
- w->d_func()->focus_prev = o;
- } else {
- // "create" the old list
- firstOld = w;
- }
- }
- o = w;
- }
- w = w->d_func()->focus_next;
- prevWasNew = currentIsNew;
- }
-
- //repair the old list:
- if (firstOld) {
- o->d_func()->focus_next = firstOld;
- firstOld->d_func()->focus_prev = o;
- }
-
- if (!q->isWindow()) {
- QWidget *topLevel = q->window();
- //insert new chain into toplevel's chain
-
- QWidget *prev = topLevel->d_func()->focus_prev;
-
- topLevel->d_func()->focus_prev = n;
- prev->d_func()->focus_next = q;
-
- focus_prev = prev;
- n->d_func()->focus_next = topLevel;
- } else {
- //repair the new list
- n->d_func()->focus_next = q;
- focus_prev = n;
- }
-
+ insertIntoFocusChain(QWidgetPrivate::FocusDirection::Previous, q->window());
+ reparentFocusChildren(QWidgetPrivate::FocusDirection::Next);
}
/*!
@@ -7382,15 +7357,67 @@ QByteArray QWidget::saveGeometry() const
return array;
}
-static void checkRestoredGeometry(const QRect &availableGeometry, QRect *restoredGeometry,
+/*!
+ \internal
+
+ Check a if \a restoredGeometry fits into \a availableGeometry
+ This method is used to verify that a widget is restored to a geometry, which
+ fits into the target screen.
+
+ \param frameHeight represents the height of the widget's title bar, which is expected
+ to be on its top.
+
+ If the size of \a restoredGeometry exceeds \a availableGeometry, its height and width
+ will be resized to be two pixels smaller than \a availableGeometry. An exact match would
+ be full screen.
+
+ If at least one edge of \a restoredGeometry is outside \a availableGeometry,
+ \a restoredGeometry will be moved
+ \list
+ \li down if its top is off screen
+ \li up if its bottom is off screen
+ \li right if its left edge is off screen
+ \li left if its right edge is off screen
+ \endlist
+ */
+void QWidgetPrivate::checkRestoredGeometry(const QRect &availableGeometry, QRect *restoredGeometry,
int frameHeight)
{
- if (!restoredGeometry->intersects(availableGeometry)) {
- restoredGeometry->moveBottom(qMin(restoredGeometry->bottom(), availableGeometry.bottom()));
- restoredGeometry->moveLeft(qMax(restoredGeometry->left(), availableGeometry.left()));
- restoredGeometry->moveRight(qMin(restoredGeometry->right(), availableGeometry.right()));
+ // compare with restored geometry's height increased by frameHeight
+ const int height = restoredGeometry->height() + frameHeight;
+
+ // Step 1: Resize if necessary:
+ // make height / width 2px smaller than screen, because an exact match would be fullscreen
+ if (availableGeometry.height() <= height)
+ restoredGeometry->setHeight(availableGeometry.height() - 2 - frameHeight);
+ if (availableGeometry.width() <= restoredGeometry->width())
+ restoredGeometry->setWidth(availableGeometry.width() - 2);
+
+ // Step 2: Move if necessary:
+ // Construct a rectangle from restored Geometry adjusted by frameHeight
+ const QRect restored = restoredGeometry->adjusted(0, -frameHeight, 0, 0);
+
+ // Return if restoredGeometry (including frame) fits into screen
+ if (availableGeometry.contains(restored))
+ return;
+
+ // (size is correct, but at least one edge is off screen)
+
+ // Top out of bounds => move down
+ if (restored.top() <= availableGeometry.top()) {
+ restoredGeometry->moveTop(availableGeometry.top() + 1 + frameHeight);
+ } else if (restored.bottom() >= availableGeometry.bottom()) {
+ // Bottom out of bounds => move up
+ restoredGeometry->moveBottom(availableGeometry.bottom() - 1);
+ }
+
+ // Left edge out of bounds => move right
+ if (restored.left() <= availableGeometry.left()) {
+ restoredGeometry->moveLeft(availableGeometry.left() + 1);
+ } else if (restored.right() >= availableGeometry.right()) {
+ // Right edge out of bounds => move left
+ restoredGeometry->moveRight(availableGeometry.right() - 1);
}
- restoredGeometry->moveTop(qMax(restoredGeometry->top(), availableGeometry.top() + frameHeight));
}
/*!
@@ -7477,7 +7504,9 @@ bool QWidget::restoreGeometry(const QByteArray &geometry)
return false;
}
- const int frameHeight = 20;
+ const int frameHeight = QApplication::style()
+ ? QApplication::style()->pixelMetric(QStyle::PM_TitleBarHeight, nullptr, this)
+ : 20;
if (!restoredNormalGeometry.isValid())
restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
@@ -7493,11 +7522,11 @@ bool QWidget::restoreGeometry(const QByteArray &geometry)
// Modify the restored geometry if we are about to restore to coordinates
// that would make the window "lost". This happens if:
- // - The restored geometry is completely oustside the available geometry
+ // - The restored geometry is completely or partly oustside the available geometry
// - The title bar is outside the available geometry.
- checkRestoredGeometry(availableGeometry, &restoredGeometry, frameHeight);
- checkRestoredGeometry(availableGeometry, &restoredNormalGeometry, frameHeight);
+ QWidgetPrivate::checkRestoredGeometry(availableGeometry, &restoredGeometry, frameHeight);
+ QWidgetPrivate::checkRestoredGeometry(availableGeometry, &restoredNormalGeometry, frameHeight);
if (maximized || fullScreen) {
// set geometry before setting the window state to make
@@ -7529,6 +7558,8 @@ bool QWidget::restoreGeometry(const QByteArray &geometry)
d_func()->topData()->normalGeometry = restoredNormalGeometry;
} else {
setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
+
+ // FIXME: Why fall back to restoredNormalGeometry if majorVersion <= 2?
if (majorVersion > 2)
setGeometry(restoredGeometry);
else
@@ -7827,21 +7858,29 @@ void QWidget::setUpdatesEnabled(bool enable)
/*!
Shows the widget and its child widgets.
- This is equivalent to calling showFullScreen(), showMaximized(), or setVisible(true),
- depending on the platform's default behavior for the window flags.
+ For child windows, this is equivalent to calling setVisible(true).
+ Otherwise, it is equivalent to calling showFullScreen(), showMaximized(),
+ or setVisible(true), depending on the platform's default behavior for the window flags.
- \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
+ \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
showNormal(), isVisible(), windowFlags()
*/
void QWidget::show()
{
- Qt::WindowState defaultState = QGuiApplicationPrivate::platformIntegration()->defaultWindowState(data->window_flags);
- if (defaultState == Qt::WindowFullScreen)
- showFullScreen();
- else if (defaultState == Qt::WindowMaximized)
- showMaximized();
- else
- setVisible(true); // Don't call showNormal() as not to clobber Qt::Window(Max/Min)imized
+ // Note: We don't call showNormal() as not to clobber Qt::Window(Max/Min)imized
+
+ if (!isWindow()) {
+ setVisible(true);
+ } else {
+ const auto *platformIntegration = QGuiApplicationPrivate::platformIntegration();
+ Qt::WindowState defaultState = platformIntegration->defaultWindowState(data->window_flags);
+ if (defaultState == Qt::WindowFullScreen)
+ showFullScreen();
+ else if (defaultState == Qt::WindowMaximized)
+ showMaximized();
+ else
+ setVisible(true);
+ }
}
/*! \internal
@@ -8208,13 +8247,17 @@ void QWidgetPrivate::hide_sys()
void QWidget::setVisible(bool visible)
{
+ Q_D(QWidget);
+ qCDebug(lcWidgetShowHide) << "Setting visibility of" << this
+ << "with attributes" << WidgetAttributes{this}
+ << "to" << visible << "via QWidget";
+
if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden) == !visible)
return;
// Remember that setVisible was called explicitly
setAttribute(Qt::WA_WState_ExplicitShowHide);
- Q_D(QWidget);
d->setVisible(visible);
}
@@ -8224,6 +8267,10 @@ void QWidget::setVisible(bool visible)
void QWidgetPrivate::setVisible(bool visible)
{
Q_Q(QWidget);
+ qCDebug(lcWidgetShowHide) << "Setting visibility of" << q
+ << "with attributes" << WidgetAttributes{q}
+ << "to" << visible << "via QWidgetPrivate";
+
if (visible) { // show
// Designer uses a trick to make grabWidget work without showing
if (!q->isWindow() && q->parentWidget() && q->parentWidget()->isVisible()
@@ -8303,8 +8350,7 @@ void QWidgetPrivate::setVisible(bool visible)
if (!q->testAttribute(Qt::WA_WState_Hidden)) {
q->setAttribute(Qt::WA_WState_Hidden);
- if (q->testAttribute(Qt::WA_WState_Created))
- hide_helper();
+ hide_helper();
}
// invalidate layout similar to updateGeometry()
@@ -8328,23 +8374,35 @@ void QWidget::setHidden(bool hidden)
setVisible(!hidden);
}
+bool QWidgetPrivate::isExplicitlyHidden() const
+{
+ Q_Q(const QWidget);
+ return q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
+}
+
void QWidgetPrivate::_q_showIfNotHidden()
{
Q_Q(QWidget);
- if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
+ if (!isExplicitlyHidden())
q->setVisible(true);
}
void QWidgetPrivate::showChildren(bool spontaneous)
{
+ Q_Q(QWidget);
+ qCDebug(lcWidgetShowHide) << "Showing children of" << q
+ << "spontaneously" << spontaneous;
+
QList<QObject*> childList = children;
for (int i = 0; i < childList.size(); ++i) {
QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
- if (widget && widget->windowHandle() && !widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
+ if (!widget)
+ continue;
+ qCDebug(lcWidgetShowHide) << "Considering" << widget
+ << "with attributes" << WidgetAttributes{widget};
+ if (widget->windowHandle() && !widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
widget->setAttribute(Qt::WA_WState_Hidden, false);
- if (!widget
- || widget->isWindow()
- || widget->testAttribute(Qt::WA_WState_Hidden))
+ if (widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
continue;
if (spontaneous) {
widget->setAttribute(Qt::WA_Mapped);
@@ -8355,7 +8413,7 @@ void QWidgetPrivate::showChildren(bool spontaneous)
if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
widget->d_func()->show_recursive();
else
- widget->show();
+ widget->d_func()->setVisible(true);
}
}
}
@@ -8363,10 +8421,17 @@ void QWidgetPrivate::showChildren(bool spontaneous)
void QWidgetPrivate::hideChildren(bool spontaneous)
{
Q_Q(QWidget);
+ qCDebug(lcWidgetShowHide) << "Hiding children of" << q
+ << "spontaneously" << spontaneous;
+
QList<QObject*> childList = children;
for (int i = 0; i < childList.size(); ++i) {
QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
- if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
+ if (!widget)
+ continue;
+ qCDebug(lcWidgetShowHide) << "Considering" << widget
+ << "with attributes" << WidgetAttributes{widget};
+ if (widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
continue;
if (spontaneous)
@@ -8424,13 +8489,15 @@ void QWidgetPrivate::hideChildren(bool spontaneous)
*/
bool QWidgetPrivate::handleClose(CloseMode mode)
{
+ Q_Q(QWidget);
+ qCDebug(lcWidgetShowHide) << "Handling close event for" << q;
+
if (data.is_closing)
return true;
// We might not have initiated the close, so update the state now that we know
data.is_closing = true;
- Q_Q(QWidget);
QPointer<QWidget> that = q;
if (data.in_destructor)
@@ -8540,7 +8607,7 @@ bool QWidgetPrivate::close()
when the user minimizes the window, and a spontaneous show event
when the window is restored again.
- You almost never have to reimplement the setVisible() function. If
+ You seldom have to reimplement the setVisible() function. If
you need to change some settings before a widget is shown, use
showEvent() instead. If you need to do some delayed initialization
use the Polish event delivered to the event() function.
@@ -8867,7 +8934,7 @@ bool QWidget::event(QEvent *event)
break;
#endif
case QEvent::KeyPress: {
- QKeyEvent *k = (QKeyEvent *)event;
+ QKeyEvent *k = static_cast<QKeyEvent *>(event);
bool res = false;
if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
if (k->key() == Qt::Key_Backtab
@@ -9260,6 +9327,8 @@ bool QWidget::event(QEvent *event)
const QWindow *win = te->window;
d->setWinId((win && win->handle()) ? win->handle()->winId() : 0);
}
+ break;
+ case QEvent::DevicePixelRatioChange:
if (d->data.fnt.d->dpi != logicalDpiY())
d->updateFont(d->data.fnt);
d->renderToTextureReallyDirty = 1;
@@ -9524,7 +9593,7 @@ void QWidget::tabletEvent(QTabletEvent *event)
implementation if you act upon the key.
\sa keyReleaseEvent(), setFocusPolicy(),
- focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
+ focusInEvent(), focusOutEvent(), event(), QKeyEvent
*/
void QWidget::keyPressEvent(QKeyEvent *event)
@@ -9575,7 +9644,7 @@ void QWidget::keyReleaseEvent(QKeyEvent *event)
is passed in the \a event parameter
A widget normally must setFocusPolicy() to something other than
- Qt::NoFocus in order to receive focus events. (Note that the
+ Qt::NoFocus to receive focus events. (Note that the
application programmer can call setFocus() on any widget, even
those that do not normally accept focus.)
@@ -9601,7 +9670,7 @@ void QWidget::focusInEvent(QFocusEvent *)
passed in the \a event parameter.
A widget normally must setFocusPolicy() to something other than
- Qt::NoFocus in order to receive focus events. (Note that the
+ Qt::NoFocus to receive focus events. (Note that the
application programmer can call setFocus() on any widget, even
those that do not normally accept focus.)
@@ -9701,7 +9770,7 @@ void QWidget::leaveEvent(QEvent *)
never be called; the backingstore will be used instead.
\sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
- {Analog Clock Example}
+ {Analog Clock}
*/
void QWidget::paintEvent(QPaintEvent *)
@@ -9773,13 +9842,8 @@ void QWidget::actionEvent(QActionEvent *)
Main window applications typically use reimplementations of this function to check
whether the user's work has been saved and ask for permission before closing.
- For example, the \l{Qt Widgets - Application Example} uses a helper function to
- determine whether or not to close the window:
-
- \snippet mainwindows/application/mainwindow.cpp 3
- \snippet mainwindows/application/mainwindow.cpp 4
- \sa event(), hide(), close(), QCloseEvent, {Qt Widgets - Application Example}
+ \sa event(), hide(), close(), QCloseEvent
*/
void QWidget::closeEvent(QCloseEvent *event)
@@ -9868,7 +9932,7 @@ QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
is set, the input method may change its visual components to reflect
that only numbers can be entered.
- \warning Some widgets require certain flags in order to work as
+ \warning Some widgets require certain flags to work as
intended. To set a flag, do \c{w->setInputMethodHints(w->inputMethodHints()|f)}
instead of \c{w->setInputMethodHints(f)}.
@@ -10118,7 +10182,7 @@ void QWidget::ensurePolished() const
Returns the mask currently set on a widget. If no mask is set the
return value will be an empty region.
- \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
+ \sa setMask(), clearMask(), QRegion::isEmpty()
*/
QRegion QWidget::mask() const
{
@@ -10539,7 +10603,7 @@ void QWidget::setParent(QWidget *parent)
setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
}
-static void sendWindowChangeToTextureChildrenRecursively(QWidget *widget, QEvent::Type eventType)
+void qSendWindowChangeToTextureChildrenRecursively(QWidget *widget, QEvent::Type eventType)
{
QWidgetPrivate *d = QWidgetPrivate::get(widget);
if (d->renderToTexture) {
@@ -10549,8 +10613,14 @@ static void sendWindowChangeToTextureChildrenRecursively(QWidget *widget, QEvent
for (int i = 0; i < d->children.size(); ++i) {
QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
- if (w && !w->isWindow() && QWidgetPrivate::get(w)->textureChildSeen)
- sendWindowChangeToTextureChildrenRecursively(w, eventType);
+ if (w && !w->isWindow())
+ qSendWindowChangeToTextureChildrenRecursively(w, eventType);
+ }
+
+ // Notify QWidgetWindow after we've notified all child QWidgets
+ if (auto *window = d->windowHandle(QWidgetPrivate::WindowHandleMode::Direct)) {
+ QEvent e(eventType);
+ QCoreApplication::sendEvent(window, &e);
}
}
@@ -10582,6 +10652,7 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
const bool resized = testAttribute(Qt::WA_Resized);
const bool wasCreated = testAttribute(Qt::WA_WState_Created);
QWidget *oldtlw = window();
+ Q_ASSERT(oldtlw);
if (f & Qt::Window) // Frame geometry likely changes, refresh.
d->data.fstrut_dirty = true;
@@ -10600,7 +10671,20 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
if (wasCreated) {
if (!testAttribute(Qt::WA_WState_Hidden)) {
+ // Hiding the widget will set WA_WState_Hidden as well, which would
+ // normally require the widget to be explicitly shown again to become
+ // visible, even as a child widget. But we refine this value later in
+ // setParent_sys(), applying WA_WState_Hidden based on whether the
+ // widget is a top level or not.
hide();
+
+ // We reset WA_WState_ExplicitShowHide here, likely as a remnant of
+ // when we only had QWidget::setVisible(), which is treated as an
+ // explicit show/hide. Nowadays we have QWidgetPrivate::setVisible(),
+ // that allows us to hide a widget without affecting ExplicitShowHide.
+ // Though it can be argued that ExplicitShowHide should reflect the
+ // last update of the widget's state, so if we hide the widget as a
+ // side effect of changing parent, perhaps we _should_ reset it?
setAttribute(Qt::WA_WState_ExplicitShowHide, false);
}
if (newParent) {
@@ -10611,8 +10695,8 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
// texture-based widgets need a pre-notification when their associated top-level window changes
// This is not under the wasCreated/newParent conditions above in order to also play nice with QDockWidget.
- if (d->textureChildSeen && ((!parent && parentWidget()) || (parent && parent->window() != oldtlw)))
- sendWindowChangeToTextureChildrenRecursively(this, QEvent::WindowAboutToChangeInternal);
+ if (oldtlw->d_func()->usesRhiFlush && ((!parent && parentWidget()) || (parent && parent->window() != oldtlw)))
+ qSendWindowChangeToTextureChildrenRecursively(this, QEvent::WindowAboutToChangeInternal);
// If we get parented into another window, children will be folded
// into the new parent's focus chain, so clear focus now.
@@ -10692,8 +10776,8 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
// texture-based widgets need another event when their top-level window
// changes (more precisely, has already changed at this point)
- if (d->textureChildSeen && oldtlw != window())
- sendWindowChangeToTextureChildrenRecursively(this, QEvent::WindowChangeInternal);
+ if (oldtlw->d_func()->usesRhiFlush && oldtlw != window())
+ qSendWindowChangeToTextureChildrenRecursively(this, QEvent::WindowChangeInternal);
if (!wasCreated) {
if (isWindow() || parentWidget()->isVisible())
@@ -10727,12 +10811,26 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
// do it on newtlw instead, the performance implications of that are
// problematic when it comes to large widget trees.
if (q_evaluateRhiConfig(this, nullptr, &surfaceType)) {
+ const bool wasUsingRhiFlush = newtlw->d_func()->usesRhiFlush;
newtlw->d_func()->usesRhiFlush = true;
+ bool recreate = false;
if (QWindow *w = newtlw->windowHandle()) {
- if (w->surfaceType() != surfaceType) {
- newtlw->destroy();
- newtlw->create();
- }
+ if (w->surfaceType() != surfaceType || !wasUsingRhiFlush)
+ recreate = true;
+ }
+ // QTBUG-115652: Besides the toplevel the nativeParentWidget()'s QWindow must be checked as well.
+ if (QWindow *w = d->windowHandle(QWidgetPrivate::WindowHandleMode::Closest)) {
+ if (w->surfaceType() != surfaceType)
+ recreate = true;
+ }
+ if (recreate) {
+ const auto windowStateBeforeDestroy = newtlw->windowState();
+ const auto visibilityBeforeDestroy = newtlw->isVisible();
+ newtlw->destroy();
+ newtlw->create();
+ Q_ASSERT(newtlw->windowHandle());
+ newtlw->windowHandle()->setWindowStates(windowStateBeforeDestroy);
+ QWidgetPrivate::get(newtlw)->setVisible(visibilityBeforeDestroy);
}
}
}
@@ -10756,57 +10854,61 @@ void QWidgetPrivate::setParent_sys(QWidget *newparent, Qt::WindowFlags f)
setWinId(0);
- if (parent != newparent) {
- QObjectPrivate::setParent_helper(newparent); //### why does this have to be done in the _sys function???
- if (q->windowHandle()) {
- q->windowHandle()->setFlags(f);
- QWidget *parentWithWindow =
- newparent ? (newparent->windowHandle() ? newparent : newparent->nativeParentWidget()) : nullptr;
- if (parentWithWindow) {
- QWidget *topLevel = parentWithWindow->window();
- if ((f & Qt::Window) && topLevel && topLevel->windowHandle()) {
- q->windowHandle()->setTransientParent(topLevel->windowHandle());
- q->windowHandle()->setParent(nullptr);
- } else {
- q->windowHandle()->setTransientParent(nullptr);
- q->windowHandle()->setParent(parentWithWindow->windowHandle());
- }
- } else {
- q->windowHandle()->setTransientParent(nullptr);
- q->windowHandle()->setParent(nullptr);
- }
- }
- }
-
if (!newparent) {
f |= Qt::Window;
if (parent)
targetScreen = q->parentWidget()->window()->screen();
}
- bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
+ const bool destroyWindow = (
+ // Reparenting top level to child
+ (oldFlags & Qt::Window) && !(f & Qt::Window)
+ // And we can dispose of the window
+ && wasCreated && !q->testAttribute(Qt::WA_NativeWindow)
+ );
- // Reparenting toplevel to child
- if (wasCreated && !(f & Qt::Window) && (oldFlags & Qt::Window) && !q->testAttribute(Qt::WA_NativeWindow)) {
- if (extra && extra->hasWindowContainer)
- QWindowContainer::toplevelAboutToBeDestroyed(q);
+ if (parent != newparent) {
+ // Update object parent now, so we can resolve new parent window below
+ QObjectPrivate::setParent_helper(newparent);
- QWindow *newParentWindow = newparent->windowHandle();
- if (!newParentWindow)
- if (QWidget *npw = newparent->nativeParentWidget())
- newParentWindow = npw->windowHandle();
+ if (q->windowHandle())
+ q->windowHandle()->setFlags(f);
- for (QObject *child : q->windowHandle()->children()) {
- QWindow *childWindow = qobject_cast<QWindow *>(child);
- if (!childWindow)
- continue;
+ // If the widget itself or any of its children have been created,
+ // we need to reparent their QWindows as well.
+ QWidget *parentWithWindow = closestParentWidgetWithWindowHandle();
+ // But if the widget is about to be destroyed we must skip the
+ // widget itself, and only reparent children.
+ if (destroyWindow)
+ reparentWidgetWindowChildren(parentWithWindow);
+ else
+ reparentWidgetWindows(parentWithWindow, f);
+ }
+
+ bool explicitlyHidden = isExplicitlyHidden();
- QWidgetWindow *childWW = qobject_cast<QWidgetWindow *>(childWindow);
- QWidget *childWidget = childWW ? childWW->widget() : nullptr;
- if (!childWW || (childWidget && childWidget->testAttribute(Qt::WA_NativeWindow)))
- childWindow->setParent(newParentWindow);
+ if (destroyWindow) {
+ if (extra && extra->hasWindowContainer)
+ QWindowContainer::toplevelAboutToBeDestroyed(q);
+
+ // There shouldn't be any QWindow children left, but if there
+ // are, re-parent them now, before we destroy.
+ if (!q->windowHandle()->children().isEmpty()) {
+ QWidget *parentWithWindow = closestParentWidgetWithWindowHandle();
+ QWindow *newParentWindow = parentWithWindow ? parentWithWindow->windowHandle() : nullptr;
+ for (QObject *child : q->windowHandle()->children()) {
+ if (QWindow *childWindow = qobject_cast<QWindow *>(child)) {
+ qCWarning(lcWidgetWindow) << "Reparenting" << childWindow
+ << "before destroying" << this;
+ childWindow->setParent(newParentWindow);
+ }
+ }
}
- q->destroy();
+
+ // We have reparented any child windows of the widget we are
+ // about to destroy to the new parent window handle, so we can
+ // safely destroy this widget without destroying sub windows.
+ q->destroy(true, false);
}
adjustFlags(f, q);
@@ -10832,6 +10934,53 @@ void QWidgetPrivate::setParent_sys(QWidget *newparent, Qt::WindowFlags f)
}
}
+void QWidgetPrivate::reparentWidgetWindows(QWidget *parentWithWindow, Qt::WindowFlags windowFlags)
+{
+ if (QWindow *window = windowHandle()) {
+ // Reparent this QWindow, and all QWindow children will follow
+ if (parentWithWindow) {
+ // The reparented widget has not updated its window flags yet,
+ // so we can't ask the widget directly. And we can't use the
+ // QWindow flags, as unlike QWidgets the QWindow flags always
+ // reflect Qt::Window, even for child windows. And we can't use
+ // QWindow::isTopLevel() either, as that depends on the parent,
+ // which we are in the process of updating. So we propagate the
+ // new flags of the reparented window from setParent_sys().
+ if (windowFlags & Qt::Window) {
+ // Top level windows can only have transient parents,
+ // and the transient parent must be another top level.
+ QWidget *topLevel = parentWithWindow->window();
+ auto *transientParent = topLevel->windowHandle();
+ Q_ASSERT(transientParent);
+ qCDebug(lcWidgetWindow) << "Setting" << window << "transient parent to" << transientParent;
+ window->setTransientParent(transientParent);
+ window->setParent(nullptr);
+ } else {
+ auto *parentWindow = parentWithWindow->windowHandle();
+ qCDebug(lcWidgetWindow) << "Reparenting" << window << "into" << parentWindow;
+ window->setTransientParent(nullptr);
+ window->setParent(parentWindow);
+ }
+ } else {
+ qCDebug(lcWidgetWindow) << "Making" << window << "top level window";
+ window->setTransientParent(nullptr);
+ window->setParent(nullptr);
+ }
+ } else {
+ reparentWidgetWindowChildren(parentWithWindow);
+ }
+}
+
+void QWidgetPrivate::reparentWidgetWindowChildren(QWidget *parentWithWindow)
+{
+ for (auto *child : std::as_const(children)) {
+ if (auto *childWidget = qobject_cast<QWidget*>(child)) {
+ auto *childPrivate = QWidgetPrivate::get(childWidget);
+ childPrivate->reparentWidgetWindows(parentWithWindow);
+ }
+ }
+}
+
/*!
Scrolls the widget including its children \a dx pixels to the
right and \a dy downward. Both \a dx and \a dy may be negative.
@@ -10926,7 +11075,7 @@ void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r)
unless updates are disabled or the widget is hidden.
We suggest only using repaint() if you need an immediate repaint,
- for example during animation. In almost all circumstances update()
+ for example during animation. In most circumstances update()
is better, as it permits Qt to optimize for speed and minimize
flicker.
@@ -11013,7 +11162,7 @@ void QWidgetPrivate::repaint(T r)
If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
responsible for painting all its pixels with an opaque color.
- \sa repaint(), paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
+ \sa repaint(), paintEvent(), setUpdatesEnabled(), {Analog Clock}
*/
void QWidget::update()
{
@@ -11422,8 +11571,7 @@ void QWidgetPrivate::setWindowOpacity_sys(qreal level)
its parent because other children of the parent might have been
modified.
- \sa windowTitle, {Qt Widgets - Application Example}, {SDI Example},
- {MDI Example}
+ \sa windowTitle
*/
bool QWidget::isWindowModified() const
{
@@ -12114,7 +12262,7 @@ void QWidget::setBackingStore(QBackingStore *store)
return;
QBackingStore *oldStore = topData->backingStore;
- deleteBackingStore(d);
+ delete topData->backingStore;
topData->backingStore = store;
QWidgetRepaintManager *repaintManager = d->maybeRepaintManager();
@@ -12312,7 +12460,7 @@ void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
if ((windowType() == Qt::Popup) && qApp)
qApp->d_func()->closePopup(this);
- if (this == QApplicationPrivate::active_window)
+ if (this == qApp->activeWindow())
QApplicationPrivate::setActiveWindow(nullptr);
if (QWidget::mouseGrabber() == this)
releaseMouse();
@@ -12550,7 +12698,7 @@ static void releaseMouseGrabOfWidget(QWidget *widget)
terminal. Use this function with extreme caution, and consider
using the \c -nograb command line option while debugging.
- It is almost never necessary to grab the mouse when using Qt, as
+ It is seldom necessary to grab the mouse when using Qt, as
Qt grabs and releases it sensibly. In particular, Qt grabs the
mouse when a mouse button is pressed and keeps it until the last
button is released.
@@ -12752,9 +12900,8 @@ int QWidget::metric(PaintDeviceMetric m) const
// Note: keep in sync with QBackingStorePrivate::backingStoreDevicePixelRatio()!
static bool downscale = qEnvironmentVariableIntValue("QT_WIDGETS_HIGHDPI_DOWNSCALE") > 0;
QWindow *window = this->window()->windowHandle();
- if (downscale && window)
- return std::ceil(window->devicePixelRatio());
-
+ if (window)
+ return downscale ? std::ceil(window->devicePixelRatio()) : window->devicePixelRatio();
return screen->devicePixelRatio();
};
@@ -12850,8 +12997,16 @@ QPainter *QWidget::sharedPainter() const
widget, window system controls in that area may or may not be
visible, depending on the platform.
- Note that this effect can be slow if the region is particularly
- complex.
+ Since QRegion allows arbitrarily complex regions to be created, widget
+ masks can be made to suit the most unconventionally-shaped windows, and
+ even allow widgets to be displayed with holes in them. Note that this
+ effect can be slow if the region is particularly complex.
+
+ Widget masks are used to hint to the window system that the application
+ does not want mouse events for areas outside the mask. On most systems,
+ they also result in coarse visual clipping. To get smooth window edges, use
+ translucent background and anti-aliased painting instead, as shown in the
+ \l{Translucent Background} example.
\sa windowOpacity
*/
@@ -12937,7 +13092,7 @@ void QWidgetPrivate::setMask_sys(const QRegion &region)
Masked widgets receive mouse events only on their visible
portions.
- \sa clearMask(), windowOpacity(), {Shaped Clock Example}
+ \sa clearMask(), windowOpacity()
*/
void QWidget::setMask(const QBitmap &bitmap)
{
@@ -13032,22 +13187,47 @@ void QWidgetPrivate::setNetWmWindowTypes(bool skipIfMissing)
#endif
}
+/*!
+ \internal
+ \return \c true, if a child with \param policy exists and isn't a child of \param excludeChildrenOf.
+ Return false otherwise.
+ */
+bool QWidgetPrivate::hasChildWithFocusPolicy(Qt::FocusPolicy policy, const QWidget *excludeChildrenOf) const
+{
+ Q_Q(const QWidget);
+ const QWidgetList &children = q->findChildren<QWidget *>(Qt::FindChildrenRecursively);
+ for (const auto *child : children) {
+ if (child->focusPolicy() == policy && child->isEnabled()
+ && (!excludeChildrenOf || !excludeChildrenOf->isAncestorOf(child))) {
+ return true;
+ }
+ }
+ return false;
+}
+
#ifndef QT_NO_DEBUG_STREAM
-static inline void formatWidgetAttributes(QDebug debug, const QWidget *widget)
+namespace {
+QDebug operator<<(QDebug debug, const WidgetAttributes &attributes)
{
- const QMetaObject *qtMo = qt_getEnumMetaObject(Qt::WA_AttributeCount);
- const QMetaEnum me = qtMo->enumerator(qtMo->indexOfEnumerator("WidgetAttribute"));
- debug << ", attributes=[";
- int count = 0;
- for (int a = 0; a < Qt::WA_AttributeCount; ++a) {
- if (widget->testAttribute(static_cast<Qt::WidgetAttribute>(a))) {
- if (count++)
- debug << ',';
- debug << me.valueToKey(a);
+ const QDebugStateSaver saver(debug);
+ debug.nospace();
+ debug << '[';
+ if (const QWidget *widget = attributes.widget) {
+ const QMetaObject *qtMo = qt_getEnumMetaObject(Qt::WA_AttributeCount);
+ const QMetaEnum me = qtMo->enumerator(qtMo->indexOfEnumerator("WidgetAttribute"));
+ int count = 0;
+ for (int a = 0; a < Qt::WA_AttributeCount; ++a) {
+ if (widget->testAttribute(static_cast<Qt::WidgetAttribute>(a))) {
+ if (count++)
+ debug << ',';
+ debug << me.valueToKey(a);
+ }
}
}
debug << ']';
+ return debug;
+}
}
QDebug operator<<(QDebug debug, const QWidget *widget)
@@ -13067,7 +13247,7 @@ QDebug operator<<(QDebug debug, const QWidget *widget)
debug << ", disabled";
debug << ", states=" << widget->windowState()
<< ", type=" << widget->windowType() << ", flags=" << widget->windowFlags();
- formatWidgetAttributes(debug, widget);
+ debug << ", attributes=" << WidgetAttributes{widget};
if (widget->isWindow())
debug << ", window";
debug << ", " << geometry.width() << 'x' << geometry.height()
@@ -13091,6 +13271,399 @@ QDebug operator<<(QDebug debug, const QWidget *widget)
}
#endif // !QT_NO_DEBUG_STREAM
+
+// *************************** Focus abstraction ************************************
+
+#define FOCUS_NEXT(w) w->d_func()->focus_next
+#define FOCUS_PREV(w) w->d_func()->focus_prev
+
+/*!
+ \internal
+ \return next or previous element in the focus chain, depending on
+ \param direction, irrespective of focus proxies or widgets with Qt::NoFocus.
+ */
+QWidget *QWidgetPrivate::nextPrevElementInFocusChain(FocusDirection direction) const
+{
+ Q_Q(const QWidget);
+ return direction == FocusDirection::Next ? FOCUS_NEXT(q) : FOCUS_PREV(q);
+}
+
+/*!
+ \internal
+ Removes a widget from the focus chain, respecting the flags set in \param rules.
+ \list
+ \li EnsureFocusOut: If the widget has input focus, transfer focus to the next or previous widget
+ in the focus chain, depending on \param direction.
+ \li RemoveInconsistent: Remove the widget, even if its focus chain is inconsistent.
+ \li AssertConsistency: qFatal, if the focus chain is inconsistent. This is used in the QWidget destructor.
+ \endlist
+ \return \c true if the widget has been removed, otherwise \c false.
+ */
+bool QWidgetPrivate::removeFromFocusChain(FocusChainRemovalRules rules, FocusDirection direction)
+{
+ Q_Q(QWidget);
+ if (!isFocusChainConsistent()) {
+#ifdef QT_DEBUG
+ if (rules.testFlag(FocusChainRemovalRule::AssertConsistency))
+ qFatal() << q << "has inconsistent focus chain.";
+#endif
+ qCDebug(lcWidgetFocus) << q << "wasn't removed, because of inconsistent focus chain.";
+ return false;
+ }
+
+ if (!isInFocusChain()) {
+ qCDebug(lcWidgetFocus) << q << "wasn't removed, because it is not part of a focus chain.";
+ return false;
+ }
+
+ if (rules.testFlag(FocusChainRemovalRule::EnsureFocusOut))
+ q->focusNextPrevChild(direction == FocusDirection::Next);
+
+ FOCUS_NEXT(FOCUS_PREV(q)) = FOCUS_NEXT(q);
+ FOCUS_PREV(FOCUS_NEXT(q)) = FOCUS_PREV(q);
+ initFocusChain();
+ qCDebug(lcWidgetFocus) << q << "removed from focus chain.";
+ return true;
+}
+
+/*!
+ \internal
+ Initialises the focus chain by making the widget point to itself.
+ */
+void QWidgetPrivate::initFocusChain()
+{
+ Q_Q(QWidget);
+ qCDebug(lcWidgetFocus) << "Initializing focus chain of" << q;
+ FOCUS_PREV(q) = q;
+ FOCUS_NEXT(q) = q;
+}
+
+/*!
+ \internal
+ Reads QWidget children, which are not part of a focus chain yet.
+ Inserts them into the focus chain before or after the widget,
+ depending on \param direction and in the order of their creation.
+ This is used, when QWidget::setParent() causes a widget to change toplevel windows.
+ */
+void QWidgetPrivate::reparentFocusChildren(FocusDirection direction)
+{
+ Q_Q(QWidget);
+ QWidgetList focusChildrenInsideChain;
+ QDuplicateTracker<QWidget *> seen;
+ QWidget *widget = q->nextInFocusChain();
+ while (q->isAncestorOf(widget)
+ && !seen.hasSeen(widget)
+ && widget != q->window()) {
+ if (widget->focusPolicy() != Qt::NoFocus)
+ focusChildrenInsideChain << widget;
+
+ widget = direction == FocusDirection::Next ? widget->nextInFocusChain()
+ : widget->previousInFocusChain();
+ }
+
+ const QWidgetList children = q->findChildren<QWidget *>(Qt::FindDirectChildrenOnly);
+ QWidgetList focusChildrenOutsideChain;
+ for (auto *child : children) {
+ if (!focusChildrenInsideChain.contains(child))
+ focusChildrenOutsideChain << child;
+ }
+ if (focusChildrenOutsideChain.isEmpty())
+ return;
+
+ QWidget *previous = q;
+ for (auto *child : focusChildrenOutsideChain) {
+ child->d_func()->insertIntoFocusChain(direction, previous);
+ previous = child;
+ }
+}
+
+/*!
+ \internal
+ Inserts a widget into the focus chain before or after \param position, depending on
+ \param direction.
+ \return \c true, if the insertion has changed the focus chain, otherwise \c false.
+ */
+bool QWidgetPrivate::insertIntoFocusChain(FocusDirection direction, QWidget *position)
+{
+ Q_Q(QWidget);
+ Q_ASSERT(position);
+ QWidget *next = FOCUS_NEXT(q);
+ QWidget *previous = FOCUS_PREV(q);
+
+ switch (direction) {
+ case FocusDirection::Next:
+ if (previous == position) {
+ qCDebug(lcWidgetFocus) << "No-op insertion." << q << "is already before" << position;
+ return false;
+ }
+
+ removeFromFocusChain(FocusChainRemovalRule::AssertConsistency);
+
+ FOCUS_NEXT(q) = FOCUS_NEXT(position);
+ FOCUS_PREV(FOCUS_NEXT(position)) = q;
+ FOCUS_NEXT(position) = q;
+ FOCUS_PREV(q) = position;
+ qCDebug(lcWidgetFocus) << q << "inserted after" << position;
+ break;
+
+ case FocusDirection::Previous:
+ if (next == position) {
+ qCDebug(lcWidgetFocus) << "No-op insertion." << q << "is already after" << position;
+ return false;
+ }
+
+ removeFromFocusChain(FocusChainRemovalRule::AssertConsistency);
+
+ FOCUS_PREV(q) = FOCUS_PREV(position);
+ FOCUS_NEXT(FOCUS_PREV(position)) = q;
+ FOCUS_PREV(position) = q;
+ FOCUS_NEXT(q) = position;
+ qCDebug(lcWidgetFocus) << q << "inserted before" << position;
+ break;
+ }
+
+ Q_ASSERT(isFocusChainConsistent());
+ return true;
+}
+
+/*!
+ \internal
+ Convenience override to insert a QWidgetList \param toBeInserted into the focus chain
+ before or after \param position, depending on \param direction.
+ \return \c true, if the insertion has changed the focus chain, otherwise \c false.
+ \note
+ \param toBeInserted must be a consistent focus chain.
+ */
+bool QWidgetPrivate::insertIntoFocusChain(const QWidgetList &toBeInserted,
+ FocusDirection direction, QWidget *position)
+{
+ if (toBeInserted.isEmpty()) {
+ qCDebug(lcWidgetFocus) << "No-op insertion of an empty list";
+ return false;
+ }
+
+ Q_ASSERT_X(!toBeInserted.contains(position),
+ Q_FUNC_INFO,
+ "Coding error: toBeInserted contains position");
+
+ QWidget *first = toBeInserted.constFirst();
+ QWidget *last = toBeInserted.constLast();
+
+ // Call QWidget override to log accordingly
+ if (toBeInserted.count() == 1)
+ return first->d_func()->insertIntoFocusChain(direction, position);
+
+ Q_ASSERT(first != last);
+ switch (direction) {
+ case FocusDirection::Previous:
+ if (FOCUS_PREV(position) == last) {
+ qCDebug(lcWidgetFocus) << "No-op insertion." << toBeInserted << "is already before"
+ << position;
+ return false;
+ }
+ FOCUS_NEXT(FOCUS_PREV(position)) = first;
+ FOCUS_PREV(first) = FOCUS_PREV(position);
+ FOCUS_NEXT(last) = position;
+ FOCUS_PREV(position) = last;
+ qCDebug(lcWidgetFocus) << toBeInserted << "inserted before" << position;
+ break;
+ case FocusDirection::Next:
+ if (FOCUS_PREV(position) == last) {
+ qCDebug(lcWidgetFocus) << "No-op insertion." << toBeInserted << "is already after"
+ << position;
+ return false;
+ }
+ FOCUS_PREV(FOCUS_NEXT(position)) = last;
+ FOCUS_NEXT(last) = FOCUS_NEXT(position);
+ FOCUS_PREV(first) = position;
+ FOCUS_NEXT(position) = first;
+ qCDebug(lcWidgetFocus) << toBeInserted << "inserted after" << position;
+ break;
+ }
+
+ Q_ASSERT(position->d_func()->isFocusChainConsistent());
+ return true;
+}
+
+/*!
+ \internal
+ \return a QWidgetList, representing the part of the focus chain,
+ starting with \param from and ending with \param to, in \param direction.
+ */
+QWidgetList focusPath(QWidget *from, QWidget *to, QWidgetPrivate::FocusDirection direction)
+{
+ QWidgetList path({from});
+ if (from == to)
+ return path;
+
+ QWidget *current = from;
+ do {
+ switch (direction) {
+ case QWidgetPrivate::FocusDirection::Previous:
+ current = current->previousInFocusChain();
+ break;
+ case QWidgetPrivate::FocusDirection::Next:
+ current = current->nextInFocusChain();
+ break;
+ }
+ if (path.contains(current))
+ return QWidgetList();
+ path << current;
+ } while (current != to);
+
+ return path;
+}
+
+/*!
+ \internal
+ Removes the part from the focus chain starting with \param from and ending with \param to,
+ in \param direction.
+ \return removed part as a QWidgetList.
+ */
+QWidgetList QWidgetPrivate::takeFromFocusChain(QWidget *from,
+ QWidget *to,
+ FocusDirection direction)
+{
+ // Check if there is a path from->to in direction
+ const QWidgetList path = focusPath(from, to , direction);
+ if (path.isEmpty()) {
+ qCDebug(lcWidgetFocus) << "No-op removal. Focus chain from" << from << "doesn't lead to " << to;
+ return QWidgetList();
+ }
+
+ QWidget *first = path.constFirst();
+ QWidget *last = path.constLast();
+ if (first == last) {
+ first->d_func()->removeFromFocusChain();
+ return QWidgetList({first});
+ }
+
+ FOCUS_NEXT(FOCUS_PREV(first)) = FOCUS_NEXT(last);
+ FOCUS_PREV(FOCUS_NEXT(last)) = FOCUS_PREV(first);
+ FOCUS_PREV(first) = last;
+ FOCUS_NEXT(last) = first;
+ qCDebug(lcWidgetFocus) << path << "removed from focus chain";
+ return path;
+}
+
+/*!
+ \internal
+ \return The last focus child of the widget, traversing the focus chain no further than
+ \param noFurtherThan.
+ */
+QWidget *QWidgetPrivate::determineLastFocusChild(QWidget *noFurtherThan)
+{
+ Q_Q(QWidget);
+ // Since we need to repeat the same logic for both 'first' and 'second', we add a function
+ // that determines the last focus child for a widget, taking proxies and compound widgets into
+ // account. If the target is not a compound widget (it doesn't have a focus proxy that points
+ // to a child), 'lastFocusChild' will be set to the target itself.
+ QWidget *lastFocusChild = q;
+
+ QWidget *focusProxy = deepestFocusProxy();
+ if (!focusProxy) {
+ // QTBUG-81097: Another case is possible here. We can have a child
+ // widget, that sets its focusProxy() to the parent (target).
+ // An example of such widget is a QLineEdit, nested into
+ // a QAbstractSpinBox. In this case such widget should be considered
+ // the last focus child.
+ for (auto *object : std::as_const(q->children())) {
+ QWidget *w = qobject_cast<QWidget *>(object);
+ if (w && w->focusProxy() == q) {
+ lastFocusChild = w;
+ break;
+ }
+ }
+ } else if (q->isAncestorOf(focusProxy)) {
+ lastFocusChild = focusProxy;
+ for (QWidget *focusNext = lastFocusChild->nextInFocusChain();
+ focusNext != focusProxy && q->isAncestorOf(focusNext)
+ && focusNext->window() == focusProxy->window();
+ focusNext = focusNext->nextInFocusChain()) {
+ if (focusNext == noFurtherThan)
+ break;
+ if (focusNext->focusPolicy() != Qt::NoFocus)
+ lastFocusChild = focusNext;
+ }
+ }
+ return lastFocusChild;
+};
+
+/*!
+ \internal
+ \return \c true, if the widget is part of a focus chain and \c false otherwise.
+ A widget is considered to be part of a focus chain, neither FOCUS_NEXT, nor FOCUS_PREV
+ are pointing to the widget itself.
+
+ \note
+ This method doesn't check the consistency of the focus chain.
+ If multiple widgets have been removed from the focus chain by takeFromFocusChain(),
+ isInFocusChain() will return \c true for all of those widgets, even if they represent
+ an inconsistent focus chain.
+ */
+bool QWidgetPrivate::isInFocusChain() const
+{
+ Q_Q(const QWidget);
+ return !(FOCUS_NEXT(q) == q && FOCUS_PREV(q) == q);
+}
+
+/*!
+ \internal
+ A focus chain is consistent, when it is circular: Following the chain in either direction
+ has to return to the beginning. This is why a newly constructed widget points to itself,
+ when the focus chain has been initialized. A newly constructed widget is considered to have
+ a consistent focus chain, while not being part of a focus chain.
+
+ This method returns \c true early, if a widget is pointing to itself.
+ It returns \c false, if one of the following is detected:
+ \list
+ \li nullptr found in a previous/next pointer.
+ \li broken chain: widget A is B's previous, but B isn't A's next.
+ \li chain isn't closed: starting at A doesn't lead back to A.
+ \endlist
+ It return \c true, if none of the above is observed.
+
+ \note
+ The focus chain is checked only in forward direction.
+ This is sufficient, because the check for a broken chain asserts consistent paths
+ in both directions.
+ */
+bool QWidgetPrivate::isFocusChainConsistent() const
+{
+ Q_Q(const QWidget);
+ if (!isInFocusChain())
+ return true;
+
+ const QWidget *position = q;
+
+ for (int i = 0; i < QApplication::allWidgets().count(); ++i) {
+ if (!FOCUS_PREV(position) || !FOCUS_NEXT(position)) {
+ qCDebug(lcWidgetFocus) << "Nullptr found at:" << position
+ << "Previous pointing to" << FOCUS_PREV(position)
+ << "Next pointing to" << FOCUS_NEXT(position);
+ return false;
+ }
+ if (!(FOCUS_PREV(FOCUS_NEXT(position)) == position
+ && FOCUS_NEXT(FOCUS_PREV(position)) == position)) {
+ qCDebug(lcWidgetFocus) << "Inconsistent focus chain at:" << position
+ << "Previous pointing to" << FOCUS_PREV(FOCUS_NEXT(position))
+ << "Next pointing to" << FOCUS_NEXT(FOCUS_PREV(position));
+ return false;
+ }
+ position = FOCUS_NEXT(position);
+ if (position == q)
+ return true;
+
+ }
+
+ qCDebug(lcWidgetFocus) << "Focus chain leading from" << q << "to" << position << "is not closed.";
+ return false;
+}
+
+#undef FOCUS_NEXT
+#undef FOCUS_PREV
+
+
QT_END_NAMESPACE
#include "moc_qwidget.cpp"
diff --git a/src/widgets/kernel/qwidget.h b/src/widgets/kernel/qwidget.h
index 06ac265ede..e5e83a43f2 100644
--- a/src/widgets/kernel/qwidget.h
+++ b/src/widgets/kernel/qwidget.h
@@ -8,7 +8,9 @@
#include <QtGui/qwindowdefs.h>
#include <QtCore/qobject.h>
#include <QtCore/qmargins.h>
+#if QT_CONFIG(action)
#include <QtGui/qaction.h>
+#endif
#include <QtGui/qpaintdevice.h>
#include <QtGui/qpalette.h>
#include <QtGui/qfont.h>
@@ -175,6 +177,7 @@ class Q_WIDGETS_EXPORT QWidget : public QObject, public QPaintDevice
Q_PROPERTY(QString windowFilePath READ windowFilePath WRITE setWindowFilePath)
Q_PROPERTY(Qt::InputMethodHints inputMethodHints READ inputMethodHints WRITE setInputMethodHints)
+#if QT_CONFIG(action)
#if 0
// ### TODO: make this work (requires SFINAE-friendly connect())
template <typename...Args>
@@ -197,6 +200,8 @@ class Q_WIDGETS_EXPORT QWidget : public QObject, public QPaintDevice
std::negation<std::is_convertible<Args, QString>>...
>>;
#endif
+#endif // QT_CONFIG(action)
+
public:
enum RenderFlag {
DrawWindowBackground = 0x1,
@@ -427,6 +432,7 @@ public:
void setFocusPolicy(Qt::FocusPolicy policy);
bool hasFocus() const;
static void setTabOrder(QWidget *, QWidget *);
+ static void setTabOrder(std::initializer_list<QWidget *> widgets);
void setFocusProxy(QWidget *);
QWidget *focusProxy() const;
Qt::ContextMenuPolicy contextMenuPolicy() const;
@@ -763,9 +769,6 @@ private:
#endif // QT_NO_GESTURES
friend class QWidgetEffectSourcePrivate;
-#ifdef Q_OS_MAC
- friend bool qt_mac_is_metal(const QWidget *w);
-#endif
friend Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget);
friend Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget);
@@ -911,7 +914,6 @@ inline bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
return testAttribute_helper(attribute);
}
-
#define QWIDGETSIZE_MAX ((1<<24)-1)
#ifndef QT_NO_DEBUG_STREAM
diff --git a/src/widgets/kernel/qwidget_p.h b/src/widgets/kernel/qwidget_p.h
index 25a9c75701..9fab9efa62 100644
--- a/src/widgets/kernel/qwidget_p.h
+++ b/src/widgets/kernel/qwidget_p.h
@@ -41,6 +41,9 @@
#include <private/qgesture_p.h>
#include <qpa/qplatformbackingstore.h>
#include <QtGui/private/qbackingstorerhisupport_p.h>
+#include <private/qapplication_p.h>
+
+#include <QtCore/qpointer.h>
#include <vector>
#include <memory>
@@ -48,6 +51,7 @@
QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(lcWidgetPainting);
+Q_DECLARE_LOGGING_CATEGORY(lcWidgetShowHide);
// Extra QWidget data
// - to minimize memory usage for members that are seldom used.
@@ -65,6 +69,7 @@ class QUnifiedToolbarSurface;
// implemented in qshortcut.cpp
bool qWidgetShortcutContextMatcher(QObject *object, Qt::ShortcutContext context);
+void qSendWindowChangeToTextureChildrenRecursively(QWidget *widget, QEvent::Type eventType);
class QUpdateLaterEvent : public QEvent
{
@@ -74,13 +79,10 @@ public:
{
}
- ~QUpdateLaterEvent()
- {
- }
-
inline const QRegion &region() const { return m_region; }
protected:
+ friend class QApplication;
QRegion m_region;
};
@@ -210,6 +212,9 @@ public:
static QWidgetPrivate *get(QWidget *w) { return w->d_func(); }
static const QWidgetPrivate *get(const QWidget *w) { return w->d_func(); }
+ static void checkRestoredGeometry(const QRect &availableGeometry, QRect *restoredGeometry,
+ int frameHeight);
+
QWExtra *extraData() const;
QTLWExtra *topData() const;
QTLWExtra *maybeTopData() const;
@@ -217,6 +222,8 @@ public:
void setSharedPainter(QPainter *painter);
QWidgetRepaintManager *maybeRepaintManager() const;
+ QRhi *rhi() const;
+
enum class WindowHandleMode {
Direct,
Closest,
@@ -364,6 +371,8 @@ public:
void showChildren(bool spontaneous);
void hideChildren(bool spontaneous);
void setParent_sys(QWidget *parent, Qt::WindowFlags);
+ void reparentWidgetWindows(QWidget *parentWithWindow, Qt::WindowFlags windowFlags = {});
+ void reparentWidgetWindowChildren(QWidget *parentWithWindow);
void scroll_sys(int dx, int dy);
void scroll_sys(int dx, int dy, const QRect &r);
void deactivateWidgetCleanup();
@@ -376,6 +385,7 @@ public:
void show_sys();
void hide_sys();
void hide_helper();
+ bool isExplicitlyHidden() const;
void _q_showIfNotHidden();
void setVisible(bool);
@@ -575,7 +585,7 @@ public:
inline QRect mapFromWS(const QRect &r) const
{ return r.translated(data.wrect.topLeft()); }
- virtual QObject *focusObject() { return nullptr; }
+ virtual QObject *focusObject();
virtual QPlatformBackingStoreRhiConfig rhiConfig() const { return {}; }
@@ -630,6 +640,8 @@ public:
std::string flagsForDumping() const override;
+ QWidget *closestParentWidgetWithWindowHandle() const;
+
// Variables.
// Regular pointers (keep them together to avoid gaps on 64 bit architectures).
std::unique_ptr<QWExtra> extra;
@@ -722,6 +734,40 @@ public:
uint childrenHiddenByWState : 1;
uint childrenShownByExpose : 1;
+ // *************************** Focus abstraction ************************************
+ enum class FocusDirection {
+ Previous,
+ Next,
+ };
+
+ enum class FocusChainRemovalRule {
+ EnsureFocusOut = 0x01,
+ AssertConsistency = 0x02,
+ };
+ Q_DECLARE_FLAGS(FocusChainRemovalRules, FocusChainRemovalRule)
+
+ // Getters
+ QWidget *nextPrevElementInFocusChain(FocusDirection direction) const;
+
+ // manipulators
+ bool removeFromFocusChain(FocusChainRemovalRules rules = FocusChainRemovalRules(),
+ FocusDirection direction = FocusDirection::Next);
+ bool insertIntoFocusChain(FocusDirection direction, QWidget *position);
+ static bool insertIntoFocusChain(const QWidgetList &toBeInserted, FocusDirection direction, QWidget *position);
+ bool insertIntoFocusChainBefore(QWidget *position)
+ { return insertIntoFocusChain(FocusDirection::Previous, position); }
+ bool insertIntoFocusChainAfter(QWidget *position)
+ { return insertIntoFocusChain(FocusDirection::Next, position); }
+ static QWidgetList takeFromFocusChain(QWidget *from, QWidget *to,
+ FocusDirection direction = FocusDirection::Next);
+ void reparentFocusChildren(FocusDirection direction);
+ QWidget *determineLastFocusChild(QWidget *noFurtherThan);
+
+ // Initialization and tests
+ void initFocusChain();
+ bool isInFocusChain() const;
+ bool isFocusChainConsistent() const;
+
// *************************** Platform specific ************************************
#if defined(Q_OS_WIN)
uint noPaintOnScreen : 1; // see qwidget.cpp ::paintEngine()
@@ -732,6 +778,7 @@ public:
bool stealKeyboardGrab(bool grab);
bool stealMouseGrab(bool grab);
+ bool hasChildWithFocusPolicy(Qt::FocusPolicy policy, const QWidget *excludeChildrenOf = nullptr) const;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QWidgetPrivate::DrawWidgetFlags)
diff --git a/src/widgets/kernel/qwidgetaction.cpp b/src/widgets/kernel/qwidgetaction.cpp
index 4a3fb2be89..13f386d3ec 100644
--- a/src/widgets/kernel/qwidgetaction.cpp
+++ b/src/widgets/kernel/qwidgetaction.cpp
@@ -5,6 +5,8 @@
#include "qwidget.h"
#include "qdebug.h"
+#include <QtWidgets/private/qwidget_p.h>
+
#include "qwidgetaction_p.h"
QT_BEGIN_NAMESPACE
@@ -82,9 +84,9 @@ QWidgetAction::QWidgetAction(QObject *parent)
QWidgetAction::~QWidgetAction()
{
Q_D(QWidgetAction);
- for (int i = 0; i < d->createdWidgets.size(); ++i)
- disconnect(d->createdWidgets.at(i), SIGNAL(destroyed(QObject*)),
- this, SLOT(_q_widgetDestroyed(QObject*)));
+ for (QWidget *w : std::as_const(d->createdWidgets))
+ QObjectPrivate::disconnect(w, &QWidget::destroyed,
+ d, &QWidgetActionPrivate::widgetDestroyed);
QList<QWidget *> widgetsToDelete = d->createdWidgets;
d->createdWidgets.clear();
qDeleteAll(widgetsToDelete);
@@ -108,7 +110,7 @@ void QWidgetAction::setDefaultWidget(QWidget *widget)
if (!widget)
return;
- setVisible(!(widget->isHidden() && widget->testAttribute(Qt::WA_WState_ExplicitShowHide)));
+ setVisible(!QWidgetPrivate::get(widget)->isExplicitlyHidden());
d->defaultWidget->hide();
d->defaultWidget->setParent(nullptr);
d->defaultWidgetInUse = false;
@@ -147,8 +149,8 @@ QWidget *QWidgetAction::requestWidget(QWidget *parent)
return d->defaultWidget;
}
- connect(w, SIGNAL(destroyed(QObject*)),
- this, SLOT(_q_widgetDestroyed(QObject*)));
+ QObjectPrivate::connect(w, &QWidget::destroyed,
+ d, &QWidgetActionPrivate::widgetDestroyed);
d->createdWidgets.append(w);
return w;
}
@@ -175,8 +177,8 @@ void QWidgetAction::releaseWidget(QWidget *widget)
if (!d->createdWidgets.contains(widget))
return;
- disconnect(widget, SIGNAL(destroyed(QObject*)),
- this, SLOT(_q_widgetDestroyed(QObject*)));
+ QObjectPrivate::disconnect(widget, &QWidget::destroyed,
+ d, &QWidgetActionPrivate::widgetDestroyed);
d->createdWidgets.removeAll(widget);
deleteWidget(widget);
}
diff --git a/src/widgets/kernel/qwidgetaction.h b/src/widgets/kernel/qwidgetaction.h
index b8539f275b..296ff52d1e 100644
--- a/src/widgets/kernel/qwidgetaction.h
+++ b/src/widgets/kernel/qwidgetaction.h
@@ -37,7 +37,6 @@ protected:
private:
Q_DISABLE_COPY(QWidgetAction)
- Q_PRIVATE_SLOT(d_func(), void _q_widgetDestroyed(QObject *))
friend class QToolBar;
};
diff --git a/src/widgets/kernel/qwidgetaction_p.h b/src/widgets/kernel/qwidgetaction_p.h
index bd156241c6..6a1cd8c186 100644
--- a/src/widgets/kernel/qwidgetaction_p.h
+++ b/src/widgets/kernel/qwidgetaction_p.h
@@ -18,6 +18,8 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "private/qaction_widgets_p.h"
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(action);
QT_BEGIN_NAMESPACE
@@ -32,7 +34,7 @@ public:
uint defaultWidgetInUse : 1;
uint autoCreated : 1; // created by QToolBar::addWidget and the like
- inline void _q_widgetDestroyed(QObject *o) {
+ inline void widgetDestroyed(QObject *o) {
createdWidgets.removeAll(static_cast<QWidget *>(o));
}
};
diff --git a/src/widgets/kernel/qwidgetrepaintmanager.cpp b/src/widgets/kernel/qwidgetrepaintmanager.cpp
index 16db49f95e..607a767a20 100644
--- a/src/widgets/kernel/qwidgetrepaintmanager.cpp
+++ b/src/widgets/kernel/qwidgetrepaintmanager.cpp
@@ -1,7 +1,6 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
-
#include "qplatformdefs.h"
#include "qwidgetrepaintmanager_p.h"
@@ -49,7 +48,7 @@ public:
}
bool isLocked() const {
- foreach (bool v, m_locked) {
+ for (const auto &[_, v] : m_locked.asKeyValueRange()) {
if (v)
return true;
}
@@ -340,9 +339,9 @@ void QWidgetRepaintManager::sendUpdateRequest(QWidget *widget, UpdateTime update
// compositing and waiting for vsync each and every time. Change to
// UpdateLater, except for approx. once per frame to prevent starvation in
// case the control does not get back to the event loop.
- QWidget *w = widget->window();
- if (updateTime == UpdateNow && w && w->windowHandle() && QWindowPrivate::get(w->windowHandle())->compositing) {
+ if (updateTime == UpdateNow && QWidgetPrivate::get(widget)->textureChildSeen) {
int refresh = 60;
+ QWidget *w = widget->window();
QScreen *ws = w->windowHandle()->screen();
if (ws)
refresh = ws->refreshRate();
@@ -351,12 +350,16 @@ void QWidgetRepaintManager::sendUpdateRequest(QWidget *widget, UpdateTime update
const qint64 elapsed = wd->lastComposeTime.elapsed();
if (elapsed <= qint64(1000.0f / refresh))
updateTime = UpdateLater;
- }
+ }
}
switch (updateTime) {
case UpdateLater:
- updateRequestSent = true;
+ // Prevent redundant update request events, unless it's a
+ // paint on screen widget, as these don't go through the
+ // normal backingstore sync machinery.
+ if (!widget->d_func()->shouldPaintOnScreen())
+ updateRequestSent = true;
QCoreApplication::postEvent(widget, new QEvent(QEvent::UpdateRequest), Qt::LowEventPriority);
break;
case UpdateNow: {
@@ -707,7 +710,9 @@ void QWidgetRepaintManager::paintAndFlush()
const QRect tlwRect = tlw->data->crect;
if (!updatesDisabled && store->size() != tlwRect.size()) {
- if (hasStaticContents() && !store->size().isEmpty() ) {
+ QPlatformIntegration *integration = QGuiApplicationPrivate::platformIntegration();
+ if (hasStaticContents() && !store->size().isEmpty()
+ && integration->hasCapability(QPlatformIntegration::BackingStoreStaticContents)) {
// Repaint existing dirty area and newly visible area.
const QRect clipRect(QPoint(0, 0), store->size());
const QRegion staticRegion(staticContents(nullptr, clipRect));
@@ -800,7 +805,6 @@ void QWidgetRepaintManager::paintAndFlush()
QTLWExtra *tlwExtra = tlw->d_func()->topData();
tlwExtra->widgetTextures.clear();
findAllTextureWidgetsRecursively(tlw, tlw);
- qt_window_private(tlw->windowHandle())->compositing = false; // will get updated in flush()
if (toClean.isEmpty()) {
// Nothing to repaint. However renderToTexture widgets are handled
@@ -1033,7 +1037,36 @@ void QWidgetRepaintManager::flush(QWidget *widget, const QRegion &region, QPlatf
if (widget != tlw)
offset += widget->mapTo(tlw, QPoint());
- if (tlw->d_func()->usesRhiFlush) {
+ // Use a condition that tries to keep both QTBUG-108344 and QTBUG-113557
+ // happy, i.e. support both (A) "native rhi-based child in a rhi-based
+ // toplevel" and (B) "native raster child in a rhi-based toplevel".
+ //
+ // If the tlw and the backingstore are RHI-based, then there are two cases
+ // to consider:
+ //
+ // (1) widget is not a native child, i.e. the QWindow for widget and tlw are
+ // the same,
+ //
+ // (2) widget is a native child which we now attempt to flush with tlw's
+ // backingstore to widget's native window. This is the interesting one.
+ //
+ // Using the condition tlw->usesRhiFlush on its own is insufficient since
+ // it fails to capture the case of a raster-based native child widget
+ // within tlw. (which must hit the non-rhi flush path)
+ //
+ // Extending the condition with tlw->windowHandle() == widget->windowHandle()
+ // would be logical but wrong, when it comes to (A) since flushing a
+ // RHI-based native child with a given 3D API using a RHI-based
+ // tlw/backingstore with the same 3D API needs to be supported still. (this
+ // happens when e.g. someone calls winId() on a QOpenGLWidget)
+ //
+ // Different 3D APIs do not need to be supported since we do not allow to
+ // do things like having a QQuickWidget with Vulkan and a QOpenGLWidget in
+ // the same toplevel, regardless of the widgets being native children or
+ // not. Hence comparing the surfaceType() instead. This satisfies both (A)
+ // and (B) given that an RHI-based toplevel cannot be RasterSurface.
+ //
+ if (tlw->d_func()->usesRhiFlush && tlw->windowHandle()->surfaceType() == widget->windowHandle()->surfaceType()) {
QRhi *rhi = store->handle()->rhi();
qCDebug(lcWidgetPainting) << "Flushing" << region << "of" << widget
<< "with QRhi" << rhi
@@ -1041,7 +1074,6 @@ void QWidgetRepaintManager::flush(QWidget *widget, const QRegion &region, QPlatf
if (!widgetTextures)
widgetTextures = qt_dummy_platformTextureList;
- qt_window_private(tlw->windowHandle())->compositing = true;
QWidgetPrivate *widgetWindowPrivate = widget->window()->d_func();
widgetWindowPrivate->sendComposeStatus(widget->window(), false);
// A window may have alpha even when the app did not request
@@ -1058,7 +1090,11 @@ void QWidgetRepaintManager::flush(QWidget *widget, const QRegion &region, QPlatf
translucentBackground);
widgetWindowPrivate->sendComposeStatus(widget->window(), true);
if (flushResult == QPlatformBackingStore::FlushFailedDueToLostDevice) {
+ qSendWindowChangeToTextureChildrenRecursively(widget->window(),
+ QEvent::WindowAboutToChangeInternal);
store->handle()->graphicsDeviceReportedLost();
+ qSendWindowChangeToTextureChildrenRecursively(widget->window(),
+ QEvent::WindowChangeInternal);
widget->update();
}
} else {
@@ -1108,11 +1144,7 @@ void QWidgetRepaintManager::removeStaticWidget(QWidget *widget)
bool QWidgetRepaintManager::hasStaticContents() const
{
-#if defined(Q_OS_WIN)
return !staticWidgets.isEmpty();
-#else
- return !staticWidgets.isEmpty() && false;
-#endif
}
/*!
diff --git a/src/widgets/kernel/qwidgetsvariant.cpp b/src/widgets/kernel/qwidgetsvariant.cpp
index f5d511abd2..17a19aa780 100644
--- a/src/widgets/kernel/qwidgetsvariant.cpp
+++ b/src/widgets/kernel/qwidgetsvariant.cpp
@@ -12,7 +12,8 @@ QT_BEGIN_NAMESPACE
namespace {
-static const struct : QMetaTypeModuleHelper
+// NOLINTNEXTLINE(cppcoreguidelines-virtual-class-destructor): this is not a base class
+static constexpr struct : QMetaTypeModuleHelper
{
const QtPrivate::QMetaTypeInterface *interfaceForType(int type) const override {
switch (type) {
diff --git a/src/widgets/kernel/qwidgetwindow.cpp b/src/widgets/kernel/qwidgetwindow.cpp
index 7a3c38bb8d..f51baba88b 100644
--- a/src/widgets/kernel/qwidgetwindow.cpp
+++ b/src/widgets/kernel/qwidgetwindow.cpp
@@ -39,21 +39,25 @@ public:
void setVisible(bool visible) override
{
Q_Q(QWidgetWindow);
+ qCDebug(lcWidgetShowHide) << "Setting visibility of" << q->widget()
+ << "to" << visible << "via QWidgetWindowPrivate";
+
if (QWidget *widget = q->widget()) {
- // Check if the widget was already hidden, as this indicates it was done
- // explicitly and not because the parent window in this case made it hidden.
- // In which case do not automatically show the widget when the parent
- // window is shown.
- const bool wasExplicitShowHide = widget->testAttribute(Qt::WA_WState_ExplicitShowHide);
- const bool wasHidden = widget->testAttribute(Qt::WA_WState_Hidden);
- QWidgetPrivate::get(widget)->setVisible(visible);
- if (wasExplicitShowHide) {
- widget->setAttribute(Qt::WA_WState_ExplicitShowHide, wasExplicitShowHide);
- widget->setAttribute(Qt::WA_WState_Hidden, wasHidden);
- }
- } else {
- QWindowPrivate::setVisible(visible);
+ // If the widget's visible state is already matching the new QWindow
+ // visible state we assume the widget has already synced up.
+ if (visible != widget->isVisible())
+ QWidgetPrivate::get(widget)->setVisible(visible);
}
+
+ // If we end up calling QWidgetPrivate::setVisible() above, we will
+ // in most cases recurse back into setNativeWindowVisibility() to
+ // update the QWindow state. But during QWidget::destroy() this is
+ // not the case, as Qt::WA_WState_Created has been unset by the time
+ // we check if we should call hide_helper(). We handle this case, as
+ // well as the cases where we don't call QWidgetPrivate::setVisible(),
+ // by syncing up the QWindow state here if needed.
+ if (q->isVisible() != visible)
+ QWindowPrivate::setVisible(visible);
}
QWindow *eventReceiver() override {
@@ -129,11 +133,26 @@ QWidgetWindow::QWidgetWindow(QWidget *widget)
}
connect(widget, &QObject::objectNameChanged, this, &QWidgetWindow::updateObjectName);
- connect(this, SIGNAL(screenChanged(QScreen*)), this, SLOT(handleScreenChange()));
+ connect(this, &QWidgetWindow::screenChanged, this, &QWidgetWindow::handleScreenChange);
}
QWidgetWindow::~QWidgetWindow()
{
+ if (!m_widget)
+ return;
+
+ QTLWExtra *topData = QWidgetPrivate::get(m_widget)->topData();
+ Q_ASSERT(topData);
+
+ // The QPlaformBackingStore may hold a reference to the window,
+ // so the backingstore needs to be deleted first.
+ topData->repaintManager.reset(nullptr);
+ delete topData->backingStore;
+ topData->backingStore = nullptr;
+ topData->widgetTextures.clear();
+
+ // Too late to do anything beyond this point
+ topData->window = nullptr;
}
#if QT_CONFIG(accessibility)
@@ -170,6 +189,9 @@ QObject *QWidgetWindow::focusObject() const
void QWidgetWindow::setNativeWindowVisibility(bool visible)
{
Q_D(QWidgetWindow);
+ qCDebug(lcWidgetShowHide) << "Setting visibility of" << this
+ << "to" << visible << "via QWidgetWindow::setNativeWindowVisibility";
+
// Call base class setVisible() implementation to run the QWindow
// visibility logic. Don't call QWidgetWindowPrivate::setVisible()
// since that will recurse back into QWidget code.
@@ -329,6 +351,10 @@ bool QWidgetWindow::event(QEvent *event)
m_widget->repaint();
return true;
+ case QEvent::DevicePixelRatioChange:
+ handleDevicePixelRatioChange();
+ break;
+
default:
break;
}
@@ -451,11 +477,11 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
QEvent::MouseButtonRelease : QEvent::MouseButtonPress;
if (QApplicationPrivate::inPopupMode()) {
QPointer<QWidget> activePopupWidget = QApplication::activePopupWidget();
- QPoint mapped = event->position().toPoint();
+ QPointF mapped = event->position();
if (activePopupWidget != m_widget)
- mapped = activePopupWidget->mapFromGlobal(event->globalPosition().toPoint());
+ mapped = activePopupWidget->mapFromGlobal(event->globalPosition());
bool releaseAfter = false;
- QWidget *popupChild = activePopupWidget->childAt(mapped);
+ QWidget *popupChild = activePopupWidget->childAt(mapped.toPoint());
if (activePopupWidget != qt_popup_down) {
qt_button_down = nullptr;
@@ -482,15 +508,15 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
// deliver event
qt_replay_popup_mouse_event = false;
QPointer<QWidget> receiver = activePopupWidget;
- QPoint widgetPos = mapped;
+ QPointF widgetPos = mapped;
if (qt_button_down)
receiver = qt_button_down;
else if (popupChild)
receiver = popupChild;
if (receiver != activePopupWidget)
- widgetPos = receiver->mapFromGlobal(event->globalPosition().toPoint());
+ widgetPos = receiver->mapFromGlobal(event->globalPosition());
- const bool reallyUnderMouse = activePopupWidget->rect().contains(mapped);
+ const bool reallyUnderMouse = activePopupWidget->rect().contains(mapped.toPoint());
const bool underMouse = activePopupWidget->underMouse();
if (underMouse != reallyUnderMouse) {
if (reallyUnderMouse) {
@@ -695,22 +721,32 @@ void QWidgetWindow::updateMargins()
m_widget->data->fstrut_dirty = false;
}
-static void sendScreenChangeRecursively(QWidget *widget)
+static void sendChangeRecursively(QWidget *widget, QEvent::Type type)
{
- QEvent e(QEvent::ScreenChangeInternal);
+ QEvent e(type);
QCoreApplication::sendEvent(widget, &e);
QWidgetPrivate *d = QWidgetPrivate::get(widget);
for (int i = 0; i < d->children.size(); ++i) {
QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
if (w)
- sendScreenChangeRecursively(w);
+ sendChangeRecursively(w, type);
}
}
void QWidgetWindow::handleScreenChange()
{
// Send an event recursively to the widget and its children.
- sendScreenChangeRecursively(m_widget);
+ sendChangeRecursively(m_widget, QEvent::ScreenChangeInternal);
+
+ // Invalidate the backing store buffer and repaint immediately.
+ if (screen())
+ repaintWindow();
+}
+
+void QWidgetWindow::handleDevicePixelRatioChange()
+{
+ // Send an event recursively to the widget and its children.
+ sendChangeRecursively(m_widget, QEvent::DevicePixelRatioChange);
// Invalidate the backing store buffer and repaint immediately.
if (screen())
diff --git a/src/widgets/kernel/qwidgetwindow_p.h b/src/widgets/kernel/qwidgetwindow_p.h
index 92f1a8b6d4..0ee6b71a79 100644
--- a/src/widgets/kernel/qwidgetwindow_p.h
+++ b/src/widgets/kernel/qwidgetwindow_p.h
@@ -22,6 +22,8 @@
#include <QtGui/private/qevent_p.h>
#include <QtWidgets/qwidget.h>
+#include <QtCore/qpointer.h>
+
QT_BEGIN_NAMESPACE
@@ -81,9 +83,10 @@ protected:
private slots:
void updateObjectName();
- void handleScreenChange();
private:
+ void handleScreenChange();
+ void handleDevicePixelRatioChange();
void repaintWindow();
bool updateSize();
void updateMargins();
diff --git a/src/widgets/kernel/qwindowcontainer.cpp b/src/widgets/kernel/qwindowcontainer.cpp
index 072a0bc5fa..2c374ac408 100644
--- a/src/widgets/kernel/qwindowcontainer.cpp
+++ b/src/widgets/kernel/qwindowcontainer.cpp
@@ -3,6 +3,7 @@
#include "qwindowcontainer_p.h"
#include "qwidget_p.h"
+#include "qwidgetwindow_p.h"
#include <QtGui/qwindow.h>
#include <QtGui/private/qguiapplication_p.h>
#include <qpa/qplatformintegration.h>
@@ -14,6 +15,8 @@
#include <QAbstractScrollArea>
#include <QPainter>
+#include <QtCore/qpointer.h>
+
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
@@ -25,7 +28,6 @@ public:
QWindowContainerPrivate()
: window(nullptr)
- , oldFocusWindow(nullptr)
, usesNativeWidgets(false)
{
}
@@ -100,7 +102,6 @@ public:
}
QPointer<QWindow> window;
- QWindow *oldFocusWindow;
QWindow fakeParent;
uint usesNativeWidgets : 1;
@@ -162,11 +163,31 @@ public:
application can greatly hurt the overall performance of the
application.
+ \li Since 6.7, if \a window belongs to a widget (that is, \a window
+ was received from calling \l windowHandle()), no container will be
+ created. Instead, this function will return the widget itself, after
+ being reparented to \l parent. Since no container will be created,
+ \a flags will be ignored. In other words, if \a window belongs to
+ a widget, consider just reparenting that widget to \a parent instead
+ of using this function.
+
\endlist
*/
QWidget *QWidget::createWindowContainer(QWindow *window, QWidget *parent, Qt::WindowFlags flags)
{
+ // Embedding a QWidget in a window container doesn't make sense,
+ // and has various issues in practice, so just return the widget
+ // itself.
+ if (auto *widgetWindow = qobject_cast<QWidgetWindow *>(window)) {
+ QWidget *widget = widgetWindow->widget();
+ if (flags != Qt::WindowFlags()) {
+ qWarning() << window << "refers to a widget:" << widget
+ << "WindowFlags" << flags << "will be ignored.";
+ }
+ widget->setParent(parent);
+ return widget;
+ }
return new QWindowContainer(window, parent, flags);
}
@@ -184,6 +205,7 @@ QWindowContainer::QWindowContainer(QWindow *embeddedWindow, QWidget *parent, Qt:
}
d->window = embeddedWindow;
+ d->window->installEventFilter(this);
QString windowName = d->window->objectName();
if (windowName.isEmpty())
@@ -196,7 +218,8 @@ QWindowContainer::QWindowContainer(QWindow *embeddedWindow, QWidget *parent, Qt:
setAcceptDrops(true);
- connect(QGuiApplication::instance(), SIGNAL(focusWindowChanged(QWindow*)), this, SLOT(focusWindowChanged(QWindow*)));
+ connect(containedWindow(), &QWindow::minimumHeightChanged, this, &QWindowContainer::updateGeometry);
+ connect(containedWindow(), &QWindow::minimumWidthChanged, this, &QWindowContainer::updateGeometry);
}
QWindow *QWindowContainer::containedWindow() const
@@ -217,29 +240,14 @@ QWindowContainer::~QWindowContainer()
// QEvent::PlatformSurface delivery relies on virtuals. Getting
// SurfaceAboutToBeDestroyed can be essential for OpenGL, Vulkan, etc.
// QWindow subclasses in particular. Keep these working.
- if (d->window)
+ if (d->window) {
+ d->window->removeEventFilter(this);
d->window->destroy();
+ }
delete d->window;
}
-
-
-/*!
- \internal
- */
-
-void QWindowContainer::focusWindowChanged(QWindow *focusWindow)
-{
- Q_D(QWindowContainer);
- d->oldFocusWindow = focusWindow;
- if (focusWindow == d->window) {
- QWidget *widget = QApplication::focusWidget();
- if (widget)
- widget->clearFocus();
- }
-}
-
/*!
\internal
*/
@@ -254,8 +262,12 @@ bool QWindowContainer::eventFilter(QObject *o, QEvent *e)
QChildEvent *ce = static_cast<QChildEvent *>(e);
if (ce->child() == d->window) {
o->removeEventFilter(this);
+ d->window->removeEventFilter(this);
d->window = nullptr;
}
+ } else if (e->type() == QEvent::FocusIn) {
+ if (o == d->window)
+ setFocus(Qt::ActiveWindowFocusReason);
}
return false;
}
@@ -305,12 +317,8 @@ bool QWindowContainer::event(QEvent *e)
break;
case QEvent::FocusIn:
if (d->window->parent()) {
- if (d->oldFocusWindow != d->window) {
+ if (QGuiApplication::focusWindow() != d->window)
d->window->requestActivate();
- } else {
- QWidget *next = nextInFocusChain();
- next->setFocus();
- }
}
break;
#if QT_CONFIG(draganddrop)
@@ -346,6 +354,11 @@ bool QWindowContainer::event(QEvent *e)
return QWidget::event(e);
}
+QSize QWindowContainer::minimumSizeHint() const
+{
+ return containedWindow() ? containedWindow()->minimumSize() : QSize(0, 0);
+}
+
typedef void (*qwindowcontainer_traverse_callback)(QWidget *parent);
static void qwindowcontainer_traverse(QWidget *parent, qwindowcontainer_traverse_callback callback)
{
diff --git a/src/widgets/kernel/qwindowcontainer_p.h b/src/widgets/kernel/qwindowcontainer_p.h
index 8dc5c64af4..0cbcc5321d 100644
--- a/src/widgets/kernel/qwindowcontainer_p.h
+++ b/src/widgets/kernel/qwindowcontainer_p.h
@@ -31,6 +31,7 @@ public:
explicit QWindowContainer(QWindow *embeddedWindow, QWidget *parent = nullptr, Qt::WindowFlags f = { });
~QWindowContainer();
QWindow *containedWindow() const;
+ QSize minimumSizeHint() const override;
static void toplevelAboutToBeDestroyed(QWidget *parent);
static void parentWasChanged(QWidget *parent);
@@ -41,9 +42,6 @@ public:
protected:
bool event(QEvent *ev) override;
bool eventFilter(QObject *, QEvent *ev) override;
-
-private slots:
- void focusWindowChanged(QWindow *focusWindow);
};
QT_END_NAMESPACE
diff --git a/src/widgets/platform/ios/PrivacyInfo.xcprivacy b/src/widgets/platform/ios/PrivacyInfo.xcprivacy
new file mode 100644
index 0000000000..819b868e1a
--- /dev/null
+++ b/src/widgets/platform/ios/PrivacyInfo.xcprivacy
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>NSPrivacyTracking</key>
+ <false/>
+ <key>NSPrivacyCollectedDataTypes</key>
+ <array/>
+ <key>NSPrivacyTrackingDomains</key>
+ <array/>
+ <key>NSPrivacyAccessedAPITypes</key>
+ <array>
+ <dict>
+ <key>NSPrivacyAccessedAPIType</key>
+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
+ <key>NSPrivacyAccessedAPITypeReasons</key>
+ <array>
+ <string>DDA9.1</string> <!-- QFileDialog -->
+ <string>C617.1</string> <!-- QFileDialog -->
+ <string>3B52.1</string> <!-- QFileDialog -->
+ </array>
+ </dict>
+ </array>
+</dict>
+</plist>
diff --git a/src/widgets/qtwidgets.tracepoints b/src/widgets/qtwidgets.tracepoints
deleted file mode 100644
index b967aaf4aa..0000000000
--- a/src/widgets/qtwidgets.tracepoints
+++ /dev/null
@@ -1,8 +0,0 @@
-{
-QT_BEGIN_NAMESPACE
-class QEvent;
-QT_END_NAMESPACE
-}
-
-QApplication_notify_entry(QObject *receiver, QEvent *event, int type)
-QApplication_notify_exit(bool consumed, bool filtered)
diff --git a/src/widgets/styles/images/cleartext-128.png b/src/widgets/styles/images/cleartext-128.png
new file mode 100644
index 0000000000..b5a2ceb233
--- /dev/null
+++ b/src/widgets/styles/images/cleartext-128.png
Binary files differ
diff --git a/src/widgets/styles/images/cleartext-16.png b/src/widgets/styles/images/cleartext-16.png
index 74133bafff..53c42929cb 100644
--- a/src/widgets/styles/images/cleartext-16.png
+++ b/src/widgets/styles/images/cleartext-16.png
Binary files differ
diff --git a/src/widgets/styles/images/cleartext-32.png b/src/widgets/styles/images/cleartext-32.png
index ff5a2b5ec1..e7ecf70d6d 100644
--- a/src/widgets/styles/images/cleartext-32.png
+++ b/src/widgets/styles/images/cleartext-32.png
Binary files differ
diff --git a/src/widgets/styles/images/cleartext.svg b/src/widgets/styles/images/cleartext.svg
new file mode 100644
index 0000000000..d93c0c6b96
--- /dev/null
+++ b/src/widgets/styles/images/cleartext.svg
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ viewBox="0 0 16 16"
+ style="enable-background:new 0 0 16 16;"
+ xml:space="preserve"
+ sodipodi:docname="cleartext.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="false"
+ inkscape:zoom="33.14563"
+ inkscape:cx="1.0250743"
+ inkscape:cy="9.2813006"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1" />
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:none;}
+</style>
+
+<circle
+ style="fill:#4d4d4d;fill-opacity:1;stroke:none;stroke-width:0.0875;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="path873"
+ cx="8"
+ cy="8"
+ r="7"
+ inkscape:label="circle" /><rect
+ id="rect19"
+ width="2.0723703"
+ height="9.2413387"
+ x="10.277523"
+ y="-4.6206694"
+ style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.101216;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ transform="rotate(44.999999)"
+ inkscape:label="rect2" /><rect
+ id="rect19-6"
+ width="2.0723705"
+ height="9.2413378"
+ x="-1.0361853"
+ y="6.6930394"
+ style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.101217;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ transform="rotate(-45)"
+ inkscape:label="rect1"
+ sodipodi:insensitive="true" /></svg>
diff --git a/src/widgets/styles/images/critical-128.png b/src/widgets/styles/images/critical-128.png
new file mode 100644
index 0000000000..329963cb38
--- /dev/null
+++ b/src/widgets/styles/images/critical-128.png
Binary files differ
diff --git a/src/widgets/styles/images/critical-16.png b/src/widgets/styles/images/critical-16.png
new file mode 100644
index 0000000000..d9da98beee
--- /dev/null
+++ b/src/widgets/styles/images/critical-16.png
Binary files differ
diff --git a/src/widgets/styles/images/critical-32.png b/src/widgets/styles/images/critical-32.png
new file mode 100644
index 0000000000..04d52591c3
--- /dev/null
+++ b/src/widgets/styles/images/critical-32.png
Binary files differ
diff --git a/src/widgets/styles/images/filedialog_end-128.png b/src/widgets/styles/images/filedialog_end-128.png
new file mode 100644
index 0000000000..f634792d2a
--- /dev/null
+++ b/src/widgets/styles/images/filedialog_end-128.png
Binary files differ
diff --git a/src/widgets/styles/images/filedialog_end-16.png b/src/widgets/styles/images/filedialog_end-16.png
new file mode 100644
index 0000000000..51fe8d1559
--- /dev/null
+++ b/src/widgets/styles/images/filedialog_end-16.png
Binary files differ
diff --git a/src/widgets/styles/images/filedialog_end-32.png b/src/widgets/styles/images/filedialog_end-32.png
new file mode 100644
index 0000000000..faa3a10293
--- /dev/null
+++ b/src/widgets/styles/images/filedialog_end-32.png
Binary files differ
diff --git a/src/widgets/styles/images/filedialog_start-128.png b/src/widgets/styles/images/filedialog_start-128.png
new file mode 100644
index 0000000000..f1272bd169
--- /dev/null
+++ b/src/widgets/styles/images/filedialog_start-128.png
Binary files differ
diff --git a/src/widgets/styles/images/filedialog_start-16.png b/src/widgets/styles/images/filedialog_start-16.png
new file mode 100644
index 0000000000..04430f53c9
--- /dev/null
+++ b/src/widgets/styles/images/filedialog_start-16.png
Binary files differ
diff --git a/src/widgets/styles/images/filedialog_start-32.png b/src/widgets/styles/images/filedialog_start-32.png
new file mode 100644
index 0000000000..c8b81a5ec7
--- /dev/null
+++ b/src/widgets/styles/images/filedialog_start-32.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_closedock-10.png b/src/widgets/styles/images/fusion_closedock-10.png
new file mode 100644
index 0000000000..d0c34d618b
--- /dev/null
+++ b/src/widgets/styles/images/fusion_closedock-10.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_closedock-16.png b/src/widgets/styles/images/fusion_closedock-16.png
new file mode 100644
index 0000000000..889c91e43f
--- /dev/null
+++ b/src/widgets/styles/images/fusion_closedock-16.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_closedock-20.png b/src/widgets/styles/images/fusion_closedock-20.png
new file mode 100644
index 0000000000..9076683d11
--- /dev/null
+++ b/src/widgets/styles/images/fusion_closedock-20.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_closedock-32.png b/src/widgets/styles/images/fusion_closedock-32.png
new file mode 100644
index 0000000000..a2a3328a50
--- /dev/null
+++ b/src/widgets/styles/images/fusion_closedock-32.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_closedock-48.png b/src/widgets/styles/images/fusion_closedock-48.png
new file mode 100644
index 0000000000..e915a1098b
--- /dev/null
+++ b/src/widgets/styles/images/fusion_closedock-48.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_closedock-64.png b/src/widgets/styles/images/fusion_closedock-64.png
new file mode 100644
index 0000000000..73c60feb6a
--- /dev/null
+++ b/src/widgets/styles/images/fusion_closedock-64.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_closedock.svg b/src/widgets/styles/images/fusion_closedock.svg
new file mode 100644
index 0000000000..eb5e472ce2
--- /dev/null
+++ b/src/widgets/styles/images/fusion_closedock.svg
@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ width="8px"
+ height="8px"
+ viewBox="0 0 8 8"
+ style="enable-background:new 0 0 8 8;"
+ xml:space="preserve"
+ sodipodi:docname="fusion_closedock.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/fusion_closedock-64.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata120"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs118">
+
+
+
+
+
+ </defs><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="917"
+ id="namedview116"
+ showgrid="false"
+ inkscape:zoom="63.727999"
+ inkscape:cx="5.1718865"
+ inkscape:cy="4.7238684"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0" />
+<style
+ type="text/css"
+ id="style101">
+ .st0{fill:none;}
+ .st1{fill:#353637;}
+</style>
+<g
+ id="g105">
+
+ </g>
+<g
+ id="g981"><rect
+ x="5.1188383"
+ y="-2.9975181"
+ transform="rotate(45.000001)"
+ class="st1"
+ width="1.0760319"
+ height="5.9950356"
+ id="rect107"
+ style="fill:#6c6a67;fill-opacity:1;stroke-width:0.768594" /><rect
+ x="-0.53801638"
+ y="-8.6545134"
+ transform="rotate(135)"
+ class="st1"
+ width="1.0760319"
+ height="5.9950356"
+ id="rect109"
+ style="fill:#6c6a67;fill-opacity:1;stroke-width:0.768594" /><rect
+ style="fill:none;stroke:#6c6a67;stroke-width:0.469731;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect151"
+ width="6.5302691"
+ height="6.5302691"
+ x="0.73486549"
+ y="0.73486549" /></g></svg>
diff --git a/src/widgets/styles/images/fusion_normalizedockup-16.png b/src/widgets/styles/images/fusion_normalizedockup-16.png
new file mode 100644
index 0000000000..9e8d1f4716
--- /dev/null
+++ b/src/widgets/styles/images/fusion_normalizedockup-16.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_normalizedockup-32.png b/src/widgets/styles/images/fusion_normalizedockup-32.png
new file mode 100644
index 0000000000..453449cc7d
--- /dev/null
+++ b/src/widgets/styles/images/fusion_normalizedockup-32.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_normalizedockup.svg b/src/widgets/styles/images/fusion_normalizedockup.svg
new file mode 100644
index 0000000000..0d7068b563
--- /dev/null
+++ b/src/widgets/styles/images/fusion_normalizedockup.svg
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ width="8px"
+ height="8px"
+ viewBox="0 0 8 8"
+ style="enable-background:new 0 0 8 8;"
+ xml:space="preserve"
+ sodipodi:docname="fusion_normalizedockup.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/fusion_normalizedockup_64.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata120"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs118">
+
+
+
+
+
+ </defs><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="917"
+ id="namedview116"
+ showgrid="false"
+ inkscape:zoom="63.727999"
+ inkscape:cx="3.979318"
+ inkscape:cy="4.7238684"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="g1123"
+ inkscape:document-rotation="0" />
+<style
+ type="text/css"
+ id="style101">
+ .st0{fill:none;}
+ .st1{fill:#353637;}
+</style>
+
+<rect
+ style="fill:none;stroke:#6c6a67;stroke-width:0.469731;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect151"
+ width="6.5302691"
+ height="6.5302691"
+ x="0.73486549"
+ y="0.73486549" /><g
+ id="g1123"
+ transform="matrix(0.85891433,0,0,0.86643038,0.5610817,0.55019701)"><path
+ id="rect151-3-6"
+ style="fill:none;stroke:#6c6a67;stroke-width:0.5;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ d="m 2.6347656,1.6347656 v 1 h 2.7304688 v 2.7304688 h 1 V 1.6347656 Z" /><path
+ style="fill:none;fill-opacity:1;stroke:#6c6a67;stroke-width:0.5;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ d="M 1.634209,2.6342089 H 5.3657907 V 6.3657906 H 1.634209 Z"
+ id="rect151-3" /></g></svg>
diff --git a/src/widgets/styles/images/fusion_normalizedockup_10.png b/src/widgets/styles/images/fusion_normalizedockup_10.png
new file mode 100644
index 0000000000..7516e4ee4f
--- /dev/null
+++ b/src/widgets/styles/images/fusion_normalizedockup_10.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_normalizedockup_20.png b/src/widgets/styles/images/fusion_normalizedockup_20.png
new file mode 100644
index 0000000000..2bc9421d5a
--- /dev/null
+++ b/src/widgets/styles/images/fusion_normalizedockup_20.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_normalizedockup_48.png b/src/widgets/styles/images/fusion_normalizedockup_48.png
new file mode 100644
index 0000000000..6c497abdde
--- /dev/null
+++ b/src/widgets/styles/images/fusion_normalizedockup_48.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_normalizedockup_64.png b/src/widgets/styles/images/fusion_normalizedockup_64.png
new file mode 100644
index 0000000000..5ec620e5a0
--- /dev/null
+++ b/src/widgets/styles/images/fusion_normalizedockup_64.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_titlebar-min-10.png b/src/widgets/styles/images/fusion_titlebar-min-10.png
new file mode 100644
index 0000000000..97b1ab88c3
--- /dev/null
+++ b/src/widgets/styles/images/fusion_titlebar-min-10.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_titlebar-min-16.png b/src/widgets/styles/images/fusion_titlebar-min-16.png
new file mode 100644
index 0000000000..b318a232b3
--- /dev/null
+++ b/src/widgets/styles/images/fusion_titlebar-min-16.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_titlebar-min-20.png b/src/widgets/styles/images/fusion_titlebar-min-20.png
new file mode 100644
index 0000000000..4a6012bd2b
--- /dev/null
+++ b/src/widgets/styles/images/fusion_titlebar-min-20.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_titlebar-min-32.png b/src/widgets/styles/images/fusion_titlebar-min-32.png
new file mode 100644
index 0000000000..6e1c94827e
--- /dev/null
+++ b/src/widgets/styles/images/fusion_titlebar-min-32.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_titlebar-min-48.png b/src/widgets/styles/images/fusion_titlebar-min-48.png
new file mode 100644
index 0000000000..a79724f3ea
--- /dev/null
+++ b/src/widgets/styles/images/fusion_titlebar-min-48.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_titlebar-min-64.png b/src/widgets/styles/images/fusion_titlebar-min-64.png
new file mode 100644
index 0000000000..5dba9a0979
--- /dev/null
+++ b/src/widgets/styles/images/fusion_titlebar-min-64.png
Binary files differ
diff --git a/src/widgets/styles/images/fusion_titlebar-min.svg b/src/widgets/styles/images/fusion_titlebar-min.svg
new file mode 100644
index 0000000000..9f6350c8bf
--- /dev/null
+++ b/src/widgets/styles/images/fusion_titlebar-min.svg
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ width="8px"
+ height="8px"
+ viewBox="0 0 8 8"
+ style="enable-background:new 0 0 8 8;"
+ xml:space="preserve"
+ sodipodi:docname="fusion_titlebar-min.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/fusion_titlebar-min-64.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata120"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs118">
+
+
+
+
+
+ </defs><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="917"
+ id="namedview116"
+ showgrid="false"
+ inkscape:zoom="45.0625"
+ inkscape:cx="-0.80217757"
+ inkscape:cy="6.6858335"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0" />
+<style
+ type="text/css"
+ id="style101">
+ .st0{fill:none;}
+ .st1{fill:#353637;}
+</style>
+
+<rect
+ style="fill:#6c6a67;fill-opacity:1;stroke:none;stroke-width:0.529435;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect1157"
+ width="5.5"
+ height="1.5"
+ x="1"
+ y="5.5" /></svg>
diff --git a/src/widgets/styles/images/information-128.png b/src/widgets/styles/images/information-128.png
new file mode 100644
index 0000000000..2feebc4598
--- /dev/null
+++ b/src/widgets/styles/images/information-128.png
Binary files differ
diff --git a/src/widgets/styles/images/information-16.png b/src/widgets/styles/images/information-16.png
new file mode 100644
index 0000000000..deb24c71ab
--- /dev/null
+++ b/src/widgets/styles/images/information-16.png
Binary files differ
diff --git a/src/widgets/styles/images/information-32.png b/src/widgets/styles/images/information-32.png
new file mode 100644
index 0000000000..83b32b737a
--- /dev/null
+++ b/src/widgets/styles/images/information-32.png
Binary files differ
diff --git a/src/widgets/styles/images/media-pause-128.png b/src/widgets/styles/images/media-pause-128.png
new file mode 100644
index 0000000000..897ad3c80f
--- /dev/null
+++ b/src/widgets/styles/images/media-pause-128.png
Binary files differ
diff --git a/src/widgets/styles/images/media-pause-16.png b/src/widgets/styles/images/media-pause-16.png
index 6cb1fd7f63..862fd49746 100644
--- a/src/widgets/styles/images/media-pause-16.png
+++ b/src/widgets/styles/images/media-pause-16.png
Binary files differ
diff --git a/src/widgets/styles/images/media-pause-32.png b/src/widgets/styles/images/media-pause-32.png
index 3f172a04d6..ce9b706674 100644
--- a/src/widgets/styles/images/media-pause-32.png
+++ b/src/widgets/styles/images/media-pause-32.png
Binary files differ
diff --git a/src/widgets/styles/images/media-pause.svg b/src/widgets/styles/images/media-pause.svg
new file mode 100644
index 0000000000..c13a4ef400
--- /dev/null
+++ b/src/widgets/styles/images/media-pause.svg
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ viewBox="0 0 16 16"
+ style="enable-background:new 0 0 16 16;"
+ xml:space="preserve"
+ sodipodi:docname="media-pause.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/media-pause-128.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="true"
+ inkscape:zoom="16.572815"
+ inkscape:cx="13.411945"
+ inkscape:cy="7.5009653"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0"><inkscape:grid
+ type="xygrid"
+ id="grid925" /></sodipodi:namedview>
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:none;}
+</style>
+
+<g
+ id="g1774"><rect
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:2.0575"
+ id="rect1755"
+ width="3"
+ height="10"
+ x="3.5"
+ y="3" /><rect
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:2.0575"
+ id="rect1755-3"
+ width="3"
+ height="10"
+ x="9.5"
+ y="3" /></g></svg>
diff --git a/src/widgets/styles/images/media-play-128.png b/src/widgets/styles/images/media-play-128.png
new file mode 100644
index 0000000000..22b260891f
--- /dev/null
+++ b/src/widgets/styles/images/media-play-128.png
Binary files differ
diff --git a/src/widgets/styles/images/media-play-16.png b/src/widgets/styles/images/media-play-16.png
index d7ee3ccbe3..60e86d7fe8 100644
--- a/src/widgets/styles/images/media-play-16.png
+++ b/src/widgets/styles/images/media-play-16.png
Binary files differ
diff --git a/src/widgets/styles/images/media-play-32.png b/src/widgets/styles/images/media-play-32.png
index af8d2f7ba5..d51e130fec 100644
--- a/src/widgets/styles/images/media-play-32.png
+++ b/src/widgets/styles/images/media-play-32.png
Binary files differ
diff --git a/src/widgets/styles/images/media-play.svg b/src/widgets/styles/images/media-play.svg
new file mode 100644
index 0000000000..b0130735f1
--- /dev/null
+++ b/src/widgets/styles/images/media-play.svg
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ viewBox="0 0 16 16"
+ style="enable-background:new 0 0 16 16;"
+ xml:space="preserve"
+ sodipodi:docname="media-play.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/media-play-128.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="true"
+ inkscape:zoom="33.14563"
+ inkscape:cx="11.425943"
+ inkscape:cy="9.1913339"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0"><inkscape:grid
+ type="xygrid"
+ id="grid925" /></sodipodi:namedview>
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:none;}
+</style>
+
+<path
+ id="rect873"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.93347"
+ d="M 3 3 L 3 13 L 12.896484 8 L 3 3 z " /></svg>
diff --git a/src/widgets/styles/images/media-seek-backward-128.png b/src/widgets/styles/images/media-seek-backward-128.png
new file mode 100644
index 0000000000..3d4470bd5c
--- /dev/null
+++ b/src/widgets/styles/images/media-seek-backward-128.png
Binary files differ
diff --git a/src/widgets/styles/images/media-seek-backward-16.png b/src/widgets/styles/images/media-seek-backward-16.png
index b8a8ea42d1..8bfba869e0 100644
--- a/src/widgets/styles/images/media-seek-backward-16.png
+++ b/src/widgets/styles/images/media-seek-backward-16.png
Binary files differ
diff --git a/src/widgets/styles/images/media-seek-backward-32.png b/src/widgets/styles/images/media-seek-backward-32.png
index a21d1372fe..9148f8a0c6 100644
--- a/src/widgets/styles/images/media-seek-backward-32.png
+++ b/src/widgets/styles/images/media-seek-backward-32.png
Binary files differ
diff --git a/src/widgets/styles/images/media-seek-backward.svg b/src/widgets/styles/images/media-seek-backward.svg
new file mode 100644
index 0000000000..13e1e67e6b
--- /dev/null
+++ b/src/widgets/styles/images/media-seek-backward.svg
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ viewBox="0 0 16 16"
+ style="enable-background:new 0 0 16 16;"
+ xml:space="preserve"
+ sodipodi:docname="media-seek-backward.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/media-seek-backward-128.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="true"
+ inkscape:zoom="33.14563"
+ inkscape:cx="12.532344"
+ inkscape:cy="7.584329"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0"><inkscape:grid
+ type="xygrid"
+ id="grid925" /></sodipodi:namedview>
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:none;}
+</style>
+
+<g
+ id="g1560"
+ transform="rotate(180,8,7.9999997)"><path
+ id="rect873"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.45442"
+ d="m 2,4 v 8 L 9,7.9999998 Z" /><path
+ id="rect873-5"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.45442"
+ d="m 7,4 v 8 l 7,-4.0000002 z" /></g></svg>
diff --git a/src/widgets/styles/images/media-seek-forward-128.png b/src/widgets/styles/images/media-seek-forward-128.png
new file mode 100644
index 0000000000..786136b014
--- /dev/null
+++ b/src/widgets/styles/images/media-seek-forward-128.png
Binary files differ
diff --git a/src/widgets/styles/images/media-seek-forward-16.png b/src/widgets/styles/images/media-seek-forward-16.png
index 3c900dcb62..1ddd379adc 100644
--- a/src/widgets/styles/images/media-seek-forward-16.png
+++ b/src/widgets/styles/images/media-seek-forward-16.png
Binary files differ
diff --git a/src/widgets/styles/images/media-seek-forward-32.png b/src/widgets/styles/images/media-seek-forward-32.png
index 4f8d370fa1..aa0e4b36bd 100644
--- a/src/widgets/styles/images/media-seek-forward-32.png
+++ b/src/widgets/styles/images/media-seek-forward-32.png
Binary files differ
diff --git a/src/widgets/styles/images/media-seek-forward.svg b/src/widgets/styles/images/media-seek-forward.svg
new file mode 100644
index 0000000000..f3753b49a6
--- /dev/null
+++ b/src/widgets/styles/images/media-seek-forward.svg
@@ -0,0 +1,61 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ viewBox="0 0 16 16"
+ style="enable-background:new 0 0 16 16;"
+ xml:space="preserve"
+ sodipodi:docname="media-seek-forward.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/media-seek-forward-128.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="true"
+ inkscape:zoom="33.14563"
+ inkscape:cx="12.532344"
+ inkscape:cy="7.584329"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0"><inkscape:grid
+ type="xygrid"
+ id="grid925" /></sodipodi:namedview>
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:none;}
+</style>
+
+<g
+ id="g1560"><path
+ id="rect873"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.45442"
+ d="m 2,4 v 8 L 9,7.9999998 Z" /><path
+ id="rect873-5"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.45442"
+ d="m 7,4 v 8 l 7,-4.0000002 z" /></g></svg>
diff --git a/src/widgets/styles/images/media-skip-backward-128.png b/src/widgets/styles/images/media-skip-backward-128.png
new file mode 100644
index 0000000000..f286da7769
--- /dev/null
+++ b/src/widgets/styles/images/media-skip-backward-128.png
Binary files differ
diff --git a/src/widgets/styles/images/media-skip-backward-16.png b/src/widgets/styles/images/media-skip-backward-16.png
index f5b3f4f56d..644dc4cc01 100644
--- a/src/widgets/styles/images/media-skip-backward-16.png
+++ b/src/widgets/styles/images/media-skip-backward-16.png
Binary files differ
diff --git a/src/widgets/styles/images/media-skip-backward-32.png b/src/widgets/styles/images/media-skip-backward-32.png
index 1d338035ef..ca405e3c01 100644
--- a/src/widgets/styles/images/media-skip-backward-32.png
+++ b/src/widgets/styles/images/media-skip-backward-32.png
Binary files differ
diff --git a/src/widgets/styles/images/media-skip-backward.svg b/src/widgets/styles/images/media-skip-backward.svg
new file mode 100644
index 0000000000..083a0a477e
--- /dev/null
+++ b/src/widgets/styles/images/media-skip-backward.svg
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ viewBox="0 0 16 16"
+ style="enable-background:new 0 0 16 16;"
+ xml:space="preserve"
+ sodipodi:docname="media-skip-backward.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/media-skip-backward-128.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="true"
+ inkscape:zoom="33.14563"
+ inkscape:cx="5.5133468"
+ inkscape:cy="10.107665"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0"><inkscape:grid
+ type="xygrid"
+ id="grid925" /></sodipodi:namedview>
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:none;}
+</style>
+
+<g
+ id="g1687"><path
+ id="rect873"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.45442"
+ d="M 14,11.999999 V 3.9999994 L 7,7.9999996 Z" /><path
+ id="rect873-5"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.45442"
+ d="M 9,11.999999 V 3.9999994 L 2,7.9999996 Z" /><rect
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:2.13809"
+ id="rect1594"
+ width="1"
+ height="8"
+ x="2"
+ y="4" /></g></svg>
diff --git a/src/widgets/styles/images/media-skip-forward-128.png b/src/widgets/styles/images/media-skip-forward-128.png
new file mode 100644
index 0000000000..d28fbc1708
--- /dev/null
+++ b/src/widgets/styles/images/media-skip-forward-128.png
Binary files differ
diff --git a/src/widgets/styles/images/media-skip-forward-16.png b/src/widgets/styles/images/media-skip-forward-16.png
index 27e205b02f..7e921f9a06 100644
--- a/src/widgets/styles/images/media-skip-forward-16.png
+++ b/src/widgets/styles/images/media-skip-forward-16.png
Binary files differ
diff --git a/src/widgets/styles/images/media-skip-forward-32.png b/src/widgets/styles/images/media-skip-forward-32.png
index a583fa1b11..19b22a5420 100644
--- a/src/widgets/styles/images/media-skip-forward-32.png
+++ b/src/widgets/styles/images/media-skip-forward-32.png
Binary files differ
diff --git a/src/widgets/styles/images/media-skip-forward.svg b/src/widgets/styles/images/media-skip-forward.svg
new file mode 100644
index 0000000000..f2f3c56a8e
--- /dev/null
+++ b/src/widgets/styles/images/media-skip-forward.svg
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ viewBox="0 0 16 16"
+ style="enable-background:new 0 0 16 16;"
+ xml:space="preserve"
+ sodipodi:docname="media-skip-forward.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/media-skip-forward-128.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="true"
+ inkscape:zoom="33.14563"
+ inkscape:cx="12.532344"
+ inkscape:cy="7.584329"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0"><inkscape:grid
+ type="xygrid"
+ id="grid925" /></sodipodi:namedview>
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:none;}
+</style>
+
+<g
+ id="g1659"><path
+ id="rect873"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.45442"
+ d="m 2,4 v 8 L 9,7.9999998 Z" /><path
+ id="rect873-5"
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.45442"
+ d="m 7,4 v 8 l 7,-4.0000002 z" /><rect
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:2"
+ id="rect1633"
+ width="1"
+ height="8"
+ x="13"
+ y="4" /></g></svg>
diff --git a/src/widgets/styles/images/media-stop-128.png b/src/widgets/styles/images/media-stop-128.png
new file mode 100644
index 0000000000..680d40697c
--- /dev/null
+++ b/src/widgets/styles/images/media-stop-128.png
Binary files differ
diff --git a/src/widgets/styles/images/media-stop-16.png b/src/widgets/styles/images/media-stop-16.png
index 9ce035d696..e047c2bf6b 100644
--- a/src/widgets/styles/images/media-stop-16.png
+++ b/src/widgets/styles/images/media-stop-16.png
Binary files differ
diff --git a/src/widgets/styles/images/media-stop-32.png b/src/widgets/styles/images/media-stop-32.png
index aae24ba925..6ba9d25d4b 100644
--- a/src/widgets/styles/images/media-stop-32.png
+++ b/src/widgets/styles/images/media-stop-32.png
Binary files differ
diff --git a/src/widgets/styles/images/media-stop.svg b/src/widgets/styles/images/media-stop.svg
new file mode 100644
index 0000000000..755755ab9a
--- /dev/null
+++ b/src/widgets/styles/images/media-stop.svg
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ viewBox="0 0 16 16"
+ style="enable-background:new 0 0 16 16;"
+ xml:space="preserve"
+ sodipodi:docname="media-stop.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
+ inkscape:export-filename="/home/chehrlic/kde/qt.src/qtbase/src/widgets/styles/images/media-stop-128.png"
+ inkscape:export-xdpi="768"
+ inkscape:export-ydpi="768"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="true"
+ inkscape:zoom="33.14563"
+ inkscape:cx="5.5133468"
+ inkscape:cy="10.107665"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="Layer_1"
+ inkscape:document-rotation="0"><inkscape:grid
+ type="xygrid"
+ id="grid925" /></sodipodi:namedview>
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:none;}
+</style>
+
+<rect
+ style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:2.06992"
+ id="rect1703"
+ width="12"
+ height="12"
+ x="2"
+ y="2" /></svg>
diff --git a/src/widgets/styles/images/question-128.png b/src/widgets/styles/images/question-128.png
new file mode 100644
index 0000000000..67748522ad
--- /dev/null
+++ b/src/widgets/styles/images/question-128.png
Binary files differ
diff --git a/src/widgets/styles/images/question-16.png b/src/widgets/styles/images/question-16.png
new file mode 100644
index 0000000000..a907b3c485
--- /dev/null
+++ b/src/widgets/styles/images/question-16.png
Binary files differ
diff --git a/src/widgets/styles/images/question-32.png b/src/widgets/styles/images/question-32.png
new file mode 100644
index 0000000000..96c53c7ce0
--- /dev/null
+++ b/src/widgets/styles/images/question-32.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-128.png b/src/widgets/styles/images/standardbutton-closetab-128.png
new file mode 100644
index 0000000000..aca55c8424
--- /dev/null
+++ b/src/widgets/styles/images/standardbutton-closetab-128.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-16.png b/src/widgets/styles/images/standardbutton-closetab-16.png
index 540694eae3..26908feb2a 100644
--- a/src/widgets/styles/images/standardbutton-closetab-16.png
+++ b/src/widgets/styles/images/standardbutton-closetab-16.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-32.png b/src/widgets/styles/images/standardbutton-closetab-32.png
index 93e1246b47..effcc89eed 100644
--- a/src/widgets/styles/images/standardbutton-closetab-32.png
+++ b/src/widgets/styles/images/standardbutton-closetab-32.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-down-128.png b/src/widgets/styles/images/standardbutton-closetab-down-128.png
new file mode 100644
index 0000000000..2efdfd053f
--- /dev/null
+++ b/src/widgets/styles/images/standardbutton-closetab-down-128.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-down-16.png b/src/widgets/styles/images/standardbutton-closetab-down-16.png
index ccec241652..5228c1573b 100644
--- a/src/widgets/styles/images/standardbutton-closetab-down-16.png
+++ b/src/widgets/styles/images/standardbutton-closetab-down-16.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-down-32.png b/src/widgets/styles/images/standardbutton-closetab-down-32.png
index 343b72586e..dfd88920ab 100644
--- a/src/widgets/styles/images/standardbutton-closetab-down-32.png
+++ b/src/widgets/styles/images/standardbutton-closetab-down-32.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-down.svg b/src/widgets/styles/images/standardbutton-closetab-down.svg
new file mode 100644
index 0000000000..12aa6b21f7
--- /dev/null
+++ b/src/widgets/styles/images/standardbutton-closetab-down.svg
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ width="32px"
+ height="32px"
+ viewBox="0 0 32 32"
+ style="enable-background:new 0 0 32 32;"
+ xml:space="preserve"
+ sodipodi:docname="standardbutton-closetab-down.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="false"
+ inkscape:zoom="16.572815"
+ inkscape:cx="28.732573"
+ inkscape:cy="14.492458"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="g8" />
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:#46A2DA;}
+ .st1{fill:none;}
+</style>
+<g
+ id="g8">
+
+
+<rect
+ style="fill:#b17153;stroke:#b17153;stroke-width:1.99804;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;fill-opacity:1"
+ id="rect17-3"
+ width="22.001965"
+ height="22.001963"
+ x="4.9990177"
+ y="4.9990177"
+ rx="0"
+ ry="0" /><rect
+ style="fill:none;stroke:#ab493f;stroke-width:1.99992;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect17"
+ width="26.000072"
+ height="26.000076"
+ x="2.9999642"
+ y="2.9999642"
+ rx="1.792347"
+ ry="1.7923476" /><rect
+ style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.76951;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect1031"
+ width="3"
+ height="16"
+ x="21.127417"
+ y="-8"
+ transform="rotate(45)" /><rect
+ style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.76951;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect1031-6"
+ width="3"
+ height="16"
+ x="-1.5"
+ y="14.627417"
+ transform="rotate(-45)" /></g>
+</svg>
diff --git a/src/widgets/styles/images/standardbutton-closetab-hover-128.png b/src/widgets/styles/images/standardbutton-closetab-hover-128.png
new file mode 100644
index 0000000000..4f6b1bfde4
--- /dev/null
+++ b/src/widgets/styles/images/standardbutton-closetab-hover-128.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-hover-16.png b/src/widgets/styles/images/standardbutton-closetab-hover-16.png
index b22a0ffaf0..460411deeb 100644
--- a/src/widgets/styles/images/standardbutton-closetab-hover-16.png
+++ b/src/widgets/styles/images/standardbutton-closetab-hover-16.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-hover-32.png b/src/widgets/styles/images/standardbutton-closetab-hover-32.png
index 41ce0265c7..aa6afd72b2 100644
--- a/src/widgets/styles/images/standardbutton-closetab-hover-32.png
+++ b/src/widgets/styles/images/standardbutton-closetab-hover-32.png
Binary files differ
diff --git a/src/widgets/styles/images/standardbutton-closetab-hover.svg b/src/widgets/styles/images/standardbutton-closetab-hover.svg
new file mode 100644
index 0000000000..45dc8b8c46
--- /dev/null
+++ b/src/widgets/styles/images/standardbutton-closetab-hover.svg
@@ -0,0 +1,86 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ width="32px"
+ height="32px"
+ viewBox="0 0 32 32"
+ style="enable-background:new 0 0 32 32;"
+ xml:space="preserve"
+ sodipodi:docname="standardbutton-closetab-hover.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="false"
+ inkscape:zoom="16.572815"
+ inkscape:cx="33.318396"
+ inkscape:cy="14.492458"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="g8"
+ inkscape:document-rotation="0" />
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:#46A2DA;}
+ .st1{fill:none;}
+</style>
+<g
+ id="g8">
+
+
+<rect
+ style="fill:#ea8f60;stroke:#f2b7a7;stroke-width:1.99804;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;fill-opacity:1"
+ id="rect17-3"
+ width="22.001965"
+ height="22.001963"
+ x="4.9990177"
+ y="4.9990177"
+ rx="0"
+ ry="0" /><rect
+ style="fill:none;stroke:#d73727;stroke-width:1.99992;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect17"
+ width="26.000072"
+ height="26.000076"
+ x="2.9999642"
+ y="2.9999642"
+ rx="1.792347"
+ ry="1.7923476" /><rect
+ style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.76951;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect1031"
+ width="3"
+ height="16"
+ x="21.127417"
+ y="-8"
+ transform="rotate(45)" /><rect
+ style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.76951;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect1031-6"
+ width="3"
+ height="16"
+ x="-1.5"
+ y="14.627417"
+ transform="rotate(-45)" /></g>
+</svg>
diff --git a/src/widgets/styles/images/standardbutton-closetab.svg b/src/widgets/styles/images/standardbutton-closetab.svg
new file mode 100644
index 0000000000..d3a9279538
--- /dev/null
+++ b/src/widgets/styles/images/standardbutton-closetab.svg
@@ -0,0 +1,86 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ version="1.1"
+ id="Layer_1"
+ x="0px"
+ y="0px"
+ width="32px"
+ height="32px"
+ viewBox="0 0 32 32"
+ style="enable-background:new 0 0 32 32;"
+ xml:space="preserve"
+ sodipodi:docname="standardbutton-closetab.svg"
+ inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"><metadata
+ id="metadata15"><rdf:RDF><cc:Work
+ rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
+ id="defs13" /><sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1920"
+ inkscape:window-height="918"
+ id="namedview11"
+ showgrid="false"
+ inkscape:zoom="16.572815"
+ inkscape:cx="33.318396"
+ inkscape:cy="14.492458"
+ inkscape:window-x="0"
+ inkscape:window-y="0"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="g8"
+ inkscape:document-rotation="0" />
+<style
+ type="text/css"
+ id="style2">
+ .st0{fill:#46A2DA;}
+ .st1{fill:none;}
+</style>
+<g
+ id="g8">
+
+
+<rect
+ style="fill:#ea8f60;stroke:#ef9d8e;stroke-width:1.99804;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;fill-opacity:1"
+ id="rect17-3"
+ width="22.001965"
+ height="22.001963"
+ x="4.9990177"
+ y="4.9990177"
+ rx="0"
+ ry="0" /><rect
+ style="fill:none;stroke:#d73727;stroke-width:1.99992;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect17"
+ width="26.000072"
+ height="26.000076"
+ x="2.9999642"
+ y="2.9999642"
+ rx="1.792347"
+ ry="1.7923476" /><rect
+ style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.76951;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect1031"
+ width="3"
+ height="16"
+ x="21.127417"
+ y="-8"
+ transform="rotate(45)" /><rect
+ style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.76951;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+ id="rect1031-6"
+ width="3"
+ height="16"
+ x="-1.5"
+ y="14.627417"
+ transform="rotate(-45)" /></g>
+</svg>
diff --git a/src/widgets/styles/images/toolbar-ext-h-128.png b/src/widgets/styles/images/toolbar-ext-h-128.png
new file mode 100644
index 0000000000..071c5b1353
--- /dev/null
+++ b/src/widgets/styles/images/toolbar-ext-h-128.png
Binary files differ
diff --git a/src/widgets/styles/images/toolbar-ext-h-rtl-128.png b/src/widgets/styles/images/toolbar-ext-h-rtl-128.png
new file mode 100644
index 0000000000..7aadfc2aea
--- /dev/null
+++ b/src/widgets/styles/images/toolbar-ext-h-rtl-128.png
Binary files differ
diff --git a/src/widgets/styles/images/toolbar-ext-v-80.png b/src/widgets/styles/images/toolbar-ext-v-80.png
new file mode 100644
index 0000000000..84d15ff064
--- /dev/null
+++ b/src/widgets/styles/images/toolbar-ext-v-80.png
Binary files differ
diff --git a/src/widgets/styles/images/warning-128.png b/src/widgets/styles/images/warning-128.png
new file mode 100644
index 0000000000..07f0251b8a
--- /dev/null
+++ b/src/widgets/styles/images/warning-128.png
Binary files differ
diff --git a/src/widgets/styles/images/warning-16.png b/src/widgets/styles/images/warning-16.png
new file mode 100644
index 0000000000..dce3ac9126
--- /dev/null
+++ b/src/widgets/styles/images/warning-16.png
Binary files differ
diff --git a/src/widgets/styles/images/warning-32.png b/src/widgets/styles/images/warning-32.png
new file mode 100644
index 0000000000..a7b822737d
--- /dev/null
+++ b/src/widgets/styles/images/warning-32.png
Binary files differ
diff --git a/src/widgets/styles/qcommonstyle.cpp b/src/widgets/styles/qcommonstyle.cpp
index 7fe848d9c0..418a0c2c5f 100644
--- a/src/widgets/styles/qcommonstyle.cpp
+++ b/src/widgets/styles/qcommonstyle.cpp
@@ -96,6 +96,31 @@ static qreal qt_getDevicePixelRatio(const QWidget *widget)
return widget ? widget->devicePixelRatio() : qApp->devicePixelRatio();
}
+struct QPainterStateSaver
+{
+ QPainterStateSaver(QPainter *p, bool bSaveRestore = true)
+ : m_painter(p)
+ , m_bSaveRestore(bSaveRestore)
+ {
+ if (m_bSaveRestore)
+ m_painter->save();
+ }
+ ~QPainterStateSaver()
+ {
+ restore();
+ }
+ void restore()
+ {
+ if (m_bSaveRestore) {
+ m_bSaveRestore = false;
+ m_painter->restore();
+ }
+ }
+private:
+ QPainter *m_painter;
+ bool m_bSaveRestore;
+};
+
/*!
\class QCommonStyle
\brief The QCommonStyle class encapsulates the common Look and Feel of a GUI.
@@ -189,20 +214,19 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
case PE_FrameFocusRect:
if (const QStyleOptionFocusRect *fropt = qstyleoption_cast<const QStyleOptionFocusRect *>(opt)) {
QColor bg = fropt->backgroundColor;
- QPen oldPen = p->pen();
+ QColor color;
if (bg.isValid()) {
int h, s, v;
bg.getHsv(&h, &s, &v);
if (v >= 128)
- p->setPen(Qt::black);
+ color = Qt::black;
else
- p->setPen(Qt::white);
+ color = Qt::white;
} else {
- p->setPen(opt->palette.windowText().color());
+ color = opt->palette.windowText().color();
}
- QRect focusRect = opt->rect.adjusted(1, 1, -1, -1);
- p->drawRect(focusRect.adjusted(0, 0, -1, -1)); //draw pen inclusive
- p->setPen(oldPen);
+ const QRect focusRect = opt->rect.adjusted(1, 1, -1, -1);
+ qDrawPlainRect(p, focusRect, color, 1);
}
break;
case PE_IndicatorMenuCheckMark: {
@@ -229,11 +253,10 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
--yy;
}
if (!(opt->state & State_Enabled) && !(opt->state & State_On)) {
- p->save();
+ QPainterStateSaver pss(p);
p->translate(1, 1);
p->setPen(opt->palette.light().color());
p->drawLines(a);
- p->restore();
}
p->setPen((opt->state & State_On) ? opt->palette.highlightedText().color() : opt->palette.text().color());
p->drawLines(a);
@@ -355,7 +378,7 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
case PE_FrameTabBarBase:
if (const QStyleOptionTabBarBase *tbb
= qstyleoption_cast<const QStyleOptionTabBarBase *>(opt)) {
- p->save();
+ QPainterStateSaver pss(p);
switch (tbb->shape) {
case QTabBar::RoundedNorth:
case QTabBar::TriangularNorth:
@@ -382,14 +405,13 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
p->drawLine(tbb->rect.topRight(), tbb->rect.bottomRight());
break;
}
- p->restore();
}
break;
case PE_IndicatorTabClose: {
if (d->tabBarcloseButtonIcon.isNull())
d->tabBarcloseButtonIcon = proxy()->standardIcon(QStyle::SP_TabCloseButton, opt, widget);
- const int size = proxy()->pixelMetric(QStyle::PM_SmallIconSize, opt);
+ const int size = proxy()->pixelMetric(QStyle::PM_SmallIconSize, opt, widget);
QIcon::Mode mode = opt->state & State_Enabled ?
(opt->state & State_Raised ? QIcon::Active : QIcon::Normal)
: QIcon::Disabled;
@@ -435,15 +457,15 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
int lw = frame->lineWidth;
if (lw <= 0)
- lw = proxy()->pixelMetric(PM_DockWidgetFrameWidth, opt);
+ lw = proxy()->pixelMetric(PM_DockWidgetFrameWidth, opt, widget);
qDrawShadePanel(p, frame->rect, frame->palette, false, lw);
}
break;
#endif // QT_CONFIG(dockwidget)
#if QT_CONFIG(toolbar)
- case PE_IndicatorToolBarHandle:
- p->save();
+ case PE_IndicatorToolBarHandle: {
+ QPainterStateSaver pss(p);
p->translate(opt->rect.x(), opt->rect.y());
if (opt->state & State_Horizontal) {
int x = opt->rect.width() / 3;
@@ -464,8 +486,8 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
opt->palette, false, 1, nullptr);
}
}
- p->restore();
break;
+ }
case PE_IndicatorToolBarSeparator:
{
QPoint p1, p2;
@@ -486,24 +508,58 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
QRect r = opt->rect;
int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
QRect br = r.adjusted(fw, fw, -fw, -fw);
-
- int offset = (opt->state & State_Sunken) ? 1 : 0;
- int step = (br.width() + 4) / 5;
- p->fillRect(br.x() + offset, br.y() + offset +br.height() / 2 - step / 2,
- br.width(), step,
- opt->palette.buttonText());
+ int x = br.x();
+ int y = br.y();
+ int w = br.width();
+ int h = br.height();
+ QPainterStateSaver pss(p);
+ const qreal devicePixelRatio = p->device()->devicePixelRatio();
+ if (!qFuzzyCompare(devicePixelRatio, qreal(1))) {
+ const qreal inverseScale = qreal(1) / devicePixelRatio;
+ p->scale(inverseScale, inverseScale);
+ x = qRound(devicePixelRatio * x);
+ y = qRound(devicePixelRatio * y);
+ w = qRound(devicePixelRatio * w);
+ h = qRound(devicePixelRatio * h);
+ p->translate(0.5, 0.5);
+ }
+ int len = std::min(w, h);
+ if (len & 1)
+ ++len;
+ int step = (len + 4) / 5;
+ if (step & 1)
+ ++step;
+ const int step2 = step / 2;
+ QPoint center(x + w / 2, y + h / 2);
+ if (opt->state & State_Sunken) {
+ center += QPoint(proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget),
+ proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget));
+ }
+ p->translate(center);
+ p->fillRect(-len / 2, -step2, len, step, opt->palette.buttonText());
if (pe == PE_IndicatorSpinPlus)
- p->fillRect(br.x() + br.width() / 2 - step / 2 + offset, br.y() + offset,
- step, br.height(),
- opt->palette.buttonText());
-
+ p->fillRect(-step2, -len / 2, step, len, opt->palette.buttonText());
break; }
case PE_IndicatorSpinUp:
case PE_IndicatorSpinDown: {
QRect r = opt->rect;
int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
// QRect br = r.adjusted(fw, fw, -fw, -fw);
- int x = r.x(), y = r.y(), w = r.width(), h = r.height();
+ int x = r.x();
+ int y = r.y();
+ int w = r.width();
+ int h = r.height();
+ QPainterStateSaver pss(p);
+ const qreal devicePixelRatio = p->device()->devicePixelRatio();
+ if (!qFuzzyCompare(devicePixelRatio, qreal(1))) {
+ const qreal inverseScale = qreal(1) / devicePixelRatio;
+ p->scale(inverseScale, inverseScale);
+ x = qRound(devicePixelRatio * x);
+ y = qRound(devicePixelRatio * y);
+ w = qRound(devicePixelRatio * w);
+ h = qRound(devicePixelRatio * h);
+ p->translate(0.5, 0.5);
+ }
int sw = w-4;
if (sw < 3)
break;
@@ -521,10 +577,9 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
int bsx = 0;
int bsy = 0;
if (opt->state & State_Sunken) {
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt);
+ bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget);
+ bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget);
}
- p->save();
p->translate(sx + bsx, sy + bsy);
p->setPen(opt->palette.buttonText().color());
p->setBrush(opt->palette.buttonText());
@@ -535,7 +590,6 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
const QPoint points[] = { QPoint(0, sh-1), QPoint(sw-1, sh-1), QPoint(sh-2, 1) };
p->drawPolygon(points, sizeof points / sizeof *points);
}
- p->restore();
break; }
#endif // QT_CONFIG(spinbox)
case PE_PanelTipLabel: {
@@ -593,7 +647,7 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
case PE_IndicatorColumnViewArrow: {
if (const QStyleOptionViewItem *viewOpt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
bool reverse = (viewOpt->direction == Qt::RightToLeft);
- p->save();
+ QPainterStateSaver pss(p);
QPainterPath path;
int x = viewOpt->rect.x() + 1;
int offset = (viewOpt->rect.height() / 3);
@@ -638,7 +692,6 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
p->setPen(color);
p->drawPath(lines);
}
- p->restore();
}
break; }
#endif //QT_CONFIG(columnview)
@@ -697,37 +750,36 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
case PE_IndicatorArrowRight:
case PE_IndicatorArrowLeft:
{
- if (opt->rect.width() <= 1 || opt->rect.height() <= 1)
+ const QRect &r = opt->rect;
+ if (r.width() <= 1 || r.height() <= 1)
break;
- QRect r = opt->rect;
int size = qMin(r.height(), r.width());
QPixmap pixmap;
- QString pixmapName =
- QStyleHelper::uniqueName("$qt_ia-"_L1
- % QLatin1StringView(metaObject()->className()),
- opt, QSize(size, size))
- % HexString<uint>(pe);
+ const qreal dpr = p->device()->devicePixelRatio();
+ const QString pixmapName = QStyleHelper::uniqueName("$qt_ia-"_L1
+ % QLatin1StringView(metaObject()->className())
+ % HexString<uint>(pe),
+ opt, QSize(size, size), dpr);
if (!QPixmapCache::find(pixmapName, &pixmap)) {
- qreal pixelRatio = p->device()->devicePixelRatio();
- int border = qRound(pixelRatio*(size/5));
- int sqsize = qRound(pixelRatio*(2*(size/2)));
- QImage image(sqsize, sqsize, QImage::Format_ARGB32_Premultiplied);
- image.fill(0);
- QPainter imagePainter(&image);
-
- QPolygon a;
+ const qreal border = size / 5.;
+ const qreal sqsize = size;
+ pixmap = styleCachePixmap(QSize(size, size), dpr);
+ QPainter imagePainter(&pixmap);
+ imagePainter.setRenderHint(QPainter::Antialiasing);
+
+ QPolygonF poly;
switch (pe) {
case PE_IndicatorArrowUp:
- a.setPoints(3, border, sqsize/2, sqsize/2, border, sqsize - border, sqsize/2);
+ poly = {QPointF(border, sqsize / 2), QPointF(sqsize / 2, border), QPointF(sqsize - border, sqsize / 2)};
break;
case PE_IndicatorArrowDown:
- a.setPoints(3, border, sqsize/2, sqsize/2, sqsize - border, sqsize - border, sqsize/2);
+ poly = {QPointF(border, sqsize / 2), QPointF(sqsize / 2, sqsize - border), QPointF(sqsize - border, sqsize / 2)};
break;
case PE_IndicatorArrowRight:
- a.setPoints(3, sqsize - border, sqsize/2, sqsize/2, border, sqsize/2, sqsize - border);
+ poly = {QPointF(sqsize - border, sqsize / 2), QPointF(sqsize / 2, border), QPointF(sqsize / 2, sqsize - border)};
break;
case PE_IndicatorArrowLeft:
- a.setPoints(3, border, sqsize/2, sqsize/2, border, sqsize/2, sqsize - border);
+ poly = {QPointF(border, sqsize / 2), QPointF(sqsize / 2, border), QPointF(sqsize / 2, sqsize - border)};
break;
default:
break;
@@ -741,9 +793,9 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget);
}
- QRect bounds = a.boundingRect();
- int sx = sqsize / 2 - bounds.center().x() - 1;
- int sy = sqsize / 2 - bounds.center().y() - 1;
+ const QPointF boundsCenter = poly.boundingRect().center();
+ const qreal sx = sqsize / 2 - boundsCenter.x();
+ const qreal sy = sqsize / 2 - boundsCenter.y();
imagePainter.translate(sx + bsx, sy + bsy);
imagePainter.setPen(opt->palette.buttonText().color());
imagePainter.setBrush(opt->palette.buttonText());
@@ -752,16 +804,14 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
imagePainter.translate(1, 1);
imagePainter.setBrush(opt->palette.light().color());
imagePainter.setPen(opt->palette.light().color());
- imagePainter.drawPolygon(a);
+ imagePainter.drawPolygon(poly);
imagePainter.translate(-1, -1);
imagePainter.setBrush(opt->palette.mid().color());
imagePainter.setPen(opt->palette.mid().color());
}
- imagePainter.drawPolygon(a);
+ imagePainter.drawPolygon(poly);
imagePainter.end();
- pixmap = QPixmap::fromImage(image);
- pixmap.setDevicePixelRatio(pixelRatio);
QPixmapCache::insert(pixmapName, pixmap);
}
int xOffset = r.x() + (r.width() - size)/2;
@@ -941,18 +991,27 @@ QSize QCommonStylePrivate::viewItemSize(const QStyleOptionViewItem *option, int
break;
}
case QStyleOptionViewItem::Top:
- case QStyleOptionViewItem::Bottom:
- if (wrapText)
- bounds.setWidth(bounds.isValid() ? bounds.width() - 2 * textMargin : option->decorationSize.width());
- else
- bounds.setWidth(QFIXED_MAX);
+ case QStyleOptionViewItem::Bottom: {
+ int width;
+ if (wrapText) {
+ if (bounds.isValid())
+ width = bounds.width() - 2 * textMargin;
+ else if (option->features & QStyleOptionViewItem::HasDecoration)
+ width = option->decorationSize.width();
+ else
+ width = 0;
+ } else {
+ width = QFIXED_MAX;
+ }
+ bounds.setWidth(width);
break;
+ }
default:
break;
}
if (wrapText && option->features & QStyleOptionViewItem::HasCheckIndicator)
- bounds.setWidth(bounds.width() - proxyStyle->pixelMetric(QStyle::PM_IndicatorWidth, option) - 2 * textMargin);
+ bounds.setWidth(bounds.width() - proxyStyle->pixelMetric(QStyle::PM_IndicatorWidth, option, widget) - 2 * textMargin);
const int lineWidth = bounds.width();
const QSizeF size = viewItemTextLayout(textLayout, lineWidth);
@@ -1118,12 +1177,8 @@ void QCommonStylePrivate::viewItemLayout(const QStyleOptionViewItem *opt, QRect
checkRect->size(), check);
*pixmapRect = QStyle::alignedRect(opt->direction, opt->decorationAlignment,
pixmapRect->size(), decoration);
- // the text takes up all available space, unless the decoration is not shown as selected
- if (opt->showDecorationSelected)
- *textRect = display;
- else
- *textRect = QStyle::alignedRect(opt->direction, opt->displayAlignment,
- textRect->size().boundedTo(display.size()), display);
+ // the textRect takes up all remaining size
+ *textRect = display;
} else {
*checkRect = check;
*pixmapRect = decoration;
@@ -1198,7 +1253,7 @@ void QCommonStylePrivate::tabLayout(const QStyleOptionTab *opt, const QWidget *w
if (!opt->icon.isNull()) {
QSize iconSize = opt->iconSize;
if (!iconSize.isValid()) {
- int iconExtent = proxyStyle->pixelMetric(QStyle::PM_SmallIconSize, opt);
+ int iconExtent = proxyStyle->pixelMetric(QStyle::PM_SmallIconSize, opt, widget);
iconSize = QSize(iconExtent, iconExtent);
}
QSize tabIconSize = opt->icon.actualSize(iconSize,
@@ -1224,12 +1279,6 @@ void QCommonStylePrivate::tabLayout(const QStyleOptionTab *opt, const QWidget *w
#if QT_CONFIG(animation)
/*! \internal */
-QList<const QObject*> QCommonStylePrivate::animationTargets() const
-{
- return animations.keys();
-}
-
-/*! \internal */
QStyleAnimation * QCommonStylePrivate::animation(const QObject *target) const
{
return animations.value(target);
@@ -1239,9 +1288,11 @@ QStyleAnimation * QCommonStylePrivate::animation(const QObject *target) const
void QCommonStylePrivate::startAnimation(QStyleAnimation *animation) const
{
Q_Q(const QCommonStyle);
- stopAnimation(animation->target());
- q->connect(animation, SIGNAL(destroyed()), SLOT(_q_removeAnimation()), Qt::UniqueConnection);
- animations.insert(animation->target(), animation);
+ const auto target = animation->target();
+ stopAnimation(target);
+ QObject::connect(animation, &QStyleAnimation::destroyed,
+ q, [this, target]() { removeAnimation(target); });
+ animations.insert(target, animation);
animation->start();
}
@@ -1256,12 +1307,9 @@ void QCommonStylePrivate::stopAnimation(const QObject *target) const
}
/*! \internal */
-void QCommonStylePrivate::_q_removeAnimation()
+void QCommonStylePrivate::removeAnimation(const QObject *target) const
{
- Q_Q(QCommonStyle);
- QObject *animation = q->sender();
- if (animation)
- animations.remove(animation->parent());
+ animations.remove(target);
}
#endif
@@ -1316,7 +1364,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
case CE_PushButtonLabel:
if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
QRect textRect = button->rect;
- uint tf = Qt::AlignVCenter | Qt::TextShowMnemonic;
+ int tf = Qt::AlignVCenter | Qt::TextShowMnemonic;
if (!proxy()->styleHint(SH_UnderlineShortcut, button, widget))
tf |= Qt::TextHideMnemonic;
@@ -1354,13 +1402,16 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
iconRect = visualRect(button->direction, textRect, iconRect);
- if (button->direction == Qt::RightToLeft) {
- tf |= Qt::AlignRight;
+ if (button->direction == Qt::RightToLeft)
textRect.setRight(iconRect.left() - iconSpacing / 2);
- } else {
- tf |= Qt::AlignLeft; //left align, we adjust the text-rect instead
+ else
textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing / 2);
- }
+
+ // qt_format_text reverses again when painter->layoutDirection is also RightToLeft
+ if (p->layoutDirection() == button->direction)
+ tf |= Qt::AlignLeft;
+ else
+ tf |= Qt::AlignRight;
if (button->state & (State_On | State_Sunken))
iconRect.translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget),
@@ -1401,7 +1452,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
case CE_RadioButtonLabel:
case CE_CheckBoxLabel:
if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- uint alignment = visualAlignment(btn->direction, Qt::AlignLeft | Qt::AlignVCenter);
+ int alignment = visualAlignment(btn->direction, Qt::AlignLeft | Qt::AlignVCenter);
if (!proxy()->styleHint(SH_UnderlineShortcut, btn, widget))
alignment |= Qt::TextHideMnemonic;
@@ -1445,11 +1496,11 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
#if QT_CONFIG(menubar)
case CE_MenuBarItem:
if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip
- | Qt::TextSingleLine;
+ int alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip
+ | Qt::TextSingleLine;
if (!proxy()->styleHint(SH_UnderlineShortcut, mbi, widget))
alignment |= Qt::TextHideMnemonic;
- int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt);
+ int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
QPixmap pix = mbi->icon.pixmap(QSize(iconExtent, iconExtent), p->device()->devicePixelRatio(), (mbi->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
if (!pix.isNull())
proxy()->drawItemPixmap(p,mbi->rect, alignment, pix);
@@ -1605,7 +1656,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
QRect rect = header->rect;
if (!header->icon.isNull()) {
- int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt);
+ int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
QPixmap pixmap
= header->icon.pixmap(QSize(iconExtent, iconExtent), p->device()->devicePixelRatio(), (header->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
int pixw = pixmap.width() / pixmap.devicePixelRatio();
@@ -1626,9 +1677,12 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
QFontMetrics fm(header->fontMetrics);
if (header->state & QStyle::State_On) {
QFont fnt = p->font();
- fnt.setBold(true);
- p->setFont(fnt);
- fm = QFontMetrics((p->font()));
+ // the font already has a weight set; don't override that
+ if (!(fnt.resolveMask() & QFont::WeightResolved)) {
+ fnt.setBold(true);
+ p->setFont(fnt);
+ fm = QFontMetrics((p->font()));
+ }
}
QString text = header->text;
if (const QStyleOptionHeaderV2 *headerV2 = qstyleoption_cast<const QStyleOptionHeaderV2 *>(header)) {
@@ -1659,8 +1713,9 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
alignment |= Qt::TextHideMnemonic;
rect.translate(shiftX, shiftY);
p->setFont(toolbutton->font);
+ const QString text = d->toolButtonElideText(toolbutton, rect, alignment);
proxy()->drawItemText(p, rect, alignment, toolbutton->palette,
- opt->state & State_Enabled, toolbutton->text,
+ opt->state & State_Enabled, text,
QPalette::ButtonText);
} else {
QPixmap pm;
@@ -1784,8 +1839,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
break;
case CE_TabBarTabShape:
if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- p->save();
-
+ QPainterStateSaver pss(p);
QRect rect(tab->rect);
bool selected = tab->state & State_Selected;
bool onlyOne = tab->position == QStyleOptionTab::OnlyOneTab;
@@ -1886,7 +1940,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
default:
break;
}
- p->restore();
}
break;
case CE_ToolBoxTabLabel:
@@ -1947,8 +2000,8 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
if (!proxy()->styleHint(SH_UnderlineShortcut, opt, widget))
alignment |= Qt::TextHideMnemonic;
+ QPainterStateSaver pss(p, verticalTabs);
if (verticalTabs) {
- p->save();
int newX, newY, newRot;
if (tab->shape == QTabBar::RoundedEast || tab->shape == QTabBar::TriangularEast) {
newX = tr.width() + tr.x();
@@ -1965,7 +2018,10 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
}
QRect iconRect;
d->tabLayout(tab, widget, &tr, &iconRect);
- tr = proxy()->subElementRect(SE_TabBarTabText, opt, widget); //we compute tr twice because the style may override subElementRect
+
+ // compute tr again, unless tab is moving, because the style may override subElementRect
+ if (tab->position != QStyleOptionTab::TabPosition::Moving)
+ tr = proxy()->subElementRect(SE_TabBarTabText, opt, widget);
if (!tab->icon.isNull()) {
QPixmap tabIcon = tab->icon.pixmap(tab->iconSize, p->device()->devicePixelRatio(),
@@ -1978,11 +2034,10 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
proxy()->drawItemText(p, tr, alignment, tab->palette, tab->state & State_Enabled, tab->text,
widget ? widget->foregroundRole() : QPalette::WindowText);
- if (verticalTabs)
- p->restore();
+ pss.restore();
if (tab->state & State_HasFocus) {
- const int OFFSET = 1 + pixelMetric(PM_DefaultFrameWidth);
+ const int OFFSET = 1 + pixelMetric(PM_DefaultFrameWidth, opt, widget);
int x1, x2;
x1 = tab->rect.left();
@@ -1999,7 +2054,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
#endif // QT_CONFIG(tabbar)
#if QT_CONFIG(sizegrip)
case CE_SizeGrip: {
- p->save();
+ QPainterStateSaver pss(p);
int x, y, w, h;
opt->rect.getRect(&x, &y, &w, &h);
@@ -2068,7 +2123,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
sy += s;
}
}
- p->restore();
break; }
#endif // QT_CONFIG(sizegrip)
#if QT_CONFIG(rubberband)
@@ -2085,7 +2139,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
// ### workaround for borked XRENDER
tiledPixmap = QPixmap::fromImage(tiledPixmap.toImage());
- p->save();
+ QPainterStateSaver pss(p);
QRect r = opt->rect;
QStyleHintReturnMask mask;
if (proxy()->styleHint(QStyle::SH_RubberBand_Mask, opt, widget, &mask))
@@ -2096,7 +2150,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
p->drawRect(r.adjusted(0, 0, -1, -1));
if (rbOpt->shape == QRubberBand::Rectangle)
p->drawRect(r.adjusted(3, 3, -4, -4));
- p->restore();
}
break; }
#endif // QT_CONFIG(rubberband)
@@ -2112,10 +2165,10 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
if (!dwOpt->title.isEmpty()) {
const bool verticalTitleBar = dwOpt->verticalTitleBar;
+ QPainterStateSaver pss(p, verticalTitleBar);
if (verticalTitleBar) {
r = r.transposed();
- p->save();
p->translate(r.left(), r.top() + r.width());
p->rotate(-90);
p->translate(-r.left(), -r.top());
@@ -2123,12 +2176,9 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
const int indent = p->fontMetrics().descent();
proxy()->drawItemText(p, r.adjusted(indent + 1, 1, -indent - 1, -1),
- Qt::AlignLeft | Qt::AlignVCenter, dwOpt->palette,
+ Qt::AlignLeft | Qt::AlignVCenter | Qt::TextHideMnemonic, dwOpt->palette,
dwOpt->state & State_Enabled, dwOpt->title,
QPalette::WindowText);
-
- if (verticalTitleBar)
- p->restore();
}
}
break;
@@ -2138,7 +2188,13 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
QRegion clipRegion = p->clipRegion();
p->setClipRect(opt->rect);
proxy()->drawControl(CE_HeaderSection, header, p, widget);
- QStyleOptionHeader subopt = *header;
+ // opt can be a QStyleOptionHeaderV2 and we must pass it to the subcontrol drawings
+ QStyleOptionHeaderV2 subopt;
+ QStyleOptionHeader &v1Copy = subopt;
+ if (auto v2 = qstyleoption_cast<const QStyleOptionHeaderV2 *>(opt))
+ subopt = *v2;
+ else
+ v1Copy = *header;
subopt.rect = subElementRect(SE_HeaderLabel, header, widget);
if (subopt.rect.isValid())
proxy()->drawControl(CE_HeaderLabel, &subopt, p, widget);
@@ -2164,7 +2220,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
case CE_ComboBoxLabel:
if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
QRect editRect = proxy()->subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, widget);
- p->save();
+ QPainterStateSaver pss(p);
p->setClipRect(editRect);
if (!cb->currentIcon.isNull()) {
QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal
@@ -2189,7 +2245,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
visualAlignment(cb->direction, cb->textAlignment),
cb->palette, cb->state & State_Enabled, cb->currentText);
}
- p->restore();
}
break;
#endif // QT_CONFIG(combobox)
@@ -2235,7 +2290,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
#if QT_CONFIG(itemviews)
case CE_ItemViewItem:
if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
- p->save();
+ QPainterStateSaver pss(p);
// the style calling this might want to clip, so respect any region already set
const QRegion clipRegion = p->hasClipping() ? (p->clipRegion() & opt->rect) : opt->rect;
p->setClipRegion(clipRegion);
@@ -2309,8 +2364,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
? QPalette::Highlight : QPalette::Window);
proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, p, widget);
}
-
- p->restore();
}
break;
@@ -3232,7 +3285,7 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
int fudge = len / 2;
int pos;
// Since there is no subrect for tickmarks do a translation here.
- p->save();
+ QPainterStateSaver pss(p);
p->translate(slider->rect.x(), slider->rect.y());
p->setPen(slider->palette.windowText().color());
int v = slider->minimum;
@@ -3261,7 +3314,6 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
break;
v = nextInterval;
}
- p->restore();
}
}
break;
@@ -3527,12 +3579,11 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
tool.state = down ? State_Sunken : State_Raised;
proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
+ QPainterStateSaver pss(p, down);
if (down)
p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
}
if (tb->subControls & SC_TitleBarMaxButton
@@ -3546,12 +3597,11 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
tool.state = down ? State_Sunken : State_Raised;
proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
+ QPainterStateSaver pss(p, down);
if (down)
p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
}
if (tb->subControls & SC_TitleBarMinButton
@@ -3564,12 +3614,11 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
tool.state = down ? State_Sunken : State_Raised;
proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
+ QPainterStateSaver pss(p, down);
if (down)
p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
}
bool drawNormalButton = (tb->subControls & SC_TitleBarNormalButton)
@@ -3586,12 +3635,11 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
tool.state = down ? State_Sunken : State_Raised;
proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
+ QPainterStateSaver pss(p, down);
if (down)
p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
}
if (tb->subControls & SC_TitleBarShadeButton
@@ -3603,12 +3651,11 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
tool.rect = ir;
tool.state = down ? State_Sunken : State_Raised;
proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
+ QPainterStateSaver pss(p, down);
if (down)
p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
}
if (tb->subControls & SC_TitleBarUnshadeButton
@@ -3621,12 +3668,11 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
tool.rect = ir;
tool.state = down ? State_Sunken : State_Raised;
proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
+ QPainterStateSaver pss(p, down);
if (down)
p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
}
if (tb->subControls & SC_TitleBarContextHelpButton
&& tb->titleBarFlags & Qt::WindowContextHelpButtonHint) {
@@ -3637,12 +3683,11 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
tool.rect = ir;
tool.state = down ? State_Sunken : State_Raised;
proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
+ QPainterStateSaver pss(p, down);
if (down)
p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
}
if (tb->subControls & SC_TitleBarSysMenu && tb->titleBarFlags & Qt::WindowSystemMenuHint) {
ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarSysMenu, widget);
@@ -3652,9 +3697,8 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
int iconSize = proxy()->pixelMetric(PM_SmallIconSize, tb, widget);
pm = proxy()->standardIcon(SP_TitleBarMenuButton, &tool, widget).pixmap(QSize(iconSize, iconSize), p->device()->devicePixelRatio());
tool.rect = ir;
- p->save();
+ QPainterStateSaver pss(p);
proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
}
}
}
@@ -3663,7 +3707,7 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
case CC_Dial:
if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
// OK, this is more a port of things over
- p->save();
+ QPainterStateSaver pss(p);
// avoid dithering
if (p->paintEngine()->hasFeature(QPaintEngine::Antialiasing))
@@ -3748,7 +3792,6 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
fropt.rect = br.adjusted(-2, -2, 2, 2);
proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &fropt, p, widget);
}
- p->restore();
}
break;
#endif // QT_CONFIG(dial)
@@ -3765,7 +3808,7 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
frame.lineWidth = groupBox->lineWidth;
frame.midLineWidth = groupBox->midLineWidth;
frame.rect = proxy()->subControlRect(CC_GroupBox, opt, SC_GroupBoxFrame, widget);
- p->save();
+ QPainterStateSaver pss(p);
QRegion region(groupBox->rect);
if (!groupBox->text.isEmpty()) {
bool ltr = groupBox->direction == Qt::LeftToRight;
@@ -3780,7 +3823,6 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
}
p->setClipRegion(region);
proxy()->drawPrimitive(PE_FrameGroupBox, &frame, p, widget);
- p->restore();
}
// Draw title
@@ -3828,8 +3870,8 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
if (opt->activeSubControls & QStyle::SC_MdiCloseButton && (opt->state & State_Sunken)) {
btnOpt.state |= State_Sunken;
btnOpt.state &= ~State_Raised;
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt);
+ bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget);
+ bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget);
} else {
btnOpt.state |= State_Raised;
btnOpt.state &= ~State_Sunken;
@@ -3845,8 +3887,8 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
if (opt->activeSubControls & QStyle::SC_MdiNormalButton && (opt->state & State_Sunken)) {
btnOpt.state |= State_Sunken;
btnOpt.state &= ~State_Raised;
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt);
+ bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget);
+ bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget);
} else {
btnOpt.state |= State_Raised;
btnOpt.state &= ~State_Sunken;
@@ -3862,8 +3904,8 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
if (opt->activeSubControls & QStyle::SC_MdiMinButton && (opt->state & State_Sunken)) {
btnOpt.state |= State_Sunken;
btnOpt.state &= ~State_Raised;
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt);
+ bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget);
+ bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget);
} else {
btnOpt.state |= State_Raised;
btnOpt.state &= ~State_Sunken;
@@ -4183,6 +4225,7 @@ QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex
break;
case SC_SpinBoxFrame:
ret = spinbox->rect;
+ break;
default:
break;
}
@@ -4343,7 +4386,7 @@ QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex
if (verticalAlignment & Qt::AlignVCenter)
topMargin = topHeight / 2;
else if (verticalAlignment & Qt::AlignTop)
- topMargin = topHeight;
+ topMargin = topHeight + proxy()->pixelMetric(PM_FocusFrameVMargin, groupBox, widget);
}
QRect frameRect = groupBox->rect;
@@ -4476,15 +4519,6 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
case PM_MenuBarHMargin:
ret = 0;
break;
- case PM_DialogButtonsSeparator:
- ret = int(QStyleHelper::dpiScaled(5, opt));
- break;
- case PM_DialogButtonsButtonWidth:
- ret = int(QStyleHelper::dpiScaled(70, opt));
- break;
- case PM_DialogButtonsButtonHeight:
- ret = int(QStyleHelper::dpiScaled(30, opt));
- break;
case PM_TitleBarHeight:
{
if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
@@ -4843,125 +4877,141 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
/*!
\reimp
*/
-QSize QCommonStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &csz, const QWidget *widget) const
+QSize QCommonStyle::sizeFromContents(ContentsType contentsType, const QStyleOption *opt,
+ const QSize &contentsSize, const QWidget *widget) const
{
Q_D(const QCommonStyle);
- QSize sz(csz);
- switch (ct) {
+ QSize size(contentsSize);
+ switch (contentsType) {
case CT_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- int w = csz.width(),
- h = csz.height(),
- bm = proxy()->pixelMetric(PM_ButtonMargin, btn, widget),
- fw = proxy()->pixelMetric(PM_DefaultFrameWidth, btn, widget) * 2;
- w += bm + fw;
- h += bm + fw;
- if (btn->features & QStyleOptionButton::AutoDefaultButton){
- int dbw = proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget) * 2;
- w += dbw;
- h += dbw;
- }
- sz = QSize(w, h);
+ if (const auto *buttonOpt = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
+ int width = contentsSize.width();
+ int height = contentsSize.height();
+ const int buttonMargin = proxy()->pixelMetric(PM_ButtonMargin, buttonOpt, widget);
+ const int defaultFrameWidth = proxy()->pixelMetric(PM_DefaultFrameWidth, buttonOpt, widget) * 2;
+ width += buttonMargin + defaultFrameWidth;
+ height += buttonMargin + defaultFrameWidth;
+ if (buttonOpt->features.testFlag(QStyleOptionButton::AutoDefaultButton)) {
+ const int buttonIndicator = proxy()->pixelMetric(PM_ButtonDefaultIndicator,
+ buttonOpt,
+ widget) * 2;
+ width += buttonIndicator;
+ height += buttonIndicator;
+ }
+ size = QSize(width, height);
}
break;
case CT_RadioButton:
case CT_CheckBox:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- bool isRadio = (ct == CT_RadioButton);
+ if (const auto *buttonOpt = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
+ const bool isRadio = (contentsType == CT_RadioButton);
- int w = proxy()->pixelMetric(isRadio ? PM_ExclusiveIndicatorWidth
- : PM_IndicatorWidth, btn, widget);
- int h = proxy()->pixelMetric(isRadio ? PM_ExclusiveIndicatorHeight
- : PM_IndicatorHeight, btn, widget);
+ const int width = proxy()->pixelMetric(isRadio ? PM_ExclusiveIndicatorWidth
+ : PM_IndicatorWidth, buttonOpt, widget);
+ const int height = proxy()->pixelMetric(isRadio ? PM_ExclusiveIndicatorHeight
+ : PM_IndicatorHeight, buttonOpt, widget);
int margins = 0;
+
// we add 4 pixels for label margins
- if (!btn->icon.isNull() || !btn->text.isEmpty())
+ if (!buttonOpt->icon.isNull() || !buttonOpt->text.isEmpty()) {
margins = 4 + proxy()->pixelMetric(isRadio ? PM_RadioButtonLabelSpacing
: PM_CheckBoxLabelSpacing, opt, widget);
- sz += QSize(w + margins, 4);
- sz.setHeight(qMax(sz.height(), h));
+ }
+
+ size += QSize(width + margins, 4);
+ size.setHeight(qMax(size.height(), height));
}
break;
#if QT_CONFIG(menu)
case CT_MenuItem:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- bool checkable = mi->menuHasCheckableItems;
- int maxpmw = mi->maxIconWidth;
- int w = sz.width(), h = sz.height();
- if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
- w = 10;
- h = 2;
+ if (const auto *menuItemOpt = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
+ const bool checkable = menuItemOpt->menuHasCheckableItems;
+ const int maxpmw = menuItemOpt->maxIconWidth;
+ int width = size.width();
+ int height;
+ if (menuItemOpt->menuItemType == QStyleOptionMenuItem::Separator) {
+ width = 10;
+ height = 2;
} else {
- h = mi->fontMetrics.height() + 8;
- if (!mi->icon.isNull()) {
- int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt);
- h = qMax(h, mi->icon.actualSize(QSize(iconExtent, iconExtent)).height() + 4);
+ height = menuItemOpt->fontMetrics.height() + 8;
+ if (!menuItemOpt->icon.isNull()) {
+ int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
+ height = qMax(height,
+ menuItemOpt->icon.actualSize(QSize(iconExtent,
+ iconExtent)).height() + 4);
}
}
- if (mi->text.contains(u'\t'))
- w += 12;
+ if (menuItemOpt->text.contains(u'\t'))
+ width += 12;
if (maxpmw > 0)
- w += maxpmw + 6;
+ width += maxpmw + 6;
if (checkable && maxpmw < 20)
- w += 20 - maxpmw;
+ width += 20 - maxpmw;
if (checkable || maxpmw > 0)
- w += 2;
- w += 12;
- sz = QSize(w, h);
+ width += 2;
+ width += 12;
+ size = QSize(width, height);
}
break;
#endif // QT_CONFIG(menu)
#if QT_CONFIG(toolbutton)
case CT_ToolButton:
- sz = QSize(sz.width() + 6, sz.height() + 5);
+ size = QSize(size.width() + 6, size.height() + 5);
break;
#endif // QT_CONFIG(toolbutton)
#if QT_CONFIG(combobox)
case CT_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- int fw = cmb->frame ? proxy()->pixelMetric(PM_ComboBoxFrameWidth, opt, widget) * 2 : 0;
- const int textMargins = 2*(proxy()->pixelMetric(PM_FocusFrameHMargin, opt) + 1);
+ if (const auto *comboBoxOpt = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
+ const int frameWidth = comboBoxOpt->frame ? proxy()->pixelMetric(PM_ComboBoxFrameWidth,
+ opt,
+ widget) * 2 : 0;
+ const int textMargins = 2 * (proxy()->pixelMetric(PM_FocusFrameHMargin, opt, widget) + 1);
+
// QItemDelegate::sizeHint expands the textMargins two times, thus the 2*textMargins...
- int other = qMax(23, 2*textMargins + proxy()->pixelMetric(QStyle::PM_ScrollBarExtent, opt, widget));
- sz = QSize(sz.width() + fw + other, sz.height() + fw);
+ const int other = qMax(23, 2 * textMargins
+ + proxy()->pixelMetric(QStyle::PM_ScrollBarExtent,
+ opt, widget));
+
+ size = QSize(size.width() + frameWidth + other, size.height() + frameWidth);
}
break;
#endif // QT_CONFIG(combobox)
case CT_HeaderSection:
- if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- bool nullIcon = hdr->icon.isNull();
- int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, hdr, widget);
- int iconSize = nullIcon ? 0 : proxy()->pixelMetric(QStyle::PM_SmallIconSize, hdr, widget);
- QSize txt = hdr->fontMetrics.size(0, hdr->text);
- sz.setHeight(margin + qMax(iconSize, txt.height()) + margin);
- sz.setWidth((nullIcon ? 0 : margin) + iconSize
- + (hdr->text.isNull() ? 0 : margin) + txt.width() + margin);
- if (hdr->sortIndicator != QStyleOptionHeader::None) {
- int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, hdr, widget);
- if (hdr->orientation == Qt::Horizontal)
- sz.rwidth() += sz.height() + margin;
+ if (const auto *headerOpt = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
+ const bool nullIcon = headerOpt->icon.isNull();
+ const int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, headerOpt, widget);
+ const int iconSize = nullIcon ? 0 : proxy()->pixelMetric(QStyle::PM_SmallIconSize,
+ headerOpt,
+ widget);
+ const QSize textSize = headerOpt->fontMetrics.size(0, headerOpt->text);
+ size.setHeight(margin + qMax(iconSize, textSize.height()) + margin);
+ size.setWidth((nullIcon ? 0 : margin) + iconSize
+ + (headerOpt->text.isNull() ? 0 : margin) + textSize.width() + margin);
+ if (headerOpt->sortIndicator != QStyleOptionHeader::None) {
+ const int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, headerOpt, widget);
+ if (headerOpt->orientation == Qt::Horizontal)
+ size.rwidth() += size.height() + margin;
else
- sz.rheight() += sz.width() + margin;
+ size.rheight() += size.width() + margin;
}
}
break;
case CT_TabWidget:
- sz += QSize(4, 4);
+ size += QSize(4, 4);
break;
case CT_LineEdit:
- if (const QStyleOptionFrame *f = qstyleoption_cast<const QStyleOptionFrame *>(opt))
- sz += QSize(2*f->lineWidth, 2*f->lineWidth);
+ if (const auto *frameOpt = qstyleoption_cast<const QStyleOptionFrame *>(opt))
+ size += QSize(2 * frameOpt->lineWidth, 2 * frameOpt->lineWidth);
break;
#if QT_CONFIG(groupbox)
case CT_GroupBox:
- if (const QStyleOptionGroupBox *styleOpt = qstyleoption_cast<const QStyleOptionGroupBox *>(opt))
- sz += QSize(styleOpt->features.testFlag(QStyleOptionFrame::Flat) ? 0 : 16, 0);
+ if (const auto *groupBoxOpt = qstyleoption_cast<const QStyleOptionGroupBox *>(opt))
+ size += QSize(groupBoxOpt->features.testFlag(QStyleOptionFrame::Flat) ? 0 : 16, 0);
break;
#endif // QT_CONFIG(groupbox)
case CT_MdiControls:
- if (const QStyleOptionComplex *styleOpt = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
+ if (const auto *styleOpt = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
const int buttonSize = proxy()->pixelMetric(PM_TitleBarButtonSize, styleOpt, widget);
int width = 1;
if (styleOpt->subControls & SC_MdiMinButton)
@@ -4970,34 +5020,36 @@ QSize QCommonStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
width += buttonSize + 1;
if (styleOpt->subControls & SC_MdiCloseButton)
width += buttonSize + 1;
- sz = QSize(width, buttonSize);
+ size = QSize(width, buttonSize);
} else {
const int buttonSize = proxy()->pixelMetric(PM_TitleBarButtonSize, opt, widget);
- sz = QSize(1 + 3 * (buttonSize + 1), buttonSize);
+ size = QSize(1 + 3 * (buttonSize + 1), buttonSize);
}
break;
#if QT_CONFIG(itemviews)
case CT_ItemViewItem:
- if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
+ if (const auto *viewItemOpt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
QRect decorationRect, displayRect, checkRect;
- d->viewItemLayout(vopt, &checkRect, &decorationRect, &displayRect, true);
- sz = (decorationRect|displayRect|checkRect).size();
- if (decorationRect.isValid() && sz.height() == decorationRect.height())
- sz.rheight() += 2; // Prevent icons from overlapping.
- }
+ d->viewItemLayout(viewItemOpt, &checkRect, &decorationRect, &displayRect, true);
+ size = (decorationRect|displayRect|checkRect).size();
+ if (decorationRect.isValid() && size.height() == decorationRect.height())
+ size.rheight() += 2; // Prevent icons from overlapping.
+ }
break;
#else
Q_UNUSED(d);
#endif // QT_CONFIG(itemviews)
#if QT_CONFIG(spinbox)
case CT_SpinBox:
- if (const QStyleOptionSpinBox *vopt = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
+ if (const auto *spinBoxOpt = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
// Add button + frame widths
const qreal dpi = QStyleHelper::dpi(opt);
- const bool hasButtons = (vopt->buttonSymbols != QAbstractSpinBox::NoButtons);
+ const bool hasButtons = (spinBoxOpt->buttonSymbols != QAbstractSpinBox::NoButtons);
const int buttonWidth = hasButtons ? qRound(QStyleHelper::dpiScaled(16, dpi)) : 0;
- const int fw = vopt->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, vopt, widget) : 0;
- sz += QSize(buttonWidth + 2*fw, 2*fw);
+ const int frameWidth = spinBoxOpt->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth,
+ spinBoxOpt, widget) : 0;
+
+ size += QSize(buttonWidth + 2 * frameWidth, 2 * frameWidth);
}
break;
#endif
@@ -5013,7 +5065,7 @@ QSize QCommonStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
default:
break;
}
- return sz;
+ return size;
}
@@ -5128,9 +5180,12 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
ret = 1;
break;
- case SH_UnderlineShortcut:
- ret = 1;
+ case SH_UnderlineShortcut: {
+ const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme();
+ ret = theme ? theme->themeHint(QPlatformTheme::UnderlineShortcut).toInt()
+ : QPlatformTheme::defaultThemeHint(QPlatformTheme::UnderlineShortcut).toInt();
break;
+ }
case SH_SpinBox_ClickAutoRepeatRate:
ret = 150;
@@ -5173,8 +5228,8 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
if (widget) {
if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
mask->region = widget->rect();
- const int vmargin = proxy()->pixelMetric(QStyle::PM_FocusFrameVMargin, opt);
- const int hmargin = proxy()->pixelMetric(QStyle::PM_FocusFrameHMargin, opt);
+ const int vmargin = proxy()->pixelMetric(QStyle::PM_FocusFrameVMargin, opt, widget);
+ const int hmargin = proxy()->pixelMetric(QStyle::PM_FocusFrameHMargin, opt, widget);
mask->region -= QRect(widget->rect().adjusted(hmargin, vmargin, -hmargin, -vmargin));
}
}
@@ -5187,7 +5242,7 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
ret = true;
if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
mask->region = opt->rect;
- const int margin = proxy()->pixelMetric(PM_DefaultFrameWidth, opt) * 2;
+ const int margin = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget) * 2;
mask->region -= opt->rect.adjusted(margin, margin, -margin, -margin);
}
}
@@ -5407,7 +5462,6 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
case SH_ItemView_PaintAlternatingRowColorsForEmptyArea:
case SH_ComboBox_UseNativePopup:
case SH_Table_AlwaysDrawLeftTopGridLines:
- case SH_SupportsDarkAppearance:
ret = false;
break;
case SH_MenuBar_AltKeyNavigation:
@@ -5438,647 +5492,313 @@ static QPixmap cachedPixmapFromXPM(const char * const *xpm)
static inline QPixmap titleBarMenuCachedPixmapFromXPM() { return cachedPixmapFromXPM(qt_menu_xpm); }
#endif // QT_CONFIG(imageformat_xpm)
-#ifndef QT_NO_IMAGEFORMAT_PNG
-static inline QString clearText16IconPath()
-{
- return QStringLiteral(":/qt-project.org/styles/commonstyle/images/cleartext-16.png");
-}
-#endif // !QT_NO_IMAGEFORMAT_PNG
+#if QT_CONFIG(imageformat_png)
+static constexpr QLatin1StringView iconResourcePrefix() noexcept { return ":/qt-project.org/styles/commonstyle/images/"_L1; }
+static constexpr QLatin1StringView iconPngSuffix() noexcept { return ".png"_L1; }
-#if defined(Q_OS_WIN) || QT_CONFIG(imageformat_png)
-static QIcon clearTextIcon(bool rtl)
+template <typename T>
+static void addIconFiles(QStringView prefix, std::initializer_list<T> sizes, QIcon &icon,
+ QIcon::Mode mode = QIcon::Normal, QIcon::State state = QIcon::Off)
{
- const QString directionalThemeName = rtl
- ? QStringLiteral("edit-clear-locationbar-ltr") : QStringLiteral("edit-clear-locationbar-rtl");
- if (QIcon::hasThemeIcon(directionalThemeName))
- return QIcon::fromTheme(directionalThemeName);
- const QString themeName = QStringLiteral("edit-clear");
- if (QIcon::hasThemeIcon(themeName))
- return QIcon::fromTheme(themeName);
-
- QIcon icon;
-#ifndef QT_NO_IMAGEFORMAT_PNG
- QPixmap clearText16(clearText16IconPath());
- Q_ASSERT(!clearText16.size().isEmpty());
- icon.addPixmap(clearText16);
- QPixmap clearText32(QStringLiteral(":/qt-project.org/styles/commonstyle/images/cleartext-32.png"));
- Q_ASSERT(!clearText32.size().isEmpty());
- icon.addPixmap(clearText32);
- clearText32.setDevicePixelRatio(2); // The 32x32 pixmap can also be used for 16x16/devicePixelRatio=2
- icon.addPixmap(clearText32);
-#endif // !QT_NO_IMAGEFORMAT_PNG
- return icon;
+ const auto fullPrefix = iconResourcePrefix() + prefix;
+ for (int size : sizes)
+ icon.addFile(fullPrefix + QString::number(size) + iconPngSuffix(),
+ QSize(size, size), mode, state);
}
-#endif
+
+static constexpr auto dockTitleIconSizes = {10, 16, 20, 32, 48, 64};
+static constexpr auto titleBarSizes = {16, 32, 48};
+static constexpr auto toolBarExtHSizes = {8, 16, 32, 128};
+static constexpr auto toolBarExtVSizes = {5, 10, 20, 80};
+static constexpr auto pngIconSizes = {16, 32, 128};
+#endif // imageformat_png
/*! \reimp */
QPixmap QCommonStyle::standardPixmap(StandardPixmap sp, const QStyleOption *option,
const QWidget *widget) const
{
- const bool rtl = (option && option->direction == Qt::RightToLeft) || (!option && QGuiApplication::isRightToLeft());
-#ifdef QT_NO_IMAGEFORMAT_PNG
- Q_UNUSED(widget);
- Q_UNUSED(sp);
-#else
- QPixmap pixmap;
+ Q_D(const QCommonStyle);
+ QIcon icon;
- if (QGuiApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty()) {
- switch (sp) {
- case SP_DialogYesButton:
- case SP_DialogOkButton:
- pixmap = QIcon::fromTheme("dialog-ok"_L1).pixmap(16);
- break;
- case SP_DialogApplyButton:
- pixmap = QIcon::fromTheme("dialog-ok-apply"_L1).pixmap(16);
- break;
- case SP_DialogDiscardButton:
- pixmap = QIcon::fromTheme("edit-delete"_L1).pixmap(16);
- break;
- case SP_DialogCloseButton:
- pixmap = QIcon::fromTheme("dialog-close"_L1).pixmap(16);
- break;
- case SP_DirHomeIcon:
- pixmap = QIcon::fromTheme("user-home"_L1).pixmap(16);
- break;
- case SP_MessageBoxInformation:
- pixmap = QIcon::fromTheme("messagebox_info"_L1).pixmap(16);
- break;
- case SP_MessageBoxWarning:
- pixmap = QIcon::fromTheme("messagebox_warning"_L1).pixmap(16);
- break;
- case SP_MessageBoxCritical:
- pixmap = QIcon::fromTheme("messagebox_critical"_L1).pixmap(16);
- break;
- case SP_MessageBoxQuestion:
- pixmap = QIcon::fromTheme("help"_L1).pixmap(16);
- break;
- case SP_DialogOpenButton:
- case SP_DirOpenIcon:
- pixmap = QIcon::fromTheme("folder-open"_L1).pixmap(16);
- break;
- case SP_FileIcon:
- pixmap = QIcon::fromTheme("text-x-generic"_L1, QIcon::fromTheme("empty"_L1)).pixmap(16);
- break;
- case SP_DirClosedIcon:
- case SP_DirIcon:
- pixmap = QIcon::fromTheme("folder"_L1).pixmap(16);
- break;
- case SP_DriveFDIcon:
- pixmap = QIcon::fromTheme("media-floppy"_L1,
- QIcon::fromTheme("3floppy_unmount"_L1)).pixmap(16);
- break;
- case SP_ComputerIcon:
- pixmap = QIcon::fromTheme("computer"_L1, QIcon::fromTheme("system"_L1)).pixmap(16);
- break;
- case SP_DesktopIcon:
- pixmap = QIcon::fromTheme("user-desktop"_L1,
- QIcon::fromTheme("desktop"_L1)).pixmap(16);
- break;
- case SP_TrashIcon:
- pixmap = QIcon::fromTheme("user-trash"_L1,
- QIcon::fromTheme("trashcan_empty"_L1)).pixmap(16);
- break;
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- pixmap = QIcon::fromTheme("media-optical"_L1,
- QIcon::fromTheme("cdrom_unmount"_L1)).pixmap(16);
- break;
- case SP_DriveHDIcon:
- pixmap = QIcon::fromTheme("drive-harddisk"_L1,
- QIcon::fromTheme("hdd_unmount"_L1)).pixmap(16);
- break;
- case SP_FileDialogToParent:
- pixmap = QIcon::fromTheme("go-up"_L1, QIcon::fromTheme("up"_L1)).pixmap(16);
- break;
- case SP_FileDialogNewFolder:
- pixmap = QIcon::fromTheme("folder_new"_L1).pixmap(16);
- break;
- case SP_ArrowUp:
- pixmap = QIcon::fromTheme("go-up"_L1,
- QIcon::fromTheme("up"_L1)).pixmap(16);
- break;
- case SP_ArrowDown:
- pixmap = QIcon::fromTheme("go-down"_L1, QIcon::fromTheme("down"_L1)).pixmap(16);
- break;
- case SP_ArrowRight:
- pixmap = QIcon::fromTheme("go-next"_L1, QIcon::fromTheme("forward"_L1)).pixmap(16);
- break;
- case SP_ArrowLeft:
- pixmap = QIcon::fromTheme("go-previous"_L1, QIcon::fromTheme("back"_L1)).pixmap(16);
- break;
- case SP_FileDialogDetailedView:
- pixmap = QIcon::fromTheme("view_detailed"_L1).pixmap(16);
- break;
- case SP_FileDialogListView:
- pixmap = QIcon::fromTheme("view_icon"_L1).pixmap(16);
- break;
- case SP_BrowserReload:
- pixmap = QIcon::fromTheme("reload"_L1).pixmap(16);
- break;
- case SP_BrowserStop:
- pixmap = QIcon::fromTheme("process-stop"_L1).pixmap(16);
- break;
- case SP_MediaPlay:
- pixmap = QIcon::fromTheme("media-playback-start"_L1).pixmap(16);
- break;
- case SP_MediaPause:
- pixmap = QIcon::fromTheme("media-playback-pause"_L1).pixmap(16);
- break;
- case SP_MediaStop:
- pixmap = QIcon::fromTheme("media-playback-stop"_L1).pixmap(16);
- break;
- case SP_MediaSeekForward:
- pixmap = QIcon::fromTheme("media-seek-forward"_L1).pixmap(16);
- break;
- case SP_MediaSeekBackward:
- pixmap = QIcon::fromTheme("media-seek-backward"_L1).pixmap(16);
- break;
- case SP_MediaSkipForward:
- pixmap = QIcon::fromTheme("media-skip-forward"_L1).pixmap(16);
- break;
- case SP_MediaSkipBackward:
- pixmap = QIcon::fromTheme("media-skip-backward"_L1).pixmap(16);
- break;
- case SP_DialogResetButton:
- pixmap = QIcon::fromTheme("edit-clear"_L1).pixmap(24);
- break;
- case SP_DialogHelpButton:
- pixmap = QIcon::fromTheme("help-contents"_L1).pixmap(24);
- break;
- case SP_DialogNoButton:
- case SP_DialogCancelButton:
- pixmap = QIcon::fromTheme("dialog-cancel"_L1,
- QIcon::fromTheme("process-stop"_L1)).pixmap(24);
- break;
- case SP_DialogSaveButton:
- pixmap = QIcon::fromTheme("document-save"_L1).pixmap(24);
- break;
- case SP_FileLinkIcon:
- pixmap = QIcon::fromTheme("emblem-symbolic-link"_L1).pixmap(16);
- if (!pixmap.isNull()) {
- QPixmap fileIcon = QIcon::fromTheme("text-x-generic"_L1).pixmap(16);
- if (fileIcon.isNull())
- fileIcon = QIcon::fromTheme("empty"_L1).pixmap(16);
- if (!fileIcon.isNull()) {
- QPainter painter(&fileIcon);
- painter.drawPixmap(0, 0, 16, 16, pixmap);
- return fileIcon;
- }
- }
- break;
- case SP_DirLinkIcon:
- pixmap = QIcon::fromTheme("emblem-symbolic-link"_L1).pixmap(16);
- if (!pixmap.isNull()) {
- QPixmap dirIcon = QIcon::fromTheme("folder"_L1).pixmap(16);
- if (!dirIcon.isNull()) {
- QPainter painter(&dirIcon);
- painter.drawPixmap(0, 0, 16, 16, pixmap);
- return dirIcon;
- }
- }
- break;
- case SP_LineEditClearButton:
- pixmap = clearTextIcon(rtl).pixmap(16);
- break;
- default:
- break;
- }
- }
+ icon = d->iconFromWindowsTheme(sp, option, widget);
+ if (!icon.isNull())
+ return icon.pixmap(QSize(16, 16), qt_getDevicePixelRatio(widget));
+
+ icon = d->iconFromApplicationTheme(sp, option, widget);
+ if (!icon.isNull())
+ return icon.pixmap(QSize(16, 16), qt_getDevicePixelRatio(widget));
+
+ icon = d->iconFromMacTheme(sp, option, widget);
+ if (!icon.isNull())
+ return icon.pixmap(QSize(16, 16), qt_getDevicePixelRatio(widget));
+
+ icon = d->iconFromResourceTheme(sp, option, widget);
+ if (!icon.isNull())
+ return icon.pixmap(QSize(16, 16), qt_getDevicePixelRatio(widget));
- if (!pixmap.isNull())
- return pixmap;
-#endif //QT_NO_IMAGEFORMAT_PNG
- switch (sp) {
#ifndef QT_NO_IMAGEFORMAT_XPM
- case SP_ToolBarHorizontalExtensionButton:
- if (rtl) {
- QImage im(tb_extension_arrow_h_xpm);
- im = im.convertToFormat(QImage::Format_ARGB32).mirrored(true, false);
- return QPixmap::fromImage(im);
+ switch (sp) {
+ case QStyle::SP_ToolBarHorizontalExtensionButton:
+ if (d->rtl(option)) {
+ auto im = QImage(tb_extension_arrow_h_xpm).convertToFormat(QImage::Format_ARGB32).mirrored(true, false);
+ return QPixmap::fromImage(std::move(im));
}
return cachedPixmapFromXPM(tb_extension_arrow_h_xpm);
- case SP_ToolBarVerticalExtensionButton:
+ case QStyle::SP_ToolBarVerticalExtensionButton:
return cachedPixmapFromXPM(tb_extension_arrow_v_xpm);
- case SP_FileDialogStart:
+ case QStyle::SP_FileDialogStart:
return cachedPixmapFromXPM(filedialog_start_xpm);
- case SP_FileDialogEnd:
+ case QStyle::SP_FileDialogEnd:
return cachedPixmapFromXPM(filedialog_end_xpm);
-#endif
-#ifndef QT_NO_IMAGEFORMAT_PNG
- case SP_CommandLink:
- case SP_ArrowForward:
- if (rtl)
- return proxy()->standardPixmap(SP_ArrowLeft, option, widget);
- return proxy()->standardPixmap(SP_ArrowRight, option, widget);
- case SP_ArrowBack:
- if (rtl)
- return proxy()->standardPixmap(SP_ArrowRight, option, widget);
- return proxy()->standardPixmap(SP_ArrowLeft, option, widget);
- case SP_ArrowLeft:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/left-16.png"_L1);
- case SP_ArrowRight:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/right-16.png"_L1);
- case SP_ArrowUp:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/up-16.png"_L1);
- case SP_ArrowDown:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/down-16.png"_L1);
- case SP_FileDialogToParent:
- return proxy()->standardPixmap(SP_ArrowUp, option, widget);
- case SP_FileDialogNewFolder:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/newdirectory-16.png"_L1);
- case SP_FileDialogDetailedView:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/viewdetailed-16.png"_L1);
- case SP_FileDialogInfoView:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/fileinfo-16.png"_L1);
- case SP_FileDialogContentsView:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/filecontents-16.png"_L1);
- case SP_FileDialogListView:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/viewlist-16.png"_L1);
- case SP_FileDialogBack:
- return proxy()->standardPixmap(SP_ArrowBack, option, widget);
- case SP_DriveHDIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/harddrive-16.png"_L1);
- case SP_TrashIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/trash-16.png"_L1);
- case SP_DriveFDIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/floppy-16.png"_L1);
- case SP_DriveNetIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/networkdrive-16.png"_L1);
- case SP_DesktopIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/desktop-16.png"_L1);
- case SP_ComputerIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/computer-16.png"_L1);
- case SP_DriveCDIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/cdr-16.png"_L1);
- case SP_DriveDVDIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/dvd-16.png"_L1);
- case SP_DirHomeIcon:
- case SP_DirOpenIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/diropen-16.png"_L1);
- case SP_DirIcon:
- case SP_DirClosedIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/dirclosed-16.png"_L1);
- case SP_DirLinkIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/dirlink-16.png"_L1);
- case SP_FileIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/file-16.png"_L1);
- case SP_FileLinkIcon:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/filelink-16.png"_L1);
- case SP_DialogOkButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-ok-16.png"_L1);
- case SP_DialogCancelButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-cancel-16.png"_L1);
- case SP_DialogHelpButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-help-16.png"_L1);
- case SP_DialogOpenButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-open-16.png"_L1);
- case SP_DialogSaveButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-save-16.png"_L1);
- case SP_DialogCloseButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-close-16.png"_L1);
- case SP_DialogApplyButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-apply-16.png"_L1);
- case SP_DialogResetButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-clear-16.png"_L1);
- case SP_DialogDiscardButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-delete-16.png"_L1);
- case SP_DialogYesButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-yes-16.png"_L1);
- case SP_DialogNoButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-no-16.png"_L1);
- case SP_BrowserReload:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/refresh-24.png"_L1);
- case SP_BrowserStop:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/stop-24.png"_L1);
- case SP_MediaPlay:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-play-32.png"_L1);
- case SP_MediaPause:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-pause-32.png"_L1);
- case SP_MediaStop:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-stop-32.png"_L1);
- case SP_MediaSeekForward:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-seek-forward-32.png"_L1);
- case SP_MediaSeekBackward:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-seek-backward-32.png"_L1);
- case SP_MediaSkipForward:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-skip-forward-32.png"_L1);
- case SP_MediaSkipBackward:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-skip-backward-32.png"_L1);
- case SP_MediaVolume:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-volume-16.png"_L1);
- case SP_MediaVolumeMuted:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/media-volume-muted-16.png"_L1);
- case SP_LineEditClearButton:
- return QPixmap(clearText16IconPath());
- case SP_TabCloseButton:
- return QPixmap(":/qt-project.org/styles/commonstyle/images/standardbutton-closetab-16.png"_L1);
-#endif // QT_NO_IMAGEFORMAT_PNG
- default:
- break;
- }
-
-#ifndef QT_NO_IMAGEFORMAT_XPM
- switch (sp) {
- case SP_TitleBarMenuButton:
+ case QStyle::SP_TitleBarMenuButton:
return titleBarMenuCachedPixmapFromXPM();
- case SP_TitleBarShadeButton:
+ case QStyle::SP_TitleBarShadeButton:
return cachedPixmapFromXPM(qt_shade_xpm);
- case SP_TitleBarUnshadeButton:
+ case QStyle::SP_TitleBarUnshadeButton:
return cachedPixmapFromXPM(qt_unshade_xpm);
- case SP_TitleBarNormalButton:
+ case QStyle::SP_TitleBarNormalButton:
return cachedPixmapFromXPM(qt_normalizeup_xpm);
- case SP_TitleBarMinButton:
+ case QStyle::SP_TitleBarMinButton:
return cachedPixmapFromXPM(qt_minimize_xpm);
- case SP_TitleBarMaxButton:
+ case QStyle::SP_TitleBarMaxButton:
return cachedPixmapFromXPM(qt_maximize_xpm);
- case SP_TitleBarCloseButton:
+ case QStyle::SP_TitleBarCloseButton:
return cachedPixmapFromXPM(qt_close_xpm);
- case SP_TitleBarContextHelpButton:
+ case QStyle::SP_TitleBarContextHelpButton:
return cachedPixmapFromXPM(qt_help_xpm);
- case SP_DockWidgetCloseButton:
+ case QStyle::SP_DockWidgetCloseButton:
return cachedPixmapFromXPM(dock_widget_close_xpm);
- case SP_MessageBoxInformation:
+ case QStyle::SP_MessageBoxInformation:
return cachedPixmapFromXPM(information_xpm);
- case SP_MessageBoxWarning:
+ case QStyle::SP_MessageBoxWarning:
return cachedPixmapFromXPM(warning_xpm);
- case SP_MessageBoxCritical:
+ case QStyle::SP_MessageBoxCritical:
return cachedPixmapFromXPM(critical_xpm);
- case SP_MessageBoxQuestion:
+ case QStyle::SP_MessageBoxQuestion:
return cachedPixmapFromXPM(question_xpm);
default:
break;
}
#endif //QT_NO_IMAGEFORMAT_XPM
-#if !QT_CONFIG(imageformat_png) && !QT_CONFIG(imageformat_xpm) && !QT_CONFIG(imageformat_png)
- Q_UNUSED(rtl);
-#endif
-
return QPixmap();
}
-#if QT_CONFIG(imageformat_png)
-static inline QString iconResourcePrefix() { return QStringLiteral(":/qt-project.org/styles/commonstyle/images/"); }
-static inline QString iconPngSuffix() { return QStringLiteral(".png"); }
-
-static void addIconFiles(const QString &prefix, const int sizes[], size_t count, QIcon &icon)
-{
- for (size_t i = 0; i < count; ++i)
- icon.addFile(prefix + QString::number(sizes[i]) + iconPngSuffix());
-}
-
-static const int dockTitleIconSizes[] = {10, 16, 20, 32, 48, 64};
-static const int titleBarSizes[] = {16, 32, 48};
-static const int toolBarExtHSizes[] = {8, 16, 32};
-static const int toolBarExtVSizes[] = {5, 10, 20};
-#endif // imageformat_png
-
-/*!
- \internal
-*/
-QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget) const
+QIcon QCommonStylePrivate::iconFromWindowsTheme(QCommonStyle::StandardPixmap standardIcon,
+ const QStyleOption *option,
+ const QWidget *widget) const
{
+ Q_UNUSED(option);
+ Q_UNUSED(widget);
QIcon icon;
- const bool rtl = (option && option->direction == Qt::RightToLeft) || (!option && QGuiApplication::isRightToLeft());
-
#ifdef Q_OS_WIN
switch (standardIcon) {
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- case SP_DriveNetIcon:
- case SP_DriveHDIcon:
- case SP_DriveFDIcon:
- case SP_FileIcon:
- case SP_FileLinkIcon:
- case SP_DesktopIcon:
- case SP_ComputerIcon:
- case SP_VistaShield:
- case SP_MessageBoxInformation:
- case SP_MessageBoxWarning:
- case SP_MessageBoxCritical:
- case SP_MessageBoxQuestion:
+ case QStyle::SP_DriveCDIcon:
+ case QStyle::SP_DriveDVDIcon:
+ case QStyle::SP_DriveNetIcon:
+ case QStyle::SP_DriveHDIcon:
+ case QStyle::SP_DriveFDIcon:
+ case QStyle::SP_FileIcon:
+ case QStyle::SP_FileLinkIcon:
+ case QStyle::SP_DesktopIcon:
+ case QStyle::SP_ComputerIcon:
+ case QStyle::SP_VistaShield:
+ case QStyle::SP_MessageBoxInformation:
+ case QStyle::SP_MessageBoxWarning:
+ case QStyle::SP_MessageBoxCritical:
+ case QStyle::SP_MessageBoxQuestion:
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
QPlatformTheme::StandardPixmap sp = static_cast<QPlatformTheme::StandardPixmap>(standardIcon);
- for (int size = 16 ; size <= 32 ; size += 16) {
- QPixmap pixmap = theme->standardPixmap(sp, QSizeF(size, size));
+ const auto dpr = qt_getDevicePixelRatio(widget);
+ const QList<QSize> sizes = theme->themeHint(QPlatformTheme::IconPixmapSizes).value<QList<QSize>>();
+ for (const QSize &size : sizes) {
+ QPixmap pixmap = theme->standardPixmap(sp, size * dpr);
+ pixmap.setDevicePixelRatio(dpr);
icon.addPixmap(pixmap, QIcon::Normal);
}
}
break;
- case SP_DirIcon:
- case SP_DirLinkIcon:
+ case QStyle::SP_DirIcon:
+ case QStyle::SP_DirLinkIcon:
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
QPlatformTheme::StandardPixmap spOff = static_cast<QPlatformTheme::StandardPixmap>(standardIcon);
- QPlatformTheme::StandardPixmap spOn = standardIcon == SP_DirIcon ? QPlatformTheme::DirOpenIcon :
- QPlatformTheme::DirLinkOpenIcon;
- for (int size = 16 ; size <= 32 ; size += 16) {
- QSizeF pixSize(size, size);
+ QPlatformTheme::StandardPixmap spOn = standardIcon == QStyle::SP_DirIcon ? QPlatformTheme::DirOpenIcon
+ : QPlatformTheme::DirLinkOpenIcon;
+ const auto dpr = qt_getDevicePixelRatio(widget);
+ const QList<QSize> sizes = theme->themeHint(QPlatformTheme::IconPixmapSizes).value<QList<QSize>>();
+ for (const QSize &size : sizes) {
+ const QSizeF pixSize = size * dpr;
QPixmap pixmap = theme->standardPixmap(spOff, pixSize);
+ pixmap.setDevicePixelRatio(dpr);
icon.addPixmap(pixmap, QIcon::Normal, QIcon::Off);
pixmap = theme->standardPixmap(spOn, pixSize);
+ pixmap.setDevicePixelRatio(dpr);
icon.addPixmap(pixmap, QIcon::Normal, QIcon::On);
}
}
break;
- case SP_LineEditClearButton:
- icon = clearTextIcon(rtl);
- break;
default:
break;
}
- if (!icon.isNull())
- return icon;
-
+#else
+ Q_UNUSED(standardIcon)
#endif
+ return icon;
+}
+QIcon QCommonStylePrivate::iconFromApplicationTheme(QCommonStyle::StandardPixmap standardIcon,
+ const QStyleOption *option,
+ const QWidget *widget) const
+{
if (QGuiApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty()) {
switch (standardIcon) {
- case SP_DirHomeIcon:
- icon = QIcon::fromTheme("user-home"_L1);
- break;
- case SP_MessageBoxInformation:
- icon = QIcon::fromTheme("dialog-information"_L1);
- break;
- case SP_MessageBoxWarning:
- icon = QIcon::fromTheme("dialog-warning"_L1);
- break;
- case SP_MessageBoxCritical:
- icon = QIcon::fromTheme("dialog-error"_L1);
- break;
- case SP_MessageBoxQuestion:
- icon = QIcon::fromTheme("dialog-question"_L1);
- break;
- case SP_DialogOpenButton:
- case SP_DirOpenIcon:
- icon = QIcon::fromTheme("folder-open"_L1);
- break;
- case SP_DialogSaveButton:
- icon = QIcon::fromTheme("document-save"_L1);
- break;
- case SP_DialogApplyButton:
- icon = QIcon::fromTheme("dialog-ok-apply"_L1);
- break;
- case SP_DialogYesButton:
- case SP_DialogOkButton:
- icon = QIcon::fromTheme("dialog-ok"_L1);
- break;
- case SP_DialogDiscardButton:
- icon = QIcon::fromTheme("edit-delete"_L1);
- break;
- case SP_DialogResetButton:
- icon = QIcon::fromTheme("edit-clear"_L1);
- break;
- case SP_DialogHelpButton:
- icon = QIcon::fromTheme("help-contents"_L1);
- break;
- case SP_FileIcon:
- icon = QIcon::fromTheme("text-x-generic"_L1);
- break;
- case SP_DirClosedIcon:
- case SP_DirIcon:
- icon = QIcon::fromTheme("folder"_L1);
- break;
- case SP_DriveFDIcon:
- icon = QIcon::fromTheme("floppy_unmount"_L1);
- break;
- case SP_ComputerIcon:
- icon = QIcon::fromTheme("computer"_L1, QIcon::fromTheme("system"_L1));
- break;
- case SP_DesktopIcon:
- icon = QIcon::fromTheme("user-desktop"_L1);
- break;
- case SP_TrashIcon:
- icon = QIcon::fromTheme("user-trash"_L1);
- break;
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- icon = QIcon::fromTheme("media-optical"_L1);
- break;
- case SP_DriveHDIcon:
- icon = QIcon::fromTheme("drive-harddisk"_L1);
- break;
- case SP_FileDialogToParent:
- icon = QIcon::fromTheme("go-up"_L1);
- break;
- case SP_FileDialogNewFolder:
- icon = QIcon::fromTheme("folder-new"_L1);
- break;
- case SP_ArrowUp:
- icon = QIcon::fromTheme("go-up"_L1);
- break;
- case SP_ArrowDown:
- icon = QIcon::fromTheme("go-down"_L1);
- break;
- case SP_ArrowRight:
- icon = QIcon::fromTheme("go-next"_L1);
- break;
- case SP_ArrowLeft:
- icon = QIcon::fromTheme("go-previous"_L1);
- break;
- case SP_DialogNoButton:
- case SP_DialogCancelButton:
- icon = QIcon::fromTheme("dialog-cancel"_L1, QIcon::fromTheme("process-stop"_L1));
- break;
- case SP_DialogCloseButton:
- icon = QIcon::fromTheme("window-close"_L1);
- break;
- case SP_FileDialogDetailedView:
- icon = QIcon::fromTheme("view-list-details"_L1);
- break;
- case SP_FileDialogListView:
- icon = QIcon::fromTheme("view-list-icons"_L1);
- break;
- case SP_BrowserReload:
- icon = QIcon::fromTheme("view-refresh"_L1);
- break;
- case SP_BrowserStop:
- icon = QIcon::fromTheme("process-stop"_L1);
- break;
- case SP_MediaPlay:
- icon = QIcon::fromTheme("media-playback-start"_L1);
- break;
- case SP_MediaPause:
- icon = QIcon::fromTheme("media-playback-pause"_L1);
- break;
- case SP_MediaStop:
- icon = QIcon::fromTheme("media-playback-stop"_L1);
- break;
- case SP_MediaSeekForward:
- icon = QIcon::fromTheme("media-seek-forward"_L1);
- break;
- case SP_MediaSeekBackward:
- icon = QIcon::fromTheme("media-seek-backward"_L1);
- break;
- case SP_MediaSkipForward:
- icon = QIcon::fromTheme("media-skip-forward"_L1);
- break;
- case SP_MediaSkipBackward:
- icon = QIcon::fromTheme("media-skip-backward"_L1);
- break;
- case SP_MediaVolume:
- icon = QIcon::fromTheme("audio-volume-medium"_L1);
- break;
- case SP_MediaVolumeMuted:
- icon = QIcon::fromTheme("audio-volume-muted"_L1);
- break;
- case SP_ArrowForward:
- if (rtl)
- return QCommonStyle::standardIcon(SP_ArrowLeft, option, widget);
- return QCommonStyle::standardIcon(SP_ArrowRight, option, widget);
- case SP_ArrowBack:
- if (rtl)
- return QCommonStyle::standardIcon(SP_ArrowRight, option, widget);
- return QCommonStyle::standardIcon(SP_ArrowLeft, option, widget);
- case SP_FileLinkIcon:
- {
- QIcon linkIcon = QIcon::fromTheme("emblem-symbolic-link"_L1);
- if (!linkIcon.isNull()) {
- QIcon baseIcon = QCommonStyle::standardIcon(SP_FileIcon, option, widget);
- const QList<QSize> sizes = baseIcon.availableSizes(QIcon::Normal, QIcon::Off);
- for (int i = 0 ; i < sizes.size() ; ++i) {
- int size = sizes[i].width();
- QPixmap basePixmap = baseIcon.pixmap(QSize(size, size), qt_getDevicePixelRatio(widget));
- QPixmap linkPixmap = linkIcon.pixmap(QSize(size / 2, size / 2), qt_getDevicePixelRatio(widget));
+ case QStyle::SP_DirHomeIcon:
+ return QIcon::fromTheme("user-home"_L1);
+ case QStyle::SP_MessageBoxInformation:
+ return QIcon::fromTheme("dialog-information"_L1);
+ case QStyle::SP_MessageBoxWarning:
+ return QIcon::fromTheme("dialog-warning"_L1);
+ case QStyle::SP_MessageBoxCritical:
+ return QIcon::fromTheme("dialog-error"_L1);
+ case QStyle::SP_MessageBoxQuestion:
+ return QIcon::fromTheme("dialog-question"_L1);
+ case QStyle::SP_DialogOpenButton:
+ case QStyle::SP_DirOpenIcon:
+ return QIcon::fromTheme("folder-open"_L1);
+ case QStyle::SP_DialogSaveButton:
+ return QIcon::fromTheme("document-save"_L1);
+ case QStyle::SP_DialogApplyButton:
+ return QIcon::fromTheme("dialog-ok-apply"_L1);
+ case QStyle::SP_DialogYesButton:
+ case QStyle::SP_DialogOkButton:
+ return QIcon::fromTheme("dialog-ok"_L1);
+ case QStyle::SP_DialogDiscardButton:
+ return QIcon::fromTheme("edit-delete"_L1);
+ case QStyle::SP_DialogResetButton:
+ return QIcon::fromTheme("edit-clear"_L1);
+ case QStyle::SP_DialogHelpButton:
+ return QIcon::fromTheme("help-contents"_L1);
+ case QStyle::SP_FileIcon:
+ return QIcon::fromTheme("text-x-generic"_L1);
+ case QStyle::SP_DirClosedIcon:
+ case QStyle::SP_DirIcon:
+ return QIcon::fromTheme("folder"_L1);
+ case QStyle::SP_DriveFDIcon:
+ return QIcon::fromTheme("floppy_unmount"_L1);
+ case QStyle::SP_ComputerIcon:
+ return QIcon::fromTheme("computer"_L1, QIcon::fromTheme("system"_L1));
+ case QStyle::SP_DesktopIcon:
+ return QIcon::fromTheme("user-desktop"_L1);
+ case QStyle::SP_TrashIcon:
+ return QIcon::fromTheme("user-trash"_L1);
+ case QStyle::SP_DriveCDIcon:
+ case QStyle::SP_DriveDVDIcon:
+ return QIcon::fromTheme("media-optical"_L1);
+ case QStyle::SP_DriveHDIcon:
+ return QIcon::fromTheme("drive-harddisk"_L1);
+ case QStyle::SP_FileDialogToParent:
+ return QIcon::fromTheme("go-up"_L1);
+ case QStyle::SP_FileDialogNewFolder:
+ return QIcon::fromTheme("folder-new"_L1);
+ case QStyle::SP_ArrowUp:
+ return QIcon::fromTheme("go-up"_L1);
+ case QStyle::SP_ArrowDown:
+ return QIcon::fromTheme("go-down"_L1);
+ case QStyle::SP_ArrowRight:
+ return QIcon::fromTheme("go-next"_L1);
+ case QStyle::SP_ArrowLeft:
+ return QIcon::fromTheme("go-previous"_L1);
+ case QStyle::SP_DialogNoButton:
+ case QStyle::SP_DialogCancelButton:
+ return QIcon::fromTheme("dialog-cancel"_L1, QIcon::fromTheme("process-stop"_L1));
+ case QStyle::SP_DialogCloseButton:
+ return QIcon::fromTheme("window-close"_L1);
+ case QStyle::SP_FileDialogDetailedView:
+ return QIcon::fromTheme("view-list-details"_L1);
+ case QStyle::SP_FileDialogListView:
+ return QIcon::fromTheme("view-list-icons"_L1);
+ case QStyle::SP_BrowserReload:
+ return QIcon::fromTheme("view-refresh"_L1);
+ case QStyle::SP_BrowserStop:
+ return QIcon::fromTheme("process-stop"_L1);
+ case QStyle::SP_MediaPlay:
+ return QIcon::fromTheme("media-playback-start"_L1);
+ case QStyle::SP_MediaPause:
+ return QIcon::fromTheme("media-playback-pause"_L1);
+ case QStyle::SP_MediaStop:
+ return QIcon::fromTheme("media-playback-stop"_L1);
+ case QStyle::SP_MediaSeekForward:
+ return QIcon::fromTheme("media-seek-forward"_L1);
+ case QStyle::SP_MediaSeekBackward:
+ return QIcon::fromTheme("media-seek-backward"_L1);
+ case QStyle::SP_MediaSkipForward:
+ return QIcon::fromTheme("media-skip-forward"_L1);
+ case QStyle::SP_MediaSkipBackward:
+ return QIcon::fromTheme("media-skip-backward"_L1);
+ case QStyle::SP_MediaVolume:
+ return QIcon::fromTheme("audio-volume-medium"_L1);
+ case QStyle::SP_MediaVolumeMuted:
+ return QIcon::fromTheme("audio-volume-muted"_L1);
+ case QStyle::SP_ArrowForward:
+ return iconFromApplicationTheme(rtl(option) ? QStyle::SP_ArrowLeft
+ : QStyle::SP_ArrowRight,
+ option, widget);
+ case QStyle::SP_ArrowBack:
+ return iconFromApplicationTheme(rtl(option) ? QStyle::SP_ArrowRight
+ : QStyle::SP_ArrowLeft,
+ option, widget);
+ case QStyle::SP_DirLinkIcon:
+ case QStyle::SP_FileLinkIcon: {
+ const auto si = (standardIcon == QStyle::SP_DirLinkIcon)
+ ? QStyle::SP_DirIcon : QStyle::SP_FileIcon;
+ QIcon icon;
+ const QIcon linkIcon = QIcon::fromTheme("emblem-symbolic-link"_L1);
+ const QIcon baseIcon = iconFromApplicationTheme(si, option, widget);
+ if (!linkIcon.isNull() || !baseIcon.isNull()) {
+ const auto sizes = baseIcon.availableSizes(QIcon::Normal, QIcon::Off);
+ const auto dpr = qt_getDevicePixelRatio(widget);
+ for (const auto size : sizes) {
+ QPixmap basePixmap = baseIcon.pixmap(size, dpr);
+ QPixmap linkPixmap = linkIcon.pixmap(size / 2, dpr);
QPainter painter(&basePixmap);
- painter.drawPixmap(size/2, size/2, linkPixmap);
+ const auto w = size.width() / 2;
+ painter.drawPixmap(w, w, linkPixmap);
icon.addPixmap(basePixmap);
}
}
+ return icon;
}
break;
- case SP_DirLinkIcon:
- {
- QIcon linkIcon = QIcon::fromTheme("emblem-symbolic-link"_L1);
- if (!linkIcon.isNull()) {
- QIcon baseIcon = QCommonStyle::standardIcon(SP_DirIcon, option, widget);
- const QList<QSize> sizes = baseIcon.availableSizes(QIcon::Normal, QIcon::Off);
- for (int i = 0 ; i < sizes.size() ; ++i) {
- int size = sizes[i].width();
- QPixmap basePixmap = baseIcon.pixmap(QSize(size, size), qt_getDevicePixelRatio(widget));
- QPixmap linkPixmap = linkIcon.pixmap(QSize(size / 2, size / 2), qt_getDevicePixelRatio(widget));
- QPainter painter(&basePixmap);
- painter.drawPixmap(size/2, size/2, linkPixmap);
- icon.addPixmap(basePixmap);
- }
- }
+ case QStyle::SP_LineEditClearButton: {
+ const QString directionalThemeName = rtl(option)
+ ? QStringLiteral("edit-clear-locationbar-ltr") : QStringLiteral("edit-clear-locationbar-rtl");
+ if (QIcon::hasThemeIcon(directionalThemeName))
+ return QIcon::fromTheme(directionalThemeName);
+ const QString themeName = QStringLiteral("edit-clear");
+ if (QIcon::hasThemeIcon(themeName))
+ return QIcon::fromTheme(themeName);
+ break;
}
- break;
default:
break;
}
} // if (QGuiApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty())
- if (!icon.isNull())
- return icon;
+ return {};
+}
-#if defined(Q_OS_MAC)
+QIcon QCommonStylePrivate::iconFromMacTheme(QCommonStyle::StandardPixmap standardIcon,
+ const QStyleOption *option,
+ const QWidget *widget) const
+{
+#ifdef Q_OS_DARWIN
+ Q_Q(const QCommonStyle);
if (QGuiApplication::desktopSettingsAware()) {
switch (standardIcon) {
- case SP_DirIcon: {
+ case QStyle::SP_DirIcon: {
// A rather special case
- QIcon closeIcon = QCommonStyle::standardIcon(SP_DirClosedIcon, option, widget);
- QIcon openIcon = QCommonStyle::standardIcon(SP_DirOpenIcon, option, widget);
+ QIcon closeIcon = q->standardIcon(QStyle::SP_DirClosedIcon, option, widget);
+ QIcon openIcon = q->standardIcon(QStyle::SP_DirOpenIcon, option, widget);
closeIcon.addPixmap(openIcon.pixmap(16, 16), QIcon::Normal, QIcon::On);
closeIcon.addPixmap(openIcon.pixmap(32, 32), QIcon::Normal, QIcon::On);
closeIcon.addPixmap(openIcon.pixmap(64, 64), QIcon::Normal, QIcon::On);
@@ -6086,38 +5806,39 @@ QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption
return closeIcon;
}
- case SP_TitleBarNormalButton:
- case SP_TitleBarCloseButton: {
+ case QStyle::SP_TitleBarNormalButton:
+ case QStyle::SP_TitleBarCloseButton: {
QIcon titleBarIcon;
- QString prefix = standardIcon == SP_TitleBarCloseButton
- ? QStringLiteral(":/qt-project.org/styles/macstyle/images/closedock-")
- : QStringLiteral(":/qt-project.org/styles/macstyle/images/dockdock-");
+ constexpr auto imagesPrefix = ":/qt-project.org/styles/macstyle/images/"_L1;
+ const auto namePrefix = standardIcon == QStyle::SP_TitleBarCloseButton
+ ? "closedock-"_L1
+ : "dockdock-"_L1;
for (const auto size : dockTitleIconSizes) {
- titleBarIcon.addFile(prefix + QStringLiteral("macstyle-") + QString::number(size) + iconPngSuffix(),
- QSize(size, size), QIcon::Normal, QIcon::Off);
- titleBarIcon.addFile(prefix + QStringLiteral("down-macstyle-") + QString::number(size) + iconPngSuffix(),
- QSize(size, size), QIcon::Normal, QIcon::On);
+ titleBarIcon.addFile(imagesPrefix + namePrefix + "macstyle-"_L1 + QString::number(size)
+ + iconPngSuffix(), QSize(size, size), QIcon::Normal, QIcon::Off);
+ titleBarIcon.addFile(imagesPrefix + namePrefix + "down-macstyle-"_L1 + QString::number(size)
+ + iconPngSuffix(), QSize(size, size), QIcon::Normal, QIcon::On);
}
return titleBarIcon;
}
- case SP_MessageBoxQuestion:
- case SP_MessageBoxInformation:
- case SP_MessageBoxWarning:
- case SP_MessageBoxCritical:
- case SP_DesktopIcon:
- case SP_TrashIcon:
- case SP_ComputerIcon:
- case SP_DriveFDIcon:
- case SP_DriveHDIcon:
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- case SP_DriveNetIcon:
- case SP_DirOpenIcon:
- case SP_DirClosedIcon:
- case SP_DirLinkIcon:
- case SP_FileLinkIcon:
- case SP_FileIcon:
+ case QStyle::SP_MessageBoxQuestion:
+ case QStyle::SP_MessageBoxInformation:
+ case QStyle::SP_MessageBoxWarning:
+ case QStyle::SP_MessageBoxCritical:
+ case QStyle::SP_DesktopIcon:
+ case QStyle::SP_TrashIcon:
+ case QStyle::SP_ComputerIcon:
+ case QStyle::SP_DriveFDIcon:
+ case QStyle::SP_DriveHDIcon:
+ case QStyle::SP_DriveCDIcon:
+ case QStyle::SP_DriveDVDIcon:
+ case QStyle::SP_DriveNetIcon:
+ case QStyle::SP_DirOpenIcon:
+ case QStyle::SP_DirClosedIcon:
+ case QStyle::SP_DirLinkIcon:
+ case QStyle::SP_FileLinkIcon:
+ case QStyle::SP_FileIcon:
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
QPlatformTheme::StandardPixmap sp = static_cast<QPlatformTheme::StandardPixmap>(standardIcon);
QIcon retIcon;
@@ -6134,277 +5855,288 @@ QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption
retIcon.addPixmap(mainIcon);
}
- if (!retIcon.isNull())
- return retIcon;
+ return retIcon;
}
default:
break;
}
} // if (QGuiApplication::desktopSettingsAware())
-#endif // Q_OS_MAC
+#else // Q_OS_DARWIN
+ Q_UNUSED(standardIcon);
+ Q_UNUSED(option);
+ Q_UNUSED(widget);
+#endif // Q_OS_DARWIN
+ return {};
+}
- switch (standardIcon) {
+QIcon QCommonStylePrivate::iconFromResourceTheme(QCommonStyle::StandardPixmap standardIcon,
+ const QStyleOption *option,
+ const QWidget *widget) const
+{
+ Q_Q(const QCommonStyle);
+ QIcon icon;
#ifndef QT_NO_IMAGEFORMAT_PNG
- case SP_TitleBarMinButton:
- addIconFiles(iconResourcePrefix() + QStringLiteral("titlebar-min-"),
- titleBarSizes, sizeof(titleBarSizes)/sizeof(titleBarSizes[0]), icon);
- break;
- case SP_TitleBarMaxButton:
- addIconFiles(iconResourcePrefix() + QStringLiteral("titlebar-max-"),
- titleBarSizes, sizeof(titleBarSizes)/sizeof(titleBarSizes[0]), icon);
- break;
- case SP_TitleBarShadeButton:
- addIconFiles(iconResourcePrefix() + QStringLiteral("titlebar-shade-"),
- titleBarSizes, sizeof(titleBarSizes)/sizeof(titleBarSizes[0]), icon);
-
- break;
- case SP_TitleBarUnshadeButton:
- addIconFiles(iconResourcePrefix() + QStringLiteral("titlebar-unshade-"),
- titleBarSizes, sizeof(titleBarSizes)/sizeof(titleBarSizes[0]), icon);
- break;
- case SP_TitleBarContextHelpButton:
- addIconFiles(iconResourcePrefix() + QStringLiteral("titlebar-contexthelp-"),
- titleBarSizes, sizeof(titleBarSizes)/sizeof(titleBarSizes[0]), icon);
- break;
- case SP_FileDialogNewFolder:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/newdirectory-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/newdirectory-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/newdirectory-128.png"_L1, QSize(128, 128));
- break;
- case SP_FileDialogBack:
- return QCommonStyle::standardIcon(SP_ArrowBack, option, widget);
- case SP_FileDialogToParent:
- return QCommonStyle::standardIcon(SP_ArrowUp, option, widget);
- case SP_FileDialogDetailedView:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/viewdetailed-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/viewdetailed-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/viewdetailed-128.png"_L1, QSize(128, 128));
- break;
- case SP_FileDialogInfoView:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/fileinfo-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/fileinfo-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/fileinfo-128.png"_L1, QSize(128, 128));
- break;
- case SP_FileDialogContentsView:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/filecontents-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/filecontents-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/filecontents-128.png"_L1, QSize(128, 128));
- break;
- case SP_FileDialogListView:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/viewlist-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/viewlist-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/viewlist-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogOkButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-ok-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-ok-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-ok-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogCancelButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-cancel-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-cancel-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-cancel-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogHelpButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-help-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-help-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-help-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogOpenButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-open-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-open-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-open-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogSaveButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-save-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-save-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-save-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogCloseButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-close-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-close-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-close-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogApplyButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-apply-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-apply-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-apply-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogResetButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-clear-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-clear-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-clear-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogDiscardButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-delete-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-delete-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-delete-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogYesButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-yes-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-yes-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-yes-128.png"_L1, QSize(128, 128));
- break;
- case SP_DialogNoButton:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-no-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-no-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/standardbutton-no-128.png"_L1, QSize(128, 128));
- break;
- case SP_ArrowForward:
- if (rtl)
- return QCommonStyle::standardIcon(SP_ArrowLeft, option, widget);
- return QCommonStyle::standardIcon(SP_ArrowRight, option, widget);
- case SP_ArrowBack:
- if (rtl)
- return QCommonStyle::standardIcon(SP_ArrowRight, option, widget);
- return QCommonStyle::standardIcon(SP_ArrowLeft, option, widget);
- case SP_ArrowLeft:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/left-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/left-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/left-128.png"_L1, QSize(128, 128));
- break;
- case SP_ArrowRight:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/right-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/right-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/right-128.png"_L1, QSize(128, 128));
- break;
- case SP_ArrowUp:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/up-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/up-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/up-128.png"_L1, QSize(128, 128));
- break;
- case SP_ArrowDown:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/down-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/down-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/down-128.png"_L1, QSize(128, 128));
- break;
- case SP_DirHomeIcon:
- case SP_DirIcon:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/dirclosed-16.png"_L1,
- QSize(), QIcon::Normal, QIcon::Off);
- icon.addFile(":/qt-project.org/styles/commonstyle/images/diropen-16.png"_L1,
- QSize(), QIcon::Normal, QIcon::On);
- icon.addFile(":/qt-project.org/styles/commonstyle/images/dirclosed-32.png"_L1,
- QSize(32, 32), QIcon::Normal, QIcon::Off);
- icon.addFile(":/qt-project.org/styles/commonstyle/images/diropen-32.png"_L1,
- QSize(32, 32), QIcon::Normal, QIcon::On);
- icon.addFile(":/qt-project.org/styles/commonstyle/images/dirclosed-128.png"_L1,
- QSize(128, 128), QIcon::Normal, QIcon::Off);
- icon.addFile(":/qt-project.org/styles/commonstyle/images/diropen-128.png"_L1,
- QSize(128, 128), QIcon::Normal, QIcon::On);
- break;
- case SP_DriveCDIcon:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/cdr-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/cdr-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/cdr-128.png"_L1, QSize(128, 128));
- break;
- case SP_DriveDVDIcon:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/dvd-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/dvd-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/dvd-128.png"_L1, QSize(128, 128));
- break;
- case SP_FileIcon:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/file-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/file-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/file-128.png"_L1, QSize(128, 128));
- break;
- case SP_FileLinkIcon:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/filelink-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/filelink-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/filelink-128.png"_L1, QSize(128, 128));
- break;
- case SP_TrashIcon:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/trash-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/trash-32.png"_L1, QSize(32, 32));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/trash-128.png"_L1, QSize(128, 128));
- break;
- case SP_BrowserReload:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/refresh-24.png"_L1, QSize(24, 24));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/refresh-32.png"_L1, QSize(32, 32));
- break;
- case SP_BrowserStop:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/stop-24.png"_L1, QSize(24, 24));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/stop-32.png"_L1, QSize(32, 32));
- break;
- case SP_MediaPlay:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-play-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-play-32.png"_L1, QSize(32, 32));
- break;
- case SP_MediaPause:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-pause-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-pause-32.png"_L1, QSize(32, 32));
- break;
- case SP_MediaStop:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-stop-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-stop-32.png"_L1, QSize(32, 32));
- break;
- case SP_MediaSeekForward:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-seek-forward-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-seek-forward-32.png"_L1, QSize(32, 32));
- break;
- case SP_MediaSeekBackward:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-seek-backward-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-seek-backward-32.png"_L1, QSize(32, 32));
- break;
- case SP_MediaSkipForward:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-skip-forward-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-skip-forward-32.png"_L1, QSize(32, 32));
- break;
- case SP_MediaSkipBackward:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-skip-backward-16.png"_L1, QSize(16, 16));
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-skip-backward-32.png"_L1, QSize(32, 32));
- break;
- case SP_MediaVolume:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-volume-16.png"_L1, QSize(16, 16));
- break;
- case SP_MediaVolumeMuted:
- icon.addFile(":/qt-project.org/styles/commonstyle/images/media-volume-muted-16.png"_L1, QSize(16, 16));
- break;
- case SP_TitleBarCloseButton:
- addIconFiles(iconResourcePrefix() + QStringLiteral("closedock-"),
- dockTitleIconSizes, sizeof(dockTitleIconSizes)/sizeof(dockTitleIconSizes[0]), icon);
- break;
- case SP_TitleBarMenuButton:
+ switch (standardIcon) {
+ case QStyle::SP_MessageBoxInformation:
+ addIconFiles(u"information-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MessageBoxWarning:
+ addIconFiles(u"warning-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MessageBoxCritical:
+ addIconFiles(u"critical-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MessageBoxQuestion:
+ addIconFiles(u"question-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_FileDialogStart:
+ addIconFiles(u"filedialog_start-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_FileDialogEnd:
+ addIconFiles(u"filedialog_end-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_TitleBarMinButton:
+ addIconFiles(u"titlebar-min-", titleBarSizes, icon);
+ break;
+ case QStyle::SP_TitleBarMaxButton:
+ addIconFiles(u"titlebar-max-", titleBarSizes, icon);
+ break;
+ case QStyle::SP_TitleBarShadeButton:
+ addIconFiles(u"titlebar-shade-", titleBarSizes, icon);
+ break;
+ case QStyle::SP_TitleBarUnshadeButton:
+ addIconFiles(u"titlebar-unshade-", titleBarSizes, icon);
+ break;
+ case QStyle::SP_TitleBarContextHelpButton:
+ addIconFiles(u"titlebar-contexthelp-", titleBarSizes, icon);
+ break;
+ case QStyle::SP_FileDialogNewFolder:
+ addIconFiles(u"newdirectory-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_FileDialogBack:
+ return q->proxy()->standardIcon(QStyle::SP_ArrowBack, option, widget);
+ case QStyle::SP_FileDialogToParent:
+ return q->proxy()->standardIcon(QStyle::SP_ArrowUp, option, widget);
+ case QStyle::SP_FileDialogDetailedView:
+ addIconFiles(u"viewdetailed-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_FileDialogInfoView:
+ addIconFiles(u"fileinfo-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_FileDialogContentsView:
+ addIconFiles(u"filecontents-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_FileDialogListView:
+ addIconFiles(u"viewlist-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogOkButton:
+ addIconFiles(u"standardbutton-ok-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogCancelButton:
+ addIconFiles(u"standardbutton-cancel-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogHelpButton:
+ addIconFiles(u"standardbutton-help-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogOpenButton:
+ addIconFiles(u"standardbutton-open-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogSaveButton:
+ addIconFiles(u"standardbutton-save-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogCloseButton:
+ addIconFiles(u"standardbutton-close-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogApplyButton:
+ addIconFiles(u"standardbutton-apply-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogResetButton:
+ addIconFiles(u"standardbutton-clear-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogDiscardButton:
+ addIconFiles(u"standardbutton-delete-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogYesButton:
+ addIconFiles(u"standardbutton-yes-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DialogNoButton:
+ addIconFiles(u"standardbutton-no-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_CommandLink:
+ case QStyle::SP_ArrowForward:
+ return q->proxy()->standardIcon(rtl(option) ? QStyle::SP_ArrowLeft
+ : QStyle::SP_ArrowRight,
+ option, widget);
+ case QStyle::SP_ArrowBack:
+ return q->proxy()->standardIcon(rtl(option) ? QStyle::SP_ArrowRight
+ : QStyle::SP_ArrowLeft,
+ option, widget);
+ case QStyle::SP_ArrowLeft:
+ addIconFiles(u"left-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_ArrowRight:
+ addIconFiles(u"right-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_ArrowUp:
+ addIconFiles(u"up-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_ArrowDown:
+ addIconFiles(u"down-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DirHomeIcon:
+ case QStyle::SP_DirIcon:
+ addIconFiles(u"dirclosed-", pngIconSizes, icon, QIcon::Normal, QIcon::Off);
+ addIconFiles(u"diropen-", pngIconSizes, icon, QIcon::Normal, QIcon::On);
+ break;
+ case QStyle::SP_DirOpenIcon:
+ addIconFiles(u"diropen-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DirClosedIcon:
+ addIconFiles(u"dirclosed-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DirLinkIcon:
+ addIconFiles(u"dirlink-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DriveCDIcon:
+ addIconFiles(u"cdr-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DriveFDIcon:
+ addIconFiles(u"floppy-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DriveHDIcon:
+ addIconFiles(u"harddrive-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DriveDVDIcon:
+ addIconFiles(u"dvd-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DriveNetIcon:
+ addIconFiles(u"networkdrive-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_FileIcon:
+ addIconFiles(u"file-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_FileLinkIcon:
+ addIconFiles(u"filelink-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_DesktopIcon:
+ addIconFiles(u"desktop-", {16, 32}, icon);
+ break;
+ case QStyle::SP_TrashIcon:
+ addIconFiles(u"trash-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_ComputerIcon:
+ addIconFiles(u"computer-", {16, 32}, icon);
+ break;
+ case QStyle::SP_BrowserReload:
+ addIconFiles(u"refresh-", {24, 32}, icon);
+ break;
+ case QStyle::SP_BrowserStop:
+ addIconFiles(u"stop-", {24, 32}, icon);
+ break;
+ case QStyle::SP_MediaPlay:
+ addIconFiles(u"media-play-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MediaPause:
+ addIconFiles(u"media-pause-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MediaStop:
+ addIconFiles(u"media-stop-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MediaSeekForward:
+ addIconFiles(u"media-seek-forward-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MediaSeekBackward:
+ addIconFiles(u"media-seek-backward-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MediaSkipForward:
+ addIconFiles(u"media-skip-forward-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MediaSkipBackward:
+ addIconFiles(u"media-skip-backward-", pngIconSizes, icon);
+ break;
+ case QStyle::SP_MediaVolume:
+ addIconFiles(u"media-volume-", {16}, icon);
+ break;
+ case QStyle::SP_MediaVolumeMuted:
+ addIconFiles(u"media-volume-muted-", {16}, icon);
+ break;
+ case QStyle::SP_TitleBarCloseButton:
+ case QStyle::SP_DockWidgetCloseButton:
+ addIconFiles(u"closedock-", dockTitleIconSizes, icon);
+ break;
+ case QStyle::SP_TitleBarMenuButton:
# ifndef QT_NO_IMAGEFORMAT_XPM
icon.addPixmap(titleBarMenuCachedPixmapFromXPM());
# endif
icon.addFile(":/qt-project.org/qmessagebox/images/qtlogo-64.png"_L1);
break;
- case SP_TitleBarNormalButton:
- addIconFiles(iconResourcePrefix() + QStringLiteral("normalizedockup-"),
- dockTitleIconSizes, sizeof(dockTitleIconSizes)/sizeof(dockTitleIconSizes[0]), icon);
+ case QStyle::SP_TitleBarNormalButton:
+ addIconFiles(u"normalizedockup-", dockTitleIconSizes, icon);
break;
- case SP_ToolBarHorizontalExtensionButton: {
- QString prefix = iconResourcePrefix() + QStringLiteral("toolbar-ext-h-");
- if (rtl)
- prefix += QStringLiteral("rtl-");
- addIconFiles(prefix, toolBarExtHSizes, sizeof(toolBarExtHSizes)/sizeof(toolBarExtHSizes[0]), icon);
- }
+ case QStyle::SP_ToolBarHorizontalExtensionButton:
+ addIconFiles(rtl(option) ? u"toolbar-ext-h-rtl-" : u"toolbar-ext-h-", toolBarExtHSizes, icon);
+ break;
+ case QStyle::SP_ToolBarVerticalExtensionButton:
+ addIconFiles(u"toolbar-ext-v-", toolBarExtVSizes, icon);
+ break;
+ case QStyle::SP_TabCloseButton:
+ addIconFiles(u"standardbutton-closetab-", pngIconSizes, icon, QIcon::Normal, QIcon::Off);
+ addIconFiles(u"standardbutton-closetab-down-", pngIconSizes, icon, QIcon::Normal, QIcon::On);
+ addIconFiles(u"standardbutton-closetab-hover-", pngIconSizes, icon, QIcon::Active, QIcon::Off);
break;
- case SP_ToolBarVerticalExtensionButton:
- addIconFiles(iconResourcePrefix() + QStringLiteral("toolbar-ext-v-"),
- toolBarExtVSizes, sizeof(toolBarExtVSizes)/sizeof(toolBarExtVSizes[0]), icon);
+ case QStyle::SP_LineEditClearButton:
+ addIconFiles(u"cleartext-", pngIconSizes, icon);
break;
+ default:
+ break;
+ }
+#else // QT_NO_IMAGEFORMAT_PNG
+ Q_UNUSED(standardIcon);
+ Q_UNUSED(option);
+ Q_UNUSED(widget);
#endif // QT_NO_IMAGEFORMAT_PNG
- case SP_TabCloseButton:
- icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-16.png", QSize(16, 16),
- QIcon::Normal, QIcon::Off);
- icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-32.png", QSize(32, 32),
- QIcon::Normal, QIcon::Off);
- icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-down-16.png", QSize(16, 16),
- QIcon::Normal, QIcon::On);
- icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-down-32.png", QSize(32, 32),
- QIcon::Normal, QIcon::On);
- icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-hover-16.png", QSize(16, 16),
- QIcon::Active, QIcon::Off);
- icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-hover-32.png", QSize(32, 32),
- QIcon::Active, QIcon::Off);
+ return icon;
+}
+
+
+/*!
+ \internal
+*/
+QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option,
+ const QWidget *widget) const
+{
+ Q_D(const QCommonStyle);
+ QIcon icon;
+
+ icon = d->iconFromWindowsTheme(standardIcon, option, widget);
+ if (!icon.isNull())
+ return icon;
+
+ icon = d->iconFromApplicationTheme(standardIcon, option, widget);
+ if (!icon.isNull())
+ return icon;
+
+ icon = d->iconFromMacTheme(standardIcon, option, widget);
+ if (!icon.isNull())
+ return icon;
+
+ icon = d->iconFromResourceTheme(standardIcon, option, widget);
+ if (!icon.isNull())
+ return icon;
+
+#ifndef QT_NO_IMAGEFORMAT_XPM
+ switch (standardIcon) {
+ case QStyle::SP_TitleBarMenuButton:
+ icon.addPixmap(titleBarMenuCachedPixmapFromXPM());
break;
default:
- icon.addPixmap(proxy()->standardPixmap(standardIcon, option, widget));
break;
}
+ if (!icon.isNull())
+ return icon;
+#endif
+ icon = proxy()->standardPixmap(standardIcon, option, widget);
return icon;
}
@@ -6464,7 +6196,7 @@ QPixmap QCommonStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &p
}
}
- return QPixmap::fromImage(im);
+ return QPixmap::fromImage(std::move(im));
}
case QIcon::Selected: {
QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied);
@@ -6474,7 +6206,7 @@ QPixmap QCommonStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &p
painter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
painter.fillRect(0, 0, img.width(), img.height(), color);
painter.end();
- return QPixmap::fromImage(img); }
+ return QPixmap::fromImage(std::move(img)); }
case QIcon::Active:
return pixmap;
default:
diff --git a/src/widgets/styles/qcommonstyle.h b/src/widgets/styles/qcommonstyle.h
index d6485c6015..40ed13d453 100644
--- a/src/widgets/styles/qcommonstyle.h
+++ b/src/widgets/styles/qcommonstyle.h
@@ -61,9 +61,6 @@ protected:
private:
Q_DECLARE_PRIVATE(QCommonStyle)
Q_DISABLE_COPY(QCommonStyle)
-#if QT_CONFIG(animation)
- Q_PRIVATE_SLOT(d_func(), void _q_removeAnimation())
-#endif
};
QT_END_NAMESPACE
diff --git a/src/widgets/styles/qcommonstyle_p.h b/src/widgets/styles/qcommonstyle_p.h
index d6c701cc2c..2fa90a8949 100644
--- a/src/widgets/styles/qcommonstyle_p.h
+++ b/src/widgets/styles/qcommonstyle_p.h
@@ -5,6 +5,7 @@
#define QCOMMONSTYLE_P_H
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "qhash.h"
#include "qcommonstyle.h"
#include "qstyle_p.h"
#if QT_CONFIG(animation)
@@ -91,13 +92,29 @@ public:
int animationFps;
#if QT_CONFIG(animation)
- void _q_removeAnimation();
-
- QList<const QObject*> animationTargets() const;
QStyleAnimation* animation(const QObject *target) const;
void startAnimation(QStyleAnimation *animation) const;
void stopAnimation(const QObject *target) const;
+ void removeAnimation(const QObject *target) const;
+#endif
+ QIcon iconFromWindowsTheme(QCommonStyle::StandardPixmap standardIcon,
+ const QStyleOption *option,
+ const QWidget *widget) const;
+ QIcon iconFromMacTheme(QCommonStyle::StandardPixmap standardIcon,
+ const QStyleOption *option,
+ const QWidget *widget) const;
+ QIcon iconFromApplicationTheme(QCommonStyle::StandardPixmap standardIcon,
+ const QStyleOption *option,
+ const QWidget *widget) const;
+ QIcon iconFromResourceTheme(QCommonStyle::StandardPixmap standardIcon,
+ const QStyleOption *option,
+ const QWidget *widget) const;
+ static bool inline rtl(const QStyleOption *option) {
+ return (option && option->direction == Qt::RightToLeft) ||
+ (!option && QGuiApplication::isRightToLeft());
+ }
+#if QT_CONFIG(animation)
private:
mutable QHash<const QObject*, QStyleAnimation*> animations;
#endif // animation
diff --git a/src/widgets/styles/qdrawutil.cpp b/src/widgets/styles/qdrawutil.cpp
index bfffeecb6b..5bdbdb1139 100644
--- a/src/widgets/styles/qdrawutil.cpp
+++ b/src/widgets/styles/qdrawutil.cpp
@@ -230,8 +230,8 @@ void qDrawShadeRect(QPainter *p, int x, int y, int w, int h,
p->scale(inverseScale, inverseScale);
x = qRound(devicePixelRatio * x);
y = qRound(devicePixelRatio * y);
- w = qRound(devicePixelRatio * w);
- h = qRound(devicePixelRatio * h);
+ w = devicePixelRatio * w;
+ h = devicePixelRatio * h;
lineWidth = qRound(devicePixelRatio * lineWidth);
midLineWidth = qRound(devicePixelRatio * midLineWidth);
p->translate(0.5, 0.5);
@@ -297,7 +297,6 @@ void qDrawShadeRect(QPainter *p, int x, int y, int w, int h,
p->setPen(oldPen); // restore pen
}
-
/*!
\fn void qDrawShadePanel(QPainter *painter, int x, int y, int width, int height,
const QPalette &palette, bool sunken,
@@ -346,8 +345,8 @@ void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
p->scale(inverseScale, inverseScale);
x = qRound(devicePixelRatio * x);
y = qRound(devicePixelRatio * y);
- w = qRound(devicePixelRatio * w);
- h = qRound(devicePixelRatio * h);
+ w = devicePixelRatio * w;
+ h = devicePixelRatio * h;
lineWidth = qRound(devicePixelRatio * lineWidth);
p->translate(0.5, 0.5);
isTranslated = true;
@@ -409,7 +408,6 @@ void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
p->setPen(oldPen); // restore pen
}
-
/*!
\internal
This function draws a rectangle with two pixel line width.
@@ -443,8 +441,8 @@ static void qDrawWinShades(QPainter *p,
p->scale(inverseScale, inverseScale);
x = qRound(devicePixelRatio * x);
y = qRound(devicePixelRatio * y);
- w = qRound(devicePixelRatio * w);
- h = qRound(devicePixelRatio * h);
+ w = devicePixelRatio * w;
+ h = devicePixelRatio * h;
p->translate(0.5, 0.5);
isTranslated = true;
}
@@ -590,8 +588,8 @@ void qDrawPlainRect(QPainter *p, int x, int y, int w, int h, const QColor &c,
p->scale(inverseScale, inverseScale);
x = qRound(devicePixelRatio * x);
y = qRound(devicePixelRatio * y);
- w = qRound(devicePixelRatio * w);
- h = qRound(devicePixelRatio * h);
+ w = devicePixelRatio * w;
+ h = devicePixelRatio * h;
lineWidth = qRound(devicePixelRatio * lineWidth);
p->translate(0.5, 0.5);
}
@@ -611,6 +609,74 @@ void qDrawPlainRect(QPainter *p, int x, int y, int w, int h, const QColor &c,
p->setBrush(oldBrush);
}
+/*!
+ \fn void qDrawPlainRoundedRect(QPainter *painter, int x, int y,
+ int width, int height, qreal rx, qreal ry,
+ const QColor &lineColor, int lineWidth,
+ const QBrush *fill)
+ \since 6.7
+ \relates <qdrawutil.h>
+
+ Draws the plain rounded rectangle beginning at (\a x, \a y)
+ with the given \a width and \a height,
+ using the horizontal \a rx and vertical radius \a ry,
+ specified \a painter, \a lineColor and \a lineWidth.
+ The rectangle's interior is filled with the \a
+ fill brush unless \a fill is \nullptr.
+
+ \warning This function does not look at QWidget::style() or
+ QApplication::style(). Use the drawing functions in QStyle to make
+ widgets that follow the current GUI style.
+
+ Alternatively you can use a QFrame widget and apply the
+ QFrame::setFrameStyle() function to display a plain rectangle:
+
+ \snippet code/src_gui_painting_qdrawutil.cpp 4
+
+ \sa qDrawShadeRect(), QStyle
+*/
+
+// ### Qt7: Pass QPen instead of QColor for frame drawing
+void qDrawPlainRoundedRect(QPainter *p, int x, int y, int w, int h,
+ qreal rx, qreal ry, const QColor &c,
+ int lineWidth, const QBrush *fill)
+{
+ if (w == 0 || h == 0)
+ return;
+ if (Q_UNLIKELY(w < 0 || h < 0 || lineWidth < 0)) {
+ qWarning("qDrawPlainRect: Invalid parameters");
+ }
+
+ PainterStateGuard painterGuard(p);
+ const qreal devicePixelRatio = p->device()->devicePixelRatio();
+ if (!qFuzzyCompare(devicePixelRatio, qreal(1))) {
+ painterGuard.save();
+ const qreal inverseScale = qreal(1) / devicePixelRatio;
+ p->scale(inverseScale, inverseScale);
+ x = qRound(devicePixelRatio * x);
+ y = qRound(devicePixelRatio * y);
+ w = devicePixelRatio * w;
+ h = devicePixelRatio * h;
+ lineWidth = qRound(devicePixelRatio * lineWidth);
+ p->translate(0.5, 0.5);
+ }
+
+ p->save();
+ p->setPen(c);
+ p->setBrush(Qt::NoBrush);
+ for (int i=0; i<lineWidth; i++) {
+ QRectF rect(x+i, y+i, w-i*2 - 1, h-i*2 - 1);
+ rect.marginsRemoved(QMarginsF(0.5,0.5,0.5,0.5));
+ p->drawRoundedRect(rect, rx, ry);
+ }
+ if (fill) { // fill with fill color
+ p->setPen(Qt::NoPen);
+ p->setBrush(*fill);
+ p->drawRoundedRect(x+lineWidth, y+lineWidth, w-lineWidth*2, h-lineWidth*2, rx, ry);
+ }
+ p->restore();
+}
+
/*****************************************************************************
Overloaded functions.
*****************************************************************************/
@@ -819,6 +885,32 @@ void qDrawPlainRect(QPainter *p, const QRect &r, const QColor &c,
lineWidth, fill);
}
+/*!
+ \fn void qDrawPlainRoundedRect(QPainter *painter, const QRect &rect,
+ qreal rx, qreal ry,
+ const QColor &lineColor, int lineWidth,
+ const QBrush *fill)
+ \since 6.7
+ \relates <qdrawutil.h>
+ \overload
+
+ Draws the plain rectangle specified by \a rect using
+ the horizontal \a rx and vertical radius \a ry,
+ the given \a painter, \a lineColor and \a lineWidth.
+ The rectangle's interior is filled with the
+ \a fill brush unless \a fill is \nullptr.
+
+ \warning This function does not look at QWidget::style() or
+ QApplication::style(). Use the drawing functions in QStyle to make
+ widgets that follow the current GUI style.
+
+ Alternatively you can use a QFrame widget and apply the
+ QFrame::setFrameStyle() function to display a plain rectangle:
+
+ \snippet code/src_gui_painting_qdrawutil.cpp 9
+
+ \sa qDrawShadeRect(), QStyle
+*/
/*!
\class QTileRules
diff --git a/src/widgets/styles/qdrawutil.h b/src/widgets/styles/qdrawutil.h
index 2fc957d493..26d8d5075f 100644
--- a/src/widgets/styles/qdrawutil.h
+++ b/src/widgets/styles/qdrawutil.h
@@ -71,6 +71,17 @@ Q_WIDGETS_EXPORT void qDrawPlainRect(QPainter *p, int x, int y, int w, int h, co
Q_WIDGETS_EXPORT void qDrawPlainRect(QPainter *p, const QRect &r, const QColor &,
int lineWidth = 1, const QBrush *fill = nullptr);
+Q_WIDGETS_EXPORT void qDrawPlainRoundedRect(QPainter *p, int x, int y, int w, int h,
+ qreal rx, qreal ry, const QColor &, int lineWidth = 1,
+ const QBrush *fill = nullptr);
+
+inline void qDrawPlainRoundedRect(QPainter *painter, const QRect& rect, qreal rx, qreal ry,
+ const QColor &lineColor, int lineWidth = 1,
+ const QBrush *fill = nullptr)
+{
+ qDrawPlainRoundedRect(painter, rect.x(), rect.y(), rect.width(), rect.height(),
+ rx, ry, lineColor, lineWidth, fill);
+}
struct QTileRules
diff --git a/src/widgets/styles/qfusionstyle.cpp b/src/widgets/styles/qfusionstyle.cpp
index 966bd47380..34a0105b80 100644
--- a/src/widgets/styles/qfusionstyle.cpp
+++ b/src/widgets/styles/qfusionstyle.cpp
@@ -75,77 +75,6 @@ static const int groupBoxBottomMargin = 0; // space below the groupbox
static const int groupBoxTopMargin = 3;
#if QT_CONFIG(imageformat_xpm)
-/* XPM */
-static const char * const dock_widget_close_xpm[] = {
- "11 13 7 1",
- " c None",
- ". c #D5CFCB",
- "+ c #8F8B88",
- "@ c #6C6A67",
- "# c #ABA6A3",
- "$ c #B5B0AC",
- "% c #A4A09D",
- " ",
- " +@@@@@@@+ ",
- "+# #+",
- "@ $@ @$ @",
- "@ @@@ @@@ @",
- "@ @@@@@ @",
- "@ @@@ @",
- "@ @@@@@ @",
- "@ @@@ @@@ @",
- "@ $@ @$ @",
- "+% #+",
- " +@@@@@@@+ ",
- " "};
-
-static const char * const dock_widget_restore_xpm[] = {
- "11 13 7 1",
- " c None",
- ". c #D5CFCB",
- "+ c #8F8B88",
- "@ c #6C6A67",
- "# c #ABA6A3",
- "$ c #B5B0AC",
- "% c #A4A09D",
- " ",
- " +@@@@@@@+ ",
- "+# #+",
- "@ #@@@# @",
- "@ @ @ @",
- "@ #@@@# @ @",
- "@ @ @ @ @",
- "@ @ @@@ @",
- "@ @ @ @",
- "@ #@@@# @",
- "+% #+",
- " +@@@@@@@+ ",
- " "};
-
-static const char * const workspace_minimize[] = {
- "11 13 7 1",
- " c None",
- ". c #D5CFCB",
- "+ c #8F8B88",
- "@ c #6C6A67",
- "# c #ABA6A3",
- "$ c #B5B0AC",
- "% c #A4A09D",
- " ",
- " +@@@@@@@+ ",
- "+# #+",
- "@ @",
- "@ @",
- "@ @",
- "@ @@@@@@@ @",
- "@ @@@@@@@ @",
- "@ @",
- "@ @",
- "+% #+",
- " +@@@@@@@+ ",
- " "};
-
-
static const char * const qt_titlebar_context_help[] = {
"10 10 3 1",
" c None",
@@ -216,6 +145,7 @@ static void qt_fusion_draw_arrow(Qt::ArrowType type, QPainter *painter, const QS
return;
const qreal dpi = QStyleHelper::dpi(option);
+ const qreal dpr = painter->device()->devicePixelRatio();
const int arrowWidth = int(QStyleHelper::dpiScaled(14, dpi));
const int arrowHeight = int(QStyleHelper::dpiScaled(8, dpi));
@@ -224,12 +154,12 @@ static void qt_fusion_draw_arrow(Qt::ArrowType type, QPainter *painter, const QS
const int size = qMin(arrowMax, rectMax);
QPixmap cachePixmap;
- QString cacheKey = QStyleHelper::uniqueName("fusion-arrow"_L1, option, rect.size())
- % HexString<uint>(type)
- % HexString<uint>(color.rgba());
+ const QString cacheKey = QStyleHelper::uniqueName("fusion-arrow"_L1
+ % HexString<uint>(type)
+ % HexString<uint>(color.rgba()),
+ option, rect.size(), dpr);
if (!QPixmapCache::find(cacheKey, &cachePixmap)) {
- cachePixmap = styleCachePixmap(rect.size());
- cachePixmap.fill(Qt::transparent);
+ cachePixmap = styleCachePixmap(rect.size(), dpr);
QPainter cachePainter(&cachePixmap);
QRectF arrowRect;
@@ -240,27 +170,26 @@ static void qt_fusion_draw_arrow(Qt::ArrowType type, QPainter *painter, const QS
arrowRect.moveTo((rect.width() - arrowRect.width()) / 2.0,
(rect.height() - arrowRect.height()) / 2.0);
- QPolygonF triangle;
- triangle.reserve(3);
+ std::array<QPointF, 3> triangle;
switch (type) {
case Qt::DownArrow:
- triangle << arrowRect.topLeft() << arrowRect.topRight() << QPointF(arrowRect.center().x(), arrowRect.bottom());
+ triangle = {arrowRect.topLeft(), arrowRect.topRight(), QPointF(arrowRect.center().x(), arrowRect.bottom())};
break;
case Qt::RightArrow:
- triangle << arrowRect.topLeft() << arrowRect.bottomLeft() << QPointF(arrowRect.right(), arrowRect.center().y());
+ triangle = {arrowRect.topLeft(), arrowRect.bottomLeft(), QPointF(arrowRect.right(), arrowRect.center().y())};
break;
case Qt::LeftArrow:
- triangle << arrowRect.topRight() << arrowRect.bottomRight() << QPointF(arrowRect.left(), arrowRect.center().y());
+ triangle = {arrowRect.topRight(), arrowRect.bottomRight(), QPointF(arrowRect.left(), arrowRect.center().y())};
break;
default:
- triangle << arrowRect.bottomLeft() << arrowRect.bottomRight() << QPointF(arrowRect.center().x(), arrowRect.top());
+ triangle = {arrowRect.bottomLeft(), arrowRect.bottomRight(), QPointF(arrowRect.center().x(), arrowRect.top())};
break;
}
cachePainter.setPen(Qt::NoPen);
cachePainter.setBrush(color);
cachePainter.setRenderHint(QPainter::Antialiasing);
- cachePainter.drawPolygon(triangle);
+ cachePainter.drawPolygon(triangle.data(), int(triangle.size()));
QPixmapCache::insert(cacheKey, cachePixmap);
}
@@ -375,37 +304,18 @@ QFusionStyle::~QFusionStyle()
}
/*!
- \fn void QFusionStyle::drawItemText(QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const
-
- Draws the given \a text in the specified \a rectangle using the
- provided \a painter and \a palette.
-
- Text is drawn using the painter's pen. If an explicit \a textRole
- is specified, then the text is drawn using the \a palette's color
- for the specified role. The \a enabled value indicates whether or
- not the item is enabled; when reimplementing, this value should
- influence how the item is drawn.
-
- The text is aligned and wrapped according to the specified \a
- alignment.
-
- \sa Qt::Alignment
+ \reimp
*/
void QFusionStyle::drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
bool enabled, const QString& text, QPalette::ColorRole textRole) const
{
+ Q_UNUSED(enabled);
if (text.isEmpty())
return;
QPen savedPen = painter->pen();
- if (textRole != QPalette::NoRole) {
+ if (textRole != QPalette::NoRole)
painter->setPen(QPen(pal.brush(textRole), savedPen.widthF()));
- }
- if (!enabled) {
- QPen pen = painter->pen();
- painter->setPen(pen);
- }
painter->drawText(rect, alignment, text);
painter->setPen(savedPen);
}
@@ -424,10 +334,10 @@ void QFusionStyle::drawPrimitive(PrimitiveElement elem,
QRect rect = option->rect;
int state = option->state;
- QColor outline = d->outline(option->palette);
- QColor highlightedOutline = d->highlightedOutline(option->palette);
+ const QColor outline = d->outline(option->palette);
+ const QColor highlightedOutline = d->highlightedOutline(option->palette);
- QColor tabFrameColor = d->tabFrameColor(option->palette);
+ const QColor tabFrameColor = d->tabFrameColor(option->palette);
switch (elem) {
@@ -436,16 +346,7 @@ void QFusionStyle::drawPrimitive(PrimitiveElement elem,
case PE_FrameGroupBox:
{
QPixmap pixmap(":/qt-project.org/styles/commonstyle/images/fusion_groupbox.png"_L1);
- int topMargin = 0;
- auto control = qobject_cast<const QGroupBox *>(widget);
- if (control && !control->isCheckable() && control->title().isEmpty()) {
- // Shrinking the topMargin if Not checkable AND title is empty
- topMargin = groupBoxTopMargin;
- } else {
- topMargin = qMax(pixelMetric(PM_ExclusiveIndicatorHeight), option->fontMetrics.height()) + groupBoxTopMargin;
- }
- QRect frame = option->rect.adjusted(0, topMargin, 0, 0);
- qDrawBorderPixmap(painter, frame, QMargins(6, 6, 6, 6), pixmap);
+ qDrawBorderPixmap(painter, option->rect, QMargins(6, 6, 6, 6), pixmap);
break;
}
#endif // QT_CONFIG(groupbox)
@@ -899,7 +800,7 @@ void QFusionStyle::drawPrimitive(PrimitiveElement elem,
if (isDefault)
buttonColor = mergedColors(buttonColor, highlightedOutline.lighter(130), 90);
- BEGIN_STYLE_PIXMAPCACHE(QStringLiteral("pushbutton-") + buttonColor.name(QColor::HexArgb))
+ BEGIN_STYLE_PIXMAPCACHE(u"pushbutton-" + buttonColor.name(QColor::HexArgb))
r = rect.adjusted(0, 1, -1, 0);
p->setRenderHint(QPainter::Antialiasing, true);
@@ -1224,7 +1125,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
Qt::ElideRight, titleRect.width());
proxy()->drawItemText(painter,
titleRect,
- Qt::AlignLeft | Qt::AlignVCenter, dwOpt->palette,
+ Qt::AlignLeft | Qt::AlignVCenter | Qt::TextHideMnemonic, dwOpt->palette,
dwOpt->state & State_Enabled, titleText,
QPalette::WindowText);
}
@@ -1236,22 +1137,22 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
// Draws the header in tables.
if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
const QStyleOptionHeaderV2 *headerV2 = qstyleoption_cast<const QStyleOptionHeaderV2 *>(option);
- QString pixmapName = QStyleHelper::uniqueName("headersection"_L1, option, option->rect.size());
- pixmapName += QString::number(- int(header->position));
- pixmapName += QString::number(- int(header->orientation));
- if (headerV2)
- pixmapName += QString::number(- int(headerV2->isSectionDragTarget));
-
+ const bool isSectionDragTarget = headerV2 ? headerV2->isSectionDragTarget : false;
+ const qreal dpr = painter->device()->devicePixelRatio();
+ const QString pixmapName = QStyleHelper::uniqueName("headersection-"_L1
+ % HexString(header->position)
+ % HexString(header->orientation)
+ % QLatin1Char(isSectionDragTarget ? '1' : '0'),
+ option, option->rect.size(), dpr);
QPixmap cache;
if (!QPixmapCache::find(pixmapName, &cache)) {
- cache = styleCachePixmap(rect.size());
- cache.fill(Qt::transparent);
+ cache = styleCachePixmap(rect.size(), dpr);
QRect pixmapRect(0, 0, rect.width(), rect.height());
QPainter cachePainter(&cache);
QColor buttonColor = d->buttonColor(option->palette);
QColor gradientStartColor = buttonColor.lighter(104);
QColor gradientStopColor = buttonColor.darker(102);
- if (headerV2 && headerV2->isSectionDragTarget) {
+ if (isSectionDragTarget) {
gradientStopColor = gradientStartColor.darker(130);
gradientStartColor = gradientStartColor.darker(130);
}
@@ -1318,36 +1219,39 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
case CE_ProgressBarContents:
painter->save();
painter->setRenderHint(QPainter::Antialiasing, true);
- painter->translate(0.5, 0.5);
if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- bool vertical = false;
- bool inverted = false;
- bool indeterminate = (bar->minimum == 0 && bar->maximum == 0);
- bool complete = bar->progress == bar->maximum;
-
- vertical = !(bar->state & QStyle::State_Horizontal);
- inverted = bar->invertedAppearance;
+ const auto indeterminate = (bar->minimum == 0 && bar->maximum == 0);
+ const auto complete = bar->progress == bar->maximum;
+ const auto vertical = !(bar->state & QStyle::State_Horizontal);
+ const auto inverted = bar->invertedAppearance;
+ const auto reverse = (bar->direction == Qt::RightToLeft) ^ inverted;
// If the orientation is vertical, we use a transform to rotate
- // the progress bar 90 degrees clockwise. This way we can use the
+ // the progress bar 90 degrees (counter)clockwise. This way we can use the
// same rendering code for both orientations.
if (vertical) {
rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
- QTransform m = QTransform::fromTranslate(rect.height()-1, -1.0);
- m.rotate(90.0);
+ QTransform m;
+ if (inverted) {
+ m.rotate(90);
+ m.translate(0, -rect.height());
+ } else {
+ m.rotate(-90);
+ m.translate(-rect.width(), 0);
+ }
+ painter->setTransform(m, true);
+ } else if (reverse) {
+ QTransform m = QTransform::fromScale(-1, 1);
+ m.translate(-rect.width(), 0);
painter->setTransform(m, true);
}
+ painter->translate(0.5, 0.5);
- int maxWidth = rect.width();
const auto progress = qMax(bar->progress, bar->minimum); // workaround for bug in QProgressBar
const auto totalSteps = qMax(Q_INT64_C(1), qint64(bar->maximum) - bar->minimum);
const auto progressSteps = qint64(progress) - bar->minimum;
- const auto progressBarWidth = progressSteps * maxWidth / totalSteps;
- int width = indeterminate ? maxWidth : progressBarWidth;
-
- bool reverse = (!vertical && (bar->direction == Qt::RightToLeft)) || vertical;
- if (inverted)
- reverse = !reverse;
+ const auto progressBarWidth = progressSteps * rect.width() / totalSteps;
+ int width = indeterminate ? rect.width() : progressBarWidth;
int step = 0;
QRect progressBar;
@@ -1356,28 +1260,10 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
if (qGray(outline.rgb()) > qGray(highlightedoutline.rgb()))
outline = highlightedoutline;
- if (!indeterminate) {
- QColor innerShadow(Qt::black);
- innerShadow.setAlpha(35);
- painter->setPen(innerShadow);
- if (!reverse) {
- progressBar.setRect(rect.left(), rect.top(), width - 1, rect.height() - 1);
- if (!complete) {
- painter->drawLine(progressBar.topRight() + QPoint(2, 1), progressBar.bottomRight() + QPoint(2, 0));
- painter->setPen(QPen(highlight.darker(140)));
- painter->drawLine(progressBar.topRight() + QPoint(1, 1), progressBar.bottomRight() + QPoint(1, 0));
- }
- } else {
- progressBar.setRect(rect.right() - width - 1, rect.top(), width + 2, rect.height() - 1);
- if (!complete) {
- painter->drawLine(progressBar.topLeft() + QPoint(-2, 1), progressBar.bottomLeft() + QPoint(-2, 0));
- painter->setPen(QPen(highlight.darker(140)));
- painter->drawLine(progressBar.topLeft() + QPoint(-1, 1), progressBar.bottomLeft() + QPoint(-1, 0));
- }
- }
- } else {
+ if (!indeterminate)
+ progressBar.setRect(rect.left(), rect.top(), width - 1, rect.height() - 1);
+ else
progressBar.setRect(rect.left(), rect.top(), rect.width() - 1, rect.height() - 1);
- }
if (indeterminate || bar->progress > bar->minimum) {
@@ -1392,10 +1278,13 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
painter->setBrush(gradient);
painter->save();
+ // 0.5 - half the width of a cosmetic pen (for vertical line below)
if (!complete && !indeterminate)
- painter->setClipRect(progressBar.adjusted(-1, -1, -1, 1));
- QRect fillRect = progressBar.adjusted( !indeterminate && !complete && reverse ? -2 : 0, 0,
- indeterminate || complete || reverse ? 0 : 2, 0);
+ painter->setClipRect(QRectF(progressBar).adjusted(-1, -1, 0.5, 1));
+
+ QRect fillRect = progressBar;
+ if (!indeterminate && !complete)
+ fillRect.setWidth(std::min(fillRect.width() + 2, rect.width() - 1)); // avoid round borders at the right end
painter->drawRoundedRect(fillRect, 2, 2);
painter->restore();
@@ -1422,43 +1311,63 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
x + rect.height() + step, progressBar.top() - 2);
}
}
+ if (!indeterminate && !complete) {
+ QColor innerShadow(Qt::black);
+ innerShadow.setAlpha(35);
+ painter->setPen(innerShadow);
+ painter->drawLine(progressBar.topRight() + QPoint(2, 1), progressBar.bottomRight() + QPoint(2, 0));
+ painter->setPen(QPen(highlight.darker(140)));
+ painter->drawLine(progressBar.topRight() + QPoint(1, 1), progressBar.bottomRight() + QPoint(1, 0));
+ }
}
painter->restore();
break;
case CE_ProgressBarLabel:
if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- QRect leftRect;
QRect rect = bar->rect;
+ QRect leftRect = rect;
+ QRect rightRect = rect;
QColor textColor = option->palette.text().color();
QColor alternateTextColor = d->highlightedText(option->palette);
painter->save();
- bool vertical = false, inverted = false;
- vertical = !(bar->state & QStyle::State_Horizontal);
- inverted = bar->invertedAppearance;
- if (vertical)
- rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
+ const auto vertical = !(bar->state & QStyle::State_Horizontal);
+ const auto inverted = bar->invertedAppearance;
+ const auto reverse = (bar->direction == Qt::RightToLeft) ^ inverted;
const auto totalSteps = qMax(Q_INT64_C(1), qint64(bar->maximum) - bar->minimum);
const auto progressSteps = qint64(bar->progress) - bar->minimum;
- const auto progressIndicatorPos = progressSteps * rect.width() / totalSteps;
- if (progressIndicatorPos >= 0 && progressIndicatorPos <= rect.width())
- leftRect = QRect(rect.left(), rect.top(), progressIndicatorPos, rect.height());
- if (vertical)
- leftRect.translate(rect.width() - progressIndicatorPos, 0);
-
- bool flip = (!vertical && (((bar->direction == Qt::RightToLeft) && !inverted) ||
- ((bar->direction == Qt::LeftToRight) && inverted)));
-
- QRegion rightRect = rect;
- rightRect = rightRect.subtracted(leftRect);
- painter->setClipRegion(rightRect);
- painter->setPen(flip ? alternateTextColor : textColor);
- painter->drawText(rect, bar->text, QTextOption(Qt::AlignAbsolute | Qt::AlignHCenter | Qt::AlignVCenter));
- if (!leftRect.isNull()) {
- painter->setPen(flip ? textColor : alternateTextColor);
- painter->setClipRect(leftRect);
- painter->drawText(rect, bar->text, QTextOption(Qt::AlignAbsolute | Qt::AlignHCenter | Qt::AlignVCenter));
+ const auto progressIndicatorPos = progressSteps * (vertical ? rect.height() : rect.width()) / totalSteps;
+
+ if (vertical) {
+ if (progressIndicatorPos >= 0 && progressIndicatorPos <= rect.height()) {
+ if (inverted) {
+ leftRect.setHeight(progressIndicatorPos);
+ rightRect.setY(progressIndicatorPos);
+ } else {
+ leftRect.setHeight(rect.height() - progressIndicatorPos);
+ rightRect.setY(rect.height() - progressIndicatorPos);
+ }
+ }
+ } else {
+ if (progressIndicatorPos >= 0 && progressIndicatorPos <= rect.width()) {
+ if (reverse) {
+ leftRect.setWidth(rect.width() - progressIndicatorPos);
+ rightRect.setX(rect.width() - progressIndicatorPos);
+ } else {
+ leftRect.setWidth(progressIndicatorPos);
+ rightRect.setX(progressIndicatorPos);
+ }
+ }
}
+
+ const auto firstIsAlternateColor = (vertical && !inverted) || (!vertical && reverse);
+ painter->setClipRect(rightRect);
+ painter->setPen(firstIsAlternateColor ? alternateTextColor : textColor);
+ painter->drawText(rect, bar->text, QTextOption(Qt::AlignAbsolute | Qt::AlignHCenter | Qt::AlignVCenter));
+ painter->setPen(firstIsAlternateColor ? textColor : alternateTextColor);
+ painter->setClipRect(leftRect);
+ painter->drawText(rect, bar->text, QTextOption(Qt::AlignAbsolute | Qt::AlignHCenter | Qt::AlignVCenter));
+
painter->restore();
}
break;
@@ -1919,7 +1828,23 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
frame.lineWidth = groupBox->lineWidth;
frame.midLineWidth = groupBox->midLineWidth;
frame.rect = proxy()->subControlRect(CC_GroupBox, option, SC_GroupBoxFrame, widget);
+ painter->save();
+ QRegion region(groupBox->rect);
+ if (!groupBox->text.isEmpty()) {
+ bool ltr = groupBox->direction == Qt::LeftToRight;
+ QRect finalRect;
+ if (groupBox->subControls & QStyle::SC_GroupBoxCheckBox) {
+ finalRect = checkBoxRect.united(textRect);
+ finalRect.adjust(ltr ? -4 : -2, 0, ltr ? 2 : 4, 0);
+ } else {
+ finalRect = textRect;
+ finalRect.adjust(-2, 0, 2, 0);
+ }
+ region -= finalRect.adjusted(0, 0, 0, 3 - textRect.height() / 2);
+ }
+ painter->setClipRegion(region);
proxy()->drawPrimitive(PE_FrameGroupBox, &frame, painter, widget);
+ painter->restore();
}
// Draw title
@@ -1954,12 +1879,12 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
#if QT_CONFIG(spinbox)
case CC_SpinBox:
if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
+ const qreal dpr = painter->device()->devicePixelRatio();
QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName("spinbox"_L1, spinBox, spinBox->rect.size());
+ QString pixmapName = QStyleHelper::uniqueName("spinbox"_L1, spinBox, spinBox->rect.size(), dpr);
if (!QPixmapCache::find(pixmapName, &cache)) {
- cache = styleCachePixmap(spinBox->rect.size());
- cache.fill(Qt::transparent);
+ cache = styleCachePixmap(spinBox->rect.size(), dpr);
QRect pixmapRect(0, 0, spinBox->rect.width(), spinBox->rect.height());
QRect rect = pixmapRect;
@@ -2044,9 +1969,9 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
// and a tiny rect painted in the corner.
cachePainter.setPen(outline);
if (spinBox->direction == Qt::RightToLeft)
- cachePainter.drawLine(upRect.right(), upRect.top() - 1, upRect.right(), downRect.bottom() + 1);
+ cachePainter.drawLine(QLineF(upRect.right(), upRect.top() - 0.5, upRect.right(), downRect.bottom() + 1.5));
else
- cachePainter.drawLine(upRect.left(), upRect.top() - 1, upRect.left(), downRect.bottom() + 1);
+ cachePainter.drawLine(QLineF(upRect.left(), upRect.top() - 0.5, upRect.left(), downRect.bottom() + 1.5));
}
if (upIsActive && sunken) {
@@ -2521,7 +2446,6 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
subtleEdge.setAlpha(40);
painter->setPen(subtleEdge);
painter->setBrush(Qt::NoBrush);
- painter->setClipRect(scrollBarGroove.adjusted(1, 0, -1, -3));
painter->drawRect(scrollBarGroove.adjusted(1, 0, -1, -1));
painter->restore();
}
@@ -2561,10 +2485,12 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
painter->setBrush(midColor2);
else if (option->state & State_MouseOver && scrollBar->activeSubControls & SC_ScrollBarSlider)
painter->setBrush(highlightedGradient);
- else
+ else if (!isDarkBg)
painter->setBrush(gradient);
+ else
+ painter->setBrush(midColor2);
- painter->drawRect(pixmapRect.adjusted(horizontal ? -1 : 0, horizontal ? 0 : -1, horizontal ? 0 : 1, horizontal ? 1 : 0));
+ painter->drawRect(pixmapRect.adjusted(horizontal ? -1 : 0, horizontal ? 0 : -1, horizontal ? 0 : -1, horizontal ? -1 : 0));
painter->setPen(d->innerContrastLine());
painter->drawRect(scrollBarSlider.adjusted(horizontal ? 0 : 1, horizontal ? 1 : 0, -1, -1));
@@ -2594,16 +2520,9 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
painter->drawRect(scrollBarSubLine.adjusted(horizontal ? 0 : 1, horizontal ? 1 : 0, 0, 0));
painter->setPen(QPen(alphaOutline));
if (option->state & State_Horizontal) {
- if (option->direction == Qt::RightToLeft) {
- pixmapRect.setLeft(scrollBarSubLine.left());
- painter->drawLine(pixmapRect.topLeft(), pixmapRect.bottomLeft());
- } else {
- pixmapRect.setRight(scrollBarSubLine.right());
- painter->drawLine(pixmapRect.topRight(), pixmapRect.bottomRight());
- }
+ painter->drawRect(scrollBarSubLine.adjusted(horizontal ? 0 : 1, 0, horizontal ? 1 : 0, horizontal ? -1 : 0));
} else {
- pixmapRect.setBottom(scrollBarSubLine.bottom());
- painter->drawLine(pixmapRect.bottomLeft(), pixmapRect.bottomRight());
+ painter->drawRect(scrollBarSubLine.adjusted(0, 0, horizontal ? 0 : -1, 0));
}
QRect upRect = scrollBarSubLine.adjusted(horizontal ? 0 : 1, horizontal ? 1 : 0, horizontal ? -2 : -1, horizontal ? -1 : -2);
@@ -2631,16 +2550,9 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
painter->drawRect(scrollBarAddLine.adjusted(horizontal ? 0 : 1, horizontal ? 1 : 0, 0, 0));
painter->setPen(QPen(alphaOutline, 1));
if (option->state & State_Horizontal) {
- if (option->direction == Qt::LeftToRight) {
- pixmapRect.setLeft(scrollBarAddLine.left());
- painter->drawLine(pixmapRect.topLeft(), pixmapRect.bottomLeft());
- } else {
- pixmapRect.setRight(scrollBarAddLine.right());
- painter->drawLine(pixmapRect.topRight(), pixmapRect.bottomRight());
- }
+ painter->drawRect(scrollBarAddLine.adjusted(horizontal ? -1 : 0, 0, horizontal ? -1 : 0, horizontal ? -1 : 0));
} else {
- pixmapRect.setTop(scrollBarAddLine.top());
- painter->drawLine(pixmapRect.topLeft(), pixmapRect.topRight());
+ painter->drawRect(scrollBarAddLine.adjusted(0, horizontal ? 0 : -1, horizontal ? 0 : -1, horizontal ? 0 : -1));
}
QRect downRect = scrollBarAddLine.adjusted(1, 1, -1, -1);
@@ -2656,7 +2568,7 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
}
painter->restore();
- break;;
+ break;
#endif // QT_CONFIG(slider)
case CC_ComboBox:
painter->save();
@@ -2664,20 +2576,16 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
bool hasFocus = option->state & State_HasFocus && option->state & State_KeyboardFocusChange;
bool sunken = comboBox->state & State_On; // play dead, if combobox has no items
bool isEnabled = (comboBox->state & State_Enabled);
+ const qreal dpr = painter->device()->devicePixelRatio();
QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName("combobox"_L1, option, comboBox->rect.size());
- if (sunken)
- pixmapName += "-sunken"_L1;
- if (comboBox->editable)
- pixmapName += "-editable"_L1;
- if (isEnabled)
- pixmapName += "-enabled"_L1;
- if (!comboBox->frame)
- pixmapName += "-frameless"_L1;
-
+ const QString pixmapName = QStyleHelper::uniqueName("combobox"_L1
+ % QLatin1StringView(sunken ? "-sunken" : "")
+ % QLatin1StringView(comboBox->editable ? "-editable" : "")
+ % QLatin1StringView(isEnabled ? "-enabled" : "")
+ % QLatin1StringView(!comboBox->frame ? "-frameless" : ""),
+ option, comboBox->rect.size(), dpr);
if (!QPixmapCache::find(pixmapName, &cache)) {
- cache = styleCachePixmap(comboBox->rect.size());
- cache.fill(Qt::transparent);
+ cache = styleCachePixmap(comboBox->rect.size(), dpr);
QPainter cachePainter(&cache);
QRect pixmapRect(0, 0, comboBox->rect.width(), comboBox->rect.height());
QStyleOptionComboBox comboBoxCopy = *comboBox;
@@ -2765,6 +2673,7 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
#if QT_CONFIG(slider)
case CC_Slider:
if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
+ const qreal dpr = painter->device()->devicePixelRatio();
QRect groove = proxy()->subControlRect(CC_Slider, option, SC_SliderGroove, widget);
QRect handle = proxy()->subControlRect(CC_Slider, option, SC_SliderHandle, widget);
@@ -2786,13 +2695,13 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
grooveColor.setHsv(buttonColor.hue(),
qMin(255, (int)(buttonColor.saturation())),
qMin(255, (int)(buttonColor.value()*0.9)));
- QString groovePixmapName = QStyleHelper::uniqueName("slider_groove"_L1, option, groove.size());
+ QString groovePixmapName = QStyleHelper::uniqueName("slider_groove"_L1, option,
+ groove.size(), dpr);
QRect pixmapRect(0, 0, groove.width(), groove.height());
// draw background groove
if (!QPixmapCache::find(groovePixmapName, &cache)) {
- cache = styleCachePixmap(pixmapRect.size());
- cache.fill(Qt::transparent);
+ cache = styleCachePixmap(pixmapRect.size(), dpr);
QPainter groovePainter(&cache);
groovePainter.setRenderHint(QPainter::Antialiasing, true);
groovePainter.translate(0.5, 0.5);
@@ -2817,10 +2726,10 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
// draw blue groove highlight
QRect clipRect;
- groovePixmapName += "_blue"_L1;
+ if (!groovePixmapName.isEmpty())
+ groovePixmapName += "_blue"_L1;
if (!QPixmapCache::find(groovePixmapName, &cache)) {
- cache = styleCachePixmap(pixmapRect.size());
- cache.fill(Qt::transparent);
+ cache = styleCachePixmap(pixmapRect.size(), dpr);
QPainter groovePainter(&cache);
QLinearGradient gradient;
if (horizontal) {
@@ -2833,13 +2742,13 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
}
QColor highlight = d->highlight(option->palette);
QColor highlightedoutline = highlight.darker(140);
- if (qGray(outline.rgb()) > qGray(highlightedoutline.rgb()))
- outline = highlightedoutline;
-
+ QColor grooveOutline = outline;
+ if (qGray(grooveOutline.rgb()) > qGray(highlightedoutline.rgb()))
+ grooveOutline = highlightedoutline;
groovePainter.setRenderHint(QPainter::Antialiasing, true);
groovePainter.translate(0.5, 0.5);
- groovePainter.setPen(QPen(outline));
+ groovePainter.setPen(QPen(grooveOutline));
gradient.setColorAt(0, activeHighlight);
gradient.setColorAt(1, activeHighlight.lighter(130));
groovePainter.setBrush(gradient);
@@ -2854,10 +2763,11 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
if (slider->upsideDown)
clipRect = QRect(handle.right(), groove.top(), groove.right() - handle.right(), groove.height());
else
- clipRect = QRect(groove.left(), groove.top(), handle.left(), groove.height());
+ clipRect = QRect(groove.left(), groove.top(),
+ handle.left() - slider->rect.left(), groove.height());
} else {
if (slider->upsideDown)
- clipRect = QRect(groove.left(), handle.bottom(), groove.width(), groove.height() - handle.bottom());
+ clipRect = QRect(groove.left(), handle.bottom(), groove.width(), groove.height() - (handle.bottom() - slider->rect.top()));
else
clipRect = QRect(groove.left(), groove.top(), groove.width(), handle.top() - groove.top());
}
@@ -2868,6 +2778,8 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
}
if (option->subControls & SC_SliderTickmarks) {
+ painter->save();
+ painter->translate(slider->rect.x(), slider->rect.y());
painter->setPen(outline);
int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
int available = proxy()->pixelMetric(PM_SliderSpaceAvailable, slider, widget);
@@ -2885,6 +2797,7 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
int v = slider->minimum;
int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
+ QVector<QLine> lines;
while (v <= slider->maximum + 1) {
if (v == slider->maximum + 1 && interval == 1)
break;
@@ -2898,21 +2811,21 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
if (horizontal) {
if (ticksAbove) {
- painter->drawLine(pos, slider->rect.top() + extra,
- pos, slider->rect.top() + tickSize);
+ lines += QLine(pos, slider->rect.top() + extra,
+ pos, slider->rect.top() + tickSize);
}
if (ticksBelow) {
- painter->drawLine(pos, slider->rect.bottom() - extra,
- pos, slider->rect.bottom() - tickSize);
+ lines += QLine(pos, slider->rect.bottom() - extra,
+ pos, slider->rect.bottom() - tickSize);
}
} else {
if (ticksAbove) {
- painter->drawLine(slider->rect.left() + extra, pos,
- slider->rect.left() + tickSize, pos);
+ lines += QLine(slider->rect.left() + extra, pos,
+ slider->rect.left() + tickSize, pos);
}
if (ticksBelow) {
- painter->drawLine(slider->rect.right() - extra, pos,
- slider->rect.right() - tickSize, pos);
+ lines += QLine(slider->rect.right() - extra, pos,
+ slider->rect.right() - tickSize, pos);
}
}
// in the case where maximum is max int
@@ -2921,13 +2834,15 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
break;
v = nextInterval;
}
+ painter->drawLines(lines);
+ painter->restore();
}
// draw handle
if ((option->subControls & SC_SliderHandle) ) {
- QString handlePixmapName = QStyleHelper::uniqueName("slider_handle"_L1, option, handle.size());
+ QString handlePixmapName = QStyleHelper::uniqueName("slider_handle"_L1, option,
+ handle.size(), dpr);
if (!QPixmapCache::find(handlePixmapName, &cache)) {
- cache = styleCachePixmap(handle.size());
- cache.fill(Qt::transparent);
+ cache = styleCachePixmap(handle.size(), dpr);
QRect pixmapRect(0, 0, handle.width(), handle.height());
QPainter handlePainter(&cache);
QRect gradRect = pixmapRect.adjusted(2, 2, -2, -2);
@@ -2941,7 +2856,7 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
handlePainter.setPen(Qt::NoPen);
handlePainter.setBrush(QColor(0, 0, 0, 40));
- handlePainter.drawRect(r.adjusted(-1, 2, 1, -2));
+ handlePainter.drawRect(horizontal ? r.adjusted(-1, 2, 1, -2) : r.adjusted(2, -1, -2, 1));
handlePainter.setPen(QPen(d->outline(option->palette)));
if (option->state & State_HasFocus && option->state & State_KeyboardFocusChange)
@@ -3011,7 +2926,6 @@ int QFusionStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, co
case PM_ListViewIconSize:
val = 24;
break;
- case PM_DialogButtonsSeparator:
case PM_ScrollBarSliderMin:
val = 26;
break;
@@ -3126,7 +3040,7 @@ QSize QFusionStyle::sizeFromContents(ContentsType type, const QStyleOption *opti
break;
case CT_GroupBox:
if (option) {
- int topMargin = qMax(pixelMetric(PM_ExclusiveIndicatorHeight), option->fontMetrics.height()) + groupBoxTopMargin;
+ int topMargin = qMax(pixelMetric(PM_IndicatorHeight, option, widget), option->fontMetrics.height()) + groupBoxTopMargin;
newSize += QSize(10, topMargin); // Add some space below the groupbox
}
break;
@@ -3308,23 +3222,28 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
switch (subControl) {
case SC_SliderHandle: {
+ const bool bothTicks = (slider->tickPosition & QSlider::TicksBothSides) == QSlider::TicksBothSides;
if (slider->orientation == Qt::Horizontal) {
- rect.setHeight(proxy()->pixelMetric(PM_SliderThickness, option));
- rect.setWidth(proxy()->pixelMetric(PM_SliderLength, option));
+ rect.setHeight(proxy()->pixelMetric(PM_SliderThickness, option, widget));
+ rect.setWidth(proxy()->pixelMetric(PM_SliderLength, option, widget));
int centerY = slider->rect.center().y() - rect.height() / 2;
- if (slider->tickPosition & QSlider::TicksAbove)
- centerY += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- centerY -= tickSize;
+ if (!bothTicks) {
+ if (slider->tickPosition & QSlider::TicksAbove)
+ centerY += tickSize;
+ if (slider->tickPosition & QSlider::TicksBelow)
+ centerY -= tickSize - 1;
+ }
rect.moveTop(centerY);
} else {
- rect.setWidth(proxy()->pixelMetric(PM_SliderThickness, option));
- rect.setHeight(proxy()->pixelMetric(PM_SliderLength, option));
+ rect.setWidth(proxy()->pixelMetric(PM_SliderThickness, option, widget));
+ rect.setHeight(proxy()->pixelMetric(PM_SliderLength, option, widget));
int centerX = slider->rect.center().x() - rect.width() / 2;
- if (slider->tickPosition & QSlider::TicksAbove)
- centerX += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- centerX -= tickSize;
+ if (!bothTicks) {
+ if (slider->tickPosition & QSlider::TicksAbove)
+ centerX += tickSize;
+ if (slider->tickPosition & QSlider::TicksBelow)
+ centerX -= tickSize - 1;
+ }
rect.moveLeft(centerX);
}
}
@@ -3332,18 +3251,23 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
case SC_SliderGroove: {
QPoint grooveCenter = slider->rect.center();
const int grooveThickness = QStyleHelper::dpiScaled(7, option);
+ const bool bothTicks = (slider->tickPosition & QSlider::TicksBothSides) == QSlider::TicksBothSides;
if (slider->orientation == Qt::Horizontal) {
rect.setHeight(grooveThickness);
- if (slider->tickPosition & QSlider::TicksAbove)
- grooveCenter.ry() += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- grooveCenter.ry() -= tickSize;
+ if (!bothTicks) {
+ if (slider->tickPosition & QSlider::TicksAbove)
+ grooveCenter.ry() += tickSize;
+ if (slider->tickPosition & QSlider::TicksBelow)
+ grooveCenter.ry() -= tickSize - 1;
+ }
} else {
rect.setWidth(grooveThickness);
- if (slider->tickPosition & QSlider::TicksAbove)
- grooveCenter.rx() += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- grooveCenter.rx() -= tickSize;
+ if (!bothTicks) {
+ if (slider->tickPosition & QSlider::TicksAbove)
+ grooveCenter.rx() += tickSize;
+ if (slider->tickPosition & QSlider::TicksBelow)
+ grooveCenter.rx() -= tickSize - 1;
+ }
}
rect.moveCenter(grooveCenter);
break;
@@ -3386,6 +3310,7 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
break;
case SC_SpinBoxFrame:
rect = spinbox->rect;
+ break;
default:
break;
}
@@ -3395,18 +3320,19 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
#endif // QT_CONFIG(spinbox)
case CC_GroupBox:
if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- rect = option->rect;
+ const int groupBoxTextAlignment = groupBox->textAlignment;
+ const bool hasVerticalAlignment = (groupBoxTextAlignment & Qt::AlignVertical_Mask) == Qt::AlignVCenter;
+ const int fontMetricsHeight = groupBox->text.isEmpty() ? 0 : groupBox->fontMetrics.height();
+
if (subControl == SC_GroupBoxFrame)
- return rect.adjusted(0, 0, 0, 0);
+ return rect;
else if (subControl == SC_GroupBoxContents) {
QRect frameRect = option->rect.adjusted(0, 0, 0, -groupBoxBottomMargin);
int margin = 3;
int leftMarginExtension = 0;
- const int exclusiveIndicatorHeight = option->subControls.testFlag(SC_GroupBoxCheckBox) ?
- pixelMetric(PM_ExclusiveIndicatorHeight) : 0;
- const int fontMetricsHeight = groupBox->text.isEmpty() ? 0 :
- groupBox->fontMetrics.height();
- const int topMargin = qMax(exclusiveIndicatorHeight, fontMetricsHeight) +
+ const int indicatorHeight = option->subControls.testFlag(SC_GroupBoxCheckBox) ?
+ pixelMetric(PM_IndicatorHeight, option, widget) : 0;
+ const int topMargin = qMax(indicatorHeight, fontMetricsHeight) +
groupBoxTopMargin;
return frameRect.adjusted(leftMarginExtension + margin, margin + topMargin, -margin, -margin - groupBoxBottomMargin);
}
@@ -3421,12 +3347,17 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
rect = QRect();
if (option->rect.width() > width) {
- switch (groupBox->textAlignment & Qt::AlignHorizontal_Mask) {
+ switch (groupBoxTextAlignment & Qt::AlignHorizontal_Mask) {
case Qt::AlignHCenter:
rect.moveLeft((option->rect.width() - width) / 2);
break;
case Qt::AlignRight:
- rect.moveLeft(option->rect.width() - width);
+ rect.moveLeft(option->rect.width() - width
+ - (hasVerticalAlignment ? proxy()->pixelMetric(PM_LayoutRightMargin, groupBox, widget) : 0));
+ break;
+ case Qt::AlignLeft:
+ if (hasVerticalAlignment)
+ rect.moveLeft(proxy()->pixelMetric(PM_LayoutLeftMargin, option, widget));
break;
}
}
@@ -3630,7 +3561,6 @@ int QFusionStyle::styleHint(StyleHint hint, const QStyleOption *option, const QW
case SH_MenuBar_MouseTracking:
case SH_Menu_MouseTracking:
case SH_Menu_SupportsSections:
- case SH_SupportsDarkAppearance:
return 1;
#if defined(QT_PLATFORM_UIKIT)
@@ -3679,6 +3609,17 @@ int QFusionStyle::styleHint(StyleHint hint, const QStyleOption *option, const QW
mask->region -= QRect(option->rect.right() , option->rect.top() + 3, 1, 2);
return 1;
}
+ break;
+ case SH_GroupBox_TextLabelVerticalAlignment: {
+ if (const auto *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
+ if (groupBox) {
+ const auto vAlign = groupBox->textAlignment & Qt::AlignVertical_Mask;
+ // default fusion style is AlignTop
+ return vAlign == 0 ? Qt::AlignTop : vAlign;
+ }
+ }
+ break;
+ }
default:
break;
}
@@ -3721,22 +3662,47 @@ QRect QFusionStyle::subElementRect(SubElement sr, const QStyleOption *opt, const
/*!
\reimp
*/
-QIcon QFusionStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget) const
+QIcon QFusionStyle::iconFromTheme(StandardPixmap standardIcon) const
{
-#if QT_CONFIG(imageformat_xpm)
+ QIcon icon;
+#if QT_CONFIG(imageformat_png)
+ auto addIconFiles = [](QStringView prefix, QIcon &icon)
+ {
+ const auto fullPrefix = QStringLiteral(":/qt-project.org/styles/fusionstyle/images/") + prefix;
+ static constexpr auto dockTitleIconSizes = {10, 16, 20, 32, 48, 64};
+ for (int size : dockTitleIconSizes)
+ icon.addFile(fullPrefix + QString::number(size) + QStringLiteral(".png"),
+ QSize(size, size));
+ };
switch (standardIcon) {
case SP_TitleBarNormalButton:
- return QIcon(QPixmap(dock_widget_restore_xpm));
+ addIconFiles(u"fusion_normalizedockup-", icon);
+ break;
case SP_TitleBarMinButton:
- return QIcon(QPixmap(workspace_minimize));
+ addIconFiles(u"fusion_titlebar-min-", icon);
+ break;
case SP_TitleBarCloseButton:
case SP_DockWidgetCloseButton:
- return QIcon(QPixmap(dock_widget_close_xpm));
+ addIconFiles(u"fusion_closedock-", icon);
+ break;
default:
break;
}
-#endif // imageformat_xpm
+#else // imageformat_png
+ Q_UNUSED(standardIcon);
+#endif // imageformat_png
+ return icon;
+}
+
+/*!
+ \reimp
+*/
+QIcon QFusionStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option,
+ const QWidget *widget) const
+{
+ const auto icon = iconFromTheme(standardIcon);
+ if (!icon.availableSizes().isEmpty())
+ return icon;
return QCommonStyle::standardIcon(standardIcon, option, widget);
}
@@ -3746,21 +3712,13 @@ QIcon QFusionStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption
QPixmap QFusionStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
const QWidget *widget) const
{
-#ifndef QT_NO_IMAGEFORMAT_XPM
- switch (standardPixmap) {
- case SP_TitleBarNormalButton:
- return QPixmap(dock_widget_restore_xpm);
- case SP_TitleBarMinButton:
- return QPixmap(workspace_minimize);
- case SP_TitleBarCloseButton:
- case SP_DockWidgetCloseButton:
- return QPixmap(dock_widget_close_xpm);
-
- default:
- break;
- }
-#endif //QT_NO_IMAGEFORMAT_XPM
-
+ auto getDevicePixelRatio = [](const QWidget *widget)
+ {
+ return widget ? widget->devicePixelRatio() : qApp->devicePixelRatio();
+ };
+ const auto icon = iconFromTheme(standardPixmap);
+ if (!icon.availableSizes().isEmpty())
+ return icon.pixmap(QSize(16, 16), getDevicePixelRatio(widget));
return QCommonStyle::standardPixmap(standardPixmap, opt, widget);
}
diff --git a/src/widgets/styles/qfusionstyle_p.h b/src/widgets/styles/qfusionstyle_p.h
index d2a2e16b12..7dfeb34d7c 100644
--- a/src/widgets/styles/qfusionstyle_p.h
+++ b/src/widgets/styles/qfusionstyle_p.h
@@ -54,6 +54,7 @@ public:
int styleHint(StyleHint hint, const QStyleOption *option = nullptr, const QWidget *widget = nullptr,
QStyleHintReturn *returnData = nullptr) const override;
QRect itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const override;
+ QIcon iconFromTheme(StandardPixmap standardIcon) const;
QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = nullptr,
const QWidget *widget = nullptr) const override;
QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
diff --git a/src/widgets/styles/qproxystyle.cpp b/src/widgets/styles/qproxystyle.cpp
index 6cca56f5b5..a85c40a329 100644
--- a/src/widgets/styles/qproxystyle.cpp
+++ b/src/widgets/styles/qproxystyle.cpp
@@ -348,7 +348,18 @@ void QProxyStyle::unpolish(QApplication *app)
*/
bool QProxyStyle::event(QEvent *e)
{
- // ### Qt 7: remove this override
+ Q_D (QProxyStyle);
+
+ switch (e->type()) {
+ // The Mac style relies on these events in order to set the focus frame
+ case QEvent::FocusIn:
+ case QEvent::FocusOut:
+ d->ensureBaseStyle();
+ return QApplication::sendEvent(d->baseStyle, e);
+ default:
+ break;
+ }
+
return QCommonStyle::event(e);
}
diff --git a/src/widgets/styles/qproxystyle_p.h b/src/widgets/styles/qproxystyle_p.h
index 1b9466bb17..6b686023a5 100644
--- a/src/widgets/styles/qproxystyle_p.h
+++ b/src/widgets/styles/qproxystyle_p.h
@@ -20,6 +20,8 @@
#include "qcommonstyle_p.h"
#include "qproxystyle.h"
+#include <QtCore/qpointer.h>
+
#ifndef QT_NO_STYLE_PROXY
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/styles/qstyle.cpp b/src/widgets/styles/qstyle.cpp
index e5025a05ea..60b2f51e95 100644
--- a/src/widgets/styles/qstyle.cpp
+++ b/src/widgets/styles/qstyle.cpp
@@ -249,9 +249,6 @@ static int unpackControlTypes(QSizePolicy::ControlTypes controls, QSizePolicy::C
widget is a QSpinBox just because the enum value is called
PE_IndicatorSpinUp or PE_IndicatorSpinDown.
- The documentation for the \l{widgets/styles}{Styles} example
- covers this topic in more detail.
-
\warning Qt style sheets are currently not supported for custom QStyle
subclasses. We plan to address this in some future release.
@@ -352,7 +349,7 @@ static int unpackControlTypes(QSizePolicy::ControlTypes controls, QSizePolicy::C
The drawing of item view headers is also done by the style, giving
control over size of header items and row and column sizes.
- \sa QStyleOption, QStylePainter, {Styles Example},
+ \sa QStyleOption, QStylePainter,
{Styles and Style Aware Widgets}, QStyledItemDelegate, {Styling}
*/
@@ -1497,8 +1494,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
Returns the value of the given pixel \a metric.
The specified \a option and \a widget can be used for calculating
- the metric. In general, the \a widget argument is not used. The \a
- option can be cast to the appropriate type using the
+ the metric. The \a option can be cast to the appropriate type using the
qstyleoption_cast() function. Note that the \a option may be zero
even for PixelMetrics that can make use of it. See the table below
for the appropriate \a option casts:
@@ -1687,7 +1683,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
the line edit receives focus, as done on Windows.
\value SH_Menu_KeyboardSearch Typing causes a menu to be search
- for relevant items, otherwise only mnemnonic is considered.
+ for relevant items, otherwise only mnemonic is considered.
\value SH_Menu_AllowActiveAndDisabled Allows disabled menu
items to be active.
@@ -1987,13 +1983,6 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
not when the header is hidden. Defaults to false.
This enum value has been introduced in Qt 6.3.
- \value SH_SupportsDarkAppearance
- Determines whether the style is able to render a UI correctly with
- a dark palette. Defaults to false. Style implementors should return true
- if they have tested the style with a palette where the background colors
- are darker than the foreground colors.
- This enum value has been introduced in Qt 6.5.
-
\sa styleHint()
*/
diff --git a/src/widgets/styles/qstyle.h b/src/widgets/styles/qstyle.h
index f47c44d7bd..198aea9557 100644
--- a/src/widgets/styles/qstyle.h
+++ b/src/widgets/styles/qstyle.h
@@ -464,11 +464,13 @@ public:
PM_ExclusiveIndicatorWidth,
PM_ExclusiveIndicatorHeight,
- PM_DialogButtonsSeparator,
- PM_DialogButtonsButtonWidth,
- PM_DialogButtonsButtonHeight,
+#if QT_DEPRECATED_SINCE(6, 8)
+ PM_DialogButtonsSeparator Q_DECL_ENUMERATOR_DEPRECATED_X("Not used and no effect since Qt 4"),
+ PM_DialogButtonsButtonWidth Q_DECL_ENUMERATOR_DEPRECATED_X("Not used and no effect since Qt 4"),
+ PM_DialogButtonsButtonHeight Q_DECL_ENUMERATOR_DEPRECATED_X("Not used and no effect since Qt 4"),
+#endif
- PM_MdiSubWindowFrameWidth,
+ PM_MdiSubWindowFrameWidth = 44,
PM_MdiSubWindowMinimizedWidth,
PM_HeaderMargin,
@@ -702,7 +704,6 @@ public:
SH_TabBar_AllowWheelScrolling,
SH_Table_AlwaysDrawLeftTopGridLines,
SH_SpinBox_SelectOnStep,
- SH_SupportsDarkAppearance,
// Add new style hint values here
SH_CustomBase = 0xf0000000
diff --git a/src/widgets/styles/qstyle_p.h b/src/widgets/styles/qstyle_p.h
index 5c1fd17130..59e87810c5 100644
--- a/src/widgets/styles/qstyle_p.h
+++ b/src/widgets/styles/qstyle_p.h
@@ -29,49 +29,36 @@ class QStylePrivate: public QObjectPrivate
{
Q_DECLARE_PUBLIC(QStyle)
public:
- inline QStylePrivate()
- : layoutSpacingIndex(-1), proxyStyle(nullptr) {}
-
static bool useFullScreenForPopup();
- mutable int layoutSpacingIndex;
QStyle *proxyStyle;
QString name;
};
-inline QImage styleCacheImage(const QSize &size)
-{
- const qreal pixelRatio = qApp->devicePixelRatio();
- QImage cacheImage = QImage(size * pixelRatio, QImage::Format_ARGB32_Premultiplied);
- cacheImage.setDevicePixelRatio(pixelRatio);
- return cacheImage;
-}
-
-inline QPixmap styleCachePixmap(const QSize &size)
+inline QPixmap styleCachePixmap(const QSize &size, qreal pixelRatio)
{
- const qreal pixelRatio = qApp->devicePixelRatio();
QPixmap cachePixmap = QPixmap(size * pixelRatio);
cachePixmap.setDevicePixelRatio(pixelRatio);
+ cachePixmap.fill(Qt::transparent);
return cachePixmap;
}
#define BEGIN_STYLE_PIXMAPCACHE(a) \
QRect rect = option->rect; \
QPixmap internalPixmapCache; \
- QImage imageCache; \
QPainter *p = painter; \
- QString unique = QStyleHelper::uniqueName((a), option, option->rect.size()); \
+ const auto dpr = p->device()->devicePixelRatio(); \
+ const QString unique = QStyleHelper::uniqueName((a), option, option->rect.size(), dpr); \
int txType = painter->deviceTransform().type() | painter->worldTransform().type(); \
- bool doPixmapCache = (!option->rect.isEmpty()) \
+ const bool doPixmapCache = (!option->rect.isEmpty()) \
&& ((txType <= QTransform::TxTranslate) || (painter->deviceTransform().type() == QTransform::TxScale)); \
if (doPixmapCache && QPixmapCache::find(unique, &internalPixmapCache)) { \
painter->drawPixmap(option->rect.topLeft(), internalPixmapCache); \
} else { \
if (doPixmapCache) { \
rect.setRect(0, 0, option->rect.width(), option->rect.height()); \
- imageCache = styleCacheImage(option->rect.size()); \
- imageCache.fill(0); \
- p = new QPainter(&imageCache); \
+ internalPixmapCache = styleCachePixmap(option->rect.size(), dpr); \
+ p = new QPainter(&internalPixmapCache); \
}
@@ -80,7 +67,6 @@ inline QPixmap styleCachePixmap(const QSize &size)
if (doPixmapCache) { \
p->end(); \
delete p; \
- internalPixmapCache = QPixmap::fromImage(imageCache); \
painter->drawPixmap(option->rect.topLeft(), internalPixmapCache); \
QPixmapCache::insert(unique, internalPixmapCache); \
} \
diff --git a/src/widgets/styles/qstyleanimation.cpp b/src/widgets/styles/qstyleanimation.cpp
index 32b77f1b53..8e71bb4fae 100644
--- a/src/widgets/styles/qstyleanimation.cpp
+++ b/src/widgets/styles/qstyleanimation.cpp
@@ -256,6 +256,7 @@ static QImage blendedImage(const QImage &start, const QImage &end, float alpha)
front_data += bpl;
}
}
+ break;
default:
break;
}
diff --git a/src/widgets/styles/qstylehelper.cpp b/src/widgets/styles/qstylehelper.cpp
index f79e83be61..02827de847 100644
--- a/src/widgets/styles/qstylehelper.cpp
+++ b/src/widgets/styles/qstylehelper.cpp
@@ -25,15 +25,26 @@ Q_GUI_EXPORT int qt_defaultDpiX();
namespace QStyleHelper {
-QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size)
+static inline bool usePixmapCache(const QStyleOption *opt)
{
+ if (QWidget *widget = qobject_cast<QWidget *>(opt->styleObject))
+ return !widget->testAttribute(Qt::WA_StyleSheetTarget);
+ return true;
+}
+
+QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size, qreal dpr)
+{
+ if (!usePixmapCache(option))
+ return {};
+
const QStyleOptionComplex *complexOption = qstyleoption_cast<const QStyleOptionComplex *>(option);
QString tmp = key % HexString<uint>(option->state)
% HexString<uint>(option->direction)
% HexString<uint>(complexOption ? uint(complexOption->activeSubControls) : 0u)
% HexString<quint64>(option->palette.cacheKey())
% HexString<uint>(size.width())
- % HexString<uint>(size.height());
+ % HexString<uint>(size.height())
+ % HexString<qreal>(dpr);
#if QT_CONFIG(spinbox)
if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
diff --git a/src/widgets/styles/qstylehelper_p.h b/src/widgets/styles/qstylehelper_p.h
index 524417e405..98470ad1ce 100644
--- a/src/widgets/styles/qstylehelper_p.h
+++ b/src/widgets/styles/qstylehelper_p.h
@@ -39,7 +39,7 @@ class QWindow;
namespace QStyleHelper
{
- QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size);
+ QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size, qreal dpr);
Q_WIDGETS_EXPORT qreal dpi(const QStyleOption *option);
diff --git a/src/widgets/styles/qstyleoption.cpp b/src/widgets/styles/qstyleoption.cpp
index de7cd482a3..d3a395246c 100644
--- a/src/widgets/styles/qstyleoption.cpp
+++ b/src/widgets/styles/qstyleoption.cpp
@@ -50,9 +50,6 @@ QT_BEGIN_NAMESPACE
The qstyleoption_cast() function will return 0 if the object to
which \c option points is not of the correct type.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyle, QStylePainter
*/
@@ -329,9 +326,6 @@ QStyleOption &QStyleOption::operator=(const QStyleOption &other)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -428,9 +422,6 @@ QStyleOptionFocusRect::QStyleOptionFocusRect(int version)
without breaking compatibility. If you use qstyleoption_cast(),
you normally do not need to check it.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -555,9 +546,6 @@ QStyleOptionFrame::QStyleOptionFrame(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QStyleOptionComplex, QGroupBox
*/
@@ -688,9 +676,6 @@ QStyleOptionGroupBox::QStyleOptionGroupBox(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -915,9 +900,6 @@ QStyleOptionHeaderV2::QStyleOptionHeaderV2(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QStyleOptionToolButton
*/
@@ -1054,9 +1036,6 @@ QStyleOptionButton::QStyleOptionButton(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -1238,9 +1217,6 @@ QStyleOptionToolBar::QStyleOptionToolBar(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -1314,6 +1290,7 @@ QStyleOptionTab::QStyleOptionTab(int version)
\value Middle The tab is neither the first nor the last tab in the tab bar.
\value End The tab is the last tab in the tab bar.
\value OnlyOneTab The tab is both the first and the last tab in the tab bar.
+ \value [since 6.6] Moving The tab is moving by mouse drag or animation.
\sa position
*/
@@ -1365,7 +1342,7 @@ QStyleOptionTab::QStyleOptionTab(int version)
/*!
\variable QStyleOptionTab::shape
\brief the tab shape used to draw the tab; by default
- QTabBar::RoundedNorth
+ QTabBar::RoundedNorth.
\sa QTabBar::Shape
*/
@@ -1475,9 +1452,6 @@ QStyleOptionTab::QStyleOptionTab(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -1583,7 +1557,7 @@ QStyleOptionProgressBar::QStyleOptionProgressBar(int version)
/*!
\variable QStyleOptionProgressBar::textAlignment
- \brief the text alignment for the text in the QProgressBar
+ \brief the text alignment for the text in the QProgressBar.
This can be used as a guide on where the text should be in the
progress bar. The default value is Qt::AlignLeft.
@@ -1636,9 +1610,6 @@ QStyleOptionProgressBar::QStyleOptionProgressBar(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -1839,9 +1810,6 @@ QStyleOptionMenuItem::QStyleOptionMenuItem(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -1932,9 +1900,6 @@ QStyleOptionComplex::QStyleOptionComplex(int version, int type)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOptionComplex, QSlider, QScrollBar
*/
@@ -2129,9 +2094,6 @@ QStyleOptionSlider::QStyleOptionSlider(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QStyleOptionComplex
*/
@@ -2234,9 +2196,6 @@ QStyleOptionSpinBox::QStyleOptionSpinBox(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption
*/
@@ -2340,9 +2299,6 @@ QStyleOptionDockWidget::QStyleOptionDockWidget(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QStyleOptionComplex, QStyleOptionButton
*/
@@ -2504,9 +2460,6 @@ QStyleOptionToolButton::QStyleOptionToolButton(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QStyleOptionComplex, QComboBox
*/
@@ -2640,9 +2593,6 @@ QStyleOptionComboBox::QStyleOptionComboBox(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QToolBox
*/
@@ -2767,9 +2717,6 @@ QStyleOptionToolBox::QStyleOptionToolBox(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QRubberBand
*/
@@ -2859,9 +2806,6 @@ QStyleOptionRubberBand::QStyleOptionRubberBand(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QStyleOptionComplex, QMdiSubWindow
*/
@@ -2972,9 +2916,6 @@ QStyleOptionTitleBar::QStyleOptionTitleBar(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, {model-view-programming.html}{Model/View
Programming}
*/
@@ -3235,9 +3176,6 @@ QStyleOptionViewItem::QStyleOptionViewItem(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QTabWidget
*/
@@ -3377,9 +3315,6 @@ QStyleOptionTabWidgetFrame::QStyleOptionTabWidgetFrame(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QTabBar::drawBase()
*/
@@ -3487,9 +3422,6 @@ QStyleOptionTabBarBase::QStyleOptionTabBarBase(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QStyleOptionComplex, QSizeGrip
*/
@@ -3567,9 +3499,6 @@ QStyleOptionSizeGrip::QStyleOptionSizeGrip(int version)
and emphasizes that these are simply parameters used by the style
functions.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
\sa QStyleOption, QGraphicsItem::paint()
*/
diff --git a/src/widgets/styles/qstyleoption.h b/src/widgets/styles/qstyleoption.h
index c41256fe35..0e0118f6e9 100644
--- a/src/widgets/styles/qstyleoption.h
+++ b/src/widgets/styles/qstyleoption.h
@@ -193,6 +193,7 @@ protected:
QStyleOptionHeader(int version);
};
+// ### Qt7: merge with QStyleOptionHeader
class Q_WIDGETS_EXPORT QStyleOptionHeaderV2 : public QStyleOptionHeader
{
public:
@@ -243,7 +244,7 @@ public:
enum StyleOptionType { Type = SO_Tab };
enum StyleOptionVersion { Version = 1 };
- enum TabPosition { Beginning, Middle, End, OnlyOneTab };
+ enum TabPosition { Beginning, Middle, End, OnlyOneTab, Moving };
enum SelectedPosition { NotAdjacent, NextIsSelected, PreviousIsSelected };
enum CornerWidget { NoCornerWidgets = 0x00, LeftCornerWidget = 0x01,
RightCornerWidget = 0x02 };
diff --git a/src/widgets/styles/qstylepainter.h b/src/widgets/styles/qstylepainter.h
index 65664b776e..240ffbd137 100644
--- a/src/widgets/styles/qstylepainter.h
+++ b/src/widgets/styles/qstylepainter.h
@@ -26,7 +26,7 @@ public:
const bool res = QPainter::begin(pd);
setRenderHint(QPainter::SmoothPixmapTransform);
return res;
- };
+ }
inline void drawPrimitive(QStyle::PrimitiveElement pe, const QStyleOption &opt);
inline void drawControl(QStyle::ControlElement ce, const QStyleOption &opt);
inline void drawComplexControl(QStyle::ComplexControl cc, const QStyleOptionComplex &opt);
diff --git a/src/widgets/styles/qstylesheetstyle.cpp b/src/widgets/styles/qstylesheetstyle.cpp
index 518e452792..655b224617 100644
--- a/src/widgets/styles/qstylesheetstyle.cpp
+++ b/src/widgets/styles/qstylesheetstyle.cpp
@@ -59,7 +59,7 @@
#include <private/qstyleanimation_p.h>
#endif
#if QT_CONFIG(tabbar)
-#include <qtabbar.h>
+#include <private/qtabbar_p.h>
#endif
#include <QMetaProperty>
#if QT_CONFIG(mainwindow)
@@ -138,8 +138,6 @@ class QStyleSheetStyleRecursionGuard
if (globalStyleSheetStyle != 0 && globalStyleSheetStyle != this) { RETURN; } \
QStyleSheetStyleRecursionGuard recursion_guard(this);
-#define ceil(x) ((int)(x) + ((x) > 0 && (x) != (int)(x)))
-
enum PseudoElement {
PseudoElement_None,
PseudoElement_DownArrow,
@@ -436,16 +434,26 @@ struct QStyleSheetBoxData : public QSharedData
struct QStyleSheetPaletteData : public QSharedData
{
- QStyleSheetPaletteData(const QBrush &fg, const QBrush &sfg, const QBrush &sbg,
- const QBrush &abg, const QBrush &pfg)
- : foreground(fg), selectionForeground(sfg), selectionBackground(sbg),
- alternateBackground(abg), placeholderForeground(pfg) { }
+ QStyleSheetPaletteData(const QBrush &foreground,
+ const QBrush &selectedForeground,
+ const QBrush &selectedBackground,
+ const QBrush &alternateBackground,
+ const QBrush &placeHolderTextForeground,
+ const QBrush &accent)
+ : foreground(foreground)
+ , selectionForeground(selectedForeground)
+ , selectionBackground(selectedBackground)
+ , alternateBackground(alternateBackground)
+ , placeholderForeground(placeHolderTextForeground)
+ , accent(accent)
+ { }
QBrush foreground;
QBrush selectionForeground;
QBrush selectionBackground;
QBrush alternateBackground;
QBrush placeholderForeground;
+ QBrush accent;
};
struct QStyleSheetGeometryData : public QSharedData
@@ -617,7 +625,7 @@ public:
Q_DECLARE_TYPEINFO(QRenderRule, Q_RELOCATABLE_TYPE);
///////////////////////////////////////////////////////////////////////////////////////////
-static const char knownStyleHints[][45] = {
+static constexpr std::array<const char*, 90> knownStyleHints = {
"activate-on-singleclick",
"alignment",
"arrow-keys-navigate-into-children",
@@ -710,13 +718,10 @@ static const char knownStyleHints[][45] = {
"widget-animation-duration"
};
-static const int numKnownStyleHints = sizeof(knownStyleHints)/sizeof(knownStyleHints[0]);
-
-static QList<QVariant> subControlLayout(const QString& layout)
+static QList<QVariant> subControlLayout(QByteArrayView layout)
{
QList<QVariant> buttons;
- for (int i = 0; i < layout.size(); i++) {
- int button = layout[i].toLatin1();
+ for (int button : layout) {
switch (button) {
case 'm':
buttons.append(PseudoElement_MdiMinButton);
@@ -778,10 +783,9 @@ QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget
int offsets[3] = { 0, 0, 0 };
enum Where { Left, Right, Center, NoWhere } where = Left;
QList<ButtonInfo> infos;
- const int numLayouts = layout.size();
- infos.reserve(numLayouts);
- for (int i = 0; i < numLayouts; i++) {
- const int element = layout[i].toInt();
+ infos.reserve(layout.size());
+ for (const QVariant &val : std::as_const(layout)) {
+ const int element = val.toInt();
if (element == '(') {
where = Center;
} else if (element == ')') {
@@ -840,8 +844,7 @@ QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget
}
}
- for (int i = 0; i < infos.size(); i++) {
- const ButtonInfo &info = infos[i];
+ for (const ButtonInfo &info : std::as_const(infos)) {
QRect lr = cr;
switch (info.where) {
case Center: {
@@ -957,10 +960,17 @@ QRenderRule::QRenderRule(const QList<Declaration> &declarations, const QObject *
bg = new QStyleSheetBackgroundData(brush, pixmap, repeat, alignment, origin, attachment, clip);
}
- QBrush sfg, fg, pfg;
- QBrush sbg, abg;
- if (v.extractPalette(&fg, &sfg, &sbg, &abg, &pfg))
- pal = new QStyleSheetPaletteData(fg, sfg, sbg, abg, pfg);
+ QBrush foreground;
+ QBrush selectedForeground;
+ QBrush selectedBackground;
+ QBrush alternateBackground;
+ QBrush placeHolderTextForeground;
+ QBrush accent;
+ if (v.extractPalette(&foreground, &selectedForeground, &selectedBackground,
+ &alternateBackground, &placeHolderTextForeground, &accent)) {
+ pal = new QStyleSheetPaletteData(foreground, selectedForeground, selectedBackground,
+ alternateBackground, placeHolderTextForeground, accent);
+ }
QIcon imgIcon;
alignment = Qt::AlignCenter;
@@ -1015,8 +1025,8 @@ QRenderRule::QRenderRule(const QList<Declaration> &declarations, const QObject *
// intentionally left blank...
} else if (decl.d->propertyId == UnknownProperty) {
bool knownStyleHint = false;
- for (int i = 0; i < numKnownStyleHints; i++) {
- QLatin1StringView styleHint(knownStyleHints[i]);
+ for (const auto sh : knownStyleHints) {
+ QLatin1StringView styleHint(sh);
if (decl.d->property.compare(styleHint) == 0) {
QString hintName = QString(styleHint);
QVariant hintValue;
@@ -1056,9 +1066,9 @@ QRenderRule::QRenderRule(const QList<Declaration> &declarations, const QObject *
}
} else if (hintName.endsWith("icon"_L1)) {
hintValue = decl.iconValue();
- } else if (hintName == "button-layout"_L1
- && decl.d->values.size() != 0 && decl.d->values.at(0).type == Value::String) {
- hintValue = subControlLayout(decl.d->values.at(0).variant.toString());
+ } else if (hintName == "button-layout"_L1 && decl.d->values.size() != 0
+ && decl.d->values.at(0).type == QCss::Value::String) {
+ hintValue = subControlLayout(decl.d->values.at(0).variant.toString().toLatin1());
} else {
int integer;
decl.intValue(&integer);
@@ -1450,6 +1460,16 @@ void QRenderRule::configurePalette(QPalette *p, QPalette::ColorRole fr, QPalette
p->setBrush(QPalette::AlternateBase, pal->alternateBackground);
}
+void setDefault(QPalette *palette, QPalette::ColorGroup group, QPalette::ColorRole role,
+ const QBrush &defaultBrush, const QWidget *widget)
+{
+ const QPalette &widgetPalette = widget->palette();
+ if (widgetPalette.isBrushSet(group, role))
+ palette->setBrush(group, role, widgetPalette.brush(group, role));
+ else
+ palette->setBrush(group, role, defaultBrush);
+}
+
void QRenderRule::configurePalette(QPalette *p, QPalette::ColorGroup cg, const QWidget *w, bool embedded)
{
if (bg && bg->brush.style() != Qt::NoBrush) {
@@ -1471,15 +1491,15 @@ void QRenderRule::configurePalette(QPalette *p, QPalette::ColorGroup cg, const Q
return;
if (pal->foreground.style() != Qt::NoBrush) {
- p->setBrush(cg, QPalette::ButtonText, pal->foreground);
- p->setBrush(cg, w->foregroundRole(), pal->foreground);
- p->setBrush(cg, QPalette::WindowText, pal->foreground);
- p->setBrush(cg, QPalette::Text, pal->foreground);
+ setDefault(p, cg, QPalette::ButtonText, pal->foreground, w);
+ setDefault(p, cg, w->foregroundRole(), pal->foreground, w);
+ setDefault(p, cg, QPalette::WindowText, pal->foreground, w);
+ setDefault(p, cg, QPalette::Text, pal->foreground, w);
QColor phColor(pal->foreground.color());
phColor.setAlpha((phColor.alpha() + 1) / 2);
QBrush placeholder = pal->foreground;
placeholder.setColor(phColor);
- p->setBrush(cg, QPalette::PlaceholderText, placeholder);
+ setDefault(p, cg, QPalette::PlaceholderText, placeholder, w);
}
if (pal->selectionBackground.style() != Qt::NoBrush)
p->setBrush(cg, QPalette::Highlight, pal->selectionBackground);
@@ -1489,6 +1509,8 @@ void QRenderRule::configurePalette(QPalette *p, QPalette::ColorGroup cg, const Q
p->setBrush(cg, QPalette::AlternateBase, pal->alternateBackground);
if (pal->placeholderForeground.style() != Qt::NoBrush)
p->setBrush(cg, QPalette::PlaceholderText, pal->placeholderForeground);
+ if (pal->accent.style() != Qt::NoBrush)
+ p->setBrush(cg, QPalette::Accent, pal->accent);
}
bool QRenderRule::hasModification() const
@@ -1603,8 +1625,8 @@ public:
return nodeName == "QToolTip"_L1;
#endif
do {
- const ushort *uc = (const ushort *)nodeName.constData();
- const ushort *e = uc + nodeName.size();
+ const auto *uc = reinterpret_cast<const char16_t *>(nodeName.constData());
+ const auto *e = uc + nodeName.size();
const uchar *c = (const uchar *)metaObject->className();
while (*c && uc != e && (*uc == *c || (*c == ':' && *uc == '-'))) {
++uc;
@@ -1654,7 +1676,8 @@ QList<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const
defaultSs = getDefaultStyleSheet();
QStyle *bs = baseStyle();
styleSheetCaches->styleSheetCache.insert(bs, defaultSs);
- QObject::connect(bs, SIGNAL(destroyed(QObject*)), styleSheetCaches, SLOT(styleDestroyed(QObject*)), Qt::UniqueConnection);
+ QObject::connect(bs, &QStyle::destroyed, styleSheetCaches,
+ &QStyleSheetStyleCaches::styleDestroyed);
} else {
defaultSs = defaultCacheIt.value();
}
@@ -2571,8 +2594,9 @@ static quint64 extendedPseudoClass(const QWidget *w)
} else
if (const QPlainTextEdit *edit = qobject_cast<const QPlainTextEdit *>(w)) {
pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
- }
+ } else
#endif
+ {}
return pc;
}
@@ -2876,7 +2900,9 @@ bool QStyleSheetStyle::initObject(const QObject *obj) const
const_cast<QWidget *>(w)->setAttribute(Qt::WA_StyleSheet, true);
}
- QObject::connect(obj, SIGNAL(destroyed(QObject*)), styleSheetCaches, SLOT(objectDestroyed(QObject*)), Qt::UniqueConnection);
+ connect(obj, &QObject::destroyed,
+ styleSheetCaches, &QStyleSheetStyleCaches::objectDestroyed,
+ Qt::UniqueConnection);
return true;
}
@@ -2920,10 +2946,10 @@ void QStyleSheetStyle::polish(QWidget *w)
QRenderRule rule = renderRule(sa, PseudoElement_None, PseudoClass_Enabled);
if ((rule.hasBorder() && rule.border()->hasBorderImage())
|| (rule.hasBackground() && !rule.background()->pixmap.isNull())) {
- QObject::connect(sa->horizontalScrollBar(), SIGNAL(valueChanged(int)),
- sa, SLOT(update()), Qt::UniqueConnection);
- QObject::connect(sa->verticalScrollBar(), SIGNAL(valueChanged(int)),
- sa, SLOT(update()), Qt::UniqueConnection);
+ connect(sa->horizontalScrollBar(), &QScrollBar::valueChanged,
+ sa, QOverload<>::of(&QAbstractScrollArea::update), Qt::UniqueConnection);
+ connect(sa->verticalScrollBar(), &QScrollBar::valueChanged,
+ sa, QOverload<>::of(&QAbstractScrollArea::update), Qt::UniqueConnection);
}
}
#endif
@@ -3026,13 +3052,13 @@ void QStyleSheetStyle::unpolish(QWidget *w)
setGeometry(w);
w->setAttribute(Qt::WA_StyleSheetTarget, false);
w->setAttribute(Qt::WA_StyleSheet, false);
- QObject::disconnect(w, nullptr, this, nullptr);
+ w->disconnect(this);
#if QT_CONFIG(scrollarea)
if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w)) {
- QObject::disconnect(sa->horizontalScrollBar(), SIGNAL(valueChanged(int)),
- sa, SLOT(update()));
- QObject::disconnect(sa->verticalScrollBar(), SIGNAL(valueChanged(int)),
- sa, SLOT(update()));
+ disconnect(sa->horizontalScrollBar(), &QScrollBar::valueChanged,
+ sa, QOverload<>::of(&QAbstractScrollArea::update));
+ disconnect(sa->verticalScrollBar(), &QScrollBar::valueChanged,
+ sa, QOverload<>::of(&QAbstractScrollArea::update));
}
#endif
baseStyle()->unpolish(w);
@@ -3048,16 +3074,6 @@ void QStyleSheetStyle::unpolish(QApplication *app)
styleSheetCaches->styleSheetCache.remove(qApp);
}
-#if QT_CONFIG(tabbar)
-inline static bool verticalTabs(QTabBar::Shape shape)
-{
- return shape == QTabBar::RoundedWest
- || shape == QTabBar::RoundedEast
- || shape == QTabBar::TriangularWest
- || shape == QTabBar::TriangularEast;
-}
-#endif // QT_CONFIG(tabbar)
-
void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
const QWidget *w) const
{
@@ -3487,12 +3503,12 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
|| hasStyleRule(w, PseudoElement_MdiMinButton)) {
QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
if (layout.isEmpty())
- layout = subControlLayout("mNX"_L1);
+ layout = subControlLayout("mNX");
QStyleOptionComplex optCopy(*opt);
optCopy.subControls = { };
- for (int i = 0; i < layout.size(); i++) {
- int layoutButton = layout[i].toInt();
+ for (const QVariant &val : std::as_const(layout)) {
+ int layoutButton = val.toInt();
if (layoutButton < PseudoElement_MdiCloseButton
|| layoutButton > PseudoElement_MdiNormalButton)
continue;
@@ -3523,6 +3539,7 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
break;
subRule.drawRule(p, opt->rect);
QHash<QStyle::SubControl, QRect> layout = titleBarLayout(w, tb);
+ const auto paintDeviceDpr = p->device()->devicePixelRatio();
QRect ir;
ir = layout[SC_TitleBarLabel];
@@ -3533,8 +3550,6 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
p->drawText(ir.x(), ir.y(), ir.width(), ir.height(), Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, tb->text);
}
- QPixmap pm;
-
ir = layout[SC_TitleBarSysMenu];
if (ir.isValid()) {
QRenderRule subSubRule = renderRule(w, opt, PseudoElement_TitleBarSysMenu);
@@ -3544,7 +3559,9 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
tb->icon.paint(p, ir);
} else {
int iconSize = pixelMetric(PM_SmallIconSize, tb, w);
- pm = standardIcon(SP_TitleBarMenuButton, nullptr, w).pixmap(iconSize, iconSize);
+ const QSize sz(iconSize, iconSize);
+ const auto pm = standardIcon(SP_TitleBarMenuButton, nullptr, w)
+ .pixmap(sz, paintDeviceDpr);
drawItemPixmap(p, ir, Qt::AlignCenter, pm);
}
}
@@ -3554,15 +3571,14 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
QRenderRule subSubRule = renderRule(w, opt, PseudoElement_TitleBarCloseButton);
subSubRule.drawRule(p, ir);
- QSize sz = subSubRule.contentsRect(ir).size();
- if ((tb->titleBarFlags & Qt::WindowType_Mask) == Qt::Tool)
- pm = standardIcon(SP_DockWidgetCloseButton, nullptr, w).pixmap(sz);
- else
- pm = standardIcon(SP_TitleBarCloseButton, nullptr, w).pixmap(sz);
+ const QSize sz = subSubRule.contentsRect(ir).size();
+ const auto type = ((tb->titleBarFlags & Qt::WindowType_Mask) == Qt::Tool)
+ ? SP_DockWidgetCloseButton : SP_TitleBarCloseButton;
+ const auto pm = standardIcon(type, nullptr, w).pixmap(sz, paintDeviceDpr);
drawItemPixmap(p, ir, Qt::AlignCenter, pm);
}
- int pes[] = {
+ constexpr std::array<int, 6> pes = {
PseudoElement_TitleBarMaxButton,
PseudoElement_TitleBarMinButton,
PseudoElement_TitleBarNormalButton,
@@ -3571,15 +3587,15 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
PseudoElement_TitleBarContextHelpButton
};
- for (unsigned int i = 0; i < sizeof(pes)/sizeof(int); i++) {
- int pe = pes[i];
+ for (int pe : pes) {
QStyle::SubControl sc = knownPseudoElements[pe].subControl;
ir = layout[sc];
if (!ir.isValid())
continue;
QRenderRule subSubRule = renderRule(w, opt, pe);
subSubRule.drawRule(p, ir);
- pm = standardIcon(subControlIcon(pe), nullptr, w).pixmap(subSubRule.contentsRect(ir).size());
+ const QSize sz = subSubRule.contentsRect(ir).size();
+ const auto pm = standardIcon(subControlIcon(pe), nullptr, w).pixmap(sz, paintDeviceDpr);
drawItemPixmap(p, ir, Qt::AlignCenter, pm);
}
@@ -3602,7 +3618,9 @@ void QStyleSheetStyle::renderMenuItemIcon(const QStyleOptionMenuItem *mi, QPaint
? (mi->state & QStyle::State_Selected ? QIcon::Active : QIcon::Normal)
: QIcon::Disabled;
const bool checked = mi->checkType != QStyleOptionMenuItem::NotCheckable && mi->checked;
- const QPixmap pixmap(mi->icon.pixmap(pixelMetric(PM_SmallIconSize), mode,
+ const auto iconSize = pixelMetric(PM_SmallIconSize, mi, w);
+ const QSize sz(iconSize, iconSize);
+ const QPixmap pixmap(mi->icon.pixmap(sz, p->device()->devicePixelRatio(), mode,
checked ? QIcon::On : QIcon::Off));
const int pixw = pixmap.width() / pixmap.devicePixelRatio();
const int pixh = pixmap.height() / pixmap.devicePixelRatio();
@@ -3737,7 +3755,8 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
if (button->state & State_On)
state = QIcon::On;
- QPixmap pixmap = icon.pixmap(button->iconSize, mode, state);
+ const auto paintDeviceDpr = p->device()->devicePixelRatio();
+ QPixmap pixmap = icon.pixmap(button->iconSize, paintDeviceDpr, mode, state);
int pixmapWidth = pixmap.width() / pixmap.devicePixelRatio();
int pixmapHeight = pixmap.height() / pixmap.devicePixelRatio();
int labelWidth = pixmapWidth;
@@ -4039,7 +4058,8 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
if (spacing == -1)
spacing = 6;
QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
- QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
+ const auto paintDeviceDpr = p->device()->devicePixelRatio();
+ QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, paintDeviceDpr, mode);
QRect iconRect(editRect);
iconRect.setWidth(cb->iconSize.width());
iconRect = alignedRect(cb->direction,
@@ -4100,15 +4120,22 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
case CE_HeaderLabel:
if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- QStyleOptionHeader hdr(*header);
+ QStyleOptionHeaderV2 hdr;
+ QStyleOptionHeader &v1Copy = hdr;
+ if (auto v2 = qstyleoption_cast<const QStyleOptionHeaderV2 *>(opt))
+ hdr = *v2;
+ else
+ v1Copy = *header;
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
if (hasStyleRule(w, PseudoElement_HeaderViewUpArrow)
|| hasStyleRule(w, PseudoElement_HeaderViewDownArrow)) {
- const QRect arrowRect = subElementRect(SE_HeaderArrow, opt, w);
- if (hdr.orientation == Qt::Horizontal)
- hdr.rect.setWidth(hdr.rect.width() - arrowRect.width());
- else
- hdr.rect.setHeight(hdr.rect.height() - arrowRect.height());
+ if (hdr.sortIndicator != QStyleOptionHeader::None) {
+ const QRect arrowRect = subElementRect(SE_HeaderArrow, opt, w);
+ if (hdr.orientation == Qt::Horizontal)
+ hdr.rect.setWidth(hdr.rect.width() - arrowRect.width());
+ else
+ hdr.rect.setHeight(hdr.rect.height() - arrowRect.height());
+ }
}
subRule.configurePalette(&hdr.palette, QPalette::ButtonText, QPalette::Button);
if (subRule.hasFont) {
@@ -4208,6 +4235,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
--chunkCount;
};
} else if (chunkWidth > 0) {
+ const auto ceil = [](qreal x) { return int(x) + (x > 0 && x != int(x)); };
const int chunkCount = ceil(qreal(fillWidth)/chunkWidth);
int x = reverse ? r.left() + r.width() - chunkWidth : r.x();
@@ -4248,12 +4276,11 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
if (rule.hasDrawable()) {
rule.drawFrame(p, opt->rect);
p->save();
- switch (sgOpt->corner) {
- case Qt::BottomRightCorner: break;
- case Qt::BottomLeftCorner: p->rotate(90); break;
- case Qt::TopLeftCorner: p->rotate(180); break;
- case Qt::TopRightCorner: p->rotate(270); break;
- default: break;
+ static constexpr int rotation[] = { 180, 270, 90, 0 };
+ if (rotation[sgOpt->corner]) {
+ p->translate(opt->rect.center());
+ p->rotate(rotation[sgOpt->corner]);
+ p->translate(-opt->rect.center());
}
rule.drawImage(p, opt->rect);
p->restore();
@@ -4356,19 +4383,23 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
vopt->state & QStyle::State_Selected
? QPalette::Highlight
: QPalette::Base);
- // only draw the indicator; no text or background
+ // only draw the indicator; no text, icon or background
optIndicator.backgroundBrush = Qt::NoBrush; // no background
optIndicator.text.clear();
+ optIndicator.icon = QIcon();
QWindowsStyle::drawControl(ce, &optIndicator, p, w);
- // Now draw text, background, and highlight, but not the indicator with the
- // base style. Since we can't turn off HasCheckIndicator to prevent the base
+
+ // Now draw text, background,icon, and highlight, but not the indicator with
+ // the base style. Since we can't turn off HasCheckIndicator to prevent the base
// style from drawing the check indicator again (it would change how the item
// gets laid out) we have to clip the indicator that's already been painted.
- const QRect checkRect = subElementRect(QStyle::SE_ItemViewItemCheckIndicator,
- &optIndicator, w);
+ const QRect crStyle = subElementRect(QStyle::SE_ItemViewItemCheckIndicator,
+ &optIndicator, w);
+ const QRect crBase = baseStyle()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator,
+ &optIndicator, w);
const QRegion clipRegion = QRegion(p->hasClipping() ? p->clipRegion()
: QRegion(optIndicator.rect))
- - checkRect;
+ - crStyle.united(crBase);
p->setClipRegion(clipRegion);
}
subRule.configurePalette(&optCopy.palette, QPalette::Text, QPalette::NoRole);
@@ -4457,7 +4488,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
QString titleText = p->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight, r.width());
drawItemText(p, r,
- alignment, dwOpt->palette,
+ alignment | Qt::TextHideMnemonic, dwOpt->palette,
dwOpt->state & State_Enabled, titleText,
QPalette::WindowText);
@@ -4842,6 +4873,7 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op
w = w->parentWidget(); //match on the QTabBar instead of the CloseButton
}
pseudoElement = PseudoElement_TabBarTabCloseButton;
+ break;
#endif
default:
@@ -5102,7 +5134,7 @@ int QStyleSheetStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const
break;
case PM_ScrollView_ScrollBarOverlap:
- if (!rule.hasNativeBorder() || rule.hasBox())
+ if (!proxy()->styleHint(SH_ScrollBar_Transient, opt, w))
return 0;
break;
#endif // QT_CONFIG(scrollbar)
@@ -5469,11 +5501,11 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
if (layout.isEmpty())
- layout = subControlLayout("mNX"_L1);
+ layout = subControlLayout("mNX");
int width = 0, height = 0;
- for (int i = 0; i < layout.size(); i++) {
- int layoutButton = layout[i].toInt();
+ for (const QVariant &val : std::as_const(layout)) {
+ int layoutButton = val.toInt();
if (layoutButton < PseudoElement_MdiCloseButton
|| layoutButton > PseudoElement_MdiNormalButton)
continue;
@@ -5600,7 +5632,8 @@ QPixmap QStyleSheetStyle::standardPixmap(StandardPixmap standardPixmap, const QS
QRenderRule rule = renderRule(w, opt);
if (rule.hasStyleHint(s)) {
QIcon icon = qvariant_cast<QIcon>(rule.styleHint(s));
- return icon.pixmap(16, 16); // ###: unhard-code this if someone complains
+ const auto dpr = w ? w->devicePixelRatio() : qApp->devicePixelRatio();
+ return icon.pixmap(QSize(16, 16), dpr);
}
}
return baseStyle()->standardPixmap(standardPixmap, opt, w);
@@ -5712,7 +5745,7 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi
case SH_TitleBar_ShowToolTipsOnButtons: s = "titlebar-show-tooltips-on-buttons"_L1; break;
case SH_Widget_Animation_Duration: s = "widget-animation-duration"_L1; break;
case SH_ScrollBar_Transient:
- if (!rule.hasNativeBorder() || rule.hasBox())
+ if (!rule.hasNativeBorder() || rule.hasBox() || rule.hasDrawable())
return 0;
break;
default: break;
@@ -6035,12 +6068,12 @@ QRect QStyleSheetStyle::subControlRect(ComplexControl cc, const QStyleOptionComp
|| hasStyleRule(w, PseudoElement_MdiMinButton)) {
QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
if (layout.isEmpty())
- layout = subControlLayout("mNX"_L1);
+ layout = subControlLayout("mNX");
int x = 0, width = 0;
QRenderRule subRule;
- for (int i = 0; i < layout.size(); i++) {
- int layoutButton = layout[i].toInt();
+ for (const QVariant &val : std::as_const(layout)) {
+ int layoutButton = val.toInt();
if (layoutButton < PseudoElement_MdiCloseButton
|| layoutButton > PseudoElement_MdiNormalButton)
continue;
@@ -6196,8 +6229,22 @@ QRect QStyleSheetStyle::subElementRect(SubElement se, const QStyleOption *opt, c
case SE_HeaderLabel: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
- if (subRule.hasBox() || !subRule.hasNativeBorder())
- return subRule.contentsRect(opt->rect);
+ if (subRule.hasBox() || !subRule.hasNativeBorder()) {
+ auto r = subRule.contentsRect(opt->rect);
+ if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
+ // Subtract width needed for arrow, if there is one
+ if (header->sortIndicator != QStyleOptionHeader::None) {
+ const auto arrowRect = subElementRect(SE_HeaderArrow, opt, w);
+ if (arrowRect.isValid()) {
+ if (opt->state & State_Horizontal)
+ r.setWidth(r.width() - arrowRect.width());
+ else
+ r.setHeight(r.height() - arrowRect.height());
+ }
+ }
+ }
+ return r;
+ }
}
break;
@@ -6465,6 +6512,9 @@ bool QStyleSheetStyle::isNaturalChild(const QObject *obj)
QPixmap QStyleSheetStyle::loadPixmap(const QString &fileName, const QObject *context)
{
+ if (fileName.isEmpty())
+ return {};
+
qreal ratio = -1.0;
if (const QWidget *widget = qobject_cast<const QWidget *>(context)) {
if (QScreen *screen = QApplication::screenAt(widget->mapToGlobal(QPoint(0, 0))))
diff --git a/src/widgets/styles/qstylesheetstyle_default.cpp b/src/widgets/styles/qstylesheetstyle_default.cpp
index b299c9e022..e50e18f291 100644
--- a/src/widgets/styles/qstylesheetstyle_default.cpp
+++ b/src/widgets/styles/qstylesheetstyle_default.cpp
@@ -11,8 +11,10 @@
avoid parsing overhead.
*/
-#include "private/qcssparser_p.h"
#include "qstylesheetstyle_p.h"
+#if QT_CONFIG(cssparser)
+#include "private/qcssparser_p.h"
+#endif
#ifndef QT_NO_STYLE_STYLESHEET
@@ -134,15 +136,15 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Base);
ADD_DECLARATION;
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -158,7 +160,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_None);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -173,7 +175,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -193,11 +195,11 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("background"_L1, Background);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_None);
ADD_DECLARATION;
SET_PROPERTY("border-image"_L1, BorderImage);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_None);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -212,7 +214,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -229,11 +231,11 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Window);
ADD_DECLARATION;
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -253,12 +255,12 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("border-style"_L1, BorderStyles);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
if (!styleIsPixmapBased) {
SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
}
@@ -279,18 +281,18 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
if (!styleIsPixmapBased) {
SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-gradient"));
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-gradient"));
ADD_DECLARATION;
}
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Base);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -310,7 +312,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Button);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Button);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -327,15 +329,15 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Base);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -350,7 +352,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Window);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -365,7 +367,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -380,7 +382,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Window);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -403,17 +405,17 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Button);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Button);
ADD_DECLARATION;
if (!styleIsPixmapBased) {
SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
}
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -428,7 +430,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Base);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -443,7 +445,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Window);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -458,7 +460,7 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
ADD_SELECTOR;
SET_PROPERTY("border"_L1, Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
diff --git a/src/widgets/styles/qwindowsstyle.cpp b/src/widgets/styles/qwindowsstyle.cpp
index 63b1e85483..bae182b467 100644
--- a/src/widgets/styles/qwindowsstyle.cpp
+++ b/src/widgets/styles/qwindowsstyle.cpp
@@ -88,26 +88,6 @@ enum QSliderDirection { SlUp, SlDown, SlLeft, SlRight };
QWindowsStylePrivate::QWindowsStylePrivate() = default;
-qreal QWindowsStylePrivate::appDevicePixelRatio()
-{
- return qApp->devicePixelRatio();
-}
-
-bool QWindowsStylePrivate::isDarkMode()
-{
- bool result = false;
-#ifdef Q_OS_WIN
- using QWindowsApplication = QNativeInterface::Private::QWindowsApplication;
- // Windows only: Return whether dark mode style support is desired and
- // dark mode is in effect.
- if (auto windowsApp = dynamic_cast<QWindowsApplication *>(QGuiApplicationPrivate::platformIntegration())) {
- result = windowsApp->isDarkMode()
- && windowsApp->darkModeHandling().testFlag(QWindowsApplication::DarkModeStyle);
- }
-#endif
- return result;
-}
-
// Returns \c true if the toplevel parent of \a widget has seen the Alt-key
bool QWindowsStylePrivate::hasSeenAlt(const QWidget *widget) const
{
@@ -132,19 +112,20 @@ bool QWindowsStyle::eventFilter(QObject *o, QEvent *e)
widget = widget->window();
// Alt has been pressed - find all widgets that care
- QList<QWidget *> l = widget->findChildren<QWidget *>();
+ const QList<QWidget *> children = widget->findChildren<QWidget *>();
auto ignorable = [](QWidget *w) {
return w->isWindow() || !w->isVisible()
|| w->style()->styleHint(SH_UnderlineShortcut, nullptr, w);
};
- l.removeIf(ignorable);
// Update states before repainting
d->seenAlt.append(widget);
d->alt_down = true;
// Repaint all relevant widgets
- for (int pos = 0; pos < l.size(); ++pos)
- l.at(pos)->update();
+ for (QWidget *w : children) {
+ if (!ignorable(w))
+ w->update();
+ }
}
break;
case QEvent::KeyRelease:
@@ -154,9 +135,9 @@ bool QWindowsStyle::eventFilter(QObject *o, QEvent *e)
// Update state and repaint the menu bars.
d->alt_down = false;
#if QT_CONFIG(menubar)
- QList<QMenuBar *> l = widget->findChildren<QMenuBar *>();
- for (int i = 0; i < l.size(); ++i)
- l.at(i)->update();
+ const QList<QMenuBar *> menuBars = widget->findChildren<QMenuBar *>();
+ for (QWidget *w : menuBars)
+ w->update();
#endif
}
break;
@@ -276,28 +257,33 @@ void QWindowsStyle::polish(QPalette &pal)
int QWindowsStylePrivate::pixelMetricFromSystemDp(QStyle::PixelMetric pm, const QStyleOption *, const QWidget *widget)
{
#if defined(Q_OS_WIN)
+ // The pixel metrics are in device indepentent pixels;
+ // hardcode DPI to 1x 96 DPI.
+ const int dpi = 96;
+
switch (pm) {
case QStyle::PM_DockWidgetFrameWidth:
- return GetSystemMetrics(SM_CXFRAME);
-
- case QStyle::PM_TitleBarHeight:
- if (widget && (widget->windowType() == Qt::Tool)) {
- // MS always use one less than they say
- return GetSystemMetrics(SM_CYSMCAPTION) - 1;
- }
- return GetSystemMetrics(SM_CYCAPTION) - 1;
+ return GetSystemMetricsForDpi(SM_CXFRAME, dpi);
+
+ case QStyle::PM_TitleBarHeight: {
+ const int resizeBorderThickness =
+ GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
+ if (widget && (widget->windowType() == Qt::Tool))
+ return GetSystemMetricsForDpi(SM_CYSMCAPTION, dpi) + resizeBorderThickness;
+ return GetSystemMetricsForDpi(SM_CYCAPTION, dpi) + resizeBorderThickness;
+ }
case QStyle::PM_ScrollBarExtent:
{
NONCLIENTMETRICS ncm;
- ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICS, lfMessageFont) + sizeof(LOGFONT);
- if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0))
+ ncm.cbSize = sizeof(NONCLIENTMETRICS);
+ if (SystemParametersInfoForDpi(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0, dpi))
return qMax(ncm.iScrollHeight, ncm.iScrollWidth);
}
break;
case QStyle::PM_MdiSubWindowFrameWidth:
- return GetSystemMetrics(SM_CYFRAME);
+ return GetSystemMetricsForDpi(SM_CYFRAME, dpi);
default:
break;
@@ -369,25 +355,10 @@ static QScreen *screenOf(const QWidget *w)
}
// Calculate the overall scale factor to obtain Qt Device Independent
-// Pixels from a native Windows size. Divide by devicePixelRatio
-// and account for secondary screens with differing logical DPI.
+// Pixels from a native Windows size.
qreal QWindowsStylePrivate::nativeMetricScaleFactor(const QWidget *widget)
{
- const QPlatformScreen *screen = screenOf(widget)->handle();
- const qreal scale = screen ? (screen->logicalDpi().first / screen->logicalBaseDpi().first)
- : QWindowsStylePrivate::appDevicePixelRatio();
- qreal result = qreal(1) / scale;
- if (QGuiApplicationPrivate::screen_list.size() > 1) {
- const QScreen *primaryScreen = QGuiApplication::primaryScreen();
- const QScreen *screen = screenOf(widget);
- if (screen != primaryScreen) {
- const qreal primaryLogicalDpi = primaryScreen->handle()->logicalDpi().first;
- const qreal logicalDpi = screen->handle()->logicalDpi().first;
- if (!qFuzzyCompare(primaryLogicalDpi, logicalDpi))
- result *= logicalDpi / primaryLogicalDpi;
- }
- }
- return result;
+ return qreal(1) / QHighDpiScaling::factor(screenOf(widget));
}
/*!
@@ -397,7 +368,7 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW
{
int ret = QWindowsStylePrivate::pixelMetricFromSystemDp(pm, opt, widget);
if (ret != QWindowsStylePrivate::InvalidMetric)
- return qRound(qreal(ret) * QWindowsStylePrivate::nativeMetricScaleFactor(widget));
+ return ret;
ret = QWindowsStylePrivate::fixedPixelMetric(pm);
if (ret != QWindowsStylePrivate::InvalidMetric)
@@ -407,7 +378,7 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW
switch (pm) {
case PM_MaximumDragDistance:
- ret = QCommonStyle::pixelMetric(PM_MaximumDragDistance);
+ ret = QCommonStyle::pixelMetric(PM_MaximumDragDistance, opt, widget);
if (ret == -1)
ret = 60;
break;
@@ -464,46 +435,6 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW
QPixmap QWindowsStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
const QWidget *widget) const
{
-#if defined(Q_OS_WIN)
- QPixmap desktopIcon;
- switch(standardPixmap) {
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- case SP_DriveNetIcon:
- case SP_DriveHDIcon:
- case SP_DriveFDIcon:
- case SP_FileIcon:
- case SP_FileLinkIcon:
- case SP_DirLinkIcon:
- case SP_DirClosedIcon:
- case SP_DesktopIcon:
- case SP_ComputerIcon:
- case SP_DirOpenIcon:
- case SP_FileDialogNewFolder:
- case SP_DirHomeIcon:
- case SP_TrashIcon:
- case SP_VistaShield:
- if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
- QPlatformTheme::StandardPixmap sp = static_cast<QPlatformTheme::StandardPixmap>(standardPixmap);
- desktopIcon = theme->standardPixmap(sp, QSizeF(16, 16));
- }
- break;
- case SP_MessageBoxInformation:
- case SP_MessageBoxWarning:
- case SP_MessageBoxCritical:
- case SP_MessageBoxQuestion:
- if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
- QPlatformTheme::StandardPixmap sp = static_cast<QPlatformTheme::StandardPixmap>(standardPixmap);
- desktopIcon = theme->standardPixmap(sp, QSizeF());
- }
- break;
- default:
- break;
- }
- if (!desktopIcon.isNull()) {
- return desktopIcon;
- }
-#endif // Q_OS_WIN
return QCommonStyle::standardPixmap(standardPixmap, opt, widget);
}
@@ -514,9 +445,14 @@ int QWindowsStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWid
int ret = 0;
switch (hint) {
- case SH_EtchDisabledText:
- ret = d_func()->isDarkMode() ? 0 : 1;
+ case SH_EtchDisabledText: {
+ const QPalette pal = opt ? opt->palette
+ : widget ? widget->palette()
+ : QPalette();
+ ret = pal.window().color().lightness() > pal.text().color().lightness()
+ ? 1 : 0;
break;
+ }
case SH_Slider_SnapToValue:
case SH_PrintDialog_RightAlignButtons:
case SH_FontDialog_SelectAssociatedText:
@@ -820,7 +756,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
}
#endif // QT_CONFIG(itemviews)
if (!(opt->state & State_Off)) {
- QPointF points[6];
+ std::array<QPointF, 6> points;
qreal scaleh = opt->rect.width() / 12.0;
qreal scalev = opt->rect.height() / 12.0;
points[0] = { opt->rect.x() + qreal(3.5) * scaleh, opt->rect.y() + qreal(5.5) * scalev };
@@ -831,7 +767,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
points[5] = { points[4].x() - 4 * scaleh, points[4].y() + 4 * scalev };
p->setPen(QPen(opt->palette.text().color(), 0));
p->setBrush(opt->palette.text().color());
- p->drawPolygon(points, 6);
+ p->drawPolygon(points.data(), static_cast<int>(points.size()));
}
if (doRestore)
p->restore();
@@ -1583,11 +1519,8 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
default:
break;
}
- if (opt->direction == Qt::RightToLeft){ //reverse layout changes the order of Beginning/end
- bool tmp = paintLeftBorder;
- paintRightBorder=paintLeftBorder;
- paintLeftBorder=tmp;
- }
+ if (opt->direction == Qt::RightToLeft) //reverse layout changes the order of Beginning/end
+ std::swap(paintLeftBorder, paintRightBorder);
break;
case Qt::RightToolBarArea :
switch (toolbar->positionOfLine){
@@ -1799,7 +1732,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
titleRect.height(), titleRect.width());
}
proxy()->drawItemText(p, titleRect,
- Qt::AlignLeft | Qt::AlignVCenter, palette,
+ Qt::AlignLeft | Qt::AlignVCenter | Qt::TextHideMnemonic, palette,
dwOpt->state & State_Enabled, dwOpt->title,
floating ? (active ? QPalette::BrightText : QPalette::Window) : QPalette::WindowText);
p->setFont(oldFont);
@@ -1962,39 +1895,36 @@ void QWindowsStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComp
QSliderDirection dir;
if (orient == Qt::Horizontal)
- if (tickAbove)
- dir = SlUp;
- else
- dir = SlDown;
+ dir = tickAbove ? SlUp : SlDown;
else
- if (tickAbove)
- dir = SlLeft;
- else
- dir = SlRight;
-
- QPolygon a;
+ dir = tickAbove ? SlLeft : SlRight;
+ std::array<QPoint, 5> points;
int d = 0;
switch (dir) {
case SlUp:
- y1 = y1 + wi/2;
+ y1 = y1 + wi / 2;
d = (wi + 1) / 2 - 1;
- a.setPoints(5, x1,y1, x1,y2, x2,y2, x2,y1, x1+d,y1-d);
+ points = {QPoint(x1, y1), QPoint(x1, y2), QPoint(x2, y2),
+ QPoint(x2, y1), QPoint(x1 + d, y1 - d)};
break;
case SlDown:
- y2 = y2 - wi/2;
+ y2 = y2 - wi / 2;
d = (wi + 1) / 2 - 1;
- a.setPoints(5, x1,y1, x1,y2, x1+d,y2+d, x2,y2, x2,y1);
+ points = {QPoint(x1, y1), QPoint(x1, y2), QPoint(x1 + d, y2 + d),
+ QPoint(x2, y2), QPoint(x2, y1)};
break;
case SlLeft:
d = (he + 1) / 2 - 1;
- x1 = x1 + he/2;
- a.setPoints(5, x1,y1, x1-d,y1+d, x1,y2, x2,y2, x2,y1);
+ x1 = x1 + he / 2;
+ points = {QPoint(x1, y1), QPoint(x1 - d, y1 + d), QPoint(x1,y2),
+ QPoint(x2, y2), QPoint(x2, y1)};
break;
case SlRight:
d = (he + 1) / 2 - 1;
- x2 = x2 - he/2;
- a.setPoints(5, x1,y1, x1,y2, x2,y2, x2+d,y1+d, x2,y1);
+ x2 = x2 - he / 2;
+ points = {QPoint(x1, y1), QPoint(x1, y2), QPoint(x2, y2),
+ QPoint(x2 + d, y1 + d), QPoint(x2, y1)};
break;
}
@@ -2004,7 +1934,7 @@ void QWindowsStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComp
Qt::BGMode oldMode = p->backgroundMode();
p->setBackgroundMode(Qt::OpaqueMode);
p->drawRect(x1, y1, x2-x1+1, y2-y1+1);
- p->drawPolygon(a);
+ p->drawPolygon(points.data(), static_cast<int>(points.size()));
p->setBrush(oldBrush);
p->setBackgroundMode(oldMode);
diff --git a/src/widgets/styles/qwindowsstyle_p_p.h b/src/widgets/styles/qwindowsstyle_p_p.h
index 7d6eb2963e..dce60cbf8d 100644
--- a/src/widgets/styles/qwindowsstyle_p_p.h
+++ b/src/widgets/styles/qwindowsstyle_p_p.h
@@ -24,8 +24,6 @@
QT_BEGIN_NAMESPACE
-class QTime;
-
class Q_WIDGETS_EXPORT QWindowsStylePrivate : public QCommonStylePrivate
{
Q_DECLARE_PUBLIC(QWindowsStyle)
@@ -35,16 +33,12 @@ public:
QWindowsStylePrivate();
static int pixelMetricFromSystemDp(QStyle::PixelMetric pm, const QStyleOption *option = nullptr, const QWidget *widget = nullptr);
static int fixedPixelMetric(QStyle::PixelMetric pm);
- static qreal devicePixelRatio(const QWidget *widget = nullptr)
- { return widget ? widget->devicePixelRatio() : QWindowsStylePrivate::appDevicePixelRatio(); }
static qreal nativeMetricScaleFactor(const QWidget *widget = nullptr);
- static bool isDarkMode();
bool hasSeenAlt(const QWidget *widget) const;
bool altDown() const { return alt_down; }
bool alt_down = false;
QList<const QWidget *> seenAlt;
- int menuBarTimer = 0;
QColor inactiveCaptionText;
QColor activeCaptionColor;
@@ -61,9 +55,6 @@ public:
windowsRightBorder = 15, // right border on windows
windowsCheckMarkWidth = 12 // checkmarks width on windows
};
-
-private:
- static qreal appDevicePixelRatio();
};
QT_END_NAMESPACE
diff --git a/src/widgets/util/qcompleter.cpp b/src/widgets/util/qcompleter.cpp
index 1b519bf4c5..394a968aad 100644
--- a/src/widgets/util/qcompleter.cpp
+++ b/src/widgets/util/qcompleter.cpp
@@ -840,8 +840,8 @@ void QCompleterPrivate::setCurrentIndex(QModelIndex index, bool select)
void QCompleterPrivate::_q_completionSelected(const QItemSelection& selection)
{
QModelIndex index;
- if (!selection.indexes().isEmpty())
- index = selection.indexes().first();
+ if (const auto indexes = selection.indexes(); !indexes.isEmpty())
+ index = indexes.first();
_q_complete(index, true);
}
@@ -1207,50 +1207,55 @@ Qt::MatchFlags QCompleter::filterMode() const
*/
void QCompleter::setPopup(QAbstractItemView *popup)
{
+ Q_ASSERT(popup);
Q_D(QCompleter);
- Q_ASSERT(popup != nullptr);
+ if (popup == d->popup)
+ return;
+
+ // Remember existing widget's focus policy, default to NoFocus
+ const Qt::FocusPolicy origPolicy = d->widget ? d->widget->focusPolicy()
+ : Qt::NoFocus;
+
+ // If popup existed already, disconnect signals and delete object
if (d->popup) {
QObject::disconnect(d->popup->selectionModel(), nullptr, this, nullptr);
QObject::disconnect(d->popup, nullptr, this, nullptr);
- }
- if (d->popup != popup)
delete d->popup;
- if (popup->model() != d->proxy)
- popup->setModel(d->proxy);
- popup->hide();
+ }
- Qt::FocusPolicy origPolicy = Qt::NoFocus;
- if (d->widget)
- origPolicy = d->widget->focusPolicy();
+ // Assign new object, set model and hide
+ d->popup = popup;
+ if (d->popup->model() != d->proxy)
+ d->popup->setModel(d->proxy);
+ d->popup->hide();
// Mark the widget window as a popup, so that if the last non-popup window is closed by the
// user, the application should not be prevented from exiting. It needs to be set explicitly via
// setWindowFlag(), because passing the flag via setParent(parent, windowFlags) does not call
// QWidgetPrivate::adjustQuitOnCloseAttribute(), and causes an application not to exit if the
// popup ends up being the last window.
- popup->setParent(nullptr);
- popup->setWindowFlag(Qt::Popup);
- popup->setFocusPolicy(Qt::NoFocus);
+ d->popup->setParent(nullptr);
+ d->popup->setWindowFlag(Qt::Popup);
+ d->popup->setFocusPolicy(Qt::NoFocus);
if (d->widget)
d->widget->setFocusPolicy(origPolicy);
- popup->setFocusProxy(d->widget);
- popup->installEventFilter(this);
- popup->setItemDelegate(new QCompleterItemDelegate(popup));
+ d->popup->setFocusProxy(d->widget);
+ d->popup->installEventFilter(this);
+ d->popup->setItemDelegate(new QCompleterItemDelegate(d->popup));
#if QT_CONFIG(listview)
- if (QListView *listView = qobject_cast<QListView *>(popup)) {
+ if (QListView *listView = qobject_cast<QListView *>(d->popup)) {
listView->setModelColumn(d->column);
}
#endif
- QObject::connect(popup, SIGNAL(clicked(QModelIndex)),
+ QObject::connect(d->popup, SIGNAL(clicked(QModelIndex)),
this, SLOT(_q_complete(QModelIndex)));
QObject::connect(this, SIGNAL(activated(QModelIndex)),
- popup, SLOT(hide()));
+ d->popup, SLOT(hide()));
- QObject::connect(popup->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
+ QObject::connect(d->popup->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(_q_completionSelected(QItemSelection)));
- d->popup = popup;
}
/*!
diff --git a/src/widgets/util/qcompleter_p.h b/src/widgets/util/qcompleter_p.h
index b74de04031..a88996f180 100644
--- a/src/widgets/util/qcompleter_p.h
+++ b/src/widgets/util/qcompleter_p.h
@@ -25,7 +25,9 @@
#include "qcompleter.h"
#include "qstyleditemdelegate.h"
#include "QtGui/qpainter.h"
+
#include "private/qabstractproxymodel_p.h"
+#include <QtCore/qpointer.h>
QT_REQUIRE_CONFIG(completer);
diff --git a/src/widgets/util/qflickgesture.cpp b/src/widgets/util/qflickgesture.cpp
index 1082eeeae1..f4198daa77 100644
--- a/src/widgets/util/qflickgesture.cpp
+++ b/src/widgets/util/qflickgesture.cpp
@@ -38,43 +38,19 @@ static QMouseEvent *copyMouseEvent(QEvent *e)
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseMove: {
- QMouseEvent *me = static_cast<QMouseEvent *>(e);
- QMouseEvent *cme = new QMouseEvent(me->type(), QPoint(0, 0), me->scenePosition(), me->globalPosition(),
- me->button(), me->buttons(), me->modifiers(), me->source());
- return cme;
+ return static_cast<QMouseEvent *>(e->clone());
}
#if QT_CONFIG(graphicsview)
case QEvent::GraphicsSceneMousePress:
case QEvent::GraphicsSceneMouseRelease:
case QEvent::GraphicsSceneMouseMove: {
QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent *>(e);
-#if 1
QEvent::Type met = me->type() == QEvent::GraphicsSceneMousePress ? QEvent::MouseButtonPress :
(me->type() == QEvent::GraphicsSceneMouseRelease ? QEvent::MouseButtonRelease : QEvent::MouseMove);
QMouseEvent *cme = new QMouseEvent(met, QPoint(0, 0), QPoint(0, 0), me->screenPos(),
me->button(), me->buttons(), me->modifiers(), me->source());
+ cme->setTimestamp(me->timestamp());
return cme;
-#else
- QGraphicsSceneMouseEvent *copy = new QGraphicsSceneMouseEvent(me->type());
- copy->setPos(me->pos());
- copy->setScenePos(me->scenePos());
- copy->setScreenPos(me->screenPos());
- for (int i = 0x1; i <= 0x10; i <<= 1) {
- Qt::MouseButton button = Qt::MouseButton(i);
- copy->setButtonDownPos(button, me->buttonDownPos(button));
- copy->setButtonDownScenePos(button, me->buttonDownScenePos(button));
- copy->setButtonDownScreenPos(button, me->buttonDownScreenPos(button));
- }
- copy->setLastPos(me->lastPos());
- copy->setLastScenePos(me->lastScenePos());
- copy->setLastScreenPos(me->lastScreenPos());
- copy->setButtons(me->buttons());
- copy->setButton(me->button());
- copy->setModifiers(me->modifiers());
- copy->setSource(me->source());
- copy->setFlags(me->flags());
- return copy;
-#endif
}
#endif // QT_CONFIG(graphicsview)
default:
@@ -190,22 +166,6 @@ public:
mouseTarget = nullptr;
} else if (mouseTarget) {
// we did send a press, so we need to fake a release now
-
- // release all pressed mouse buttons
- /* Qt::MouseButtons mouseButtons = QGuiApplication::mouseButtons();
- for (int i = 0; i < 32; ++i) {
- if (mouseButtons & (1 << i)) {
- Qt::MouseButton b = static_cast<Qt::MouseButton>(1 << i);
- mouseButtons &= ~b;
- QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX);
-
- qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
- QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway,
- b, mouseButtons, QGuiApplication::keyboardModifiers());
- sendMouseEvent(&re);
- }
- }*/
-
QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX);
qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
@@ -265,6 +225,7 @@ protected:
mouseTarget->topLevelWidget()->mapFromGlobal(me->globalPosition()), me->globalPosition(),
me->button(), me->buttons(), me->modifiers(),
me->source(), me->pointingDevice());
+ copy.setTimestamp(me->timestamp());
qt_sendSpontaneousEvent(mouseTarget, &copy);
}
diff --git a/src/widgets/util/qflickgesture_p.h b/src/widgets/util/qflickgesture_p.h
index b1ae770753..e8306b77e8 100644
--- a/src/widgets/util/qflickgesture_p.h
+++ b/src/widgets/util/qflickgesture_p.h
@@ -20,6 +20,8 @@
#include "qgesturerecognizer.h"
#include "private/qgesture_p.h"
#include "qscroller.h"
+
+#include <QtCore/qpointer.h>
#include "qscopedpointer.h"
#ifndef QT_NO_GESTURES
diff --git a/src/widgets/util/qscroller.cpp b/src/widgets/util/qscroller.cpp
index c781df364a..1192a0be60 100644
--- a/src/widgets/util/qscroller.cpp
+++ b/src/widgets/util/qscroller.cpp
@@ -27,21 +27,16 @@
#include <qnumeric.h>
#include <QtDebug>
-
+#include <QtCore/qloggingcategory.h>
QT_BEGIN_NAMESPACE
-bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
-
-//#define QSCROLLER_DEBUG
+Q_LOGGING_CATEGORY(lcScroller, "qt.widgets.scroller")
-#ifdef QSCROLLER_DEBUG
-# define qScrollerDebug qDebug
-#else
-# define qScrollerDebug while (false) qDebug
-#endif
+bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
+namespace {
QDebug &operator<<(QDebug &dbg, const QScrollerPrivate::ScrollSegment &s)
{
dbg << "\n Time: start:" << s.startTime << " duration:" << s.deltaTime << " stop progress:" << s.stopProgress;
@@ -49,7 +44,7 @@ QDebug &operator<<(QDebug &dbg, const QScrollerPrivate::ScrollSegment &s)
dbg << "\n Curve: type:" << s.curve.type() << "\n";
return dbg;
}
-
+} // anonymous namespace
// a few helper operators to make the code below a lot more readable:
// otherwise a lot of ifs would have to be multi-line to check both the x
@@ -120,7 +115,8 @@ static qreal differentialForProgress(const QEasingCurve &curve, qreal pos)
qreal right = (pos >= qreal(0.5)) ? pos : pos + qreal(dx);
qreal d = (curve.valueForProgress(right) - curve.valueForProgress(left)) / qreal(dx);
- //qScrollerDebug() << "differentialForProgress(type: " << curve.type() << ", pos: " << pos << ") = " << d;
+ qCDebug(lcScroller) << "differentialForProgress(type: " << curve.type()
+ << ", pos: " << pos << ") = " << d;
return d;
}
@@ -132,7 +128,8 @@ static qreal progressForValue(const QEasingCurve &curve, qreal value)
{
if (Q_UNLIKELY(curve.type() >= QEasingCurve::InElastic &&
curve.type() < QEasingCurve::Custom)) {
- qWarning("progressForValue(): QEasingCurves of type %d do not have an inverse, since they are not injective.", curve.type());
+ qWarning("progressForValue(): QEasingCurves of type %d do not have an "
+ "inverse, since they are not injective.", curve.type());
return value;
}
if (value < qreal(0) || value > qreal(1))
@@ -224,9 +221,6 @@ private:
The scroller uses the global QAbstractAnimation timer to generate its QScrollEvents. This
can be changed with QScrollerProperties::FrameRate on a per-QScroller basis.
- The \l {Dir View Example} shows one way to use a QScroller with a QTreeView.
- An example in the \c scroller examples directory also demonstrates QScroller.
-
Even though this kinetic scroller has a large number of settings available via
QScrollerProperties, we recommend that you leave them all at their default, platform optimized
values. Before changing them you can experiment with the \c plot example in
@@ -574,14 +568,18 @@ QPointF QScroller::velocity() const
if (!d->xSegments.isEmpty()) {
const QScrollerPrivate::ScrollSegment &s = d->xSegments.head();
qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime);
- qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) * sp->decelerationFactor * qreal(0.5) * differentialForProgress(s.curve, progress);
+ qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000)
+ * sp->decelerationFactor * qreal(0.5)
+ * differentialForProgress(s.curve, progress);
vel.setX(v);
}
if (!d->ySegments.isEmpty()) {
const QScrollerPrivate::ScrollSegment &s = d->ySegments.head();
qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime);
- qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) * sp->decelerationFactor * qreal(0.5) * differentialForProgress(s.curve, progress);
+ qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000)
+ * sp->decelerationFactor * qreal(0.5)
+ * differentialForProgress(s.curve, progress);
vel.setY(v);
}
return vel;
@@ -650,7 +648,8 @@ void QScroller::scrollTo(const QPointF &pos, int scrollTime)
if (!qIsNaN(snapY))
newpos.setY(snapY);
- qScrollerDebug() << "QScroller::scrollTo(req:" << pos << " [pix] / snap:" << newpos << ", " << scrollTime << " [ms])";
+ qCDebug(lcScroller) << "QScroller::scrollTo(req:" << pos << " [pix] / snap:"
+ << newpos << ", " << scrollTime << " [ms])";
if (newpos == d->contentPosition + d->overshootPosition)
return;
@@ -714,8 +713,9 @@ void QScroller::ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin,
QSizeF visible = d->viewportSize;
QRectF visibleRect(startPos, visible);
- qScrollerDebug() << "QScroller::ensureVisible(" << rect << " [pix], " << xmargin << " [pix], " << ymargin << " [pix], " << scrollTime << "[ms])";
- qScrollerDebug() << " --> content position:" << d->contentPosition;
+ qCDebug(lcScroller) << "QScroller::ensureVisible(" << rect << " [pix], " << xmargin
+ << " [pix], " << ymargin << " [pix], " << scrollTime << "[ms])";
+ qCDebug(lcScroller) << " --> content position:" << d->contentPosition;
if (visibleRect.contains(marginRect))
return;
@@ -943,7 +943,8 @@ bool QScroller::handleInput(Input input, const QPointF &position, qint64 timesta
{
Q_D(QScroller);
- qScrollerDebug() << "QScroller::handleInput(" << input << ", " << d->stateName(d->state) << ", " << position << ", " << timestamp << ')';
+ qCDebug(lcScroller) << "QScroller::handleInput(" << input << ", " << d->stateName(d->state)
+ << ", " << position << ", " << timestamp << ')';
struct statechange {
State state;
Input input;
@@ -1012,7 +1013,8 @@ void QScrollerPrivate::updateVelocity(const QPointF &deltaPixelRaw, qint64 delta
const QScrollerPropertiesPrivate *sp = properties.d.data();
QPointF deltaPixel = deltaPixelRaw;
- qScrollerDebug() << "QScroller::updateVelocity(" << deltaPixelRaw << " [delta pix], " << deltaTime << " [delta ms])";
+ qCDebug(lcScroller) << "QScroller::updateVelocity(" << deltaPixelRaw
+ << " [delta pix], " << deltaTime << " [delta ms])";
// faster than 2.5mm/ms seems bogus (that would be a screen height in ~20 ms)
if (((deltaPixelRaw / qreal(deltaTime)).manhattanLength() / ((ppm.x() + ppm.y()) / 2) * 1000) > qreal(2.5))
@@ -1027,7 +1029,8 @@ void QScrollerPrivate::updateVelocity(const QPointF &deltaPixelRaw, qint64 delta
// only smooth if we already have a release velocity and only if the
// user hasn't stopped to move his finger for more than 100ms
if ((releaseVelocity != QPointF(0, 0)) && (deltaTime < 100)) {
- qScrollerDebug() << "SMOOTHED from " << newv << " to " << newv * smoothing + releaseVelocity * (qreal(1) - smoothing);
+ qCDebug(lcScroller) << "SMOOTHED from " << newv << " to "
+ << newv * smoothing + releaseVelocity * (qreal(1) - smoothing);
// smooth x or y only if the new velocity is either 0 or at least in
// the same direction of the release velocity
if (!newv.x() || (qSign(releaseVelocity.x()) == qSign(newv.x())))
@@ -1035,15 +1038,17 @@ void QScrollerPrivate::updateVelocity(const QPointF &deltaPixelRaw, qint64 delta
if (!newv.y() || (qSign(releaseVelocity.y()) == qSign(newv.y())))
newv.setY(newv.y() * smoothing + releaseVelocity.y() * (qreal(1) - smoothing));
} else
- qScrollerDebug() << "NO SMOOTHING to " << newv;
+ qCDebug(lcScroller) << "NO SMOOTHING to " << newv;
releaseVelocity.setX(qBound(-sp->maximumVelocity, newv.x(), sp->maximumVelocity));
releaseVelocity.setY(qBound(-sp->maximumVelocity, newv.y(), sp->maximumVelocity));
- qScrollerDebug() << " --> new velocity:" << releaseVelocity;
+ qCDebug(lcScroller) << " --> new velocity:" << releaseVelocity;
}
-void QScrollerPrivate::pushSegment(ScrollType type, qreal deltaTime, qreal stopProgress, qreal startPos, qreal deltaPos, qreal stopPos, QEasingCurve::Type curve, Qt::Orientation orientation)
+void QScrollerPrivate::pushSegment(ScrollType type, qreal deltaTime, qreal stopProgress,
+ qreal startPos, qreal deltaPos, qreal stopPos,
+ QEasingCurve::Type curve, Qt::Orientation orientation)
{
if (startPos == stopPos || deltaPos == 0)
return;
@@ -1072,7 +1077,7 @@ void QScrollerPrivate::pushSegment(ScrollType type, qreal deltaTime, qreal stopP
else
ySegments.enqueue(s);
- qScrollerDebug() << "+++ Added a new ScrollSegment: " << s;
+ qCDebug(lcScroller) << "+++ Added a new ScrollSegment: " << s;
}
@@ -1158,7 +1163,8 @@ bool QScrollerPrivate::scrollingSegmentsValid(Qt::Orientation orientation) const
/*! \internal
Creates the sections needed to scroll to the specific \a endPos to the segments queue.
*/
-void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal endPos, Qt::Orientation orientation, ScrollType type)
+void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal endPos,
+ Qt::Orientation orientation, ScrollType type)
{
Q_UNUSED(v);
@@ -1167,7 +1173,8 @@ void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal en
else
ySegments.clear();
- qScrollerDebug() << "+++ createScrollToSegments: t:" << deltaTime << "ep:" << endPos << "o:" << int(orientation);
+ qCDebug(lcScroller) << "+++ createScrollToSegments: t:" << deltaTime << "ep:"
+ << endPos << "o:" << int(orientation);
const QScrollerPropertiesPrivate *sp = properties.d.data();
@@ -1175,8 +1182,10 @@ void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal en
: contentPosition.y() + overshootPosition.y();
qreal deltaPos = (endPos - startPos) / 2;
- pushSegment(type, deltaTime * qreal(0.3), qreal(1.0), startPos, deltaPos, startPos + deltaPos, QEasingCurve::InQuad, orientation);
- pushSegment(type, deltaTime * qreal(0.7), qreal(1.0), startPos + deltaPos, deltaPos, endPos, sp->scrollingCurve.type(), orientation);
+ pushSegment(type, deltaTime * qreal(0.3), qreal(1.0), startPos, deltaPos, startPos + deltaPos,
+ QEasingCurve::InQuad, orientation);
+ pushSegment(type, deltaTime * qreal(0.7), qreal(1.0), startPos + deltaPos, deltaPos, endPos,
+ sp->scrollingCurve.type(), orientation);
}
/*! \internal
@@ -1210,13 +1219,15 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos,
bool noOvershoot = (policy == QScrollerProperties::OvershootAlwaysOff) || !sp->overshootScrollDistanceFactor;
bool canOvershoot = !noOvershoot && (alwaysOvershoot || maxPos);
- qScrollerDebug() << "+++ createScrollingSegments: s:" << startPos << "maxPos:" << maxPos << "o:" << int(orientation);
+ qCDebug(lcScroller) << "+++ createScrollingSegments: s:" << startPos << "maxPos:" << maxPos
+ << "o:" << int(orientation);
- qScrollerDebug() << "v = " << v << ", decelerationFactor = " << sp->decelerationFactor << ", curveType = " << sp->scrollingCurve.type();
+ qCDebug(lcScroller) << "v = " << v << ", decelerationFactor = " << sp->decelerationFactor
+ << ", curveType = " << sp->scrollingCurve.type();
qreal endPos = startPos + deltaPos;
- qScrollerDebug() << " Real Delta:" << deltaPos;
+ qCDebug(lcScroller) << " Real Delta:" << deltaPos;
// -- check if are in overshoot and end in overshoot
if ((startPos < minPos && endPos < minPos) ||
@@ -1224,7 +1235,8 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos,
qreal stopPos = endPos < minPos ? minPos : maxPos;
qreal oDeltaTime = sp->overshootScrollTime;
- pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), startPos, stopPos - startPos, stopPos, sp->scrollingCurve.type(), orientation);
+ pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), startPos,
+ stopPos - startPos, stopPos, sp->scrollingCurve.type(), orientation);
return;
}
@@ -1233,7 +1245,7 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos,
qreal lowerSnapPos = nextSnapPos(startPos, -1, orientation);
qreal higherSnapPos = nextSnapPos(startPos, 1, orientation);
- qScrollerDebug() << " Real Delta:" << lowerSnapPos << '-' << nextSnap << '-' <<higherSnapPos;
+ qCDebug(lcScroller) << " Real Delta:" << lowerSnapPos << '-' << nextSnap << '-' <<higherSnapPos;
// - check if we can reach another snap point
if (nextSnap > higherSnapPos || qIsNaN(higherSnapPos))
@@ -1243,7 +1255,7 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos,
if (qAbs(v) < sp->minimumVelocity) {
- qScrollerDebug() << "### below minimum Vel" << orientation;
+ qCDebug(lcScroller) << "### below minimum Vel" << orientation;
// - no snap points or already at one
if (qIsNaN(nextSnap) || nextSnap == startPos)
@@ -1267,8 +1279,10 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos,
deltaPos = endPos - startPos;
qreal midPos = startPos + deltaPos * qreal(0.3);
- pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.3), qreal(1.0), startPos, midPos - startPos, midPos, QEasingCurve::InQuad, orientation);
- pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.7), qreal(1.0), midPos, endPos - midPos, endPos, sp->scrollingCurve.type(), orientation);
+ pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.3), qreal(1.0), startPos,
+ midPos - startPos, midPos, QEasingCurve::InQuad, orientation);
+ pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.7), qreal(1.0), midPos,
+ endPos - midPos, endPos, sp->scrollingCurve.type(), orientation);
return;
}
@@ -1293,35 +1307,43 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos,
} else if (endPos < minPos || endPos > maxPos) {
qreal stopPos = endPos < minPos ? minPos : maxPos;
- qScrollerDebug() << "Overshoot: delta:" << (stopPos - startPos);
+ qCDebug(lcScroller) << "Overshoot: delta:" << (stopPos - startPos);
qreal stopProgress = progressForValue(sp->scrollingCurve, qAbs((stopPos - startPos) / deltaPos));
if (!canOvershoot) {
- qScrollerDebug() << "Overshoot stopp:" << stopProgress;
+ qCDebug(lcScroller) << "Overshoot stopp:" << stopProgress;
- pushSegment(ScrollTypeFlick, deltaTime, stopProgress, startPos, endPos, stopPos, sp->scrollingCurve.type(), orientation);
+ pushSegment(ScrollTypeFlick, deltaTime, stopProgress, startPos, endPos, stopPos,
+ sp->scrollingCurve.type(), orientation);
} else {
qreal oDeltaTime = sp->overshootScrollTime;
qreal oStopProgress = qMin(stopProgress + oDeltaTime * qreal(0.3) / deltaTime, qreal(1));
qreal oDistance = startPos + deltaPos * sp->scrollingCurve.valueForProgress(oStopProgress) - stopPos;
qreal oMaxDistance = qSign(oDistance) * (viewSize * sp->overshootScrollDistanceFactor);
- qScrollerDebug() << "1 oDistance:" << oDistance << "Max:" << oMaxDistance << "stopP/oStopP" << stopProgress << oStopProgress;
+ qCDebug(lcScroller) << "1 oDistance:" << oDistance << "Max:" << oMaxDistance
+ << "stopP/oStopP" << stopProgress << oStopProgress;
if (qAbs(oDistance) > qAbs(oMaxDistance)) {
- oStopProgress = progressForValue(sp->scrollingCurve, qAbs((stopPos + oMaxDistance - startPos) / deltaPos));
+ oStopProgress = progressForValue(sp->scrollingCurve,
+ qAbs((stopPos + oMaxDistance - startPos) / deltaPos));
oDistance = oMaxDistance;
- qScrollerDebug() << "2 oDistance:" << oDistance << "Max:" << oMaxDistance << "stopP/oStopP" << stopProgress << oStopProgress;
+ qCDebug(lcScroller) << "2 oDistance:" << oDistance << "Max:" << oMaxDistance
+ << "stopP/oStopP" << stopProgress << oStopProgress;
}
- pushSegment(ScrollTypeFlick, deltaTime, oStopProgress, startPos, deltaPos, stopPos + oDistance, sp->scrollingCurve.type(), orientation);
- pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), stopPos + oDistance, -oDistance, stopPos, sp->scrollingCurve.type(), orientation);
+ pushSegment(ScrollTypeFlick, deltaTime, oStopProgress, startPos, deltaPos,
+ stopPos + oDistance, sp->scrollingCurve.type(), orientation);
+ pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0),
+ stopPos + oDistance, -oDistance, stopPos, sp->scrollingCurve.type(),
+ orientation);
}
return;
}
- pushSegment(ScrollTypeFlick, deltaTime, qreal(1.0), startPos, deltaPos, endPos, sp->scrollingCurve.type(), orientation);
+ pushSegment(ScrollTypeFlick, deltaTime, qreal(1.0), startPos, deltaPos, endPos,
+ sp->scrollingCurve.type(), orientation);
}
@@ -1346,8 +1368,10 @@ void QScrollerPrivate::createScrollingSegments(const QPointF &v,
// deltaPos = pos(deltaTime)
QVector2D vel(v);
- qreal deltaTime = (qreal(2) * vel.length()) / (sp->decelerationFactor * differentialForProgress(sp->scrollingCurve, 0));
- QPointF deltaPos = (vel.normalized() * QVector2D(ppm)).toPointF() * deltaTime * deltaTime * qreal(0.5) * sp->decelerationFactor;
+ qreal deltaTime = (qreal(2) * vel.length())
+ / (sp->decelerationFactor * differentialForProgress(sp->scrollingCurve, 0));
+ QPointF deltaPos = (vel.normalized() * QVector2D(ppm)).toPointF()
+ * deltaTime * deltaTime * qreal(0.5) * sp->decelerationFactor;
createScrollingSegments(v.x(), startPos.x(), deltaTime, deltaPos.x(),
Qt::Horizontal);
@@ -1365,7 +1389,8 @@ bool QScrollerPrivate::prepareScrolling(const QPointF &position)
spe.ignore();
sendEvent(target, &spe);
- qScrollerDebug() << "QScrollPrepareEvent returned from" << target << "with" << spe.isAccepted() << "mcp:" << spe.contentPosRange() << "cp:" << spe.contentPos();
+ qCDebug(lcScroller) << "QScrollPrepareEvent returned from" << target << "with" << spe.isAccepted()
+ << "mcp:" << spe.contentPosRange() << "cp:" << spe.contentPos();
if (spe.isAccepted()) {
QPointF oldContentPos = contentPosition + overshootPosition;
QPointF contentDelta = spe.contentPos() - oldContentPos;
@@ -1424,7 +1449,8 @@ void QScrollerPrivate::handleDrag(const QPointF &position, qint64 timestamp)
if (dx || dy) {
bool vertical = (dy > dx);
qreal alpha = qreal(vertical ? dx : dy) / qreal(vertical ? dy : dx);
- //qScrollerDebug() << "QScroller::handleDrag() -- axis lock:" << alpha << " / " << axisLockThreshold << "- isvertical:" << vertical << "- dx:" << dx << "- dy:" << dy;
+ qCDebug(lcScroller) << "QScroller::handleDrag() -- axis lock:" << alpha << " / " << sp->axisLockThreshold
+ << "- isvertical:" << vertical << "- dx:" << dx << "- dy:" << dy;
if (alpha <= sp->axisLockThreshold) {
if (vertical)
deltaPixel.setX(0);
@@ -1451,15 +1477,7 @@ void QScrollerPrivate::handleDrag(const QPointF &position, qint64 timestamp)
releaseVelocity.setY(0);
}
-// if (firstDrag) {
-// // Do not delay the first drag
-// setContentPositionHelper(q->contentPosition() - overshootDistance - deltaPixel);
-// dragDistance = QPointF(0, 0);
-// } else {
dragDistance += deltaPixel;
-// }
-//qScrollerDebug() << "######################" << deltaPixel << position.y() << lastPosition.y();
-
lastPosition = position;
lastTimestamp = timestamp;
}
@@ -1551,7 +1569,7 @@ bool QScrollerPrivate::moveWhileDragging(const QPointF &position, qint64 timesta
void QScrollerPrivate::timerEventWhileDragging()
{
if (dragDistance != QPointF(0, 0)) {
- qScrollerDebug() << "QScroller::timerEventWhileDragging() -- dragDistance:" << dragDistance;
+ qCDebug(lcScroller) << "QScroller::timerEventWhileDragging() -- dragDistance:" << dragDistance;
setContentPositionHelperDragging(-dragDistance);
dragDistance = QPointF(0, 0);
@@ -1596,7 +1614,8 @@ bool QScrollerPrivate::releaseWhileDragging(const QPointF &position, qint64 time
QPointF ppm = q->pixelPerMeter();
createScrollingSegments(releaseVelocity, contentPosition + overshootPosition, ppm);
- qScrollerDebug() << "QScroller::releaseWhileDragging() -- velocity:" << releaseVelocity << "-- minimum velocity:" << sp->minimumVelocity << "overshoot" << overshootPosition;
+ qCDebug(lcScroller) << "QScroller::releaseWhileDragging() -- velocity:" << releaseVelocity
+ << "-- minimum velocity:" << sp->minimumVelocity << "overshoot" << overshootPosition;
if (xSegments.isEmpty() && ySegments.isEmpty())
setState(QScroller::Inactive);
@@ -1608,7 +1627,7 @@ bool QScrollerPrivate::releaseWhileDragging(const QPointF &position, qint64 time
void QScrollerPrivate::timerEventWhileScrolling()
{
- qScrollerDebug("QScroller::timerEventWhileScrolling()");
+ qCDebug(lcScroller) << "QScroller::timerEventWhileScrolling()";
setContentPositionHelperScrolling();
if (xSegments.isEmpty() && ySegments.isEmpty())
@@ -1643,7 +1662,7 @@ void QScrollerPrivate::setState(QScroller::State newstate)
if (state == newstate)
return;
- qScrollerDebug() << q << "QScroller::setState(" << stateName(newstate) << ')';
+ qCDebug(lcScroller) << q << "QScroller::setState(" << stateName(newstate) << ')';
switch (newstate) {
case QScroller::Inactive:
@@ -1721,8 +1740,8 @@ void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos)
QPointF oldPos = contentPosition + overshootPosition;
QPointF newPos = oldPos + deltaPos;
- qScrollerDebug() << "QScroller::setContentPositionHelperDragging(" << deltaPos << " [pix])";
- qScrollerDebug() << " --> overshoot:" << overshootPosition << "- old pos:" << oldPos << "- new pos:" << newPos;
+ qCDebug(lcScroller) << "QScroller::setContentPositionHelperDragging(" << deltaPos << " [pix])";
+ qCDebug(lcScroller) << " --> overshoot:" << overshootPosition << "- old pos:" << oldPos << "- new pos:" << newPos;
QPointF newClampedPos = clampToRect(newPos, contentPosRange);
@@ -1744,8 +1763,9 @@ void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos)
qreal maxOvershootX = viewportSize.width() * sp->overshootDragDistanceFactor;
qreal maxOvershootY = viewportSize.height() * sp->overshootDragDistanceFactor;
- qScrollerDebug() << " --> noOs:" << noOvershootX << "drf:" << sp->overshootDragResistanceFactor << "mdf:" << sp->overshootScrollDistanceFactor << "ossP:"<<sp->hOvershootPolicy;
- qScrollerDebug() << " --> canOS:" << canOvershootX << "newOS:" << newOvershootX << "maxOS:" << maxOvershootX;
+ qCDebug(lcScroller) << " --> noOs:" << noOvershootX << "drf:" << sp->overshootDragResistanceFactor
+ << "mdf:" << sp->overshootScrollDistanceFactor << "ossP:"<<sp->hOvershootPolicy;
+ qCDebug(lcScroller) << " --> canOS:" << canOvershootX << "newOS:" << newOvershootX << "maxOS:" << maxOvershootX;
if (sp->overshootDragResistanceFactor) {
newOvershootX *= sp->overshootDragResistanceFactor;
@@ -1765,8 +1785,8 @@ void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos)
sendEvent(target, &se);
firstScroll = false;
- qScrollerDebug() << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition <<
- "- overshoot x/y?:" << overshootPosition;
+ qCDebug(lcScroller) << " --> new position:" << newClampedPos << "- new overshoot:"
+ << overshootPosition << "- overshoot x/y?:" << overshootPosition;
}
@@ -1806,7 +1826,7 @@ void QScrollerPrivate::setContentPositionHelperScrolling()
newPos.setY(nextSegmentPosition(ySegments, now, newPos.y()));
// -- set the position and handle overshoot
- qScrollerDebug() << "QScroller::setContentPositionHelperScrolling()\n"
+ qCDebug(lcScroller) << "QScroller::setContentPositionHelperScrolling()\n"
" --> overshoot:" << overshootPosition << "- new pos:" << newPos;
QPointF newClampedPos = clampToRect(newPos, contentPosRange);
@@ -1814,11 +1834,12 @@ void QScrollerPrivate::setContentPositionHelperScrolling()
overshootPosition = newPos - newClampedPos;
contentPosition = newClampedPos;
- QScrollEvent se(contentPosition, overshootPosition, firstScroll ? QScrollEvent::ScrollStarted : QScrollEvent::ScrollUpdated);
+ QScrollEvent se(contentPosition, overshootPosition, firstScroll ? QScrollEvent::ScrollStarted
+ : QScrollEvent::ScrollUpdated);
sendEvent(target, &se);
firstScroll = false;
- qScrollerDebug() << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition;
+ qCDebug(lcScroller) << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition;
}
/*! \internal
@@ -1949,7 +1970,8 @@ qreal QScrollerPrivate::nextSnapPos(qreal p, int dir, Qt::Orientation orientatio
This enum contains the different QScroller states.
\value Inactive The scroller is not scrolling and nothing is pressed.
- \value Pressed A touch event was received or the mouse button was pressed but the scroll area is currently not dragged.
+ \value Pressed A touch event was received or the mouse button was pressed
+ but the scroll area is currently not dragged.
\value Dragging The scroll area is currently following the touch point or mouse.
\value Scrolling The scroll area is moving on it's own.
*/
diff --git a/src/widgets/util/qsystemtrayicon.cpp b/src/widgets/util/qsystemtrayicon.cpp
index 903cb4380c..2a55f014e1 100644
--- a/src/widgets/util/qsystemtrayicon.cpp
+++ b/src/widgets/util/qsystemtrayicon.cpp
@@ -61,7 +61,7 @@ static QIcon messageIcon2qIcon(QSystemTrayIcon::MessageIcon icon)
called the \e{system tray} or \e{notification area}, where long-running
applications can display icons and short messages.
- \image system-tray.png The system tray on Windows XP.
+ \image system-tray.webp The system tray on Windows 10.
The QSystemTrayIcon class can be used on the following platforms:
@@ -154,9 +154,6 @@ QSystemTrayIcon::~QSystemTrayIcon()
The menu will pop up when the user requests the context menu for the system
tray icon by clicking the mouse button.
- On \macos, this is currently converted to a NSMenu, so the
- aboutToHide() signal is not emitted.
-
\note The system tray icon does not take ownership of the menu. You must
ensure that it is deleted at the appropriate time by, for example, creating
the menu with a suitable parent object.
@@ -165,12 +162,16 @@ void QSystemTrayIcon::setContextMenu(QMenu *menu)
{
Q_D(QSystemTrayIcon);
QMenu *oldMenu = d->menu.data();
+ if (oldMenu == menu)
+ return;
+
d->menu = menu;
d->updateMenu_sys();
- if (oldMenu != menu && d->qpa_sys) {
+
+ if (d->qpa_sys) {
// Show the QMenu-based menu for QPA plugins that do not provide native menus
if (oldMenu && !oldMenu->platformMenu())
- QObject::disconnect(d->qpa_sys, &QPlatformSystemTrayIcon::contextMenuRequested, menu, nullptr);
+ QObject::disconnect(d->qpa_sys, &QPlatformSystemTrayIcon::contextMenuRequested, oldMenu, nullptr);
if (menu && !menu->platformMenu()) {
QObject::connect(d->qpa_sys, &QPlatformSystemTrayIcon::contextMenuRequested,
menu,
diff --git a/src/widgets/util/qsystemtrayicon_qpa.cpp b/src/widgets/util/qsystemtrayicon_qpa.cpp
index e156cb1e57..63b24873db 100644
--- a/src/widgets/util/qsystemtrayicon_qpa.cpp
+++ b/src/widgets/util/qsystemtrayicon_qpa.cpp
@@ -59,9 +59,13 @@ void QSystemTrayIconPrivate::updateIcon_sys()
void QSystemTrayIconPrivate::updateMenu_sys()
{
#if QT_CONFIG(menu)
- if (qpa_sys && menu) {
- addPlatformMenu(menu);
- qpa_sys->updateMenu(menu->platformMenu());
+ if (qpa_sys) {
+ if (menu) {
+ addPlatformMenu(menu);
+ qpa_sys->updateMenu(menu->platformMenu());
+ } else {
+ qpa_sys->updateMenu(nullptr);
+ }
}
#endif
}
diff --git a/src/widgets/widgets/qabstractbutton.cpp b/src/widgets/widgets/qabstractbutton.cpp
index bac4a29cff..3a5fbe1b90 100644
--- a/src/widgets/widgets/qabstractbutton.cpp
+++ b/src/widgets/widgets/qabstractbutton.cpp
@@ -8,9 +8,9 @@
#endif
#if QT_CONFIG(buttongroup)
#include "qbuttongroup.h"
-#include "private/qapplication_p.h"
#include "private/qbuttongroup_p.h"
#endif
+#include "private/qapplication_p.h"
#include "qabstractbutton_p.h"
#include "qevent.h"
#include "qpainter.h"
@@ -21,6 +21,8 @@
#endif
#include <qpa/qplatformtheme.h>
+#include <QtCore/qpointer.h>
+
#include <algorithm>
QT_BEGIN_NAMESPACE
@@ -613,12 +615,13 @@ void QAbstractButton::setChecked(bool checked)
if (guard)
d->emitToggled(checked);
-
#if QT_CONFIG(accessibility)
- QAccessible::State s;
- s.checked = true;
- QAccessibleStateChangeEvent event(this, s);
- QAccessible::updateAccessibility(&event);
+ if (guard) {
+ QAccessible::State s;
+ s.checked = true;
+ QAccessibleStateChangeEvent event(this, s);
+ QAccessible::updateAccessibility(&event);
+ }
#endif
}
diff --git a/src/widgets/widgets/qabstractscrollarea.cpp b/src/widgets/widgets/qabstractscrollarea.cpp
index 91fedea650..f6f8e8b795 100644
--- a/src/widgets/widgets/qabstractscrollarea.cpp
+++ b/src/widgets/widgets/qabstractscrollarea.cpp
@@ -295,22 +295,25 @@ void QAbstractScrollAreaPrivate::layoutChildren()
void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrollbar, bool *needVerticalScrollbar)
{
Q_Q(QAbstractScrollArea);
- bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, hbar);
+ QStyleOptionSlider barOpt;
+
+ hbar->initStyleOption(&barOpt);
+ bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &barOpt, hbar);
bool needh = *needHorizontalScrollbar || ((hbarpolicy != Qt::ScrollBarAlwaysOff) && ((hbarpolicy == Qt::ScrollBarAlwaysOn && !htransient)
|| ((hbarpolicy == Qt::ScrollBarAsNeeded || htransient)
&& hbar->minimum() < hbar->maximum() && !hbar->sizeHint().isEmpty())));
+ const int hscrollOverlap = hbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &barOpt, hbar);
- bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, vbar);
+ vbar->initStyleOption(&barOpt);
+ bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &barOpt, vbar);
bool needv = *needVerticalScrollbar || ((vbarpolicy != Qt::ScrollBarAlwaysOff) && ((vbarpolicy == Qt::ScrollBarAlwaysOn && !vtransient)
|| ((vbarpolicy == Qt::ScrollBarAsNeeded || vtransient)
&& vbar->minimum() < vbar->maximum() && !vbar->sizeHint().isEmpty())));
+ const int vscrollOverlap = vbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &barOpt, vbar);
QStyleOption opt(0);
opt.initFrom(q);
- const int hscrollOverlap = hbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &opt, hbar);
- const int vscrollOverlap = vbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &opt, vbar);
-
const int hsbExt = hbar->sizeHint().height();
const int vsbExt = vbar->sizeHint().width();
const QPoint extPoint(vsbExt, hsbExt);
@@ -532,15 +535,13 @@ scrolling range.
QSize QAbstractScrollArea::maximumViewportSize() const
{
Q_D(const QAbstractScrollArea);
- int hsbExt = d->hbar->sizeHint().height();
- int vsbExt = d->vbar->sizeHint().width();
-
int f = 2 * d->frameWidth;
QSize max = size() - QSize(f + d->left + d->right, f + d->top + d->bottom);
+ // Count the sizeHint of the bar only if it is displayed.
if (d->vbarpolicy == Qt::ScrollBarAlwaysOn)
- max.rwidth() -= vsbExt;
+ max.rwidth() -= d->vbar->sizeHint().width();
if (d->hbarpolicy == Qt::ScrollBarAlwaysOn)
- max.rheight() -= hsbExt;
+ max.rheight() -= d->hbar->sizeHint().height();
return max;
}
@@ -1099,7 +1100,7 @@ void QAbstractScrollArea::resizeEvent(QResizeEvent *)
This event handler can be reimplemented in a subclass to receive
paint events (passed in \a event), for the viewport() widget.
- \note If you open a painter, make sure to open it on the viewport().
+ \note If you create a QPainter, it must operate on the viewport().
\sa QWidget::paintEvent()
*/
@@ -1342,10 +1343,14 @@ bool QAbstractScrollAreaPrivate::canStartScrollingAt(const QPoint &startPos) con
void QAbstractScrollAreaPrivate::flashScrollBars()
{
- bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, hbar);
+ QStyleOptionSlider opt;
+ hbar->initStyleOption(&opt);
+
+ bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, hbar);
if ((hbarpolicy != Qt::ScrollBarAlwaysOff) && (hbarpolicy == Qt::ScrollBarAsNeeded || htransient))
hbar->d_func()->flash();
- bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, vbar);
+ vbar->initStyleOption(&opt);
+ bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, vbar);
if ((vbarpolicy != Qt::ScrollBarAlwaysOff) && (vbarpolicy == Qt::ScrollBarAsNeeded || vtransient))
vbar->d_func()->flash();
}
@@ -1426,9 +1431,9 @@ QSize QAbstractScrollArea::sizeHint() const
if (!d->sizeHint.isValid() || d->sizeAdjustPolicy == QAbstractScrollArea::AdjustToContents) {
const int f = 2 * d->frameWidth;
- const QSize frame( f, f );
- const bool vbarHidden = d->vbar->isHidden() || d->vbarpolicy == Qt::ScrollBarAlwaysOff;
- const bool hbarHidden = d->hbar->isHidden() || d->hbarpolicy == Qt::ScrollBarAlwaysOff;
+ const QSize frame(f, f);
+ const bool vbarHidden = !d->vbar->isVisibleTo(this) || d->vbarpolicy == Qt::ScrollBarAlwaysOff;
+ const bool hbarHidden = !d->vbar->isVisibleTo(this) || d->hbarpolicy == Qt::ScrollBarAlwaysOff;
const QSize scrollbars(vbarHidden ? 0 : d->vbar->sizeHint().width(),
hbarHidden ? 0 : d->hbar->sizeHint().height());
d->sizeHint = frame + scrollbars + viewportSizeHint();
diff --git a/src/widgets/widgets/qabstractslider.cpp b/src/widgets/widgets/qabstractslider.cpp
index 6e44b2d432..4e65fbac88 100644
--- a/src/widgets/widgets/qabstractslider.cpp
+++ b/src/widgets/widgets/qabstractslider.cpp
@@ -498,18 +498,25 @@ void QAbstractSlider::setValue(int value)
value = d->bound(value);
if (d->value == value && d->position == value)
return;
+
+ // delay signal emission until sliderChanged() has been called
+ const bool emitValueChanged = (value != d->value);
d->value = value;
+
if (d->position != value) {
d->position = value;
if (d->pressed)
- emit sliderMoved((d->position = value));
+ emit sliderMoved(d->position);
}
#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(this, d->value);
QAccessible::updateAccessibility(&event);
#endif
sliderChange(SliderValueChange);
- emit valueChanged(value);
+
+ if (emitValueChanged)
+ emit valueChanged(value);
+
}
/*!
diff --git a/src/widgets/widgets/qabstractspinbox.cpp b/src/widgets/widgets/qabstractspinbox.cpp
index 10aea1da3c..f377275d23 100644
--- a/src/widgets/widgets/qabstractspinbox.cpp
+++ b/src/widgets/widgets/qabstractspinbox.cpp
@@ -26,6 +26,7 @@
# include <qaccessible.h>
#endif
+#include <QtCore/qpointer.h>
//#define QABSTRACTSPINBOX_QSBDEBUG
#ifdef QABSTRACTSPINBOX_QSBDEBUG
@@ -691,14 +692,14 @@ void QAbstractSpinBox::setLineEdit(QLineEdit *lineEdit)
d->edit->setAcceptDrops(false);
if (d->type != QMetaType::UnknownType) {
- connect(d->edit, SIGNAL(textChanged(QString)),
- this, SLOT(_q_editorTextChanged(QString)));
- connect(d->edit, SIGNAL(cursorPositionChanged(int,int)),
- this, SLOT(_q_editorCursorPositionChanged(int,int)));
- connect(d->edit, SIGNAL(cursorPositionChanged(int,int)),
- this, SLOT(updateMicroFocus()));
- connect(d->edit->d_func()->control, SIGNAL(updateMicroFocus()),
- this, SLOT(updateMicroFocus()));
+ QObjectPrivate::connect(d->edit, &QLineEdit::textChanged,
+ d, &QAbstractSpinBoxPrivate::editorTextChanged);
+ QObjectPrivate::connect(d->edit, &QLineEdit::cursorPositionChanged,
+ d, &QAbstractSpinBoxPrivate::editorCursorPositionChanged);
+ connect(d->edit, &QLineEdit::cursorPositionChanged,
+ this, [this]() { updateMicroFocus(); });
+ connect(d->edit->d_func()->control, &QWidgetLineControl::updateMicroFocus,
+ this, [this]() { updateMicroFocus(); });
}
d->updateEditFieldGeometry();
d->edit->setContextMenuPolicy(Qt::NoContextMenu);
@@ -1510,7 +1511,7 @@ void QAbstractSpinBoxPrivate::emitSignals(EmitPolicy, const QVariant &)
signal.
*/
-void QAbstractSpinBoxPrivate::_q_editorTextChanged(const QString &t)
+void QAbstractSpinBoxPrivate::editorTextChanged(const QString &t)
{
Q_Q(QAbstractSpinBox);
@@ -1540,7 +1541,7 @@ void QAbstractSpinBoxPrivate::_q_editorTextChanged(const QString &t)
the different sections etc.
*/
-void QAbstractSpinBoxPrivate::_q_editorCursorPositionChanged(int oldpos, int newpos)
+void QAbstractSpinBoxPrivate::editorCursorPositionChanged(int oldpos, int newpos)
{
if (!edit->hasSelectedText() && !ignoreCursorPositionChanged && !specialValue()) {
ignoreCursorPositionChanged = true;
@@ -2042,6 +2043,7 @@ QVariant operator-(const QVariant &arg1, const QVariant &arg2)
dt.setTime(dt.time().addMSecs(msecs));
ret = QVariant(dt);
}
+ break;
}
default: break;
}
diff --git a/src/widgets/widgets/qabstractspinbox.h b/src/widgets/widgets/qabstractspinbox.h
index 6707db45c8..91d3dcb8fc 100644
--- a/src/widgets/widgets/qabstractspinbox.h
+++ b/src/widgets/widgets/qabstractspinbox.h
@@ -136,9 +136,6 @@ protected:
QAbstractSpinBox(QAbstractSpinBoxPrivate &dd, QWidget *parent = nullptr);
private:
- Q_PRIVATE_SLOT(d_func(), void _q_editorTextChanged(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_editorCursorPositionChanged(int, int))
-
Q_DECLARE_PRIVATE(QAbstractSpinBox)
Q_DISABLE_COPY(QAbstractSpinBox)
friend class QAccessibleAbstractSpinBox;
diff --git a/src/widgets/widgets/qabstractspinbox_p.h b/src/widgets/widgets/qabstractspinbox_p.h
index efc23586cf..4252a01423 100644
--- a/src/widgets/widgets/qabstractspinbox_p.h
+++ b/src/widgets/widgets/qabstractspinbox_p.h
@@ -74,8 +74,8 @@ public:
virtual QString textFromValue(const QVariant &n) const;
virtual QVariant valueFromText(const QString &input) const;
- void _q_editorTextChanged(const QString &);
- virtual void _q_editorCursorPositionChanged(int oldpos, int newpos);
+ void editorTextChanged(const QString &);
+ virtual void editorCursorPositionChanged(int oldpos, int newpos);
virtual QStyle::SubControl newHoverControl(const QPoint &pos);
bool updateHoverControl(const QPoint &pos);
diff --git a/src/widgets/widgets/qbuttongroup.cpp b/src/widgets/widgets/qbuttongroup.cpp
index 3a992fed74..079ef45e90 100644
--- a/src/widgets/widgets/qbuttongroup.cpp
+++ b/src/widgets/widgets/qbuttongroup.cpp
@@ -57,8 +57,8 @@ void QButtonGroupPrivate::detectCheckedButton()
In addition, QButtonGroup can map between integers and buttons.
You can assign an integer id to a button with setId(), and
retrieve it with id(). The id of the currently checked button is
- available with checkedId(), and there is an overloaded signal
- buttonClicked() which emits the id of the button. The id \c {-1}
+ available with checkedId(), and there is a signal
+ idClicked() that emits the id of the button. The id \c {-1}
is reserved by QButtonGroup to mean "no such button". The purpose
of the mapping mechanism is to simplify the representation of enum
values in a user interface.
diff --git a/src/widgets/widgets/qcalendarwidget.cpp b/src/widgets/widgets/qcalendarwidget.cpp
index 4d3360226f..034127b4f3 100644
--- a/src/widgets/widgets/qcalendarwidget.cpp
+++ b/src/widgets/widgets/qcalendarwidget.cpp
@@ -37,13 +37,13 @@ enum {
MinimumDayOffset = 1
};
-namespace {
-
static QString formatNumber(int number, int fieldWidth)
{
return QString::number(number).rightJustified(fieldWidth, u'0');
}
+namespace QtPrivate {
+
class QCalendarDateSectionValidator
{
public:
@@ -398,9 +398,11 @@ struct SectionToken {
QCalendarDateSectionValidator *validator;
int repeat;
};
-} // unnamed namespace
-Q_DECLARE_TYPEINFO(SectionToken, Q_PRIMITIVE_TYPE);
-namespace {
+} // namespace QtPrivate
+
+Q_DECLARE_TYPEINFO(QtPrivate::SectionToken, Q_PRIMITIVE_TYPE);
+
+namespace QtPrivate {
class QCalendarDateValidator
{
@@ -727,7 +729,7 @@ bool QCalendarTextNavigator::eventFilter(QObject *o, QEvent *e)
{
if (m_widget) {
if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) {
- QKeyEvent* ke = (QKeyEvent*)e;
+ QKeyEvent *ke = static_cast<QKeyEvent *>(e);
if ((ke->text().size() > 0 && ke->text().at(0).isPrint()) || m_dateFrame) {
if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Select) {
applyDate();
@@ -1606,7 +1608,20 @@ protected:
}
};
-} // unnamed namespace
+} // namespace QtPrivate
+
+using QCalendarDateSectionValidator = QtPrivate::QCalendarDateSectionValidator;
+using QCalendarDayValidator = QtPrivate::QCalendarDayValidator;
+using QCalendarMonthValidator = QtPrivate::QCalendarMonthValidator;
+using QCalendarYearValidator = QtPrivate::QCalendarYearValidator;
+using QCalendarDateValidator = QtPrivate::QCalendarDateValidator;
+using QPrevNextCalButton = QtPrivate::QPrevNextCalButton;
+using QCalendarDelegate = QtPrivate::QCalendarDelegate;
+using QCalToolButton = QtPrivate::QCalToolButton;
+using QCalendarDelegate = QtPrivate::QCalendarDelegate;
+using QCalendarModel = QtPrivate::QCalendarModel;
+using QCalendarView = QtPrivate::QCalendarView;
+using QCalendarTextNavigator = QtPrivate::QCalendarTextNavigator;
class QCalendarWidgetPrivate : public QWidgetPrivate
{
@@ -2185,7 +2200,7 @@ QSize QCalendarWidget::minimumSizeHint() const
QStyleOption option;
option.initFrom(this);
- const int marginH = (style()->pixelMetric(QStyle::PM_FocusFrameHMargin, &option) + 1) * 2;
+ const int marginH = (style()->pixelMetric(QStyle::PM_FocusFrameHMargin, &option, this) + 1) * 2;
if (horizontalHeaderFormat() == QCalendarWidget::NoHorizontalHeader) {
rows = 6;
@@ -2477,14 +2492,14 @@ void QCalendarWidget::showToday()
\snippet code/src_gui_widgets_qcalendarwidget.cpp 1
\endtable
- By default, the minimum date is the earliest date that the QDate
- class can handle.
-
When setting a minimum date, the maximumDate and selectedDate
properties are adjusted if the selection range becomes invalid. If
the provided date is not a valid QDate object, the
setMinimumDate() function does nothing.
+ The default minimum date is November 25, 4714 BCE.
+ You can restore this default by calling clearMinimumDate() (since Qt 6.6).
+
\sa setDateRange()
*/
@@ -2513,6 +2528,11 @@ void QCalendarWidget::setMinimumDate(QDate date)
}
}
+void QCalendarWidget::clearMinimumDate()
+{
+ setMinimumDate(QDate::fromJulianDay(1));
+}
+
/*!
\property QCalendarWidget::maximumDate
\brief the maximum date of the currently specified date range.
@@ -2528,14 +2548,14 @@ void QCalendarWidget::setMinimumDate(QDate date)
\snippet code/src_gui_widgets_qcalendarwidget.cpp 2
\endtable
- By default, the maximum date is the last day the QDate class can
- handle.
-
When setting a maximum date, the minimumDate and selectedDate
properties are adjusted if the selection range becomes invalid. If
the provided date is not a valid QDate object, the
setMaximumDate() function does nothing.
+ The default maximum date is December 31, 9999 CE.
+ You can restore this default by calling clearMaximumDate() (since Qt 6.6).
+
\sa setDateRange()
*/
@@ -2564,6 +2584,11 @@ void QCalendarWidget::setMaximumDate(QDate date)
}
}
+void QCalendarWidget::clearMaximumDate()
+{
+ setMaximumDate(QDate(9999, 12, 31));
+}
+
/*!
Defines a date range by setting the minimumDate and maximumDate
properties.
@@ -2848,7 +2873,7 @@ QMap<QDate, QTextCharFormat> QCalendarWidget::dateTextFormat() const
}
/*!
- Returns a QTextCharFormat for \a date. The char format can be be
+ Returns a QTextCharFormat for \a date. The char format can be
empty if the date is not renderd specially.
*/
QTextCharFormat QCalendarWidget::dateTextFormat(QDate date) const
@@ -3074,6 +3099,7 @@ bool QCalendarWidget::event(QEvent *event)
case QEvent::StyleChange:
d->cachedSizeHint = QSize();
d->m_view->updateGeometry();
+ break;
default:
break;
}
diff --git a/src/widgets/widgets/qcalendarwidget.h b/src/widgets/widgets/qcalendarwidget.h
index c7b2854079..034c95dd62 100644
--- a/src/widgets/widgets/qcalendarwidget.h
+++ b/src/widgets/widgets/qcalendarwidget.h
@@ -21,8 +21,8 @@ class Q_WIDGETS_EXPORT QCalendarWidget : public QWidget
Q_OBJECT
Q_ENUMS(Qt::DayOfWeek)
Q_PROPERTY(QDate selectedDate READ selectedDate WRITE setSelectedDate)
- Q_PROPERTY(QDate minimumDate READ minimumDate WRITE setMinimumDate)
- Q_PROPERTY(QDate maximumDate READ maximumDate WRITE setMaximumDate)
+ Q_PROPERTY(QDate minimumDate READ minimumDate WRITE setMinimumDate RESET clearMinimumDate)
+ Q_PROPERTY(QDate maximumDate READ maximumDate WRITE setMaximumDate RESET clearMaximumDate)
Q_PROPERTY(Qt::DayOfWeek firstDayOfWeek READ firstDayOfWeek WRITE setFirstDayOfWeek)
Q_PROPERTY(bool gridVisible READ isGridVisible WRITE setGridVisible)
Q_PROPERTY(SelectionMode selectionMode READ selectionMode WRITE setSelectionMode)
@@ -68,9 +68,11 @@ public:
QDate minimumDate() const;
void setMinimumDate(QDate date);
+ void clearMinimumDate();
QDate maximumDate() const;
void setMaximumDate(QDate date);
+ void clearMaximumDate();
Qt::DayOfWeek firstDayOfWeek() const;
void setFirstDayOfWeek(Qt::DayOfWeek dayOfWeek);
diff --git a/src/widgets/widgets/qcheckbox.cpp b/src/widgets/widgets/qcheckbox.cpp
index 151c8b1e94..88cd603d70 100644
--- a/src/widgets/widgets/qcheckbox.cpp
+++ b/src/widgets/widgets/qcheckbox.cpp
@@ -28,7 +28,7 @@ public:
uint tristate : 1;
uint noChange : 1;
uint hovering : 1;
- uint publishedState : 2;
+ Qt::CheckState publishedState : 3;
void init();
};
@@ -59,7 +59,7 @@ public:
\endtable
Whenever a checkbox is checked or cleared, it emits the signal
- stateChanged(). Connect to this signal if you want to trigger an action
+ checkStateChanged(). Connect to this signal if you want to trigger an action
each time the checkbox changes state. You can use isChecked() to query
whether or not a checkbox is checked.
@@ -84,7 +84,7 @@ public:
setPixmap(), accel(), setAccel(), isToggleButton(), setDown(), isDown(),
isOn(), checkState(), autoRepeat(), isExclusiveToggle(), group(),
setAutoRepeat(), toggle(), pressed(), released(), clicked(), toggled(),
- checkState(), and stateChanged().
+ checkState(), and checkStateChanged().
\sa QAbstractButton, QRadioButton
*/
@@ -92,6 +92,13 @@ public:
/*!
\fn void QCheckBox::stateChanged(int state)
+ \deprecated [6.9] Use checkStateChanged(Qt::CheckState) instead.
+*/
+
+/*!
+ \fn void QCheckBox::checkStateChanged(Qt::CheckState state)
+ \since 6.7
+
This signal is emitted whenever the checkbox's state changes, i.e.,
whenever the user checks or unchecks it.
@@ -224,9 +231,14 @@ void QCheckBox::setCheckState(Qt::CheckState state)
setChecked(state != Qt::Unchecked);
d->blockRefresh = false;
d->refresh();
- if ((uint)state != d->publishedState) {
+ if (state != d->publishedState) {
d->publishedState = state;
+ emit checkStateChanged(state);
+#if QT_DEPRECATED_SINCE(6, 9)
+ QT_IGNORE_DEPRECATIONS(
emit stateChanged(state);
+ )
+#endif
}
#if QT_CONFIG(accessibility)
@@ -319,9 +331,14 @@ void QCheckBox::checkStateSet()
Q_D(QCheckBox);
d->noChange = false;
Qt::CheckState state = checkState();
- if ((uint)state != d->publishedState) {
+ if (state != d->publishedState) {
d->publishedState = state;
+ emit checkStateChanged(state);
+#if QT_DEPRECATED_SINCE(6, 9)
+ QT_IGNORE_DEPRECATIONS(
emit stateChanged(state);
+ )
+#endif
}
}
diff --git a/src/widgets/widgets/qcheckbox.h b/src/widgets/widgets/qcheckbox.h
index ab240b5500..de623b7b9e 100644
--- a/src/widgets/widgets/qcheckbox.h
+++ b/src/widgets/widgets/qcheckbox.h
@@ -36,7 +36,11 @@ public:
void setCheckState(Qt::CheckState state);
Q_SIGNALS:
+#if QT_DEPRECATED_SINCE(6, 9)
+ QT_MOC_COMPAT QT_DEPRECATED_VERSION_X_6_9("Use checkStateChanged() instead")
void stateChanged(int);
+#endif
+ void checkStateChanged(Qt::CheckState);
protected:
bool event(QEvent *e) override;
diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp
index 5889545b1c..1fe9a8d7be 100644
--- a/src/widgets/widgets/qcombobox.cpp
+++ b/src/widgets/widgets/qcombobox.cpp
@@ -12,7 +12,7 @@
#if QT_CONFIG(tableview)
#include <qtableview.h>
#endif
-#include <qitemdelegate.h>
+#include <qabstractitemdelegate.h>
#include <qmap.h>
#if QT_CONFIG(menu)
#include <qmenu.h>
@@ -48,6 +48,9 @@
#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
+#include <array>
+
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
@@ -65,6 +68,7 @@ QComboBoxPrivate::QComboBoxPrivate()
QComboBoxPrivate::~QComboBoxPrivate()
{
+ disconnectModel();
#ifdef Q_OS_MAC
cleanupNativePopup();
#endif
@@ -200,7 +204,7 @@ bool QComboMenuDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
}
#if QT_CONFIG(completer)
-void QComboBoxPrivate::_q_completerActivated(const QModelIndex &index)
+void QComboBoxPrivate::completerActivated(const QModelIndex &index)
{
Q_Q(QComboBox);
#if QT_CONFIG(proxymodel)
@@ -240,7 +244,7 @@ void QComboBoxPrivate::updateArrow(QStyle::StateFlag state)
q->update(q->rect());
}
-void QComboBoxPrivate::_q_modelReset()
+void QComboBoxPrivate::modelReset()
{
Q_Q(QComboBox);
if (lineEdit) {
@@ -252,7 +256,7 @@ void QComboBoxPrivate::_q_modelReset()
q->update();
}
-void QComboBoxPrivate::_q_modelDestroyed()
+void QComboBoxPrivate::modelDestroyed()
{
model = QAbstractItemModelPrivate::staticEmptyModel();
}
@@ -490,11 +494,13 @@ QComboBoxPrivateContainer::QComboBoxPrivateContainer(QAbstractItemView *itemView
if (top) {
layout->insertWidget(0, top);
- connect(top, SIGNAL(doScroll(int)), this, SLOT(scrollItemView(int)));
+ connect(top, &QComboBoxPrivateScroller::doScroll,
+ this, &QComboBoxPrivateContainer::scrollItemView);
}
if (bottom) {
layout->addWidget(bottom);
- connect(bottom, SIGNAL(doScroll(int)), this, SLOT(scrollItemView(int)));
+ connect(bottom, &QComboBoxPrivateScroller::doScroll,
+ this, &QComboBoxPrivateContainer::scrollItemView);
}
// Some styles (Mac) have a margin at the top and bottom of the popup.
@@ -503,6 +509,12 @@ QComboBoxPrivateContainer::QComboBoxPrivateContainer(QAbstractItemView *itemView
updateStyleSettings();
}
+QComboBoxPrivateContainer::~QComboBoxPrivateContainer()
+{
+ disconnect(view, &QAbstractItemView::destroyed,
+ this, &QComboBoxPrivateContainer::viewDestroyed);
+}
+
void QComboBoxPrivateContainer::scrollItemView(int action)
{
#if QT_CONFIG(scrollbar)
@@ -583,13 +595,13 @@ void QComboBoxPrivateContainer::setItemView(QAbstractItemView *itemView)
view->removeEventFilter(this);
view->viewport()->removeEventFilter(this);
#if QT_CONFIG(scrollbar)
- disconnect(view->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(updateScrollers()));
- disconnect(view->verticalScrollBar(), SIGNAL(rangeChanged(int,int)),
- this, SLOT(updateScrollers()));
+ disconnect(view->verticalScrollBar(), &QScrollBar::valueChanged,
+ this, &QComboBoxPrivateContainer::updateScrollers);
+ disconnect(view->verticalScrollBar(), &QScrollBar::rangeChanged,
+ this, &QComboBoxPrivateContainer::updateScrollers);
#endif
- disconnect(view, SIGNAL(destroyed()),
- this, SLOT(viewDestroyed()));
+ disconnect(view, &QAbstractItemView::destroyed,
+ this, &QComboBoxPrivateContainer::viewDestroyed);
if (isAncestorOf(view))
delete view;
@@ -620,13 +632,13 @@ void QComboBoxPrivateContainer::setItemView(QAbstractItemView *itemView)
view->setLineWidth(0);
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
#if QT_CONFIG(scrollbar)
- connect(view->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(updateScrollers()));
- connect(view->verticalScrollBar(), SIGNAL(rangeChanged(int,int)),
- this, SLOT(updateScrollers()));
+ connect(view->verticalScrollBar(), &QScrollBar::valueChanged,
+ this, &QComboBoxPrivateContainer::updateScrollers);
+ connect(view->verticalScrollBar(), &QScrollBar::rangeChanged,
+ this, &QComboBoxPrivateContainer::updateScrollers);
#endif
- connect(view, SIGNAL(destroyed()),
- this, SLOT(viewDestroyed()));
+ connect(view, &QAbstractItemView::destroyed,
+ this, &QComboBoxPrivateContainer::viewDestroyed);
}
/*!
@@ -715,6 +727,7 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
#endif
if (view->currentIndex().isValid() && view->currentIndex().flags().testFlag(Qt::ItemIsEnabled)) {
combo->hidePopup();
+ keyEvent->accept();
emit itemSelected(view->currentIndex());
}
return true;
@@ -724,11 +737,12 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
Q_FALLTHROUGH();
case Qt::Key_F4:
combo->hidePopup();
+ keyEvent->accept();
+ emit itemSelected(view->currentIndex());
return true;
default:
#if QT_CONFIG(shortcut)
- if (keyEvent->matches(QKeySequence::Cancel)) {
- closeOnCancel = true;
+ if (keyEvent->matches(QKeySequence::Cancel) && isVisible()) {
keyEvent->accept();
return true;
}
@@ -776,7 +790,6 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
void QComboBoxPrivateContainer::showEvent(QShowEvent *)
{
- closeOnCancel = true;
combo->update();
}
@@ -906,8 +919,11 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
\fn void QComboBox::currentTextChanged(const QString &text)
\since 5.0
- This signal is sent whenever currentText changes. The new value
- is passed as \a text.
+ This signal is emitted whenever currentText changes.
+ The new value is passed as \a text.
+
+ \note It is not emitted, if currentText remains the same,
+ even if currentIndex changes.
*/
/*!
@@ -933,39 +949,34 @@ QComboBox::QComboBox(QComboBoxPrivate &dd, QWidget *parent)
/*!
\class QComboBox
- \brief The QComboBox widget is a combined button and popup list.
+ \brief The QComboBox widget combines a button with a dropdown list.
\ingroup basicwidgets
\inmodule QtWidgets
- \image windows-combobox.png
-
- A QComboBox provides a means of presenting a list of options to the user
- in a way that takes up the minimum amount of screen space.
-
- A combobox is a selection widget that displays the current item,
- and can pop up a list of selectable items. A combobox may be editable,
- allowing the user to modify each item in the list.
-
- Comboboxes can contain pixmaps as well as strings; the
- insertItem() and setItemText() functions are suitably overloaded.
- For editable comboboxes, the function clearEditText() is provided,
+ \table
+ \row
+ \li \inlineimage collapsed_combobox.png
+ \caption Collapsed QCombobox
+ \li
+ \inlineimage expanded_combobox.png
+ \caption Expanded QCombobox
+ \endtable
+
+ \section1 Display Features
+ A QComboBox is a compact way to present a list of options to the user.
+
+ A combobox is a selection widget that shows the current item,
+ and pops up a list of selectable items when clicked. Comboboxes can
+ contain pixmaps as well as strings if the insertItem() and setItemText()
+ functions are suitably overloaded.
+
+ \section1 Editing Features
+ A combobox may be editable, allowing the user to modify each item in the
+ list. For editable comboboxes, the function clearEditText() is provided,
to clear the displayed string without changing the combobox's
contents.
- There are three signals emitted if the current item of a combobox
- changes, currentIndexChanged(), currentTextChanged() and activated().
- currentIndexChanged() and currentTextChanged() are always emitted
- regardless if the change
- was done programmatically or by user interaction, while
- activated() is only emitted when the change is caused by user
- interaction. The highlighted() signal is emitted when the user
- highlights an item in the combobox popup list. All three signals
- exist in two versions, one with a QString argument and one with an
- \c int argument. If the user selects or highlights a pixmap, only
- the \c int signals are emitted. Whenever the text of an editable
- combobox is changed the editTextChanged() signal is emitted.
-
When the user enters a new string in an editable combobox, the
widget may or may not insert it, and it can insert it in several
locations. The default policy is \l InsertAtBottom but you can change
@@ -988,17 +999,33 @@ QComboBox::QComboBox(QComboBoxPrivate &dd, QWidget *parent)
setCompleter() and whether or not the user can add duplicates
is set with setDuplicatesEnabled().
- QComboBox uses the \l{Model/View Programming}{model/view
- framework} for its popup list and to store its items. By default
- a QStandardItemModel stores the items and a QListView subclass
- displays the popuplist. You can access the model and view directly
- (with model() and view()), but QComboBox also provides functions
- to set and get item data (e.g., setItemData() and itemText()). You
- can also set a new model and view (with setModel() and setView()).
- For the text and icon in the combobox label, the data in the model
- that has the Qt::DisplayRole and Qt::DecorationRole is used. Note
- that you cannot alter the \l{QAbstractItemView::}{SelectionMode}
- of the view(), e.g., by using
+ \section1 Signals
+ There are three signals emitted if the current item of a combobox
+ changes: currentIndexChanged(), currentTextChanged(), and activated().
+ currentIndexChanged() and currentTextChanged() are always emitted
+ regardless if the change
+ was done programmatically or by user interaction, while
+ activated() is only emitted when the change is caused by user
+ interaction. The highlighted() signal is emitted when the user
+ highlights an item in the combobox popup list. All three signals
+ exist in two versions, one with a QString argument and one with an
+ \c int argument. If the user selects or highlights a pixmap, only
+ the \c int signals are emitted. Whenever the text of an editable
+ combobox is changed, the editTextChanged() signal is emitted.
+
+ \section1 Model/View Framework
+
+ QComboBox uses the \l{Model/View Programming}{model/view framework} for its
+ popup list and to store its items. By default a QStandardItemModel stores
+ the items and a QListView subclass displays the popuplist. You can access
+ the model and view directly (with model() and view()), but QComboBox also
+ provides functions to set and get item data, for example, setItemData() and
+ itemText(). You can also set a new model and view (with setModel()
+ and setView()). For the text and icon in the combobox label, the data in
+ the model that has the Qt::DisplayRole and Qt::DecorationRole is used.
+
+ \note You cannot alter the \l{QAbstractItemView::}{SelectionMode}
+ of the view(), for example, by using
\l{QAbstractItemView::}{setSelectionMode()}.
\sa QLineEdit, QSpinBox, QRadioButton, QButtonGroup
@@ -1035,27 +1062,30 @@ QComboBoxPrivateContainer* QComboBoxPrivate::viewContainer()
Q_Q(QComboBox);
container = new QComboBoxPrivateContainer(new QComboBoxListView(q), q);
+ disconnectModel();
container->itemView()->setModel(model);
+ connectModel();
container->itemView()->setTextElideMode(Qt::ElideMiddle);
updateDelegate(true);
updateLayoutDirection();
updateViewContainerPaletteAndOpacity();
- QObject::connect(container, SIGNAL(itemSelected(QModelIndex)),
- q, SLOT(_q_itemSelected(QModelIndex)));
- QObject::connect(container->itemView()->selectionModel(),
- SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitHighlighted(QModelIndex)));
- QObject::connect(container, SIGNAL(resetButton()), q, SLOT(_q_resetButton()));
+ QObjectPrivate::connect(container, &QComboBoxPrivateContainer::itemSelected,
+ this, &QComboBoxPrivate::itemSelected);
+ QObjectPrivate::connect(container->itemView()->selectionModel(),
+ &QItemSelectionModel::currentChanged,
+ this, &QComboBoxPrivate::emitHighlighted);
+ QObjectPrivate::connect(container, &QComboBoxPrivateContainer::resetButton,
+ this, &QComboBoxPrivate::resetButton);
return container;
}
-void QComboBoxPrivate::_q_resetButton()
+void QComboBoxPrivate::resetButton()
{
updateArrow(QStyle::State_None);
}
-void QComboBoxPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
+void QComboBoxPrivate::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
Q_Q(QComboBox);
if (inserting || topLeft.parent() != root)
@@ -1073,7 +1103,7 @@ void QComboBoxPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIn
lineEdit->setText(text);
updateLineEditGeometry();
} else {
- emit q->currentTextChanged(text);
+ updateCurrentText(text);
}
q->update();
#if QT_CONFIG(accessibility)
@@ -1083,7 +1113,7 @@ void QComboBoxPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIn
}
}
-void QComboBoxPrivate::_q_rowsInserted(const QModelIndex &parent, int start, int end)
+void QComboBoxPrivate::rowsInserted(const QModelIndex &parent, int start, int end)
{
Q_Q(QComboBox);
if (inserting || parent != root)
@@ -1098,20 +1128,31 @@ void QComboBoxPrivate::_q_rowsInserted(const QModelIndex &parent, int start, int
// set current index if combo was previously empty and there is no placeholderText
if (start == 0 && (end - start + 1) == q->count() && !currentIndex.isValid() &&
placeholderText.isEmpty()) {
+#if QT_CONFIG(accessibility)
+ // This might have been called by the model emitting rowInserted(), at which
+ // point the view won't have updated the accessibility bridge yet about its new
+ // dimensions. Do it now so that the change of the selection matches the row
+ // indexes of the accessibility bridge's representation.
+ if (container && container->itemView()) {
+ QAccessibleTableModelChangeEvent event(container->itemView(),
+ QAccessibleTableModelChangeEvent::ModelReset);
+ QAccessible::updateAccessibility(&event);
+ }
+#endif
q->setCurrentIndex(0);
// need to emit changed if model updated index "silently"
} else if (currentIndex.row() != indexBeforeChange) {
q->update();
- _q_emitCurrentIndexChanged(currentIndex);
+ emitCurrentIndexChanged(currentIndex);
}
}
-void QComboBoxPrivate::_q_updateIndexBeforeChange()
+void QComboBoxPrivate::updateIndexBeforeChange()
{
indexBeforeChange = currentIndex.row();
}
-void QComboBoxPrivate::_q_rowsRemoved(const QModelIndex &parent, int /*start*/, int /*end*/)
+void QComboBoxPrivate::rowsRemoved(const QModelIndex &parent, int /*start*/, int /*end*/)
{
Q_Q(QComboBox);
if (parent != root)
@@ -1123,6 +1164,12 @@ void QComboBoxPrivate::_q_rowsRemoved(const QModelIndex &parent, int /*start*/,
q->updateGeometry();
}
+ // model has removed the last row
+ if (model->rowCount(root) == 0) {
+ setCurrentIndex(QModelIndex());
+ return;
+ }
+
// model has changed the currentIndex
if (currentIndex.row() != indexBeforeChange) {
if (!currentIndex.isValid() && q->count()) {
@@ -1134,7 +1181,7 @@ void QComboBoxPrivate::_q_rowsRemoved(const QModelIndex &parent, int /*start*/,
updateLineEditGeometry();
}
q->update();
- _q_emitCurrentIndexChanged(currentIndex);
+ emitCurrentIndexChanged(currentIndex);
}
}
@@ -1243,7 +1290,7 @@ Qt::MatchFlags QComboBoxPrivate::matchFlags() const
}
-void QComboBoxPrivate::_q_editingFinished()
+void QComboBoxPrivate::editingFinished()
{
Q_Q(QComboBox);
if (!lineEdit)
@@ -1275,13 +1322,13 @@ void QComboBoxPrivate::_q_editingFinished()
}
-void QComboBoxPrivate::_q_returnPressed()
+void QComboBoxPrivate::returnPressed()
{
Q_Q(QComboBox);
// The insertion code below does not apply when the policy is QComboBox::NoInsert.
// In case a completer is installed, item activation via the completer is handled
- // in _q_completerActivated(). Otherwise _q_editingFinished() updates the current
+ // in completerActivated(). Otherwise editingFinished() updates the current
// index as appropriate.
if (insertPolicy == QComboBox::NoInsert)
return;
@@ -1339,7 +1386,7 @@ void QComboBoxPrivate::_q_returnPressed()
}
}
-void QComboBoxPrivate::_q_itemSelected(const QModelIndex &item)
+void QComboBoxPrivate::itemSelected(const QModelIndex &item)
{
Q_Q(QComboBox);
if (item != currentIndex) {
@@ -1361,7 +1408,7 @@ void QComboBoxPrivate::emitActivated(const QModelIndex &index)
emit q->textActivated(text);
}
-void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
+void QComboBoxPrivate::emitHighlighted(const QModelIndex &index)
{
Q_Q(QComboBox);
if (!index.isValid())
@@ -1371,14 +1418,14 @@ void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
emit q->textHighlighted(text);
}
-void QComboBoxPrivate::_q_emitCurrentIndexChanged(const QModelIndex &index)
+void QComboBoxPrivate::emitCurrentIndexChanged(const QModelIndex &index)
{
Q_Q(QComboBox);
const QString text = itemText(index);
emit q->currentIndexChanged(index.row());
// signal lineEdit.textChanged already connected to signal currentTextChanged, so don't emit double here
if (!lineEdit)
- emit q->currentTextChanged(text);
+ updateCurrentText(text);
#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(q, text);
QAccessible::updateAccessibility(&event);
@@ -1404,11 +1451,13 @@ QComboBox::~QComboBox()
Q_D(QComboBox);
QT_TRY {
- disconnect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
+ d->disconnectModel();
} QT_CATCH(...) {
; // objects can't throw in destructor
}
+
+ // Dispose of container before QComboBox goes away
+ delete d->container;
}
/*!
@@ -1439,7 +1488,7 @@ void QComboBox::setMaxVisibleItems(int maxItems)
/*!
\property QComboBox::count
- \brief the number of items in the combobox
+ \brief the number of items in the combobox.
By default, for an empty combo box, this property has a value of 0.
*/
@@ -1451,7 +1500,7 @@ int QComboBox::count() const
/*!
\property QComboBox::maxCount
- \brief the maximum number of items allowed in the combobox
+ \brief the maximum number of items allowed in the combobox.
\note If you set the maximum number to be less then the current
amount of items in the combobox, the extra items will be
@@ -1484,7 +1533,7 @@ int QComboBox::maxCount() const
/*!
\property QComboBox::duplicatesEnabled
- \brief whether the user can enter duplicate items into the combobox
+ \brief whether the user can enter duplicate items into the combobox.
Note that it is always possible to programmatically insert duplicate items into the
combobox.
@@ -1530,7 +1579,7 @@ int QComboBox::findData(const QVariant &data, int role, Qt::MatchFlags flags) co
/*!
\property QComboBox::insertPolicy
\brief the policy used to determine where user-inserted items should
- appear in the combobox
+ appear in the combobox.
The default value is \l InsertAtBottom, indicating that new items will appear
at the bottom of the list of items.
@@ -1553,7 +1602,7 @@ void QComboBox::setInsertPolicy(InsertPolicy policy)
/*!
\property QComboBox::sizeAdjustPolicy
\brief the policy describing how the size of the combobox changes
- when the content changes
+ when the content changes.
The default value is \l AdjustToContentsOnFirstShow.
@@ -1644,7 +1693,7 @@ void QComboBox::setIconSize(const QSize &size)
/*!
\property QComboBox::placeholderText
- \brief Sets a \a placeholderText text shown when no valid index is set
+ \brief Sets a \a placeholderText text shown when no valid index is set.
The \a placeholderText will be shown when an invalid index is set. The
text is not accessible in the dropdown list. When this function is called
@@ -1683,7 +1732,7 @@ QString QComboBox::placeholderText() const
/*!
\property QComboBox::editable
- \brief whether the combo box can be edited by the user
+ \brief whether the combo box can be edited by the user.
By default, this property is \c false. The effect of editing depends
on the insert policy.
@@ -1722,6 +1771,8 @@ void QComboBoxPrivate::updateDelegate(bool force)
QIcon QComboBoxPrivate::itemIcon(const QModelIndex &index) const
{
+ if (!index.isValid())
+ return {};
QVariant decoration = model->data(index, Qt::DecorationRole);
if (decoration.userType() == QMetaType::QPixmap)
return QIcon(qvariant_cast<QPixmap>(decoration));
@@ -1792,13 +1843,18 @@ void QComboBox::setLineEdit(QLineEdit *edit)
#endif
if (d->lineEdit->parent() != this)
d->lineEdit->setParent(this);
- connect(d->lineEdit, SIGNAL(returnPressed()), this, SLOT(_q_returnPressed()));
- connect(d->lineEdit, SIGNAL(editingFinished()), this, SLOT(_q_editingFinished()));
- connect(d->lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(editTextChanged(QString)));
- connect(d->lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(currentTextChanged(QString)));
- connect(d->lineEdit, SIGNAL(cursorPositionChanged(int,int)), this, SLOT(updateMicroFocus()));
- connect(d->lineEdit, SIGNAL(selectionChanged()), this, SLOT(updateMicroFocus()));
- connect(d->lineEdit->d_func()->control, SIGNAL(updateMicroFocus()), this, SLOT(updateMicroFocus()));
+ QObjectPrivate::connect(d->lineEdit, &QLineEdit::returnPressed,
+ d, &QComboBoxPrivate::returnPressed);
+ QObjectPrivate::connect(d->lineEdit, &QLineEdit::editingFinished,
+ d, &QComboBoxPrivate::editingFinished);
+ connect(d->lineEdit, &QLineEdit::textChanged, this, &QComboBox::editTextChanged);
+ connect(d->lineEdit, &QLineEdit::textChanged, this, &QComboBox::currentTextChanged);
+ QObjectPrivate::connect(d->lineEdit, &QLineEdit::cursorPositionChanged,
+ d, &QComboBoxPrivate::updateMicroFocus);
+ QObjectPrivate::connect(d->lineEdit, &QLineEdit::selectionChanged,
+ d, &QComboBoxPrivate::updateMicroFocus);
+ QObjectPrivate::connect(d->lineEdit->d_func()->control, &QWidgetLineControl::updateMicroFocus,
+ d, &QComboBoxPrivate::updateMicroFocus);
d->lineEdit->setFrame(false);
d->lineEdit->setContextMenuPolicy(Qt::NoContextMenu);
d->updateFocusPolicy();
@@ -1900,7 +1956,8 @@ void QComboBox::setCompleter(QCompleter *c)
}
d->lineEdit->setCompleter(c);
if (c) {
- connect(c, SIGNAL(activated(QModelIndex)), this, SLOT(_q_completerActivated(QModelIndex)));
+ QObjectPrivate::connect(c, QOverload<const QModelIndex &>::of(&QCompleter::activated),
+ d, &QComboBoxPrivate::completerActivated);
c->setWidget(this);
}
}
@@ -1994,59 +2051,60 @@ void QComboBox::setModel(QAbstractItemModel *model)
if (d->lineEdit && d->lineEdit->completer())
d->lineEdit->completer()->setModel(model);
#endif
- if (d->model) {
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- disconnect(d->model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- disconnect(d->model, SIGNAL(modelAboutToBeReset()),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(modelReset()),
- this, SLOT(_q_modelReset()));
- if (d->model->QObject::parent() == this)
- delete d->model;
+ d->disconnectModel();
+ if (d->model && d->model->QObject::parent() == this) {
+ delete d->model;
+ d->model = nullptr;
}
d->model = model;
- connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- connect(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- connect(model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- connect(model, SIGNAL(modelAboutToBeReset()),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(modelReset()),
- this, SLOT(_q_modelReset()));
-
if (d->container) {
d->container->itemView()->setModel(model);
- connect(d->container->itemView()->selectionModel(),
- SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_emitHighlighted(QModelIndex)), Qt::UniqueConnection);
+ QObjectPrivate::connect(d->container->itemView()->selectionModel(),
+ &QItemSelectionModel::currentChanged,
+ d, &QComboBoxPrivate::emitHighlighted, Qt::UniqueConnection);
}
+ d->connectModel();
+
setRootModelIndex(QModelIndex());
d->trySetValidIndex();
d->modelChanged();
}
+void QComboBoxPrivate::connectModel()
+{
+ if (!model)
+ return;
+
+ modelConnections = {
+ QObjectPrivate::connect(model, &QAbstractItemModel::dataChanged,
+ this, &QComboBoxPrivate::dataChanged),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsAboutToBeInserted,
+ this, &QComboBoxPrivate::updateIndexBeforeChange),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsInserted,
+ this, &QComboBoxPrivate::rowsInserted),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
+ this, &QComboBoxPrivate::updateIndexBeforeChange),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsRemoved,
+ this, &QComboBoxPrivate::rowsRemoved),
+ QObjectPrivate::connect(model, &QObject::destroyed,
+ this, &QComboBoxPrivate::modelDestroyed),
+ QObjectPrivate::connect(model, &QAbstractItemModel::modelAboutToBeReset,
+ this, &QComboBoxPrivate::updateIndexBeforeChange),
+ QObjectPrivate::connect(model, &QAbstractItemModel::modelReset,
+ this, &QComboBoxPrivate::modelReset)
+ };
+}
+
+void QComboBoxPrivate::disconnectModel()
+{
+ for (auto &connection : modelConnections)
+ QObject::disconnect(connection);
+}
+
/*!
Returns the root model item index for the items in the combobox.
@@ -2092,7 +2150,7 @@ int QComboBox::currentIndex() const
void QComboBox::setCurrentIndex(int index)
{
Q_D(QComboBox);
- QModelIndex mi = d->model->index(index, d->modelColumn, d->root);
+ QModelIndex mi = index >= 0 ? d->model->index(index, d->modelColumn, d->root) : QModelIndex();
d->setCurrentIndex(mi);
}
@@ -2129,13 +2187,24 @@ void QComboBoxPrivate::setCurrentIndex(const QModelIndex &mi)
}
updateLineEditGeometry();
}
- // If the model was reset to an empty, currentIndex will be invalidated
+ // If the model was reset to an empty one, currentIndex will be invalidated
// (because it's a QPersistentModelIndex), but the index change will never
- // be advertised. So we need an explicit check for such condition.
+ // be advertised. So an explicit check for this condition is needed.
+ // The variable used for that check has to be reset when a previously valid
+ // index becomes invalid.
const bool modelResetToEmpty = !normalized.isValid() && indexBeforeChange != -1;
+ if (modelResetToEmpty)
+ indexBeforeChange = -1;
+
if (indexChanged || modelResetToEmpty) {
+ QItemSelectionModel::SelectionFlags selectionMode = QItemSelectionModel::ClearAndSelect;
+ if (q->view()->selectionBehavior() == QAbstractItemView::SelectRows)
+ selectionMode.setFlag(QItemSelectionModel::Rows);
+ if (auto *model = q->view()->selectionModel())
+ model->setCurrentIndex(currentIndex, selectionMode);
+
q->update();
- _q_emitCurrentIndexChanged(currentIndex);
+ emitCurrentIndexChanged(currentIndex);
}
}
@@ -2264,7 +2333,7 @@ void QComboBox::insertItem(int index, const QIcon &icon, const QString &text, co
if (!values.isEmpty()) d->model->setItemData(item, values);
}
d->inserting = false;
- d->_q_rowsInserted(d->root, index, index);
+ d->rowsInserted(d->root, index, index);
++itemCount;
} else {
d->inserting = false;
@@ -2312,7 +2381,7 @@ void QComboBox::insertItems(int index, const QStringList &list)
d->model->setData(item, list.at(i), Qt::EditRole);
}
d->inserting = false;
- d->_q_rowsInserted(d->root, index, index + insertCount - 1);
+ d->rowsInserted(d->root, index, index + insertCount - 1);
} else {
d->inserting = false;
}
@@ -2422,8 +2491,11 @@ void QComboBox::setView(QAbstractItemView *itemView)
return;
}
- if (itemView->model() != d->model)
+ if (itemView->model() != d->model) {
+ d->disconnectModel();
itemView->setModel(d->model);
+ d->connectModel();
+ }
d->viewContainer()->setItemView(itemView);
}
@@ -2455,12 +2527,13 @@ void QComboBoxPrivate::cleanupNativePopup()
if (!m_platformMenu)
return;
+ m_platformMenu->setVisible(false);
int count = int(m_platformMenu->tag());
for (int i = 0; i < count; ++i)
m_platformMenu->menuItemAt(i)->deleteLater();
delete m_platformMenu;
- m_platformMenu = 0;
+ m_platformMenu = nullptr;
}
/*!
@@ -2492,15 +2565,17 @@ bool QComboBoxPrivate::showNativePopup()
QVariant textVariant = model->data(rowIndex, Qt::EditRole);
item->setText(textVariant.toString());
QVariant iconVariant = model->data(rowIndex, Qt::DecorationRole);
+ const Qt::ItemFlags itemFlags = model->flags(rowIndex);
if (iconVariant.canConvert<QIcon>())
item->setIcon(iconVariant.value<QIcon>());
item->setCheckable(true);
item->setChecked(i == currentIndex);
+ item->setEnabled(itemFlags & Qt::ItemIsEnabled);
if (!currentItem || i == currentIndex)
currentItem = item;
IndexSetter setter = { i, q };
- QObject::connect(item, &QPlatformMenuItem::activated, setter);
+ QObject::connect(item, &QPlatformMenuItem::activated, q, setter);
m_platformMenu->insertMenuItem(item, 0);
m_platformMenu->syncMenuItem(item);
@@ -2515,15 +2590,18 @@ bool QComboBoxPrivate::showNativePopup()
else if (q->testAttribute(Qt::WA_MacMiniSize))
offset = QPoint(-2, 6);
+ [[maybe_unused]] QPointer<QComboBox> guard(q);
const QRect targetRect = QRect(tlw->mapFromGlobal(q->mapToGlobal(offset)), QSize());
m_platformMenu->showPopup(tlw, QHighDpi::toNativePixels(targetRect, tlw), currentItem);
#ifdef Q_OS_MACOS
- // The Cocoa popup will swallow any mouse release event.
- // We need to fake one here to un-press the button.
- QMouseEvent mouseReleased(QEvent::MouseButtonRelease, q->pos(), q->mapToGlobal(QPoint(0, 0)),
- Qt::LeftButton, Qt::MouseButtons(Qt::LeftButton), {});
- QCoreApplication::sendEvent(q, &mouseReleased);
+ if (guard) {
+ // The Cocoa popup will swallow any mouse release event.
+ // We need to fake one here to un-press the button.
+ QMouseEvent mouseReleased(QEvent::MouseButtonRelease, q->pos(), q->mapToGlobal(QPoint(0, 0)),
+ Qt::LeftButton, Qt::MouseButtons(Qt::LeftButton), {});
+ QCoreApplication::sendEvent(q, &mouseReleased);
+ }
#endif
return true;
@@ -2561,11 +2639,6 @@ void QComboBox::showPopup()
return;
#endif // Q_OS_MAC
- // set current item and select it
- QItemSelectionModel::SelectionFlags selectionMode = QItemSelectionModel::ClearAndSelect;
- if (view()->selectionBehavior() == QAbstractItemView::SelectRows)
- selectionMode.setFlag(QItemSelectionModel::Rows);
- view()->selectionModel()->setCurrentIndex(d->currentIndex, selectionMode);
QComboBoxPrivateContainer* container = d->viewContainer();
QRect listRect(style->subControlRect(QStyle::CC_ComboBox, &opt,
QStyle::SC_ComboBoxListBoxPopup, this));
@@ -2576,6 +2649,7 @@ void QComboBox::showPopup()
QPoint above = mapToGlobal(listRect.topLeft());
int aboveHeight = above.y() - screen.y();
bool boundToScreen = !window()->testAttribute(Qt::WA_DontShowOnScreen);
+ const auto listView = qobject_cast<QListView *>(d->viewContainer()->itemView());
{
int listHeight = 0;
@@ -2590,6 +2664,8 @@ void QComboBox::showPopup()
while (!toCheck.isEmpty()) {
QModelIndex parent = toCheck.pop();
for (int i = 0, end = d->model->rowCount(parent); i < end; ++i) {
+ if (listView && listView->isRowHidden(i))
+ continue;
QModelIndex idx = d->model->index(i, d->modelColumn, parent);
if (!idx.isValid())
continue;
@@ -2663,7 +2739,13 @@ void QComboBox::showPopup()
listRect.moveLeft(above.x());
// Position vertically so the currently selected item lines up
- // with the combo box.
+ // with the combo box. In order to do that, make sure that the item
+ // view is scrolled to the top first, otherwise calls to view()->visualRect()
+ // will return the geometry the selected item had the last time the popup
+ // was visible (and perhaps scrolled). And this will not match the geometry
+ // it will actually have when we resize the container to fit all the items
+ // further down in this function.
+ view()->scrollToTop();
const QRect currentItemRect = view()->visualRect(view()->currentIndex());
const int offset = listRect.top() - currentItemRect.top();
listRect.moveTop(above.y() + offset - listRect.top());
@@ -2796,31 +2878,30 @@ void QComboBox::hidePopup()
return;
#if QT_CONFIG(effects)
- // Flash selected/triggered item (if any).
- if (style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem)) {
- QItemSelectionModel *selectionModel = d->container->itemView()
- ? d->container->itemView()->selectionModel() : nullptr;
- if (selectionModel && selectionModel->hasSelection()) {
- const QItemSelection selection = selectionModel->selection();
-
- QTimer::singleShot(0, d->container, [d, selection, selectionModel]{
+ QItemSelectionModel *selectionModel = d->container->itemView()
+ ? d->container->itemView()->selectionModel() : nullptr;
+ // Flash selected/triggered item (if any) before hiding the popup.
+ if (style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem) &&
+ selectionModel && selectionModel->hasSelection()) {
+ const QItemSelection selection = selectionModel->selection();
+
+ QTimer::singleShot(0, d->container, [d, selection, selectionModel]{
+ QSignalBlocker modelBlocker(d->model);
+ QSignalBlocker viewBlocker(d->container->itemView());
+ QSignalBlocker containerBlocker(d->container);
+
+ // Deselect item and wait 60 ms.
+ selectionModel->select(selection, QItemSelectionModel::Toggle);
+ QTimer::singleShot(60, d->container, [d, selection, selectionModel]{
QSignalBlocker modelBlocker(d->model);
QSignalBlocker viewBlocker(d->container->itemView());
QSignalBlocker containerBlocker(d->container);
-
- // Deselect item and wait 60 ms.
selectionModel->select(selection, QItemSelectionModel::Toggle);
- QTimer::singleShot(60, d->container, [d, selection, selectionModel]{
- QSignalBlocker modelBlocker(d->model);
- QSignalBlocker viewBlocker(d->container->itemView());
- QSignalBlocker containerBlocker(d->container);
- selectionModel->select(selection, QItemSelectionModel::Toggle);
- QTimer::singleShot(20, d->container, [d] {
- d->doHidePopup();
- });
+ QTimer::singleShot(20, d->container, [d] {
+ d->doHidePopup();
});
});
- }
+ });
} else
#endif // QT_CONFIG(effects)
{
@@ -2833,7 +2914,16 @@ void QComboBoxPrivate::doHidePopup()
if (container && container->isVisible())
container->hide();
- _q_resetButton();
+ resetButton();
+}
+
+void QComboBoxPrivate::updateCurrentText(const QString &text)
+{
+ if (text == currentText)
+ return;
+
+ currentText = text;
+ emit q_func()->currentTextChanged(text);
}
/*!
@@ -2916,6 +3006,7 @@ void QComboBox::changeEvent(QEvent *e)
if (d->container)
d->container->updateStyleSettings();
d->updateDelegate();
+
#ifdef Q_OS_MAC
case QEvent::MacSizeChange:
#endif
@@ -3086,7 +3177,10 @@ void QComboBoxPrivate::showPopupFromMouseEvent(QMouseEvent *e)
// viewContainer(), we avoid creating the QComboBoxPrivateContainer.
viewContainer()->initialClickPosition = q->mapToGlobal(e->position().toPoint());
}
+ QPointer<QComboBox> guard = q;
q->showPopup();
+ if (!guard)
+ return;
// The code below ensures that regular mousepress and pick item still works
// If it was not called the viewContainer would ignore event since it didn't have
// a mousePressEvent first.
@@ -3218,15 +3312,17 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
break;
#endif
default:
- if (e->matches(QKeySequence::Cancel) && (!d->container || d->container->closeOnCancel)) {
+#if QT_CONFIG(shortcut)
+ if (d->container && d->container->isVisible() && e->matches(QKeySequence::Cancel)) {
hidePopup();
e->accept();
- d->container->closeOnCancel = false;
}
+#endif
if (!d->lineEdit) {
- if (!e->text().isEmpty())
- d->keyboardSearchString(e->text());
+ const auto text = e->text();
+ if (!text.isEmpty() && text.at(0).isPrint())
+ d->keyboardSearchString(text);
else
e->ignore();
}
@@ -3424,7 +3520,7 @@ QVariant QComboBox::inputMethodQuery(Qt::InputMethodQuery query, const QVariant
/*!
\property QComboBox::frame
- \brief whether the combo box draws itself with a frame
+ \brief whether the combo box draws itself with a frame.
If enabled (the default) the combo box draws itself inside a
diff --git a/src/widgets/widgets/qcombobox.h b/src/widgets/widgets/qcombobox.h
index be28ce7173..1689d0fa1e 100644
--- a/src/widgets/widgets/qcombobox.h
+++ b/src/widgets/widgets/qcombobox.h
@@ -204,21 +204,6 @@ protected:
private:
Q_DECLARE_PRIVATE(QComboBox)
Q_DISABLE_COPY(QComboBox)
- Q_PRIVATE_SLOT(d_func(), void _q_itemSelected(const QModelIndex &item))
- Q_PRIVATE_SLOT(d_func(), void _q_emitHighlighted(const QModelIndex &))
- Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentIndexChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_editingFinished())
- Q_PRIVATE_SLOT(d_func(), void _q_returnPressed())
- Q_PRIVATE_SLOT(d_func(), void _q_resetButton())
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &, const QModelIndex &))
- Q_PRIVATE_SLOT(d_func(), void _q_updateIndexBeforeChange())
- Q_PRIVATE_SLOT(d_func(), void _q_rowsInserted(const QModelIndex & parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsRemoved(const QModelIndex & parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_modelDestroyed())
- Q_PRIVATE_SLOT(d_func(), void _q_modelReset())
-#if QT_CONFIG(completer)
- Q_PRIVATE_SLOT(d_func(), void _q_completerActivated(const QModelIndex &index))
-#endif
};
inline void QComboBox::addItem(const QString &atext, const QVariant &auserData)
diff --git a/src/widgets/widgets/qcombobox_p.h b/src/widgets/widgets/qcombobox_p.h
index 2a694d27a4..723d637ae2 100644
--- a/src/widgets/widgets/qcombobox_p.h
+++ b/src/widgets/widgets/qcombobox_p.h
@@ -27,7 +27,6 @@
#include "QtGui/qpainter.h"
#include "QtWidgets/qstyle.h"
#include "QtWidgets/qstyleoption.h"
-#include "QtCore/qpair.h"
#include "QtCore/qtimer.h"
#include "private/qwidget_p.h"
#include "QtCore/qpointer.h"
@@ -49,7 +48,11 @@ class QComboBoxListView : public QListView
{
Q_OBJECT
public:
- QComboBoxListView(QComboBox *cmb = nullptr) : combo(cmb) {}
+ QComboBoxListView(QComboBox *cmb = nullptr) : combo(cmb)
+ {
+ if (cmb)
+ setScreen(cmb->screen());
+ }
protected:
void resizeEvent(QResizeEvent *event) override
@@ -180,6 +183,7 @@ class Q_WIDGETS_EXPORT QComboBoxPrivateContainer : public QFrame
public:
QComboBoxPrivateContainer(QAbstractItemView *itemView, QComboBox *parent);
+ ~QComboBoxPrivateContainer();
QAbstractItemView *itemView() const;
void setItemView(QAbstractItemView *itemView);
int spacing() const;
@@ -221,7 +225,6 @@ private:
QComboBoxPrivateScroller *bottom = nullptr;
QElapsedTimer popupTimer;
bool maybeIgnoreMouseButtonRelease = false;
- bool closeOnCancel = false;
friend class QComboBox;
friend class QComboBoxPrivate;
@@ -316,24 +319,25 @@ public:
QComboBoxPrivateContainer* viewContainer();
void updateLineEditGeometry();
Qt::MatchFlags matchFlags() const;
- void _q_editingFinished();
- void _q_returnPressed();
- void _q_complete();
- void _q_itemSelected(const QModelIndex &item);
+ void editingFinished();
+ void returnPressed();
+ void complete();
+ void itemSelected(const QModelIndex &item);
bool contains(const QString &text, int role);
void emitActivated(const QModelIndex &index);
- void _q_emitHighlighted(const QModelIndex &index);
- void _q_emitCurrentIndexChanged(const QModelIndex &index);
- void _q_modelDestroyed();
- void _q_modelReset();
+ void emitHighlighted(const QModelIndex &index);
+ void emitCurrentIndexChanged(const QModelIndex &index);
+ void modelDestroyed();
+ void modelReset();
+ void updateMicroFocus() { q_func()->updateMicroFocus(); } // PMF connect doesn't handle default args
#if QT_CONFIG(completer)
- void _q_completerActivated(const QModelIndex &index);
+ void completerActivated(const QModelIndex &index);
#endif
- void _q_resetButton();
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void _q_updateIndexBeforeChange();
- void _q_rowsInserted(const QModelIndex &parent, int start, int end);
- void _q_rowsRemoved(const QModelIndex &parent, int start, int end);
+ void resetButton();
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+ void updateIndexBeforeChange();
+ void rowsInserted(const QModelIndex &parent, int start, int end);
+ void rowsRemoved(const QModelIndex &parent, int start, int end);
void updateArrow(QStyle::StateFlag state);
bool updateHoverControl(const QPoint &pos);
void trySetValidIndex();
@@ -354,6 +358,9 @@ public:
void updateFocusPolicy();
void showPopupFromMouseEvent(QMouseEvent *e);
void doHidePopup();
+ void updateCurrentText(const QString &text);
+ void connectModel();
+ void disconnectModel();
#ifdef Q_OS_MAC
void cleanupNativePopup();
@@ -370,15 +377,17 @@ public:
};
#endif
+ std::array<QMetaObject::Connection, 8> modelConnections;
QAbstractItemModel *model = nullptr;
QLineEdit *lineEdit = nullptr;
- QComboBoxPrivateContainer *container = nullptr;
+ QPointer<QComboBoxPrivateContainer> container;
#ifdef Q_OS_MAC
QPlatformMenu *m_platformMenu = nullptr;
#endif
QPersistentModelIndex currentIndex;
QPersistentModelIndex root;
QString placeholderText;
+ QString currentText;
QRect hoverRect;
QSize iconSize;
mutable QSize minimumSizeHint;
diff --git a/src/widgets/widgets/qcommandlinkbutton.cpp b/src/widgets/widgets/qcommandlinkbutton.cpp
index 2c59e78c1a..5c7d2601d9 100644
--- a/src/widgets/widgets/qcommandlinkbutton.cpp
+++ b/src/widgets/widgets/qcommandlinkbutton.cpp
@@ -172,7 +172,7 @@ bool QCommandLinkButtonPrivate::usingVistaStyle() const
//### This is a hack to detect if we are indeed running Vista style themed and not in classic
// When we add api to query for this, we should change this implementation to use it.
return q->property("_qt_usingVistaStyle").toBool()
- && q->style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, nullptr) == 0;
+ && q->style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, nullptr, q) == 0;
}
void QCommandLinkButtonPrivate::init()
@@ -189,7 +189,7 @@ void QCommandLinkButtonPrivate::init()
q->setIconSize(QSize(20, 20));
QStyleOptionButton opt;
q->initStyleOption(&opt);
- q->setIcon(q->style()->standardIcon(QStyle::SP_CommandLink, &opt));
+ q->setIcon(q->style()->standardIcon(QStyle::SP_CommandLink, &opt, q));
}
// Calculates the height of the description text based on widget width
@@ -325,9 +325,9 @@ void QCommandLinkButton::paintEvent(QPaintEvent *)
QSize pixmapSize = icon().actualSize(iconSize());
const int vOffset = isDown()
- ? style()->pixelMetric(QStyle::PM_ButtonShiftVertical, &option) : 0;
+ ? style()->pixelMetric(QStyle::PM_ButtonShiftVertical, &option, this) : 0;
const int hOffset = isDown()
- ? style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, &option) : 0;
+ ? style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, &option, this) : 0;
//Draw icon
p.drawControl(QStyle::CE_PushButton, option);
diff --git a/src/widgets/widgets/qdatetimeedit.cpp b/src/widgets/widgets/qdatetimeedit.cpp
index ac4d4cdc8c..01e52b2fa6 100644
--- a/src/widgets/widgets/qdatetimeedit.cpp
+++ b/src/widgets/widgets/qdatetimeedit.cpp
@@ -16,9 +16,6 @@
#include <qset.h>
#include <qstyle.h>
#include <qstylepainter.h>
-#if QT_CONFIG(timezone)
-#include <QTimeZone>
-#endif
#include <algorithm>
@@ -190,8 +187,8 @@ QDateTimeEdit::QDateTimeEdit(QTime time, QWidget *parent)
\internal
*/
QDateTimeEdit::QDateTimeEdit(const QVariant &var, QMetaType::Type parserType, QWidget *parent)
- : QAbstractSpinBox(*new QDateTimeEditPrivate(
- parserType == QMetaType::QDateTime ? Qt::LocalTime : Qt::UTC),
+ : QAbstractSpinBox(*new QDateTimeEditPrivate(parserType == QMetaType::QDateTime
+ ? QTimeZone::LocalTime : QTimeZone::UTC),
parent)
{
Q_D(QDateTimeEdit);
@@ -210,8 +207,8 @@ QDateTimeEdit::~QDateTimeEdit()
\property QDateTimeEdit::dateTime
\brief The QDateTime that is set in the QDateTimeEdit.
- When setting this property, the new QDateTime is converted to the timespec of
- the QDateTimeEdit, which thus remains unchanged.
+ When setting this property, the new QDateTime is converted to the time system
+ of the QDateTimeEdit, which thus remains unchanged.
By default, this property is set to the start of 2000 CE. It can only be set
to a valid QDateTime value. If any operation causes this property to have an
@@ -222,7 +219,7 @@ QDateTimeEdit::~QDateTimeEdit()
widget's date-range to start and end on the date of the new value of this
property.
- \sa date, time, minimumDateTime, maximumDateTime
+ \sa date, time, minimumDateTime, maximumDateTime, timeZone
*/
QDateTime QDateTimeEdit::dateTime() const
@@ -235,8 +232,8 @@ void QDateTimeEdit::setDateTime(const QDateTime &datetime)
{
Q_D(QDateTimeEdit);
if (datetime.isValid()) {
- QDateTime when = d->convertTimeSpec(datetime);
- Q_ASSERT(when.timeSpec() == d->spec);
+ QDateTime when = d->convertTimeZone(datetime);
+ Q_ASSERT(when.timeRepresentation() == d->timeZone);
d->clearCache();
const QDate date = when.date();
@@ -272,14 +269,10 @@ void QDateTimeEdit::setDate(QDate date)
setDateRange(date, date);
d->clearCache();
- QDateTime when(date, d->value.toTime(), d->spec);
- // The specified time might not exist on the specified day,
- // i.e. the time is in the gap a spring-forward jumps over.
- if (!when.isValid())
- when = QDateTime::fromMSecsSinceEpoch(when.toMSecsSinceEpoch(), d->spec);
+ QDateTime when = d->dateTimeValue(date, d->value.toTime());
Q_ASSERT(when.isValid());
d->setValue(when, EmitIfChanged);
- d->updateTimeSpec();
+ d->updateTimeZone();
}
}
@@ -306,7 +299,7 @@ void QDateTimeEdit::setTime(QTime time)
Q_D(QDateTimeEdit);
if (time.isValid()) {
d->clearCache();
- d->setValue(QDateTime(d->value.toDate(), time, d->spec), EmitIfChanged);
+ d->setValue(d->dateTimeValue(d->value.toDate(), time), EmitIfChanged);
}
}
@@ -363,7 +356,7 @@ void QDateTimeEdit::setMinimumDateTime(const QDateTime &dt)
{
Q_D(QDateTimeEdit);
if (dt.isValid() && dt.date() >= QDATETIMEEDIT_DATE_MIN) {
- const QDateTime m = dt.toTimeSpec(d->spec);
+ const QDateTime m = dt.toTimeZone(d->timeZone);
const QDateTime max = d->maximum.toDateTime();
d->setRange(m, (max > m ? max : m));
}
@@ -405,7 +398,7 @@ void QDateTimeEdit::setMaximumDateTime(const QDateTime &dt)
{
Q_D(QDateTimeEdit);
if (dt.isValid() && dt.date() <= QDATETIMEEDIT_DATE_MAX) {
- const QDateTime m = dt.toTimeSpec(d->spec);
+ const QDateTime m = dt.toTimeZone(d->timeZone);
const QDateTime min = d->minimum.toDateTime();
d->setRange((min < m ? min : m), m);
}
@@ -439,8 +432,8 @@ void QDateTimeEdit::setDateTimeRange(const QDateTime &min, const QDateTime &max)
{
Q_D(QDateTimeEdit);
// FIXME: does none of the range checks applied to setMin/setMax methods !
- const QDateTime minimum = min.toTimeSpec(d->spec);
- const QDateTime maximum = (min > max ? minimum : max.toTimeSpec(d->spec));
+ const QDateTime minimum = min.toTimeZone(d->timeZone);
+ const QDateTime maximum = (min > max ? minimum : max.toTimeZone(d->timeZone));
d->setRange(minimum, maximum);
}
@@ -475,9 +468,8 @@ QDate QDateTimeEdit::minimumDate() const
void QDateTimeEdit::setMinimumDate(QDate min)
{
Q_D(QDateTimeEdit);
- if (min.isValid() && min >= QDATETIMEEDIT_DATE_MIN) {
- setMinimumDateTime(QDateTime(min, d->minimum.toTime(), d->spec));
- }
+ if (min.isValid() && min >= QDATETIMEEDIT_DATE_MIN)
+ setMinimumDateTime(d->dateTimeValue(min, d->minimum.toTime()));
}
void QDateTimeEdit::clearMinimumDate()
@@ -517,7 +509,7 @@ void QDateTimeEdit::setMaximumDate(QDate max)
{
Q_D(QDateTimeEdit);
if (max.isValid())
- setMaximumDateTime(QDateTime(max, d->maximum.toTime(), d->spec));
+ setMaximumDateTime(d->dateTimeValue(max, d->maximum.toTime()));
}
void QDateTimeEdit::clearMaximumDate()
@@ -554,10 +546,8 @@ QTime QDateTimeEdit::minimumTime() const
void QDateTimeEdit::setMinimumTime(QTime min)
{
Q_D(QDateTimeEdit);
- if (min.isValid()) {
- const QDateTime m(d->minimum.toDate(), min, d->spec);
- setMinimumDateTime(m);
- }
+ if (min.isValid())
+ setMinimumDateTime(d->dateTimeValue(d->minimum.toDate(), min));
}
void QDateTimeEdit::clearMinimumTime()
@@ -593,10 +583,8 @@ QTime QDateTimeEdit::maximumTime() const
void QDateTimeEdit::setMaximumTime(QTime max)
{
Q_D(QDateTimeEdit);
- if (max.isValid()) {
- const QDateTime m(d->maximum.toDate(), max, d->spec);
- setMaximumDateTime(m);
- }
+ if (max.isValid())
+ setMaximumDateTime(d->dateTimeValue(d->maximum.toDate(), max));
}
void QDateTimeEdit::clearMaximumTime()
@@ -634,8 +622,8 @@ void QDateTimeEdit::setDateRange(QDate min, QDate max)
{
Q_D(QDateTimeEdit);
if (min.isValid() && max.isValid()) {
- setDateTimeRange(QDateTime(min, d->minimum.toTime(), d->spec),
- QDateTime(max, d->maximum.toTime(), d->spec));
+ setDateTimeRange(d->dateTimeValue(min, d->minimum.toTime()),
+ d->dateTimeValue(max, d->maximum.toTime()));
}
}
@@ -673,8 +661,8 @@ void QDateTimeEdit::setTimeRange(QTime min, QTime max)
{
Q_D(QDateTimeEdit);
if (min.isValid() && max.isValid()) {
- setDateTimeRange(QDateTime(d->minimum.toDate(), min, d->spec),
- QDateTime(d->maximum.toDate(), max, d->spec));
+ setDateTimeRange(d->dateTimeValue(d->minimum.toDate(), min),
+ d->dateTimeValue(d->maximum.toDate(), max));
}
}
@@ -957,10 +945,10 @@ void QDateTimeEdit::setDisplayFormat(const QString &format)
}
} else if (dateShown && !timeShown) {
setTimeRange(QDATETIMEEDIT_TIME_MIN, QDATETIMEEDIT_TIME_MAX);
- d->value = d->value.toDate().startOfDay(d->spec);
+ d->value = d->value.toDate().startOfDay(d->timeZone);
}
d->updateEdit();
- d->_q_editorCursorPositionChanged(-1, 0);
+ d->editorCursorPositionChanged(-1, 0);
}
}
@@ -996,24 +984,70 @@ void QDateTimeEdit::setCalendarPopup(bool enable)
update();
}
+#if QT_DEPRECATED_SINCE(6, 10)
/*!
\property QDateTimeEdit::timeSpec
- \brief The current timespec used by the date time edit.
\since 4.4
+ \deprecated[6.10] Use QDateTimeEdit::timeZone instead.
+ \brief The current timespec used by the date time edit.
+
+ Since Qt 6.7 this is an indirect accessor for the timeZone property.
+
+ \sa QDateTimeEdit::timeZone
*/
Qt::TimeSpec QDateTimeEdit::timeSpec() const
{
Q_D(const QDateTimeEdit);
- return d->spec;
+ return d->timeZone.timeSpec();
}
void QDateTimeEdit::setTimeSpec(Qt::TimeSpec spec)
{
Q_D(QDateTimeEdit);
- if (spec != d->spec) {
- d->spec = spec;
- d->updateTimeSpec();
+ if (spec != d->timeZone.timeSpec()) {
+ switch (spec) {
+ case Qt::UTC:
+ setTimeZone(QTimeZone::UTC);
+ break;
+ case Qt::LocalTime:
+ setTimeZone(QTimeZone::LocalTime);
+ break;
+ default:
+ qWarning() << "Ignoring attempt to set time-spec" << spec
+ << "which needs ancillary data: see setTimeZone()";
+ return;
+ }
+ }
+}
+#endif // 6.10 deprecation
+
+// TODO: enable user input to control timeZone, when the format includes it.
+/*!
+ \property QDateTimeEdit::timeZone
+ \since 6.7
+ \brief The current timezone used by the datetime editing widget
+
+ If the datetime format in use includes a timezone indicator - that is, a
+ \c{t}, \c{tt}, \c{ttt} or \c{tttt} format specifier - the user's input is
+ re-expressed in this timezone whenever it is parsed, overriding any timezone
+ the user may have specified.
+
+ \sa QDateTimeEdit::displayFormat
+*/
+
+QTimeZone QDateTimeEdit::timeZone() const
+{
+ Q_D(const QDateTimeEdit);
+ return d->timeZone;
+}
+
+void QDateTimeEdit::setTimeZone(const QTimeZone &zone)
+{
+ Q_D(QDateTimeEdit);
+ if (zone != d->timeZone) {
+ d->timeZone = zone;
+ d->updateTimeZone();
}
}
@@ -1297,6 +1331,7 @@ void QDateTimeEdit::focusInEvent(QFocusEvent *event)
case Qt::ActiveWindowFocusReason:
if (oldHasHadFocus)
return;
+ break;
case Qt::ShortcutFocusReason:
case Qt::TabFocusReason:
default:
@@ -1389,7 +1424,7 @@ void QDateTimeEdit::stepBy(int steps)
d->updateCache(d->value, d->displayText());
d->setSelected(d->currentSectionIndex);
- d->updateTimeSpec();
+ d->updateTimeZone();
}
/*!
@@ -1448,15 +1483,11 @@ void QDateTimeEdit::fixup(QString &input) const
int copy = d->edit->cursorPosition();
QDateTime value = d->validateAndInterpret(input, copy, state, true);
- /*
- String was valid, but the datetime still is not; use the time that
- has the same distance from epoch.
- CorrectToPreviousValue correction is handled by QAbstractSpinBox.
- */
- if (!value.isValid() && d->correctionMode == QAbstractSpinBox::CorrectToNearestValue) {
- value = QDateTime::fromMSecsSinceEpoch(value.toMSecsSinceEpoch(), value.timeSpec());
+ // CorrectToPreviousValue correction is handled by QAbstractSpinBox.
+ // The value might not match the input if the input represents a date-time
+ // skipped over by its time representation, such as a spring-forward.
+ if (d->correctionMode == QAbstractSpinBox::CorrectToNearestValue)
input = textFromDateTime(value);
- }
}
@@ -1703,54 +1734,42 @@ QDateEdit::~QDateEdit()
*/
-QDateTimeEditPrivate::QDateTimeEditPrivate(Qt::TimeSpec timeSpec)
+QDateTimeEditPrivate::QDateTimeEditPrivate(const QTimeZone &zone)
: QDateTimeParser(QMetaType::QDateTime, QDateTimeParser::DateTimeEdit, QCalendar()),
- spec(timeSpec)
+ timeZone(zone)
{
fixday = true;
type = QMetaType::QDateTime;
currentSectionIndex = FirstSectionIndex;
first.pos = 0;
- minimum = QDATETIMEEDIT_COMPAT_DATE_MIN.startOfDay(spec);
- maximum = QDATETIMEEDIT_DATE_MAX.endOfDay(spec);
+ minimum = QDATETIMEEDIT_COMPAT_DATE_MIN.startOfDay(timeZone);
+ maximum = QDATETIMEEDIT_DATE_MAX.endOfDay(timeZone);
readLocaleSettings();
}
-QDateTime QDateTimeEditPrivate::convertTimeSpec(const QDateTime &datetime)
+QDateTime QDateTimeEditPrivate::convertTimeZone(const QDateTime &datetime)
{
- Q_ASSERT(value.toDateTime().timeSpec() == spec);
- switch (spec) {
- case Qt::UTC:
- return datetime.toUTC();
- case Qt::LocalTime:
- return datetime.toLocalTime();
- case Qt::OffsetFromUTC:
- return datetime.toOffsetFromUtc(value.toDateTime().offsetFromUtc());
- case Qt::TimeZone:
-#if QT_CONFIG(timezone)
- return datetime.toTimeZone(value.toDateTime().timeZone());
-#else
- qWarning("QDateTimeEdit: Internal: enable timezone feature to support Qt::TimeZone");
- return datetime;
-#endif
- }
- Q_UNREACHABLE();
+ return datetime.toTimeZone(timeZone);
}
-// FIXME: architecturaly incompatible with OffsetFromUTC or TimeZone as spec (QTBUG-80417).
-void QDateTimeEditPrivate::updateTimeSpec()
+QDateTime QDateTimeEditPrivate::dateTimeValue(QDate date, QTime time) const
{
- minimum = minimum.toDateTime().toTimeSpec(spec);
- maximum = maximum.toDateTime().toTimeSpec(spec);
- value = value.toDateTime().toTimeSpec(spec);
+ return QDateTime(date, time, timeZone);
+}
+
+void QDateTimeEditPrivate::updateTimeZone()
+{
+ minimum = minimum.toDateTime().toTimeZone(timeZone);
+ maximum = maximum.toDateTime().toTimeZone(timeZone);
+ value = value.toDateTime().toTimeZone(timeZone);
// time zone changes can lead to 00:00:00 becomes 01:00:00 and 23:59:59 becomes 00:59:59 (invalid range)
const bool dateShown = (sections & QDateTimeEdit::DateSections_Mask);
if (!dateShown) {
if (minimum.toTime() >= maximum.toTime()){
- minimum = value.toDate().startOfDay(spec);
- maximum = value.toDate().endOfDay(spec);
+ minimum = value.toDate().startOfDay(timeZone);
+ maximum = value.toDate().endOfDay(timeZone);
}
}
}
@@ -1785,6 +1804,27 @@ void QDateTimeEditPrivate::updateEdit()
}
}
+QDateTime QDateTimeEditPrivate::getMinimum() const
+{
+ if (keyboardTracking)
+ return minimum.toDateTime();
+
+ if (timeZone.timeSpec() == Qt::LocalTime)
+ return QDateTimeParser::getMinimum();
+
+ return QDATETIMEEDIT_DATE_MIN.startOfDay(timeZone);
+}
+
+QDateTime QDateTimeEditPrivate::getMaximum() const
+{
+ if (keyboardTracking)
+ return maximum.toDateTime();
+
+ if (timeZone.timeSpec() == Qt::LocalTime)
+ return QDateTimeParser::getMaximum();
+
+ return QDATETIMEEDIT_DATE_MAX.endOfDay(timeZone);
+}
/*!
\internal
@@ -1997,8 +2037,10 @@ QDateTime QDateTimeEditPrivate::validateAndInterpret(QString &input, int &positi
StateNode tmp = parse(input, position, value.toDateTime(), fixup);
// Take note of any corrections imposed during parsing:
input = m_text;
- // Impose this widget's spec:
- tmp.value = tmp.value.toTimeSpec(spec);
+ // TODO: if the format specifies time-zone, update timeZone to match the
+ // parsed text; but we're in const context, so can't - QTBUG-118393.
+ // Impose this widget's time system:
+ tmp.value = tmp.value.toTimeZone(timeZone);
// ... but that might turn a valid datetime into an invalid one:
if (!tmp.value.isValid() && tmp.state == Acceptable)
tmp.state = Intermediate;
@@ -2044,7 +2086,7 @@ QString QDateTimeEditPrivate::textFromValue(const QVariant &f) const
QVariant QDateTimeEditPrivate::valueFromText(const QString &f) const
{
Q_Q(const QDateTimeEdit);
- return q->dateTimeFromText(f).toTimeSpec(spec);
+ return q->dateTimeFromText(f).toTimeZone(timeZone);
}
@@ -2119,12 +2161,11 @@ QDateTime QDateTimeEditPrivate::stepBy(int sectionIndex, int steps, bool test) c
true when date and time are valid, even if the date-time returned
isn't), so use the time that has the same distance from epoch.
*/
- if (setDigit(v, sectionIndex, val) && !v.isValid()) {
- auto msecsSinceEpoch = v.toMSecsSinceEpoch();
+ if (setDigit(v, sectionIndex, val) && getDigit(v, sectionIndex) != val
+ && sn.type & HourSectionMask && steps < 0) {
// decreasing from e.g 3am to 2am would get us back to 3am, but we want 1am
- if (steps < 0 && sn.type & HourSectionMask)
- msecsSinceEpoch -= 3600 * 1000;
- v = QDateTime::fromMSecsSinceEpoch(msecsSinceEpoch, v.timeSpec());
+ auto msecsSinceEpoch = v.toMSecsSinceEpoch() - 3600 * 1000;
+ v = QDateTime::fromMSecsSinceEpoch(msecsSinceEpoch, v.timeRepresentation());
}
// if this sets year or month it will make
// sure that days are lowered if needed.
@@ -2220,8 +2261,7 @@ QDateTime QDateTimeEditPrivate::stepBy(int sectionIndex, int steps, bool test) c
}
}
- const QDateTime ret = bound(v, value, steps).toDateTime().toTimeSpec(spec);
- return ret;
+ return bound(v, value, steps).toDateTime().toTimeZone(timeZone);
}
/*!
@@ -2257,7 +2297,7 @@ void QDateTimeEditPrivate::emitSignals(EmitPolicy ep, const QVariant &old)
\internal
*/
-void QDateTimeEditPrivate::_q_editorCursorPositionChanged(int oldpos, int newpos)
+void QDateTimeEditPrivate::editorCursorPositionChanged(int oldpos, int newpos)
{
if (ignoreCursorPositionChanged || specialValue())
return;
@@ -2315,7 +2355,7 @@ void QDateTimeEditPrivate::_q_editorCursorPositionChanged(int oldpos, int newpos
currentSectionIndex = s;
Q_ASSERT_X(currentSectionIndex < sectionNodes.size(),
- "QDateTimeEditPrivate::_q_editorCursorPositionChanged()",
+ "QDateTimeEditPrivate::editorCursorPositionChanged()",
qPrintable(QString::fromLatin1("Internal error (%1 %2)").
arg(currentSectionIndex).
arg(sectionNodes.size())));
@@ -2439,7 +2479,7 @@ void QDateTimeEditPrivate::interpret(EmitPolicy ep)
|| currentSectionIndex < 0
|| !(fieldInfo(currentSectionIndex) & AllowPartial))) {
setValue(value, ep);
- updateTimeSpec();
+ updateTimeZone();
} else {
QAbstractSpinBoxPrivate::interpret(ep);
}
@@ -2480,22 +2520,22 @@ void QDateTimeEditPrivate::init(const QVariant &var)
Q_Q(QDateTimeEdit);
switch (var.userType()) {
case QMetaType::QDate:
- value = var.toDate().startOfDay(spec);
- updateTimeSpec();
+ value = var.toDate().startOfDay(timeZone);
+ updateTimeZone();
q->setDisplayFormat(defaultDateFormat);
if (sectionNodes.isEmpty()) // ### safeguard for broken locale
q->setDisplayFormat("dd/MM/yyyy"_L1);
break;
case QMetaType::QDateTime:
value = var;
- updateTimeSpec();
+ updateTimeZone();
q->setDisplayFormat(defaultDateTimeFormat);
if (sectionNodes.isEmpty()) // ### safeguard for broken locale
q->setDisplayFormat("dd/MM/yyyy hh:mm:ss"_L1);
break;
case QMetaType::QTime:
- value = QDateTime(QDATETIMEEDIT_DATE_INITIAL, var.toTime(), spec);
- updateTimeSpec();
+ value = dateTimeValue(QDATETIMEEDIT_DATE_INITIAL, var.toTime());
+ updateTimeZone();
q->setDisplayFormat(defaultTimeFormat);
if (sectionNodes.isEmpty()) // ### safeguard for broken locale
q->setDisplayFormat("hh:mm:ss"_L1);
@@ -2573,7 +2613,7 @@ void QDateTimeEditPrivate::updateEditFieldGeometry()
QVariant QDateTimeEditPrivate::getZeroVariant() const
{
Q_ASSERT(type == QMetaType::QDateTime);
- return QDateTime(QDATETIMEEDIT_DATE_INITIAL, QTime(), spec);
+ return QDATETIMEEDIT_DATE_INITIAL.startOfDay(timeZone);
}
void QDateTimeEditPrivate::setRange(const QVariant &min, const QVariant &max)
diff --git a/src/widgets/widgets/qdatetimeedit.h b/src/widgets/widgets/qdatetimeedit.h
index acef0c5359..f7c0dd7374 100644
--- a/src/widgets/widgets/qdatetimeedit.h
+++ b/src/widgets/widgets/qdatetimeedit.h
@@ -5,7 +5,7 @@
#define QDATETIMEEDIT_H
#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtCore/qdatetime.h>
+#include <QtCore/qtimezone.h>
#include <QtCore/qcalendar.h>
#include <QtCore/qvariant.h>
#include <QtWidgets/qabstractspinbox.h>
@@ -39,7 +39,10 @@ class Q_WIDGETS_EXPORT QDateTimeEdit : public QAbstractSpinBox
Q_PROPERTY(bool calendarPopup READ calendarPopup WRITE setCalendarPopup)
Q_PROPERTY(int currentSectionIndex READ currentSectionIndex WRITE setCurrentSectionIndex)
Q_PROPERTY(int sectionCount READ sectionCount)
+#if QT_DEPRECATED_SINCE(6, 10)
Q_PROPERTY(Qt::TimeSpec timeSpec READ timeSpec WRITE setTimeSpec)
+#endif
+ Q_PROPERTY(QTimeZone timeZone READ timeZone WRITE setTimeZone)
public:
enum Section { // a sub-type of QDateTimeParser's like-named enum.
NoSection = 0x0000,
@@ -125,8 +128,14 @@ public:
bool calendarPopup() const;
void setCalendarPopup(bool enable);
+#if QT_DEPRECATED_SINCE(6, 10)
+ QT_DEPRECATED_VERSION_X_6_10("Use timeZone() instead")
Qt::TimeSpec timeSpec() const;
+ QT_DEPRECATED_VERSION_X_6_10("Use setTimeZone() instead")
void setTimeSpec(Qt::TimeSpec spec);
+#endif
+ QTimeZone timeZone() const;
+ void setTimeZone(const QTimeZone &zone);
QSize sizeHint() const override;
diff --git a/src/widgets/widgets/qdatetimeedit_p.h b/src/widgets/widgets/qdatetimeedit_p.h
index 7a04443079..215ee75bfe 100644
--- a/src/widgets/widgets/qdatetimeedit_p.h
+++ b/src/widgets/widgets/qdatetimeedit_p.h
@@ -17,6 +17,8 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtCore/qcalendar.h>
+#include <QtCore/qdatetime.h>
+#include <QtCore/qtimezone.h>
#include "QtWidgets/qcalendarwidget.h"
#include "QtWidgets/qspinbox.h"
#include "QtWidgets/qtoolbutton.h"
@@ -26,6 +28,7 @@
#include "private/qdatetimeparser_p.h"
#include "qdebug.h"
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
@@ -34,7 +37,7 @@ class Q_AUTOTEST_EXPORT QDateTimeEditPrivate : public QAbstractSpinBoxPrivate, p
{
Q_DECLARE_PUBLIC(QDateTimeEdit)
public:
- QDateTimeEditPrivate(Qt::TimeSpec timeSpec = Qt::LocalTime);
+ QDateTimeEditPrivate(const QTimeZone &zone = QTimeZone::LocalTime);
void init(const QVariant &var);
void readLocaleSettings();
@@ -47,7 +50,7 @@ public:
void emitSignals(EmitPolicy ep, const QVariant &old) override;
QString textFromValue(const QVariant &f) const override;
QVariant valueFromText(const QString &f) const override;
- void _q_editorCursorPositionChanged(int oldpos, int newpos) override;
+ void editorCursorPositionChanged(int oldpos, int newpos) override;
void interpret(EmitPolicy ep) override;
void clearCache() const override;
QStyle::SubControl newHoverControl(const QPoint &pos) override;
@@ -58,22 +61,8 @@ public:
// Override QDateTimeParser:
QString displayText() const override { return edit->text(); }
- QDateTime getMinimum() const override
- {
- if (keyboardTracking)
- return minimum.toDateTime();
- if (spec != Qt::LocalTime)
- return QDateTime(QDATETIMEEDIT_DATE_MIN.startOfDay(spec));
- return QDateTimeParser::getMinimum();
- }
- QDateTime getMaximum() const override
- {
- if (keyboardTracking)
- return maximum.toDateTime();
- if (spec != Qt::LocalTime)
- return QDateTime(QDATETIMEEDIT_DATE_MAX.endOfDay(spec));
- return QDateTimeParser::getMaximum();
- }
+ QDateTime getMinimum() const override;
+ QDateTime getMaximum() const override;
QLocale locale() const override { return q_func()->locale(); }
int cursorPosition() const override { return edit ? edit->cursorPosition() : -1; }
@@ -87,9 +76,10 @@ public:
void updateCache(const QVariant &val, const QString &str) const;
- QDateTime convertTimeSpec(const QDateTime &datetime);
- void updateTimeSpec();
+ QDateTime convertTimeZone(const QDateTime &datetime);
+ void updateTimeZone();
QString valueToText(const QVariant &var) const { return textFromValue(var); }
+ QDateTime dateTimeValue(QDate date, QTime time) const;
void _q_resetButton();
void updateArrow(QStyle::StateFlag state);
@@ -117,7 +107,7 @@ public:
bool focusOnButton = false;
#endif
- Qt::TimeSpec spec;
+ QTimeZone timeZone;
};
diff --git a/src/widgets/widgets/qdial.cpp b/src/widgets/widgets/qdial.cpp
index e16b6eadaf..14e96f8dc3 100644
--- a/src/widgets/widgets/qdial.cpp
+++ b/src/widgets/widgets/qdial.cpp
@@ -58,6 +58,8 @@ int QDialPrivate::bound(int val) const
if (wrapping) {
if ((val >= minimum) && (val <= maximum))
return val;
+ if (minimum == maximum)
+ return minimum;
val = minimum + ((val - minimum) % (maximum - minimum));
if (val < minimum)
val += maximum - minimum;
diff --git a/src/widgets/widgets/qdialogbuttonbox.cpp b/src/widgets/widgets/qdialogbuttonbox.cpp
index 1f8bdc0f94..30ace89fa8 100644
--- a/src/widgets/widgets/qdialogbuttonbox.cpp
+++ b/src/widgets/widgets/qdialogbuttonbox.cpp
@@ -14,6 +14,9 @@
#include <QtGui/qaction.h>
#include "qdialogbuttonbox.h"
+#include "qdialogbuttonbox_p.h"
+
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
@@ -53,7 +56,7 @@ QT_BEGIN_NAMESPACE
the buttons (or button texts) yourself and add them to the button box,
specifying their role.
- \snippet dialogs/extension/finddialog.cpp 1
+ \snippet dialogs/dialogs.cpp buttonbox
Alternatively, QDialogButtonBox provides several standard buttons (e.g. OK, Cancel, Save)
that you can use. They exist as flags so you can OR them together in the constructor.
@@ -111,39 +114,25 @@ QT_BEGIN_NAMESPACE
\sa QMessageBox, QPushButton, QDialog
*/
-
-class QDialogButtonBoxPrivate : public QWidgetPrivate
+QDialogButtonBoxPrivate::QDialogButtonBoxPrivate(Qt::Orientation orient)
+ : orientation(orient), buttonLayout(nullptr), center(false)
{
- Q_DECLARE_PUBLIC(QDialogButtonBox)
-
-public:
- QDialogButtonBoxPrivate(Qt::Orientation orient);
-
- QList<QAbstractButton *> buttonLists[QDialogButtonBox::NRoles];
- QHash<QPushButton *, QDialogButtonBox::StandardButton> standardButtonHash;
-
- Qt::Orientation orientation;
- QDialogButtonBox::ButtonLayout layoutPolicy;
- QBoxLayout *buttonLayout;
- bool internalRemove;
- bool center;
+ struct EventFilter : public QObject
+ {
+ EventFilter(QDialogButtonBoxPrivate *d) : d(d) {};
+
+ bool eventFilter(QObject *obj, QEvent *event) override
+ {
+ QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
+ return button ? d->handleButtonShowAndHide(button, event) : false;
+ }
- void createStandardButtons(QDialogButtonBox::StandardButtons buttons);
+ private:
+ QDialogButtonBoxPrivate *d;
- void layoutButtons();
- void initLayout();
- void resetLayout();
- QPushButton *createButton(QDialogButtonBox::StandardButton button, bool doLayout = true);
- void addButton(QAbstractButton *button, QDialogButtonBox::ButtonRole role, bool doLayout = true);
- void _q_handleButtonDestroyed();
- void _q_handleButtonClicked();
- void addButtonsToLayout(const QList<QAbstractButton *> &buttonList, bool reverse);
- void retranslateStrings();
-};
+ };
-QDialogButtonBoxPrivate::QDialogButtonBoxPrivate(Qt::Orientation orient)
- : orientation(orient), buttonLayout(nullptr), internalRemove(false), center(false)
-{
+ filter.reset(new EventFilter(this));
}
void QDialogButtonBoxPrivate::initLayout()
@@ -177,7 +166,6 @@ void QDialogButtonBoxPrivate::initLayout()
void QDialogButtonBoxPrivate::resetLayout()
{
- //delete buttonLayout;
initLayout();
layoutButtons();
}
@@ -201,6 +189,7 @@ void QDialogButtonBoxPrivate::layoutButtons()
Q_Q(QDialogButtonBox);
const int MacGap = 36 - 8; // 8 is the default gap between a widget and a spacer item
+ QBoolBlocker blocker(ignoreShowAndHide);
for (int i = buttonLayout->count() - 1; i >= 0; --i) {
QLayoutItem *item = buttonLayout->takeAt(i);
if (QWidget *widget = item->widget())
@@ -293,16 +282,20 @@ void QDialogButtonBoxPrivate::layoutButtons()
++currentLayout;
}
- QWidget *lastWidget = nullptr;
- q->setFocusProxy(nullptr);
+ QWidgetList layoutWidgets;
for (int i = 0; i < buttonLayout->count(); ++i) {
- QLayoutItem *item = buttonLayout->itemAt(i);
- if (QWidget *widget = item->widget()) {
- if (lastWidget)
- QWidget::setTabOrder(lastWidget, widget);
- else
- q->setFocusProxy(widget);
- lastWidget = widget;
+ if (auto *widget = buttonLayout->itemAt(i)->widget())
+ layoutWidgets << widget;
+ }
+
+ q->setFocusProxy(nullptr);
+ if (!layoutWidgets.isEmpty()) {
+ QWidget *prev = layoutWidgets.constLast();
+ for (QWidget *here : layoutWidgets) {
+ QWidget::setTabOrder(prev, here);
+ prev = here;
+ if (auto *pushButton = qobject_cast<QPushButton *>(prev); pushButton && pushButton->isDefault())
+ q->setFocusProxy(pushButton);
}
}
@@ -311,7 +304,7 @@ void QDialogButtonBoxPrivate::layoutButtons()
}
QPushButton *QDialogButtonBoxPrivate::createButton(QDialogButtonBox::StandardButton sbutton,
- bool doLayout)
+ LayoutRule layoutRule)
{
Q_Q(QDialogButtonBox);
int icon = 0;
@@ -386,7 +379,7 @@ QPushButton *QDialogButtonBoxPrivate::createButton(QDialogButtonBox::StandardBut
if (Q_UNLIKELY(role == QPlatformDialogHelper::InvalidRole))
qWarning("QDialogButtonBox::createButton: Invalid ButtonRole, button not added");
else
- addButton(button, static_cast<QDialogButtonBox::ButtonRole>(role), doLayout);
+ addButton(button, static_cast<QDialogButtonBox::ButtonRole>(role), layoutRule);
#if QT_CONFIG(shortcut)
const QKeySequence standardShortcut = QGuiApplicationPrivate::platformTheme()->standardButtonShortcut(sbutton);
if (!standardShortcut.isEmpty())
@@ -396,23 +389,36 @@ QPushButton *QDialogButtonBoxPrivate::createButton(QDialogButtonBox::StandardBut
}
void QDialogButtonBoxPrivate::addButton(QAbstractButton *button, QDialogButtonBox::ButtonRole role,
- bool doLayout)
+ LayoutRule layoutRule, AddRule addRule)
{
- Q_Q(QDialogButtonBox);
- QObject::connect(button, SIGNAL(clicked()), q, SLOT(_q_handleButtonClicked()));
- QObject::connect(button, SIGNAL(destroyed()), q, SLOT(_q_handleButtonDestroyed()));
buttonLists[role].append(button);
- if (doLayout)
+ switch (addRule) {
+ case AddRule::Connect:
+ QObjectPrivate::connect(button, &QAbstractButton::clicked,
+ this, &QDialogButtonBoxPrivate::handleButtonClicked);
+ QObjectPrivate::connect(button, &QAbstractButton::destroyed,
+ this, &QDialogButtonBoxPrivate::handleButtonDestroyed);
+ button->installEventFilter(filter.get());
+ break;
+ case AddRule::SkipConnect:
+ break;
+ }
+
+ switch (layoutRule) {
+ case LayoutRule::DoLayout:
layoutButtons();
+ break;
+ case LayoutRule::SkipLayout:
+ break;
+ }
}
void QDialogButtonBoxPrivate::createStandardButtons(QDialogButtonBox::StandardButtons buttons)
{
uint i = QDialogButtonBox::FirstButton;
while (i <= QDialogButtonBox::LastButton) {
- if (i & buttons) {
- createButton(QDialogButtonBox::StandardButton(i), false);
- }
+ if (i & buttons)
+ createButton(QDialogButtonBox::StandardButton(i), LayoutRule::SkipLayout);
i = i << 1;
}
layoutButtons();
@@ -420,13 +426,10 @@ void QDialogButtonBoxPrivate::createStandardButtons(QDialogButtonBox::StandardBu
void QDialogButtonBoxPrivate::retranslateStrings()
{
- typedef QHash<QPushButton *, QDialogButtonBox::StandardButton>::iterator Iterator;
-
- const Iterator end = standardButtonHash.end();
- for (Iterator it = standardButtonHash.begin(); it != end; ++it) {
- const QString text = QGuiApplicationPrivate::platformTheme()->standardButtonText(it.value());
+ for (auto &&[key, value] : std::as_const(standardButtonHash).asKeyValueRange()) {
+ const QString text = QGuiApplicationPrivate::platformTheme()->standardButtonText(value);
if (!text.isEmpty())
- it.key()->setText(text);
+ key->setText(text);
}
}
@@ -482,6 +485,14 @@ QDialogButtonBox::QDialogButtonBox(StandardButtons buttons, Qt::Orientation orie
*/
QDialogButtonBox::~QDialogButtonBox()
{
+ Q_D(QDialogButtonBox);
+
+ d->ignoreShowAndHide = true;
+
+ // QObjectPrivate::connect requires explicit disconnect in destructor
+ // otherwise the connection may kick in on child destruction and reach
+ // the parent's destroyed private object
+ d->disconnectAll();
}
/*!
@@ -638,29 +649,40 @@ void QDialogButtonBox::clear()
QList<QAbstractButton *> &list = d->buttonLists[i];
while (list.size()) {
QAbstractButton *button = list.takeAt(0);
- QObject::disconnect(button, SIGNAL(destroyed()), this, SLOT(_q_handleButtonDestroyed()));
+ QObjectPrivate::disconnect(button, &QAbstractButton::destroyed,
+ d, &QDialogButtonBoxPrivate::handleButtonDestroyed);
delete button;
}
}
}
/*!
- Returns a list of all the buttons that have been added to the button box.
+ Returns a list of all buttons that have been added to the button box.
\sa buttonRole(), addButton(), removeButton()
*/
QList<QAbstractButton *> QDialogButtonBox::buttons() const
{
Q_D(const QDialogButtonBox);
+ return d->allButtons();
+}
+
+QList<QAbstractButton *> QDialogButtonBoxPrivate::visibleButtons() const
+{
QList<QAbstractButton *> finalList;
- for (int i = 0; i < NRoles; ++i) {
- const QList<QAbstractButton *> &list = d->buttonLists[i];
+ for (int i = 0; i < QDialogButtonBox::NRoles; ++i) {
+ const QList<QAbstractButton *> &list = buttonLists[i];
for (int j = 0; j < list.size(); ++j)
finalList.append(list.at(j));
}
return finalList;
}
+QList<QAbstractButton *> QDialogButtonBoxPrivate::allButtons() const
+{
+ return visibleButtons() << hiddenButtons.keys();
+}
+
/*!
Returns the button role for the specified \a button. This function returns
\l InvalidRole if \a button is \nullptr or has not been added to the button box.
@@ -677,7 +699,7 @@ QDialogButtonBox::ButtonRole QDialogButtonBox::buttonRole(QAbstractButton *butto
return ButtonRole(i);
}
}
- return InvalidRole;
+ return d->hiddenButtons.value(button, InvalidRole);
}
/*!
@@ -688,27 +710,45 @@ QDialogButtonBox::ButtonRole QDialogButtonBox::buttonRole(QAbstractButton *butto
void QDialogButtonBox::removeButton(QAbstractButton *button)
{
Q_D(QDialogButtonBox);
+ d->removeButton(button, QDialogButtonBoxPrivate::RemoveReason::ManualRemove);
+}
+/*!
+ \internal
+ Removes \param button.
+ \param reason determines the behavior following the removal:
+ \list
+ \li \c ManualRemove disconnects all signals and removes the button from standardButtonHash.
+ \li \c HideEvent keeps connections alive, standard buttons remain in standardButtonHash.
+ \li \c Destroyed removes the button from standardButtonHash. Signals remain untouched, because
+ the button might already be only a QObject, the destructor of which handles disconnecting.
+ \endlist
+ */
+void QDialogButtonBoxPrivate::removeButton(QAbstractButton *button, RemoveReason reason)
+{
if (!button)
return;
- // Remove it from the standard button hash first and then from the roles
- d->standardButtonHash.remove(reinterpret_cast<QPushButton *>(button));
- for (int i = 0; i < NRoles; ++i) {
- QList<QAbstractButton *> &list = d->buttonLists[i];
- for (int j = 0; j < list.size(); ++j) {
- if (list.at(j) == button) {
- list.takeAt(j);
- if (!d->internalRemove) {
- disconnect(button, SIGNAL(clicked()), this, SLOT(_q_handleButtonClicked()));
- disconnect(button, SIGNAL(destroyed()), this, SLOT(_q_handleButtonDestroyed()));
- }
- break;
- }
- }
- }
- if (!d->internalRemove)
+ // Remove button from hidden buttons and roles
+ hiddenButtons.remove(button);
+ for (int i = 0; i < QDialogButtonBox::NRoles; ++i)
+ buttonLists[i].removeOne(button);
+
+ switch (reason) {
+ case RemoveReason::ManualRemove:
button->setParent(nullptr);
+ QObjectPrivate::disconnect(button, &QAbstractButton::clicked,
+ this, &QDialogButtonBoxPrivate::handleButtonClicked);
+ QObjectPrivate::disconnect(button, &QAbstractButton::destroyed,
+ this, &QDialogButtonBoxPrivate::handleButtonDestroyed);
+ button->removeEventFilter(filter.get());
+ Q_FALLTHROUGH();
+ case RemoveReason::Destroyed:
+ standardButtonHash.remove(reinterpret_cast<QPushButton *>(button));
+ break;
+ case RemoveReason::HideEvent:
+ break;
+ }
}
/*!
@@ -778,7 +818,7 @@ void QDialogButtonBox::setStandardButtons(StandardButtons buttons)
{
Q_D(QDialogButtonBox);
// Clear out all the old standard buttons, then recreate them.
- qDeleteAll(d->standardButtonHash.keys());
+ qDeleteAll(d->standardButtonHash.keyBegin(), d->standardButtonHash.keyEnd());
d->standardButtonHash.clear();
d->createStandardButtons(buttons);
@@ -820,7 +860,7 @@ QDialogButtonBox::StandardButton QDialogButtonBox::standardButton(QAbstractButto
return d->standardButtonHash.value(static_cast<QPushButton *>(button));
}
-void QDialogButtonBoxPrivate::_q_handleButtonClicked()
+void QDialogButtonBoxPrivate::handleButtonClicked()
{
Q_Q(QDialogButtonBox);
if (QAbstractButton *button = qobject_cast<QAbstractButton *>(q->sender())) {
@@ -854,13 +894,44 @@ void QDialogButtonBoxPrivate::_q_handleButtonClicked()
}
}
-void QDialogButtonBoxPrivate::_q_handleButtonDestroyed()
+void QDialogButtonBoxPrivate::handleButtonDestroyed()
+{
+ Q_Q(QDialogButtonBox);
+ if (QObject *object = q->sender())
+ removeButton(reinterpret_cast<QAbstractButton *>(object), RemoveReason::Destroyed);
+}
+
+bool QDialogButtonBoxPrivate::handleButtonShowAndHide(QAbstractButton *button, QEvent *event)
{
Q_Q(QDialogButtonBox);
- if (QObject *object = q->sender()) {
- QBoolBlocker skippy(internalRemove);
- q->removeButton(reinterpret_cast<QAbstractButton *>(object));
+
+ const QEvent::Type type = event->type();
+
+ if ((type != QEvent::HideToParent && type != QEvent::ShowToParent) || ignoreShowAndHide)
+ return false;
+
+ switch (type) {
+ case QEvent::HideToParent: {
+ const QDialogButtonBox::ButtonRole role = q->buttonRole(button);
+ if (role != QDialogButtonBox::ButtonRole::InvalidRole) {
+ removeButton(button, RemoveReason::HideEvent);
+ hiddenButtons.insert(button, role);
+ layoutButtons();
+ }
+ break;
}
+ case QEvent::ShowToParent:
+ if (hiddenButtons.contains(button)) {
+ const auto role = hiddenButtons.take(button);
+ addButton(button, role, LayoutRule::DoLayout, AddRule::SkipConnect);
+ if (role == QDialogButtonBox::AcceptRole)
+ ensureFirstAcceptIsDefault();
+ }
+ break;
+ default: break;
+ }
+
+ return false;
}
/*!
@@ -918,36 +989,80 @@ void QDialogButtonBox::changeEvent(QEvent *event)
}
}
+void QDialogButtonBoxPrivate::ensureFirstAcceptIsDefault()
+{
+ Q_Q(QDialogButtonBox);
+ const QList<QAbstractButton *> &acceptRoleList = buttonLists[QDialogButtonBox::AcceptRole];
+ QPushButton *firstAcceptButton = acceptRoleList.isEmpty()
+ ? nullptr
+ : qobject_cast<QPushButton *>(acceptRoleList.at(0));
+
+ if (!firstAcceptButton)
+ return;
+
+ bool hasDefault = false;
+ QWidget *dialog = nullptr;
+ QWidget *p = q;
+ while (p && !p->isWindow()) {
+ p = p->parentWidget();
+ if ((dialog = qobject_cast<QDialog *>(p)))
+ break;
+ }
+
+ QWidget *parent = dialog ? dialog : q;
+ Q_ASSERT(parent);
+
+ const auto pushButtons = parent->findChildren<QPushButton *>();
+ for (QPushButton *pushButton : pushButtons) {
+ if (pushButton->isDefault() && pushButton != firstAcceptButton) {
+ hasDefault = true;
+ break;
+ }
+ }
+ if (!hasDefault && firstAcceptButton) {
+ firstAcceptButton->setDefault(true);
+ // When the QDialogButtonBox is focused, and it doesn't have an
+ // explicit focus widget, it will transfer focus to its focus
+ // proxy, which is the first button in the layout. This behavior,
+ // combined with the behavior that QPushButtons in a QDialog will
+ // by default have their autoDefault set to true, results in the
+ // focus proxy/first button stealing the default button status
+ // immediately when the button box is focused, which is not what
+ // we want. Account for this by explicitly making the firstAcceptButton
+ // focused as well, unless an explicit focus widget has been set, or
+ // a dialog child has Qt::StrongFocus.
+ if (dialog && !(QWidgetPrivate::get(dialog)->hasChildWithFocusPolicy(Qt::StrongFocus, q)
+ || dialog->focusWidget()))
+ firstAcceptButton->setFocus();
+ }
+}
+
+void QDialogButtonBoxPrivate::disconnectAll()
+{
+ Q_Q(QDialogButtonBox);
+ const auto buttons = q->findChildren<QAbstractButton *>();
+ for (auto *button : buttons)
+ button->disconnect(q);
+}
+
/*!
\reimp
*/
bool QDialogButtonBox::event(QEvent *event)
{
Q_D(QDialogButtonBox);
- if (event->type() == QEvent::Show) {
- QList<QAbstractButton *> acceptRoleList = d->buttonLists[AcceptRole];
- QPushButton *firstAcceptButton = acceptRoleList.isEmpty() ? 0 : qobject_cast<QPushButton *>(acceptRoleList.at(0));
- bool hasDefault = false;
- QWidget *dialog = nullptr;
- QWidget *p = this;
- while (p && !p->isWindow()) {
- p = p->parentWidget();
- if ((dialog = qobject_cast<QDialog *>(p)))
- break;
- }
+ switch (event->type()) {
+ case QEvent::Show:
+ d->ensureFirstAcceptIsDefault();
+ break;
- const auto pbs = (dialog ? dialog : this)->findChildren<QPushButton *>();
- for (QPushButton *pb : pbs) {
- if (pb->isDefault() && pb != firstAcceptButton) {
- hasDefault = true;
- break;
- }
- }
- if (!hasDefault && firstAcceptButton)
- firstAcceptButton->setDefault(true);
- }else if (event->type() == QEvent::LanguageChange) {
+ case QEvent::LanguageChange:
d->retranslateStrings();
+ break;
+
+ default: break;
}
+
return QWidget::event(event);
}
diff --git a/src/widgets/widgets/qdialogbuttonbox.h b/src/widgets/widgets/qdialogbuttonbox.h
index f6a0371d6c..d967494d0d 100644
--- a/src/widgets/widgets/qdialogbuttonbox.h
+++ b/src/widgets/widgets/qdialogbuttonbox.h
@@ -120,8 +120,6 @@ protected:
private:
Q_DISABLE_COPY(QDialogButtonBox)
Q_DECLARE_PRIVATE(QDialogButtonBox)
- Q_PRIVATE_SLOT(d_func(), void _q_handleButtonClicked())
- Q_PRIVATE_SLOT(d_func(), void _q_handleButtonDestroyed())
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QDialogButtonBox::StandardButtons)
diff --git a/src/widgets/widgets/qdialogbuttonbox_p.h b/src/widgets/widgets/qdialogbuttonbox_p.h
new file mode 100644
index 0000000000..c3d7e03489
--- /dev/null
+++ b/src/widgets/widgets/qdialogbuttonbox_p.h
@@ -0,0 +1,80 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#ifndef QDIALOGBUTTONBOX_P_H
+#define QDIALOGBUTTONBOX_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.
+//
+
+#include <private/qwidget_p.h>
+#include <qdialogbuttonbox.h>
+
+QT_BEGIN_NAMESPACE
+
+class Q_AUTOTEST_EXPORT QDialogButtonBoxPrivate : public QWidgetPrivate
+{
+ Q_DECLARE_PUBLIC(QDialogButtonBox)
+
+public:
+ enum class RemoveReason {
+ HideEvent,
+ ManualRemove,
+ Destroyed,
+ };
+ enum class LayoutRule {
+ DoLayout,
+ SkipLayout,
+ };
+ enum class AddRule {
+ Connect,
+ SkipConnect,
+ };
+
+ QDialogButtonBoxPrivate(Qt::Orientation orient);
+
+ QList<QAbstractButton *> buttonLists[QDialogButtonBox::NRoles];
+ QHash<QPushButton *, QDialogButtonBox::StandardButton> standardButtonHash;
+ QHash<QAbstractButton *, QDialogButtonBox::ButtonRole> hiddenButtons;
+
+ Qt::Orientation orientation;
+ QDialogButtonBox::ButtonLayout layoutPolicy;
+ QBoxLayout *buttonLayout;
+ std::unique_ptr<QObject> filter;
+ bool center;
+ bool ignoreShowAndHide = false;
+
+ void createStandardButtons(QDialogButtonBox::StandardButtons buttons);
+
+ void removeButton(QAbstractButton *button, RemoveReason reason);
+ void layoutButtons();
+ void initLayout();
+ void resetLayout();
+ QPushButton *createButton(QDialogButtonBox::StandardButton button,
+ LayoutRule layoutRule = LayoutRule::DoLayout);
+ void addButton(QAbstractButton *button, QDialogButtonBox::ButtonRole role,
+ LayoutRule layoutRule = LayoutRule::DoLayout,
+ AddRule addRule = AddRule::Connect);
+ void handleButtonDestroyed();
+ void handleButtonClicked();
+ bool handleButtonShowAndHide(QAbstractButton *button, QEvent *event);
+ void addButtonsToLayout(const QList<QAbstractButton *> &buttonList, bool reverse);
+ void ensureFirstAcceptIsDefault();
+ void retranslateStrings();
+ void disconnectAll();
+ QList<QAbstractButton *> allButtons() const;
+ QList<QAbstractButton *> visibleButtons() const;
+ QDialogButtonBox::ButtonRole buttonRole(QAbstractButton *button) const;
+};
+
+QT_END_NAMESPACE
+
+#endif // QDIALOGBUTTONBOX_P_H
diff --git a/src/widgets/widgets/qdockarealayout.cpp b/src/widgets/widgets/qdockarealayout.cpp
index 2e3602e47a..da0e987171 100644
--- a/src/widgets/widgets/qdockarealayout.cpp
+++ b/src/widgets/widgets/qdockarealayout.cpp
@@ -171,6 +171,38 @@ QDockAreaLayoutItem
return *this;
}
+#ifndef QT_NO_DEBUG_STREAM
+QDebug operator<<(QDebug dbg, const QDockAreaLayoutItem *item)
+{
+ QDebugStateSaver saver(dbg);
+ dbg.nospace();
+ return item ? dbg << *item : dbg << "QDockAreaLayoutItem(0x0)";
+}
+
+QDebug operator<<(QDebug dbg, const QDockAreaLayoutItem &item)
+{
+ QDebugStateSaver saver(dbg);
+ dbg.nospace();
+ dbg << "QDockAreaLayoutItem(" << static_cast<const void *>(&item) << "->";
+ if (item.widgetItem) {
+ QWidget *widget = item.widgetItem->widget();
+ if (auto *dockWidget = qobject_cast<QDockWidget *>(widget)) {
+ dbg << "widgetItem(" << dockWidget << ")";
+ } else if (auto *groupWindow = qobject_cast<QDockWidgetGroupWindow *>(widget)) {
+ dbg << "widgetItem(" << groupWindow << "->(" << groupWindow->dockWidgets() << "))";
+ } else {
+ dbg << "widgetItem(" << widget << ")";
+ }
+ } else if (item.subinfo) {
+ dbg << "subInfo(" << item.subinfo << "->(" << item.subinfo->item_list << ")";
+ } else if (item.placeHolderItem) {
+ dbg << "placeHolderItem(" << item.placeHolderItem << ")";
+ }
+ dbg << ")";
+ return dbg;
+}
+#endif // QT_NO_DEBUG_STREAM
+
/******************************************************************************
** QDockAreaLayoutInfo
*/
@@ -986,6 +1018,14 @@ void QDockAreaLayoutInfo::remove(const QList<int> &path)
}
}
+void QDockAreaLayoutInfo::remove(QWidget *widget)
+{
+ const QList<int> path = indexOf(widget);
+ if (path.isEmpty())
+ return;
+ remove(path);
+}
+
QLayoutItem *QDockAreaLayoutInfo::plug(const QList<int> &path)
{
Q_ASSERT(!path.isEmpty());
@@ -1090,6 +1130,21 @@ static QRect dockedGeometry(QWidget *widget)
return result;
}
+bool QDockAreaLayoutInfo::hasGapItem(const QList<int> &path) const
+{
+ // empty path has no gap item
+ if (path.isEmpty())
+ return false;
+
+ // Index -1 isn't a gap
+ // Index out of range points at a position to be created. That isn't a gap either.
+ const int index = path.constFirst();
+ if (index < 0 || index >= item_list.count())
+ return false;
+
+ return item_list[index].flags & QDockAreaLayoutItem::GapItem;
+}
+
bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWidgetItem)
{
Q_ASSERT(!path.isEmpty());
@@ -1101,8 +1156,6 @@ bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWid
index = -index - 1;
}
-// dump(qDebug() << "insertGap() before:" << index << tabIndex, *this, QString());
-
if (path.size() > 1) {
QDockAreaLayoutItem &item = item_list[index];
@@ -1731,6 +1784,26 @@ QLayoutItem *QDockAreaLayoutInfo::takeAt(int *x, int index)
return nullptr;
}
+// Add a dock widget or dock widget group window to the item list
+void QDockAreaLayoutInfo::add(QWidget *widget)
+{
+ // Do not add twice
+ if (!indexOf(widget).isEmpty())
+ return;
+
+ if (auto *dockWidget = qobject_cast<QDockWidget *>(widget)) {
+ item_list.append(QDockAreaLayoutItem(new QDockWidgetItem(dockWidget)));
+ return;
+ }
+
+ if (auto *groupWindow = qobject_cast<QDockWidgetGroupWindow *>(widget)) {
+ item_list.append(QDockAreaLayoutItem(new QDockWidgetGroupWindowItem(groupWindow)));
+ return;
+ }
+
+ qFatal("Coding error. Add supports only QDockWidget and QDockWidgetGroupWindow");
+}
+
void QDockAreaLayoutInfo::deleteAllLayoutItems()
{
for (int i = 0; i < item_list.size(); ++i) {
@@ -1924,6 +1997,7 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*>
if (testing) {
//was it is not really added to the layout, we need to delete the object here
delete item.widgetItem;
+ item.widgetItem = nullptr;
}
}
} else if (nextMarker == SequenceMarker) {
@@ -1989,14 +2063,20 @@ void QDockAreaLayoutInfo::updateSeparatorWidgets() const
break;
QWidget *sepWidget;
- if (j < separatorWidgets.size() && separatorWidgets.at(j)) {
+ if (j < separatorWidgets.size()) {
sepWidget = separatorWidgets.at(j);
+ if (!sepWidget) {
+ qWarning("QDockAreaLayoutInfo::updateSeparatorWidgets: null separator widget");
+ sepWidget = mainWindowLayout()->getSeparatorWidget();
+ separatorWidgets[j] = sepWidget;
+ }
} else {
sepWidget = mainWindowLayout()->getSeparatorWidget();
separatorWidgets.append(sepWidget);
}
j++;
+ Q_ASSERT(sepWidget);
sepWidget->raise();
QRect sepRect = separatorRect(i).adjusted(-2, -2, 2, 2);
@@ -2009,7 +2089,6 @@ void QDockAreaLayoutInfo::updateSeparatorWidgets() const
separatorWidgets[k]->hide();
}
separatorWidgets.resize(j);
- Q_ASSERT(separatorWidgets.size() == j);
}
/*! \internal
@@ -3271,12 +3350,18 @@ void QDockAreaLayout::updateSeparatorWidgets() const
QWidget *sepWidget;
if (j < separatorWidgets.size()) {
sepWidget = separatorWidgets.at(j);
+ if (!sepWidget) {
+ qWarning("QDockAreaLayout::updateSeparatorWidgets: null separator widget");
+ sepWidget = qt_mainwindow_layout(mainWindow)->getSeparatorWidget();
+ separatorWidgets[j] = sepWidget;
+ }
} else {
sepWidget = qt_mainwindow_layout(mainWindow)->getSeparatorWidget();
separatorWidgets.append(sepWidget);
}
j++;
+ Q_ASSERT(sepWidget);
sepWidget->raise();
QRect sepRect = separatorRect(i).adjusted(-2, -2, 2, 2);
diff --git a/src/widgets/widgets/qdockarealayout_p.h b/src/widgets/widgets/qdockarealayout_p.h
index cf998cf665..aa39bf9913 100644
--- a/src/widgets/widgets/qdockarealayout_p.h
+++ b/src/widgets/widgets/qdockarealayout_p.h
@@ -18,7 +18,6 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "QtWidgets/qlayout.h"
#include "QtCore/qlist.h"
-#include "QtCore/qpair.h"
#include "QtCore/qrect.h"
QT_REQUIRE_CONFIG(dockwidget);
@@ -73,6 +72,10 @@ struct Q_AUTOTEST_EXPORT QDockAreaLayoutItem
int pos;
int size;
uint flags;
+#ifndef QT_NO_DEBUG_STREAM
+ friend Q_AUTOTEST_EXPORT QDebug operator<<(QDebug dbg, const QDockAreaLayoutItem &item);
+ friend Q_AUTOTEST_EXPORT QDebug operator<<(QDebug dbg, const QDockAreaLayoutItem *item);
+#endif
};
class Q_AUTOTEST_EXPORT QPlaceHolderItem
@@ -105,6 +108,7 @@ public:
QList<int> gapIndex(const QPoint &pos, bool nestingEnabled,
TabMode tabMode) const;
void remove(const QList<int> &path);
+ void remove(QWidget *widget);
void unnest(int index);
void split(int index, Qt::Orientation orientation, QLayoutItem *dockWidgetItem);
#if QT_CONFIG(tabbar)
@@ -132,6 +136,7 @@ public:
void clear();
bool isEmpty() const;
+ bool hasGapItem(const QList<int> &path) const;
bool onlyHasPlaceholders() const;
bool hasFixedSize() const;
QList<int> findSeparator(const QPoint &pos) const;
@@ -151,6 +156,7 @@ public:
QLayoutItem *itemAt(int *x, int index) const;
QLayoutItem *takeAt(int *x, int index);
+ void add(QWidget *widget);
void deleteAllLayoutItems();
QMainWindowLayout *mainWindowLayout() const;
diff --git a/src/widgets/widgets/qdockwidget.cpp b/src/widgets/widgets/qdockwidget.cpp
index 67bb099446..706306000c 100644
--- a/src/widgets/widgets/qdockwidget.cpp
+++ b/src/widgets/widgets/qdockwidget.cpp
@@ -119,7 +119,7 @@ bool QDockWidgetTitleButton::event(QEvent *event)
{
switch (event->type()) {
case QEvent::StyleChange:
- case QEvent::ScreenChangeInternal:
+ case QEvent::DevicePixelRatioChange:
m_iconSize = -1;
break;
default:
@@ -128,33 +128,12 @@ bool QDockWidgetTitleButton::event(QEvent *event)
return QAbstractButton::event(event);
}
-static inline bool isWindowsStyle(const QStyle *style)
-{
- // Note: QStyleSheetStyle inherits QWindowsStyle
- const QStyle *effectiveStyle = style;
-
-#if QT_CONFIG(style_stylesheet)
- if (style->inherits("QStyleSheetStyle"))
- effectiveStyle = static_cast<const QStyleSheetStyle *>(style)->baseStyle();
-#endif
-#if !defined(QT_NO_STYLE_PROXY)
- if (style->inherits("QProxyStyle"))
- effectiveStyle = static_cast<const QProxyStyle *>(style)->baseStyle();
-#endif
-
- return effectiveStyle->inherits("QWindowsStyle");
-}
-
QSize QDockWidgetTitleButton::dockButtonIconSize() const
{
if (m_iconSize < 0) {
m_iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, this);
- // Dock Widget title buttons on Windows where historically limited to size 10
- // (from small icon size 16) since only a 10x10 XPM was provided.
- // Adding larger pixmaps to the icons thus caused the icons to grow; limit
- // this to qpiScaled(10) here.
- if (isWindowsStyle(style()))
- m_iconSize = qMin((10 * logicalDpiX()) / 96, m_iconSize);
+ if (style()->styleHint(QStyle::SH_DockWidget_ButtonsHaveFrame, nullptr, this))
+ m_iconSize = (m_iconSize * 5) / 8; // 16 -> 10
}
return QSize(m_iconSize, m_iconSize);
}
@@ -253,7 +232,9 @@ bool QDockWidgetLayout::wmSupportsNativeWindowDeco()
return false;
#else
static const bool xcb = !QGuiApplication::platformName().compare("xcb"_L1, Qt::CaseInsensitive);
- return !xcb;
+ static const bool wayland =
+ QGuiApplication::platformName().startsWith("wayland"_L1, Qt::CaseInsensitive);
+ return !(xcb || wayland);
#endif
}
@@ -627,12 +608,13 @@ void QDockWidgetPrivate::init()
QAbstractButton *button = new QDockWidgetTitleButton(q);
button->setObjectName("qt_dockwidget_floatbutton"_L1);
- QObject::connect(button, SIGNAL(clicked()), q, SLOT(_q_toggleTopLevel()));
+ QObjectPrivate::connect(button, &QAbstractButton::clicked,
+ this, &QDockWidgetPrivate::toggleTopLevel);
layout->setWidgetForRole(QDockWidgetLayout::FloatButton, button);
button = new QDockWidgetTitleButton(q);
button->setObjectName("qt_dockwidget_closebutton"_L1);
- QObject::connect(button, SIGNAL(clicked()), q, SLOT(close()));
+ QObject::connect(button, &QAbstractButton::clicked, q, &QDockWidget::close);
layout->setWidgetForRole(QDockWidgetLayout::CloseButton, button);
font = QApplication::font("QDockWidgetTitle");
@@ -643,8 +625,8 @@ void QDockWidgetPrivate::init()
toggleViewAction->setMenuRole(QAction::NoRole);
fixedWindowTitle = qt_setWindowTitle_helperHelper(q->windowTitle(), q);
toggleViewAction->setText(fixedWindowTitle);
- QObject::connect(toggleViewAction, SIGNAL(triggered(bool)),
- q, SLOT(_q_toggleView(bool)));
+ QObjectPrivate::connect(toggleViewAction, &QAction::triggered,
+ this, &QDockWidgetPrivate::toggleView);
#endif
updateButtons();
@@ -679,7 +661,7 @@ void QDockWidget::initStyleOption(QStyleOptionDockWidget *option) const
option->verticalTitleBar = l->verticalTitleBar;
}
-void QDockWidgetPrivate::_q_toggleView(bool b)
+void QDockWidgetPrivate::toggleView(bool b)
{
Q_Q(QDockWidget);
if (b == q->isHidden()) {
@@ -727,7 +709,7 @@ void QDockWidgetPrivate::updateButtons()
layout->invalidate();
}
-void QDockWidgetPrivate::_q_toggleTopLevel()
+void QDockWidgetPrivate::toggleTopLevel()
{
Q_Q(QDockWidget);
q->setFloating(!q->isFloating());
@@ -768,7 +750,7 @@ void QDockWidgetPrivate::initDrag(const QPoint &pos, bool nca)
tabbed widgets, and false if the dock widget should always be dragged
alone.
*/
-void QDockWidgetPrivate::startDrag(bool group)
+void QDockWidgetPrivate::startDrag(DragScope scope)
{
Q_Q(QDockWidget);
@@ -778,7 +760,11 @@ void QDockWidgetPrivate::startDrag(bool group)
QMainWindowLayout *layout = qt_mainwindow_layout_from_dock(q);
Q_ASSERT(layout != nullptr);
- state->widgetItem = layout->unplug(q, group);
+#if QT_CONFIG(draganddrop)
+ bool wasFloating = q->isFloating();
+#endif
+
+ state->widgetItem = layout->unplug(q, scope);
if (state->widgetItem == nullptr) {
/* Dock widget has a QMainWindow parent, but was never inserted with
QMainWindow::addDockWidget, so the QMainWindowLayout has no
@@ -796,6 +782,20 @@ void QDockWidgetPrivate::startDrag(bool group)
layout->restore();
state->dragging = true;
+
+#if QT_CONFIG(draganddrop)
+ if (QMainWindowLayout::needsPlatformDrag()) {
+ Qt::DropAction result =
+ layout->performPlatformWidgetDrag(state->widgetItem, state->pressPos);
+ if (result == Qt::IgnoreAction && !wasFloating) {
+ layout->revert(state->widgetItem);
+ delete state;
+ state = nullptr;
+ } else {
+ endDrag(QDockWidgetPrivate::EndDragMode::LocationChange);
+ }
+ }
+#endif
}
/*! \internal
@@ -803,7 +803,7 @@ void QDockWidgetPrivate::startDrag(bool group)
The \a abort parameter specifies that it ends because of programmatic state
reset rather than mouse release event.
*/
-void QDockWidgetPrivate::endDrag(bool abort)
+void QDockWidgetPrivate::endDrag(EndDragMode mode)
{
Q_Q(QDockWidget);
Q_ASSERT(state != nullptr);
@@ -815,7 +815,11 @@ void QDockWidgetPrivate::endDrag(bool abort)
Q_ASSERT(mainWindow != nullptr);
QMainWindowLayout *mwLayout = qt_mainwindow_layout(mainWindow);
- if (abort || !mwLayout->plug(state->widgetItem)) {
+ // if mainWindow is being deleted in an ongoing drag, make it a no-op instead of crashing
+ if (!mwLayout)
+ return;
+
+ if (mode == EndDragMode::Abort || !mwLayout->plug(state->widgetItem)) {
if (hasFeature(this, QDockWidget::DockWidgetFloatable)) {
// This QDockWidget will now stay in the floating state.
if (state->ownWidgetItem) {
@@ -847,6 +851,11 @@ void QDockWidgetPrivate::endDrag(bool abort)
tabPosition = mwLayout->tabPosition(toDockWidgetArea(dwgw->layoutInfo()->dockPos));
}
#endif
+ // Reparent, if the drag was out of a dock widget group window
+ if (mode == EndDragMode::LocationChange) {
+ if (auto *groupWindow = qobject_cast<QDockWidgetGroupWindow *>(q->parentWidget()))
+ groupWindow->reparent(q);
+ }
}
q->activateWindow();
} else {
@@ -875,6 +884,10 @@ Qt::DockWidgetArea QDockWidgetPrivate::toDockWidgetArea(QInternal::DockPosition
void QDockWidgetPrivate::setResizerActive(bool active)
{
Q_Q(QDockWidget);
+ const auto *dwLayout = qobject_cast<QDockWidgetLayout *>(layout);
+ if (dwLayout->nativeWindowDeco(q->isFloating()))
+ return;
+
if (active && !resizer)
resizer = new QWidgetResizeHandler(q);
if (resizer)
@@ -937,13 +950,22 @@ bool QDockWidgetPrivate::mouseDoubleClickEvent(QMouseEvent *event)
if (event->button() == Qt::LeftButton && titleArea.contains(event->position().toPoint()) &&
hasFeature(this, QDockWidget::DockWidgetFloatable)) {
- _q_toggleTopLevel();
+ toggleTopLevel();
return true;
}
}
return false;
}
+bool QDockWidgetPrivate::isTabbed() const
+{
+ Q_Q(const QDockWidget);
+ QDockWidget *that = const_cast<QDockWidget *>(q);
+ auto *mwLayout = qt_mainwindow_layout_from_dock(that);
+ Q_ASSERT(mwLayout);
+ return mwLayout->isDockWidgetTabbed(q);
+}
+
bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event)
{
bool ret = false;
@@ -974,7 +996,8 @@ bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event)
} else
#endif
{
- startDrag();
+ const DragScope scope = isTabbed() ? DragScope::Group : DragScope::Widget;
+ startDrag(scope);
q->grabMouse();
ret = true;
}
@@ -1038,9 +1061,15 @@ bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event)
bool QDockWidgetPrivate::mouseReleaseEvent(QMouseEvent *event)
{
#if QT_CONFIG(mainwindow)
+#if QT_CONFIG(draganddrop)
+ // if we are peforming a platform drag ignore the release here and end the drag when the actual
+ // drag ends.
+ if (QMainWindowLayout::needsPlatformDrag())
+ return false;
+#endif
if (event->button() == Qt::LeftButton && state && !state->nca) {
- endDrag();
+ endDrag(EndDragMode::LocationChange);
return true; //filter out the event
}
@@ -1079,26 +1108,25 @@ void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
break;
state->ctrlDrag = (event->modifiers() & Qt::ControlModifier) ||
(!hasFeature(this, QDockWidget::DockWidgetMovable) && q->isFloating());
- startDrag();
+ startDrag(DragScope::Group);
break;
case QEvent::NonClientAreaMouseMove:
if (state == nullptr || !state->dragging)
break;
#if !defined(Q_OS_MAC) && !defined(Q_OS_WASM)
- if (state->nca) {
- endDrag();
- }
+ if (state->nca)
+ endDrag(EndDragMode::LocationChange);
#endif
break;
case QEvent::NonClientAreaMouseButtonRelease:
#if defined(Q_OS_MAC) || defined(Q_OS_WASM)
if (state)
- endDrag();
+ endDrag(EndDragMode::LocationChange);
#endif
break;
case QEvent::NonClientAreaMouseButtonDblClick:
- _q_toggleTopLevel();
+ toggleTopLevel();
break;
default:
break;
@@ -1164,10 +1192,10 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect
return; // this dockwidget can't be redocked
}
- bool wasFloating = q->isFloating();
+ const bool wasFloating = q->isFloating();
if (wasFloating) // Prevent repetitive unplugging from nested invocations (QTBUG-42818)
unplug = false;
- bool hidden = q->isHidden();
+ const bool hidden = q->isHidden();
if (q->isVisible())
q->hide();
@@ -1185,8 +1213,12 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect
flags |= Qt::FramelessWindowHint;
}
- if (unplug)
+#if QT_CONFIG(draganddrop)
+ // If we are performing a platform drag the flag is not needed and we want to avoid recreating
+ // the platform window when it would be removed later
+ if (unplug && !QMainWindowLayout::needsPlatformDrag())
flags |= Qt::X11BypassWindowManagerHint;
+#endif
q->setWindowFlags(flags);
@@ -1262,15 +1294,13 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect
possible to drag the dock widget when undocking. Starting the drag will undock
the dock widget, but a second drag will be needed to move the dock widget itself.
- \sa QMainWindow, {Dock Widgets Example}
+ \sa QMainWindow
*/
/*!
\enum QDockWidget::DockWidgetFeature
- \value DockWidgetClosable The dock widget can be closed. On some systems the dock
- widget always has a close button when it's floating
- (for example on MacOS 10.5).
+ \value DockWidgetClosable The dock widget can be closed.
\value DockWidgetMovable The dock widget can be moved between docks
by the user.
\value DockWidgetFloatable The dock widget can be detached from the
@@ -1402,9 +1432,12 @@ QDockWidget::DockWidgetFeatures QDockWidget::features() const
\property QDockWidget::floating
\brief whether the dock widget is floating
- A floating dock widget is presented to the user as an independent
- window "on top" of its parent QMainWindow, instead of being
- docked in the QMainWindow.
+ A floating dock widget is presented to the user as a single, independent
+ window "on top" of its parent QMainWindow, instead of being docked
+ either in the QMainWindow, or in a group of tabbed dock widgets.
+
+ Floating dock widgets can be individually positioned and resized, both
+ programmatically or by mouse interaction.
By default, this property is \c true.
@@ -1418,7 +1451,7 @@ void QDockWidget::setFloating(bool floating)
// the initial click of a double-click may have started a drag...
if (d->state != nullptr)
- d->endDrag(true);
+ d->endDrag(QDockWidgetPrivate::EndDragMode::Abort);
QRect r = d->undockedGeometry;
// Keep position when undocking for the first time.
@@ -1473,8 +1506,14 @@ void QDockWidget::changeEvent(QEvent *event)
QDockWidgetLayout *layout = qobject_cast<QDockWidgetLayout*>(this->layout());
switch (event->type()) {
- case QEvent::ModifiedChange:
case QEvent::WindowTitleChange:
+ if (isFloating() && windowHandle() && d->topData() && windowHandle()->isVisible()) {
+ // From QWidget::setWindowTitle(): Propagate window title without signal emission
+ d->topData()->caption = windowHandle()->title();
+ d->setWindowTitle_helper(windowHandle()->title());
+ }
+ Q_FALLTHROUGH();
+ case QEvent::ModifiedChange:
update(layout->titleArea());
#ifndef QT_NO_ACTION
d->fixedWindowTitle = qt_setWindowTitle_helperHelper(windowTitle(), this);
@@ -1500,8 +1539,14 @@ void QDockWidget::closeEvent(QCloseEvent *event)
{
Q_D(QDockWidget);
if (d->state)
- d->endDrag(true);
- QWidget::closeEvent(event);
+ d->endDrag(QDockWidgetPrivate::EndDragMode::Abort);
+
+ // For non-closable widgets, don't allow closing, except when the mainwindow
+ // is hidden, as otherwise an application wouldn't be able to be shut down.
+ const QMainWindow *win = qobject_cast<QMainWindow*>(parentWidget());
+ const bool canClose = (d->features & DockWidgetClosable)
+ || (!win || !win->isVisible());
+ event->setAccepted(canClose);
}
/*! \reimp */
@@ -1691,6 +1736,10 @@ QAction * QDockWidget::toggleViewAction() const
invisible). This happens when the widget is hidden or shown, as
well as when it is docked in a tabbed dock area and its tab
becomes selected or unselected.
+
+ \note The signal can differ from QWidget::isVisible(). This can be the case, if
+ a dock widget is minimized or tabified and associated to a non-selected or
+ inactive tab.
*/
/*!
@@ -1772,6 +1821,26 @@ QWidget *QDockWidget::titleBarWidget() const
return layout->widgetForRole(QDockWidgetLayout::TitleBar);
}
+#ifndef QT_NO_DEBUG_STREAM
+QDebug operator<<(QDebug dbg, const QDockWidget *dockWidget)
+{
+ QDebugStateSaver saver(dbg);
+ dbg.nospace();
+
+ if (!dockWidget) {
+ dbg << "QDockWidget(0x0)";
+ return dbg;
+ }
+
+ dbg << "QDockWidget(" << static_cast<const void *>(dockWidget);
+ dbg << "->(ObjectName=" << dockWidget->objectName();
+ dbg << "; floating=" << dockWidget->isFloating();
+ dbg << "; features=" << dockWidget->features();
+ dbg << ";))";
+ return dbg;
+}
+#endif // QT_NO_DEBUG_STREAM
+
QT_END_NAMESPACE
#include "qdockwidget.moc"
diff --git a/src/widgets/widgets/qdockwidget.h b/src/widgets/widgets/qdockwidget.h
index f524a88423..2efa1d3c2f 100644
--- a/src/widgets/widgets/qdockwidget.h
+++ b/src/widgets/widgets/qdockwidget.h
@@ -20,7 +20,7 @@ class Q_WIDGETS_EXPORT QDockWidget : public QWidget
{
Q_OBJECT
- Q_PROPERTY(bool floating READ isFloating WRITE setFloating)
+ Q_PROPERTY(bool floating READ isFloating WRITE setFloating NOTIFY topLevelChanged)
Q_PROPERTY(DockWidgetFeatures features READ features WRITE setFeatures NOTIFY featuresChanged)
Q_PROPERTY(Qt::DockWidgetAreas allowedAreas READ allowedAreas
WRITE setAllowedAreas NOTIFY allowedAreasChanged)
@@ -64,6 +64,10 @@ public:
inline bool isAreaAllowed(Qt::DockWidgetArea area) const
{ return (allowedAreas() & area) == area; }
+#ifndef QT_NO_DEBUG_STREAM
+ friend Q_WIDGETS_EXPORT QDebug operator<<(QDebug dbg, const QDockWidget *dockWidget);
+#endif
+
#ifndef QT_NO_ACTION
QAction *toggleViewAction() const;
#endif
@@ -72,7 +76,7 @@ Q_SIGNALS:
void featuresChanged(QDockWidget::DockWidgetFeatures features);
void topLevelChanged(bool topLevel);
void allowedAreasChanged(Qt::DockWidgetAreas allowedAreas);
- void visibilityChanged(bool visible);
+ void visibilityChanged(bool visible); // ### Qt7: Deprecate this. Better listen to hide/show events
void dockLocationChanged(Qt::DockWidgetArea area);
protected:
@@ -85,8 +89,6 @@ protected:
private:
Q_DECLARE_PRIVATE(QDockWidget)
Q_DISABLE_COPY(QDockWidget)
- Q_PRIVATE_SLOT(d_func(), void _q_toggleView(bool))
- Q_PRIVATE_SLOT(d_func(), void _q_toggleTopLevel())
friend class QDockAreaLayout;
friend class QDockWidgetItem;
friend class QMainWindowLayout;
diff --git a/src/widgets/widgets/qdockwidget_p.h b/src/widgets/widgets/qdockwidget_p.h
index 326c55cc78..fa936599c6 100644
--- a/src/widgets/widgets/qdockwidget_p.h
+++ b/src/widgets/widgets/qdockwidget_p.h
@@ -51,9 +51,19 @@ class QDockWidgetPrivate : public QWidgetPrivate
};
public:
+ enum class DragScope {
+ Group,
+ Widget
+ };
+
+ enum class EndDragMode {
+ LocationChange,
+ Abort
+ };
+
void init();
- void _q_toggleView(bool); // private slot
- void _q_toggleTopLevel(); // private slot
+ void toggleView(bool);
+ void toggleTopLevel();
void updateButtons();
static Qt::DockWidgetArea toDockWidgetArea(QInternal::DockPosition pos);
@@ -86,8 +96,8 @@ public:
void setWindowState(bool floating, bool unplug = false, const QRect &rect = QRect());
void nonClientAreaMouseEvent(QMouseEvent *event);
void initDrag(const QPoint &pos, bool nca);
- void startDrag(bool group = true);
- void endDrag(bool abort = false);
+ void startDrag(DragScope scope);
+ void endDrag(EndDragMode mode);
void moveEvent(QMoveEvent *event);
void recalculatePressPos(QResizeEvent *event);
@@ -96,6 +106,7 @@ public:
void setResizerActive(bool active);
bool isAnimating() const;
+ bool isTabbed() const;
private:
QWidgetResizeHandler *resizer = nullptr;
diff --git a/src/widgets/widgets/qeffects.cpp b/src/widgets/widgets/qeffects.cpp
index b33ec543ab..74ac24a2b0 100644
--- a/src/widgets/widgets/qeffects.cpp
+++ b/src/widgets/widgets/qeffects.cpp
@@ -115,7 +115,7 @@ void QAlphaWidget::run(int time)
qApp->installEventFilter(this);
widget->setWindowOpacity(0.0);
widget->show();
- connect(&anim, SIGNAL(timeout()), this, SLOT(render()));
+ connect(&anim, &QTimer::timeout, this, &QAlphaWidget::render);
anim.start(1);
#else
//This is roughly equivalent to calling setVisible(true) without actually showing the widget
@@ -138,7 +138,7 @@ void QAlphaWidget::run(int time)
show();
setEnabled(false);
- connect(&anim, SIGNAL(timeout()), this, SLOT(render()));
+ connect(&anim, &QTimer::timeout, this, &QAlphaWidget::render);
anim.start(1);
} else {
duration = 0;
@@ -171,7 +171,7 @@ bool QAlphaWidget::eventFilter(QObject *o, QEvent *e)
break;
case QEvent::KeyPress: {
#ifndef QT_NO_SHORTCUT
- QKeyEvent *ke = (QKeyEvent*)e;
+ QKeyEvent *ke = static_cast<QKeyEvent *>(e);
if (ke->matches(QKeySequence::Cancel)) {
showWidget = false;
} else
@@ -292,6 +292,7 @@ void QAlphaWidget::alphaBlend()
back_data += bpl;
front_data += bpl;
}
+ break;
}
default:
break;
@@ -428,7 +429,7 @@ void QRollEffect::run(int time)
duration = qMin(qMax(dist/3, 50), 120);
}
- connect(&anim, SIGNAL(timeout()), this, SLOT(scroll()));
+ connect(&anim, &QTimer::timeout, this, &QRollEffect::scroll);
move(widget->geometry().x(),widget->geometry().y());
resize(qMin(currentWidth, totalWidth), qMin(currentHeight, totalHeight));
diff --git a/src/widgets/widgets/qfocusframe.cpp b/src/widgets/widgets/qfocusframe.cpp
index 396f7fca14..d66faedbac 100644
--- a/src/widgets/widgets/qfocusframe.cpp
+++ b/src/widgets/widgets/qfocusframe.cpp
@@ -52,8 +52,8 @@ void QFocusFramePrivate::updateSize()
QStyleOption opt;
q->initStyleOption(&opt);
- int vmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameVMargin, &opt),
- hmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, &opt);
+ int vmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameVMargin, &opt, q),
+ hmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, &opt, q);
QPoint pos(widget->x(), widget->y());
if (q->parentWidget() != widget->parentWidget())
pos = widget->parentWidget()->mapTo(q->parentWidget(), pos);
@@ -229,8 +229,8 @@ QFocusFrame::paintEvent(QPaintEvent *)
QStylePainter p(this);
QStyleOption option;
initStyleOption(&option);
- const int vmargin = style()->pixelMetric(QStyle::PM_FocusFrameVMargin, &option);
- const int hmargin = style()->pixelMetric(QStyle::PM_FocusFrameHMargin, &option);
+ const int vmargin = style()->pixelMetric(QStyle::PM_FocusFrameVMargin, &option, this);
+ const int hmargin = style()->pixelMetric(QStyle::PM_FocusFrameHMargin, &option, this);
QWidgetPrivate *wd = qt_widget_private(d->widget);
QRect rect = wd->clipRect().adjusted(0, 0, hmargin*2, vmargin*2);
p.setClipRect(rect);
diff --git a/src/widgets/widgets/qfontcombobox.cpp b/src/widgets/widgets/qfontcombobox.cpp
index a7f31995e1..c80687c7ed 100644
--- a/src/widgets/widgets/qfontcombobox.cpp
+++ b/src/widgets/widgets/qfontcombobox.cpp
@@ -3,8 +3,9 @@
#include "qfontcombobox.h"
+#include <qabstractitemdelegate.h>
+#include <qaccessible.h>
#include <qstringlistmodel.h>
-#include <qitemdelegate.h>
#include <qlistview.h>
#include <qpainter.h>
#include <qevent.h>
@@ -12,6 +13,8 @@
#include <private/qcombobox_p.h>
#include <qdebug.h>
+#include <array>
+
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
@@ -100,7 +103,7 @@ static QFontDatabase::WritingSystem writingSystemFromLocale()
static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool *hasLatin)
{
- QList<QFontDatabase::WritingSystem> writingSystems = QFontDatabase::writingSystems(font.families().first());
+ QList<QFontDatabase::WritingSystem> writingSystems = QFontDatabase::writingSystems(font.families().constFirst());
// qDebug() << font.families().first() << writingSystems;
// this just confuses the algorithm below. Vietnamese is Latin with lots of special chars
@@ -147,16 +150,15 @@ static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool
class QFontComboBoxPrivate : public QComboBoxPrivate
{
public:
- inline QFontComboBoxPrivate() { filters = QFontComboBox::AllFonts; }
-
- QFontComboBox::FontFilters filters;
+ QFontComboBox::FontFilters filters = QFontComboBox::AllFonts;
QFont currentFont;
QHash<QFontDatabase::WritingSystem, QString> sampleTextForWritingSystem;
QHash<QString, QString> sampleTextForFontFamily;
QHash<QString, QFont> displayFontForFontFamily;
+ std::array<QMetaObject::Connection, 2> connections;
- void _q_updateModel();
- void _q_currentChanged(const QString &);
+ void updateModel();
+ void currentChanged(const QString &);
Q_DECLARE_PUBLIC(QFontComboBox)
};
@@ -281,7 +283,7 @@ QSize QFontFamilyDelegate::sizeHint(const QStyleOptionViewItem &option,
}
-void QFontComboBoxPrivate::_q_updateModel()
+void QFontComboBoxPrivate::updateModel()
{
Q_Q(QFontComboBox);
@@ -297,29 +299,28 @@ void QFontComboBoxPrivate::_q_updateModel()
QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(q->view()->itemDelegate());
QFontDatabase::WritingSystem system = delegate ? delegate->writingSystem : QFontDatabase::Any;
- QStringList list = QFontDatabase::families(system);
+ const QStringList list = QFontDatabase::families(system);
QStringList result;
int offset = 0;
QFontInfo fi(currentFont);
- for (int i = 0; i < list.size(); ++i) {
- if (QFontDatabase::isPrivateFamily(list.at(i)))
+ for (const auto &family : list) {
+ if (QFontDatabase::isPrivateFamily(family))
continue;
if ((filters & scalableMask) && (filters & scalableMask) != scalableMask) {
- if (bool(filters & QFontComboBox::ScalableFonts) != QFontDatabase::isSmoothlyScalable(list.at(i)))
+ if (bool(filters & QFontComboBox::ScalableFonts) != QFontDatabase::isSmoothlyScalable(family))
continue;
}
if ((filters & spacingMask) && (filters & spacingMask) != spacingMask) {
- if (bool(filters & QFontComboBox::MonospacedFonts) != QFontDatabase::isFixedPitch(list.at(i)))
+ if (bool(filters & QFontComboBox::MonospacedFonts) != QFontDatabase::isFixedPitch(family))
continue;
}
- result += list.at(i);
- if (list.at(i) == fi.family() || list.at(i).startsWith(fi.family() + " ["_L1))
+ result += family;
+ if (family == fi.family() || family.startsWith(fi.family() + " ["_L1))
offset = result.size() - 1;
}
- list = result;
//we need to block the signals so that the model doesn't emit reset
//this prevents the current index from changing
@@ -327,10 +328,17 @@ void QFontComboBoxPrivate::_q_updateModel()
///TODO: we should finda way to avoid blocking signals and have a real update of the model
{
const QSignalBlocker blocker(m);
- m->setStringList(list);
+ m->setStringList(result);
+ // Since the modelReset signal is blocked the view will not emit an accessibility event
+ #if QT_CONFIG(accessibility)
+ if (QAccessible::isActive()) {
+ QAccessibleTableModelChangeEvent accessibleEvent(q->view(), QAccessibleTableModelChangeEvent::ModelReset);
+ QAccessible::updateAccessibility(&accessibleEvent);
+ }
+ #endif
}
- if (list.isEmpty()) {
+ if (result.isEmpty()) {
if (currentFont != QFont()) {
currentFont = QFont();
emit q->currentFontChanged(currentFont);
@@ -341,10 +349,10 @@ void QFontComboBoxPrivate::_q_updateModel()
}
-void QFontComboBoxPrivate::_q_currentChanged(const QString &text)
+void QFontComboBoxPrivate::currentChanged(const QString &text)
{
Q_Q(QFontComboBox);
- QStringList families = currentFont.families();
+ const QStringList families = currentFont.families();
if (families.isEmpty() || families.first() != text) {
currentFont.setFamilies(QStringList{text});
emit q->currentFontChanged(currentFont);
@@ -381,7 +389,7 @@ void QFontComboBoxPrivate::_q_currentChanged(const QString &text)
\image windowsvista-fontcombobox.png Screenshot of QFontComboBox on Windows Vista
- \sa QComboBox, QFont, QFontInfo, QFontMetrics, QFontDatabase, {Character Map Example}
+ \sa QComboBox, QFont, QFontInfo, QFontMetrics, QFontDatabase
*/
/*!
@@ -402,11 +410,12 @@ QFontComboBox::QFontComboBox(QWidget *parent)
lview->setUniformItemSizes(true);
setWritingSystem(QFontDatabase::Any);
- connect(this, SIGNAL(currentTextChanged(QString)),
- this, SLOT(_q_currentChanged(QString)));
-
- connect(qApp, SIGNAL(fontDatabaseChanged()),
- this, SLOT(_q_updateModel()));
+ d->connections = {
+ QObjectPrivate::connect(this, &QFontComboBox::currentTextChanged,
+ d, &QFontComboBoxPrivate::currentChanged),
+ QObjectPrivate::connect(qApp, &QGuiApplication::fontDatabaseChanged,
+ d, &QFontComboBoxPrivate::updateModel),
+ };
}
@@ -415,6 +424,9 @@ QFontComboBox::QFontComboBox(QWidget *parent)
*/
QFontComboBox::~QFontComboBox()
{
+ Q_D(const QFontComboBox);
+ for (const QMetaObject::Connection &connection : d->connections)
+ QObject::disconnect(connection);
}
/*!
@@ -433,7 +445,7 @@ void QFontComboBox::setWritingSystem(QFontDatabase::WritingSystem script)
QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(view()->itemDelegate());
if (delegate)
delegate->writingSystem = script;
- d->_q_updateModel();
+ d->updateModel();
}
QFontDatabase::WritingSystem QFontComboBox::writingSystem() const
@@ -469,7 +481,7 @@ void QFontComboBox::setFontFilters(FontFilters filters)
{
Q_D(QFontComboBox);
d->filters = filters;
- d->_q_updateModel();
+ d->updateModel();
}
QFontComboBox::FontFilters QFontComboBox::fontFilters() const
@@ -495,8 +507,8 @@ void QFontComboBox::setCurrentFont(const QFont &font)
Q_D(QFontComboBox);
if (font != d->currentFont) {
d->currentFont = font;
- d->_q_updateModel();
- if (d->currentFont == font) { //else the signal has already be emitted by _q_updateModel
+ d->updateModel();
+ if (d->currentFont == font) { //else the signal has already be emitted by updateModel
emit currentFontChanged(d->currentFont);
}
}
diff --git a/src/widgets/widgets/qfontcombobox.h b/src/widgets/widgets/qfontcombobox.h
index 8c4bad2ae0..9c5432b332 100644
--- a/src/widgets/widgets/qfontcombobox.h
+++ b/src/widgets/widgets/qfontcombobox.h
@@ -65,8 +65,6 @@ protected:
private:
Q_DISABLE_COPY(QFontComboBox)
Q_DECLARE_PRIVATE(QFontComboBox)
- Q_PRIVATE_SLOT(d_func(), void _q_currentChanged(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_updateModel())
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QFontComboBox::FontFilters)
diff --git a/src/widgets/widgets/qgroupbox.cpp b/src/widgets/widgets/qgroupbox.cpp
index 8fd90f8b77..eb37599382 100644
--- a/src/widgets/widgets/qgroupbox.cpp
+++ b/src/widgets/widgets/qgroupbox.cpp
@@ -22,6 +22,7 @@
#include <qpa/qplatformtheme.h>
#include "qdebug.h"
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
@@ -132,9 +133,9 @@ void QGroupBoxPrivate::click()
widgets). The following example shows how we can set up a
QGroupBox with a layout:
- \snippet widgets/groupbox/window.cpp 2
+ \snippet code/src_gui_widgets_qgroupbox.cpp Set up QGroupBox with layout
- \sa QButtonGroup, {Group Box Example}
+ \sa QButtonGroup
*/
@@ -463,9 +464,9 @@ QSize QGroupBox::minimumSizeHint() const
int baseWidth = metrics.horizontalAdvance(d->title) + metrics.horizontalAdvance(u' ');
int baseHeight = metrics.height();
if (d->checkable) {
- baseWidth += style()->pixelMetric(QStyle::PM_IndicatorWidth, &option);
- baseWidth += style()->pixelMetric(QStyle::PM_CheckBoxLabelSpacing, &option);
- baseHeight = qMax(baseHeight, style()->pixelMetric(QStyle::PM_IndicatorHeight, &option));
+ baseWidth += style()->pixelMetric(QStyle::PM_IndicatorWidth, &option, this);
+ baseWidth += style()->pixelMetric(QStyle::PM_CheckBoxLabelSpacing, &option, this);
+ baseHeight = qMax(baseHeight, style()->pixelMetric(QStyle::PM_IndicatorHeight, &option, this));
}
QSize size = style()->sizeFromContents(QStyle::CT_GroupBox, &option, QSize(baseWidth, baseHeight), this);
diff --git a/src/widgets/widgets/qkeysequenceedit.cpp b/src/widgets/widgets/qkeysequenceedit.cpp
index dcdfde8a8d..65ed7a465a 100644
--- a/src/widgets/widgets/qkeysequenceedit.cpp
+++ b/src/widgets/widgets/qkeysequenceedit.cpp
@@ -20,7 +20,7 @@ void QKeySequenceEditPrivate::init()
lineEdit = new QLineEdit(q);
lineEdit->setObjectName(QStringLiteral("qt_keysequenceedit_lineedit"));
lineEdit->setClearButtonEnabled(false);
- q->connect(lineEdit, &QLineEdit::textChanged, [q](const QString& text) {
+ q->connect(lineEdit, &QLineEdit::textChanged, q, [q](const QString& text) {
// Clear the shortcut if the user clicked on the clear icon
if (text.isEmpty())
q->clear();
@@ -177,12 +177,8 @@ bool QKeySequenceEdit::isClearButtonEnabled() const
\property QKeySequenceEdit::maximumSequenceLength
\brief The maximum sequence length.
- The value is clamped to [1-4] inclusive, i.e. the maximum value of the
- maximum sequence length is 4 driven by QKeySequence. The minimum value is
- 1, which can be useful for single sequence, like a typical shortcut.
-
- The QKeySequence stored in QKeySequenceEdit is truncated if longer than the
- value of this property.
+ The maximum number of key sequences a user can enter. The value needs to
+ be between 1 and 4, with 4 being the default.
\since 6.5
*/
@@ -348,22 +344,23 @@ void QKeySequenceEdit::keyPressEvent(QKeyEvent *e)
return;
if (e->modifiers() & Qt::ShiftModifier) {
- QList<int> possibleKeys = QKeyMapper::possibleKeys(e);
+ const QList<QKeyCombination> possibleKeys = QKeyMapper::possibleKeys(e);
int pkTotal = possibleKeys.size();
if (!pkTotal)
return;
bool found = false;
for (int i = 0; i < possibleKeys.size(); ++i) {
- if (possibleKeys.at(i) - nextKey == int(e->modifiers())
- || (possibleKeys.at(i) == nextKey && e->modifiers() == Qt::ShiftModifier)) {
- nextKey = possibleKeys.at(i);
+ const int key = possibleKeys.at(i).toCombined();
+ if (key - nextKey == int(e->modifiers())
+ || (key == nextKey && e->modifiers() == Qt::ShiftModifier)) {
+ nextKey = key;
found = true;
break;
}
}
// Use as fallback
if (!found)
- nextKey = possibleKeys.first();
+ nextKey = possibleKeys.first().toCombined();
} else {
nextKey |= d->translateModifiers(e->modifiers(), e->text());
}
@@ -418,7 +415,8 @@ void QKeySequenceEdit::timerEvent(QTimerEvent *e)
void QKeySequenceEdit::focusOutEvent(QFocusEvent *e)
{
Q_D(QKeySequenceEdit);
- d->finishEditing();
+ if (e->reason() != Qt::PopupFocusReason)
+ d->finishEditing();
QWidget::focusOutEvent(e);
}
diff --git a/src/widgets/widgets/qkeysequenceedit.h b/src/widgets/widgets/qkeysequenceedit.h
index 15b40133b1..db0c4c80dd 100644
--- a/src/widgets/widgets/qkeysequenceedit.h
+++ b/src/widgets/widgets/qkeysequenceedit.h
@@ -33,7 +33,7 @@ public:
void setClearButtonEnabled(bool enable);
bool isClearButtonEnabled() const;
- void setFinishingKeyCombinations(const QList<QKeyCombination> &inishingKeyCombinations);
+ void setFinishingKeyCombinations(const QList<QKeyCombination> &finishingKeyCombinations);
QList<QKeyCombination> finishingKeyCombinations() const;
public Q_SLOTS:
diff --git a/src/widgets/widgets/qlabel.cpp b/src/widgets/widgets/qlabel.cpp
index 4d1c4ebb74..f4155de0a0 100644
--- a/src/widgets/widgets/qlabel.cpp
+++ b/src/widgets/widgets/qlabel.cpp
@@ -1171,12 +1171,14 @@ void QLabel::setBuddy(QWidget *buddy)
Q_D(QLabel);
if (d->buddy)
- disconnect(d->buddy, SIGNAL(destroyed()), this, SLOT(_q_buddyDeleted()));
+ QObjectPrivate::disconnect(d->buddy, &QObject::destroyed,
+ d, &QLabelPrivate::buddyDeleted);
d->buddy = buddy;
if (buddy)
- connect(buddy, SIGNAL(destroyed()), this, SLOT(_q_buddyDeleted()));
+ QObjectPrivate::connect(buddy, &QObject::destroyed,
+ d, &QLabelPrivate::buddyDeleted);
if (d->isTextLabel) {
if (d->shortcutId)
@@ -1219,7 +1221,7 @@ void QLabelPrivate::updateShortcut()
}
-void QLabelPrivate::_q_buddyDeleted()
+void QLabelPrivate::buddyDeleted()
{
Q_Q(QLabel);
q->setBuddy(nullptr);
@@ -1228,7 +1230,7 @@ void QLabelPrivate::_q_buddyDeleted()
#endif // QT_NO_SHORTCUT
#if QT_CONFIG(movie)
-void QLabelPrivate::_q_movieUpdated(const QRect& rect)
+void QLabelPrivate::movieUpdated(const QRect &rect)
{
Q_Q(QLabel);
if (movie && movie->isValid()) {
@@ -1251,12 +1253,12 @@ void QLabelPrivate::_q_movieUpdated(const QRect& rect)
}
}
-void QLabelPrivate::_q_movieResized(const QSize& size)
+void QLabelPrivate::movieResized(const QSize &size)
{
Q_Q(QLabel);
q->update(); //we need to refresh the whole background in case the new size is smaller
valid_hints = false;
- _q_movieUpdated(QRect(QPoint(0,0), size));
+ movieUpdated(QRect(QPoint(0,0), size));
q->updateGeometry();
}
@@ -1278,8 +1280,10 @@ void QLabel::setMovie(QMovie *movie)
return;
d->movie = movie;
- connect(movie, SIGNAL(resized(QSize)), this, SLOT(_q_movieResized(QSize)));
- connect(movie, SIGNAL(updated(QRect)), this, SLOT(_q_movieUpdated(QRect)));
+ d->movieConnections = {
+ QObjectPrivate::connect(movie, &QMovie::resized, d, &QLabelPrivate::movieResized),
+ QObjectPrivate::connect(movie, &QMovie::updated, d, &QLabelPrivate::movieUpdated),
+ };
// Assume that if the movie is running,
// resize/update signals will come soon enough
@@ -1317,10 +1321,8 @@ void QLabelPrivate::clearContents()
shortcutId = 0;
#endif
#if QT_CONFIG(movie)
- if (movie) {
- QObject::disconnect(movie, SIGNAL(resized(QSize)), q, SLOT(_q_movieResized(QSize)));
- QObject::disconnect(movie, SIGNAL(updated(QRect)), q, SLOT(_q_movieUpdated(QRect)));
- }
+ for (const auto &conn : std::as_const(movieConnections))
+ QObject::disconnect(conn);
movie = nullptr;
#endif
#ifndef QT_NO_CURSOR
@@ -1580,12 +1582,12 @@ void QLabelPrivate::ensureTextControl() const
control->setOpenExternalLinks(openExternalLinks);
control->setPalette(q->palette());
control->setFocus(q->hasFocus());
- QObject::connect(control, SIGNAL(updateRequest(QRectF)),
- q, SLOT(update()));
- QObject::connect(control, SIGNAL(linkHovered(QString)),
- q, SLOT(_q_linkHovered(QString)));
- QObject::connect(control, SIGNAL(linkActivated(QString)),
- q, SIGNAL(linkActivated(QString)));
+ QObject::connect(control, &QWidgetTextControl::updateRequest,
+ q, qOverload<>(&QLabel::update));
+ QObject::connect(control, &QWidgetTextControl::linkActivated,
+ q, &QLabel::linkActivated);
+ QObjectPrivate::connect(control, &QWidgetTextControl::linkHovered,
+ this, &QLabelPrivate::linkHovered);
textLayoutDirty = true;
textDirty = true;
}
@@ -1601,7 +1603,7 @@ void QLabelPrivate::sendControlEvent(QEvent *e)
control->processEvent(e, -layoutRect().topLeft(), q);
}
-void QLabelPrivate::_q_linkHovered(const QString &anchor)
+void QLabelPrivate::linkHovered(const QString &anchor)
{
Q_Q(QLabel);
#ifndef QT_NO_CURSOR
@@ -1652,15 +1654,10 @@ QPoint QLabelPrivate::layoutPoint(const QPoint& p) const
#ifndef QT_NO_CONTEXTMENU
QMenu *QLabelPrivate::createStandardContextMenu(const QPoint &pos)
{
- if (!control || effectiveTextFormat == Qt::PlainText)
+ if (!control)
return nullptr;
const QPoint p = layoutPoint(pos);
- QString linkToCopy = control->document()->documentLayout()->anchorAt(p);
-
- if (linkToCopy.isEmpty())
- return nullptr;
-
return control->createStandardContextMenu(p, q_func());
}
#endif
diff --git a/src/widgets/widgets/qlabel.h b/src/widgets/widgets/qlabel.h
index ddbe05e82a..3749ec366a 100644
--- a/src/widgets/widgets/qlabel.h
+++ b/src/widgets/widgets/qlabel.h
@@ -130,15 +130,6 @@ protected:
private:
Q_DISABLE_COPY(QLabel)
Q_DECLARE_PRIVATE(QLabel)
-#if QT_CONFIG(movie)
- Q_PRIVATE_SLOT(d_func(), void _q_movieUpdated(const QRect&))
- Q_PRIVATE_SLOT(d_func(), void _q_movieResized(const QSize&))
-#endif
- Q_PRIVATE_SLOT(d_func(), void _q_linkHovered(const QString &))
-
-#ifndef QT_NO_SHORTCUT
- Q_PRIVATE_SLOT(d_func(), void _q_buddyDeleted())
-#endif
friend class QTipLabel;
friend class QMessageBoxPrivate;
friend class QBalloonTip;
diff --git a/src/widgets/widgets/qlabel_p.h b/src/widgets/widgets/qlabel_p.h
index 4718a07614..fb6ccb04eb 100644
--- a/src/widgets/widgets/qlabel_p.h
+++ b/src/widgets/widgets/qlabel_p.h
@@ -33,6 +33,9 @@
#include "qmenu.h"
#endif
+#include <QtCore/qpointer.h>
+
+#include <array>
#include <optional>
QT_BEGIN_NAMESPACE
@@ -50,12 +53,12 @@ public:
QSize sizeForWidth(int w) const;
#if QT_CONFIG(movie)
- void _q_movieUpdated(const QRect&);
- void _q_movieResized(const QSize&);
+ void movieUpdated(const QRect &rect);
+ void movieResized(const QSize &size);
#endif
#ifndef QT_NO_SHORTCUT
void updateShortcut();
- void _q_buddyDeleted();
+ void buddyDeleted();
#endif
inline bool needTextControl() const {
Q_Q(const QLabel);
@@ -70,7 +73,7 @@ public:
void ensureTextControl() const;
void sendControlEvent(QEvent *e);
- void _q_linkHovered(const QString &link);
+ void linkHovered(const QString &link);
QRectF layoutRect() const;
QRect documentRect() const;
@@ -91,6 +94,7 @@ public:
#endif
#if QT_CONFIG(movie)
QPointer<QMovie> movie;
+ std::array<QMetaObject::Connection, 2> movieConnections;
#endif
mutable QWidgetTextControl *control;
mutable QTextCursor shortcutCursor;
diff --git a/src/widgets/widgets/qlcdnumber.cpp b/src/widgets/widgets/qlcdnumber.cpp
index eef2685569..3a65b06415 100644
--- a/src/widgets/widgets/qlcdnumber.cpp
+++ b/src/widgets/widgets/qlcdnumber.cpp
@@ -69,7 +69,7 @@ public:
Incidentally, QLCDNumber is the very oldest part of Qt, tracing
its roots back to a BASIC program on the \l{Sinclair Spectrum}{Sinclair Spectrum}.
- \sa QLabel, QFrame, {Digital Clock Example}, {Tetrix Example}
+ \sa QLabel, QFrame
*/
/*!
@@ -1123,7 +1123,7 @@ void QLCDNumberPrivate::drawSegment(const QPoint &pos, char segmentNo, QPainter
/*!
\property QLCDNumber::segmentStyle
- \brief the style of the LCDNumber
+ \brief the style of the LCDNumber.
\table
\header \li Style \li Result
diff --git a/src/widgets/widgets/qlineedit.cpp b/src/widgets/widgets/qlineedit.cpp
index c38f3db7a1..8909ac80d9 100644
--- a/src/widgets/widgets/qlineedit.cpp
+++ b/src/widgets/widgets/qlineedit.cpp
@@ -100,55 +100,66 @@ void QLineEdit::initStyleOption(QStyleOptionFrame *option) const
\image windows-lineedit.png
- A line edit allows the user to enter and edit a single line of
- plain text with a useful collection of editing functions,
- including undo and redo, cut and paste, and drag and drop (see
- \l setDragEnabled()).
+ A line edit allows users to enter and edit a single line of
+ plain text with useful editing functions, including undo and redo, cut and
+ paste, and drag and drop.
By changing the echoMode() of a line edit, it can also be used as
- a "write-only" field, for inputs such as passwords.
+ a write-only field for inputs such as passwords.
- The length of the text can be constrained to maxLength(). The text
- can be arbitrarily constrained using a validator() or an
- inputMask(), or both. When switching between a validator and an input mask
- on the same line edit, it is best to clear the validator or input mask to
- prevent undefined behavior.
-
- A related class is QTextEdit which allows multi-line, rich text
+ QTextEdit is a related class that allows multi-line, rich text
editing.
- You can change the text with setText() or insert(). The text is
- retrieved with text(); the displayed text (which may be different,
- see \l{EchoMode}) is retrieved with displayText(). Text can be
- selected with setSelection() or selectAll(), and the selection can
- be cut(), copy()ied and paste()d. The text can be aligned with
- setAlignment().
-
- When the text changes the textChanged() signal is emitted; when
- the text changes other than by calling setText() the textEdited()
- signal is emitted; when the cursor is moved the
- cursorPositionChanged() signal is emitted; and when the Return or
- Enter key is pressed the returnPressed() signal is emitted.
-
- When editing is finished, either because the line edit lost focus
- or Return/Enter is pressed the editingFinished() signal is
- emitted. Note that if focus is lost without any changes done,
- the editingFinished() signal won't be emitted.
-
- Note that if there is a validator set on the line edit, the
- returnPressed()/editingFinished() signals will only be emitted if
- the validator returns QValidator::Acceptable.
-
- By default, QLineEdits have a frame as specified by platform
- style guides; you can turn it off by calling
- setFrame(false).
-
- The default key bindings are described below. The line edit also
- provides a context menu (usually invoked by a right mouse click)
- that presents some of these editing options.
+ \section1 Constraining Text
+
+ Use \l maxLength to define the maximum permitted length of a text. You can
+ use a \l inputMask and \l setValidator() to further constrain the text
+ content.
+
+ \section1 Editing Text
+
+ You can change the text with setText() or insert(). Use text() to retrieve
+ the text and displayText() to retrieve the displayed text (which may be
+ different, see \l{EchoMode}). You can select the text with setSelection() or
+ selectAll(), and you can cut(), copy(), and paste() the selection. To align
+ the text, use setAlignment().
+
+ When the text changes, the textChanged() signal is emitted. When the text
+ changes in some other way than by calling setText(), the textEdited() signal
+ is emitted. When the cursor is moved, the cursorPositionChanged() signal is
+ emitted. And when the Return or Enter key is selected, the returnPressed()
+ signal is emitted.
+
+ When text editing is finished, either because the line edit lost focus
+ or Return/Enter was selected, the editingFinished() signal is emitted.
+
+ If the line edit focus is lost without any text changes, the
+ editingFinished() signal won't be emitted.
+
+ If there is a validator set on the line edit, the
+ returnPressed()/editingFinished() signals will only be emitted if the
+ validator returns QValidator::Acceptable.
+
+ For more information on the many ways that QLineEdit can be used, see
+ \l {Line Edits Example}, which also provides a selection of line edit
+ examples that show the effects of various properties and validators on the
+ input and output supplied by the user.
+
+ \section1 Setting a Frame
+
+ By default, QLineEdits have a frame as specified in the platform
+ style guides. You can turn the frame off by calling setFrame(false).
+
+ \section1 Default Key Bindings
+
+ The table below describes the default key bindings.
+
+ \note The line edit also provides a context menu (usually invoked by a
+ right-click) that presents some of the editing options listed below.
+
\target desc
\table
- \header \li Keypress \li Action
+ \header \li Keystroke \li Action
\row \li Left Arrow \li Moves the cursor one character to the left.
\row \li Shift+Left Arrow \li Moves and selects text one character to the left.
\row \li Right Arrow \li Moves the cursor one character to the right.
@@ -159,7 +170,7 @@ void QLineEdit::initStyleOption(QStyleOptionFrame *option) const
\row \li Ctrl+Backspace \li Deletes the word to the left of the cursor.
\row \li Delete \li Deletes the character to the right of the cursor.
\row \li Ctrl+Delete \li Deletes the word to the right of the cursor.
- \row \li Ctrl+A \li Select all.
+ \row \li Ctrl+A \li Selects all.
\row \li Ctrl+C \li Copies the selected text to the clipboard.
\row \li Ctrl+Insert \li Copies the selected text to the clipboard.
\row \li Ctrl+K \li Deletes to the end of the line.
@@ -171,8 +182,8 @@ void QLineEdit::initStyleOption(QStyleOptionFrame *option) const
\row \li Ctrl+Y \li Redoes the last undone operation.
\endtable
- Any other key sequence that represents a valid character, will
- cause the character to be inserted into the line edit.
+ Any other keystroke that represents a valid character, will cause the
+ character to be inserted into the line edit.
\sa QTextEdit, QLabel, QComboBox, {Line Edits Example}
*/
@@ -230,13 +241,11 @@ QLineEdit::QLineEdit(QWidget* parent)
}
/*!
- Constructs a line edit containing the text \a contents.
-
- The cursor position is set to the end of the line and the maximum
- text length to 32767 characters.
+ Constructs a line edit containing the text \a contents as a child of
+ \a parent.
- The \a parent and argument is sent to the QWidget
- constructor.
+ The cursor position is set to the end of the line and the maximum text
+ length to 32767 characters.
\sa text(), setMaxLength()
*/
@@ -260,10 +269,10 @@ QLineEdit::~QLineEdit()
/*!
\property QLineEdit::text
- \brief the line edit's text.
+ \brief The line edit's text.
Setting this property clears the selection, clears the undo/redo
- history, moves the cursor to the end of the line and resets the
+ history, moves the cursor to the end of the line, and resets the
\l modified property to false. The text is not validated when
inserted with setText().
@@ -289,7 +298,7 @@ void QLineEdit::setText(const QString& text)
\since 4.7
\property QLineEdit::placeholderText
- \brief the line edit's placeholder text.
+ \brief The line edit's placeholder text.
Setting this property makes the line edit display a grayed-out
placeholder text as long as the line edit is empty.
@@ -321,12 +330,12 @@ void QLineEdit::setPlaceholderText(const QString& placeholderText)
/*!
\property QLineEdit::displayText
- \brief the displayed text.
+ \brief The displayed text.
- If \l echoMode is \l Normal this returns the same as text(); if
- \l EchoMode is \l Password or \l PasswordEchoOnEdit it returns a string of
- platform-dependent password mask characters text().length() in size,
- e.g. "******"; if \l EchoMode is \l NoEcho returns an empty string, "".
+ If \l echoMode is \l Normal, this returns the same as text(). If
+ \l EchoMode is \l Password or \l PasswordEchoOnEdit, it returns a string of
+ platform-dependent password mask characters (e.g. "******"). If \l EchoMode
+ is \l NoEcho, it returns an empty string.
By default, this property contains an empty string.
@@ -342,12 +351,12 @@ QString QLineEdit::displayText() const
/*!
\property QLineEdit::maxLength
- \brief the maximum permitted length of the text.
+ \brief The maximum permitted length of the text.
If the text is too long, it is truncated at the limit.
- If truncation occurs any selected text will be unselected, the
- cursor position is set to 0 and the first part of the string is
+ If truncation occurs, any selected text will be unselected, the
+ cursor position is set to 0, and the first part of the string is
shown.
If the line edit has an input mask, the mask defines the maximum
@@ -372,10 +381,10 @@ void QLineEdit::setMaxLength(int maxLength)
/*!
\property QLineEdit::frame
- \brief whether the line edit draws itself with a frame.
+ \brief Whether the line edit draws itself with a frame.
- If enabled (the default) the line edit draws itself inside a
- frame, otherwise the line edit draws itself without any frame.
+ If enabled (the default), the line edit draws itself inside a
+ frame. Otherwise, the line edit draws itself without any frame.
*/
bool QLineEdit::hasFrame() const
{
@@ -435,9 +444,9 @@ QAction *QLineEdit::addAction(const QIcon &icon, ActionPosition position)
\property QLineEdit::clearButtonEnabled
\brief Whether the line edit displays a clear button when it is not empty.
- If enabled, the line edit displays a trailing \e clear button when it contains
- some text, otherwise the line edit does not show a clear button (the
- default).
+ If enabled, the line edit displays a trailing \uicontrol clear button when
+ it contains some text. Otherwise, the line edit does not show a
+ \uicontrol clear button (the default).
\sa addAction(), removeAction()
\since 5.2
@@ -501,9 +510,8 @@ void QLineEdit::setFrame(bool enable)
password should be kept secret.
\value Password Display platform-dependent password mask characters instead
of the characters actually entered.
- \value PasswordEchoOnEdit Display characters as they are entered
- while editing otherwise display characters as with
- \c Password.
+ \value PasswordEchoOnEdit Display characters only while they are entered.
+ Otherwise, display characters as with \c Password.
\sa setEchoMode(), echoMode()
*/
@@ -511,13 +519,13 @@ void QLineEdit::setFrame(bool enable)
/*!
\property QLineEdit::echoMode
- \brief the line edit's echo mode.
+ \brief The line edit's echo mode.
The echo mode determines how the text entered in the line edit is
displayed (or echoed) to the user.
The most common setting is \l Normal, in which the text entered by the
- user is displayed verbatim, but QLineEdit also supports modes that allow
+ user is displayed verbatim. QLineEdit also supports modes that allow
the entered text to be suppressed or obscured: these include \l NoEcho,
\l Password and \l PasswordEchoOnEdit.
@@ -574,15 +582,15 @@ const QValidator * QLineEdit::validator() const
value during editing, but will be prevented from editing the text to a
value that \a v validates as \l{QValidator::}{Invalid}.
- This allows you to constrain the text that shall finally be entered when editing is
- done, while leaving users with enough freedom to edit the text from one valid state
- to another.
+ This allows you to constrain the text that will be stored when editing is
+ done while leaving users with enough freedom to edit the text from one valid
+ state to another.
- If \a v == 0, setValidator() removes the current input validator.
- The initial setting is to have no input validator (i.e. any input
- is accepted up to maxLength()).
+ To remove the current input validator, pass \c nullptr. The initial setting
+ is to have no input validator (any input is accepted up to maxLength()).
- \sa validator(), hasAcceptableInput(), QIntValidator, QDoubleValidator, QRegularExpressionValidator
+ \sa validator(), hasAcceptableInput(), QIntValidator, QDoubleValidator,
+ QRegularExpressionValidator
*/
void QLineEdit::setValidator(const QValidator *v)
@@ -604,8 +612,7 @@ void QLineEdit::setValidator(const QValidator *v)
use the QSortFilterProxyModel to ensure that the QCompleter's model contains
only valid entries.
- If \a c == 0, setCompleter() removes the current completer, effectively
- disabling auto completion.
+ To remove the completer and disable auto-completion, pass a \c nullptr.
\sa QCompleter
*/
@@ -615,7 +622,7 @@ void QLineEdit::setCompleter(QCompleter *c)
if (c == d->control->completer())
return;
if (d->control->completer()) {
- disconnect(d->control->completer(), nullptr, this, nullptr);
+ d->disconnectCompleter();
d->control->completer()->setWidget(nullptr);
if (d->control->completer()->parent() == this)
delete d->control->completer();
@@ -625,12 +632,8 @@ void QLineEdit::setCompleter(QCompleter *c)
return;
if (c->widget() == nullptr)
c->setWidget(this);
- if (hasFocus()) {
- QObject::connect(d->control->completer(), SIGNAL(activated(QString)),
- this, SLOT(setText(QString)));
- QObject::connect(d->control->completer(), SIGNAL(highlighted(QString)),
- this, SLOT(_q_completionHighlighted(QString)));
- }
+ if (hasFocus())
+ d->connectCompleter();
}
/*!
@@ -698,7 +701,7 @@ QSize QLineEdit::minimumSizeHint() const
/*!
\property QLineEdit::cursorPosition
- \brief the current cursor position for this line edit.
+ \brief The current cursor position for this line edit.
Setting the cursor position causes a repaint when appropriate.
@@ -731,7 +734,7 @@ int QLineEdit::cursorPositionAt(const QPoint &pos)
/*!
\property QLineEdit::alignment
- \brief the alignment of the line edit.
+ \brief The alignment of the line edit.
Both horizontal and vertical alignment is allowed here, Qt::AlignJustify
will map to Qt::AlignLeft.
@@ -756,9 +759,9 @@ void QLineEdit::setAlignment(Qt::Alignment alignment)
/*!
- Moves the cursor forward \a steps characters. If \a mark is true
- each character moved over is added to the selection; if \a mark is
- false the selection is cleared.
+ Moves the cursor forward \a steps characters. If \a mark is true,
+ each character moved over is added to the selection. If \a mark is
+ false, the selection is cleared.
\sa cursorBackward()
*/
@@ -771,9 +774,9 @@ void QLineEdit::cursorForward(bool mark, int steps)
/*!
- Moves the cursor back \a steps characters. If \a mark is true each
- character moved over is added to the selection; if \a mark is
- false the selection is cleared.
+ Moves the cursor back \a steps characters. If \a mark is true, each
+ character moved over is added to the selection. If \a mark is
+ false, the selection is cleared.
\sa cursorForward()
*/
@@ -810,9 +813,9 @@ void QLineEdit::cursorWordBackward(bool mark)
/*!
If no text is selected, deletes the character to the left of the
- text cursor and moves the cursor one position to the left. If any
+ text cursor, and moves the cursor one position to the left. If any
text is selected, the cursor is moved to the beginning of the
- selected text and the selected text is deleted.
+ selected text, and the selected text is deleted.
\sa del()
*/
@@ -825,7 +828,7 @@ void QLineEdit::backspace()
/*!
If no text is selected, deletes the character to the right of the
text cursor. If any text is selected, the cursor is moved to the
- beginning of the selected text and the selected text is deleted.
+ beginning of the selected text, and the selected text is deleted.
\sa backspace()
*/
@@ -839,7 +842,7 @@ void QLineEdit::del()
/*!
Moves the text cursor to the beginning of the line unless it is
already there. If \a mark is true, text is selected towards the
- first position; otherwise, any selected text is unselected if the
+ first position. Otherwise, any selected text is unselected if the
cursor is moved.
\sa end()
@@ -854,7 +857,7 @@ void QLineEdit::home(bool mark)
/*!
Moves the text cursor to the end of the line unless it is already
there. If \a mark is true, text is selected towards the last
- position; otherwise, any selected text is unselected if the cursor
+ position. Otherwise, any selected text is unselected if the cursor
is moved.
\sa home()
@@ -869,14 +872,14 @@ void QLineEdit::end(bool mark)
/*!
\property QLineEdit::modified
- \brief whether the line edit's contents has been modified by the user.
+ \brief Whether the line edit's contents has been modified by the user.
The modified flag is never read by QLineEdit; it has a default value
of false and is changed to true whenever the user changes the line
edit's contents.
This is useful for things that need to provide a default value but
- do not start out knowing what the default should be (perhaps it
+ do not start out knowing what the default should be (for example, it
depends on other fields on the form). Start the line edit without
the best default, and when the default is known, if modified()
returns \c false (the user hasn't entered any text), insert the
@@ -899,10 +902,10 @@ void QLineEdit::setModified(bool modified)
/*!
\property QLineEdit::hasSelectedText
- \brief whether there is any text selected.
+ \brief Whether there is any text selected.
hasSelectedText() returns \c true if some or all of the text has been
- selected by the user; otherwise returns \c false.
+ selected by the user. Otherwise, it returns \c false.
By default, this property is \c false.
@@ -918,9 +921,9 @@ bool QLineEdit::hasSelectedText() const
/*!
\property QLineEdit::selectedText
- \brief the selected text.
+ \brief The selected text.
- If there is no selected text this property's value is
+ If there is no selected text, this property's value is
an empty string.
By default, this property contains an empty string.
@@ -936,7 +939,7 @@ QString QLineEdit::selectedText() const
/*!
Returns the index of the first selected character in the
- line edit or -1 if no text is selected.
+ line edit (or -1 if no text is selected).
\sa selectedText()
\sa selectionEnd()
@@ -951,7 +954,7 @@ int QLineEdit::selectionStart() const
/*!
Returns the index of the character directly after the selection
- in the line edit or -1 if no text is selected.
+ in the line edit (or -1 if no text is selected).
\since 5.10
\sa selectedText()
@@ -1005,7 +1008,7 @@ void QLineEdit::setSelection(int start, int length)
/*!
\property QLineEdit::undoAvailable
- \brief whether undo is available.
+ \brief Whether undo is available.
Undo becomes available once the user has modified the text in the line edit.
@@ -1020,10 +1023,10 @@ bool QLineEdit::isUndoAvailable() const
/*!
\property QLineEdit::redoAvailable
- \brief whether redo is available.
+ \brief Whether redo is available.
Redo becomes available once the user has performed one or more undo operations
- on text in the line edit.
+ on the text in the line edit.
By default, this property is \c false.
*/
@@ -1036,7 +1039,7 @@ bool QLineEdit::isRedoAvailable() const
/*!
\property QLineEdit::dragEnabled
- \brief whether the lineedit starts a drag if the user presses and
+ \brief Whether the line edit starts a drag if the user presses and
moves the mouse on some selected text.
Dragging is disabled by default.
@@ -1056,17 +1059,18 @@ void QLineEdit::setDragEnabled(bool b)
/*!
\property QLineEdit::cursorMoveStyle
- \brief the movement style of cursor in this line edit.
+ \brief The movement style of the cursor in this line edit.
\since 4.8
- When this property is set to Qt::VisualMoveStyle, the line edit will use visual
- movement style. Pressing the left arrow key will always cause the cursor to move
- left, regardless of the text's writing direction. The same behavior applies to
- right arrow key.
+ When this property is set to Qt::VisualMoveStyle, the line edit will use a
+ visual movement style. Using the left arrow key will always cause the
+ cursor to move left, regardless of the text's writing direction. The same
+ behavior applies to the right arrow key.
- When the property is Qt::LogicalMoveStyle (the default), within a LTR text block,
- increase cursor position when pressing left arrow key, decrease cursor position
- when pressing the right arrow key. If the text block is right to left, the opposite
+ When the property is set to Qt::LogicalMoveStyle (the default), within a
+ left-to-right (LTR) text block, using the left arrow key will increase
+ the cursor position, whereas using the right arrow key will decrease the
+ cursor position. If the text block is right-to-left (RTL), the opposite
behavior applies.
*/
@@ -1084,7 +1088,7 @@ void QLineEdit::setCursorMoveStyle(Qt::CursorMoveStyle style)
/*!
\property QLineEdit::acceptableInput
- \brief whether the input satisfies the inputMask and the
+ \brief Whether the input satisfies the inputMask and the
validator.
By default, this property is \c true.
@@ -1098,11 +1102,11 @@ bool QLineEdit::hasAcceptableInput() const
}
/*!
+ \since 4.5
Sets the margins around the text inside the frame to have the
sizes \a left, \a top, \a right, and \a bottom.
- \since 4.5
- See also textMargins().
+ \sa textMargins()
*/
void QLineEdit::setTextMargins(int left, int top, int right, int bottom)
{
@@ -1113,7 +1117,7 @@ void QLineEdit::setTextMargins(int left, int top, int right, int bottom)
\since 4.6
Sets the \a margins around the text inside the frame.
- See also textMargins().
+ \sa textMargins()
*/
void QLineEdit::setTextMargins(const QMargins &margins)
{
@@ -1139,41 +1143,47 @@ QMargins QLineEdit::textMargins() const
\property QLineEdit::inputMask
\brief The validation input mask.
- If no mask is set, inputMask() returns an empty string.
-
Sets the QLineEdit's validation mask. Validators can be used
- instead of, or in conjunction with masks; see setValidator().
+ instead of, or in conjunction with masks; see setValidator(). The default is
+ an empty string, which means that no input mask is used.
- Unset the mask and return to normal QLineEdit operation by passing
- an empty string ("").
+ To unset the mask and return to normal QLineEdit operation, pass an empty
+ string.
- The input mask is an input template string. It can contain the following elements:
+ The input mask is an input template string. It can contain the following
+ elements:
\table
- \row \li Mask Characters \li Defines the \l {QChar::} {Category} of input characters
- that are considered valid in this position
- \row \li Meta Characters \li Various special meanings
- \row \li Separators \li All other characters are regarded as immutable separators
+ \row \li Mask Characters \li Defines the \l {QChar::} {Category} of input
+ characters that are considered valid in this position.
+ \row \li Meta Characters \li Various special meanings (see details below).
+ \row \li Separators \li All other characters are regarded as immutable
+ separators.
\endtable
- The following table shows the mask and meta characters that can be used in an input mask.
+ The following table shows the mask and meta characters that can be used in
+ an input mask.
\table
\header \li Mask Character \li Meaning
- \row \li \c A \li character of the Letter category required, such as A-Z, a-z.
- \row \li \c a \li character of the Letter category permitted but not required.
- \row \li \c N \li character of the Letter or Number category required, such as
- A-Z, a-z, 0-9.
- \row \li \c n \li character of the Letter or Number category permitted but not required.
+ \row \li \c A \li Character of the Letter category required, such as A-Z,
+ a-z.
+ \row \li \c a \li Character of the Letter category permitted but not
+ required.
+ \row \li \c N \li Character of the Letter or Number category required, such
+ as A-Z, a-z, 0-9.
+ \row \li \c n \li Character of the Letter or Number category permitted but
+ not required.
\row \li \c X \li Any non-blank character required.
\row \li \c x \li Any non-blank character permitted but not required.
- \row \li \c 9 \li character of the Number category required, e.g 0-9.
- \row \li \c 0 \li character of the Number category permitted but not required.
- \row \li \c D \li character of the Number category and larger than zero required,
- such as 1-9
- \row \li \c d \li character of the Number category and larger than zero permitted but not
- required, such as 1-9.
- \row \li \c # \li character of the Number category, or plus/minus sign permitted but not
+ \row \li \c 9 \li Character of the Number category required, such as 0-9.
+ \row \li \c 0 \li Character of the Number category permitted but not
required.
+ \row \li \c D \li Character of the Number category and larger than zero
+ required, such as 1-9.
+ \row \li \c d \li Character of the Number category and larger than zero
+ permitted but not required, such as 1-9.
+ \row \li \c # \li Character of the Number category, or plus/minus sign
+ permitted but not required.
\row \li \c H \li Hexadecimal character required. A-F, a-f, 0-9.
\row \li \c h \li Hexadecimal character permitted but not required.
\row \li \c B \li Binary character required. 0-1.
@@ -1182,11 +1192,11 @@ QMargins QLineEdit::textMargins() const
\row \li \c > \li All following alphabetic characters are uppercased.
\row \li \c < \li All following alphabetic characters are lowercased.
\row \li \c ! \li Switch off case conversion.
- \row \li \c {;c} \li Terminates the input mask and sets the \e{blank} character to \e{c}.
+ \row \li \c {;c} \li Terminates the input mask and sets the \e{blank}
+ character to \e{c}.
\row \li \c {[ ] { }} \li Reserved.
- \row \li \tt{\\} \li Use \tt{\\} to escape the special
- characters listed above to use them as
- separators.
+ \row \li \tt{\\} \li Use \tt{\\} to escape the special characters listed
+ above to use them as separators.
\endtable
When created or cleared, the line edit will be filled with a copy of the
@@ -1199,7 +1209,7 @@ QMargins QLineEdit::textMargins() const
unmodified content can be read using displayText().
The hasAcceptableInput() method returns false if the current content of the
- line edit does not fulfil the requirements of the input mask.
+ line edit does not fulfill the requirements of the input mask.
Examples:
\table
@@ -1230,8 +1240,10 @@ void QLineEdit::setInputMask(const QString &inputMask)
}
/*!
- Selects all the text (i.e. highlights it) and moves the cursor to
- the end. This is useful when a default value has been inserted
+ Selects all the text (highlights it) and moves the cursor to
+ the end.
+
+ \note This is useful when a default value has been inserted
because if the user types before clicking on the widget, the
selected text will be deleted.
@@ -1259,7 +1271,7 @@ void QLineEdit::deselect()
/*!
Deletes any selected text, inserts \a newText, and validates the
- result. If it is valid, it sets it as the new contents of the line
+ result. If it is valid, it sets the new text as the new contents of the line
edit.
\sa setText(), clear()
@@ -1308,7 +1320,7 @@ void QLineEdit::redo()
/*!
\property QLineEdit::readOnly
- \brief whether the line edit is read only.
+ \brief Whether the line edit is read-only.
In read-only mode, the user can still copy the text to the
clipboard, or drag and drop the text (if echoMode() is \l Normal),
@@ -1431,7 +1443,10 @@ bool QLineEdit::event(QEvent * e)
#endif
//d->separate();
} else if (e->type() == QEvent::WindowActivate) {
- QTimer::singleShot(0, this, SLOT(_q_handleWindowActivate()));
+ QTimer::singleShot(0, this, [this]() {
+ Q_D(QLineEdit);
+ d->handleWindowActivate();
+ });
#ifndef QT_NO_SHORTCUT
} else if (e->type() == QEvent::ShortcutOverride) {
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
@@ -1447,6 +1462,8 @@ bool QLineEdit::event(QEvent * e)
|| style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
d->setCursorVisible(true);
}
+ } else if (e->type() == QEvent::Hide) {
+ d->control->setBlinkingCursorEnabled(false);
#if QT_CONFIG(action)
} else if (e->type() == QEvent::ActionRemoved) {
d->removeAction(static_cast<QActionEvent *>(e)->action());
@@ -1647,8 +1664,9 @@ void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e)
/*!
\fn void QLineEdit::returnPressed()
- This signal is emitted when the Return or Enter key is pressed.
- Note that if there is a validator() or inputMask() set on the line
+ This signal is emitted when the Return or Enter key is used.
+
+ \note If there is a validator() or inputMask() set on the line
edit, the returnPressed() signal will only be emitted if the input
follows the inputMask() and the validator() returns
QValidator::Acceptable.
@@ -1657,41 +1675,39 @@ void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e)
/*!
\fn void QLineEdit::editingFinished()
- This signal is emitted when the Return or Enter key is pressed, or
- if the line edit loses focus and its contents have changed since the
- last time this signal was emitted.
+ This signal is emitted when the Return or Enter key is used, or if the line
+ edit loses focus and its contents have changed since the last time this
+ signal was emitted.
- Note that if there is a validator() or
- inputMask() set on the line edit and enter/return is pressed, the
- editingFinished() signal will only be emitted if the input follows
- the inputMask() and the validator() returns QValidator::Acceptable.
+ \note If there is a validator() or inputMask() set on the line edit and
+ enter/return is used, the editingFinished() signal will only be emitted
+ if the input follows the inputMask() and the validator() returns
+ QValidator::Acceptable.
*/
/*!
\fn void QLineEdit::inputRejected()
\since 5.12
- This signal is emitted when the user presses a key that is not
- considered to be acceptable input. For example, if a key press
- results in a validator's validate() call to return Invalid.
- Another case is when trying to enter in more characters beyond the
- maximum length of the line edit.
+ This signal is emitted when the user uses a key that is not
+ considered to be valid input. For example, if using a key results in a
+ validator's \l {QValidator::validate()}{validate()} call to return
+ \l {QValidator::Invalid}{Invalid}. Another case is when trying
+ to enter more characters beyond the maximum length of the line edit.
- Note: This signal will still be emitted in a case where part of
- the text is accepted but not all of it is. For example, if there
- is a maximum length set and the clipboard text is longer than the
- maximum length when it is pasted.
+ \note This signal will still be emitted when only a part of the text is
+ accepted. For example, if there is a maximum length set and the clipboard
+ text is longer than the maximum length when it is pasted.
*/
/*!
Converts the given key press \a event into a line edit action.
- If Return or Enter is pressed and the current text is valid (or
+ If Return or Enter is used and the current text is valid (or
can be \l{QValidator::fixup()}{made valid} by the
validator), the signal returnPressed() is emitted.
- The default key bindings are listed in the class's detailed
- description.
+ \sa {Default Key Bindings}
*/
void QLineEdit::keyPressEvent(QKeyEvent *event)
@@ -1747,18 +1763,19 @@ void QLineEdit::keyPressEvent(QKeyEvent *event)
/*!
\reimp
*/
-void QLineEdit::keyReleaseEvent(QKeyEvent *)
+void QLineEdit::keyReleaseEvent(QKeyEvent *e)
{
Q_D(QLineEdit);
if (!isReadOnly())
d->handleSoftwareInputPanel();
d->control->updateCursorBlinking();
+ QWidget::keyReleaseEvent(e);
}
/*!
\since 4.4
- Returns a rectangle that includes the lineedit cursor.
+ Returns a rectangle that includes the line edit cursor.
*/
QRect QLineEdit::cursorRect() const
{
@@ -1802,6 +1819,22 @@ void QLineEdit::inputMethodEvent(QInputMethodEvent *e)
*/
QVariant QLineEdit::inputMethodQuery(Qt::InputMethodQuery property) const
{
+#ifdef Q_OS_ANDROID
+ // QTBUG-61652
+ if (property == Qt::ImEnterKeyType) {
+ QWidget *next = nextInFocusChain();
+ while (next && next != this && next->focusPolicy() == Qt::NoFocus)
+ next = next->nextInFocusChain();
+ if (next) {
+ const auto nextYPos = next->mapToGlobal(QPoint(0, 0)).y();
+ const auto currentYPos = mapToGlobal(QPoint(0, 0)).y();
+ if (currentYPos < nextYPos)
+ // Set EnterKey to KeyNext type only if the next widget
+ // in the focus chain is below current QLineEdit
+ return Qt::EnterKeyNext;
+ }
+ }
+#endif
return inputMethodQuery(property, QVariant());
}
@@ -1812,7 +1845,7 @@ QVariant QLineEdit::inputMethodQuery(Qt::InputMethodQuery property, QVariant arg
Q_D(const QLineEdit);
switch(property) {
case Qt::ImEnabled:
- return isEnabled();
+ return isEnabled() && !isReadOnly();
case Qt::ImCursorRectangle:
return d->cursorRect();
case Qt::ImAnchorRectangle:
@@ -1892,10 +1925,7 @@ void QLineEdit::focusInEvent(QFocusEvent *e)
#if QT_CONFIG(completer)
if (d->control->completer()) {
d->control->completer()->setWidget(this);
- QObject::connect(d->control->completer(), SIGNAL(activated(QString)),
- this, SLOT(setText(QString)));
- QObject::connect(d->control->completer(), SIGNAL(highlighted(QString)),
- this, SLOT(_q_completionHighlighted(QString)));
+ d->connectCompleter();
}
#endif
update();
@@ -1934,9 +1964,8 @@ void QLineEdit::focusOutEvent(QFocusEvent *e)
d->control->setCancelText(QString());
#endif
#if QT_CONFIG(completer)
- if (d->control->completer()) {
- QObject::disconnect(d->control->completer(), nullptr, this, nullptr);
- }
+ if (d->control->completer())
+ d->disconnectCompleter();
#endif
QWidget::focusOutEvent(e);
}
@@ -2067,7 +2096,7 @@ void QLineEdit::paintEvent(QPaintEvent *)
if (d->cursorVisible && !d->control->isReadOnly() && d->control->inputMask().isEmpty())
flags |= QWidgetLineControl::DrawCursor;
- d->control->setCursorWidth(style()->pixelMetric(QStyle::PM_TextCursorWidth, &panel));
+ d->control->setCursorWidth(style()->pixelMetric(QStyle::PM_TextCursorWidth, &panel, this));
d->control->draw(&p, topLeft, r, flags);
}
@@ -2146,10 +2175,10 @@ void QLineEdit::dropEvent(QDropEvent* e)
createStandardContextMenu().
If you do not want the line edit to have a context menu, you can set
- its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
- customize the context menu, reimplement this function. If you want
- to extend the standard context menu, reimplement this function, call
- createStandardContextMenu() and extend the menu returned.
+ its \l contextMenuPolicy to Qt::NoContextMenu. To customize the context
+ menu, reimplement this function. To extend the standard context menu,
+ reimplement this function, call createStandardContextMenu(), and extend the
+ menu returned.
\snippet code/src_gui_widgets_qlineedit.cpp 0
@@ -2166,14 +2195,7 @@ void QLineEdit::contextMenuEvent(QContextMenuEvent *event)
}
}
-static inline void setActionIcon(QAction *action, const QString &name)
-{
- const QIcon icon = QIcon::fromTheme(name);
- if (!icon.isNull())
- action->setIcon(icon);
-}
-
-/*! This function creates the standard context menu which is shown
+/*! Creates the standard context menu, which is shown
when the user clicks on the line edit with the right mouse
button. It is called from the default contextMenuEvent() handler.
The popup menu's ownership is transferred to the caller.
@@ -2190,12 +2212,12 @@ QMenu *QLineEdit::createStandardContextMenu()
action = popup->addAction(QLineEdit::tr("&Undo") + ACCEL_KEY(QKeySequence::Undo));
action->setEnabled(d->control->isUndoAvailable());
setActionIcon(action, QStringLiteral("edit-undo"));
- connect(action, SIGNAL(triggered()), SLOT(undo()));
+ connect(action, &QAction::triggered, this, &QLineEdit::undo);
action = popup->addAction(QLineEdit::tr("&Redo") + ACCEL_KEY(QKeySequence::Redo));
action->setEnabled(d->control->isRedoAvailable());
setActionIcon(action, QStringLiteral("edit-redo"));
- connect(action, SIGNAL(triggered()), SLOT(redo()));
+ connect(action, &QAction::triggered, this, &QLineEdit::redo);
popup->addSeparator();
}
@@ -2206,20 +2228,20 @@ QMenu *QLineEdit::createStandardContextMenu()
action->setEnabled(!d->control->isReadOnly() && d->control->hasSelectedText()
&& d->control->echoMode() == QLineEdit::Normal);
setActionIcon(action, QStringLiteral("edit-cut"));
- connect(action, SIGNAL(triggered()), SLOT(cut()));
+ connect(action, &QAction::triggered, this, &QLineEdit::cut);
}
action = popup->addAction(QLineEdit::tr("&Copy") + ACCEL_KEY(QKeySequence::Copy));
action->setEnabled(d->control->hasSelectedText()
&& d->control->echoMode() == QLineEdit::Normal);
setActionIcon(action, QStringLiteral("edit-copy"));
- connect(action, SIGNAL(triggered()), SLOT(copy()));
+ connect(action, &QAction::triggered, this, &QLineEdit::copy);
if (!isReadOnly()) {
action = popup->addAction(QLineEdit::tr("&Paste") + ACCEL_KEY(QKeySequence::Paste));
action->setEnabled(!d->control->isReadOnly() && !QGuiApplication::clipboard()->text().isEmpty());
setActionIcon(action, QStringLiteral("edit-paste"));
- connect(action, SIGNAL(triggered()), SLOT(paste()));
+ connect(action, &QAction::triggered, this, &QLineEdit::paste);
}
#endif
@@ -2227,7 +2249,8 @@ QMenu *QLineEdit::createStandardContextMenu()
action = popup->addAction(QLineEdit::tr("Delete"));
action->setEnabled(!d->control->isReadOnly() && !d->control->text().isEmpty() && d->control->hasSelectedText());
setActionIcon(action, QStringLiteral("edit-delete"));
- connect(action, SIGNAL(triggered()), d->control, SLOT(_q_deleteSelected()));
+ connect(action, &QAction::triggered,
+ d->control, &QWidgetLineControl::_q_deleteSelected);
}
if (!popup->isEmpty())
@@ -2237,7 +2260,7 @@ QMenu *QLineEdit::createStandardContextMenu()
action->setEnabled(!d->control->text().isEmpty() && !d->control->allSelected());
setActionIcon(action, QStringLiteral("edit-select-all"));
d->selectAllAction = action;
- connect(action, SIGNAL(triggered()), SLOT(selectAll()));
+ connect(action, &QAction::triggered, this, &QLineEdit::selectAll);
if (!d->control->isReadOnly() && QGuiApplication::styleHints()->useRtlExtensions()) {
popup->addSeparator();
diff --git a/src/widgets/widgets/qlineedit.h b/src/widgets/widgets/qlineedit.h
index e0729f0929..8955a67895 100644
--- a/src/widgets/widgets/qlineedit.h
+++ b/src/widgets/widgets/qlineedit.h
@@ -214,20 +214,6 @@ private:
#endif
Q_DISABLE_COPY(QLineEdit)
Q_DECLARE_PRIVATE(QLineEdit)
- Q_PRIVATE_SLOT(d_func(), void _q_handleWindowActivate())
- Q_PRIVATE_SLOT(d_func(), void _q_textEdited(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged(int, int))
-#if QT_CONFIG(completer)
- Q_PRIVATE_SLOT(d_func(), void _q_completionHighlighted(const QString &))
-#endif
-#ifdef QT_KEYPAD_NAVIGATION
- Q_PRIVATE_SLOT(d_func(), void _q_editFocusChange(bool))
-#endif
- Q_PRIVATE_SLOT(d_func(), void _q_selectionChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_updateNeeded(const QRect &))
- Q_PRIVATE_SLOT(d_func(), void _q_textChanged(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_clearButtonClicked())
- Q_PRIVATE_SLOT(d_func(), void _q_controlEditingFinished())
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qlineedit_p.cpp b/src/widgets/widgets/qlineedit_p.cpp
index e846600149..fdd6a3aa4f 100644
--- a/src/widgets/widgets/qlineedit_p.cpp
+++ b/src/widgets/widgets/qlineedit_p.cpp
@@ -74,8 +74,25 @@ QRect QLineEditPrivate::cursorRect() const
}
#if QT_CONFIG(completer)
+void QLineEditPrivate::connectCompleter()
+{
+ Q_Q(const QLineEdit);
+ QObject::connect(control->completer(), qOverload<const QString &>(&QCompleter::activated),
+ q, &QLineEdit::setText);
+ QObjectPrivate::connect(control->completer(), qOverload<const QString &>(&QCompleter::highlighted),
+ this, &QLineEditPrivate::completionHighlighted);
+}
-void QLineEditPrivate::_q_completionHighlighted(const QString &newText)
+void QLineEditPrivate::disconnectCompleter()
+{
+ Q_Q(const QLineEdit);
+ QObject::disconnect(control->completer(), qOverload<const QString &>(&QCompleter::activated),
+ q, &QLineEdit::setText);
+ QObjectPrivate::disconnect(control->completer(), qOverload<const QString &>(&QCompleter::highlighted),
+ this, &QLineEditPrivate::completionHighlighted);
+}
+
+void QLineEditPrivate::completionHighlighted(const QString &newText)
{
Q_Q(QLineEdit);
if (control->completer()->completionMode() != QCompleter::InlineCompletion) {
@@ -96,14 +113,14 @@ void QLineEditPrivate::_q_completionHighlighted(const QString &newText)
#endif // QT_CONFIG(completer)
-void QLineEditPrivate::_q_handleWindowActivate()
+void QLineEditPrivate::handleWindowActivate()
{
Q_Q(QLineEdit);
if (!q->hasFocus() && control->hasSelectedText())
control->deselect();
}
-void QLineEditPrivate::_q_textEdited(const QString &text)
+void QLineEditPrivate::textEdited(const QString &text)
{
Q_Q(QLineEdit);
edited = true;
@@ -115,7 +132,7 @@ void QLineEditPrivate::_q_textEdited(const QString &text)
#endif
}
-void QLineEditPrivate::_q_cursorPositionChanged(int from, int to)
+void QLineEditPrivate::cursorPositionChanged(int from, int to)
{
Q_Q(QLineEdit);
q->update();
@@ -123,14 +140,14 @@ void QLineEditPrivate::_q_cursorPositionChanged(int from, int to)
}
#ifdef QT_KEYPAD_NAVIGATION
-void QLineEditPrivate::_q_editFocusChange(bool e)
+void QLineEditPrivate::editFocusChange(bool e)
{
Q_Q(QLineEdit);
q->setEditFocus(e);
}
#endif
-void QLineEditPrivate::_q_selectionChanged()
+void QLineEditPrivate::selectionChanged()
{
Q_Q(QLineEdit);
if (control->preeditAreaText().isEmpty()) {
@@ -150,7 +167,7 @@ void QLineEditPrivate::_q_selectionChanged()
#endif
}
-void QLineEditPrivate::_q_updateNeeded(const QRect &rect)
+void QLineEditPrivate::updateNeeded(const QRect &rect)
{
q_func()->update(adjustedControlRect(rect));
}
@@ -158,45 +175,51 @@ void QLineEditPrivate::_q_updateNeeded(const QRect &rect)
void QLineEditPrivate::init(const QString& txt)
{
Q_Q(QLineEdit);
+
+ const auto qUpdateMicroFocus = [q]()
+ {
+ q->updateMicroFocus();
+ };
control = new QWidgetLineControl(txt);
control->setParent(q);
control->setFont(q->font());
- QObject::connect(control, SIGNAL(textChanged(QString)),
- q, SIGNAL(textChanged(QString)));
- QObject::connect(control, SIGNAL(textEdited(QString)),
- q, SLOT(_q_textEdited(QString)));
- QObject::connect(control, SIGNAL(cursorPositionChanged(int,int)),
- q, SLOT(_q_cursorPositionChanged(int,int)));
- QObject::connect(control, SIGNAL(selectionChanged()),
- q, SLOT(_q_selectionChanged()));
- QObject::connect(control, SIGNAL(editingFinished()),
- q, SLOT(_q_controlEditingFinished()));
+ QObject::connect(control, &QWidgetLineControl::textChanged,
+ q, &QLineEdit::textChanged);
+ QObjectPrivate::connect(control, &QWidgetLineControl::textEdited,
+ this, &QLineEditPrivate::textEdited);
+ QObjectPrivate::connect(control, &QWidgetLineControl::cursorPositionChanged,
+ this, &QLineEditPrivate::cursorPositionChanged);
+ QObjectPrivate::connect(control, &QWidgetLineControl::selectionChanged,
+ this, &QLineEditPrivate::selectionChanged);
+ QObjectPrivate::connect(control, &QWidgetLineControl::editingFinished,
+ this, &QLineEditPrivate::controlEditingFinished);
#ifdef QT_KEYPAD_NAVIGATION
- QObject::connect(control, SIGNAL(editFocusChange(bool)),
- q, SLOT(_q_editFocusChange(bool)));
+ QObject::connect(control, &QWidgetLineControl::editFocusChange,
+ this, &QLineEditPrivate::editFocusChange);
#endif
- QObject::connect(control, SIGNAL(cursorPositionChanged(int,int)),
- q, SLOT(updateMicroFocus()));
+ QObject::connect(control, &QWidgetLineControl::cursorPositionChanged,
+ q, qUpdateMicroFocus);
- QObject::connect(control, SIGNAL(textChanged(QString)),
- q, SLOT(updateMicroFocus()));
+ QObject::connect(control, &QWidgetLineControl::textChanged,
+ q, qUpdateMicroFocus);
- QObject::connect(control, SIGNAL(updateMicroFocus()),
- q, SLOT(updateMicroFocus()));
+ QObject::connect(control, &QWidgetLineControl::updateMicroFocus,
+ q, qUpdateMicroFocus);
// for now, going completely overboard with updates.
- QObject::connect(control, SIGNAL(selectionChanged()),
- q, SLOT(update()));
+ QObject::connect(control, &QWidgetLineControl::selectionChanged,
+ q, qOverload<>(&QLineEdit::update));
- QObject::connect(control, SIGNAL(selectionChanged()),
- q, SLOT(updateMicroFocus()));
+ QObject::connect(control, &QWidgetLineControl::selectionChanged,
+ q, qUpdateMicroFocus);
- QObject::connect(control, SIGNAL(displayTextChanged(QString)),
- q, SLOT(update()));
+ QObject::connect(control, &QWidgetLineControl::displayTextChanged,
+ q, qOverload<>(&QLineEdit::update));
- QObject::connect(control, SIGNAL(updateNeeded(QRect)),
- q, SLOT(_q_updateNeeded(QRect)));
- QObject::connect(control, SIGNAL(inputRejected()), q, SIGNAL(inputRejected()));
+ QObjectPrivate::connect(control, &QWidgetLineControl::updateNeeded,
+ this, &QLineEditPrivate::updateNeeded);
+ QObject::connect(control, &QWidgetLineControl::inputRejected,
+ q, &QLineEdit::inputRejected);
QStyleOptionFrame opt;
q->initStyleOption(&opt);
@@ -409,7 +432,7 @@ void QLineEditIconButton::animateShow(bool visible)
void QLineEditIconButton::startOpacityAnimation(qreal endValue)
{
- QPropertyAnimation *animation = new QPropertyAnimation(this, QByteArrayLiteral("opacity"));
+ QPropertyAnimation *animation = new QPropertyAnimation(this, QByteArrayLiteral("opacity"), this);
connect(animation, &QPropertyAnimation::finished, this, &QLineEditIconButton::onAnimationFinished);
animation->setDuration(160);
@@ -436,7 +459,7 @@ static void displayWidgets(const QLineEditPrivate::SideWidgetEntryList &widgets,
}
#endif
-void QLineEditPrivate::_q_textChanged(const QString &text)
+void QLineEditPrivate::textChanged(const QString &text)
{
if (hasSideWidgets()) {
const int newTextSize = text.size();
@@ -451,16 +474,16 @@ void QLineEditPrivate::_q_textChanged(const QString &text)
}
}
-void QLineEditPrivate::_q_clearButtonClicked()
+void QLineEditPrivate::clearButtonClicked()
{
Q_Q(QLineEdit);
if (!q->text().isEmpty()) {
q->clear();
- _q_textEdited(QString());
+ textEdited(QString());
}
}
-void QLineEditPrivate::_q_controlEditingFinished()
+void QLineEditPrivate::controlEditingFinished()
{
Q_Q(QLineEdit);
edited = false;
@@ -554,7 +577,8 @@ QWidget *QLineEditPrivate::addAction(QAction *newAction, QAction *before, QLineE
if (!newAction)
return nullptr;
if (!hasSideWidgets()) { // initial setup.
- QObject::connect(q, SIGNAL(textChanged(QString)), q, SLOT(_q_textChanged(QString)));
+ QObjectPrivate::connect(q, &QLineEdit::textChanged,
+ this, &QLineEditPrivate::textChanged);
lastTextSize = q->text().size();
}
QWidget *w = nullptr;
@@ -570,7 +594,8 @@ QWidget *QLineEditPrivate::addAction(QAction *newAction, QAction *before, QLineE
toolButton->setIcon(newAction->icon());
toolButton->setOpacity(lastTextSize > 0 || !(flags & SideWidgetFadeInWithText) ? 1 : 0);
if (flags & SideWidgetClearButton) {
- QObject::connect(toolButton, SIGNAL(clicked()), q, SLOT(_q_clearButtonClicked()));
+ QObjectPrivate::connect(toolButton, &QToolButton::clicked,
+ this, &QLineEditPrivate::clearButtonClicked);
#if QT_CONFIG(animation)
// The clear button is handled only by this widget. The button should be really
@@ -633,7 +658,8 @@ void QLineEditPrivate::removeAction(QAction *action)
delete entry.widget;
positionSideWidgets();
if (!hasSideWidgets()) // Last widget, remove connection
- QObject::disconnect(q, SIGNAL(textChanged(QString)), q, SLOT(_q_textChanged(QString)));
+ QObjectPrivate::connect(q, &QLineEdit::textChanged,
+ this, &QLineEditPrivate::textChanged);
q->update();
}
#endif // QT_CONFIG(action)
@@ -646,7 +672,7 @@ static int effectiveTextMargin(int defaultMargin, const QLineEditPrivate::SideWi
const auto visibleSideWidgetCount = std::count_if(widgets.begin(), widgets.end(),
[](const QLineEditPrivate::SideWidgetEntry &e) {
-#if QT_CONFIG(animation)
+#if QT_CONFIG(toolbutton) && QT_CONFIG(animation)
// a button that's fading out doesn't get any space
if (auto* iconButton = qobject_cast<QLineEditIconButton*>(e.widget))
return iconButton->needsSpace();
diff --git a/src/widgets/widgets/qlineedit_p.h b/src/widgets/widgets/qlineedit_p.h
index 64350ae39a..3737ac8fe6 100644
--- a/src/widgets/widgets/qlineedit_p.h
+++ b/src/widgets/widgets/qlineedit_p.h
@@ -190,25 +190,27 @@ public:
QRect adjustedContentsRect() const;
- void _q_handleWindowActivate();
- void _q_textEdited(const QString &);
- void _q_cursorPositionChanged(int, int);
+ void handleWindowActivate();
+ void textEdited(const QString &);
+ void cursorPositionChanged(int, int);
#ifdef QT_KEYPAD_NAVIGATION
- void _q_editFocusChange(bool);
+ void editFocusChange(bool);
#endif
- void _q_selectionChanged();
- void _q_updateNeeded(const QRect &);
+ void selectionChanged();
+ void updateNeeded(const QRect &);
#if QT_CONFIG(completer)
- void _q_completionHighlighted(const QString &);
+ void connectCompleter();
+ void disconnectCompleter();
+ void completionHighlighted(const QString &);
#endif
QPoint mousePressPos;
#if QT_CONFIG(draganddrop)
QBasicTimer dndTimer;
void drag();
#endif
- void _q_textChanged(const QString &);
- void _q_clearButtonClicked();
- void _q_controlEditingFinished();
+ void textChanged(const QString &);
+ void clearButtonClicked();
+ void controlEditingFinished();
QMargins textMargins; // use effectiveTextMargins() in case of icon.
diff --git a/src/widgets/widgets/qmainwindow.cpp b/src/widgets/widgets/qmainwindow.cpp
index 256e97396b..4534058d45 100644
--- a/src/widgets/widgets/qmainwindow.cpp
+++ b/src/widgets/widgets/qmainwindow.cpp
@@ -25,6 +25,7 @@
#include <qstyle.h>
#include <qdebug.h>
#include <qpainter.h>
+#include <qmimedata.h>
#include <private/qwidget_p.h>
#if QT_CONFIG(toolbar)
@@ -36,6 +37,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
class QMainWindowPrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QMainWindow)
@@ -46,7 +49,7 @@ public:
, useUnifiedToolBar(false)
#endif
{ }
- QMainWindowLayout *layout;
+ QPointer<QMainWindowLayout> layout;
QSize iconSize;
bool explicitIconSize;
Qt::ToolButtonStyle toolButtonStyle;
@@ -57,7 +60,7 @@ public:
static inline QMainWindowLayout *mainWindowLayout(const QMainWindow *mainWindow)
{
- return mainWindow ? mainWindow->d_func()->layout : static_cast<QMainWindowLayout *>(nullptr);
+ return mainWindow ? mainWindow->d_func()->layout.data() : static_cast<QMainWindowLayout *>(nullptr);
}
};
@@ -121,6 +124,7 @@ void QMainWindowPrivate::init()
const int metric = q->style()->pixelMetric(QStyle::PM_ToolBarIconSize, nullptr, q);
iconSize = QSize(metric, metric);
q->setAttribute(Qt::WA_Hover);
+ q->setAcceptDrops(true);
}
/*
@@ -276,9 +280,7 @@ void QMainWindowPrivate::init()
is the position and size (relative to the size of the main window)
of the toolbars and dock widgets that are stored.
- \sa QMenuBar, QToolBar, QStatusBar, QDockWidget,
- {Qt Widgets - Application Example}, {Dock Widgets Example},
- {MDI Example}, {SDI Example}, {Menus Example}
+ \sa QMenuBar, QToolBar, QStatusBar, QDockWidget, {Menus Example}
*/
/*!
@@ -1121,21 +1123,8 @@ void QMainWindow::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
QList<QDockWidget*> QMainWindow::tabifiedDockWidgets(QDockWidget *dockwidget) const
{
- QList<QDockWidget*> ret;
- const QDockAreaLayoutInfo *info = d_func()->layout->layoutState.dockAreaLayout.info(dockwidget);
- if (info && info->tabbed && info->tabBar) {
- for(int i = 0; i < info->item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = info->item_list.at(i);
- if (item.widgetItem) {
- if (QDockWidget *dock = qobject_cast<QDockWidget*>(item.widgetItem->widget())) {
- if (dock != dockwidget) {
- ret += dock;
- }
- }
- }
- }
- }
- return ret;
+ Q_D(const QMainWindow);
+ return d->layout ? d->layout->tabifiedDockWidgets(dockwidget) : QList<QDockWidget *>();
}
#endif // QT_CONFIG(tabbar)
@@ -1296,6 +1285,28 @@ bool QMainWindow::event(QEvent *event)
if (!d->explicitIconSize)
setIconSize(QSize());
break;
+#if QT_CONFIG(draganddrop)
+ case QEvent::DragEnter:
+ case QEvent::Drop:
+ if (!d->layout->draggingWidget)
+ break;
+ event->accept();
+ return true;
+ case QEvent::DragMove: {
+ if (!d->layout->draggingWidget)
+ break;
+ auto dragMoveEvent = static_cast<QDragMoveEvent *>(event);
+ d->layout->hover(d->layout->draggingWidget,
+ mapToGlobal(dragMoveEvent->position()).toPoint());
+ event->accept();
+ return true;
+ }
+ case QEvent::DragLeave:
+ if (!d->layout->draggingWidget)
+ break;
+ d->layout->hover(d->layout->draggingWidget, pos() - QPoint(-1, -1));
+ return true;
+#endif
default:
break;
}
diff --git a/src/widgets/widgets/qmainwindow.h b/src/widgets/widgets/qmainwindow.h
index 90e37d7283..a050093417 100644
--- a/src/widgets/widgets/qmainwindow.h
+++ b/src/widgets/widgets/qmainwindow.h
@@ -178,6 +178,7 @@ protected:
private:
Q_DECLARE_PRIVATE(QMainWindow)
Q_DISABLE_COPY(QMainWindow)
+ friend class QDockWidgetGroupWindow;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QMainWindow::DockOptions)
diff --git a/src/widgets/widgets/qmainwindowlayout.cpp b/src/widgets/widgets/qmainwindowlayout.cpp
index 12d8876fcc..db17e50d5c 100644
--- a/src/widgets/widgets/qmainwindowlayout.cpp
+++ b/src/widgets/widgets/qmainwindowlayout.cpp
@@ -24,6 +24,10 @@
#endif
#include <qapplication.h>
+#if QT_CONFIG(draganddrop)
+#include <qdrag.h>
+#endif
+#include <qmimedata.h>
#if QT_CONFIG(statusbar)
#include <qstatusbar.h>
#endif
@@ -46,6 +50,8 @@
#include <private/qlayoutengine_p.h>
#include <private/qwidgetresizehandler_p.h>
+#include <QScopedValueRollback>
+
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
@@ -145,18 +151,57 @@ QDebug operator<<(QDebug debug, const QMainWindowLayout *layout)
return debug;
}
+// Use this to dump item lists of all populated main window docks.
+// Use DUMP macro inside QMainWindowLayout
+#if 0
+static void dumpItemLists(const QMainWindowLayout *layout, const char *function, const char *comment)
+{
+ for (int i = 0; i < QInternal::DockCount; ++i) {
+ const auto &list = layout->layoutState.dockAreaLayout.docks[i].item_list;
+ if (list.isEmpty())
+ continue;
+ qDebug() << function << comment << "Dock" << i << list;
+ }
+}
+#define DUMP(comment) dumpItemLists(this, __FUNCTION__, comment)
+#endif // 0
+
#endif // QT_CONFIG(dockwidget) && !defined(QT_NO_DEBUG)
-/******************************************************************************
- ** QDockWidgetGroupWindow
- */
-// QDockWidgetGroupWindow is the floating window containing several QDockWidgets floating together.
-// (QMainWindow::GroupedDragging feature)
-// QDockWidgetGroupLayout is the layout of that window and use a QDockAreaLayoutInfo to layout
-// the QDockWidgets inside it.
-// If there is only one QDockWidgets, or all QDockWidgets are tabbed together, it is equivalent
-// of a floating QDockWidget (the title of the QDockWidget is the title of the window). But if there
-// are nested QDockWidget, an additional title bar is there.
+
+/*!
+ \internal
+ QDockWidgetGroupWindow is a floating window, containing several QDockWidgets floating together.
+ This requires QMainWindow::GroupedDragging to be enabled.
+ QDockWidgets floating jointly in a QDockWidgetGroupWindow are considered to be docked.
+ Their \c isFloating property is \c false.
+ QDockWidget children of a QDockWidgetGroupWindow are either:
+ \list
+ \li tabbed (as long as Qt is compiled with the \c tabbar feature), or
+ \li arranged next to each other, equivalent to the default on a main window dock.
+ \endlist
+
+ QDockWidgetGroupWindow uses QDockWidgetGroupLayout to lay out its QDockWidget children.
+ It stores layout information in a QDockAreaLayoutInfo, including temporary spacer items
+ and rubber bands.
+
+ If its QDockWidget children are tabbed, the QDockWidgetGroupWindow shows the active QDockWidget's
+ title as its own window title.
+
+ QDockWidgetGroupWindow is designed to hold more than one QDockWidget.
+ A QDockWidgetGroupWindow with only one QDockWidget child may occur only temporarily
+ \list
+ \li in its construction phase, or
+ \li during a hover: While QDockWidget A is hovered over B, B is converted into a QDockWidgetGroupWindow.
+ \endlist
+
+ A QDockWidgetGroupWindow with only one QDockWidget child must never get focus, be dragged or dropped.
+ To enforce this restriction, QDockWidgetGrouWindow will remove itself after its second QDockWidget
+ child has been removed. It will make its last QDockWidget child a single, floating QDockWidget.
+ Eventually, the empty QDockWidgetGroupWindow will call deleteLater() on itself.
+*/
+
+
#if QT_CONFIG(dockwidget)
class QDockWidgetGroupLayout : public QLayout,
public QMainWindowLayoutSeparatorHelper<QDockWidgetGroupLayout>
@@ -293,6 +338,7 @@ bool QDockWidgetGroupWindow::event(QEvent *e)
case QEvent::Resize:
updateCurrentGapRect();
emit resized();
+ break;
default:
break;
}
@@ -397,8 +443,8 @@ void QDockWidgetGroupWindow::destroyOrHideIfEmpty()
}
// Make sure to reparent the possibly floating or hidden QDockWidgets to the parent
- const auto dockWidgets = findChildren<QDockWidget *>(Qt::FindDirectChildrenOnly);
- for (QDockWidget *dw : dockWidgets) {
+ const auto dockWidgetsList = dockWidgets();
+ for (QDockWidget *dw : dockWidgetsList) {
const bool wasFloating = dw->isFloating();
const bool wasHidden = dw->isHidden();
dw->setParent(parentWidget());
@@ -418,14 +464,28 @@ void QDockWidgetGroupWindow::destroyOrHideIfEmpty()
if (!wasHidden)
dw->show();
}
-#if QT_CONFIG(tabbar)
- const auto tabBars = findChildren<QTabBar *>(Qt::FindDirectChildrenOnly);
- for (QTabBar *tb : tabBars)
- tb->setParent(parentWidget());
-#endif
deleteLater();
}
+/*!
+ \internal
+ \return \c true if the group window has at least one visible QDockWidget child,
+ otherwise false.
+ */
+bool QDockWidgetGroupWindow::hasVisibleDockWidgets() const
+{
+ const auto &children = findChildren<QDockWidget *>(Qt::FindChildrenRecursively);
+ for (auto child : children) {
+ // WA_WState_Visible is set on the dock widget, associated to the active tab
+ // and unset on all others.
+ // WA_WState_Hidden is set if the dock widgets have been explicitly hidden.
+ // This is the relevant information to check (equivalent to !child->isHidden()).
+ if (!child->testAttribute(Qt::WA_WState_Hidden))
+ return true;
+ }
+ return false;
+}
+
/*! \internal
Sets the flags of this window in accordance to the capabilities of the dock widgets
*/
@@ -474,7 +534,7 @@ void QDockWidgetGroupWindow::adjustFlags()
m_removedFrameSize = QSize();
}
- show(); // setWindowFlags hides the window
+ setVisible(hasVisibleDockWidgets());
}
QWidget *titleBarOf = top ? top : parentWidget();
@@ -535,8 +595,12 @@ bool QDockWidgetGroupWindow::hover(QLayoutItem *widgetItem, const QPoint &mouseP
auto newGapPos = newState.gapIndex(mousePos, nestingEnabled, tabMode);
Q_ASSERT(!newGapPos.isEmpty());
- if (newGapPos == currentGapPos)
- return false; // gap is already there
+
+ // Do not insert a new gap item, if the current position already is a gap,
+ // or if the group window contains one
+ if (newGapPos == currentGapPos || newState.hasGapItem(newGapPos))
+ return false;
+
currentGapPos = newGapPos;
newState.insertGap(currentGapPos, widgetItem);
newState.fitItems();
@@ -583,6 +647,108 @@ void QDockWidgetGroupWindow::apply()
layoutInfo()->apply(false);
}
+void QDockWidgetGroupWindow::childEvent(QChildEvent *event)
+{
+ switch (event->type()) {
+ case QEvent::ChildRemoved:
+ if (auto *dockWidget = qobject_cast<QDockWidget *>(event->child()))
+ dockWidget->removeEventFilter(this);
+ destroyIfSingleItemLeft();
+ break;
+ case QEvent::ChildAdded:
+ if (auto *dockWidget = qobject_cast<QDockWidget *>(event->child()))
+ dockWidget->installEventFilter(this);
+ break;
+ default:
+ break;
+ }
+}
+
+bool QDockWidgetGroupWindow::eventFilter(QObject *obj, QEvent *event)
+{
+ auto *dockWidget = qobject_cast<QDockWidget *>(obj);
+ if (!dockWidget)
+ return QWidget::eventFilter(obj, event);
+
+ switch (event->type()) {
+ case QEvent::Close:
+ // We don't want closed dock widgets in a floating tab
+ // => dock it to the main dock, before closing;
+ reparent(dockWidget);
+ dockWidget->setFloating(false);
+ break;
+
+ case QEvent::Hide:
+ // if the dock widget is not an active tab, it is hidden anyway.
+ // if it is the active tab, hide the whole group.
+ if (dockWidget->isVisible())
+ hide();
+ break;
+
+ default:
+ break;
+ }
+ return QWidget::eventFilter(obj, event);
+}
+
+void QDockWidgetGroupWindow::destroyIfSingleItemLeft()
+{
+ const auto &dockWidgets = this->dockWidgets();
+
+ // Handle only the last dock
+ if (dockWidgets.count() != 1)
+ return;
+
+ auto *lastDockWidget = dockWidgets.at(0);
+
+ // If the last remaining dock widget is not in the group window's item_list,
+ // a group window is being docked on a main window docking area.
+ // => don't interfere
+ if (layoutInfo()->indexOf(lastDockWidget).isEmpty())
+ return;
+
+ auto *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
+ QMainWindowLayout *mwLayout = qt_mainwindow_layout(mainWindow);
+
+ // Unplug the last remaining dock widget and hide the group window, to avoid flickering
+ mwLayout->unplug(lastDockWidget, QDockWidgetPrivate::DragScope::Widget);
+ lastDockWidget->setGeometry(geometry());
+ hide();
+
+ // Get the layout info for the main window dock, where dock widgets need to go
+ QDockAreaLayoutInfo &parentInfo = mwLayout->layoutState.dockAreaLayout.docks[layoutInfo()->dockPos];
+
+ // Re-parent last dock widget
+ reparent(lastDockWidget);
+
+ // the group window could still have placeholder items => clear everything
+ layoutInfo()->item_list.clear();
+
+ // remove the group window and the dock's item_list pointing to it.
+ parentInfo.remove(this);
+ destroyOrHideIfEmpty();
+}
+
+void QDockWidgetGroupWindow::reparent(QDockWidget *dockWidget)
+{
+ // reparent a dockWidget to the main window
+ // - remove it from the floating dock's layout info
+ // - insert it to the main dock's layout info
+ // Finally, set draggingDock to nullptr, since the drag is finished.
+ auto *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
+ Q_ASSERT(mainWindow);
+ QMainWindowLayout *mwLayout = qt_mainwindow_layout(mainWindow);
+ Q_ASSERT(mwLayout);
+ QDockAreaLayoutInfo &parentInfo = mwLayout->layoutState.dockAreaLayout.docks[layoutInfo()->dockPos];
+ dockWidget->removeEventFilter(this);
+ parentInfo.add(dockWidget);
+ layoutInfo()->remove(dockWidget);
+ const bool wasFloating = dockWidget->isFloating();
+ const bool wasVisible = dockWidget->isVisible();
+ dockWidget->setParent(mainWindow);
+ dockWidget->setFloating(wasFloating);
+ dockWidget->setVisible(wasVisible);
+}
#endif
/******************************************************************************
@@ -1195,7 +1361,7 @@ bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
if (info == nullptr) {
continue;
}
- info->item_list.append(QDockAreaLayoutItem(new QDockWidgetItem(w)));
+ info->add(w);
}
}
}
@@ -1265,17 +1431,18 @@ bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
#if QT_CONFIG(toolbar)
-static inline void validateToolBarArea(Qt::ToolBarArea &area)
+static constexpr Qt::ToolBarArea validateToolBarArea(Qt::ToolBarArea area)
{
switch (area) {
case Qt::LeftToolBarArea:
case Qt::RightToolBarArea:
case Qt::TopToolBarArea:
case Qt::BottomToolBarArea:
- break;
+ return area;
default:
- area = Qt::TopToolBarArea;
+ break;
}
+ return Qt::TopToolBarArea;
}
static QInternal::DockPosition toDockPos(Qt::ToolBarArea area)
@@ -1311,7 +1478,7 @@ static inline Qt::ToolBarArea toToolBarArea(int pos)
void QMainWindowLayout::addToolBarBreak(Qt::ToolBarArea area)
{
- validateToolBarArea(area);
+ area = validateToolBarArea(area);
layoutState.toolBarAreaLayout.addToolBarBreak(toDockPos(area));
if (savedState.isValid())
@@ -1365,7 +1532,7 @@ void QMainWindowLayout::addToolBar(Qt::ToolBarArea area,
QToolBar *toolbar,
bool)
{
- validateToolBarArea(area);
+ area = validateToolBarArea(area);
// let's add the toolbar to the layout
addChildWidget(toolbar);
QLayoutItem *item = layoutState.toolBarAreaLayout.addToolBar(toDockPos(area), toolbar);
@@ -1467,7 +1634,6 @@ inline static Qt::DockWidgetArea toDockWidgetArea(int pos)
// Checks if QDockWidgetGroupWindow or QDockWidget can be plugged the area indicated by path.
// Returns false if called with invalid widget type or if compiled without dockwidget support.
-#if QT_CONFIG(dockwidget)
static bool isAreaAllowed(QWidget *widget, const QList<int> &path)
{
Q_ASSERT_X((path.size() > 1), "isAreaAllowed", "invalid path size");
@@ -1502,7 +1668,6 @@ static bool isAreaAllowed(QWidget *widget, const QList<int> &path)
qCDebug(lcQpaDockWidgets) << "Docking requested for invalid widget type (coding error)." << widget << area;
return false;
}
-#endif
void QMainWindowLayout::setCorner(Qt::Corner corner, Qt::DockWidgetArea area)
{
@@ -1522,7 +1687,6 @@ Qt::DockWidgetArea QMainWindowLayout::corner(Qt::Corner corner) const
// Returns the rectangle of a dockWidgetArea
// if max is true, the maximum possible rectangle for dropping is returned
// the current visible rectangle otherwise
-#if QT_CONFIG(dockwidget)
QRect QMainWindowLayout::dockWidgetAreaRect(const Qt::DockWidgetArea area, DockWidgetAreaSize size) const
{
const QInternal::DockPosition dockPosition = toDockPos(area);
@@ -1538,7 +1702,6 @@ QRect QMainWindowLayout::dockWidgetAreaRect(const Qt::DockWidgetArea area, DockW
// Return maximum or visible rectangle
return (size == Maximum) ? dl.gapRect(dockPosition) : dl.docks[dockPosition].rect;
}
-#endif
void QMainWindowLayout::addDockWidget(Qt::DockWidgetArea area,
QDockWidget *dockwidget,
@@ -1569,6 +1732,7 @@ bool QMainWindowLayout::restoreDockWidget(QDockWidget *dockwidget)
#if QT_CONFIG(tabbar)
void QMainWindowLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
{
+ applyRestoredState();
addChildWidget(second);
layoutState.dockAreaLayout.tabifyDockWidget(first, second);
emit second->dockLocationChanged(dockWidgetArea(first));
@@ -1651,19 +1815,7 @@ void QMainWindowLayout::setTabPosition(Qt::DockWidgetAreas areas, QTabWidget::Ta
updateTabBarShapes();
}
-static inline QTabBar::Shape tabBarShapeFrom(QTabWidget::TabShape shape, QTabWidget::TabPosition position)
-{
- const bool rounded = (shape == QTabWidget::Rounded);
- if (position == QTabWidget::North)
- return rounded ? QTabBar::RoundedNorth : QTabBar::TriangularNorth;
- if (position == QTabWidget::South)
- return rounded ? QTabBar::RoundedSouth : QTabBar::TriangularSouth;
- if (position == QTabWidget::East)
- return rounded ? QTabBar::RoundedEast : QTabBar::TriangularEast;
- if (position == QTabWidget::West)
- return rounded ? QTabBar::RoundedWest : QTabBar::TriangularWest;
- return QTabBar::RoundedNorth;
-}
+QTabBar::Shape _q_tb_tabBarShapeFrom(QTabWidget::TabShape shape, QTabWidget::TabPosition position);
#endif // QT_CONFIG(tabwidget)
void QMainWindowLayout::updateTabBarShapes()
@@ -1689,7 +1841,7 @@ void QMainWindowLayout::updateTabBarShapes()
for (int i = 0; i < QInternal::DockCount; ++i) {
#if QT_CONFIG(tabwidget)
QTabWidget::TabPosition pos = verticalTabsEnabled ? vertical[i] : tabPositions[i];
- QTabBar::Shape shape = tabBarShapeFrom(_tabShape, pos);
+ QTabBar::Shape shape = _q_tb_tabBarShapeFrom(_tabShape, pos);
#else
QTabBar::Shape shape = verticalTabsEnabled ? vertical[i] : QTabBar::RoundedSouth;
#endif
@@ -1702,6 +1854,7 @@ void QMainWindowLayout::splitDockWidget(QDockWidget *after,
QDockWidget *dockwidget,
Qt::Orientation orientation)
{
+ applyRestoredState();
addChildWidget(dockwidget);
layoutState.dockAreaLayout.splitDockWidget(after, dockwidget, orientation);
emit dockwidget->dockLocationChanged(dockWidgetArea(after));
@@ -1726,10 +1879,15 @@ void QMainWindowLayout::keepSize(QDockWidget *w)
// Handle custom tooltip, and allow to drag tabs away.
class QMainWindowTabBar : public QTabBar
{
+ Q_OBJECT
QMainWindow *mainWindow;
QPointer<QDockWidget> draggingDock; // Currently dragging (detached) dock widget
public:
QMainWindowTabBar(QMainWindow *parent);
+ ~QMainWindowTabBar();
+ QDockWidget *dockAt(int index) const;
+ QList<QDockWidget *> dockWidgets() const;
+ bool contains(const QDockWidget *dockWidget) const;
protected:
bool event(QEvent *e) override;
void mouseReleaseEvent(QMouseEvent*) override;
@@ -1737,12 +1895,55 @@ protected:
};
+QMainWindowTabBar *QMainWindowLayout::findTabBar(const QDockWidget *dockWidget) const
+{
+ for (auto *bar : usedTabBars) {
+ Q_ASSERT(qobject_cast<QMainWindowTabBar *>(bar));
+ auto *tabBar = static_cast<QMainWindowTabBar *>(bar);
+ if (tabBar->contains(dockWidget))
+ return tabBar;
+ }
+ return nullptr;
+}
+
QMainWindowTabBar::QMainWindowTabBar(QMainWindow *parent)
: QTabBar(parent), mainWindow(parent)
{
setExpanding(false);
}
+QList<QDockWidget *> QMainWindowTabBar::dockWidgets() const
+{
+ QList<QDockWidget *> docks;
+ for (int i = 0; i < count(); ++i) {
+ if (QDockWidget *dock = dockAt(i))
+ docks << dock;
+ }
+ return docks;
+}
+
+bool QMainWindowTabBar::contains(const QDockWidget *dockWidget) const
+{
+ for (int i = 0; i < count(); ++i) {
+ if (dockAt(i) == dockWidget)
+ return true;
+ }
+ return false;
+}
+
+QDockWidget *QMainWindowTabBar::dockAt(int index) const
+{
+ QMainWindowTabBar *that = const_cast<QMainWindowTabBar *>(this);
+ QMainWindowLayout* mlayout = qt_mainwindow_layout(mainWindow);
+ QDockAreaLayoutInfo *info = mlayout->dockInfo(that);
+ if (!info)
+ return nullptr;
+ const int itemIndex = info->tabIndexToListIndex(index);
+ Q_ASSERT(itemIndex >= 0 && itemIndex < info->item_list.count());
+ const QDockAreaLayoutItem &item = info->item_list.at(itemIndex);
+ return item.widgetItem ? qobject_cast<QDockWidget *>(item.widgetItem->widget()) : nullptr;
+}
+
void QMainWindowTabBar::mouseMoveEvent(QMouseEvent *e)
{
// The QTabBar handles the moving (reordering) of tabs.
@@ -1756,13 +1957,8 @@ void QMainWindowTabBar::mouseMoveEvent(QMouseEvent *e)
offset *= 3;
QRect r = rect().adjusted(-offset, -offset, offset, offset);
if (d->dragInProgress && !r.contains(e->position().toPoint()) && d->validIndex(d->pressedIndex)) {
- QMainWindowLayout* mlayout = qt_mainwindow_layout(mainWindow);
- QDockAreaLayoutInfo *info = mlayout->dockInfo(this);
- Q_ASSERT(info);
- int idx = info->tabIndexToListIndex(d->pressedIndex);
- const QDockAreaLayoutItem &item = info->item_list.at(idx);
- if (item.widgetItem
- && (draggingDock = qobject_cast<QDockWidget *>(item.widgetItem->widget()))) {
+ draggingDock = dockAt(d->pressedIndex);
+ if (draggingDock) {
// We should drag this QDockWidget away by unpluging it.
// First cancel the QTabBar's internal move
d->moveTabFinished(d->pressedIndex);
@@ -1775,7 +1971,7 @@ void QMainWindowTabBar::mouseMoveEvent(QMouseEvent *e)
QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
QDockWidgetLayout *dwlayout = static_cast<QDockWidgetLayout *>(draggingDock->layout());
dockPriv->initDrag(dwlayout->titleArea().center(), true);
- dockPriv->startDrag(false);
+ dockPriv->startDrag(QDockWidgetPrivate::DragScope::Widget);
if (dockPriv->state)
dockPriv->state->ctrlDrag = e->modifiers() & Qt::ControlModifier;
}
@@ -1793,13 +1989,28 @@ void QMainWindowTabBar::mouseMoveEvent(QMouseEvent *e)
QTabBar::mouseMoveEvent(e);
}
+QMainWindowTabBar::~QMainWindowTabBar()
+{
+ if (!mainWindow || mainWindow == parentWidget())
+ return;
+
+ // tab bar is not parented to the main window
+ // => can only be a dock widget group window
+ // => remove itself from used and unused tab bar containers
+ auto *mwLayout = qt_mainwindow_layout(mainWindow);
+ if (!mwLayout)
+ return;
+ mwLayout->unusedTabBars.removeOne(this);
+ mwLayout->usedTabBars.remove(this);
+}
+
void QMainWindowTabBar::mouseReleaseEvent(QMouseEvent *e)
{
if (draggingDock && e->button() == Qt::LeftButton) {
QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
- if (dockPriv->state && dockPriv->state->dragging) {
- dockPriv->endDrag();
- }
+ if (dockPriv->state && dockPriv->state->dragging)
+ dockPriv->endDrag(QDockWidgetPrivate::EndDragMode::LocationChange);
+
draggingDock = nullptr;
}
QTabBar::mouseReleaseEvent(e);
@@ -1823,9 +2034,31 @@ bool QMainWindowTabBar::event(QEvent *e)
return true;
}
+QList<QDockWidget *> QMainWindowLayout::tabifiedDockWidgets(const QDockWidget *dockWidget) const
+{
+ const auto *bar = findTabBar(dockWidget);
+ if (!bar)
+ return {};
+
+ QList<QDockWidget *> buddies = bar->dockWidgets();
+ // Return only other dock widgets associated with dockWidget in a tab bar.
+ // If dockWidget is alone in a tab bar, return an empty list.
+ buddies.removeOne(dockWidget);
+ return buddies;
+}
+
+bool QMainWindowLayout::isDockWidgetTabbed(const QDockWidget *dockWidget) const
+{
+ // A single dock widget in a tab bar is not considered to be tabbed.
+ // This is to make sure, we don't drag an empty QDockWidgetGroupWindow around.
+ // => only consider tab bars with two or more tabs.
+ const auto *bar = findTabBar(dockWidget);
+ return bar && bar->count() > 1;
+}
+
QTabBar *QMainWindowLayout::getTabBar()
{
- if (!usedTabBars.isEmpty()) {
+ if (!usedTabBars.isEmpty() && !isInRestoreState) {
/*
If dock widgets have been removed and added while the main window was
hidden, then the layout hasn't been activated yet, and tab bars from empty
@@ -1997,9 +2230,37 @@ QLayoutItem *QMainWindowLayout::takeAt(int index)
return nullptr;
}
+
+/*!
+ \internal
+
+ restoredState stores what we earlier read from storage, but it couldn't
+ be applied as the mainwindow wasn't large enough (yet) to fit the state.
+ Usually, the restored state would be applied lazily in setGeometry below.
+ However, if the mainwindow's layout is modified (e.g. by a call to tabify or
+ splitDockWidgets), then we have to forget the restored state as it might contain
+ dangling pointers (QDockWidgetLayoutItem has a copy constructor that copies the
+ layout item pointer, and splitting or tabify might have to delete some of those
+ layout structures).
+
+ Functions that might result in the QMainWindowLayoutState storing dangling pointers
+ have to call this function first, so that the restoredState becomes the actual state
+ first, and is forgotten afterwards.
+*/
+void QMainWindowLayout::applyRestoredState()
+{
+ if (restoredState) {
+ layoutState = *restoredState;
+ restoredState.reset();
+ discardRestoredStateTimer.stop();
+ }
+}
+
void QMainWindowLayout::setGeometry(const QRect &_r)
{
- if (savedState.isValid())
+ // Check if the state is valid, and avoid replacing it again if it is currently used
+ // in applyState
+ if (savedState.isValid() || (restoredState && isInApplyState))
return;
QRect r = _r;
@@ -2535,25 +2796,25 @@ static QTabBar::Shape tabwidgetPositionToTabBarShape(QWidget *w)
Returns the QLayoutItem of the dragged element.
The layout item is kept in the layout but set as a gap item.
*/
-QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
+QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, QDockWidgetPrivate::DragScope scope)
{
#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
auto *groupWindow = qobject_cast<const QDockWidgetGroupWindow *>(widget->parentWidget());
if (!widget->isWindow() && groupWindow) {
- if (group && groupWindow->tabLayoutInfo()) {
+ if (scope == QDockWidgetPrivate::DragScope::Group && groupWindow->tabLayoutInfo()) {
// We are just dragging a floating window as it, not need to do anything, we just have to
// look up the corresponding QWidgetItem* if it exists
if (QDockAreaLayoutInfo *info = dockInfo(widget->parentWidget())) {
QList<int> groupWindowPath = info->indexOf(widget->parentWidget());
return groupWindowPath.isEmpty() ? nullptr : info->item(groupWindowPath).widgetItem;
}
- qCDebug(lcQpaDockWidgets) << "Drag only:" << widget << "Group:" << group;
+ qCDebug(lcQpaDockWidgets) << "Drag only:" << widget << "Group:" << (scope == QDockWidgetPrivate::DragScope::Group);
return nullptr;
}
QList<int> path = groupWindow->layoutInfo()->indexOf(widget);
QDockAreaLayoutItem parentItem = groupWindow->layoutInfo()->item(path);
QLayoutItem *item = parentItem.widgetItem;
- if (group && path.size() > 1
+ if (scope == QDockWidgetPrivate::DragScope::Group && path.size() > 1
&& unplugGroup(this, &item, parentItem)) {
qCDebug(lcQpaDockWidgets) << "Unplugging:" << widget << "from" << item;
return item;
@@ -2561,73 +2822,10 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
// We are unplugging a single dock widget from a floating window.
QDockWidget *dockWidget = qobject_cast<QDockWidget *>(widget);
Q_ASSERT(dockWidget); // cannot be a QDockWidgetGroupWindow because it's not floating.
-
- // unplug the widget first
dockWidget->d_func()->unplug(widget->geometry());
- // Create a floating tab, copy properties and generate layout info
- QDockWidgetGroupWindow *floatingTabs = createTabbedDockWindow();
- const QInternal::DockPosition dockPos = groupWindow->layoutInfo()->dockPos;
- QDockAreaLayoutInfo *info = floatingTabs->layoutInfo();
-
- const QTabBar::Shape shape = tabwidgetPositionToTabBarShape(dockWidget);
-
- // Populate newly created DockAreaLayoutInfo of floating tabs
- *info = QDockAreaLayoutInfo(&layoutState.dockAreaLayout.sep, dockPos,
- Qt::Horizontal, shape,
- layoutState.mainWindow);
-
- // Create tab and hide it as group window contains only one widget
- info->tabbed = true;
- info->tabBar = getTabBar();
- info->tabBar->hide();
- updateGapIndicator();
-
- // Reparent it to a QDockWidgetGroupLayout
- floatingTabs->setGeometry(dockWidget->geometry());
-
- // Append reference to floatingTabs to the dock's item_list
- parentItem.widgetItem = new QDockWidgetGroupWindowItem(floatingTabs);
- layoutState.dockAreaLayout.docks[dockPos].item_list.append(parentItem);
-
- // use populated parentItem to set reference to dockWidget as the first item in own list
- parentItem.widgetItem = new QDockWidgetItem(dockWidget);
- info->item_list = {parentItem};
-
- // Add non-gap items of the dock to the tab bar
- for (const auto &listItem : layoutState.dockAreaLayout.docks[dockPos].item_list) {
- if (listItem.GapItem || !listItem.widgetItem)
- continue;
- info->tabBar->addTab(listItem.widgetItem->widget()->objectName());
- }
-
- // Re-parent and fit
- floatingTabs->setParent(layoutState.mainWindow);
- floatingTabs->layoutInfo()->fitItems();
- floatingTabs->layoutInfo()->apply(dockOptions & QMainWindow::AnimatedDocks);
- groupWindow->layoutInfo()->fitItems();
- groupWindow->layoutInfo()->apply(dockOptions & QMainWindow::AnimatedDocks);
- dockWidget->d_func()->tabPosition = layoutState.mainWindow->tabPosition(toDockWidgetArea(dockPos));
- info->reparentWidgets(floatingTabs);
- dockWidget->setParent(floatingTabs);
- info->updateTabBar();
-
- // Show the new item
- const QList<int> path = layoutState.indexOf(floatingTabs);
- QRect r = layoutState.itemRect(path);
- savedState = layoutState;
- savedState.fitLayout();
-
- // Update gap, fix orientation, raise and show
- currentGapPos = path;
- currentGapRect = r;
- updateGapIndicator();
- fixToolBarOrientation(parentItem.widgetItem, currentGapPos.at(1));
- floatingTabs->show();
- floatingTabs->raise();
-
qCDebug(lcQpaDockWidgets) << "Unplugged from floating dock:" << widget << "from" << parentItem.widgetItem;
- return parentItem.widgetItem;
+ return item;
}
}
#endif
@@ -2646,7 +2844,7 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
Q_ASSERT(path.constFirst() == 1);
#if QT_CONFIG(tabwidget)
- if (group && (dockOptions & QMainWindow::GroupedDragging) && path.size() > 3
+ if (scope == QDockWidgetPrivate::DragScope::Group && (dockOptions & QMainWindow::GroupedDragging) && path.size() > 3
&& unplugGroup(this, &item,
layoutState.dockAreaLayout.item(path.mid(1, path.size() - 2)))) {
path.removeLast();
@@ -2654,21 +2852,36 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
} else
#endif // QT_CONFIG(tabwidget)
{
- // Dock widget is unplugged from the main window
- // => geometry needs to be adjusted by separator size
+ // Dock widget is unplugged from a main window dock
+ // => height or width need to be decreased by separator size
switch (dockWidgetArea(dw)) {
case Qt::LeftDockWidgetArea:
case Qt::RightDockWidgetArea:
- r.adjust(0, 0, 0, -sep);
+ r.setHeight(r.height() - sep);
break;
case Qt::TopDockWidgetArea:
case Qt::BottomDockWidgetArea:
- r.adjust(0, 0, -sep, 0);
+ r.setWidth(r.width() - sep);
break;
case Qt::NoDockWidgetArea:
case Qt::DockWidgetArea_Mask:
break;
}
+
+ // Depending on the title bar layout (vertical / horizontal),
+ // width and height have to provide minimum space for window handles
+ // and mouse dragging.
+ // Assuming horizontal title bar, if the dock widget does not have a layout.
+ const auto *layout = qobject_cast<QDockWidgetLayout *>(dw->layout());
+ const bool verticalTitleBar = layout ? layout->verticalTitleBar : false;
+ const int tbHeight = QApplication::style()
+ ? QApplication::style()->pixelMetric(QStyle::PixelMetric::PM_TitleBarHeight, nullptr, dw)
+ : 20;
+ const int minHeight = verticalTitleBar ? 2 * tbHeight : tbHeight;
+ const int minWidth = verticalTitleBar ? tbHeight : 2 * tbHeight;
+ r.setSize(r.size().expandedTo(QSize(minWidth, minHeight)));
+ qCDebug(lcQpaDockWidgets) << dw << "will be unplugged with size" << r.size();
+
dw->d_func()->unplug(r);
}
}
@@ -2680,7 +2893,7 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
#endif
#if !QT_CONFIG(dockwidget) || !QT_CONFIG(tabbar)
- Q_UNUSED(group);
+ Q_UNUSED(scope);
#endif
layoutState.unplug(path ,&savedState);
@@ -2748,6 +2961,7 @@ void QMainWindowLayout::hover(QLayoutItem *hoverTarget,
QWidget *widget = hoverTarget->widget();
#if QT_CONFIG(dockwidget)
+ widget->raise();
if ((dockOptions & QMainWindow::GroupedDragging) && (qobject_cast<QDockWidget*>(widget)
|| qobject_cast<QDockWidgetGroupWindow *>(widget))) {
@@ -2764,7 +2978,7 @@ void QMainWindowLayout::hover(QLayoutItem *hoverTarget,
continue;
// Check permission to dock on another dock widget or floating dock
- // FIXME in 6.4
+ // FIXME in Qt 7
if (w != widget && w->isWindow() && w->isVisible() && !w->isMinimized())
candidates << w;
@@ -2802,16 +3016,26 @@ void QMainWindowLayout::hover(QLayoutItem *hoverTarget,
floatingTabs->setGeometry(dropTo->geometry());
QDockAreaLayoutInfo *info = floatingTabs->layoutInfo();
const QTabBar::Shape shape = tabwidgetPositionToTabBarShape(dropTo);
- const QInternal::DockPosition dockPosition = toDockPos(dockWidgetArea(dropTo));
+
+ // dropTo and widget may be in a state where they transition
+ // from being a group window child to a single floating dock widget.
+ // In that case, their path to a main window dock may not have been
+ // updated yet.
+ // => ask both and fall back to dock 1 (right dock)
+ QInternal::DockPosition dockPosition = toDockPos(dockWidgetArea(dropTo));
+ if (dockPosition == QInternal::DockPosition::DockCount)
+ dockPosition = toDockPos(dockWidgetArea(widget));
+ if (dockPosition == QInternal::DockPosition::DockCount)
+ dockPosition = QInternal::DockPosition::RightDock;
+
*info = QDockAreaLayoutInfo(&layoutState.dockAreaLayout.sep, dockPosition,
Qt::Horizontal, shape,
static_cast<QMainWindow *>(parentWidget()));
info->tabBar = getTabBar();
info->tabbed = true;
- QLayout *parentLayout = dropTo->parentWidget()->layout();
- info->item_list.append(
- QDockAreaLayoutItem(parentLayout->takeAt(parentLayout->indexOf(dropTo))));
-
+ info->add(dropTo);
+ QDockAreaLayoutInfo &parentInfo = layoutState.dockAreaLayout.docks[dockPosition];
+ parentInfo.add(floatingTabs);
dropTo->setParent(floatingTabs);
qCDebug(lcQpaDockWidgets) << "Wrapping" << widget << "into floating tabs" << floatingTabs;
w = floatingTabs;
@@ -2824,15 +3048,21 @@ void QMainWindowLayout::hover(QLayoutItem *hoverTarget,
qCDebug(lcQpaDockWidgets) << "Raising" << widget;
}
#endif
- auto group = qobject_cast<QDockWidgetGroupWindow *>(w);
- Q_ASSERT(group);
- if (group->hover(hoverTarget, group->mapFromGlobal(mousePos))) {
- setCurrentHoveredFloat(group);
+ auto *groupWindow = qobject_cast<QDockWidgetGroupWindow *>(w);
+ Q_ASSERT(groupWindow);
+ if (groupWindow->hover(hoverTarget, groupWindow->mapFromGlobal(mousePos))) {
+ setCurrentHoveredFloat(groupWindow);
applyState(layoutState); // update the tabbars
}
return;
}
}
+
+ // If a temporary group window has been created during a hover,
+ // remove it, if it has only one dockwidget child
+ if (currentHoveredFloat)
+ currentHoveredFloat->destroyIfSingleItemLeft();
+
setCurrentHoveredFloat(nullptr);
layoutState.dockAreaLayout.fallbackToSizeHints = false;
#endif // QT_CONFIG(dockwidget)
@@ -2957,6 +3187,7 @@ void QMainWindowLayout::saveState(QDataStream &stream) const
bool QMainWindowLayout::restoreState(QDataStream &stream)
{
+ QScopedValueRollback<bool> guard(isInRestoreState, true);
savedState = layoutState;
layoutState.clear();
layoutState.rect = savedState.rect;
@@ -3002,6 +3233,42 @@ bool QMainWindowLayout::restoreState(QDataStream &stream)
return true;
}
+#if QT_CONFIG(draganddrop)
+bool QMainWindowLayout::needsPlatformDrag()
+{
+ static const bool wayland =
+ QGuiApplication::platformName().startsWith("wayland"_L1, Qt::CaseInsensitive);
+ return wayland;
+}
+
+Qt::DropAction QMainWindowLayout::performPlatformWidgetDrag(QLayoutItem *widgetItem,
+ const QPoint &pressPosition)
+{
+ draggingWidget = widgetItem;
+ QWidget *widget = widgetItem->widget();
+ auto drag = QDrag(widget);
+ auto mimeData = new QMimeData();
+ auto window = widgetItem->widget()->windowHandle();
+
+ auto serialize = [](const auto &object) {
+ QByteArray data;
+ QDataStream dataStream(&data, QIODevice::WriteOnly);
+ dataStream << object;
+ return data;
+ };
+ mimeData->setData("application/x-qt-mainwindowdrag-window"_L1,
+ serialize(reinterpret_cast<qintptr>(window)));
+ mimeData->setData("application/x-qt-mainwindowdrag-position"_L1, serialize(pressPosition));
+ drag.setMimeData(mimeData);
+
+ auto result = drag.exec();
+
+ draggingWidget = nullptr;
+ return result;
+}
+#endif
+
QT_END_NAMESPACE
+#include "qmainwindowlayout.moc"
#include "moc_qmainwindowlayout_p.cpp"
diff --git a/src/widgets/widgets/qmainwindowlayout_p.h b/src/widgets/widgets/qmainwindowlayout_p.h
index 394a052a09..55a27e4849 100644
--- a/src/widgets/widgets/qmainwindowlayout_p.h
+++ b/src/widgets/widgets/qmainwindowlayout_p.h
@@ -1,8 +1,8 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
-#ifndef QDYNAMICMAINWINDOWLAYOUT_P_H
-#define QDYNAMICMAINWINDOWLAYOUT_P_H
+#ifndef QMAINWINDOWLAYOUT_P_H
+#define QMAINWINDOWLAYOUT_P_H
//
// W A R N I N G
@@ -29,15 +29,24 @@
#include "QtCore/qset.h"
#include "private/qlayoutengine_p.h"
#include "private/qwidgetanimator_p.h"
-
#if QT_CONFIG(dockwidget)
+#include "private/qdockwidget_p.h"
+
#include "qdockarealayout_p.h"
#include "qdockwidget.h"
+#else
+struct QDockWidgetPrivate {
+ enum class DragScope {
+ Group
+ };
+};
#endif
#if QT_CONFIG(toolbar)
#include "qtoolbararealayout_p.h"
#endif
+
#include <QtCore/qloggingcategory.h>
+#include <QtCore/qpointer.h>
QT_REQUIRE_CONFIG(mainwindow);
@@ -306,14 +315,17 @@ class Q_AUTOTEST_EXPORT QDockWidgetGroupWindow : public QWidget
{
Q_OBJECT
public:
- explicit QDockWidgetGroupWindow(QWidget* parent = nullptr, Qt::WindowFlags f = { })
- : QWidget(parent, f) {}
+ explicit QDockWidgetGroupWindow(QWidget *parent = nullptr, Qt::WindowFlags f = {})
+ : QWidget(parent, f)
+ {
+ }
QDockAreaLayoutInfo *layoutInfo() const;
#if QT_CONFIG(tabbar)
const QDockAreaLayoutInfo *tabLayoutInfo() const;
QDockWidget *activeTabbedDockWidget() const;
#endif
void destroyOrHideIfEmpty();
+ bool hasVisibleDockWidgets() const;
void adjustFlags();
bool hasNativeDecos() const;
@@ -321,6 +333,10 @@ public:
void updateCurrentGapRect();
void restore();
void apply();
+ void childEvent(QChildEvent *event) override;
+ void reparent(QDockWidget *dockWidget);
+ void destroyIfSingleItemLeft();
+ QList<QDockWidget *> dockWidgets() const { return findChildren<QDockWidget *>(); }
QRect currentGapRect;
QList<int> currentGapPos;
@@ -330,6 +346,7 @@ signals:
protected:
bool event(QEvent *) override;
+ bool eventFilter(QObject *obj, QEvent *event) override;
void paintEvent(QPaintEvent*) override;
private:
@@ -433,6 +450,7 @@ public:
bool restoreState(QDataStream &stream, const QMainWindowLayoutState &oldState);
};
+class QMainWindowTabBar;
class Q_AUTOTEST_EXPORT QMainWindowLayout
: public QLayout,
public QMainWindowLayoutSeparatorHelper<QMainWindowLayout>
@@ -560,17 +578,29 @@ public:
#if QT_CONFIG(dockwidget)
QPointer<QDockWidgetGroupWindow> currentHoveredFloat; // set when dragging over a floating dock widget
void setCurrentHoveredFloat(QDockWidgetGroupWindow *w);
+#if QT_CONFIG(tabbar)
+ bool isDockWidgetTabbed(const QDockWidget *dockWidget) const;
+ QList<QDockWidget *> tabifiedDockWidgets(const QDockWidget *dockWidget) const;
+ QMainWindowTabBar *findTabBar(const QDockWidget *dockWidget) const;
+#endif
#endif
bool isInApplyState = false;
void hover(QLayoutItem *hoverTarget, const QPoint &mousePos);
bool plug(QLayoutItem *widgetItem);
- QLayoutItem *unplug(QWidget *widget, bool group = false);
+ QLayoutItem *unplug(QWidget *widget, QDockWidgetPrivate::DragScope scope);
void revert(QLayoutItem *widgetItem);
void applyState(QMainWindowLayoutState &newState, bool animate = true);
+ void applyRestoredState();
void restore(bool keepSavedState = false);
void animationFinished(QWidget *widget);
+#if QT_CONFIG(draganddrop)
+ static bool needsPlatformDrag();
+ Qt::DropAction performPlatformWidgetDrag(QLayoutItem *widgetItem, const QPoint &pressPosition);
+ QLayoutItem *draggingWidget = nullptr;
+#endif
+
protected:
void timerEvent(QTimerEvent *e) override;
@@ -586,6 +616,7 @@ private:
#if QT_CONFIG(tabbar)
void updateTabBarShapes();
#endif
+ bool isInRestoreState = false;
};
#if QT_CONFIG(dockwidget) && !defined(QT_NO_DEBUG_STREAM)
@@ -596,4 +627,4 @@ QDebug operator<<(QDebug debug, const QMainWindowLayout *layout);
QT_END_NAMESPACE
-#endif // QDYNAMICMAINWINDOWLAYOUT_P_H
+#endif // QMAINWINDOWLAYOUT_P_H
diff --git a/src/widgets/widgets/qmdiarea.cpp b/src/widgets/widgets/qmdiarea.cpp
index 8708e343fd..79b83453ac 100644
--- a/src/widgets/widgets/qmdiarea.cpp
+++ b/src/widgets/widgets/qmdiarea.cpp
@@ -220,19 +220,7 @@ static inline QMdiArea *mdiAreaParent(QWidget *widget)
}
#if QT_CONFIG(tabwidget)
-static inline QTabBar::Shape tabBarShapeFrom(QTabWidget::TabShape shape, QTabWidget::TabPosition position)
-{
- const bool rounded = (shape == QTabWidget::Rounded);
- if (position == QTabWidget::North)
- return rounded ? QTabBar::RoundedNorth : QTabBar::TriangularNorth;
- if (position == QTabWidget::South)
- return rounded ? QTabBar::RoundedSouth : QTabBar::TriangularSouth;
- if (position == QTabWidget::East)
- return rounded ? QTabBar::RoundedEast : QTabBar::TriangularEast;
- if (position == QTabWidget::West)
- return rounded ? QTabBar::RoundedWest : QTabBar::TriangularWest;
- return QTabBar::RoundedNorth;
-}
+QTabBar::Shape _q_tb_tabBarShapeFrom(QTabWidget::TabShape shape, QTabWidget::TabPosition position);
#endif // QT_CONFIG(tabwidget)
static inline QString tabTextFor(QMdiSubWindow *subWindow)
@@ -683,7 +671,11 @@ void QMdiAreaPrivate::_q_deactivateAllWindows(QMdiSubWindow *aboutToActivate)
aboutToBecomeActive = aboutToActivate;
Q_ASSERT(aboutToBecomeActive);
- foreach (QMdiSubWindow *child, childWindows) {
+ // Take a copy because child->showNormal() could indirectly call
+ // QCoreApplication::sendEvent(), which could call unknown code that e.g.
+ // recurses into the class modifying childWindows.
+ const auto subWindows = childWindows;
+ for (QMdiSubWindow *child : subWindows) {
if (!sanityCheck(child, "QMdiArea::deactivateAllWindows") || aboutToBecomeActive == child)
continue;
// We don't want to handle signals caused by child->showNormal().
@@ -858,7 +850,7 @@ void QMdiAreaPrivate::place(Placer *placer, QMdiSubWindow *child)
QList<QRect> rects;
rects.reserve(childWindows.size());
QRect parentRect = q->rect();
- foreach (QMdiSubWindow *window, childWindows) {
+ for (QMdiSubWindow *window : std::as_const(childWindows)) {
if (!sanityCheck(window, "QMdiArea::place") || window == child || !window->isVisibleTo(q)
|| !window->testAttribute(Qt::WA_Moved)) {
continue;
@@ -900,7 +892,7 @@ void QMdiAreaPrivate::rearrange(Rearranger *rearranger)
const bool reverseList = rearranger->type() == Rearranger::RegularTiler;
const QList<QMdiSubWindow *> subWindows = subWindowList(activationOrder, reverseList);
QSize minSubWindowSize;
- foreach (QMdiSubWindow *child, subWindows) {
+ for (QMdiSubWindow *child : subWindows) {
if (!sanityCheck(child, "QMdiArea::rearrange") || !child->isVisible())
continue;
if (rearranger->type() == Rearranger::IconTiler) {
@@ -1314,7 +1306,7 @@ bool QMdiAreaPrivate::lastWindowAboutToBeDestroyed() const
*/
void QMdiAreaPrivate::setChildActivationEnabled(bool enable, bool onlyNextActivationEvent) const
{
- foreach (QMdiSubWindow *subWindow, childWindows) {
+ for (QMdiSubWindow *subWindow : childWindows) {
if (!subWindow || !subWindow->isVisible())
continue;
if (onlyNextActivationEvent)
@@ -1336,7 +1328,11 @@ void QMdiAreaPrivate::scrollBarPolicyChanged(Qt::Orientation orientation, Qt::Sc
const QMdiSubWindow::SubWindowOption option = orientation == Qt::Horizontal ?
QMdiSubWindow::AllowOutsideAreaHorizontally : QMdiSubWindow::AllowOutsideAreaVertically;
const bool enable = policy != Qt::ScrollBarAlwaysOff;
- foreach (QMdiSubWindow *child, childWindows) {
+ // Take a copy because child->setOption() may indirectly call QCoreApplication::sendEvent(),
+ // the latter could call unknown code that could e.g. recurse into the class
+ // modifying childWindows.
+ const auto subWindows = childWindows;
+ for (QMdiSubWindow *child : subWindows) {
if (!sanityCheck(child, "QMdiArea::scrollBarPolicyChanged"))
continue;
child->setOption(option, enable);
@@ -1352,7 +1348,7 @@ QMdiAreaPrivate::subWindowList(QMdiArea::WindowOrder order, bool reversed) const
return list;
if (order == QMdiArea::CreationOrder) {
- foreach (QMdiSubWindow *child, childWindows) {
+ for (QMdiSubWindow *child : childWindows) {
if (!child)
continue;
if (!reversed)
@@ -1533,12 +1529,17 @@ void QMdiAreaPrivate::setViewMode(QMdiArea::ViewMode mode)
tabBar->setTabsClosable(tabsClosable);
tabBar->setMovable(tabsMovable);
#if QT_CONFIG(tabwidget)
- tabBar->setShape(tabBarShapeFrom(tabShape, tabPosition));
+ tabBar->setShape(_q_tb_tabBarShapeFrom(tabShape, tabPosition));
#endif
isSubWindowsTiled = false;
- foreach (QMdiSubWindow *subWindow, childWindows)
+ // Take a copy as tabBar->addTab() will (indirectly) create a connection between
+ // the tab close button clicked() signal and the _q_closeTab() slot, which may
+ // indirectly call QCoreApplication::sendEvent(), the latter could result in
+ // invoking unknown code that could e.g. recurse into the class modifying childWindows.
+ const auto subWindows = childWindows;
+ for (QMdiSubWindow *subWindow : subWindows)
tabBar->addTab(subWindow->windowIcon(), tabTextFor(subWindow));
QMdiSubWindow *current = q->currentSubWindow();
@@ -1597,7 +1598,7 @@ void QMdiAreaPrivate::updateTabBarGeometry()
Q_Q(QMdiArea);
#if QT_CONFIG(tabwidget)
- Q_ASSERT(tabBarShapeFrom(tabShape, tabPosition) == tabBar->shape());
+ Q_ASSERT(_q_tb_tabBarShapeFrom(tabShape, tabPosition) == tabBar->shape());
#endif
const QSize tabBarSizeHint = tabBar->sizeHint();
@@ -1654,7 +1655,7 @@ void QMdiAreaPrivate::refreshTabBar()
tabBar->setTabsClosable(tabsClosable);
tabBar->setMovable(tabsMovable);
#if QT_CONFIG(tabwidget)
- tabBar->setShape(tabBarShapeFrom(tabShape, tabPosition));
+ tabBar->setShape(_q_tb_tabBarShapeFrom(tabShape, tabPosition));
#endif
updateTabBarGeometry();
}
@@ -1860,7 +1861,11 @@ void QMdiArea::closeAllSubWindows()
return;
d->isSubWindowsTiled = false;
- foreach (QMdiSubWindow *child, d->childWindows) {
+ // Take a copy because the child->close() call below may end up indirectly calling
+ // QCoreApplication::send{Spontaneous}Event(), which may call unknown code that
+ // could e.g. recurse into the class modifying d->childWindows.
+ const auto subWindows = d->childWindows;
+ for (QMdiSubWindow *child : subWindows) {
if (!sanityCheck(child, "QMdiArea::closeAllSubWindows"))
continue;
child->close();
@@ -1999,7 +2004,11 @@ void QMdiArea::removeSubWindow(QWidget *widget)
}
bool found = false;
- foreach (QMdiSubWindow *child, d->childWindows) {
+ // Take a copy because child->setWidget(nullptr) will indirectly
+ // QCoreApplication::sendEvent(); the latter could call unknown code that could
+ // e.g. recurse into the class modifying d->childWindows.
+ const auto subWindows = d->childWindows;
+ for (QMdiSubWindow *child : subWindows) {
if (!sanityCheck(child, "QMdiArea::removeSubWindow"))
continue;
if (child->widget() == widget) {
@@ -2280,7 +2289,11 @@ void QMdiArea::resizeEvent(QResizeEvent *resizeEvent)
// Resize maximized views.
bool hasMaximizedSubWindow = false;
- foreach (QMdiSubWindow *child, d->childWindows) {
+ // Take a copy because child->resize() may call QCoreApplication::sendEvent()
+ // which may invoke unknown code, that could e.g. recurse into the class
+ // modifying d->childWindows.
+ const auto subWindows = d->childWindows;
+ for (QMdiSubWindow *child : subWindows) {
if (sanityCheck(child, "QMdiArea::resizeEvent") && child->isMaximized()
&& child->size() != resizeEvent->size()) {
auto realSize = resizeEvent->size();
@@ -2339,7 +2352,9 @@ void QMdiArea::showEvent(QShowEvent *showEvent)
Q_D(QMdiArea);
if (!d->pendingRearrangements.isEmpty()) {
bool skipPlacement = false;
- foreach (Rearranger *rearranger, d->pendingRearrangements) {
+ // Take a copy because d->rearrange() may modify d->pendingRearrangements
+ const auto pendingRearrange = d->pendingRearrangements;
+ for (Rearranger *rearranger : pendingRearrange) {
// If this is the case, we don't have to lay out pending child windows
// since the rearranger will find a placement for them.
if (rearranger->type() != Rearranger::IconTiler && !skipPlacement)
@@ -2353,9 +2368,19 @@ void QMdiArea::showEvent(QShowEvent *showEvent)
}
if (!d->pendingPlacements.isEmpty()) {
- foreach (QMdiSubWindow *window, d->pendingPlacements) {
+ // Nothing obvious in the loop body changes the container (in this code path)
+ // during iteration, this is calling into a non-const method that does change
+ // the container when called from other places. So take a copy anyway for good
+ // measure.
+ const auto copy = d->pendingPlacements;
+ for (QMdiSubWindow *window : copy) {
if (!window)
continue;
+ if (d->viewMode == TabbedView && window->d_func()->isActive && !d->active) {
+ d->showActiveWindowMaximized = true;
+ d->emitWindowActivated(window); // Also maximizes the window
+ continue;
+ }
if (!window->testAttribute(Qt::WA_Resized)) {
QSize newSize(window->sizeHint().boundedTo(viewport()->size()));
window->resize(newSize.expandedTo(qSmartMinSize(window)));
@@ -2489,12 +2514,16 @@ bool QMdiArea::event(QEvent *event)
d->isSubWindowsTiled = true;
}
break;
- case QEvent::WindowIconChange:
- foreach (QMdiSubWindow *window, d->childWindows) {
+ case QEvent::WindowIconChange: {
+ // Take a copy because QCoreApplication::sendEvent() may call unknown code,
+ // that may cause recursing into the class
+ const auto subWindows = d->childWindows;
+ for (QMdiSubWindow *window : subWindows) {
if (sanityCheck(window, "QMdiArea::WindowIconChange"))
QCoreApplication::sendEvent(window, event);
}
break;
+ }
case QEvent::Hide:
d->setActive(d->active, false, false);
d->setChildActivationEnabled(false);
@@ -2649,7 +2678,10 @@ void QMdiArea::setupViewport(QWidget *viewport)
Q_D(QMdiArea);
if (viewport)
viewport->setAttribute(Qt::WA_OpaquePaintEvent, d->background.isOpaque());
- foreach (QMdiSubWindow *child, d->childWindows) {
+ // Take a copy because the child->setParent() call below may call QCoreApplication::sendEvent()
+ // which may call unknown code that could e.g. recurse into the class modifying d->childWindows.
+ const auto subWindows = d->childWindows;
+ for (QMdiSubWindow *child : subWindows) {
if (!sanityCheck(child, "QMdiArea::setupViewport"))
continue;
child->setParent(viewport, child->windowFlags());
diff --git a/src/widgets/widgets/qmdiarea_p.h b/src/widgets/widgets/qmdiarea_p.h
index 2e66a31fbc..e57b9772ca 100644
--- a/src/widgets/widgets/qmdiarea_p.h
+++ b/src/widgets/widgets/qmdiarea_p.h
@@ -29,6 +29,8 @@ QT_REQUIRE_CONFIG(mdiarea);
#include <private/qmdisubwindow_p.h>
#include <private/qabstractscrollarea_p.h>
+#include <QtCore/qpointer.h>
+
QT_BEGIN_NAMESPACE
namespace QMdi {
diff --git a/src/widgets/widgets/qmdisubwindow.cpp b/src/widgets/widgets/qmdisubwindow.cpp
index ef1cab998f..d8700e3df2 100644
--- a/src/widgets/widgets/qmdisubwindow.cpp
+++ b/src/widgets/widgets/qmdisubwindow.cpp
@@ -1914,20 +1914,16 @@ QPalette QMdiSubWindowPrivate::desktopPalette() const
Q_Q(const QMdiSubWindow);
QPalette newPalette = q->palette();
- bool colorsInitialized = false;
-
- if (!colorsInitialized) {
- newPalette.setColor(QPalette::Active, QPalette::Highlight,
- newPalette.color(QPalette::Active, QPalette::Highlight));
- newPalette.setColor(QPalette::Active, QPalette::Base,
- newPalette.color(QPalette::Active, QPalette::Highlight));
- newPalette.setColor(QPalette::Inactive, QPalette::Highlight,
- newPalette.color(QPalette::Inactive, QPalette::Dark));
- newPalette.setColor(QPalette::Inactive, QPalette::Base,
- newPalette.color(QPalette::Inactive, QPalette::Dark));
- newPalette.setColor(QPalette::Inactive, QPalette::HighlightedText,
- newPalette.color(QPalette::Inactive, QPalette::Window));
- }
+ newPalette.setColor(QPalette::Active, QPalette::Highlight,
+ newPalette.color(QPalette::Active, QPalette::Highlight));
+ newPalette.setColor(QPalette::Active, QPalette::Base,
+ newPalette.color(QPalette::Active, QPalette::Highlight));
+ newPalette.setColor(QPalette::Inactive, QPalette::Highlight,
+ newPalette.color(QPalette::Inactive, QPalette::Dark));
+ newPalette.setColor(QPalette::Inactive, QPalette::Base,
+ newPalette.color(QPalette::Inactive, QPalette::Dark));
+ newPalette.setColor(QPalette::Inactive, QPalette::HighlightedText,
+ newPalette.color(QPalette::Inactive, QPalette::Window));
return newPalette;
}
diff --git a/src/widgets/widgets/qmdisubwindow.h b/src/widgets/widgets/qmdisubwindow.h
index a34c0249ec..4227f02dac 100644
--- a/src/widgets/widgets/qmdisubwindow.h
+++ b/src/widgets/widgets/qmdisubwindow.h
@@ -101,6 +101,7 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_enterInteractiveMode())
Q_PRIVATE_SLOT(d_func(), void _q_processFocusChanged(QWidget *, QWidget *))
friend class QMdiAreaPrivate;
+ friend class QMdiArea;
#if QT_CONFIG(tabbar)
friend class QMdiAreaTabBar;
#endif
diff --git a/src/widgets/widgets/qmdisubwindow_p.h b/src/widgets/widgets/qmdisubwindow_p.h
index 60909eb3bc..2a1f83269a 100644
--- a/src/widgets/widgets/qmdisubwindow_p.h
+++ b/src/widgets/widgets/qmdisubwindow_p.h
@@ -39,7 +39,7 @@ class QMouseEvent;
namespace QMdi {
template<typename T>
-class ControlElement : public T
+class ControlElement : public T // ELFVERSION:ignore
{
public:
ControlElement(QMdiSubWindow *child) : T(child, nullptr)
@@ -58,7 +58,7 @@ public:
QPointer<QMdiSubWindow> mdiChild;
};
-class ControlContainer : public QObject
+class ControlContainer : public QObject // ELFVERSION:ignore
{
public:
ControlContainer(QMdiSubWindow *mdiChild);
diff --git a/src/widgets/widgets/qmenu.cpp b/src/widgets/widgets/qmenu.cpp
index e789c1bef2..db00f8a650 100644
--- a/src/widgets/widgets/qmenu.cpp
+++ b/src/widgets/widgets/qmenu.cpp
@@ -93,7 +93,9 @@ public:
Q_D(QTornOffMenu);
// make the torn-off menu a sibling of p (instead of a child)
QWidget *parentWidget = d->causedStack.isEmpty() ? p : d->causedStack.constLast();
- if (parentWidget->parentWidget())
+ if (!parentWidget && p)
+ parentWidget = p;
+ if (parentWidget && parentWidget->parentWidget())
parentWidget = parentWidget->parentWidget();
setParent(parentWidget, Qt::Window | Qt::Tool);
setAttribute(Qt::WA_DeleteOnClose, true);
@@ -163,7 +165,7 @@ void QMenuPrivate::init()
defaultMenuAction = menuAction = new QAction(q);
menuAction->setMenu(q); // this calls setOverrideMenuAction
setOverrideMenuAction(nullptr);
- QObject::connect(menuAction, &QAction::changed, [this] {
+ QObject::connect(menuAction, &QAction::changed, q, [this] {
if (!tornPopup.isNull())
tornPopup->updateWindowTitle();
});
@@ -290,6 +292,13 @@ inline bool QMenuPrivate::useFullScreenForPopup() const
QRect QMenuPrivate::popupGeometry(QScreen *screen) const
{
Q_Q(const QMenu);
+ if (screen == nullptr
+#if QT_CONFIG(graphicsview)
+ && q->graphicsProxyWidget() == nullptr
+#endif
+ ) {
+ screen = q->isVisible() ? q->screen() : popupScreen.data();
+ }
if (useFullScreenForPopup())
return screen ? screen->geometry()
: QWidgetPrivate::screenGeometry(q);
@@ -567,10 +576,16 @@ void QMenuPrivate::hideMenu(QMenu *menu)
};
#if QT_CONFIG(effects)
- QSignalBlocker blocker(menu);
+ // If deleteLater has been called and the event loop spins, while waiting
+ // for visual effects to happen, menu might become stale.
+ // To prevent a QSignalBlocker from restoring a stale object, block and restore signals manually.
+ QPointer<QMenu> stillAlive(menu);
+ const bool signalsBlocked = menu->signalsBlocked();
+ menu->blockSignals(true);
+
aboutToHide = true;
// Flash item which is about to trigger (if any).
- if (menu->style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem)
+ if (menu && menu->style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem)
&& currentAction && currentAction == actionAboutToTrigger
&& menu->actions().contains(currentAction)) {
QEventLoop eventLoop;
@@ -581,6 +596,9 @@ void QMenuPrivate::hideMenu(QMenu *menu)
QTimer::singleShot(60, &eventLoop, SLOT(quit()));
eventLoop.exec();
+ if (!stillAlive)
+ return;
+
// Select and wait 20 ms.
menu->setActiveAction(activeAction);
QTimer::singleShot(20, &eventLoop, SLOT(quit()));
@@ -588,10 +606,16 @@ void QMenuPrivate::hideMenu(QMenu *menu)
}
aboutToHide = false;
- blocker.unblock();
+
+ if (stillAlive)
+ menu->blockSignals(signalsBlocked);
+ else
+ return;
+
#endif // QT_CONFIG(effects)
if (activeMenu == menu)
activeMenu = nullptr;
+
menu->d_func()->causedPopup.action = nullptr;
menu->close();
menu->d_func()->causedPopup.widget = nullptr;
@@ -1387,9 +1411,18 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
void QMenuPrivate::activateCausedStack(const QList<QPointer<QWidget>> &causedStack, QAction *action,
QAction::ActionEvent action_e, bool self)
{
- QBoolBlocker guard(activationRecursionGuard);
+ Q_Q(QMenu);
+ // can't use QBoolBlocker here
+ const bool activationRecursionGuardReset = activationRecursionGuard;
+ activationRecursionGuard = true;
+ QPointer<QMenu> guard(q);
if (self)
action->activate(action_e);
+ if (!guard)
+ return;
+ auto boolBlocker = qScopeGuard([this, activationRecursionGuardReset]{
+ activationRecursionGuard = activationRecursionGuardReset;
+ });
for(int i = 0; i < causedStack.size(); ++i) {
QPointer<QWidget> widget = causedStack.at(i);
@@ -1465,9 +1498,10 @@ void QMenuPrivate::activateAction(QAction *action, QAction::ActionEvent action_e
#endif
}
-
+ QPointer<QMenu> thisGuard(q);
activateCausedStack(causedStack, action, action_e, self);
-
+ if (!thisGuard)
+ return;
if (action_e == QAction::Hover) {
#if QT_CONFIG(accessibility)
@@ -1698,7 +1732,7 @@ void QMenu::initStyleOption(QStyleOptionMenuItem *option, const QAction *action)
\b{Important inherited functions:} addAction(), removeAction(), clear(),
addSeparator(), and addMenu().
- \sa QMenuBar, {Qt Widgets - Application Example}, {Menus Example}
+ \sa QMenuBar, {Menus Example}
*/
@@ -2282,6 +2316,9 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
void QMenuPrivate::popup(const QPoint &p, QAction *atAction, PositionFunction positionFunction)
{
Q_Q(QMenu);
+ popupScreen = QGuiApplication::screenAt(p);
+ QScopeGuard popupScreenGuard([this](){ popupScreen.clear(); });
+
if (scroll) { // reset scroll state from last popup
if (scroll->scrollOffset)
itemsDirty = 1; // sizeHint will be incorrect if there is previous scroll
@@ -2357,6 +2394,7 @@ void QMenuPrivate::popup(const QPoint &p, QAction *atAction, PositionFunction po
pos = QPushButtonPrivate::get(causedButton)->adjustedMenuPosition();
else
pos = p;
+ popupScreen = QGuiApplication::screenAt(pos);
const QSize menuSizeHint(q->sizeHint());
QSize size = menuSizeHint;
@@ -2495,6 +2533,7 @@ void QMenuPrivate::popup(const QPoint &p, QAction *atAction, PositionFunction po
}
}
}
+ popupScreen = QGuiApplication::screenAt(pos);
q->setGeometry(QRect(pos, size));
#if QT_CONFIG(effects)
int hGuess = q->isRightToLeft() ? QEffects::LeftScroll : QEffects::RightScroll;
@@ -2635,6 +2674,7 @@ QAction *QMenuPrivate::exec(const QPoint &p, QAction *action, PositionFunction p
action = syncAction;
syncAction = nullptr;
eventLoop = nullptr;
+ popupScreen.clear();
return action;
}
@@ -2812,7 +2852,7 @@ void QMenu::paintEvent(QPaintEvent *e)
frame.rect = rect();
frame.palette = palette();
frame.state = QStyle::State_None;
- frame.lineWidth = style()->pixelMetric(QStyle::PM_MenuPanelWidth, &frame);
+ frame.lineWidth = style()->pixelMetric(QStyle::PM_MenuPanelWidth, &frame, this);
frame.midLineWidth = 0;
p.drawPrimitive(QStyle::PE_FrameMenu, frame);
}
@@ -2939,7 +2979,7 @@ bool QMenu::event(QEvent *e)
d->updateLayoutDirection();
break;
case QEvent::ShortcutOverride: {
- QKeyEvent *kev = static_cast<QKeyEvent*>(e);
+ QKeyEvent *kev = static_cast<QKeyEvent *>(e);
if (kev->key() == Qt::Key_Up || kev->key() == Qt::Key_Down
|| kev->key() == Qt::Key_Left || kev->key() == Qt::Key_Right
|| kev->key() == Qt::Key_Enter || kev->key() == Qt::Key_Return
@@ -2953,7 +2993,7 @@ bool QMenu::event(QEvent *e)
}
break;
case QEvent::KeyPress: {
- QKeyEvent *ke = (QKeyEvent*)e;
+ QKeyEvent *ke = static_cast<QKeyEvent *>(e);
if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
keyPressEvent(ke);
return true;
diff --git a/src/widgets/widgets/qmenu_p.h b/src/widgets/widgets/qmenu_p.h
index 0d849e5eed..1e32fbcdfa 100644
--- a/src/widgets/widgets/qmenu_p.h
+++ b/src/widgets/widgets/qmenu_p.h
@@ -29,6 +29,8 @@
#include <qpa/qplatformmenu.h>
+#include <QtCore/qpointer.h>
+
#include <functional>
QT_REQUIRE_CONFIG(menu);
@@ -471,6 +473,11 @@ public:
mutable quint8 ncols = 0; // "255cols ought to be enough for anybody."
+ // Contains the screen of the popup point during popup(QPoint).
+ // This is to make sure the screen is remembered,
+ // when the menu contains many items on multiple screens
+ QPointer<QScreen> popupScreen;
+
mutable bool itemsDirty : 1;
mutable bool hasCheckableItems : 1;
bool lastContextMenu : 1;
diff --git a/src/widgets/widgets/qmenubar.cpp b/src/widgets/widgets/qmenubar.cpp
index 01ad37cab0..c9c9191c17 100644
--- a/src/widgets/widgets/qmenubar.cpp
+++ b/src/widgets/widgets/qmenubar.cpp
@@ -281,17 +281,28 @@ void QMenuBarPrivate::popupAction(QAction *action, bool activateFirst)
if (action->isEnabled() && action->menu()->isEnabled()) {
closePopupMode = 0;
activeMenu = action->menu();
- activeMenu->d_func()->causedPopup.widget = q;
- activeMenu->d_func()->causedPopup.action = action;
+ auto *activeMenuPriv = activeMenu->d_func();
+ activeMenuPriv->causedPopup.widget = q;
+ activeMenuPriv->causedPopup.action = action;
QRect adjustedActionRect = actionRect(action);
- QPoint pos(q->mapToGlobal(QPoint(adjustedActionRect.left(), adjustedActionRect.bottom() + 1)));
- QSize popup_size = activeMenu->sizeHint();
+ QPoint popupPos = adjustedActionRect.bottomLeft() + QPoint(0, 1);
+
//we put the popup menu on the screen containing the bottom-center of the action rect
QScreen *menubarScreen = q->window()->windowHandle()->screen();
- QScreen *popupScreen = menubarScreen->virtualSiblingAt(pos + QPoint(adjustedActionRect.width() / 2, 0));
+ QPoint screenTestPos = q->mapToGlobal(popupPos + QPoint(adjustedActionRect.width() / 2, 0));
+ QPointer<QScreen> popupScreen = menubarScreen->virtualSiblingAt(screenTestPos);
if (!popupScreen)
popupScreen = menubarScreen;
+ std::swap(popupScreen, activeMenuPriv->popupScreen);
+ const QSize popup_size = activeMenu->sizeHint();
+ std::swap(popupScreen, activeMenuPriv->popupScreen);
+
+ // Use screenTestPos.y() for the popup y position. This is the correct global y
+ // consistent with the selected screen in cases where the action rect spans
+ // multiple screens with different scale factors.
+ QPoint pos(q->mapToGlobal(popupPos).x(), screenTestPos.y());
+
QRect screenRect = popupScreen->geometry();
pos = QPoint(qMax(pos.x(), screenRect.x()), qMax(pos.y(), screenRect.y()));
const bool fitUp = (pos.y() - popup_size.height() >= screenRect.top());
@@ -596,11 +607,13 @@ void QMenuBar::initStyleOption(QStyleOptionMenuItem *option, const QAction *acti
Qt for \macos also provides a menu bar merging feature to make
QMenuBar conform more closely to accepted \macos menu bar layout.
- The merging functionality is based on string matching the title of
- a QMenu entry. These strings are translated (using QObject::tr())
- in the "QMenuBar" context. If an entry is moved its slots will still
- fire as if it was in the original place. The table below outlines
- the strings looked for and where the entry is placed if matched:
+ If an entry is moved its slots will still fire as if it was in the
+ original place.
+
+ The merging functionality is based on the QAction::menuRole() of
+ the menu entries. If an item has QAction::TextHeuristicRole,
+ the role is determined by string matching the title using the
+ following heuristics:
\table
\header \li String matches \li Placement \li Notes
@@ -618,8 +631,8 @@ void QMenuBar::initStyleOption(QStyleOptionMenuItem *option, const QAction *acti
created to call QCoreApplication::quit()
\endtable
- You can override this behavior by using the QAction::menuRole()
- property.
+ You can override this behavior by setting the QAction::menuRole()
+ property to QAction::NoRole.
If you want all windows in a Mac application to share one menu
bar, you must create a menu bar that does not have a parent.
@@ -912,7 +925,7 @@ void QMenuBar::paintEvent(QPaintEvent *e)
frame.rect = rect();
frame.palette = palette();
frame.state = QStyle::State_None;
- frame.lineWidth = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, &frame);
+ frame.lineWidth = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, &frame, this);
frame.midLineWidth = 0;
style()->drawPrimitive(QStyle::PE_PanelMenuBar, &frame, &p, this);
}
@@ -1285,7 +1298,12 @@ void QMenuBarPrivate::handleReparent()
QList<QPointer<QWidget>> newParents;
// Remove event filters on ex-parents, keep them on still-parents
// The parents are always ordered in the vector
- foreach (const QPointer<QWidget> &w, oldParents) {
+ //
+ // Take a copy because this method is called from changeEvent() and eventFilter(),
+ // which might cause recursion into the class due to event processing, which might
+ // modify oldParents.
+ const auto copy = oldParents;
+ for (const QPointer<QWidget> &w : copy) {
if (w) {
if (newParent == w) {
newParents.append(w);
@@ -1356,7 +1374,7 @@ bool QMenuBar::event(QEvent *e)
Q_D(QMenuBar);
switch (e->type()) {
case QEvent::KeyPress: {
- QKeyEvent *ke = (QKeyEvent*)e;
+ QKeyEvent *ke = static_cast<QKeyEvent *>(e);
#if 0
if (!d->keyboardState) { //all keypresses..
d->setCurrentAction(0);
@@ -1384,7 +1402,7 @@ bool QMenuBar::event(QEvent *e)
break;
#ifndef QT_NO_SHORTCUT
case QEvent::ShortcutOverride: {
- QKeyEvent *kev = static_cast<QKeyEvent*>(e);
+ QKeyEvent *kev = static_cast<QKeyEvent *>(e);
//we only filter out escape if there is a current action
if (kev->matches(QKeySequence::Cancel) && d->currentAction) {
e->accept();
@@ -1772,6 +1790,7 @@ void QMenuBar::setNativeMenuBar(bool nativeMenuBar)
if (!nativeMenuBar) {
delete d->platformMenuBar;
d->platformMenuBar = nullptr;
+ d->itemsDirty = true;
} else {
if (!d->platformMenuBar)
d->platformMenuBar = QGuiApplicationPrivate::platformTheme()->createPlatformMenuBar();
diff --git a/src/widgets/widgets/qmenubar_p.h b/src/widgets/widgets/qmenubar_p.h
index ee524c3acb..549a4c7a1f 100644
--- a/src/widgets/widgets/qmenubar_p.h
+++ b/src/widgets/widgets/qmenubar_p.h
@@ -20,6 +20,8 @@
#include <private/qmenu_p.h> // Mac needs what in this file!
#include <qpa/qplatformmenu.h>
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(menubar);
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/widgets/qplaintextedit.cpp b/src/widgets/widgets/qplaintextedit.cpp
index cd9889e9ff..8362c6c629 100644
--- a/src/widgets/widgets/qplaintextedit.cpp
+++ b/src/widgets/widgets/qplaintextedit.cpp
@@ -418,7 +418,7 @@ QPlainTextEditControl::QPlainTextEditControl(QPlainTextEdit *parent)
setAcceptRichText(false);
}
-void QPlainTextEditPrivate::_q_cursorPositionChanged()
+void QPlainTextEditPrivate::cursorPositionChanged()
{
pageUpDownLastCursorYIsValid = false;
Q_Q(QPlainTextEdit);
@@ -429,11 +429,18 @@ void QPlainTextEditPrivate::_q_cursorPositionChanged()
emit q->cursorPositionChanged();
}
-void QPlainTextEditPrivate::_q_verticalScrollbarActionTriggered(int action) {
- if (action == QAbstractSlider::SliderPageStepAdd) {
+void QPlainTextEditPrivate::verticalScrollbarActionTriggered(int action) {
+
+ const auto a = static_cast<QAbstractSlider::SliderAction>(action);
+ switch (a) {
+ case QAbstractSlider::SliderPageStepAdd:
pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor, false);
- } else if (action == QAbstractSlider::SliderPageStepSub) {
+ break;
+ case QAbstractSlider::SliderPageStepSub:
pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor, false);
+ break;
+ default:
+ break;
}
}
@@ -622,10 +629,7 @@ void QPlainTextEditPrivate::setTopBlock(int blockNumber, int lineNumber, int dx)
lineNumber = maxTopLine - block.firstLineNumber();
}
- {
- const QSignalBlocker blocker(vbar);
- vbar->setValue(newTopLine);
- }
+ vbar->setValue(newTopLine);
if (!dx && blockNumber == control->topBlock && lineNumber == topLine)
return;
@@ -641,10 +645,7 @@ void QPlainTextEditPrivate::setTopBlock(int blockNumber, int lineNumber, int dx)
control->topBlock = blockNumber;
topLine = lineNumber;
- {
- const QSignalBlocker blocker(vbar);
- vbar->setValue(block.firstLineNumber() + lineNumber);
- }
+ vbar->setValue(block.firstLineNumber() + lineNumber);
if (dx || dy) {
viewport->scroll(q->isRightToLeft() ? -dx : dx, dy);
@@ -724,9 +725,14 @@ void QPlainTextEditPrivate::updateViewport()
}
QPlainTextEditPrivate::QPlainTextEditPrivate()
- : tabChangesFocus(false), showCursorOnInitialShow(false), backgroundVisible(false),
- centerOnScroll(false), inDrag(false), clickCausedFocus(false), placeholderVisible(true),
- pageUpDownLastCursorYIsValid(false)
+ : tabChangesFocus(false)
+ , showCursorOnInitialShow(false)
+ , backgroundVisible(false)
+ , centerOnScroll(false)
+ , inDrag(false)
+ , clickCausedFocus(false)
+ , pageUpDownLastCursorYIsValid(false)
+ , placeholderTextShown(false)
{
}
@@ -742,23 +748,28 @@ void QPlainTextEditPrivate::init(const QString &txt)
control->setPalette(q->palette());
- QObject::connect(vbar, SIGNAL(actionTriggered(int)), q, SLOT(_q_verticalScrollbarActionTriggered(int)));
-
- QObject::connect(control, SIGNAL(microFocusChanged()), q, SLOT(updateMicroFocus()));
- QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)), q, SLOT(_q_adjustScrollbars()));
- QObject::connect(control, SIGNAL(blockCountChanged(int)), q, SIGNAL(blockCountChanged(int)));
- QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(_q_repaintContents(QRectF)));
- QObject::connect(control, SIGNAL(modificationChanged(bool)), q, SIGNAL(modificationChanged(bool)));
-
- QObject::connect(control, SIGNAL(textChanged()), q, SIGNAL(textChanged()));
- QObject::connect(control, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
- QObject::connect(control, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
- QObject::connect(control, SIGNAL(copyAvailable(bool)), q, SIGNAL(copyAvailable(bool)));
- QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));
- QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SLOT(_q_cursorPositionChanged()));
-
- QObject::connect(control, SIGNAL(textChanged()), q, SLOT(_q_updatePlaceholderVisibility()));
- QObject::connect(control, SIGNAL(textChanged()), q, SLOT(updateMicroFocus()));
+ QObjectPrivate::connect(vbar, &QAbstractSlider::actionTriggered,
+ this, &QPlainTextEditPrivate::verticalScrollbarActionTriggered);
+ QObject::connect(control, &QWidgetTextControl::microFocusChanged, q,
+ [q](){q->updateMicroFocus(); });
+ QObjectPrivate::connect(control, &QWidgetTextControl::documentSizeChanged,
+ this, &QPlainTextEditPrivate::adjustScrollbars);
+ QObject::connect(control, &QWidgetTextControl::blockCountChanged,
+ q, &QPlainTextEdit::blockCountChanged);
+ QObjectPrivate::connect(control, &QWidgetTextControl::updateRequest,
+ this, &QPlainTextEditPrivate::repaintContents);
+ QObject::connect(control, &QWidgetTextControl::modificationChanged,
+ q, &QPlainTextEdit::modificationChanged);
+ QObject::connect(control, &QWidgetTextControl::textChanged, q, &QPlainTextEdit::textChanged);
+ QObject::connect(control, &QWidgetTextControl::undoAvailable, q, &QPlainTextEdit::undoAvailable);
+ QObject::connect(control, &QWidgetTextControl::redoAvailable, q, &QPlainTextEdit::redoAvailable);
+ QObject::connect(control, &QWidgetTextControl::copyAvailable, q, &QPlainTextEdit::copyAvailable);
+ QObject::connect(control, &QWidgetTextControl::selectionChanged, q, &QPlainTextEdit::selectionChanged);
+ QObjectPrivate::connect(control, &QWidgetTextControl::cursorPositionChanged,
+ this, &QPlainTextEditPrivate::cursorPositionChanged);
+ QObjectPrivate::connect(control, &QWidgetTextControl::textChanged,
+ this, &QPlainTextEditPrivate::updatePlaceholderVisibility);
+ QObject::connect(control, &QWidgetTextControl::textChanged, q, [q](){q->updateMicroFocus(); });
// set a null page size initially to avoid any relayouting until the textedit
// is shown. relayoutDocument() will take care of setting the page size to the
@@ -786,26 +797,19 @@ void QPlainTextEditPrivate::init(const QString &txt)
#endif
}
-void QPlainTextEditPrivate::_q_updatePlaceholderVisibility()
+void QPlainTextEditPrivate::updatePlaceholderVisibility()
{
- Q_Q(QPlainTextEdit);
-
// We normally only repaint the part of view that contains text in the
- // document that has changed (in _q_repaintContents). But the placeholder
+ // document that has changed (in repaintContents). But the placeholder
// text is not a part of the document, but is drawn on separately. So whenever
// we either show or hide the placeholder text, we issue a full update.
- bool placeholderCurrentyVisible = placeholderVisible;
-
- placeholderVisible = !placeholderText.isEmpty()
- && q->document()->isEmpty()
- && (!q->firstVisibleBlock().isValid() ||
- q->firstVisibleBlock().layout()->preeditAreaText().isEmpty());
-
- if (placeholderCurrentyVisible != placeholderVisible)
+ if (placeholderTextShown != placeHolderTextToBeShown()) {
viewport->update();
+ placeholderTextShown = placeHolderTextToBeShown();
+ }
}
-void QPlainTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
+void QPlainTextEditPrivate::repaintContents(const QRectF &contentsRect)
{
Q_Q(QPlainTextEdit);
if (!contentsRect.isValid()) {
@@ -938,7 +942,7 @@ void QPlainTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCurso
#if QT_CONFIG(scrollbar)
-void QPlainTextEditPrivate::_q_adjustScrollbars()
+void QPlainTextEditPrivate::adjustScrollbars()
{
Q_Q(QPlainTextEdit);
QTextDocument *doc = control->document();
@@ -992,8 +996,6 @@ void QPlainTextEditPrivate::_q_adjustScrollbars()
vSliderLength = lineSpacing != 0 ? viewport->height() / lineSpacing : 0;
}
-
-
QSizeF documentSize = documentLayout->documentSize();
vbar->setRange(0, qMax(0, vmax));
vbar->setPageStep(vSliderLength);
@@ -1002,10 +1004,7 @@ void QPlainTextEditPrivate::_q_adjustScrollbars()
if (firstVisibleBlock.isValid())
visualTopLine = firstVisibleBlock.firstLineNumber() + topLine;
- {
- const QSignalBlocker blocker(vbar);
- vbar->setValue(visualTopLine);
- }
+ vbar->setValue(visualTopLine);
hbar->setRange(0, (int)documentSize.width() - viewport->width());
hbar->setPageStep(viewport->width());
@@ -1185,10 +1184,8 @@ void QPlainTextEditPrivate::ensureViewportLayouted()
editor with line wrap enabled in real time. It also makes for a
fast log viewer (see setMaximumBlockCount()).
-
- \sa QTextDocument, QTextCursor, {Qt Widgets - Application Example},
- {Code Editor Example}, {Syntax Highlighter Example},
- {Rich Text Processing}
+ \sa QTextDocument, QTextCursor
+ {Syntax Highlighter Example}, {Rich Text Processing}
*/
@@ -1300,7 +1297,7 @@ void QPlainTextEdit::setDocument(QTextDocument *document)
d->documentLayoutPtr = documentLayout;
d->updateDefaultTextOption();
d->relayoutDocument();
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
}
/*!
@@ -1332,7 +1329,7 @@ void QPlainTextEdit::setPlaceholderText(const QString &placeholderText)
Q_D(QPlainTextEdit);
if (d->placeholderText != placeholderText) {
d->placeholderText = placeholderText;
- d->_q_updatePlaceholderVisibility();
+ d->updatePlaceholderVisibility();
}
}
@@ -1512,53 +1509,61 @@ bool QPlainTextEdit::event(QEvent *e)
{
Q_D(QPlainTextEdit);
+ switch (e->type()) {
#ifndef QT_NO_CONTEXTMENU
- if (e->type() == QEvent::ContextMenu
- && static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
- ensureCursorVisible();
- const QPoint cursorPos = cursorRect().center();
- QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
- ce.setAccepted(e->isAccepted());
- const bool result = QAbstractScrollArea::event(&ce);
- e->setAccepted(ce.isAccepted());
- return result;
- }
+ case QEvent::ContextMenu:
+ if (static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
+ ensureCursorVisible();
+ const QPoint cursorPos = cursorRect().center();
+ QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
+ ce.setAccepted(e->isAccepted());
+ const bool result = QAbstractScrollArea::event(&ce);
+ e->setAccepted(ce.isAccepted());
+ return result;
+ }
+ break;
#endif // QT_NO_CONTEXTMENU
- if (e->type() == QEvent::ShortcutOverride
- || e->type() == QEvent::ToolTip) {
+ case QEvent::ShortcutOverride:
+ case QEvent::ToolTip:
d->sendControlEvent(e);
- }
+ break;
#ifdef QT_KEYPAD_NAVIGATION
- else if (e->type() == QEvent::EnterEditFocus || e->type() == QEvent::LeaveEditFocus) {
+ case QEvent::EnterEditFocus:
+ case QEvent::LeaveEditFocus:
if (QApplicationPrivate::keypadNavigationEnabled())
d->sendControlEvent(e);
- }
+ break;
#endif
#ifndef QT_NO_GESTURES
- else if (e->type() == QEvent::Gesture) {
- QGestureEvent *ge = static_cast<QGestureEvent *>(e);
- QPanGesture *g = static_cast<QPanGesture *>(ge->gesture(Qt::PanGesture));
- if (g) {
+ case QEvent::Gesture:
+ if (auto *g = static_cast<QGestureEvent *>(e)->gesture(Qt::PanGesture)) {
+ QPanGesture *panGesture = static_cast<QPanGesture *>(g);
QScrollBar *hBar = horizontalScrollBar();
QScrollBar *vBar = verticalScrollBar();
- if (g->state() == Qt::GestureStarted)
+ if (panGesture->state() == Qt::GestureStarted)
d->originalOffsetY = vBar->value();
- QPointF offset = g->offset();
+ QPointF offset = panGesture->offset();
if (!offset.isNull()) {
if (QGuiApplication::isRightToLeft())
offset.rx() *= -1;
// QPlainTextEdit scrolls by lines only in vertical direction
QFontMetrics fm(document()->defaultFont());
int lineHeight = fm.height();
- int newX = hBar->value() - g->delta().x();
+ int newX = hBar->value() - panGesture->delta().x();
int newY = d->originalOffsetY - offset.y()/lineHeight;
hBar->setValue(newX);
vBar->setValue(newY);
}
}
return true;
- }
#endif // QT_NO_GESTURES
+ case QEvent::WindowActivate:
+ case QEvent::WindowDeactivate:
+ d->control->setPalette(palette());
+ break;
+ default:
+ break;
+ }
return QAbstractScrollArea::event(e);
}
@@ -1841,7 +1846,7 @@ void QPlainTextEdit::resizeEvent(QResizeEvent *e)
Q_D(QPlainTextEdit);
if (e->oldSize().width() != e->size().width())
d->relayoutDocument();
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
}
void QPlainTextEditPrivate::relayoutDocument()
@@ -1907,7 +1912,7 @@ void QPlainTextEdit::paintEvent(QPaintEvent *e)
er.setRight(qMin(er.right(), maxX));
painter.setClipRect(er);
- if (d->placeholderVisible) {
+ if (d->placeHolderTextToBeShown()) {
const QColor col = d->control->palette().placeholderText().color();
painter.setPen(col);
painter.setClipRect(e->rect());
@@ -2207,7 +2212,7 @@ QVariant QPlainTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant a
Q_D(const QPlainTextEdit);
switch (query) {
case Qt::ImEnabled:
- return isEnabled();
+ return isEnabled() && !isReadOnly();
case Qt::ImHints:
case Qt::ImInputItemClipRectangle:
return QWidget::inputMethodQuery(query);
@@ -2281,7 +2286,7 @@ void QPlainTextEdit::showEvent(QShowEvent *)
d->showCursorOnInitialShow = false;
ensureCursorVisible();
}
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
}
/*! \reimp
@@ -2290,20 +2295,29 @@ void QPlainTextEdit::changeEvent(QEvent *e)
{
Q_D(QPlainTextEdit);
QAbstractScrollArea::changeEvent(e);
- if (e->type() == QEvent::ApplicationFontChange
- || e->type() == QEvent::FontChange) {
+
+ switch (e->type()) {
+ case QEvent::ApplicationFontChange:
+ case QEvent::FontChange:
d->control->document()->setDefaultFont(font());
- } else if (e->type() == QEvent::ActivationChange) {
+ break;
+ case QEvent::ActivationChange:
if (!isActiveWindow())
d->autoScrollTimer.stop();
- } else if (e->type() == QEvent::EnabledChange) {
+ break;
+ case QEvent::EnabledChange:
e->setAccepted(isEnabled());
d->control->setPalette(palette());
d->sendControlEvent(e);
- } else if (e->type() == QEvent::PaletteChange) {
+ break;
+ case QEvent::PaletteChange:
d->control->setPalette(palette());
- } else if (e->type() == QEvent::LayoutDirectionChange) {
+ break;
+ case QEvent::LayoutDirectionChange:
d->sendControlEvent(e);
+ break;
+ default:
+ break;
}
}
@@ -2589,7 +2603,7 @@ void QPlainTextEdit::insertFromMimeData(const QMimeData *source)
bool QPlainTextEdit::isReadOnly() const
{
Q_D(const QPlainTextEdit);
- return !(d->control->textInteractionFlags() & Qt::TextEditable);
+ return !d->control || !(d->control->textInteractionFlags() & Qt::TextEditable);
}
void QPlainTextEdit::setReadOnly(bool ro)
@@ -2774,7 +2788,7 @@ void QPlainTextEdit::setLineWrapMode(LineWrapMode wrap)
d->lineWrap = wrap;
d->updateDefaultTextOption();
d->relayoutDocument();
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
ensureCursorVisible();
}
@@ -2860,7 +2874,7 @@ void QPlainTextEdit::setCenterOnScroll(bool enabled)
if (enabled == d->centerOnScroll)
return;
d->centerOnScroll = enabled;
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
}
@@ -2883,11 +2897,14 @@ bool QPlainTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
\overload
Finds the next occurrence, matching the regular expression, \a exp, using the given
- \a options. The QTextDocument::FindCaseSensitively option is ignored for this overload,
- use QRegularExpression::CaseInsensitiveOption instead.
+ \a options.
Returns \c true if a match was found and changes the cursor to select the match;
otherwise returns \c false.
+
+ \warning For historical reasons, the case sensitivity option set on
+ \a exp is ignored. Instead, the \a options are used to determine
+ if the search is case sensitive or not.
*/
#if QT_CONFIG(regularexpression)
bool QPlainTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
@@ -2988,12 +3005,17 @@ void QPlainTextEditPrivate::append(const QString &text, Qt::TextFormat format)
bool documentSizeChangedBlocked = documentLayout->priv()->blockDocumentSizeChanged;
documentLayout->priv()->blockDocumentSizeChanged = true;
- if (format == Qt::RichText)
+ switch (format) {
+ case Qt::RichText:
control->appendHtml(text);
- else if (format == Qt::PlainText)
+ break;
+ case Qt::PlainText:
control->appendPlainText(text);
- else
+ break;
+ default:
control->append(text);
+ break;
+ }
if (maximumBlockCount > 0) {
if (document->blockCount() > maximumBlockCount) {
@@ -3015,7 +3037,7 @@ void QPlainTextEditPrivate::append(const QString &text, Qt::TextFormat format)
}
documentLayout->priv()->blockDocumentSizeChanged = documentSizeChangedBlocked;
- _q_adjustScrollbars();
+ adjustScrollbars();
if (atBottom) {
diff --git a/src/widgets/widgets/qplaintextedit.h b/src/widgets/widgets/qplaintextedit.h
index d42b67fa69..89a4d3ab04 100644
--- a/src/widgets/widgets/qplaintextedit.h
+++ b/src/widgets/widgets/qplaintextedit.h
@@ -240,11 +240,6 @@ protected:
private:
Q_DISABLE_COPY(QPlainTextEdit)
- Q_PRIVATE_SLOT(d_func(), void _q_repaintContents(const QRectF &r))
- Q_PRIVATE_SLOT(d_func(), void _q_updatePlaceholderVisibility())
- Q_PRIVATE_SLOT(d_func(), void _q_adjustScrollbars())
- Q_PRIVATE_SLOT(d_func(), void _q_verticalScrollbarActionTriggered(int))
- Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged())
friend class QPlainTextEditControl;
};
diff --git a/src/widgets/widgets/qplaintextedit_p.h b/src/widgets/widgets/qplaintextedit_p.h
index 541011cc7e..9ca1cdcc67 100644
--- a/src/widgets/widgets/qplaintextedit_p.h
+++ b/src/widgets/widgets/qplaintextedit_p.h
@@ -32,6 +32,8 @@
#include "private/qwidgettextcontrol_p.h"
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(textedit);
QT_BEGIN_NAMESPACE
@@ -84,14 +86,14 @@ public:
QPlainTextEditPrivate();
void init(const QString &txt = QString());
- void _q_repaintContents(const QRectF &contentsRect);
- void _q_updatePlaceholderVisibility();
+ void repaintContents(const QRectF &contentsRect);
+ void updatePlaceholderVisibility();
inline QPoint mapToContents(const QPoint &point) const
{ return QPoint(point.x() + horizontalOffset(), point.y() + verticalOffset()); }
- void _q_adjustScrollbars();
- void _q_verticalScrollbarActionTriggered(int action);
+ void adjustScrollbars();
+ void verticalScrollbarActionTriggered(int action);
void ensureViewportLayouted();
void relayoutDocument();
@@ -128,8 +130,8 @@ public:
uint centerOnScroll : 1;
uint inDrag : 1;
uint clickCausedFocus : 1;
- uint placeholderVisible : 1;
uint pageUpDownLastCursorYIsValid : 1;
+ uint placeholderTextShown : 1;
void setTopLine(int visualTopLine, int dx = 0);
void setTopBlock(int newTopBlock, int newTopLine, int dx = 0);
@@ -142,8 +144,13 @@ public:
void append(const QString &text, Qt::TextFormat format = Qt::AutoText);
- void _q_cursorPositionChanged();
- void _q_modificationChanged(bool);
+ void cursorPositionChanged();
+ void modificationChanged(bool);
+ inline bool placeHolderTextToBeShown() const
+ {
+ Q_Q(const QPlainTextEdit);
+ return q->document()->isEmpty() && !q->placeholderText().isEmpty();
+ }
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qpushbutton.cpp b/src/widgets/widgets/qpushbutton.cpp
index ec882db175..c180a08d62 100644
--- a/src/widgets/widgets/qpushbutton.cpp
+++ b/src/widgets/widgets/qpushbutton.cpp
@@ -525,7 +525,8 @@ void QPushButton::setMenu(QMenu* menu)
return;
if (menu && !d->menu) {
- connect(this, SIGNAL(pressed()), this, SLOT(_q_popupPressed()), Qt::UniqueConnection);
+ QObjectPrivate::connect(this, &QPushButton::pressed,
+ d, &QPushButtonPrivate::popupPressed, Qt::UniqueConnection);
}
if (d->menu)
removeAction(d->menu->menuAction());
@@ -562,10 +563,10 @@ void QPushButton::showMenu()
if (!d || !d->menu)
return;
setDown(true);
- d->_q_popupPressed();
+ d->popupPressed();
}
-void QPushButtonPrivate::_q_popupPressed()
+void QPushButtonPrivate::popupPressed()
{
Q_Q(QPushButton);
if (!down || !menu)
@@ -575,17 +576,14 @@ void QPushButtonPrivate::_q_popupPressed()
QPoint menuPos = adjustedMenuPosition();
- QPointer<QPushButton> guard(q);
- QMenuPrivate::get(menu)->causedPopup.widget = guard;
+ QMenuPrivate::get(menu)->causedPopup.widget = q;
//Because of a delay in menu effects, we must keep track of the
//menu visibility to avoid flicker on button release
menuOpen = true;
- menu->exec(menuPos);
- if (guard) {
- menuOpen = false;
- q->setDown(false);
- }
+ QObject::connect(menu, &QMenu::aboutToHide,
+ q, [q, this]{ menuOpen = false; q->setDown(false); }, Qt::SingleShotConnection);
+ menu->popup(menuPos);
}
QPoint QPushButtonPrivate::adjustedMenuPosition()
diff --git a/src/widgets/widgets/qpushbutton.h b/src/widgets/widgets/qpushbutton.h
index 6162d6dc80..3c420b5313 100644
--- a/src/widgets/widgets/qpushbutton.h
+++ b/src/widgets/widgets/qpushbutton.h
@@ -62,14 +62,9 @@ protected:
bool hitButton(const QPoint &pos) const override;
QPushButton(QPushButtonPrivate &dd, QWidget* parent = nullptr);
-public:
-
private:
Q_DISABLE_COPY(QPushButton)
Q_DECLARE_PRIVATE(QPushButton)
-#if QT_CONFIG(menu)
- Q_PRIVATE_SLOT(d_func(), void _q_popupPressed())
-#endif
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qpushbutton_p.h b/src/widgets/widgets/qpushbutton_p.h
index 4c97663343..0817589baf 100644
--- a/src/widgets/widgets/qpushbutton_p.h
+++ b/src/widgets/widgets/qpushbutton_p.h
@@ -7,6 +7,8 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "private/qabstractbutton_p.h"
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(pushbutton);
//
@@ -43,7 +45,7 @@ public:
QPoint adjustedMenuPosition();
#endif
void resetLayoutItemMargins();
- void _q_popupPressed();
+ void popupPressed();
#if QT_CONFIG(dialog)
QDialog *dialogParent() const;
#else
diff --git a/src/widgets/widgets/qradiobutton.cpp b/src/widgets/widgets/qradiobutton.cpp
index e34b04e5ee..af1bd3f649 100644
--- a/src/widgets/widgets/qradiobutton.cpp
+++ b/src/widgets/widgets/qradiobutton.cpp
@@ -82,7 +82,7 @@ void QRadioButtonPrivate::init()
setDown(), isDown(), autoRepeat(), group(), setAutoRepeat(),
toggle(), pressed(), released(), clicked(), and toggled().
- \sa QPushButton, QToolButton, QCheckBox, {Group Box Example}
+ \sa QPushButton, QToolButton, QCheckBox
*/
diff --git a/src/widgets/widgets/qscrollarea.cpp b/src/widgets/widgets/qscrollarea.cpp
index 00e2f42a81..efbf4da07f 100644
--- a/src/widgets/widgets/qscrollarea.cpp
+++ b/src/widgets/widgets/qscrollarea.cpp
@@ -91,11 +91,7 @@ QT_BEGIN_NAMESPACE
cause the size of the scroll area to be updated whenever the
contents of the layout changes.
- For a complete example using the QScrollArea class, see the \l
- {widgets/imageviewer}{Image Viewer} example. The example shows how
- to combine QLabel and QScrollArea to display an image.
-
- \sa QAbstractScrollArea, QScrollBar, {Image Viewer Example}
+ \sa QAbstractScrollArea, QScrollBar
*/
diff --git a/src/widgets/widgets/qscrollarea_p.h b/src/widgets/widgets/qscrollarea_p.h
index 8d066e9e17..a599fa8c36 100644
--- a/src/widgets/widgets/qscrollarea_p.h
+++ b/src/widgets/widgets/qscrollarea_p.h
@@ -20,6 +20,8 @@
#include "private/qabstractscrollarea_p.h"
#include <QtWidgets/qscrollbar.h>
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(scrollarea);
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/widgets/qscrollbar.cpp b/src/widgets/widgets/qscrollbar.cpp
index ed456c56b8..789cffba99 100644
--- a/src/widgets/widgets/qscrollbar.cpp
+++ b/src/widgets/widgets/qscrollbar.cpp
@@ -12,7 +12,10 @@
#if QT_CONFIG(menu)
#include "qmenu.h"
#endif
+
#include <QtCore/qelapsedtimer.h>
+#include <QtCore/qpointer.h>
+
#if QT_CONFIG(accessibility)
#include "qaccessible.h"
@@ -189,7 +192,9 @@ void QScrollBarPrivate::setTransient(bool value)
if (transient != value) {
transient = value;
if (q->isVisible()) {
- if (q->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, q))
+ QStyleOptionSlider opt;
+ q->initStyleOption(&opt);
+ if (q->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, q))
q->update();
} else if (!transient) {
q->show();
@@ -200,7 +205,9 @@ void QScrollBarPrivate::setTransient(bool value)
void QScrollBarPrivate::flash()
{
Q_Q(QScrollBar);
- if (!flashed && q->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, q)) {
+ QStyleOptionSlider opt;
+ q->initStyleOption(&opt);
+ if (!flashed && q->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, q)) {
flashed = true;
if (!q->isVisible())
q->show();
@@ -284,7 +291,7 @@ void QScrollBar::initStyleOption(QStyleOptionSlider *option) const
option->upsideDown = d->invertedAppearance;
if (d->orientation == Qt::Horizontal)
option->state |= QStyle::State_Horizontal;
- if ((d->flashed || !d->transient) && style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, this))
+ if ((d->flashed || !d->transient) && style()->styleHint(QStyle::SH_ScrollBar_Transient, option, this))
option->state |= QStyle::State_On;
}
@@ -341,7 +348,9 @@ void QScrollBarPrivate::init()
invertedControls = true;
pressedControl = hoverControl = QStyle::SC_None;
pointerOutsidePressedControl = false;
- transient = q->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, q);
+ QStyleOption opt;
+ opt.initFrom(q);
+ transient = q->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, q);
flashed = false;
flashTimer = 0;
q->setFocusPolicy(Qt::NoFocus);
@@ -435,12 +444,17 @@ bool QScrollBar::event(QEvent *event)
if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
d_func()->updateHoverControl(he->position().toPoint());
break;
- case QEvent::StyleChange:
- d_func()->setTransient(style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, this));
+ case QEvent::StyleChange: {
+ QStyleOptionSlider opt;
+ initStyleOption(&opt);
+ d_func()->setTransient(style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, this));
break;
+ }
case QEvent::Timer:
if (static_cast<QTimerEvent *>(event)->timerId() == d->flashTimer) {
- if (d->flashed && style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, this)) {
+ QStyleOptionSlider opt;
+ initStyleOption(&opt);
+ if (d->flashed && style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, this)) {
d->flashed = false;
update();
}
diff --git a/src/widgets/widgets/qsizegrip.cpp b/src/widgets/widgets/qsizegrip.cpp
index 8ffcb0081b..2500983450 100644
--- a/src/widgets/widgets/qsizegrip.cpp
+++ b/src/widgets/widgets/qsizegrip.cpp
@@ -18,6 +18,8 @@
#include <qpa/qplatformtheme.h>
#include <QtWidgets/qabstractscrollarea.h>
+#include <QtCore/qpointer.h>
+
QT_BEGIN_NAMESPACE
static QWidget *qt_sizegrip_topLevelWidget(QWidget* w)
@@ -73,7 +75,7 @@ public:
void _q_showIfNotHidden()
{
Q_Q(QSizeGrip);
- bool showSizeGrip = !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide));
+ bool showSizeGrip = !isExplicitlyHidden();
updateTopLevelWidget();
if (tlw && showSizeGrip) {
Qt::WindowStates sizeGripNotVisibleState = Qt::WindowFullScreen;
@@ -449,7 +451,7 @@ void QSizeGrip::setVisible(bool visible)
bool QSizeGrip::eventFilter(QObject *o, QEvent *e)
{
Q_D(QSizeGrip);
- if ((isHidden() && testAttribute(Qt::WA_WState_ExplicitShowHide))
+ if (d->isExplicitlyHidden()
|| e->type() != QEvent::WindowStateChange
|| o != d->tlw) {
return QWidget::eventFilter(o, e);
diff --git a/src/widgets/widgets/qspinbox.cpp b/src/widgets/widgets/qspinbox.cpp
index 5178763bc1..73946d54a9 100644
--- a/src/widgets/widgets/qspinbox.cpp
+++ b/src/widgets/widgets/qspinbox.cpp
@@ -132,12 +132,9 @@ public:
for a custom spin box that allows the user to enter icon sizes
(e.g., "32 x 32"):
- \snippet widgets/icons/iconsizespinbox.cpp 1
+ \snippet code/src_gui_widgets_qspinbox.cpp 8
\codeline
- \snippet widgets/icons/iconsizespinbox.cpp 2
-
- See the \l{widgets/icons}{Icons} example for the full source
- code.
+ \snippet code/src_gui_widgets_qspinbox.cpp 9
\sa QDoubleSpinBox, QDateTimeEdit, QSlider, {Spin Boxes Example}
*/
diff --git a/src/widgets/widgets/qsplashscreen.cpp b/src/widgets/widgets/qsplashscreen.cpp
index 040b7424cf..fcd09908cd 100644
--- a/src/widgets/widgets/qsplashscreen.cpp
+++ b/src/widgets/widgets/qsplashscreen.cpp
@@ -32,6 +32,8 @@ public:
int currAlign;
inline QSplashScreenPrivate();
+
+ void handlePaintEvent();
};
/*!
@@ -67,9 +69,9 @@ public:
\snippet qsplashscreen/main.cpp 1
The user can hide the splash screen by clicking on it with the
- mouse. Since the splash screen is typically displayed before the
- event loop has started running, it is necessary to periodically
- call QCoreApplication::processEvents() to receive the mouse clicks.
+ mouse. For mouse handling to work, call QApplication::processEvents()
+ periodically during startup.
+
It is sometimes useful to update the splash screen with messages,
for example, announcing connections established or modules loaded
@@ -201,18 +203,21 @@ void QSplashScreen::clearMessage()
repaint();
}
-// A copy of Qt Test's qWaitForWindowExposed() and qSleep().
-inline static bool waitForWindowExposed(QWindow *window, int timeout = 1000)
+static bool waitForWidgetMapped(QWidget *widget, int timeout = 1000)
{
enum { TimeOutMs = 10 };
+ auto isMapped = [widget](){
+ return widget->windowHandle() && widget->windowHandle()->isVisible();
+ };
+
QElapsedTimer timer;
timer.start();
- while (!window->isExposed()) {
+ while (!isMapped()) {
const int remaining = timeout - int(timer.elapsed());
if (remaining <= 0)
break;
QCoreApplication::processEvents(QEventLoop::AllEvents, remaining);
- QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
+ QCoreApplication::sendPostedEvents();
#if defined(Q_OS_WIN)
Sleep(uint(TimeOutMs));
#else
@@ -220,7 +225,7 @@ inline static bool waitForWindowExposed(QWindow *window, int timeout = 1000)
nanosleep(&ts, nullptr);
#endif
}
- return window->isExposed();
+ return isMapped();
}
/*!
@@ -233,7 +238,7 @@ void QSplashScreen::finish(QWidget *mainWin)
if (mainWin) {
if (!mainWin->windowHandle())
mainWin->createWinId();
- waitForWindowExposed(mainWin->windowHandle());
+ waitForWidgetMapped(mainWin);
}
close();
}
@@ -311,18 +316,33 @@ void QSplashScreen::drawContents(QPainter *painter)
}
}
+void QSplashScreenPrivate::handlePaintEvent()
+{
+ Q_Q(QSplashScreen);
+ QPainter painter(q);
+ painter.setRenderHints(QPainter::SmoothPixmapTransform);
+ painter.setLayoutDirection(q->layoutDirection());
+ if (!pixmap.isNull())
+ painter.drawPixmap(QPoint(), pixmap);
+ q->drawContents(&painter);
+}
+
/*! \reimp */
bool QSplashScreen::event(QEvent *e)
{
- if (e->type() == QEvent::Paint) {
- Q_D(QSplashScreen);
- QPainter painter(this);
- painter.setRenderHints(QPainter::SmoothPixmapTransform);
- painter.setLayoutDirection(layoutDirection());
- if (!d->pixmap.isNull())
- painter.drawPixmap(QPoint(), d->pixmap);
- drawContents(&painter);
+ Q_D(QSplashScreen);
+
+ switch (e->type()) {
+ case QEvent::Paint:
+ d->handlePaintEvent();
+ break;
+ case QEvent::Show:
+ waitForWidgetMapped(this);
+ break;
+ default:
+ break;
}
+
return QWidget::event(e);
}
diff --git a/src/widgets/widgets/qsplitter.cpp b/src/widgets/widgets/qsplitter.cpp
index 84c3799494..d0519a56a2 100644
--- a/src/widgets/widgets/qsplitter.cpp
+++ b/src/widgets/widgets/qsplitter.cpp
@@ -709,7 +709,7 @@ void QSplitterPrivate::setSizes_helper(const QList<int> &sizes, bool clampNegati
bool QSplitterPrivate::shouldShowWidget(const QWidget *w) const
{
Q_Q(const QSplitter);
- return q->isVisible() && !(w->isHidden() && w->testAttribute(Qt::WA_WState_ExplicitShowHide));
+ return q->isVisible() && !QWidgetPrivate::get(w)->isExplicitlyHidden();
}
void QSplitterPrivate::setGeo(QSplitterLayoutStruct *sls, int p, int s, bool allowCollapse)
diff --git a/src/widgets/widgets/qsplitter_p.h b/src/widgets/widgets/qsplitter_p.h
index 9fbd3ea520..5d5723a957 100644
--- a/src/widgets/widgets/qsplitter_p.h
+++ b/src/widgets/widgets/qsplitter_p.h
@@ -18,6 +18,8 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "private/qframe_p.h"
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(splitter);
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/widgets/qstackedwidget.cpp b/src/widgets/widgets/qstackedwidget.cpp
index 938cc22ee8..9cecee2ef8 100644
--- a/src/widgets/widgets/qstackedwidget.cpp
+++ b/src/widgets/widgets/qstackedwidget.cpp
@@ -15,7 +15,6 @@ class QStackedWidgetPrivate : public QFramePrivate
public:
QStackedWidgetPrivate():layout(nullptr){}
QStackedLayout *layout;
- bool blockChildAdd;
};
/*!
@@ -99,8 +98,10 @@ QStackedWidget::QStackedWidget(QWidget *parent)
{
Q_D(QStackedWidget);
d->layout = new QStackedLayout(this);
- connect(d->layout, SIGNAL(widgetRemoved(int)), this, SIGNAL(widgetRemoved(int)));
- connect(d->layout, SIGNAL(currentChanged(int)), this, SIGNAL(currentChanged(int)));
+ connect(d->layout, &QStackedLayout::widgetRemoved,
+ this, &QStackedWidget::widgetRemoved);
+ connect(d->layout, &QStackedLayout::currentChanged,
+ this, &QStackedWidget::currentChanged);
}
/*!
diff --git a/src/widgets/widgets/qstatusbar.cpp b/src/widgets/widgets/qstatusbar.cpp
index 9a9879a48d..e398f52ac4 100644
--- a/src/widgets/widgets/qstatusbar.cpp
+++ b/src/widgets/widgets/qstatusbar.cpp
@@ -151,12 +151,12 @@ QRect QStatusBarPrivate::messageRect() const
Use the showMessage() slot to display a \e temporary message:
- \snippet mainwindows/dockwidgets/mainwindow.cpp 8
+ \snippet code/src_gui_widgets_qstatusbar.cpp 1
To remove a temporary message, use the clearMessage() slot, or set
a time limit when calling showMessage(). For example:
- \snippet mainwindows/dockwidgets/mainwindow.cpp 3
+ \snippet code/src_gui_widgets_qstatusbar.cpp 2
Use the currentMessage() function to retrieve the temporary
message currently shown. The QStatusBar class also provide the
@@ -179,7 +179,7 @@ QRect QStatusBarPrivate::messageRect() const
\image fusion-statusbar-sizegrip.png A status bar shown in the Fusion widget style
- \sa QMainWindow, QStatusTipEvent, {Qt Widgets - Application Example}
+ \sa QMainWindow, QStatusTipEvent
*/
@@ -271,7 +271,7 @@ int QStatusBar::insertWidget(int index, QWidget *widget, int stretch)
widget->hide();
reformat();
- if (!widget->isHidden() || !widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
+ if (!QWidgetPrivate::get(widget)->isExplicitlyHidden())
widget->show();
return index;
@@ -286,7 +286,7 @@ int QStatusBar::insertWidget(int index, QWidget *widget, int stretch)
minimum of space.
Permanently means that the widget may not be obscured by temporary
- messages. It is is located at the far right of the status bar.
+ messages. It is located at the far right of the status bar.
\sa insertPermanentWidget(), removeWidget(), addWidget()
*/
@@ -298,7 +298,6 @@ void QStatusBar::addPermanentWidget(QWidget * widget, int stretch)
insertPermanentWidget(d_func()->items.size(), widget, stretch);
}
-
/*!
\since 4.2
@@ -313,7 +312,7 @@ void QStatusBar::addPermanentWidget(QWidget * widget, int stretch)
minimum of space.
Permanently means that the widget may not be obscured by temporary
- messages. It is is located at the far right of the status bar.
+ messages. It is located at the far right of the status bar.
\sa addPermanentWidget(), removeWidget(), addWidget()
*/
@@ -333,7 +332,7 @@ int QStatusBar::insertPermanentWidget(int index, QWidget *widget, int stretch)
d->items.insert(index, item);
reformat();
- if (!widget->isHidden() || !widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
+ if (!QWidgetPrivate::get(widget)->isExplicitlyHidden())
widget->show();
return index;
@@ -355,19 +354,10 @@ void QStatusBar::removeWidget(QWidget *widget)
return;
Q_D(QStatusBar);
- bool found = false;
- for (int i = 0; i < d->items.size(); ++i) {
- const auto &item = d->items.at(i);
- if (item.widget == widget) {
- d->items.removeAt(i);
- item.widget->hide();
- found = true;
- break;
- }
- }
-
- if (found)
+ if (d->items.removeIf([widget](const auto &item) { return item.widget == widget; })) {
+ widget->hide();
reformat();
+ }
#if defined(QT_DEBUG)
else
qDebug("QStatusBar::removeWidget(): Widget not found.");
@@ -504,7 +494,7 @@ void QStatusBar::showMessage(const QString &message, int timeout)
if (timeout > 0) {
if (!d->timer) {
d->timer = new QTimer(this);
- connect(d->timer, SIGNAL(timeout()), this, SLOT(clearMessage()));
+ connect(d->timer, &QTimer::timeout, this, &QStatusBar::clearMessage);
}
d->timer->start(timeout);
} else if (d->timer) {
@@ -530,7 +520,7 @@ void QStatusBar::clearMessage()
if (d->tempItem.isEmpty())
return;
if (d->timer) {
- qDeleteInEventHandler(d->timer);
+ delete d->timer;
d->timer = nullptr;
}
d->tempItem.clear();
diff --git a/src/widgets/widgets/qtabbar.cpp b/src/widgets/widgets/qtabbar.cpp
index 0b1190ebf1..0b463840ae 100644
--- a/src/widgets/widgets/qtabbar.cpp
+++ b/src/widgets/widgets/qtabbar.cpp
@@ -71,14 +71,6 @@ void QMovableTabWidget::paintEvent(QPaintEvent *e)
p.drawPixmap(0, 0, m_pixmap);
}
-inline static bool verticalTabs(QTabBar::Shape shape)
-{
- return shape == QTabBar::RoundedWest
- || shape == QTabBar::RoundedEast
- || shape == QTabBar::TriangularWest
- || shape == QTabBar::TriangularEast;
-}
-
void QTabBarPrivate::updateMacBorderMetrics()
{
#if defined(Q_OS_MACOS)
@@ -283,9 +275,9 @@ void QTabBar::initStyleOption(QStyleOptionTab *option, int tabIndex) const
returns the visual geometry of a single tab.
\table 100%
- \row \li \inlineimage fusion-tabbar.png Screenshot of a Fusion style tab bar
+ \row \li \inlineimage {fusion-tabbar.png} {Screenshot of a Fusion style tab bar}
\li A tab bar shown in the \l{Qt Widget Gallery}{Fusion widget style}.
- \row \li \inlineimage fusion-tabbar-truncated.png Screenshot of a truncated Fusion tab bar
+ \row \li \inlineimage {fusion-tabbar-truncated.png} {Screenshot of a truncated Fusion tab bar}
\li A truncated tab bar shown in the Fusion widget style.
\endtable
@@ -374,12 +366,14 @@ void QTabBarPrivate::init()
leftB = new QToolButton(q);
leftB->setObjectName(u"ScrollLeftButton"_s);
leftB->setAutoRepeat(true);
- QObject::connect(leftB, SIGNAL(clicked()), q, SLOT(_q_scrollTabs()));
+ QObjectPrivate::connect(leftB, &QToolButton::clicked,
+ this, &QTabBarPrivate::scrollTabs);
leftB->hide();
rightB = new QToolButton(q);
rightB->setObjectName(u"ScrollRightButton"_s);
rightB->setAutoRepeat(true);
- QObject::connect(rightB, SIGNAL(clicked()), q, SLOT(_q_scrollTabs()));
+ QObjectPrivate::connect(rightB, &QToolButton::clicked,
+ this, &QTabBarPrivate::scrollTabs);
rightB->hide();
#ifdef QT_KEYPAD_NAVIGATION
if (QApplicationPrivate::keypadNavigationEnabled()) {
@@ -534,7 +528,6 @@ void QTabBarPrivate::layoutTabs()
if (useScrollButtons && tabList.size() && last > available) {
const QRect scrollRect = normalizedScrollRect(0);
- scrollOffset = -scrollRect.left();
Q_Q(QTabBar);
QStyleOption opt;
@@ -571,10 +564,9 @@ void QTabBarPrivate::layoutTabs()
leftB->show();
rightB->setGeometry(scrollButtonRightRect);
- rightB->setEnabled(last - scrollOffset > scrollRect.x() + scrollRect.width());
+ rightB->setEnabled(last + scrollRect.left() > scrollRect.x() + scrollRect.width());
rightB->show();
} else {
- scrollOffset = 0;
rightB->hide();
leftB->hide();
}
@@ -591,6 +583,11 @@ QRect QTabBarPrivate::normalizedScrollRect(int index)
// tab bar itself is in a different orientation.
Q_Q(QTabBar);
+ // If scrollbuttons are not visible, then there's no tear either, and
+ // the entire widget is the scroll rect.
+ if (leftB->isHidden())
+ return verticalTabs(shape) ? q->rect().transposed() : q->rect();
+
QStyleOptionTab opt;
q->initStyleOption(&opt, currentIndex);
opt.rect = q->rect();
@@ -670,25 +667,33 @@ int QTabBarPrivate::hoveredTabIndex() const
void QTabBarPrivate::makeVisible(int index)
{
Q_Q(QTabBar);
- if (!validIndex(index) || leftB->isHidden())
+ if (!validIndex(index))
return;
const QRect tabRect = tabList.at(index)->rect;
const int oldScrollOffset = scrollOffset;
const bool horiz = !verticalTabs(shape);
+ const int available = horiz ? q->width() : q->height();
const int tabStart = horiz ? tabRect.left() : tabRect.top();
const int tabEnd = horiz ? tabRect.right() : tabRect.bottom();
const int lastTabEnd = horiz ? tabList.constLast()->rect.right() : tabList.constLast()->rect.bottom();
const QRect scrollRect = normalizedScrollRect(index);
+ const QRect entireScrollRect = normalizedScrollRect(0); // ignore tears
const int scrolledTabBarStart = qMax(1, scrollRect.left() + scrollOffset);
const int scrolledTabBarEnd = qMin(lastTabEnd - 1, scrollRect.right() + scrollOffset);
- if (tabStart < scrolledTabBarStart) {
+ if (available >= lastTabEnd) {
+ // the entire tabbar fits, reset scroll
+ scrollOffset = 0;
+ } else if (tabStart < scrolledTabBarStart) {
// Tab is outside on the left, so scroll left.
scrollOffset = tabStart - scrollRect.left();
} else if (tabEnd > scrolledTabBarEnd) {
// Tab is outside on the right, so scroll right.
- scrollOffset = tabEnd - scrollRect.right();
+ scrollOffset = qMax(0, tabEnd - scrollRect.right());
+ } else if (scrollOffset + entireScrollRect.width() > lastTabEnd + 1) {
+ // fill any free space on the right without overshooting
+ scrollOffset = qMax(0, lastTabEnd - entireScrollRect.width() + 1);
}
leftB->setEnabled(scrollOffset > -scrollRect.left());
@@ -762,7 +767,7 @@ void QTabBarPrivate::autoHideTabs()
q->setVisible(q->count() > 1);
}
-void QTabBarPrivate::_q_closeTab()
+void QTabBarPrivate::closeTab()
{
Q_Q(QTabBar);
QObject *object = q->sender();
@@ -785,7 +790,7 @@ void QTabBarPrivate::_q_closeTab()
emit q->tabCloseRequested(tabToClose);
}
-void QTabBarPrivate::_q_scrollTabs()
+void QTabBarPrivate::scrollTabs()
{
Q_Q(QTabBar);
const QObject *sender = q->sender();
@@ -975,7 +980,8 @@ int QTabBar::insertTab(int index, const QIcon& icon, const QString &text)
initStyleOption(&opt, index);
ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, this);
QAbstractButton *closeButton = new CloseButton(this);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(_q_closeTab()));
+ QObjectPrivate::connect(closeButton, &CloseButton::clicked,
+ d, &QTabBarPrivate::closeTab);
setTabButton(index, closeSide, closeButton);
}
@@ -1410,7 +1416,10 @@ void QTabBar::setCurrentIndex(int index)
if (tabRect(index).size() != tabSizeHint(index))
d->layoutTabs();
update();
- d->makeVisible(index);
+ if (!isVisible())
+ d->layoutDirty = true;
+ else
+ d->makeVisible(index);
if (d->validIndex(oldIndex)) {
tab->lastTab = oldIndex;
d->layoutTab(oldIndex);
@@ -1645,6 +1654,8 @@ void QTabBar::showEvent(QShowEvent *)
d->refresh();
if (!d->validIndex(d->currentIndex))
setCurrentIndex(0);
+ else
+ d->makeVisible(d->currentIndex);
d->updateMacBorderMetrics();
}
@@ -1778,6 +1789,8 @@ void QTabBar::resizeEvent(QResizeEvent *)
Q_D(QTabBar);
if (d->layoutDirty)
updateGeometry();
+
+ // when resizing, we want to keep the scroll offset as much as possible
d->layoutTabs();
d->makeVisible(d->currentIndex);
@@ -1873,21 +1886,30 @@ void QTabBar::paintEvent(QPaintEvent *)
QStyleOptionTab tabOption;
const auto tab = d->tabList.at(selected);
initStyleOption(&tabOption, selected);
+
if (d->paintWithOffsets && tab->dragOffset != 0) {
+ // if the drag offset is != 0, a move is in progress (drag or animation)
+ // => set the tab position to Moving to preserve the rect
+ tabOption.position = QStyleOptionTab::TabPosition::Moving;
+
if (vertical)
tabOption.rect.moveTop(tabOption.rect.y() + tab->dragOffset);
else
tabOption.rect.moveLeft(tabOption.rect.x() + tab->dragOffset);
}
- if (!d->dragInProgress)
- p.drawControl(QStyle::CE_TabBarTab, tabOption);
- else {
- int taboverlap = style()->pixelMetric(QStyle::PM_TabBarTabOverlap, nullptr, this);
- if (verticalTabs(d->shape))
- d->movingTab->setGeometry(tabOption.rect.adjusted(0, -taboverlap, 0, taboverlap));
- else
- d->movingTab->setGeometry(tabOption.rect.adjusted(-taboverlap, 0, taboverlap, 0));
- }
+
+ // Calculate the rect of a moving tab
+ const int taboverlap = style()->pixelMetric(QStyle::PM_TabBarTabOverlap, nullptr, this);
+ const QRect &movingRect = verticalTabs(d->shape)
+ ? tabOption.rect.adjusted(0, -taboverlap, 0, taboverlap)
+ : tabOption.rect.adjusted(-taboverlap, 0, taboverlap, 0);
+
+ // If a drag is in process, set the moving tab's geometry here
+ // (in an animation, it is already set)
+ if (d->dragInProgress)
+ d->movingTab->setGeometry(movingRect);
+
+ p.drawControl(QStyle::CE_TabBarTab, tabOption);
}
// Only draw the tear indicator if necessary. Most of the time we don't need too.
@@ -2194,7 +2216,8 @@ void QTabBar::mouseMoveEvent(QMouseEvent *event)
}
}
// Buttons needs to follow the dragged tab
- d->layoutTab(d->pressedIndex);
+ if (d->pressedIndex != -1)
+ d->layoutTab(d->pressedIndex);
update();
}
@@ -2226,7 +2249,7 @@ void QTabBarPrivate::setupMovableTab()
QStyleOptionTab tab;
q->initStyleOption(&tab, pressedIndex);
- tab.position = QStyleOptionTab::OnlyOneTab;
+ tab.position = QStyleOptionTab::Moving;
if (verticalTabs(shape))
tab.rect.moveTopLeft(QPoint(0, taboverlap));
else
@@ -2416,7 +2439,7 @@ void QTabBarPrivate::setCurrentNextEnabledIndex(int offset)
{
Q_Q(QTabBar);
for (int index = currentIndex + offset; validIndex(index); index += offset) {
- if (tabList.at(index)->enabled) {
+ if (tabList.at(index)->enabled && tabList.at(index)->visible) {
q->setCurrentIndex(index);
break;
}
@@ -2562,7 +2585,8 @@ void QTabBar::setTabsClosable(bool closable)
continue;
newButtons = true;
QAbstractButton *closeButton = new CloseButton(this);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(_q_closeTab()));
+ QObjectPrivate::connect(closeButton, &CloseButton::clicked,
+ d, &QTabBarPrivate::closeTab);
setTabButton(i, closeSide, closeButton);
}
if (newButtons)
diff --git a/src/widgets/widgets/qtabbar.h b/src/widgets/widgets/qtabbar.h
index 2d3179e2d0..2759d5a318 100644
--- a/src/widgets/widgets/qtabbar.h
+++ b/src/widgets/widgets/qtabbar.h
@@ -185,8 +185,6 @@ protected:
private:
Q_DISABLE_COPY(QTabBar)
Q_DECLARE_PRIVATE(QTabBar)
- Q_PRIVATE_SLOT(d_func(), void _q_scrollTabs())
- Q_PRIVATE_SLOT(d_func(), void _q_closeTab())
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qtabbar_p.h b/src/widgets/widgets/qtabbar_p.h
index a421836b93..d76f439bd7 100644
--- a/src/widgets/widgets/qtabbar_p.h
+++ b/src/widgets/widgets/qtabbar_p.h
@@ -187,8 +187,8 @@ public:
inline bool validIndex(int index) const { return index >= 0 && index < tabList.size(); }
void setCurrentNextEnabledIndex(int offset);
- void _q_scrollTabs();
- void _q_closeTab();
+ void scrollTabs();
+ void closeTab();
void moveTab(int index, int offset);
void moveTabFinished(int index);
@@ -245,6 +245,14 @@ public:
};
+constexpr inline bool verticalTabs(QTabBar::Shape shape) noexcept
+{
+ return shape == QTabBar::RoundedWest
+ || shape == QTabBar::RoundedEast
+ || shape == QTabBar::TriangularWest
+ || shape == QTabBar::TriangularEast;
+}
+
QT_END_NAMESPACE
#endif
diff --git a/src/widgets/widgets/qtabwidget.cpp b/src/widgets/widgets/qtabwidget.cpp
index 89e3d59a06..5e7c266ef6 100644
--- a/src/widgets/widgets/qtabwidget.cpp
+++ b/src/widgets/widgets/qtabwidget.cpp
@@ -156,9 +156,9 @@ public:
QTabWidgetPrivate();
~QTabWidgetPrivate();
void updateTabBarPosition();
- void _q_showTab(int);
- void _q_removeTab(int);
- void _q_tabMoved(int from, int to);
+ void showTab(int);
+ void removeTab(int);
+ void tabMoved(int from, int to);
void init();
bool isAutoHidden() const
{
@@ -197,7 +197,7 @@ void QTabWidgetPrivate::init()
// hack so that QMacStyle::layoutSpacing() can detect tab widget pages
stack->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred, QSizePolicy::TabWidget));
- QObject::connect(stack, SIGNAL(widgetRemoved(int)), q, SLOT(_q_removeTab(int)));
+ QObjectPrivate::connect(stack, &QStackedWidget::widgetRemoved, this, &QTabWidgetPrivate::removeTab);
QTabBar *tabBar = new QTabBar(q);
tabBar->setObjectName("qt_tabwidget_tabbar"_L1);
tabBar->setDrawBase(false);
@@ -720,17 +720,17 @@ void QTabWidget::setTabBar(QTabBar* tb)
delete d->tabs;
d->tabs = tb;
setFocusProxy(d->tabs);
- connect(d->tabs, SIGNAL(currentChanged(int)),
- this, SLOT(_q_showTab(int)));
- connect(d->tabs, SIGNAL(tabMoved(int,int)),
- this, SLOT(_q_tabMoved(int,int)));
- connect(d->tabs, SIGNAL(tabBarClicked(int)),
- this, SIGNAL(tabBarClicked(int)));
- connect(d->tabs, SIGNAL(tabBarDoubleClicked(int)),
- this, SIGNAL(tabBarDoubleClicked(int)));
+ QObjectPrivate::connect(d->tabs, &QTabBar::currentChanged,
+ d, &QTabWidgetPrivate::showTab);
+ QObjectPrivate::connect(d->tabs, &QTabBar::tabMoved,
+ d, &QTabWidgetPrivate::tabMoved);
+ connect(d->tabs, &QTabBar::tabBarClicked,
+ this, &QTabWidget::tabBarClicked);
+ connect(d->tabs, &QTabBar::tabBarDoubleClicked,
+ this, &QTabWidget::tabBarDoubleClicked);
if (d->tabs->tabsClosable())
- connect(d->tabs, SIGNAL(tabCloseRequested(int)),
- this, SIGNAL(tabCloseRequested(int)));
+ connect(d->tabs, &QTabBar::tabCloseRequested,
+ this, &QTabWidget::tabCloseRequested);
tb->setExpanding(!documentMode());
setUpLayout();
}
@@ -752,7 +752,7 @@ QTabBar* QTabWidget::tabBar() const
sized.
*/
-void QTabWidgetPrivate::_q_showTab(int index)
+void QTabWidgetPrivate::showTab(int index)
{
Q_Q(QTabWidget);
if (index < stack->count() && index >= 0)
@@ -760,7 +760,7 @@ void QTabWidgetPrivate::_q_showTab(int index)
emit q->currentChanged(index);
}
-void QTabWidgetPrivate::_q_removeTab(int index)
+void QTabWidgetPrivate::removeTab(int index)
{
Q_Q(QTabWidget);
tabs->removeTab(index);
@@ -768,7 +768,7 @@ void QTabWidgetPrivate::_q_removeTab(int index)
q->tabRemoved(index);
}
-void QTabWidgetPrivate::_q_tabMoved(int from, int to)
+void QTabWidgetPrivate::tabMoved(int from, int to)
{
const QSignalBlocker blocker(stack);
QWidget *w = stack->widget(from);
@@ -1139,7 +1139,7 @@ void QTabWidget::keyPressEvent(QKeyEvent *e)
) {
page = 0;
}
- if (d->tabs->isTabEnabled(page)) {
+ if (d->tabs->isTabEnabled(page) && d->tabs->isTabVisible(page)) {
setCurrentIndex(page);
break;
}
@@ -1407,6 +1407,20 @@ void QTabWidget::clear()
removeTab(0);
}
+QTabBar::Shape _q_tb_tabBarShapeFrom(QTabWidget::TabShape shape, QTabWidget::TabPosition position)
+{
+ const bool rounded = (shape == QTabWidget::Rounded);
+ if (position == QTabWidget::North)
+ return rounded ? QTabBar::RoundedNorth : QTabBar::TriangularNorth;
+ if (position == QTabWidget::South)
+ return rounded ? QTabBar::RoundedSouth : QTabBar::TriangularSouth;
+ if (position == QTabWidget::East)
+ return rounded ? QTabBar::RoundedEast : QTabBar::TriangularEast;
+ if (position == QTabWidget::West)
+ return rounded ? QTabBar::RoundedWest : QTabBar::TriangularWest;
+ return QTabBar::RoundedNorth;
+}
+
QT_END_NAMESPACE
#include "moc_qtabwidget.cpp"
diff --git a/src/widgets/widgets/qtabwidget.h b/src/widgets/widgets/qtabwidget.h
index 6188ea4999..c813f8d921 100644
--- a/src/widgets/widgets/qtabwidget.h
+++ b/src/widgets/widgets/qtabwidget.h
@@ -141,9 +141,6 @@ protected:
private:
Q_DECLARE_PRIVATE(QTabWidget)
Q_DISABLE_COPY(QTabWidget)
- Q_PRIVATE_SLOT(d_func(), void _q_showTab(int))
- Q_PRIVATE_SLOT(d_func(), void _q_removeTab(int))
- Q_PRIVATE_SLOT(d_func(), void _q_tabMoved(int, int))
void setUpLayout(bool = false);
};
diff --git a/src/widgets/widgets/qtextbrowser.cpp b/src/widgets/widgets/qtextbrowser.cpp
index 1cac46e8a8..2c01ed2b26 100644
--- a/src/widgets/widgets/qtextbrowser.cpp
+++ b/src/widgets/widgets/qtextbrowser.cpp
@@ -46,6 +46,11 @@ public:
, lastKeypadScrollValue(-1)
#endif
{}
+ ~QTextBrowserPrivate()
+ {
+ for (const QMetaObject::Connection &connection : connections)
+ QObject::disconnect(connection);
+ }
void init();
@@ -103,14 +108,14 @@ public:
QString findFile(const QUrl &name) const;
- inline void _q_documentModified()
+ inline void documentModified()
{
textOrSourceChanged = true;
forceLoadOnSourceChange = !currentURL.path().isEmpty();
}
- void _q_activateAnchor(const QString &href);
- void _q_highlightLink(const QString &href);
+ void activateAnchor(const QString &href);
+ void highlightLink(const QString &href);
void setSource(const QUrl &url, QTextDocument::ResourceType type);
@@ -129,6 +134,7 @@ public:
Q_Q(QTextBrowser);
emit q->highlighted(url);
}
+ std::array<QMetaObject::Connection, 3> connections;
};
Q_DECLARE_TYPEINFO(QTextBrowserPrivate::HistoryEntry, Q_RELOCATABLE_TYPE);
@@ -190,7 +196,7 @@ QUrl QTextBrowserPrivate::resolveUrl(const QUrl &url) const
return url;
}
-void QTextBrowserPrivate::_q_activateAnchor(const QString &href)
+void QTextBrowserPrivate::activateAnchor(const QString &href)
{
if (href.isEmpty())
return;
@@ -231,7 +237,7 @@ void QTextBrowserPrivate::_q_activateAnchor(const QString &href)
q->setSource(url);
}
-void QTextBrowserPrivate::_q_highlightLink(const QString &anchor)
+void QTextBrowserPrivate::highlightLink(const QString &anchor)
{
if (anchor.isEmpty()) {
#ifndef QT_NO_CURSOR
@@ -670,11 +676,14 @@ void QTextBrowserPrivate::init()
q->setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(q));
q->setUndoRedoEnabled(false);
viewport->setMouseTracking(true);
- QObject::connect(q->document(), SIGNAL(contentsChanged()), q, SLOT(_q_documentModified()));
- QObject::connect(control, SIGNAL(linkActivated(QString)),
- q, SLOT(_q_activateAnchor(QString)));
- QObject::connect(control, SIGNAL(linkHovered(QString)),
- q, SLOT(_q_highlightLink(QString)));
+ connections = {
+ QObjectPrivate::connect(q->document(), &QTextDocument::contentsChanged,
+ this, &QTextBrowserPrivate::documentModified),
+ QObjectPrivate::connect(control, &QWidgetTextControl::linkActivated,
+ this, &QTextBrowserPrivate::activateAnchor),
+ QObjectPrivate::connect(control, &QWidgetTextControl::linkHovered,
+ this, &QTextBrowserPrivate::highlightLink),
+ };
}
/*!
diff --git a/src/widgets/widgets/qtextbrowser.h b/src/widgets/widgets/qtextbrowser.h
index 1a6cd412d1..f8e9c0c301 100644
--- a/src/widgets/widgets/qtextbrowser.h
+++ b/src/widgets/widgets/qtextbrowser.h
@@ -82,9 +82,6 @@ protected:
private:
Q_DISABLE_COPY(QTextBrowser)
Q_DECLARE_PRIVATE(QTextBrowser)
- Q_PRIVATE_SLOT(d_func(), void _q_documentModified())
- Q_PRIVATE_SLOT(d_func(), void _q_activateAnchor(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_highlightLink(const QString &))
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qtextedit.cpp b/src/widgets/widgets/qtextedit.cpp
index f3d1d3e511..90884dd438 100644
--- a/src/widgets/widgets/qtextedit.cpp
+++ b/src/widgets/widgets/qtextedit.cpp
@@ -88,8 +88,7 @@ QTextEditPrivate::QTextEditPrivate()
: control(nullptr),
autoFormatting(QTextEdit::AutoNone), tabChangesFocus(false),
lineWrap(QTextEdit::WidgetWidth), lineWrapColumnOrWidth(0),
- wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere), clickCausedFocus(0),
- textFormat(Qt::AutoText)
+ wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere), clickCausedFocus(0)
{
ignoreAutomaticScrollbarAdjustment = false;
preferRichText = false;
@@ -97,6 +96,12 @@ QTextEditPrivate::QTextEditPrivate()
inDrag = false;
}
+QTextEditPrivate::~QTextEditPrivate()
+{
+ for (const QMetaObject::Connection &connection : connections)
+ QObject::disconnect(connection);
+}
+
void QTextEditPrivate::createAutoBulletList()
{
QTextCursor cursor = control->textCursor();
@@ -123,24 +128,34 @@ void QTextEditPrivate::init(const QString &html)
control = new QTextEditControl(q);
control->setPalette(q->palette());
- QObject::connect(control, SIGNAL(microFocusChanged()), q, SLOT(updateMicroFocus()));
- QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)), q, SLOT(_q_adjustScrollbars()));
- QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(_q_repaintContents(QRectF)));
- QObject::connect(control, SIGNAL(visibilityRequest(QRectF)), q, SLOT(_q_ensureVisible(QRectF)));
- QObject::connect(control, SIGNAL(currentCharFormatChanged(QTextCharFormat)),
- q, SLOT(_q_currentCharFormatChanged(QTextCharFormat)));
-
- QObject::connect(control, SIGNAL(textChanged()), q, SIGNAL(textChanged()));
- QObject::connect(control, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
- QObject::connect(control, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
- QObject::connect(control, SIGNAL(copyAvailable(bool)), q, SIGNAL(copyAvailable(bool)));
- QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));
- QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SLOT(_q_cursorPositionChanged()));
-#if QT_CONFIG(cursor)
- QObject::connect(control, SIGNAL(blockMarkerHovered(QTextBlock)), q, SLOT(_q_hoveredBlockWithMarkerChanged(QTextBlock)));
-#endif
-
- QObject::connect(control, SIGNAL(textChanged()), q, SLOT(updateMicroFocus()));
+ connections = {
+ QObjectPrivate::connect(control, &QTextEditControl::documentSizeChanged,
+ this, &QTextEditPrivate::adjustScrollbars),
+ QObjectPrivate::connect(control, &QTextEditControl::updateRequest,
+ this, &QTextEditPrivate::repaintContents),
+ QObjectPrivate::connect(control, &QTextEditControl::visibilityRequest,
+ this, &QTextEditPrivate::ensureVisible),
+ QObjectPrivate::connect(control, &QTextEditControl::blockMarkerHovered,
+ this, &QTextEditPrivate::hoveredBlockWithMarkerChanged),
+ QObjectPrivate::connect(control, &QTextEditControl::cursorPositionChanged,
+ this, &QTextEditPrivate::cursorPositionChanged),
+ QObject::connect(control, &QTextEditControl::microFocusChanged,
+ q, [q]() { q->updateMicroFocus(); }),
+ QObject::connect(control, &QTextEditControl::currentCharFormatChanged,
+ q, &QTextEdit::currentCharFormatChanged),
+ QObject::connect(control, &QTextEditControl::textChanged,
+ q, &QTextEdit::textChanged),
+ QObject::connect(control, &QTextEditControl::undoAvailable,
+ q, &QTextEdit::undoAvailable),
+ QObject::connect(control, &QTextEditControl::redoAvailable,
+ q, &QTextEdit::redoAvailable),
+ QObject::connect(control, &QTextEditControl::copyAvailable,
+ q, &QTextEdit::copyAvailable),
+ QObject::connect(control, &QTextEditControl::selectionChanged,
+ q, &QTextEdit::selectionChanged),
+ QObject::connect(control, &QTextEditControl::textChanged,
+ q, [q]() { q->updateMicroFocus(); }),
+ };
QTextDocument *doc = control->document();
// set a null page size initially to avoid any relayouting until the textedit
@@ -170,7 +185,7 @@ void QTextEditPrivate::init(const QString &html)
#endif
}
-void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
+void QTextEditPrivate::repaintContents(const QRectF &contentsRect)
{
if (!contentsRect.isValid()) {
viewport->update();
@@ -188,7 +203,7 @@ void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
viewport->update(r);
}
-void QTextEditPrivate::_q_cursorPositionChanged()
+void QTextEditPrivate::cursorPositionChanged()
{
Q_Q(QTextEdit);
emit q->cursorPositionChanged();
@@ -198,9 +213,9 @@ void QTextEditPrivate::_q_cursorPositionChanged()
#endif
}
-#if QT_CONFIG(cursor)
-void QTextEditPrivate::_q_hoveredBlockWithMarkerChanged(const QTextBlock &block)
+void QTextEditPrivate::hoveredBlockWithMarkerChanged(const QTextBlock &block)
{
+#if QT_CONFIG(cursor)
Q_Q(QTextEdit);
Qt::CursorShape cursor = cursorToRestoreAfterHover;
if (block.isValid() && !q->isReadOnly()) {
@@ -212,8 +227,8 @@ void QTextEditPrivate::_q_hoveredBlockWithMarkerChanged(const QTextBlock &block)
}
}
viewport->setCursor(cursor);
-}
#endif
+}
void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode)
{
@@ -262,7 +277,7 @@ static QSize documentSize(QWidgetTextControl *control)
return docSize;
}
-void QTextEditPrivate::_q_adjustScrollbars()
+void QTextEditPrivate::adjustScrollbars()
{
if (ignoreAutomaticScrollbarAdjustment)
return;
@@ -312,12 +327,12 @@ void QTextEditPrivate::_q_adjustScrollbars()
#endif
// rect is in content coordinates
-void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
+void QTextEditPrivate::ensureVisible(const QRectF &_rect)
{
const QRect rect = _rect.toRect();
if ((vbar->isVisible() && vbar->maximum() < rect.bottom())
|| (hbar->isVisible() && hbar->maximum() < rect.right()))
- _q_adjustScrollbars();
+ adjustScrollbars();
const int visibleWidth = viewport->width();
const int visibleHeight = viewport->height();
const bool rtl = q_func()->isRightToLeft();
@@ -540,7 +555,7 @@ void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
of the movement keystrokes, for example, \e{Shift+Right}
will select the character to the right, and \e{Shift+Ctrl+Right} will select the word to the right, etc.
- \sa QTextDocument, QTextCursor, {Qt Widgets - Application Example},
+ \sa QTextDocument, QTextCursor,
{Syntax Highlighter Example}, {Rich Text Processing}
*/
@@ -713,7 +728,8 @@ QColor QTextEdit::textColor() const
QColor QTextEdit::textBackgroundColor() const
{
Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().background().color();
+ const QBrush &brush = d->control->textCursor().charFormat().background();
+ return brush.style() == Qt::NoBrush ? Qt::transparent : brush.color();
}
/*!
@@ -1064,30 +1080,38 @@ void QTextEdit::selectAll()
bool QTextEdit::event(QEvent *e)
{
Q_D(QTextEdit);
-#ifndef QT_NO_CONTEXTMENU
- if (e->type() == QEvent::ContextMenu
- && static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
- Q_D(QTextEdit);
- ensureCursorVisible();
- const QPoint cursorPos = cursorRect().center();
- QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
- ce.setAccepted(e->isAccepted());
- const bool result = QAbstractScrollArea::event(&ce);
- e->setAccepted(ce.isAccepted());
- return result;
- } else if (e->type() == QEvent::ShortcutOverride
- || e->type() == QEvent::ToolTip) {
+ switch (e->type()) {
+ case QEvent::ShortcutOverride:
+ case QEvent::ToolTip:
d->sendControlEvent(e);
- }
-#else
- Q_UNUSED(d);
+ break;
+ case QEvent::WindowActivate:
+ case QEvent::WindowDeactivate:
+ d->control->setPalette(palette());
+ break;
+#ifndef QT_NO_CONTEXTMENU
+ case QEvent::ContextMenu:
+ if (static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
+ ensureCursorVisible();
+ const QPoint cursorPos = cursorRect().center();
+ QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
+ ce.setAccepted(e->isAccepted());
+ const bool result = QAbstractScrollArea::event(&ce);
+ e->setAccepted(ce.isAccepted());
+ return result;
+ }
+ break;
#endif // QT_NO_CONTEXTMENU
#ifdef QT_KEYPAD_NAVIGATION
- if (e->type() == QEvent::EnterEditFocus || e->type() == QEvent::LeaveEditFocus) {
+ case QEvent::EnterEditFocus:
+ case QEvent::LeaveEditFocus:
if (QApplicationPrivate::keypadNavigationEnabled())
d->sendControlEvent(e);
- }
+ break;
#endif
+ default:
+ break;
+ }
return QAbstractScrollArea::event(e);
}
@@ -1477,7 +1501,7 @@ void QTextEdit::resizeEvent(QResizeEvent *e)
&& alignmentProperty.userType() == QMetaType::Bool
&& !alignmentProperty.toBool()) {
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
return;
}
}
@@ -1486,7 +1510,7 @@ void QTextEdit::resizeEvent(QResizeEvent *e)
&& e->oldSize().width() != e->size().width())
d->relayoutDocument();
else
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
}
void QTextEditPrivate::relayoutDocument()
@@ -1508,7 +1532,7 @@ void QTextEditPrivate::relayoutDocument()
else
lastUsedSize = layout->documentSize().toSize();
- // ignore calls to _q_adjustScrollbars caused by an emission of the
+ // ignore calls to adjustScrollbars caused by an emission of the
// usedSizeChanged() signal in the layout, as we're calling it
// later on our own anyway (or deliberately not) .
const bool oldIgnoreScrollbarAdjustment = ignoreAutomaticScrollbarAdjustment;
@@ -1547,7 +1571,7 @@ void QTextEditPrivate::relayoutDocument()
// its size. So a layout with less width _can_ take up less vertical space, too.
// If the wider case causes a vertical scroll bar to appear and the narrower one
// (narrower because the vertical scroll bar takes up horizontal space)) to disappear
- // again then we have an endless loop, as _q_adjustScrollBars sets new ranges on the
+ // again then we have an endless loop, as adjustScrollbars sets new ranges on the
// scroll bars, the QAbstractScrollArea will find out about it and try to show/hide
// the scroll bars again. That's why we try to detect this case here and break out.
//
@@ -1560,7 +1584,7 @@ void QTextEditPrivate::relayoutDocument()
&& usedSize.height() <= viewport->height())
return;
- _q_adjustScrollbars();
+ adjustScrollbars();
}
void QTextEditPrivate::paint(QPainter *p, QPaintEvent *e)
@@ -1598,6 +1622,8 @@ void QTextEditPrivate::paint(QPainter *p, QPaintEvent *e)
This event handler can be reimplemented in a subclass to receive paint events passed in \a event.
It is usually unnecessary to reimplement this function in a subclass of QTextEdit.
+\note If you create a QPainter, it must operate on the \l{QAbstractScrollArea::}{viewport()}.
+
\warning The underlying text document must not be modified from within a reimplementation
of this function.
*/
@@ -1608,12 +1634,6 @@ void QTextEdit::paintEvent(QPaintEvent *e)
d->paint(&p, e);
}
-void QTextEditPrivate::_q_currentCharFormatChanged(const QTextCharFormat &fmt)
-{
- Q_Q(QTextEdit);
- emit q->currentCharFormatChanged(fmt);
-}
-
void QTextEditPrivate::updateDefaultTextOption()
{
QTextDocument *doc = control->document();
@@ -1804,7 +1824,7 @@ QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant argume
Q_D(const QTextEdit);
switch (query) {
case Qt::ImEnabled:
- return isEnabled();
+ return isEnabled() && !isReadOnly();
case Qt::ImHints:
case Qt::ImInputItemClipRectangle:
return QWidget::inputMethodQuery(query);
@@ -2209,7 +2229,7 @@ void QTextEdit::insertFromMimeData(const QMimeData *source)
bool QTextEdit::isReadOnly() const
{
Q_D(const QTextEdit);
- return !(d->control->textInteractionFlags() & Qt::TextEditable);
+ return !d->control || !(d->control->textInteractionFlags() & Qt::TextEditable);
}
void QTextEdit::setReadOnly(bool ro)
@@ -2366,7 +2386,7 @@ void QTextEdit::scrollToAnchor(const QString &name)
QPointF p = d->control->anchorPosition(name);
const int newPosition = qRound(p.y());
if ( d->vbar->maximum() < newPosition )
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
d->vbar->setValue(newPosition);
}
@@ -2580,11 +2600,14 @@ bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
\overload
Finds the next occurrence, matching the regular expression, \a exp, using the given
- \a options. The QTextDocument::FindCaseSensitively option is ignored for this overload,
- use QRegularExpression::CaseInsensitiveOption instead.
+ \a options.
Returns \c true if a match was found and changes the cursor to select the match;
otherwise returns \c false.
+
+ \warning For historical reasons, the case sensitivity option set on
+ \a exp is ignored. Instead, the \a options are used to determine
+ if the search is case sensitive or not.
*/
#if QT_CONFIG(regularexpression)
bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
@@ -2648,10 +2671,7 @@ bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags opt
*/
void QTextEdit::setText(const QString &text)
{
- Q_D(QTextEdit);
- Qt::TextFormat format = d->textFormat;
- if (d->textFormat == Qt::AutoText)
- format = Qt::mightBeRichText(text) ? Qt::RichText : Qt::PlainText;
+ Qt::TextFormat format = Qt::mightBeRichText(text) ? Qt::RichText : Qt::PlainText;
#ifndef QT_NO_TEXTHTMLPARSER
if (format == Qt::RichText)
setHtml(text);
diff --git a/src/widgets/widgets/qtextedit.h b/src/widgets/widgets/qtextedit.h
index eed0d4e7e9..421eb9136b 100644
--- a/src/widgets/widgets/qtextedit.h
+++ b/src/widgets/widgets/qtextedit.h
@@ -280,14 +280,6 @@ protected:
private:
Q_DISABLE_COPY(QTextEdit)
- Q_PRIVATE_SLOT(d_func(), void _q_repaintContents(const QRectF &r))
- Q_PRIVATE_SLOT(d_func(), void _q_currentCharFormatChanged(const QTextCharFormat &))
- Q_PRIVATE_SLOT(d_func(), void _q_adjustScrollbars())
- Q_PRIVATE_SLOT(d_func(), void _q_ensureVisible(const QRectF &))
- Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged())
-#if QT_CONFIG(cursor)
- Q_PRIVATE_SLOT(d_func(), void _q_hoveredBlockWithMarkerChanged(const QTextBlock &))
-#endif
friend class QTextEditControl;
friend class QTextDocument;
friend class QWidgetTextControl;
diff --git a/src/widgets/widgets/qtextedit_p.h b/src/widgets/widgets/qtextedit_p.h
index 1200b7470e..7dd7d9c107 100644
--- a/src/widgets/widgets/qtextedit_p.h
+++ b/src/widgets/widgets/qtextedit_p.h
@@ -33,6 +33,8 @@
#include "private/qwidgettextcontrol_p.h"
+#include <array>
+
QT_REQUIRE_CONFIG(textedit);
QT_BEGIN_NAMESPACE
@@ -43,16 +45,17 @@ class QTextEditPrivate : public QAbstractScrollAreaPrivate
Q_DECLARE_PUBLIC(QTextEdit)
public:
QTextEditPrivate();
+ ~QTextEditPrivate();
void init(const QString &html = QString());
void paint(QPainter *p, QPaintEvent *e);
- void _q_repaintContents(const QRectF &contentsRect);
+ void repaintContents(const QRectF &contentsRect);
inline QPoint mapToContents(const QPoint &point) const
{ return QPoint(point.x() + horizontalOffset(), point.y() + verticalOffset()); }
- void _q_adjustScrollbars();
- void _q_ensureVisible(const QRectF &rect);
+ void adjustScrollbars();
+ void ensureVisible(const QRectF &rect);
void relayoutDocument();
void createAutoBulletList();
@@ -66,9 +69,8 @@ public:
inline void sendControlEvent(QEvent *e)
{ control->processEvent(e, QPointF(horizontalOffset(), verticalOffset()), viewport); }
- void _q_currentCharFormatChanged(const QTextCharFormat &format);
- void _q_cursorPositionChanged();
- void _q_hoveredBlockWithMarkerChanged(const QTextBlock &block);
+ void cursorPositionChanged();
+ void hoveredBlockWithMarkerChanged(const QTextBlock &block);
void updateDefaultTextOption();
@@ -94,15 +96,14 @@ public:
uint inDrag : 1;
uint clickCausedFocus : 1;
- // Qt3 COMPAT only, for setText
- Qt::TextFormat textFormat;
-
QString anchorToScrollToWhenVisible;
QString placeholderText;
Qt::CursorShape cursorToRestoreAfterHover = Qt::IBeamCursor;
+ std::array<QMetaObject::Connection, 13> connections;
+
#ifdef QT_KEYPAD_NAVIGATION
QBasicTimer deleteAllTimer;
#endif
diff --git a/src/widgets/widgets/qtoolbar.cpp b/src/widgets/widgets/qtoolbar.cpp
index ae0414e776..5e5ef8e8d5 100644
--- a/src/widgets/widgets/qtoolbar.cpp
+++ b/src/widgets/widgets/qtoolbar.cpp
@@ -7,6 +7,9 @@
#if QT_CONFIG(combobox)
#include <qcombobox.h>
#endif
+#if QT_CONFIG(draganddrop)
+#include <qdrag.h>
+#endif
#include <qevent.h>
#include <qlayout.h>
#include <qmainwindow.h>
@@ -14,6 +17,7 @@
#if QT_CONFIG(menubar)
#include <qmenubar.h>
#endif
+#include <qmimedata.h>
#if QT_CONFIG(rubberband)
#include <qrubberband.h>
#endif
@@ -24,6 +28,7 @@
#include <qtimer.h>
#include <private/qwidgetaction_p.h>
#include <private/qmainwindowlayout_p.h>
+#include <private/qhighdpiscaling_p.h>
#ifdef Q_OS_MACOS
#include <qpa/qplatformnativeinterface.h>
@@ -39,6 +44,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
// qmainwindow.cpp
extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
@@ -104,8 +111,12 @@ void QToolBarPrivate::updateWindowFlags(bool floating, bool unplug)
flags |= Qt::FramelessWindowHint;
- if (unplug)
+#if QT_CONFIG(draganddrop)
+ // If we are performing a platform drag the flag is not needed and we want to avoid recreating
+ // the platform window when it would be removed later
+ if (unplug && !QMainWindowLayout::needsPlatformDrag())
flags |= Qt::X11BypassWindowManagerHint;
+#endif
q->setWindowFlags(flags);
}
@@ -116,8 +127,6 @@ void QToolBarPrivate::setWindowState(bool floating, bool unplug, const QRect &re
bool visible = !q->isHidden();
bool wasFloating = q->isFloating(); // ...is also currently using popup menus
- q->hide();
-
updateWindowFlags(floating, unplug);
if (floating != wasFloating)
@@ -171,12 +180,29 @@ void QToolBarPrivate::startDrag(bool moving)
QMainWindowLayout *layout = qt_mainwindow_layout(win);
Q_ASSERT(layout != nullptr);
+#if QT_CONFIG(draganddrop)
+ const bool wasFloating = q->isFloating();
+#endif
+
if (!moving) {
- state->widgetItem = layout->unplug(q);
+ state->widgetItem = layout->unplug(q, QDockWidgetPrivate::DragScope::Group);
Q_ASSERT(state->widgetItem != nullptr);
}
state->dragging = !moving;
state->moving = moving;
+
+#if QT_CONFIG(draganddrop)
+ if (QMainWindowLayout::needsPlatformDrag() && state->dragging) {
+ auto result = layout->performPlatformWidgetDrag(state->widgetItem, state->pressPos);
+ if (result == Qt::IgnoreAction && !wasFloating) {
+ layout->revert(state->widgetItem);
+ delete state;
+ state = nullptr;
+ } else {
+ endDrag();
+ }
+ }
+#endif
}
void QToolBarPrivate::endDrag()
@@ -242,6 +268,13 @@ bool QToolBarPrivate::mousePressEvent(QMouseEvent *event)
bool QToolBarPrivate::mouseReleaseEvent(QMouseEvent*)
{
+#if QT_CONFIG(draganddrop)
+ // if we are peforming a platform drag ignore the release here and end the drag when the actual
+ // drag ends.
+ if (QMainWindowLayout::needsPlatformDrag())
+ return false;
+#endif
+
if (state != nullptr) {
endDrag();
return true;
@@ -292,6 +325,11 @@ bool QToolBarPrivate::mouseMoveEvent(QMouseEvent *event)
q->grabMouse();
}
+ if (!state) {
+ q->releaseMouse();
+ return true;
+ }
+
if (state->dragging) {
QPoint pos = event->globalPosition().toPoint();
// if we are right-to-left, we move so as to keep the right edge the same distance
@@ -309,7 +347,12 @@ bool QToolBarPrivate::mouseMoveEvent(QMouseEvent *event)
const QPoint globalPressPos = q->mapToGlobal(q->isRightToLeft() ? rtl : state->pressPos);
int pos = 0;
- QPoint delta = event->globalPosition().toPoint() - globalPressPos;
+ const QWindow *handle = q->window() ? q->window()->windowHandle() : nullptr;
+ const QPoint delta = handle
+ ? QHighDpi::fromNativePixels(event->globalPosition(), handle).toPoint()
+ - QHighDpi::fromNativePixels(globalPressPos, handle)
+ : event->globalPosition().toPoint() - globalPressPos;
+
if (orientation == Qt::Vertical) {
pos = q->y() + delta.y();
} else {
@@ -352,6 +395,10 @@ void QToolBarPrivate::plug(const QRect &r)
\ingroup mainwindow-classes
\inmodule QtWidgets
+ A toolbar is typically created by calling
+ \l QMainWindow::addToolBar(const QString &title), but it can also
+ be added as the first widget in a QVBoxLayout, for example.
+
Toolbar buttons are added by adding \e actions, using addAction()
or insertAction(). Groups of buttons can be separated using
addSeparator() or insertSeparator(). If a toolbar button is not
@@ -375,7 +422,7 @@ void QToolBarPrivate::plug(const QRect &r)
addWidget(). Please use widget actions created by inheriting QWidgetAction
and implementing QWidgetAction::createWidget() instead.
- \sa QToolButton, QMenu, QAction, {Qt Widgets - Application Example}
+ \sa QToolButton, QMenu, QAction
*/
/*!
@@ -1037,6 +1084,7 @@ bool QToolBar::event(QEvent *event)
d->layout->setExpanded(false);
break;
}
+ break;
default:
break;
}
diff --git a/src/widgets/widgets/qtoolbarextension.cpp b/src/widgets/widgets/qtoolbarextension.cpp
index 9df3cfbda0..350a900457 100644
--- a/src/widgets/widgets/qtoolbarextension.cpp
+++ b/src/widgets/widgets/qtoolbarextension.cpp
@@ -27,9 +27,9 @@ void QToolBarExtension::setOrientation(Qt::Orientation o)
QStyleOption opt;
opt.initFrom(this);
if (o == Qt::Horizontal) {
- setIcon(style()->standardIcon(QStyle::SP_ToolBarHorizontalExtensionButton, &opt));
+ setIcon(style()->standardIcon(QStyle::SP_ToolBarHorizontalExtensionButton, &opt, this));
} else {
- setIcon(style()->standardIcon(QStyle::SP_ToolBarVerticalExtensionButton, &opt));
+ setIcon(style()->standardIcon(QStyle::SP_ToolBarVerticalExtensionButton, &opt, this));
}
m_orientation = o;
}
@@ -49,7 +49,7 @@ QSize QToolBarExtension::sizeHint() const
{
QStyleOption opt;
opt.initFrom(this);
- const int ext = style()->pixelMetric(QStyle::PM_ToolBarExtensionExtent, &opt);
+ const int ext = style()->pixelMetric(QStyle::PM_ToolBarExtensionExtent, &opt, this);
return QSize(ext, ext);
}
diff --git a/src/widgets/widgets/qtoolbutton.cpp b/src/widgets/widgets/qtoolbutton.cpp
index e6ec9ec0bc..e0775afd26 100644
--- a/src/widgets/widgets/qtoolbutton.cpp
+++ b/src/widgets/widgets/qtoolbutton.cpp
@@ -39,14 +39,14 @@ class QToolButtonPrivate : public QAbstractButtonPrivate
public:
void init();
#if QT_CONFIG(menu)
- void _q_buttonPressed();
- void _q_buttonReleased();
+ void onButtonPressed();
+ void onButtonReleased();
void popupTimerDone();
- void _q_updateButtonDown();
- void _q_menuTriggered(QAction *);
+ void updateButtonDown();
+ void onMenuTriggered(QAction *);
#endif
bool updateHoverControl(const QPoint &pos);
- void _q_actionTriggered();
+ void onActionTriggered();
QStyle::SubControl newHoverControl(const QPoint &pos);
QStyle::SubControl hoverControl;
QRect hoverRect;
@@ -187,8 +187,10 @@ void QToolButtonPrivate::init()
QSizePolicy::ToolButton));
#if QT_CONFIG(menu)
- QObject::connect(q, SIGNAL(pressed()), q, SLOT(_q_buttonPressed()));
- QObject::connect(q, SIGNAL(released()), q, SLOT(_q_buttonReleased()));
+ QObjectPrivate::connect(q, &QAbstractButton::pressed,
+ this, &QToolButtonPrivate::onButtonPressed);
+ QObjectPrivate::connect(q, &QAbstractButton::released,
+ this, &QToolButtonPrivate::onButtonReleased);
#endif
setLayoutItemMargins(QStyle::SE_ToolButtonLayoutItem);
@@ -435,7 +437,8 @@ void QToolButton::actionEvent(QActionEvent *event)
setDefaultAction(action); // update button state
break;
case QEvent::ActionAdded:
- connect(action, SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
+ QObjectPrivate::connect(action, &QAction::triggered, d,
+ &QToolButtonPrivate::onActionTriggered);
break;
case QEvent::ActionRemoved:
if (d->defaultAction == action)
@@ -480,7 +483,7 @@ bool QToolButtonPrivate::updateHoverControl(const QPoint &pos)
return !doesHover;
}
-void QToolButtonPrivate::_q_actionTriggered()
+void QToolButtonPrivate::onActionTriggered()
{
Q_Q(QToolButton);
if (QAction *action = qobject_cast<QAction *>(q->sender()))
@@ -581,8 +584,10 @@ void QToolButton::mousePressEvent(QMouseEvent *e)
void QToolButton::mouseReleaseEvent(QMouseEvent *e)
{
Q_D(QToolButton);
+ QPointer<QAbstractButton> guard(this);
QAbstractButton::mouseReleaseEvent(e);
- d->buttonPressed = QToolButtonPrivate::NoButtonPressed;
+ if (guard)
+ d->buttonPressed = QToolButtonPrivate::NoButtonPressed;
}
/*!
@@ -667,7 +672,7 @@ void QToolButton::showMenu()
d->popupTimerDone();
}
-void QToolButtonPrivate::_q_buttonPressed()
+void QToolButtonPrivate::onButtonPressed()
{
Q_Q(QToolButton);
if (!hasMenu())
@@ -680,7 +685,7 @@ void QToolButtonPrivate::_q_buttonPressed()
q->showMenu();
}
-void QToolButtonPrivate::_q_buttonReleased()
+void QToolButtonPrivate::onButtonReleased()
{
popupTimer.stop();
}
@@ -722,8 +727,13 @@ static QPoint positionMenu(const QToolButton *q, bool horizontal,
}
}
}
+
+ // QTBUG-118695 Force point inside the current screen. If the returned point
+ // is not found inside any screen, QMenu's positioning logic kicks in without
+ // taking the QToolButton's screen into account. This can cause the menu to
+ // end up on primary monitor, even if the QToolButton is on a non-primary monitor.
p.rx() = qMax(screen.left(), qMin(p.x(), screen.right() - sh.width()));
- p.ry() += 1;
+ p.ry() = qMax(screen.top(), qMin(p.y() + 1, screen.bottom()));
return p;
}
@@ -757,9 +767,12 @@ void QToolButtonPrivate::popupTimerDone()
#endif
QPointer<QToolButton> that = q;
actualMenu->setNoReplayFor(q);
- if (!mustDeleteActualMenu) //only if action are not in this widget
- QObject::connect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));
- QObject::connect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
+ if (!mustDeleteActualMenu) { //only if action are not in this widget
+ QObjectPrivate::connect(actualMenu, &QMenu::triggered,
+ this, &QToolButtonPrivate::onMenuTriggered);
+ }
+ QObjectPrivate::connect(actualMenu, &QMenu::aboutToHide,
+ this, &QToolButtonPrivate::updateButtonDown);
actualMenu->d_func()->causedPopup.widget = q;
actualMenu->d_func()->causedPopup.action = defaultAction;
actionsCopy = q->actions(); //(the list of action may be modified in slots)
@@ -773,11 +786,14 @@ void QToolButtonPrivate::popupTimerDone()
if (!that)
return;
- QObject::disconnect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
- if (mustDeleteActualMenu)
+ QObjectPrivate::disconnect(actualMenu, &QMenu::aboutToHide,
+ this, &QToolButtonPrivate::updateButtonDown);
+ if (mustDeleteActualMenu) {
delete actualMenu;
- else
- QObject::disconnect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));
+ } else {
+ QObjectPrivate::disconnect(actualMenu, &QMenu::triggered,
+ this, &QToolButtonPrivate::onMenuTriggered);
+ }
actionsCopy.clear();
@@ -785,7 +801,7 @@ void QToolButtonPrivate::popupTimerDone()
q->setAutoRepeat(true);
}
-void QToolButtonPrivate::_q_updateButtonDown()
+void QToolButtonPrivate::updateButtonDown()
{
Q_Q(QToolButton);
menuButtonDown = false;
@@ -795,7 +811,7 @@ void QToolButtonPrivate::_q_updateButtonDown()
q->repaint();
}
-void QToolButtonPrivate::_q_menuTriggered(QAction *action)
+void QToolButtonPrivate::onMenuTriggered(QAction *action)
{
Q_Q(QToolButton);
if (action && !actionsCopy.contains(action))
diff --git a/src/widgets/widgets/qtoolbutton.h b/src/widgets/widgets/qtoolbutton.h
index 68b04c42bf..72429620ad 100644
--- a/src/widgets/widgets/qtoolbutton.h
+++ b/src/widgets/widgets/qtoolbutton.h
@@ -89,14 +89,6 @@ protected:
private:
Q_DISABLE_COPY(QToolButton)
Q_DECLARE_PRIVATE(QToolButton)
-#if QT_CONFIG(menu)
- Q_PRIVATE_SLOT(d_func(), void _q_buttonPressed())
- Q_PRIVATE_SLOT(d_func(), void _q_buttonReleased())
- Q_PRIVATE_SLOT(d_func(), void _q_updateButtonDown())
- Q_PRIVATE_SLOT(d_func(), void _q_menuTriggered(QAction*))
-#endif
- Q_PRIVATE_SLOT(d_func(), void _q_actionTriggered())
-
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qwidgetanimator.cpp b/src/widgets/widgets/qwidgetanimator.cpp
index b7abd1f0dc..d45215dee3 100644
--- a/src/widgets/widgets/qwidgetanimator.cpp
+++ b/src/widgets/widgets/qwidgetanimator.cpp
@@ -73,7 +73,8 @@ void QWidgetAnimator::animate(QWidget *widget, const QRect &_final_geometry, boo
anim->setEasingCurve(QEasingCurve::InOutQuad);
anim->setEndValue(final_geometry);
m_animation_map[widget] = anim;
- connect(anim, SIGNAL(finished()), SLOT(animationFinished()));
+ connect(anim, &QPropertyAnimation::finished,
+ this, &QWidgetAnimator::animationFinished);
anim->start(QPropertyAnimation::DeleteWhenStopped);
} else
#endif // animation
diff --git a/src/widgets/widgets/qwidgetlinecontrol.cpp b/src/widgets/widgets/qwidgetlinecontrol.cpp
index 30465b95fa..ce1b8706ae 100644
--- a/src/widgets/widgets/qwidgetlinecontrol.cpp
+++ b/src/widgets/widgets/qwidgetlinecontrol.cpp
@@ -85,8 +85,7 @@ void QWidgetLineControl::updateDisplayText(bool forceUpdate)
for (int i = 0; i < (int)str.size(); ++i) {
if ((uc[i].unicode() < 0x20 && uc[i].unicode() != 0x09)
|| uc[i] == QChar::LineSeparator
- || uc[i] == QChar::ParagraphSeparator
- || uc[i] == QChar::ObjectReplacementCharacter)
+ || uc[i] == QChar::ParagraphSeparator)
uc[i] = QChar(0x0020);
}
@@ -719,7 +718,7 @@ bool QWidgetLineControl::finishChange(int validateFromState, bool update, bool e
emit selectionChanged();
}
if (m_cursor == m_lastCursorPos)
- updateMicroFocus();
+ emit updateMicroFocus();
emitCursorPositionChanged();
return true;
}
@@ -1396,7 +1395,7 @@ void QWidgetLineControl::emitCursorPositionChanged()
if (m_cursor != m_lastCursorPos) {
const int oldLast = m_lastCursorPos;
m_lastCursorPos = m_cursor;
- cursorPositionChanged(oldLast, m_cursor);
+ emit cursorPositionChanged(oldLast, m_cursor);
#if QT_CONFIG(accessibility)
// otherwise we send a selection update which includes the cursor
if (!hasSelectedText()) {
@@ -1639,6 +1638,7 @@ void QWidgetLineControl::processKeyEvent(QKeyEvent* event)
setText(m_completer->currentCompletion());
inlineCompletionAccepted = true;
}
+ break;
default:
break; // normal key processing
}
@@ -1810,13 +1810,18 @@ void QWidgetLineControl::processKeyEvent(QKeyEvent* event)
}
else if (event == QKeySequence::DeleteEndOfWord) {
if (!isReadOnly()) {
- cursorWordForward(true);
- del();
+ if (!hasSelectedText())
+ cursorWordForward(true);
+
+ if (hasSelectedText())
+ del();
}
}
else if (event == QKeySequence::DeleteStartOfWord) {
if (!isReadOnly()) {
- cursorWordBackward(true);
+ if (!hasSelectedText())
+ cursorWordBackward(true);
+
if (hasSelectedText())
del();
}
diff --git a/src/widgets/widgets/qwidgetlinecontrol_p.h b/src/widgets/widgets/qwidgetlinecontrol_p.h
index 838a46fff6..2ce0fe7d94 100644
--- a/src/widgets/widgets/qwidgetlinecontrol_p.h
+++ b/src/widgets/widgets/qwidgetlinecontrol_p.h
@@ -516,6 +516,8 @@ private:
// accessibility events are sent for this object
QObject *m_accessibleObject;
+
+ friend class QLineEdit;
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qwidgettextcontrol.cpp b/src/widgets/widgets/qwidgettextcontrol.cpp
index 1b78442ed1..6dcaeee0c8 100644
--- a/src/widgets/widgets/qwidgettextcontrol.cpp
+++ b/src/widgets/widgets/qwidgettextcontrol.cpp
@@ -967,9 +967,12 @@ void QWidgetTextControl::selectAll()
{
Q_D(QWidgetTextControl);
const int selectionLength = qAbs(d->cursor.position() - d->cursor.anchor());
+ const int oldCursorPos = d->cursor.position();
d->cursor.select(QTextCursor::Document);
d->selectionChanged(selectionLength != qAbs(d->cursor.position() - d->cursor.anchor()));
d->cursorIsFocusIndicator = false;
+ if (d->cursor.position() != oldCursorPos)
+ emit cursorPositionChanged();
emit updateRequest();
}
@@ -1818,25 +1821,36 @@ void QWidgetTextControlPrivate::mouseReleaseEvent(QEvent *e, Qt::MouseButton but
}
if (interactionFlags & Qt::LinksAccessibleByMouse) {
- if (!(button & Qt::LeftButton))
+
+ // Ignore event unless left button has been pressed
+ if (!(button & Qt::LeftButton)) {
+ e->ignore();
return;
+ }
const QString anchor = q->anchorAt(pos);
- if (anchor.isEmpty())
+ // Ignore event without selection anchor
+ if (anchor.isEmpty()) {
+ e->ignore();
return;
+ }
if (!cursor.hasSelection()
|| (anchor == anchorOnMousePress && hadSelectionOnMousePress)) {
const int anchorPos = q->hitTest(pos, Qt::ExactHit);
- if (anchorPos != -1) {
- cursor.setPosition(anchorPos);
- QString anchor = anchorOnMousePress;
- anchorOnMousePress = QString();
- activateLinkUnderCursor(anchor);
+ // Ignore event without valid anchor position
+ if (anchorPos < 0) {
+ e->ignore();
+ return;
}
+
+ cursor.setPosition(anchorPos);
+ QString anchor = anchorOnMousePress;
+ anchorOnMousePress = QString();
+ activateLinkUnderCursor(anchor);
}
}
}
@@ -2021,6 +2035,11 @@ void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
|| e->preeditString() != cursor.block().layout()->preeditAreaText()
|| e->replacementLength() > 0;
+ if (!isGettingInput && e->attributes().isEmpty()) {
+ e->ignore();
+ return;
+ }
+
int oldCursorPos = cursor.position();
cursor.beginEditBlock();
@@ -2285,7 +2304,7 @@ void QWidgetTextControlPrivate::editFocusEvent(QEvent *e)
#endif
#ifndef QT_NO_CONTEXTMENU
-static inline void setActionIcon(QAction *action, const QString &name)
+void setActionIcon(QAction *action, const QString &name)
{
const QIcon icon = QIcon::fromTheme(name);
if (!icon.isNull())
@@ -2451,7 +2470,7 @@ void QWidgetTextControl::setCursorWidth(int width)
{
Q_D(QWidgetTextControl);
if (width == -1)
- width = QApplication::style()->pixelMetric(QStyle::PM_TextCursorWidth, nullptr);
+ width = QApplication::style()->pixelMetric(QStyle::PM_TextCursorWidth, nullptr, qobject_cast<QWidget *>(parent()));
d->doc->documentLayout()->setProperty("cursorWidth", width);
d->repaintCursor();
}
@@ -2699,7 +2718,8 @@ void QWidgetTextControl::insertFromMimeData(const QMimeData *source)
bool hasData = false;
QTextDocumentFragment fragment;
#if QT_CONFIG(textmarkdownreader)
- if (source->formats().first() == "text/markdown"_L1) {
+ const auto formats = source->formats();
+ if (formats.size() && formats.first() == "text/markdown"_L1) {
auto s = QString::fromUtf8(source->data("text/markdown"_L1));
fragment = QTextDocumentFragment::fromMarkdown(s);
hasData = true;
diff --git a/src/widgets/widgets/qwidgettextcontrol_p.h b/src/widgets/widgets/qwidgettextcontrol_p.h
index 67812dda57..9df4c0c810 100644
--- a/src/widgets/widgets/qwidgettextcontrol_p.h
+++ b/src/widgets/widgets/qwidgettextcontrol_p.h
@@ -276,6 +276,11 @@ private:
mutable QTextDocumentFragment fragment;
};
+#ifndef QT_NO_CONTEXTMENU
+// also used by QLineEdit
+void setActionIcon(QAction *action, const QString &name);
+#endif // QT_NO_CONTEXTMENU
+
QT_END_NAMESPACE
#endif // QWidgetTextControl_H