summaryrefslogtreecommitdiffstats
path: root/src/widgets
diff options
context:
space:
mode:
Diffstat (limited to 'src/widgets')
-rw-r--r--src/widgets/CMakeLists.txt930
-rw-r--r--src/widgets/Qt5WidgetsConfigExtras.cmake.in19
-rw-r--r--src/widgets/Qt5WidgetsMacros.cmake68
-rw-r--r--src/widgets/Qt6WidgetsMacros.cmake51
-rw-r--r--src/widgets/accessible/accessible.pri26
-rw-r--r--src/widgets/accessible/complexwidgets.cpp250
-rw-r--r--src/widgets/accessible/complexwidgets_p.h61
-rw-r--r--src/widgets/accessible/itemviews.cpp427
-rw-r--r--src/widgets/accessible/itemviews_p.h57
-rw-r--r--src/widgets/accessible/qaccessiblemenu.cpp68
-rw-r--r--src/widgets/accessible/qaccessiblemenu_p.h44
-rw-r--r--src/widgets/accessible/qaccessiblewidget.cpp103
-rw-r--r--src/widgets/accessible/qaccessiblewidget.h47
-rw-r--r--src/widgets/accessible/qaccessiblewidgetfactory.cpp148
-rw-r--r--src/widgets/accessible/qaccessiblewidgetfactory_p.h45
-rw-r--r--src/widgets/accessible/qaccessiblewidgets.cpp104
-rw-r--r--src/widgets/accessible/qaccessiblewidgets_p.h45
-rw-r--r--src/widgets/accessible/rangecontrols.cpp58
-rw-r--r--src/widgets/accessible/rangecontrols_p.h44
-rw-r--r--src/widgets/accessible/simplewidgets.cpp147
-rw-r--r--src/widgets/accessible/simplewidgets_p.h63
-rw-r--r--src/widgets/accessible/widgets.pro25
-rw-r--r--src/widgets/compat/removed_api.cpp103
-rw-r--r--src/widgets/configure.cmake544
-rw-r--r--src/widgets/configure.json681
-rw-r--r--src/widgets/configure.pri8
-rw-r--r--src/widgets/dialogs/dialogs.pri84
-rw-r--r--src/widgets/dialogs/images/qtlogo-64.pngbin1032 -> 1219 bytes
-rw-r--r--src/widgets/dialogs/qcolordialog.cpp410
-rw-r--r--src/widgets/dialogs/qcolordialog.h56
-rw-r--r--src/widgets/dialogs/qdialog.cpp451
-rw-r--r--src/widgets/dialogs/qdialog.h51
-rw-r--r--src/widgets/dialogs/qdialog_p.h55
-rw-r--r--src/widgets/dialogs/qerrormessage.cpp172
-rw-r--r--src/widgets/dialogs/qerrormessage.h40
-rw-r--r--src/widgets/dialogs/qfiledialog.cpp1525
-rw-r--r--src/widgets/dialogs/qfiledialog.h136
-rw-r--r--src/widgets/dialogs/qfiledialog.ui43
-rw-r--r--src/widgets/dialogs/qfiledialog_p.h131
-rw-r--r--src/widgets/dialogs/qfileinfogatherer.cpp435
-rw-r--r--src/widgets/dialogs/qfileinfogatherer_p.h229
-rw-r--r--src/widgets/dialogs/qfilesystemmodel.cpp2167
-rw-r--r--src/widgets/dialogs/qfilesystemmodel.h186
-rw-r--r--src/widgets/dialogs/qfilesystemmodel_p.h323
-rw-r--r--src/widgets/dialogs/qfontdialog.cpp212
-rw-r--r--src/widgets/dialogs/qfontdialog.h47
-rw-r--r--src/widgets/dialogs/qfontdialog_p.h56
-rw-r--r--src/widgets/dialogs/qfscompleter_p.h42
-rw-r--r--src/widgets/dialogs/qinputdialog.cpp176
-rw-r--r--src/widgets/dialogs/qinputdialog.h62
-rw-r--r--src/widgets/dialogs/qmessagebox.cpp725
-rw-r--r--src/widgets/dialogs/qmessagebox.h153
-rw-r--r--src/widgets/dialogs/qmessagebox.qrc5
-rw-r--r--src/widgets/dialogs/qprogressdialog.cpp169
-rw-r--r--src/widgets/dialogs/qprogressdialog.h40
-rw-r--r--src/widgets/dialogs/qsidebar.cpp153
-rw-r--r--src/widgets/dialogs/qsidebar_p.h48
-rw-r--r--src/widgets/dialogs/qwizard.cpp409
-rw-r--r--src/widgets/dialogs/qwizard.h51
-rw-r--r--src/widgets/dialogs/qwizard_win.cpp359
-rw-r--r--src/widgets/dialogs/qwizard_win_p.h62
-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/msgbox1.pngbin4529 -> 12001 bytes
-rw-r--r--src/widgets/doc/images/msgbox2.pngbin9175 -> 22021 bytes
-rw-r--r--src/widgets/doc/images/msgbox3.pngbin9589 -> 17975 bytes
-rw-r--r--src/widgets/doc/images/msgbox4.pngbin17520 -> 24600 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.qdocconf49
-rw-r--r--src/widgets/doc/snippets/CMakeLists.txt7
-rw-r--r--src/widgets/doc/snippets/cmake-macros/examples.cmake11
-rw-r--r--src/widgets/doc/snippets/code/doc_gui_widgets_qopenglwidget.cpp209
-rw-r--r--src/widgets/doc/snippets/code/doc_src_layout.cpp61
-rw-r--r--src/widgets/doc/snippets/code/doc_src_model-view-programming.cpp51
-rw-r--r--src/widgets/doc/snippets/code/doc_src_qt4-mainwindow.cpp96
-rw-r--r--src/widgets/doc/snippets/code/doc_src_qt4-styles.cpp70
-rw-r--r--src/widgets/doc/snippets/code/doc_src_qtwidgets.cpp53
-rw-r--r--src/widgets/doc/snippets/code/doc_src_qtwidgets.pro3
-rw-r--r--src/widgets/doc/snippets/code/doc_src_styles.cpp51
-rw-r--r--src/widgets/doc/snippets/code/doc_src_stylesheet.cpp53
-rw-r--r--src/widgets/doc/snippets/code/doc_src_stylesheet.qdoc108
-rw-r--r--src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp55
-rw-r--r--src/widgets/doc/snippets/code/src_gui_dialogs_qfontdialog.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp77
-rw-r--r--src/widgets/doc/snippets/code/src_gui_dialogs_qwizard.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_effects_qgraphicseffect.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp60
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp85
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicslinearlayout.cpp60
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp54
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsview.cpp61
-rw-r--r--src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_image_qpixmapfilter.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_itemviews_qabstractitemview.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp53
-rw-r--r--src/widgets/doc/snippets/code/src_gui_itemviews_qtablewidget.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_itemviews_qtreewidget.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qaction.cpp59
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp145
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qformlayout.cpp60
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qlayout.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qlayoutitem.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qshortcut.cpp65
-rw-r--r--src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp69
-rw-r--r--src/widgets/doc/snippets/code/src_gui_painting_qdrawutil.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_qproxystyle.cpp75
-rw-r--r--src/widgets/doc/snippets/code/src_gui_styles_qstyle.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_styles_qstyleoption.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_util_qcompleter.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_util_qundostack.cpp119
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qabstractbutton.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qabstractspinbox.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qcalendarwidget.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qcheckbox.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qdatetimeedit.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qdockwidget.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qframe.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qgroupbox.cpp68
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qlabel.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qlineedit.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qmainwindow.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp57
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qmenubar.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qplaintextedit.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qpushbutton.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qradiobutton.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qrubberband.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qscrollarea.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qspinbox.cpp71
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qsplashscreen.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qsplitter.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qstatusbar.cpp59
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qtextbrowser.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_gui_widgets_qtextedit.cpp51
-rw-r--r--src/widgets/doc/snippets/code/src_widgets_util_qscroller.cpp40
-rw-r--r--src/widgets/doc/snippets/code/src_widgets_widgets_qmainwindow.cpp40
-rw-r--r--src/widgets/doc/snippets/common-table-model/model.cpp51
-rw-r--r--src/widgets/doc/snippets/common-table-model/model.h51
-rw-r--r--src/widgets/doc/snippets/customstyle/customstyle.cpp55
-rw-r--r--src/widgets/doc/snippets/customstyle/customstyle.h53
-rw-r--r--src/widgets/doc/snippets/customstyle/customstyle.pro3
-rw-r--r--src/widgets/doc/snippets/customstyle/main.cpp51
-rw-r--r--src/widgets/doc/snippets/customviewstyle.cpp79
-rw-r--r--src/widgets/doc/snippets/customviewstyle/CMakeLists.txt16
-rw-r--r--src/widgets/doc/snippets/customviewstyle/customviewstyle.cpp31
-rw-r--r--src/widgets/doc/snippets/dialogs/dialogs.cpp80
-rw-r--r--src/widgets/doc/snippets/dockwidgets/mainwindow.cpp55
-rw-r--r--src/widgets/doc/snippets/filedialogurls.cpp71
-rw-r--r--src/widgets/doc/snippets/filedialogurls/CMakeLists.txt12
-rw-r--r--src/widgets/doc/snippets/filedialogurls/filedialogurls.cpp22
-rw-r--r--src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt12
-rw-r--r--src/widgets/doc/snippets/graphicssceneadditem/graphicssceneadditemsnippet.cpp34
-rw-r--r--src/widgets/doc/snippets/graphicssceneadditemsnippet.cpp90
-rw-r--r--src/widgets/doc/snippets/graphicsview.cpp127
-rw-r--r--src/widgets/doc/snippets/graphicsview/CMakeLists.txt15
-rw-r--r--src/widgets/doc/snippets/graphicsview/graphicsview.cpp103
-rw-r--r--src/widgets/doc/snippets/graphicsview/graphicsview_snippet.cpp16
-rw-r--r--src/widgets/doc/snippets/itemselection/itemselection.pro5
-rw-r--r--src/widgets/doc/snippets/itemselection/main.cpp51
-rw-r--r--src/widgets/doc/snippets/javastyle.cpp59
-rw-r--r--src/widgets/doc/snippets/layouts/layouts.cpp63
-rw-r--r--src/widgets/doc/snippets/mainwindowsnippet.cpp54
-rw-r--r--src/widgets/doc/snippets/mdiarea/CMakeLists.txt12
-rw-r--r--src/widgets/doc/snippets/mdiarea/mdiareasnippets.cpp39
-rw-r--r--src/widgets/doc/snippets/mdiareasnippets.cpp107
-rw-r--r--src/widgets/doc/snippets/myscrollarea.cpp138
-rw-r--r--src/widgets/doc/snippets/myscrollarea/CMakeLists.txt12
-rw-r--r--src/widgets/doc/snippets/myscrollarea/myscrollarea.cpp78
-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/qlistview-dnd/main.cpp51
-rw-r--r--src/widgets/doc/snippets/qlistview-dnd/mainwindow.cpp51
-rw-r--r--src/widgets/doc/snippets/qlistview-dnd/mainwindow.h51
-rw-r--r--src/widgets/doc/snippets/qlistview-dnd/model.cpp55
-rw-r--r--src/widgets/doc/snippets/qlistview-dnd/model.h55
-rw-r--r--src/widgets/doc/snippets/qlistview-dnd/qlistview-dnd.pro6
-rw-r--r--src/widgets/doc/snippets/qlistwidget-dnd/main.cpp51
-rw-r--r--src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.cpp51
-rw-r--r--src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.h51
-rw-r--r--src/widgets/doc/snippets/qlistwidget-dnd/qlistwidget-dnd.pro3
-rw-r--r--src/widgets/doc/snippets/qlistwidget-using/mainwindow.cpp51
-rw-r--r--src/widgets/doc/snippets/qmacnativewidget/main.mm94
-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/qsortfilterproxymodel/main.cpp51
-rw-r--r--src/widgets/doc/snippets/qsortfilterproxymodel/qsortfilterproxymodel.pro1
-rw-r--r--src/widgets/doc/snippets/qsplashscreen/main.cpp51
-rw-r--r--src/widgets/doc/snippets/qstackedlayout/main.cpp53
-rw-r--r--src/widgets/doc/snippets/qstackedwidget/main.cpp55
-rw-r--r--src/widgets/doc/snippets/qstyleoption/main.cpp53
-rw-r--r--src/widgets/doc/snippets/qstyleplugin/main.cpp55
-rw-r--r--src/widgets/doc/snippets/qtablewidget-resizing/mainwindow.cpp51
-rw-r--r--src/widgets/doc/snippets/qtablewidget-using/main.cpp51
-rw-r--r--src/widgets/doc/snippets/qtablewidget-using/mainwindow.cpp51
-rw-r--r--src/widgets/doc/snippets/qtablewidget-using/mainwindow.h51
-rw-r--r--src/widgets/doc/snippets/qtablewidget-using/qtablewidget-using.pro4
-rw-r--r--src/widgets/doc/snippets/qtreewidget-using/mainwindow.cpp51
-rw-r--r--src/widgets/doc/snippets/qtreewidgetitemiterator-using/mainwindow.cpp51
-rw-r--r--src/widgets/doc/snippets/reading-selections/main.cpp51
-rw-r--r--src/widgets/doc/snippets/reading-selections/reading-selections.pro4
-rw-r--r--src/widgets/doc/snippets/reading-selections/window.cpp51
-rw-r--r--src/widgets/doc/snippets/reading-selections/window.h53
-rw-r--r--src/widgets/doc/snippets/shareddirmodel/main.cpp51
-rw-r--r--src/widgets/doc/snippets/sharedtablemodel/main.cpp51
-rw-r--r--src/widgets/doc/snippets/sharedtablemodel/sharedtablemodel.pro5
-rw-r--r--src/widgets/doc/snippets/simplemodel-use/main.cpp107
-rw-r--r--src/widgets/doc/snippets/simplemodel-use/simplemodel-use.pro1
-rw-r--r--src/widgets/doc/snippets/snippets.pro3
-rw-r--r--src/widgets/doc/snippets/splitter/splitter.cpp59
-rw-r--r--src/widgets/doc/snippets/splitterhandle/splitter.cpp51
-rw-r--r--src/widgets/doc/snippets/splitterhandle/splitter.h53
-rw-r--r--src/widgets/doc/snippets/stringlistmodel/main.cpp51
-rw-r--r--src/widgets/doc/snippets/stringlistmodel/model.cpp51
-rw-r--r--src/widgets/doc/snippets/stringlistmodel/model.h51
-rw-r--r--src/widgets/doc/snippets/stringlistmodel/stringlistmodel.pro3
-rw-r--r--src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp58
-rw-r--r--src/widgets/doc/snippets/styles/styles.cpp51
-rw-r--r--src/widgets/doc/snippets/stylesheet/common-mistakes.cpp51
-rw-r--r--src/widgets/doc/snippets/textdocument-imagedrop/textedit.cpp51
-rw-r--r--src/widgets/doc/snippets/timeline/main.cpp51
-rw-r--r--src/widgets/doc/snippets/tooltips/main.cpp74
-rw-r--r--src/widgets/doc/snippets/updating-selections/main.cpp51
-rw-r--r--src/widgets/doc/snippets/updating-selections/updating-selections.pro4
-rw-r--r--src/widgets/doc/snippets/updating-selections/window.cpp55
-rw-r--r--src/widgets/doc/snippets/updating-selections/window.h53
-rw-r--r--src/widgets/doc/snippets/whatsthis/whatsthis.cpp51
-rw-r--r--src/widgets/doc/snippets/widget-mask/main.cpp51
-rw-r--r--src/widgets/doc/snippets/widgetdelegate.cpp51
-rw-r--r--src/widgets/doc/snippets/widgets-tutorial/template.cpp51
-rw-r--r--src/widgets/doc/src/cmake-macros.qdoc49
-rw-r--r--src/widgets/doc/src/dontdocument.qdoc28
-rw-r--r--src/widgets/doc/src/external-resources.qdoc32
-rw-r--r--src/widgets/doc/src/gestures.qdoc28
-rw-r--r--src/widgets/doc/src/graphicsview.qdoc50
-rw-r--r--src/widgets/doc/src/guibooks.qdoc104
-rw-r--r--src/widgets/doc/src/includes/cmake-find-package-widgets.qdocinc5
-rw-r--r--src/widgets/doc/src/model-view-programming.qdoc73
-rw-r--r--src/widgets/doc/src/modelview.qdoc54
-rw-r--r--src/widgets/doc/src/qt6-changes.qdoc113
-rw-r--r--src/widgets/doc/src/qtwidgets-examples.qdoc28
-rw-r--r--src/widgets/doc/src/qtwidgets-index.qdoc98
-rw-r--r--src/widgets/doc/src/qtwidgets.qdoc41
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/focus.qdoc51
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/gallery.qdoc57
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/layout.qdoc39
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/styles.qdoc38
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc1516
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/widgets.qdoc28
-rw-r--r--src/widgets/doc/src/widgets-tutorial.qdoc36
-rw-r--r--src/widgets/doc/src/windows-and-dialogs/dialogs.qdoc29
-rw-r--r--src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc102
-rw-r--r--src/widgets/effects/effects.pri6
-rw-r--r--src/widgets/effects/qgraphicseffect.cpp44
-rw-r--r--src/widgets/effects/qgraphicseffect.h42
-rw-r--r--src/widgets/effects/qgraphicseffect_p.h41
-rw-r--r--src/widgets/effects/qpixmapfilter.cpp371
-rw-r--r--src/widgets/effects/qpixmapfilter_p.h44
-rw-r--r--src/widgets/graphicsview/graphicsview.pri61
-rw-r--r--src/widgets/graphicsview/qgraph_p.h46
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout.cpp67
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout.h40
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp297
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout_p.h210
-rw-r--r--src/widgets/graphicsview/qgraphicsgridlayout.cpp55
-rw-r--r--src/widgets/graphicsview/qgraphicsgridlayout.h40
-rw-r--r--src/widgets/graphicsview/qgraphicsgridlayoutengine.cpp70
-rw-r--r--src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h48
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.cpp515
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.h99
-rw-r--r--src/widgets/graphicsview/qgraphicsitem_p.h115
-rw-r--r--src/widgets/graphicsview/qgraphicsitemanimation.cpp103
-rw-r--r--src/widgets/graphicsview/qgraphicsitemanimation.h50
-rw-r--r--src/widgets/graphicsview/qgraphicslayout.cpp42
-rw-r--r--src/widgets/graphicsview/qgraphicslayout.h42
-rw-r--r--src/widgets/graphicsview/qgraphicslayout_p.cpp40
-rw-r--r--src/widgets/graphicsview/qgraphicslayout_p.h50
-rw-r--r--src/widgets/graphicsview/qgraphicslayoutitem.cpp61
-rw-r--r--src/widgets/graphicsview/qgraphicslayoutitem.h43
-rw-r--r--src/widgets/graphicsview/qgraphicslayoutitem_p.h40
-rw-r--r--src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp44
-rw-r--r--src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h40
-rw-r--r--src/widgets/graphicsview/qgraphicslinearlayout.cpp50
-rw-r--r--src/widgets/graphicsview/qgraphicslinearlayout.h40
-rw-r--r--src/widgets/graphicsview/qgraphicsproxywidget.cpp142
-rw-r--r--src/widgets/graphicsview/qgraphicsproxywidget.h40
-rw-r--r--src/widgets/graphicsview/qgraphicsproxywidget_p.h42
-rw-r--r--src/widgets/graphicsview/qgraphicsscene.cpp591
-rw-r--r--src/widgets/graphicsview/qgraphicsscene.h77
-rw-r--r--src/widgets/graphicsview/qgraphicsscene_bsp.cpp126
-rw-r--r--src/widgets/graphicsview/qgraphicsscene_bsp_p.h64
-rw-r--r--src/widgets/graphicsview/qgraphicsscene_p.h44
-rw-r--r--src/widgets/graphicsview/qgraphicsscenebsptreeindex.cpp40
-rw-r--r--src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h40
-rw-r--r--src/widgets/graphicsview/qgraphicssceneevent.cpp131
-rw-r--r--src/widgets/graphicsview/qgraphicssceneevent.h55
-rw-r--r--src/widgets/graphicsview/qgraphicssceneindex.cpp43
-rw-r--r--src/widgets/graphicsview/qgraphicssceneindex_p.h40
-rw-r--r--src/widgets/graphicsview/qgraphicsscenelinearindex.cpp42
-rw-r--r--src/widgets/graphicsview/qgraphicsscenelinearindex_p.h40
-rw-r--r--src/widgets/graphicsview/qgraphicstransform.cpp44
-rw-r--r--src/widgets/graphicsview/qgraphicstransform.h40
-rw-r--r--src/widgets/graphicsview/qgraphicstransform_p.h43
-rw-r--r--src/widgets/graphicsview/qgraphicsview.cpp622
-rw-r--r--src/widgets/graphicsview/qgraphicsview.h64
-rw-r--r--src/widgets/graphicsview/qgraphicsview_p.h52
-rw-r--r--src/widgets/graphicsview/qgraphicswidget.cpp175
-rw-r--r--src/widgets/graphicsview/qgraphicswidget.h50
-rw-r--r--src/widgets/graphicsview/qgraphicswidget_p.cpp66
-rw-r--r--src/widgets/graphicsview/qgraphicswidget_p.h40
-rw-r--r--src/widgets/graphicsview/qsimplex_p.cpp48
-rw-r--r--src/widgets/graphicsview/qsimplex_p.h40
-rw-r--r--src/widgets/itemviews/itemviews.pri105
-rw-r--r--src/widgets/itemviews/qabstractitemdelegate.cpp122
-rw-r--r--src/widgets/itemviews/qabstractitemdelegate.h48
-rw-r--r--src/widgets/itemviews/qabstractitemdelegate_p.h43
-rw-r--r--src/widgets/itemviews/qabstractitemview.cpp1202
-rw-r--r--src/widgets/itemviews/qabstractitemview.h81
-rw-r--r--src/widgets/itemviews/qabstractitemview_p.h146
-rw-r--r--src/widgets/itemviews/qbsptree.cpp52
-rw-r--r--src/widgets/itemviews/qbsptree_p.h56
-rw-r--r--src/widgets/itemviews/qcolumnview.cpp158
-rw-r--r--src/widgets/itemviews/qcolumnview.h43
-rw-r--r--src/widgets/itemviews/qcolumnview_p.h66
-rw-r--r--src/widgets/itemviews/qcolumnviewgrip.cpp44
-rw-r--r--src/widgets/itemviews/qcolumnviewgrip_p.h40
-rw-r--r--src/widgets/itemviews/qdatawidgetmapper.cpp120
-rw-r--r--src/widgets/itemviews/qdatawidgetmapper.h44
-rw-r--r--src/widgets/itemviews/qdirmodel.cpp1378
-rw-r--r--src/widgets/itemviews/qdirmodel.h152
-rw-r--r--src/widgets/itemviews/qfileiconprovider.cpp162
-rw-r--r--src/widgets/itemviews/qfileiconprovider.h62
-rw-r--r--src/widgets/itemviews/qfileiconprovider_p.h45
-rw-r--r--src/widgets/itemviews/qheaderview.cpp651
-rw-r--r--src/widgets/itemviews/qheaderview.h87
-rw-r--r--src/widgets/itemviews/qheaderview_p.h102
-rw-r--r--src/widgets/itemviews/qitemdelegate.cpp130
-rw-r--r--src/widgets/itemviews/qitemdelegate.h44
-rw-r--r--src/widgets/itemviews/qitemeditorfactory.cpp83
-rw-r--r--src/widgets/itemviews/qitemeditorfactory.h40
-rw-r--r--src/widgets/itemviews/qitemeditorfactory_p.h40
-rw-r--r--src/widgets/itemviews/qlistview.cpp546
-rw-r--r--src/widgets/itemviews/qlistview.h46
-rw-r--r--src/widgets/itemviews/qlistview_p.h112
-rw-r--r--src/widgets/itemviews/qlistwidget.cpp436
-rw-r--r--src/widgets/itemviews/qlistwidget.h132
-rw-r--r--src/widgets/itemviews/qlistwidget_p.h71
-rw-r--r--src/widgets/itemviews/qstyleditemdelegate.cpp167
-rw-r--r--src/widgets/itemviews/qstyleditemdelegate.h40
-rw-r--r--src/widgets/itemviews/qtableview.cpp551
-rw-r--r--src/widgets/itemviews/qtableview.h53
-rw-r--r--src/widgets/itemviews/qtableview_p.h84
-rw-r--r--src/widgets/itemviews/qtablewidget.cpp417
-rw-r--r--src/widgets/itemviews/qtablewidget.h157
-rw-r--r--src/widgets/itemviews/qtablewidget_p.h92
-rw-r--r--src/widgets/itemviews/qtreeview.cpp618
-rw-r--r--src/widgets/itemviews/qtreeview.h54
-rw-r--r--src/widgets/itemviews/qtreeview_p.h105
-rw-r--r--src/widgets/itemviews/qtreewidget.cpp629
-rw-r--r--src/widgets/itemviews/qtreewidget.h153
-rw-r--r--src/widgets/itemviews/qtreewidget_p.h82
-rw-r--r--src/widgets/itemviews/qtreewidgetitemiterator.cpp44
-rw-r--r--src/widgets/itemviews/qtreewidgetitemiterator.h40
-rw-r--r--src/widgets/itemviews/qtreewidgetitemiterator_p.h41
-rw-r--r--src/widgets/itemviews/qwidgetitemdata_p.h43
-rw-r--r--src/widgets/kernel/kernel.pri89
-rw-r--r--src/widgets/kernel/mac.pri1
-rw-r--r--src/widgets/kernel/qaction.cpp354
-rw-r--r--src/widgets/kernel/qaction.h111
-rw-r--r--src/widgets/kernel/qaction_p.h100
-rw-r--r--src/widgets/kernel/qaction_widgets.cpp71
-rw-r--r--src/widgets/kernel/qaction_widgets_p.h54
-rw-r--r--src/widgets/kernel/qactiongroup.cpp188
-rw-r--r--src/widgets/kernel/qactiongroup.h79
-rw-r--r--src/widgets/kernel/qapplication.cpp1761
-rw-r--r--src/widgets/kernel/qapplication.h89
-rw-r--r--src/widgets/kernel/qapplication_p.h89
-rw-r--r--src/widgets/kernel/qboxlayout.cpp162
-rw-r--r--src/widgets/kernel/qboxlayout.h44
-rw-r--r--src/widgets/kernel/qdesktopwidget.cpp385
-rw-r--r--src/widgets/kernel/qdesktopwidget.h129
-rw-r--r--src/widgets/kernel/qdesktopwidget.qdoc336
-rw-r--r--src/widgets/kernel/qdesktopwidget_p.h120
-rw-r--r--src/widgets/kernel/qformlayout.cpp305
-rw-r--r--src/widgets/kernel/qformlayout.h64
-rw-r--r--src/widgets/kernel/qgesture.cpp49
-rw-r--r--src/widgets/kernel/qgesture.h59
-rw-r--r--src/widgets/kernel/qgesture_p.h40
-rw-r--r--src/widgets/kernel/qgesturemanager.cpp110
-rw-r--r--src/widgets/kernel/qgesturemanager_p.h50
-rw-r--r--src/widgets/kernel/qgesturerecognizer.cpp40
-rw-r--r--src/widgets/kernel/qgesturerecognizer.h40
-rw-r--r--src/widgets/kernel/qgridlayout.cpp126
-rw-r--r--src/widgets/kernel/qgridlayout.h48
-rw-r--r--src/widgets/kernel/qlayout.cpp249
-rw-r--r--src/widgets/kernel/qlayout.h67
-rw-r--r--src/widgets/kernel/qlayout_p.h42
-rw-r--r--src/widgets/kernel/qlayoutengine.cpp55
-rw-r--r--src/widgets/kernel/qlayoutengine_p.h48
-rw-r--r--src/widgets/kernel/qlayoutitem.cpp80
-rw-r--r--src/widgets/kernel/qlayoutitem.h51
-rw-r--r--src/widgets/kernel/qmacgesturerecognizer.cpp60
-rw-r--r--src/widgets/kernel/qmacgesturerecognizer_p.h40
-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.cpp551
-rw-r--r--src/widgets/kernel/qshortcut.h128
-rw-r--r--src/widgets/kernel/qshortcut_widgets.cpp328
-rw-r--r--src/widgets/kernel/qsizepolicy.cpp45
-rw-r--r--src/widgets/kernel/qsizepolicy.h141
-rw-r--r--src/widgets/kernel/qstackedlayout.cpp64
-rw-r--r--src/widgets/kernel/qstackedlayout.h40
-rw-r--r--src/widgets/kernel/qstandardgestures.cpp142
-rw-r--r--src/widgets/kernel/qstandardgestures_p.h40
-rw-r--r--src/widgets/kernel/qt_widgets_pch.h41
-rw-r--r--src/widgets/kernel/qtestsupport_widgets.cpp213
-rw-r--r--src/widgets/kernel/qtestsupport_widgets.h75
-rw-r--r--src/widgets/kernel/qtooltip.cpp204
-rw-r--r--src/widgets/kernel/qtooltip.h52
-rw-r--r--src/widgets/kernel/qtwidgetsglobal.h55
-rw-r--r--src/widgets/kernel/qtwidgetsglobal_p.h40
-rw-r--r--src/widgets/kernel/qwhatsthis.cpp130
-rw-r--r--src/widgets/kernel/qwhatsthis.h40
-rw-r--r--src/widgets/kernel/qwidget.cpp2518
-rw-r--r--src/widgets/kernel/qwidget.h195
-rw-r--r--src/widgets/kernel/qwidget_p.h224
-rw-r--r--src/widgets/kernel/qwidgetaction.cpp63
-rw-r--r--src/widgets/kernel/qwidgetaction.h43
-rw-r--r--src/widgets/kernel/qwidgetaction_p.h48
-rw-r--r--src/widgets/kernel/qwidgetrepaintmanager.cpp392
-rw-r--r--src/widgets/kernel/qwidgetrepaintmanager_p.h57
-rw-r--r--src/widgets/kernel/qwidgetsvariant.cpp147
-rw-r--r--src/widgets/kernel/qwidgetwindow.cpp430
-rw-r--r--src/widgets/kernel/qwidgetwindow_p.h55
-rw-r--r--src/widgets/kernel/qwindowcontainer.cpp127
-rw-r--r--src/widgets/kernel/qwindowcontainer_p.h42
-rw-r--r--src/widgets/kernel/win.pri7
-rw-r--r--src/widgets/platform/ios/PrivacyInfo.xcprivacy25
-rw-r--r--src/widgets/qt_cmdline.cmake9
-rw-r--r--src/widgets/qtwidgets.tracepoints8
-rw-r--r--src/widgets/statemachine/qbasickeyeventtransition.cpp204
-rw-r--r--src/widgets/statemachine/qbasickeyeventtransition_p.h93
-rw-r--r--src/widgets/statemachine/qbasicmouseeventtransition.cpp208
-rw-r--r--src/widgets/statemachine/qbasicmouseeventtransition_p.h96
-rw-r--r--src/widgets/statemachine/qguistatemachine.cpp473
-rw-r--r--src/widgets/statemachine/qkeyeventtransition.cpp174
-rw-r--r--src/widgets/statemachine/qkeyeventtransition.h79
-rw-r--r--src/widgets/statemachine/qmouseeventtransition.cpp202
-rw-r--r--src/widgets/statemachine/qmouseeventtransition.h83
-rw-r--r--src/widgets/statemachine/statemachine.pri16
-rw-r--r--src/widgets/styles/images/check_list_controller.svg21
-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/closedock-down-macstyle-10.pngbin0 -> 195 bytes
-rw-r--r--src/widgets/styles/images/closedock-down-macstyle-20.pngbin0 -> 344 bytes
-rw-r--r--src/widgets/styles/images/closedock-down-macstyle-32.pngbin0 -> 474 bytes
-rw-r--r--src/widgets/styles/images/closedock-down-macstyle-48.pngbin0 -> 721 bytes
-rw-r--r--src/widgets/styles/images/closedock-down-macstyle-64.pngbin0 -> 920 bytes
-rw-r--r--src/widgets/styles/images/closedock-down-macstyle.svg15
-rw-r--r--src/widgets/styles/images/closedock-macstyle-10.pngbin0 -> 309 bytes
-rw-r--r--src/widgets/styles/images/closedock-macstyle-20.pngbin0 -> 579 bytes
-rw-r--r--src/widgets/styles/images/closedock-macstyle-32.pngbin0 -> 938 bytes
-rw-r--r--src/widgets/styles/images/closedock-macstyle-48.pngbin0 -> 1236 bytes
-rw-r--r--src/widgets/styles/images/closedock-macstyle-64.pngbin0 -> 1495 bytes
-rw-r--r--src/widgets/styles/images/closedock-macstyle.svg15
-rw-r--r--src/widgets/styles/images/closedock.svg18
-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/critical.svg14
-rw-r--r--src/widgets/styles/images/dockdock-down-macstyle-10.pngbin0 -> 246 bytes
-rw-r--r--src/widgets/styles/images/dockdock-down-macstyle-20.pngbin0 -> 363 bytes
-rw-r--r--src/widgets/styles/images/dockdock-down-macstyle-32.pngbin0 -> 416 bytes
-rw-r--r--src/widgets/styles/images/dockdock-down-macstyle-48.pngbin0 -> 622 bytes
-rw-r--r--src/widgets/styles/images/dockdock-down-macstyle-64.pngbin0 -> 771 bytes
-rw-r--r--src/widgets/styles/images/dockdock-down-macstyle.svg16
-rw-r--r--src/widgets/styles/images/dockdock-macstyle-10.pngbin0 -> 339 bytes
-rw-r--r--src/widgets/styles/images/dockdock-macstyle-20.pngbin0 -> 555 bytes
-rw-r--r--src/widgets/styles/images/dockdock-macstyle-32.pngbin0 -> 654 bytes
-rw-r--r--src/widgets/styles/images/dockdock-macstyle-48.pngbin0 -> 915 bytes
-rw-r--r--src/widgets/styles/images/dockdock-macstyle-64.pngbin0 -> 1212 bytes
-rw-r--r--src/widgets/styles/images/dockdock-macstyle.svg17
-rw-r--r--src/widgets/styles/images/file_open.svg19
-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_end.svg27
-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/filedialog_start.svg27
-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/information.svg14
-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/qt_close.svg18
-rw-r--r--src/widgets/styles/images/qt_help.svg25
-rw-r--r--src/widgets/styles/images/qt_maximize.svg12
-rw-r--r--src/widgets/styles/images/qt_menu.svg22
-rw-r--r--src/widgets/styles/images/qt_minimize.svg15
-rw-r--r--src/widgets/styles/images/qt_normalizeup.svg20
-rw-r--r--src/widgets/styles/images/qt_shade.svg15
-rw-r--r--src/widgets/styles/images/qt_unshade.svg15
-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/question.svg21
-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.pngbin0 -> 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.pngbin0 -> 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.pngbin0 -> 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-h.svg16
-rw-r--r--src/widgets/styles/images/toolbar-ext-v-80.pngbin0 -> 2035 bytes
-rw-r--r--src/widgets/styles/images/toolbar-ext-v.svg16
-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/images/warning.svg16
-rw-r--r--src/widgets/styles/qcommonstyle.cpp2233
-rw-r--r--src/widgets/styles/qcommonstyle.h43
-rw-r--r--src/widgets/styles/qcommonstyle_p.h67
-rw-r--r--src/widgets/styles/qcommonstylepixmaps_p.h42
-rw-r--r--src/widgets/styles/qdrawutil.cpp219
-rw-r--r--src/widgets/styles/qdrawutil.h55
-rw-r--r--src/widgets/styles/qfusionstyle.cpp790
-rw-r--r--src/widgets/styles/qfusionstyle_p.h41
-rw-r--r--src/widgets/styles/qfusionstyle_p_p.h42
-rw-r--r--src/widgets/styles/qpixmapstyle.cpp64
-rw-r--r--src/widgets/styles/qpixmapstyle_p.h44
-rw-r--r--src/widgets/styles/qpixmapstyle_p_p.h40
-rw-r--r--src/widgets/styles/qproxystyle.cpp69
-rw-r--r--src/widgets/styles/qproxystyle.h40
-rw-r--r--src/widgets/styles/qproxystyle_p.h42
-rw-r--r--src/widgets/styles/qstyle.cpp233
-rw-r--r--src/widgets/styles/qstyle.h90
-rw-r--r--src/widgets/styles/qstyle.qrc176
-rw-r--r--src/widgets/styles/qstyle_p.h45
-rw-r--r--src/widgets/styles/qstyleanimation.cpp49
-rw-r--r--src/widgets/styles/qstyleanimation_p.h42
-rw-r--r--src/widgets/styles/qstylefactory.cpp68
-rw-r--r--src/widgets/styles/qstylefactory.h40
-rw-r--r--src/widgets/styles/qstylehelper.cpp82
-rw-r--r--src/widgets/styles/qstylehelper_p.h42
-rw-r--r--src/widgets/styles/qstyleoption.cpp622
-rw-r--r--src/widgets/styles/qstyleoption.h115
-rw-r--r--src/widgets/styles/qstylepainter.cpp40
-rw-r--r--src/widgets/styles/qstylepainter.h46
-rw-r--r--src/widgets/styles/qstyleplugin.cpp40
-rw-r--r--src/widgets/styles/qstyleplugin.h40
-rw-r--r--src/widgets/styles/qstylesheetstyle.cpp1267
-rw-r--r--src/widgets/styles/qstylesheetstyle_default.cpp213
-rw-r--r--src/widgets/styles/qstylesheetstyle_p.h64
-rw-r--r--src/widgets/styles/qwindowsstyle.cpp268
-rw-r--r--src/widgets/styles/qwindowsstyle_p.h40
-rw-r--r--src/widgets/styles/qwindowsstyle_p_p.h48
-rw-r--r--src/widgets/styles/styles.pri49
-rw-r--r--src/widgets/util/qcolormap.cpp57
-rw-r--r--src/widgets/util/qcolormap.h46
-rw-r--r--src/widgets/util/qcolormap.qdoc38
-rw-r--r--src/widgets/util/qcompleter.cpp198
-rw-r--r--src/widgets/util/qcompleter.h40
-rw-r--r--src/widgets/util/qcompleter_p.h60
-rw-r--r--src/widgets/util/qflickgesture.cpp141
-rw-r--r--src/widgets/util/qflickgesture_p.h42
-rw-r--r--src/widgets/util/qscroller.cpp224
-rw-r--r--src/widgets/util/qscroller.h43
-rw-r--r--src/widgets/util/qscroller_p.h40
-rw-r--r--src/widgets/util/qscrollerproperties.cpp49
-rw-r--r--src/widgets/util/qscrollerproperties.h46
-rw-r--r--src/widgets/util/qscrollerproperties_p.h40
-rw-r--r--src/widgets/util/qsystemtrayicon.cpp94
-rw-r--r--src/widgets/util/qsystemtrayicon.h40
-rw-r--r--src/widgets/util/qsystemtrayicon_p.h40
-rw-r--r--src/widgets/util/qsystemtrayicon_qpa.cpp52
-rw-r--r--src/widgets/util/qsystemtrayicon_x11.cpp52
-rw-r--r--src/widgets/util/qundogroup.cpp502
-rw-r--r--src/widgets/util/qundogroup.h103
-rw-r--r--src/widgets/util/qundostack.cpp1388
-rw-r--r--src/widgets/util/qundostack.h161
-rw-r--r--src/widgets/util/qundostack_p.h115
-rw-r--r--src/widgets/util/qundoview.cpp56
-rw-r--r--src/widgets/util/qundoview.h40
-rw-r--r--src/widgets/util/util.pri56
-rw-r--r--src/widgets/widgets.pro49
-rw-r--r--src/widgets/widgets/qabstractbutton.cpp151
-rw-r--r--src/widgets/widgets/qabstractbutton.h42
-rw-r--r--src/widgets/widgets/qabstractbutton_p.h40
-rw-r--r--src/widgets/widgets/qabstractscrollarea.cpp132
-rw-r--r--src/widgets/widgets/qabstractscrollarea.h46
-rw-r--r--src/widgets/widgets/qabstractscrollarea_p.h51
-rw-r--r--src/widgets/widgets/qabstractslider.cpp57
-rw-r--r--src/widgets/widgets/qabstractslider.h40
-rw-r--r--src/widgets/widgets/qabstractslider_p.h40
-rw-r--r--src/widgets/widgets/qabstractspinbox.cpp203
-rw-r--r--src/widgets/widgets/qabstractspinbox.h45
-rw-r--r--src/widgets/widgets/qabstractspinbox_p.h82
-rw-r--r--src/widgets/widgets/qbuttongroup.cpp64
-rw-r--r--src/widgets/widgets/qbuttongroup.h48
-rw-r--r--src/widgets/widgets/qbuttongroup_p.h40
-rw-r--r--src/widgets/widgets/qcalendarwidget.cpp269
-rw-r--r--src/widgets/widgets/qcalendarwidget.h78
-rw-r--r--src/widgets/widgets/qcheckbox.cpp80
-rw-r--r--src/widgets/widgets/qcheckbox.h46
-rw-r--r--src/widgets/widgets/qcombobox.cpp1024
-rw-r--r--src/widgets/widgets/qcombobox.h89
-rw-r--r--src/widgets/widgets/qcombobox_p.h142
-rw-r--r--src/widgets/widgets/qcommandlinkbutton.cpp65
-rw-r--r--src/widgets/widgets/qcommandlinkbutton.h48
-rw-r--r--src/widgets/widgets/qdatetimeedit.cpp563
-rw-r--r--src/widgets/widgets/qdatetimeedit.h93
-rw-r--r--src/widgets/widgets/qdatetimeedit_p.h70
-rw-r--r--src/widgets/widgets/qdial.cpp78
-rw-r--r--src/widgets/widgets/qdial.h42
-rw-r--r--src/widgets/widgets/qdialogbuttonbox.cpp379
-rw-r--r--src/widgets/widgets/qdialogbuttonbox.h45
-rw-r--r--src/widgets/widgets/qdialogbuttonbox_p.h80
-rw-r--r--src/widgets/widgets/qdockarealayout.cpp428
-rw-r--r--src/widgets/widgets/qdockarealayout_p.h71
-rw-r--r--src/widgets/widgets/qdockwidget.cpp408
-rw-r--r--src/widgets/widgets/qdockwidget.h53
-rw-r--r--src/widgets/widgets/qdockwidget_p.h68
-rw-r--r--src/widgets/widgets/qeffects.cpp75
-rw-r--r--src/widgets/widgets/qeffects_p.h40
-rw-r--r--src/widgets/widgets/qfocusframe.cpp58
-rw-r--r--src/widgets/widgets/qfocusframe.h42
-rw-r--r--src/widgets/widgets/qfontcombobox.cpp254
-rw-r--r--src/widgets/widgets/qfontcombobox.h51
-rw-r--r--src/widgets/widgets/qframe.cpp51
-rw-r--r--src/widgets/widgets/qframe.h44
-rw-r--r--src/widgets/widgets/qframe_p.h43
-rw-r--r--src/widgets/widgets/qgroupbox.cpp79
-rw-r--r--src/widgets/widgets/qgroupbox.h42
-rw-r--r--src/widgets/widgets/qkeysequenceedit.cpp214
-rw-r--r--src/widgets/widgets/qkeysequenceedit.h57
-rw-r--r--src/widgets/widgets/qkeysequenceedit_p.h48
-rw-r--r--src/widgets/widgets/qlabel.cpp253
-rw-r--r--src/widgets/widgets/qlabel.h69
-rw-r--r--src/widgets/widgets/qlabel_p.h67
-rw-r--r--src/widgets/widgets/qlcdnumber.cpp92
-rw-r--r--src/widgets/widgets/qlcdnumber.h40
-rw-r--r--src/widgets/widgets/qlineedit.cpp683
-rw-r--r--src/widgets/widgets/qlineedit.h61
-rw-r--r--src/widgets/widgets/qlineedit_p.cpp215
-rw-r--r--src/widgets/widgets/qlineedit_p.h78
-rw-r--r--src/widgets/widgets/qmaccocoaviewcontainer_mac.h67
-rw-r--r--src/widgets/widgets/qmaccocoaviewcontainer_mac.mm199
-rw-r--r--src/widgets/widgets/qmacnativewidget_mac.h66
-rw-r--r--src/widgets/widgets/qmacnativewidget_mac.mm166
-rw-r--r--src/widgets/widgets/qmainwindow.cpp181
-rw-r--r--src/widgets/widgets/qmainwindow.h53
-rw-r--r--src/widgets/widgets/qmainwindowlayout.cpp946
-rw-r--r--src/widgets/widgets/qmainwindowlayout_p.h163
-rw-r--r--src/widgets/widgets/qmdiarea.cpp232
-rw-r--r--src/widgets/widgets/qmdiarea.h40
-rw-r--r--src/widgets/widgets/qmdiarea_p.h70
-rw-r--r--src/widgets/widgets/qmdisubwindow.cpp162
-rw-r--r--src/widgets/widgets/qmdisubwindow.h41
-rw-r--r--src/widgets/widgets/qmdisubwindow_p.h47
-rw-r--r--src/widgets/widgets/qmenu.cpp828
-rw-r--r--src/widgets/widgets/qmenu.h160
-rw-r--r--src/widgets/widgets/qmenu_mac.mm154
-rw-r--r--src/widgets/widgets/qmenu_p.h69
-rw-r--r--src/widgets/widgets/qmenubar.cpp385
-rw-r--r--src/widgets/widgets/qmenubar.h72
-rw-r--r--src/widgets/widgets/qmenubar_p.h48
-rw-r--r--src/widgets/widgets/qplaintextedit.cpp382
-rw-r--r--src/widgets/widgets/qplaintextedit.h59
-rw-r--r--src/widgets/widgets/qplaintextedit_p.h94
-rw-r--r--src/widgets/widgets/qprogressbar.cpp70
-rw-r--r--src/widgets/widgets/qprogressbar.h42
-rw-r--r--src/widgets/widgets/qpushbutton.cpp118
-rw-r--r--src/widgets/widgets/qpushbutton.h49
-rw-r--r--src/widgets/widgets/qpushbutton_p.h53
-rw-r--r--src/widgets/widgets/qradiobutton.cpp48
-rw-r--r--src/widgets/widgets/qradiobutton.h42
-rw-r--r--src/widgets/widgets/qrubberband.cpp40
-rw-r--r--src/widgets/widgets/qrubberband.h42
-rw-r--r--src/widgets/widgets/qscrollarea.cpp68
-rw-r--r--src/widgets/widgets/qscrollarea.h40
-rw-r--r--src/widgets/widgets/qscrollarea_p.h42
-rw-r--r--src/widgets/widgets/qscrollbar.cpp107
-rw-r--r--src/widgets/widgets/qscrollbar.h42
-rw-r--r--src/widgets/widgets/qscrollbar_p.h40
-rw-r--r--src/widgets/widgets/qsizegrip.cpp109
-rw-r--r--src/widgets/widgets/qsizegrip.h40
-rw-r--r--src/widgets/widgets/qslider.cpp82
-rw-r--r--src/widgets/widgets/qslider.h42
-rw-r--r--src/widgets/widgets/qspinbox.cpp162
-rw-r--r--src/widgets/widgets/qspinbox.h48
-rw-r--r--src/widgets/widgets/qsplashscreen.cpp187
-rw-r--r--src/widgets/widgets/qsplashscreen.h44
-rw-r--r--src/widgets/widgets/qsplitter.cpp202
-rw-r--r--src/widgets/widgets/qsplitter.h46
-rw-r--r--src/widgets/widgets/qsplitter_p.h42
-rw-r--r--src/widgets/widgets/qstackedwidget.cpp49
-rw-r--r--src/widgets/widgets/qstackedwidget.h42
-rw-r--r--src/widgets/widgets/qstatusbar.cpp213
-rw-r--r--src/widgets/widgets/qstatusbar.h41
-rw-r--r--src/widgets/widgets/qtabbar.cpp849
-rw-r--r--src/widgets/widgets/qtabbar.h66
-rw-r--r--src/widgets/widgets/qtabbar_p.h199
-rw-r--r--src/widgets/widgets/qtabwidget.cpp139
-rw-r--r--src/widgets/widgets/qtabwidget.h59
-rw-r--r--src/widgets/widgets/qtextbrowser.cpp219
-rw-r--r--src/widgets/widgets/qtextbrowser.h54
-rw-r--r--src/widgets/widgets/qtextedit.cpp318
-rw-r--r--src/widgets/widgets/qtextedit.h62
-rw-r--r--src/widgets/widgets/qtextedit_p.h59
-rw-r--r--src/widgets/widgets/qtoolbar.cpp252
-rw-r--r--src/widgets/widgets/qtoolbar.h99
-rw-r--r--src/widgets/widgets/qtoolbar_p.h46
-rw-r--r--src/widgets/widgets/qtoolbararealayout.cpp172
-rw-r--r--src/widgets/widgets/qtoolbararealayout_p.h50
-rw-r--r--src/widgets/widgets/qtoolbarextension.cpp54
-rw-r--r--src/widgets/widgets/qtoolbarextension_p.h40
-rw-r--r--src/widgets/widgets/qtoolbarlayout.cpp82
-rw-r--r--src/widgets/widgets/qtoolbarlayout_p.h46
-rw-r--r--src/widgets/widgets/qtoolbarseparator.cpp40
-rw-r--r--src/widgets/widgets/qtoolbarseparator_p.h40
-rw-r--r--src/widgets/widgets/qtoolbox.cpp71
-rw-r--r--src/widgets/widgets/qtoolbox.h44
-rw-r--r--src/widgets/widgets/qtoolbutton.cpp212
-rw-r--r--src/widgets/widgets/qtoolbutton.h53
-rw-r--r--src/widgets/widgets/qwidgetanimator.cpp47
-rw-r--r--src/widgets/widgets/qwidgetanimator_p.h40
-rw-r--r--src/widgets/widgets/qwidgetlinecontrol.cpp249
-rw-r--r--src/widgets/widgets/qwidgetlinecontrol_p.h74
-rw-r--r--src/widgets/widgets/qwidgetresizehandler.cpp171
-rw-r--r--src/widgets/widgets/qwidgetresizehandler_p.h74
-rw-r--r--src/widgets/widgets/qwidgettextcontrol.cpp376
-rw-r--r--src/widgets/widgets/qwidgettextcontrol_p.h65
-rw-r--r--src/widgets/widgets/qwidgettextcontrol_p_p.h48
-rw-r--r--src/widgets/widgets/widgets.pri371
829 files changed, 30848 insertions, 57597 deletions
diff --git a/src/widgets/CMakeLists.txt b/src/widgets/CMakeLists.txt
new file mode 100644
index 0000000000..fdef309a4a
--- /dev/null
+++ b/src/widgets/CMakeLists.txt
@@ -0,0 +1,930 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+#####################################################################
+## Widgets Module:
+#####################################################################
+
+qt_internal_add_module(Widgets
+ QMAKE_MODULE_CONFIG uic
+ PLUGIN_TYPES styles
+ SOURCES
+ compat/removed_api.cpp
+ itemviews/qfileiconprovider.cpp itemviews/qfileiconprovider.h itemviews/qfileiconprovider_p.h
+ kernel/qapplication.cpp kernel/qapplication.h kernel/qapplication_p.h
+ kernel/qboxlayout.cpp kernel/qboxlayout.h
+ kernel/qgesture.cpp kernel/qgesture.h kernel/qgesture_p.h
+ kernel/qgesturemanager.cpp kernel/qgesturemanager_p.h
+ kernel/qgesturerecognizer.cpp kernel/qgesturerecognizer.h
+ kernel/qgridlayout.cpp kernel/qgridlayout.h
+ 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
+ kernel/qtestsupport_widgets.cpp kernel/qtestsupport_widgets.h
+ kernel/qtwidgetsglobal.h kernel/qtwidgetsglobal_p.h
+ kernel/qwidget.cpp kernel/qwidget.h kernel/qwidget_p.h
+ kernel/qwidgetrepaintmanager.cpp kernel/qwidgetrepaintmanager_p.h
+ kernel/qwidgetsvariant.cpp
+ kernel/qwidgetwindow.cpp kernel/qwidgetwindow_p.h
+ kernel/qwindowcontainer.cpp kernel/qwindowcontainer_p.h
+ styles/qcommonstyle.cpp styles/qcommonstyle.h styles/qcommonstyle_p.h
+ styles/qcommonstylepixmaps_p.h
+ styles/qdrawutil.cpp styles/qdrawutil.h
+ styles/qpixmapstyle.cpp styles/qpixmapstyle_p.h
+ styles/qpixmapstyle_p_p.h
+ styles/qproxystyle.cpp styles/qproxystyle.h styles/qproxystyle_p.h
+ styles/qstyle.cpp styles/qstyle.h styles/qstyle_p.h
+ styles/qstylefactory.cpp styles/qstylefactory.h
+ styles/qstylehelper.cpp styles/qstylehelper_p.h
+ styles/qstyleoption.cpp styles/qstyleoption.h
+ styles/qstylepainter.cpp styles/qstylepainter.h
+ styles/qstyleplugin.cpp styles/qstyleplugin.h
+ styles/qstylesheetstyle.cpp styles/qstylesheetstyle_p.h
+ styles/qstylesheetstyle_default.cpp
+ util/qcolormap.cpp util/qcolormap.h
+ util/qsystemtrayicon.cpp util/qsystemtrayicon.h util/qsystemtrayicon_p.h
+ widgets/qabstractscrollarea.cpp widgets/qabstractscrollarea.h widgets/qabstractscrollarea_p.h
+ widgets/qfocusframe.cpp widgets/qfocusframe.h
+ 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
+ Qt::CorePrivate
+ Qt::GuiPrivate
+ PUBLIC_LIBRARIES
+ Qt::Core
+ Qt::Gui
+ PRIVATE_MODULE_INTERFACE
+ Qt::CorePrivate
+ 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"
+ "styles/images/closedock-16.png"
+ "styles/images/closedock-20.png"
+ "styles/images/closedock-32.png"
+ "styles/images/closedock-48.png"
+ "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"
+ "styles/images/dirclosed-16.png"
+ "styles/images/dirclosed-32.png"
+ "styles/images/dirlink-128.png"
+ "styles/images/dirlink-16.png"
+ "styles/images/dirlink-32.png"
+ "styles/images/diropen-128.png"
+ "styles/images/diropen-16.png"
+ "styles/images/diropen-32.png"
+ "styles/images/down-128.png"
+ "styles/images/down-16.png"
+ "styles/images/down-32.png"
+ "styles/images/dvd-128.png"
+ "styles/images/dvd-16.png"
+ "styles/images/dvd-32.png"
+ "styles/images/file-128.png"
+ "styles/images/file-16.png"
+ "styles/images/file-32.png"
+ "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"
+ "styles/images/filelink-128.png"
+ "styles/images/filelink-16.png"
+ "styles/images/filelink-32.png"
+ "styles/images/floppy-128.png"
+ "styles/images/floppy-16.png"
+ "styles/images/floppy-32.png"
+ "styles/images/fontbitmap-16.png"
+ "styles/images/fonttruetype-16.png"
+ "styles/images/fusion_groupbox.png"
+ "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"
+ "styles/images/media-volume-muted-16.png"
+ "styles/images/networkdrive-128.png"
+ "styles/images/networkdrive-16.png"
+ "styles/images/networkdrive-32.png"
+ "styles/images/newdirectory-128.png"
+ "styles/images/newdirectory-16.png"
+ "styles/images/newdirectory-32.png"
+ "styles/images/normalizedockup-10.png"
+ "styles/images/normalizedockup-16.png"
+ "styles/images/normalizedockup-20.png"
+ "styles/images/normalizedockup-32.png"
+ "styles/images/normalizedockup-48.png"
+ "styles/images/normalizedockup-64.png"
+ "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"
+ "styles/images/right-16.png"
+ "styles/images/right-32.png"
+ "styles/images/standardbutton-apply-128.png"
+ "styles/images/standardbutton-apply-16.png"
+ "styles/images/standardbutton-apply-32.png"
+ "styles/images/standardbutton-cancel-128.png"
+ "styles/images/standardbutton-cancel-16.png"
+ "styles/images/standardbutton-cancel-32.png"
+ "styles/images/standardbutton-clear-128.png"
+ "styles/images/standardbutton-clear-16.png"
+ "styles/images/standardbutton-clear-32.png"
+ "styles/images/standardbutton-close-128.png"
+ "styles/images/standardbutton-close-16.png"
+ "styles/images/standardbutton-close-32.png"
+ "styles/images/standardbutton-closetab-128.png"
+ "styles/images/standardbutton-closetab-16.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-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"
+ "styles/images/standardbutton-help-128.png"
+ "styles/images/standardbutton-help-16.png"
+ "styles/images/standardbutton-help-32.png"
+ "styles/images/standardbutton-no-128.png"
+ "styles/images/standardbutton-no-16.png"
+ "styles/images/standardbutton-no-32.png"
+ "styles/images/standardbutton-ok-128.png"
+ "styles/images/standardbutton-ok-16.png"
+ "styles/images/standardbutton-ok-32.png"
+ "styles/images/standardbutton-open-128.png"
+ "styles/images/standardbutton-open-16.png"
+ "styles/images/standardbutton-open-32.png"
+ "styles/images/standardbutton-save-128.png"
+ "styles/images/standardbutton-save-16.png"
+ "styles/images/standardbutton-save-32.png"
+ "styles/images/standardbutton-yes-128.png"
+ "styles/images/standardbutton-yes-16.png"
+ "styles/images/standardbutton-yes-32.png"
+ "styles/images/stop-24.png"
+ "styles/images/stop-32.png"
+ "styles/images/titlebar-contexthelp-16.png"
+ "styles/images/titlebar-contexthelp-32.png"
+ "styles/images/titlebar-contexthelp-48.png"
+ "styles/images/titlebar-max-16.png"
+ "styles/images/titlebar-max-32.png"
+ "styles/images/titlebar-max-48.png"
+ "styles/images/titlebar-min-16.png"
+ "styles/images/titlebar-min-32.png"
+ "styles/images/titlebar-min-48.png"
+ "styles/images/titlebar-shade-16.png"
+ "styles/images/titlebar-shade-32.png"
+ "styles/images/titlebar-shade-48.png"
+ "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"
+ "styles/images/trash-32.png"
+ "styles/images/up-128.png"
+ "styles/images/up-16.png"
+ "styles/images/up-32.png"
+ "styles/images/viewdetailed-128.png"
+ "styles/images/viewdetailed-16.png"
+ "styles/images/viewdetailed-32.png"
+ "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"
+)
+
+qt_internal_add_resource(Widgets "qstyle"
+ PREFIX
+ "/qt-project.org/styles/commonstyle"
+ BASE
+ "styles"
+ FILES
+ ${qstyle_resource_files}
+)
+set(qstyle1_resource_files
+ "styles/images/closedock-down-macstyle-10.png"
+ "styles/images/closedock-down-macstyle-16.png"
+ "styles/images/closedock-down-macstyle-20.png"
+ "styles/images/closedock-down-macstyle-32.png"
+ "styles/images/closedock-down-macstyle-48.png"
+ "styles/images/closedock-down-macstyle-64.png"
+ "styles/images/closedock-macstyle-10.png"
+ "styles/images/closedock-macstyle-16.png"
+ "styles/images/closedock-macstyle-20.png"
+ "styles/images/closedock-macstyle-32.png"
+ "styles/images/closedock-macstyle-48.png"
+ "styles/images/closedock-macstyle-64.png"
+ "styles/images/dockdock-down-macstyle-10.png"
+ "styles/images/dockdock-down-macstyle-16.png"
+ "styles/images/dockdock-down-macstyle-20.png"
+ "styles/images/dockdock-down-macstyle-32.png"
+ "styles/images/dockdock-down-macstyle-48.png"
+ "styles/images/dockdock-down-macstyle-64.png"
+ "styles/images/dockdock-macstyle-10.png"
+ "styles/images/dockdock-macstyle-16.png"
+ "styles/images/dockdock-macstyle-20.png"
+ "styles/images/dockdock-macstyle-32.png"
+ "styles/images/dockdock-macstyle-48.png"
+ "styles/images/dockdock-macstyle-64.png"
+ "styles/images/toolbar-ext-macstyle.png"
+ "styles/images/toolbar-ext-macstyle@2x.png"
+)
+
+qt_internal_add_resource(Widgets "qstyle1"
+ PREFIX
+ "/qt-project.org/styles/macstyle"
+ BASE
+ "styles"
+ FILES
+ ${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()
+
+## Scopes:
+#####################################################################
+
+qt_internal_extend_target(Widgets CONDITION MSVC AND (TEST_architecture_arch STREQUAL "i386")
+ LINK_OPTIONS
+ "/BASE:0x65000000"
+)
+
+qt_internal_extend_target(Widgets CONDITION MACOS
+ SOURCES
+ kernel/qmacgesturerecognizer.cpp kernel/qmacgesturerecognizer_p.h
+ LIBRARIES
+ ${FWAppKit}
+ z
+)
+
+qt_internal_extend_target(Widgets CONDITION WIN32
+ LIBRARIES
+ dwmapi
+ shell32
+ uxtheme
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_graphicseffect
+ SOURCES
+ effects/qgraphicseffect.cpp effects/qgraphicseffect.h effects/qgraphicseffect_p.h
+ effects/qpixmapfilter.cpp effects/qpixmapfilter_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_action
+ SOURCES
+ kernel/qaction.h
+ kernel/qaction_widgets.cpp kernel/qaction_widgets_p.h
+ kernel/qactiongroup.h
+ kernel/qwidgetaction.cpp kernel/qwidgetaction.h kernel/qwidgetaction_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_formlayout
+ SOURCES
+ kernel/qformlayout.cpp kernel/qformlayout.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_shortcut
+ SOURCES
+ kernel/qshortcut.h
+ kernel/qshortcut_widgets.cpp
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_tooltip
+ SOURCES
+ kernel/qtooltip.cpp kernel/qtooltip.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_whatsthis
+ SOURCES
+ kernel/qwhatsthis.cpp kernel/qwhatsthis.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_animation
+ SOURCES
+ styles/qstyleanimation.cpp styles/qstyleanimation_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_style_windows
+ SOURCES
+ styles/qwindowsstyle.cpp styles/qwindowsstyle_p.h
+ styles/qwindowsstyle_p_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_style_fusion
+ SOURCES
+ styles/qfusionstyle.cpp styles/qfusionstyle_p.h
+ styles/qfusionstyle_p_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_abstractbutton
+ SOURCES
+ widgets/qabstractbutton.cpp widgets/qabstractbutton.h widgets/qabstractbutton_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_abstractslider
+ SOURCES
+ widgets/qabstractslider.cpp widgets/qabstractslider.h widgets/qabstractslider_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_buttongroup
+ SOURCES
+ widgets/qbuttongroup.cpp widgets/qbuttongroup.h widgets/qbuttongroup_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_calendarwidget
+ SOURCES
+ widgets/qcalendarwidget.cpp widgets/qcalendarwidget.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_checkbox
+ SOURCES
+ widgets/qcheckbox.cpp widgets/qcheckbox.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_combobox
+ SOURCES
+ widgets/qcombobox.cpp widgets/qcombobox.h widgets/qcombobox_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_commandlinkbutton
+ SOURCES
+ widgets/qcommandlinkbutton.cpp widgets/qcommandlinkbutton.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_datetimeedit
+ SOURCES
+ widgets/qdatetimeedit.cpp widgets/qdatetimeedit.h widgets/qdatetimeedit_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_dial
+ SOURCES
+ widgets/qdial.cpp widgets/qdial.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_dockwidget
+ SOURCES
+ widgets/qdockarealayout.cpp widgets/qdockarealayout_p.h
+ widgets/qdockwidget.cpp widgets/qdockwidget.h widgets/qdockwidget_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_effects
+ SOURCES
+ widgets/qeffects.cpp widgets/qeffects_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_fontcombobox
+ SOURCES
+ widgets/qfontcombobox.cpp widgets/qfontcombobox.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_groupbox
+ SOURCES
+ widgets/qgroupbox.cpp widgets/qgroupbox.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_keysequenceedit
+ SOURCES
+ widgets/qkeysequenceedit.cpp widgets/qkeysequenceedit.h widgets/qkeysequenceedit_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_label
+ SOURCES
+ widgets/qlabel.cpp widgets/qlabel.h widgets/qlabel_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_lcdnumber
+ SOURCES
+ widgets/qlcdnumber.cpp widgets/qlcdnumber.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_lineedit
+ SOURCES
+ widgets/qlineedit.cpp widgets/qlineedit.h widgets/qlineedit_p.cpp widgets/qlineedit_p.h
+ widgets/qwidgetlinecontrol.cpp widgets/qwidgetlinecontrol_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_mainwindow
+ SOURCES
+ widgets/qmainwindow.cpp widgets/qmainwindow.h
+ widgets/qmainwindowlayout.cpp widgets/qmainwindowlayout_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_mdiarea
+ SOURCES
+ widgets/qmdiarea.cpp widgets/qmdiarea.h widgets/qmdiarea_p.h
+ widgets/qmdisubwindow.cpp widgets/qmdisubwindow.h widgets/qmdisubwindow_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_menu
+ SOURCES
+ widgets/qmenu.cpp widgets/qmenu.h widgets/qmenu_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_menubar
+ SOURCES
+ widgets/qmenubar.cpp widgets/qmenubar.h widgets/qmenubar_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_progressbar
+ SOURCES
+ widgets/qprogressbar.cpp widgets/qprogressbar.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_pushbutton
+ SOURCES
+ widgets/qpushbutton.cpp widgets/qpushbutton.h widgets/qpushbutton_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_radiobutton
+ SOURCES
+ widgets/qradiobutton.cpp widgets/qradiobutton.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_resizehandler
+ SOURCES
+ widgets/qwidgetresizehandler.cpp widgets/qwidgetresizehandler_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_dialogbuttonbox
+ SOURCES
+ widgets/qdialogbuttonbox.cpp widgets/qdialogbuttonbox.h widgets/qdialogbuttonbox_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_rubberband
+ SOURCES
+ widgets/qrubberband.cpp widgets/qrubberband.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_scrollarea
+ SOURCES
+ widgets/qscrollarea.cpp widgets/qscrollarea.h widgets/qscrollarea_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_scrollbar
+ SOURCES
+ widgets/qscrollbar.cpp widgets/qscrollbar.h widgets/qscrollbar_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_sizegrip
+ SOURCES
+ widgets/qsizegrip.cpp widgets/qsizegrip.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_slider
+ SOURCES
+ widgets/qslider.cpp widgets/qslider.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_spinbox
+ SOURCES
+ widgets/qabstractspinbox.cpp widgets/qabstractspinbox.h widgets/qabstractspinbox_p.h
+ widgets/qspinbox.cpp widgets/qspinbox.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_splashscreen
+ SOURCES
+ widgets/qsplashscreen.cpp widgets/qsplashscreen.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_splitter
+ SOURCES
+ widgets/qsplitter.cpp widgets/qsplitter.h widgets/qsplitter_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_stackedwidget
+ SOURCES
+ widgets/qstackedwidget.cpp widgets/qstackedwidget.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_statusbar
+ SOURCES
+ widgets/qstatusbar.cpp widgets/qstatusbar.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_tabbar
+ SOURCES
+ widgets/qtabbar.cpp widgets/qtabbar.h widgets/qtabbar_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_textedit
+ SOURCES
+ widgets/qplaintextedit.cpp widgets/qplaintextedit.h widgets/qplaintextedit_p.h
+ widgets/qtextedit.cpp widgets/qtextedit.h widgets/qtextedit_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_textbrowser
+ SOURCES
+ widgets/qtextbrowser.cpp widgets/qtextbrowser.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_tabwidget
+ SOURCES
+ widgets/qtabwidget.cpp widgets/qtabwidget.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_toolbar
+ SOURCES
+ widgets/qtoolbar.cpp widgets/qtoolbar.h widgets/qtoolbar_p.h
+ widgets/qtoolbararealayout.cpp widgets/qtoolbararealayout_p.h
+ widgets/qtoolbarlayout.cpp widgets/qtoolbarlayout_p.h
+ widgets/qtoolbarseparator.cpp widgets/qtoolbarseparator_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_toolbox
+ SOURCES
+ widgets/qtoolbox.cpp widgets/qtoolbox.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_toolbutton
+ SOURCES
+ widgets/qtoolbarextension.cpp widgets/qtoolbarextension_p.h
+ widgets/qtoolbutton.cpp widgets/qtoolbutton.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_widgettextcontrol
+ SOURCES
+ widgets/qwidgettextcontrol.cpp widgets/qwidgettextcontrol_p.h
+ widgets/qwidgettextcontrol_p_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION MACOS AND (QT_FEATURE_menu OR QT_FEATURE_menubar)
+ SOURCES
+ widgets/qmenu_mac.mm
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_colordialog
+ SOURCES
+ dialogs/qcolordialog.cpp dialogs/qcolordialog.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_dialog
+ SOURCES
+ dialogs/qdialog.cpp dialogs/qdialog.h dialogs/qdialog_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_errormessage
+ SOURCES
+ dialogs/qerrormessage.cpp dialogs/qerrormessage.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_filedialog
+ SOURCES
+ dialogs/qfiledialog.cpp dialogs/qfiledialog.h dialogs/qfiledialog.ui dialogs/qfiledialog_p.h
+ dialogs/qsidebar.cpp dialogs/qsidebar_p.h
+ ENABLE_AUTOGEN_TOOLS
+ uic
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_filesystemmodel
+ SOURCES
+ dialogs/qfilesystemmodel.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_fontdialog
+ SOURCES
+ dialogs/qfontdialog.cpp dialogs/qfontdialog.h dialogs/qfontdialog_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_fscompleter
+ SOURCES
+ dialogs/qfscompleter_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_inputdialog
+ SOURCES
+ dialogs/qinputdialog.cpp dialogs/qinputdialog.h
+)
+
+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)
+ # Resources:
+ set(qmessagebox_resource_files
+ "dialogs/images/qtlogo-64.png"
+ )
+
+ qt_internal_add_resource(Widgets "qmessagebox"
+ PREFIX
+ "/qt-project.org/qmessagebox"
+ BASE
+ "dialogs"
+ FILES
+ ${qmessagebox_resource_files}
+ )
+endif()
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_progressdialog
+ SOURCES
+ dialogs/qprogressdialog.cpp dialogs/qprogressdialog.h
+)
+
+if(QT_FEATURE_wizard)
+ qt_internal_extend_target(Widgets CONDITION
+ SOURCES
+ dialogs/qwizard.cpp dialogs/qwizard.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
+ accessible/complexwidgets.cpp accessible/complexwidgets_p.h
+ accessible/qaccessiblemenu.cpp accessible/qaccessiblemenu_p.h
+ accessible/qaccessiblewidget.cpp accessible/qaccessiblewidget.h
+ accessible/qaccessiblewidgetfactory.cpp accessible/qaccessiblewidgetfactory_p.h
+ accessible/qaccessiblewidgets.cpp accessible/qaccessiblewidgets_p.h
+ accessible/rangecontrols.cpp accessible/rangecontrols_p.h
+ accessible/simplewidgets.cpp accessible/simplewidgets_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_accessibility AND QT_FEATURE_itemviews
+ SOURCES
+ accessible/itemviews.cpp accessible/itemviews_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_itemviews
+ SOURCES
+ itemviews/qabstractitemdelegate.cpp itemviews/qabstractitemdelegate.h itemviews/qabstractitemdelegate_p.h
+ itemviews/qabstractitemview.cpp itemviews/qabstractitemview.h itemviews/qabstractitemview_p.h
+ itemviews/qbsptree.cpp itemviews/qbsptree_p.h
+ itemviews/qheaderview.cpp itemviews/qheaderview.h itemviews/qheaderview_p.h
+ itemviews/qitemdelegate.cpp itemviews/qitemdelegate.h
+ itemviews/qitemeditorfactory.cpp itemviews/qitemeditorfactory.h itemviews/qitemeditorfactory_p.h
+ itemviews/qstyleditemdelegate.cpp itemviews/qstyleditemdelegate.h
+ itemviews/qwidgetitemdata_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_columnview
+ SOURCES
+ itemviews/qcolumnview.cpp itemviews/qcolumnview.h itemviews/qcolumnview_p.h
+ itemviews/qcolumnviewgrip.cpp itemviews/qcolumnviewgrip_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_datawidgetmapper
+ SOURCES
+ itemviews/qdatawidgetmapper.cpp itemviews/qdatawidgetmapper.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_listview
+ SOURCES
+ itemviews/qlistview.cpp itemviews/qlistview.h itemviews/qlistview_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_listwidget
+ SOURCES
+ itemviews/qlistwidget.cpp itemviews/qlistwidget.h itemviews/qlistwidget_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_tableview
+ SOURCES
+ itemviews/qtableview.cpp itemviews/qtableview.h itemviews/qtableview_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_tablewidget
+ SOURCES
+ itemviews/qtablewidget.cpp itemviews/qtablewidget.h itemviews/qtablewidget_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_treeview
+ SOURCES
+ itemviews/qtreeview.cpp itemviews/qtreeview.h itemviews/qtreeview_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_treewidget
+ SOURCES
+ itemviews/qtreewidget.cpp itemviews/qtreewidget.h itemviews/qtreewidget_p.h
+ itemviews/qtreewidgetitemiterator.cpp itemviews/qtreewidgetitemiterator.h
+ itemviews/qtreewidgetitemiterator_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_graphicsview
+ SOURCES
+ graphicsview/qgraph_p.h
+ graphicsview/qgraphicsanchorlayout.cpp graphicsview/qgraphicsanchorlayout.h graphicsview/qgraphicsanchorlayout_p.cpp graphicsview/qgraphicsanchorlayout_p.h
+ graphicsview/qgraphicsgridlayout.cpp graphicsview/qgraphicsgridlayout.h
+ graphicsview/qgraphicsgridlayoutengine.cpp graphicsview/qgraphicsgridlayoutengine_p.h
+ graphicsview/qgraphicsitem.cpp graphicsview/qgraphicsitem.h graphicsview/qgraphicsitem_p.h
+ graphicsview/qgraphicslayout.cpp graphicsview/qgraphicslayout.h graphicsview/qgraphicslayout_p.cpp graphicsview/qgraphicslayout_p.h
+ graphicsview/qgraphicslayoutitem.cpp graphicsview/qgraphicslayoutitem.h graphicsview/qgraphicslayoutitem_p.h
+ graphicsview/qgraphicslayoutstyleinfo.cpp graphicsview/qgraphicslayoutstyleinfo_p.h
+ graphicsview/qgraphicslinearlayout.cpp graphicsview/qgraphicslinearlayout.h
+ graphicsview/qgraphicsproxywidget.cpp graphicsview/qgraphicsproxywidget.h graphicsview/qgraphicsproxywidget_p.h
+ graphicsview/qgraphicsscene.cpp graphicsview/qgraphicsscene.h graphicsview/qgraphicsscene_p.h
+ graphicsview/qgraphicsscene_bsp.cpp graphicsview/qgraphicsscene_bsp_p.h
+ graphicsview/qgraphicsscenebsptreeindex.cpp graphicsview/qgraphicsscenebsptreeindex_p.h
+ graphicsview/qgraphicssceneevent.cpp graphicsview/qgraphicssceneevent.h
+ graphicsview/qgraphicssceneindex.cpp graphicsview/qgraphicssceneindex_p.h
+ graphicsview/qgraphicsscenelinearindex.cpp graphicsview/qgraphicsscenelinearindex_p.h
+ graphicsview/qgraphicstransform.cpp graphicsview/qgraphicstransform.h graphicsview/qgraphicstransform_p.h
+ graphicsview/qgraphicsview.cpp graphicsview/qgraphicsview.h graphicsview/qgraphicsview_p.h
+ graphicsview/qgraphicswidget.cpp graphicsview/qgraphicswidget.h graphicsview/qgraphicswidget_p.cpp graphicsview/qgraphicswidget_p.h
+ graphicsview/qsimplex_p.cpp graphicsview/qsimplex_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_easingcurve AND QT_FEATURE_graphicsview
+ SOURCES
+ graphicsview/qgraphicsitemanimation.cpp graphicsview/qgraphicsitemanimation.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_completer
+ SOURCES
+ util/qcompleter.cpp util/qcompleter.h util/qcompleter_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_scroller
+ SOURCES
+ util/qflickgesture.cpp util/qflickgesture_p.h
+ util/qscroller.cpp util/qscroller.h util/qscroller_p.h
+ util/qscrollerproperties.cpp util/qscrollerproperties.h util/qscrollerproperties_p.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_undocommand
+ SOURCES
+ util/qundostack.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_undogroup
+ SOURCES
+ util/qundogroup.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_undoview
+ SOURCES
+ util/qundoview.cpp util/qundoview.h
+)
+
+qt_internal_extend_target(Widgets CONDITION QT_FEATURE_xcb
+ SOURCES
+ util/qsystemtrayicon_x11.cpp
+)
+
+qt_internal_extend_target(Widgets CONDITION NOT QT_FEATURE_xcb
+ SOURCES
+ util/qsystemtrayicon_qpa.cpp
+)
+
+
+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)
+ add_subdirectory(doc/snippets/filedialogurls)
+ add_subdirectory(doc/snippets/graphicssceneadditem)
+ if(QT_FEATURE_opengl AND QT_FEATURE_printdialog)
+ add_subdirectory(doc/snippets/graphicsview)
+ endif()
+ add_subdirectory(doc/snippets/mdiarea)
+ add_subdirectory(doc/snippets/myscrollarea)
+endif()
diff --git a/src/widgets/Qt5WidgetsConfigExtras.cmake.in b/src/widgets/Qt5WidgetsConfigExtras.cmake.in
deleted file mode 100644
index 99d87e2e46..0000000000
--- a/src/widgets/Qt5WidgetsConfigExtras.cmake.in
+++ /dev/null
@@ -1,19 +0,0 @@
-
-if (NOT TARGET Qt5::uic)
- add_executable(Qt5::uic IMPORTED)
-
-!!IF isEmpty(CMAKE_BIN_DIR_IS_ABSOLUTE)
- set(imported_location \"${_qt5Widgets_install_prefix}/$${CMAKE_BIN_DIR}uic$$CMAKE_BIN_SUFFIX\")
-!!ELSE
- set(imported_location \"$${CMAKE_BIN_DIR}uic$$CMAKE_BIN_SUFFIX\")
-!!ENDIF
- _qt5_Widgets_check_file_exists(${imported_location})
-
- set_target_properties(Qt5::uic PROPERTIES
- IMPORTED_LOCATION ${imported_location}
- )
-endif()
-
-include(\"${CMAKE_CURRENT_LIST_DIR}/Qt5Widgets_AccessibleFactory.cmake\" OPTIONAL)
-
-set(Qt5Widgets_UIC_EXECUTABLE Qt5::uic)
diff --git a/src/widgets/Qt5WidgetsMacros.cmake b/src/widgets/Qt5WidgetsMacros.cmake
deleted file mode 100644
index 21e73d4f0c..0000000000
--- a/src/widgets/Qt5WidgetsMacros.cmake
+++ /dev/null
@@ -1,68 +0,0 @@
-#=============================================================================
-# Copyright 2005-2011 Kitware, Inc.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# * Neither the name of Kitware, Inc. nor the names of its
-# contributors may be used to endorse or promote products derived
-# from this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#=============================================================================
-
-######################################
-#
-# Macros for building Qt files
-#
-######################################
-
-include(CMakeParseArguments)
-
-
-# qt5_wrap_ui(outfiles inputfile ... )
-
-function(qt5_wrap_ui outfiles )
- set(options)
- set(oneValueArgs)
- set(multiValueArgs OPTIONS)
-
- cmake_parse_arguments(_WRAP_UI "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
-
- set(ui_files ${_WRAP_UI_UNPARSED_ARGUMENTS})
- set(ui_options ${_WRAP_UI_OPTIONS})
-
- foreach(it ${ui_files})
- get_filename_component(outfile ${it} NAME_WE)
- get_filename_component(infile ${it} ABSOLUTE)
- set(outfile ${CMAKE_CURRENT_BINARY_DIR}/ui_${outfile}.h)
- add_custom_command(OUTPUT ${outfile}
- COMMAND ${Qt5Widgets_UIC_EXECUTABLE}
- ARGS ${ui_options} -o ${outfile} ${infile}
- MAIN_DEPENDENCY ${infile} VERBATIM)
- set_source_files_properties(${infile} PROPERTIES SKIP_AUTOUIC ON)
- set_source_files_properties(${outfile} PROPERTIES SKIP_AUTOMOC ON)
- set_source_files_properties(${outfile} PROPERTIES SKIP_AUTOUIC ON)
- list(APPEND ${outfiles} ${outfile})
- endforeach()
- set(${outfiles} ${${outfiles}} PARENT_SCOPE)
-endfunction()
diff --git a/src/widgets/Qt6WidgetsMacros.cmake b/src/widgets/Qt6WidgetsMacros.cmake
new file mode 100644
index 0000000000..b15d1fe81d
--- /dev/null
+++ b/src/widgets/Qt6WidgetsMacros.cmake
@@ -0,0 +1,51 @@
+# Copyright 2005-2011 Kitware, Inc.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+######################################
+#
+# Macros for building Qt files
+#
+######################################
+
+
+# qt6_wrap_ui(outfiles inputfile ... )
+
+function(qt6_wrap_ui outfiles )
+ set(options)
+ set(oneValueArgs)
+ set(multiValueArgs OPTIONS)
+
+ cmake_parse_arguments(_WRAP_UI "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ set(ui_files ${_WRAP_UI_UNPARSED_ARGUMENTS})
+ set(ui_options ${_WRAP_UI_OPTIONS})
+
+ foreach(it ${ui_files})
+ get_filename_component(outfile ${it} NAME_WE)
+ get_filename_component(infile ${it} ABSOLUTE)
+ set(outfile ${CMAKE_CURRENT_BINARY_DIR}/ui_${outfile}.h)
+ add_custom_command(OUTPUT ${outfile}
+ DEPENDS ${QT_CMAKE_EXPORT_NAMESPACE}::uic
+ COMMAND ${QT_CMAKE_EXPORT_NAMESPACE}::uic
+ ARGS ${ui_options} -o ${outfile} ${infile}
+ MAIN_DEPENDENCY ${infile} VERBATIM)
+ set_source_files_properties(${infile} PROPERTIES SKIP_AUTOUIC ON)
+ set_source_files_properties(${outfile} PROPERTIES SKIP_AUTOMOC ON)
+ set_source_files_properties(${outfile} PROPERTIES SKIP_AUTOUIC ON)
+ list(APPEND ${outfiles} ${outfile})
+ endforeach()
+ set(${outfiles} ${${outfiles}} PARENT_SCOPE)
+endfunction()
+
+# This will override the CMake upstream command, because that one is for Qt 3.
+if(NOT QT_NO_CREATE_VERSIONLESS_FUNCTIONS)
+ function(qt_wrap_ui outfiles)
+ if(QT_DEFAULT_MAJOR_VERSION EQUAL 5)
+ qt5_wrap_ui("${outfiles}" ${ARGN})
+ elseif(QT_DEFAULT_MAJOR_VERSION EQUAL 6)
+ qt6_wrap_ui("${outfiles}" ${ARGN})
+ endif()
+ set("${outfiles}" "${${outfiles}}" PARENT_SCOPE)
+ endfunction()
+endif()
diff --git a/src/widgets/accessible/accessible.pri b/src/widgets/accessible/accessible.pri
deleted file mode 100644
index 06467d0ff0..0000000000
--- a/src/widgets/accessible/accessible.pri
+++ /dev/null
@@ -1,26 +0,0 @@
-# Qt accessibility module
-
-qtConfig(accessibility) {
- HEADERS += \
- accessible/qaccessiblewidget.h \
- accessible/qaccessiblewidgetfactory_p.h \
- accessible/complexwidgets_p.h \
- accessible/qaccessiblemenu_p.h \
- accessible/qaccessiblewidgets_p.h \
- accessible/rangecontrols_p.h \
- accessible/simplewidgets_p.h
-
- SOURCES += \
- accessible/qaccessiblewidget.cpp \
- accessible/qaccessiblewidgetfactory.cpp \
- accessible/complexwidgets.cpp \
- accessible/qaccessiblemenu.cpp \
- accessible/qaccessiblewidgets.cpp \
- accessible/rangecontrols.cpp \
- accessible/simplewidgets.cpp
-
- qtConfig(itemviews) {
- HEADERS += accessible/itemviews_p.h
- SOURCES += accessible/itemviews.cpp
- }
-}
diff --git a/src/widgets/accessible/complexwidgets.cpp b/src/widgets/accessible/complexwidgets.cpp
index ce2ceac938..77bf8504fa 100644
--- a/src/widgets/accessible/complexwidgets.cpp
+++ b/src/widgets/accessible/complexwidgets.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "complexwidgets_p.h"
@@ -57,7 +21,9 @@
#endif
#include <qstyle.h>
#include <qstyleoption.h>
+#if QT_CONFIG(tooltip)
#include <qtooltip.h>
+#endif
#if QT_CONFIG(whatsthis)
#include <qwhatsthis.h>
#endif
@@ -70,10 +36,12 @@
#endif
#include <QDebug>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
QString qt_accStripAmp(const QString &text);
QString qt_accHotKey(const QString &text);
@@ -110,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 {
@@ -209,10 +179,18 @@ QAccessibleTabBar::QAccessibleTabBar(QWidget *w)
QAccessibleTabBar::~QAccessibleTabBar()
{
- for (QAccessible::Id id : qAsConst(m_childInterfaces))
+ for (QAccessible::Id id : std::as_const(m_childInterfaces))
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
{
@@ -290,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)
@@ -315,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;
}
@@ -333,55 +367,86 @@ 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;
}
+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 (QComboBox *cBox = comboBox()) {
+ if (cBox->isEditable())
+ return child(1);
+ }
+ return nullptr;
+}
+
/*! \reimp */
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;
}
+QAccessible::State QAccessibleComboBox::state() const
+{
+ QAccessible::State s = QAccessibleWidget::state();
+
+ if (QComboBox *cBox = comboBox()) {
+ s.expandable = true;
+ s.expanded = isValid() && cBox->view()->isVisible();
+ s.editable = cBox->isEditable();
+ }
+ return s;
+}
+
QStringList QAccessibleComboBox::actionNames() const
{
return QStringList() << showMenuAction() << pressAction();
@@ -396,11 +461,28 @@ QString QAccessibleComboBox::localizedActionDescription(const QString &actionNam
void QAccessibleComboBox::doAction(const QString &actionName)
{
- if (actionName == showMenuAction() || actionName == pressAction()) {
- if (comboBox()->view()->isVisible()) {
- comboBox()->hidePopup();
- } else {
- comboBox()->showPopup();
+ 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) {
+ cBox->setCurrentIndex(list->selectedRows().at(0));
+ }
+ cBox->setFocus();
+#endif
+ 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);
+ }
+#endif
+ }
}
}
}
@@ -427,7 +509,7 @@ QAccessibleInterface *QAccessibleAbstractScrollArea::child(int index) const
int QAccessibleAbstractScrollArea::childCount() const
{
- return accessibleChildren().count();
+ return accessibleChildren().size();
}
int QAccessibleAbstractScrollArea::indexOfChild(const QAccessibleInterface *child) const
@@ -473,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.
@@ -500,9 +588,9 @@ QAccessibleAbstractScrollArea::elementType(QWidget *widget) const
return Self;
if (widget == abstractScrollArea()->viewport())
return Viewport;
- if (widget->objectName() == QLatin1String("qt_scrollarea_hcontainer"))
+ if (widget->objectName() == "qt_scrollarea_hcontainer"_L1)
return HorizontalContainer;
- if (widget->objectName() == QLatin1String("qt_scrollarea_vcontainer"))
+ if (widget->objectName() == "qt_scrollarea_vcontainer"_L1)
return VerticalContainer;
if (widget == abstractScrollArea()->cornerWidget())
return CornerWidget;
@@ -525,4 +613,4 @@ QAccessibleScrollArea::QAccessibleScrollArea(QWidget *widget)
QT_END_NAMESPACE
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
diff --git a/src/widgets/accessible/complexwidgets_p.h b/src/widgets/accessible/complexwidgets_p.h
index 335e257476..5169aa8243 100644
--- a/src/widgets/accessible/complexwidgets_p.h
+++ b/src/widgets/accessible/complexwidgets_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 COMPLEXWIDGETS_H
#define COMPLEXWIDGETS_H
@@ -60,7 +24,7 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
class QAbstractButton;
class QHeaderView;
@@ -106,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;
@@ -119,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;
@@ -135,9 +111,12 @@ public:
QAccessibleInterface *childAt(int x, int y) const override;
int indexOfChild(const QAccessibleInterface *child) const override;
QAccessibleInterface* child(int index) const override;
+ QAccessibleInterface* focusChild() const override;
QString text(QAccessible::Text t) const override;
+ QAccessible::State state() const override;
+
// QAccessibleActionInterface
QStringList actionNames() const override;
QString localizedActionDescription(const QString &actionName) const override;
@@ -149,7 +128,7 @@ protected:
};
#endif // QT_CONFIG(combobox)
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/itemviews.cpp b/src/widgets/accessible/itemviews.cpp
index 5a7fdf9a03..aa5f729820 100644
--- a/src/widgets/accessible/itemviews.cpp
+++ b/src/widgets/accessible/itemviews.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "itemviews_p.h"
@@ -52,7 +16,7 @@
#endif
#include <private/qwidget_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QT_BEGIN_NAMESPACE
@@ -75,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)
@@ -115,7 +84,7 @@ bool QAccessibleTable::isValid() const
QAccessibleTable::~QAccessibleTable()
{
- for (QAccessible::Id id : qAsConst(childToId))
+ for (QAccessible::Id id : std::as_const(childToId))
QAccessible::deleteAccessibleInterface(id);
}
@@ -149,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));
@@ -167,51 +138,59 @@ 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
{
if (!view()->selectionModel())
return 0;
- return view()->selectionModel()->selectedIndexes().count();
+ return view()->selectionModel()->selectedIndexes().size();
}
int QAccessibleTable::selectedColumnCount() const
{
if (!view()->selectionModel())
return 0;
- return view()->selectionModel()->selectedColumns().count();
+ return view()->selectionModel()->selectedColumns().size();
}
int QAccessibleTable::selectedRowCount() const
{
if (!view()->selectionModel())
return 0;
- return view()->selectionModel()->selectedRows().count();
+ return view()->selectionModel()->selectedRows().size();
}
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
@@ -273,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;
@@ -289,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;
@@ -303,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
@@ -352,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;
@@ -388,20 +387,100 @@ 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;
+}
+
+int QAccessibleTable::selectedItemCount() const
+{
+ return selectedCellCount();
+}
+
+QList<QAccessibleInterface*> QAccessibleTable::selectedItems() const
+{
+ return selectedCells();
+}
+
+bool QAccessibleTable::isSelected(QAccessibleInterface *childCell) const
+{
+ if (!childCell || childCell->parent() != this) {
+ qWarning() << "QAccessibleTable::isSelected: Accessible interface must be a direct child of the table interface.";
+ return false;
+ }
+
+ const QAccessibleTableCellInterface *cell = childCell->tableCellInterface();
+ if (cell)
+ return cell->isSelected();
+
+ return false;
+}
+
+bool QAccessibleTable::select(QAccessibleInterface *childCell)
+{
+ if (!childCell || childCell->parent() != this) {
+ qWarning() << "QAccessibleTable::select: Accessible interface must be a direct child of the table interface.";
+ return false;
+ }
+
+ if (!childCell->tableCellInterface()) {
+ qWarning() << "QAccessibleTable::select: Accessible interface doesn't implement table cell interface.";
+ return false;
+ }
+
+ if (childCell->role() == QAccessible::Cell || childCell->role() == QAccessible::ListItem || childCell->role() == QAccessible::TreeItem) {
+ QAccessibleTableCell* cell = static_cast<QAccessibleTableCell*>(childCell);
+ cell->selectCell();
+ return true;
+ }
+
+ return false;
+}
+
+bool QAccessibleTable::unselect(QAccessibleInterface *childCell)
+{
+ if (!childCell || childCell->parent() != this) {
+ qWarning() << "QAccessibleTable::select: Accessible interface must be a direct child of the table interface.";
+ return false;
+ }
+
+ if (!childCell->tableCellInterface()) {
+ qWarning() << "QAccessibleTable::unselect: Accessible interface doesn't implement table cell interface.";
+ return false;
+ }
+
+ if (childCell->role() == QAccessible::Cell || childCell->role() == QAccessible::ListItem || childCell->role() == QAccessible::TreeItem) {
+ QAccessibleTableCell* cell = static_cast<QAccessibleTableCell*>(childCell);
+ cell->unselectCell();
+ return true;
+ }
+
+ return false;
+}
+
+bool QAccessibleTable::selectAll()
+{
+ view()->selectAll();
+ return true;
+}
+
+bool QAccessibleTable::clear()
+{
+ view()->selectionModel()->clearSelection();
return true;
}
+
QAccessible::Role QAccessibleTable::role() const
{
return m_role;
@@ -409,7 +488,27 @@ QAccessible::Role QAccessibleTable::role() const
QAccessible::State QAccessibleTable::state() const
{
- return QAccessible::State();
+ QAccessible::State state;
+ const auto *w = view();
+
+ if (w->testAttribute(Qt::WA_WState_Visible) == false)
+ state.invisible = true;
+ if (w->focusPolicy() != Qt::NoFocus)
+ state.focusable = true;
+ if (w->hasFocus())
+ state.focused = true;
+ if (!w->isEnabled())
+ state.disabled = true;
+ if (w->isWindow()) {
+ if (w->windowFlags() & Qt::WindowSystemMenuHint)
+ state.movable = true;
+ if (w->minimumSize() != w->maximumSize())
+ state.sizeable = true;
+ if (w->isActiveWindow())
+ state.active = true;
+ }
+
+ return state;
}
QAccessibleInterface *QAccessibleTable::childAt(int x, int y) const
@@ -418,30 +517,44 @@ 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;
}
+QAccessibleInterface *QAccessibleTable::focusChild() const
+{
+ QModelIndex index = view()->currentIndex();
+ if (!index.isValid())
+ return nullptr;
+
+ return child(logicalIndex(index));
+}
+
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);
@@ -451,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 {
@@ -485,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());
@@ -500,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;
@@ -510,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);
@@ -540,6 +656,8 @@ QAccessibleInterface *QAccessibleTable::child(int logicalIndex) const
void *QAccessibleTable::interface_cast(QAccessible::InterfaceType t)
{
+ if (t == QAccessible::SelectionInterface)
+ return static_cast<QAccessibleSelectionInterface*>(this);
if (t == QAccessible::TableInterface)
return static_cast<QAccessibleTableInterface*>(this);
return nullptr;
@@ -553,7 +671,7 @@ void QAccessibleTable::modelChange(QAccessibleTableModelChangeEvent *event)
switch (event->modelChangeType()) {
case QAccessibleTableModelChangeEvent::ModelReset:
- for (QAccessible::Id id : qAsConst(childToId))
+ for (QAccessible::Id id : std::as_const(childToId))
QAccessible::deleteAccessibleInterface(id);
childToId.clear();
break;
@@ -661,7 +779,7 @@ QModelIndex QAccessibleTree::indexFromLogical(int row, int column) const
return QModelIndex();
const QTreeView *treeView = qobject_cast<const QTreeView*>(view());
- if (Q_UNLIKELY(row < 0 || column < 0 || treeView->d_func()->viewItems.count() <= row)) {
+ if (Q_UNLIKELY(row < 0 || column < 0 || treeView->d_func()->viewItems.size() <= row)) {
qWarning() << "QAccessibleTree::indexFromLogical: invalid index: " << row << column << " for " << treeView;
return QModelIndex();
}
@@ -675,20 +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
+{
+ 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 *>(theView);
+ const int row = treeView->d_func()->viewIndex(index) + (horizontalHeader() ? 1 : 0);
+ const int column = index.column();
+
+ int i = row * theModel->columnCount(theView->rootIndex()) + column;
return child(i);
}
@@ -696,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.count() + 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());
@@ -736,12 +877,14 @@ int QAccessibleTree::rowCount() const
{
const QTreeView *treeView = qobject_cast<const QTreeView*>(view());
Q_ASSERT(treeView);
- return treeView->d_func()->viewItems.count();
+ return treeView->d_func()->viewItems.size();
}
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())
@@ -749,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);
@@ -934,10 +1077,23 @@ QStringList QAccessibleTableCell::actionNames() const
void QAccessibleTableCell::doAction(const QString& actionName)
{
if (actionName == toggleAction()) {
- if (isSelected())
+#if defined(Q_OS_ANDROID)
+ QAccessibleInterface *parentInterface = parent();
+ while (parentInterface){
+ if (parentInterface->role() == QAccessible::ComboBox) {
+ selectCell();
+ parentInterface->actionInterface()->doAction(pressAction());
+ return;
+ } else {
+ parentInterface = parentInterface->parent();
+ }
+ }
+#endif
+ if (isSelected()) {
unselectCell();
- else
+ } else {
selectCell();
+ }
}
}
@@ -1004,7 +1160,7 @@ void QAccessibleTableCell::unselectCell()
//one cell is selected it cannot be unselected by the user
if ((selectionMode != QAbstractItemView::MultiSelection)
&& (selectionMode != QAbstractItemView::ExtendedSelection)
- && (view->selectionModel()->selectedIndexes().count() <= 1))
+ && (view->selectionModel()->selectedIndexes().size() <= 1))
return;
view->selectionModel()->select(m_index, QItemSelectionModel::Deselect);
@@ -1035,10 +1191,14 @@ QAccessible::State QAccessibleTableCell::state() const
st.selected = true;
if (view->selectionModel()->currentIndex() == m_index)
st.focused = true;
- if (m_index.model()->data(m_index, Qt::CheckStateRole).toInt() == Qt::Checked)
+
+ QVariant checkState = m_index.model()->data(m_index, Qt::CheckStateRole);
+ if (checkState.toInt() == Qt::Checked)
st.checked = true;
Qt::ItemFlags flags = m_index.flags();
+ if ((flags & Qt::ItemIsUserCheckable) && checkState.isValid())
+ st.checkable = true;
if (flags & Qt::ItemIsSelectable) {
st.selectable = true;
st.focusable = true;
@@ -1194,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
@@ -1231,4 +1396,4 @@ QHeaderView *QAccessibleTableHeaderCell::headerView() const
QT_END_NAMESPACE
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
diff --git a/src/widgets/accessible/itemviews_p.h b/src/widgets/accessible/itemviews_p.h
index 683ae9c948..ddc97baba1 100644
--- a/src/widgets/accessible/itemviews_p.h
+++ b/src/widgets/accessible/itemviews_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 ACCESSIBLE_ITEMVIEWS_H
#define ACCESSIBLE_ITEMVIEWS_H
@@ -62,12 +26,12 @@ QT_REQUIRE_CONFIG(itemviews);
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
class QAccessibleTableCell;
class QAccessibleTableHeaderCell;
-class QAccessibleTable :public QAccessibleTableInterface, public QAccessibleObject
+class QAccessibleTable :public QAccessibleTableInterface, public QAccessibleSelectionInterface, public QAccessibleObject
{
public:
explicit QAccessibleTable(QWidget *w);
@@ -79,6 +43,7 @@ public:
QRect rect() const override;
QAccessibleInterface *childAt(int x, int y) const override;
+ QAccessibleInterface *focusChild() const override;
int childCount() const override;
int indexOfChild(const QAccessibleInterface *) const override;
@@ -110,6 +75,15 @@ public:
virtual bool unselectRow(int row) override;
virtual bool unselectColumn(int column) override;
+ // QAccessibleSelectionInterface
+ virtual int selectedItemCount() const override;
+ virtual QList<QAccessibleInterface*> selectedItems() const override;
+ virtual bool isSelected(QAccessibleInterface *childCell) const override;
+ virtual bool select(QAccessibleInterface *childCell) override;
+ virtual bool unselect(QAccessibleInterface *childCell) override;
+ virtual bool selectAll() override;
+ virtual bool clear() override;
+
QAbstractItemView *view() const;
void modelChange(QAccessibleTableModelChangeEvent *event) override;
@@ -154,6 +128,7 @@ public:
QAccessibleInterface *childAt(int x, int y) const override;
+ QAccessibleInterface *focusChild() const override;
int childCount() const override;
QAccessibleInterface *child(int index) const override;
@@ -298,7 +273,7 @@ private:
};
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/qaccessiblemenu.cpp b/src/widgets/accessible/qaccessiblemenu.cpp
index 99a9444ff1..1d72a82456 100644
--- a/src/widgets/accessible/qaccessiblemenu.cpp
+++ b/src/widgets/accessible/qaccessiblemenu.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qaccessiblemenu_p.h"
@@ -45,11 +9,10 @@
#if QT_CONFIG(menubar)
#include <qmenubar.h>
#endif
-#include <QtWidgets/QAction>
#include <qstyle.h>
#include <private/qwidget_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QT_BEGIN_NAMESPACE
@@ -81,13 +44,13 @@ QMenu *QAccessibleMenu::menu() const
int QAccessibleMenu::childCount() const
{
- return menu()->actions().count();
+ return menu()->actions().size();
}
QAccessibleInterface *QAccessibleMenu::childAt(int x, int y) const
{
QAction *act = menu()->actionAt(menu()->mapFromGlobal(QPoint(x,y)));
- if(act && act->isSeparator())
+ if (act && act->isSeparator())
act = nullptr;
return act ? getOrCreateMenu(menu(), act) : nullptr;
}
@@ -118,16 +81,19 @@ QAccessibleInterface *QAccessibleMenu::child(int index) const
QAccessibleInterface *QAccessibleMenu::parent() const
{
if (QAction *menuAction = menu()->menuAction()) {
- const QList<QWidget*> parentCandidates =
- QList<QWidget*>() << menu()->parentWidget() << menuAction->associatedWidgets();
- for (QWidget *w : parentCandidates) {
- if (qobject_cast<QMenu*>(w)
+ QList<QObject *> parentCandidates;
+ const QList<QObject *> associatedObjects = menuAction->associatedObjects();
+ parentCandidates.reserve(associatedObjects.size() + 1);
+ parentCandidates << menu()->parentWidget() << associatedObjects;
+ for (QObject *object : std::as_const(parentCandidates)) {
+ if (qobject_cast<QMenu*>(object)
#if QT_CONFIG(menubar)
- || qobject_cast<QMenuBar*>(w)
+ || qobject_cast<QMenuBar*>(object)
#endif
) {
- if (w->actions().indexOf(menuAction) != -1)
- return getOrCreateMenu(w, menuAction);
+ QWidget *widget = static_cast<QWidget*>(object);
+ if (widget->actions().indexOf(menuAction) != -1)
+ return getOrCreateMenu(widget, menuAction);
}
}
}
@@ -157,7 +123,7 @@ QMenuBar *QAccessibleMenuBar::menuBar() const
int QAccessibleMenuBar::childCount() const
{
- return menuBar()->actions().count();
+ return menuBar()->actions().size();
}
QAccessibleInterface *QAccessibleMenuBar::child(int index) const
@@ -391,5 +357,5 @@ QWidget *QAccessibleMenuItem::owner() const
QT_END_NAMESPACE
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
diff --git a/src/widgets/accessible/qaccessiblemenu_p.h b/src/widgets/accessible/qaccessiblemenu_p.h
index 9acd2a42f9..8eb9a37e2d 100644
--- a/src/widgets/accessible/qaccessiblemenu_p.h
+++ b/src/widgets/accessible/qaccessiblemenu_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QACCESSIBLEMENU_H
#define QACCESSIBLEMENU_H
@@ -57,7 +21,7 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#if QT_CONFIG(menu)
class QMenu;
@@ -139,5 +103,5 @@ private:
#endif // QT_CONFIG(menu)
QT_END_NAMESPACE
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
#endif // QACCESSIBLEMENU_H
diff --git a/src/widgets/accessible/qaccessiblewidget.cpp b/src/widgets/accessible/qaccessiblewidget.cpp
index 1a7372728d..b0bb12ea86 100644
--- a/src/widgets/accessible/qaccessiblewidget.cpp
+++ b/src/widgets/accessible/qaccessiblewidget.cpp
@@ -1,45 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qaccessiblewidget.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qapplication.h"
#if QT_CONFIG(groupbox)
@@ -48,7 +12,9 @@
#if QT_CONFIG(label)
#include "qlabel.h"
#endif
+#if QT_CONFIG(tooltip)
#include "qtooltip.h"
+#endif
#if QT_CONFIG(whatsthis)
#include "qwhatsthis.h"
#endif
@@ -66,22 +32,9 @@
QT_BEGIN_NAMESPACE
-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() != QLatin1String("qt_rubberband")
- && w->objectName() != QLatin1String("qt_spinbox_lineedit"))
- widgets.append(w);
- }
- return widgets;
-}
+using namespace Qt::StringLiterals;
+
+QWidgetList _q_ac_childWidgets(const QWidget *widget);
static QString buddyString(const QWidget *widget)
{
@@ -110,18 +63,18 @@ static QString buddyString(const QWidget *widget)
/* This function will return the offset of the '&' in the text that would be
preceding the accelerator character.
If this text does not have an accelerator, -1 will be returned. */
-static int qt_accAmpIndex(const QString &text)
+static qsizetype qt_accAmpIndex(const QString &text)
{
#ifndef QT_NO_SHORTCUT
if (text.isEmpty())
return -1;
- int fa = 0;
- while ((fa = text.indexOf(QLatin1Char('&'), fa)) != -1) {
+ qsizetype fa = 0;
+ while ((fa = text.indexOf(u'&', fa)) != -1) {
++fa;
- if (fa < text.length()) {
+ if (fa < text.size()) {
// ignore "&&"
- if (text.at(fa) == QLatin1Char('&')) {
+ if (text.at(fa) == u'&') {
++fa;
continue;
@@ -142,21 +95,21 @@ static int qt_accAmpIndex(const QString &text)
QString qt_accStripAmp(const QString &text)
{
QString newText(text);
- int ampIndex = qt_accAmpIndex(newText);
+ qsizetype ampIndex = qt_accAmpIndex(newText);
if (ampIndex != -1)
newText.remove(ampIndex, 1);
- return newText.replace(QLatin1String("&&"), QLatin1String("&"));
+ return newText.replace("&&"_L1, "&"_L1);
}
QString qt_accHotKey(const QString &text)
{
#ifndef QT_NO_SHORTCUT
- int ampIndex = qt_accAmpIndex(text);
+ qsizetype ampIndex = qt_accAmpIndex(text);
if (ampIndex != -1)
return QKeySequence(Qt::ALT).toString(QKeySequence::NativeText) + text.at(ampIndex + 1);
#else
- Q_UNUSED(text)
+ Q_UNUSED(text);
#endif
return QString();
@@ -283,7 +236,7 @@ void QAccessibleWidget::addControllingSignal(const QString &signal)
QByteArray s = QMetaObject::normalizedSignature(signal.toLatin1());
if (Q_UNLIKELY(object()->metaObject()->indexOfSignal(s) < 0))
qWarning("Signal %s unknown in %s", s.constData(), object()->metaObject()->className());
- d->primarySignals << QLatin1String(s);
+ d->primarySignals << QLatin1StringView(s);
}
static inline bool isAncestor(const QObject *obj, const QObject *child)
@@ -297,10 +250,10 @@ static inline bool isAncestor(const QObject *obj, const QObject *child)
}
/*! \reimp */
-QVector<QPair<QAccessibleInterface*, QAccessible::Relation> >
+QList<QPair<QAccessibleInterface *, QAccessible::Relation>>
QAccessibleWidget::relations(QAccessible::Relation match /*= QAccessible::AllRelations*/) const
{
- QVector<QPair<QAccessibleInterface*, QAccessible::Relation> > rels;
+ QList<QPair<QAccessibleInterface *, QAccessible::Relation>> rels;
if (match & QAccessible::Label) {
const QAccessible::Relation rel = QAccessible::Label;
if (QWidget *parent = widget()->parentWidget()) {
@@ -308,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()) {
@@ -331,14 +284,14 @@ QAccessibleWidget::relations(QAccessible::Relation match /*= QAccessible::AllRel
if (match & QAccessible::Controlled) {
QObjectList allReceivers;
QObject *connectionObject = object();
- for (int sig = 0; sig < d->primarySignals.count(); ++sig) {
+ for (int sig = 0; sig < d->primarySignals.size(); ++sig) {
const QObjectList receivers = connectionObject->d_func()->receiverList(d->primarySignals.at(sig).toLatin1());
allReceivers += receivers;
}
allReceivers.removeAll(object()); //### The object might connect to itself internally
- for (int i = 0; i < allReceivers.count(); ++i) {
+ for (int i = 0; i < allReceivers.size(); ++i) {
const QAccessible::Relation rel = QAccessible::Controlled;
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(allReceivers.at(i));
if (iface)
@@ -359,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;
@@ -387,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();
}
@@ -396,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()));
}
@@ -425,7 +378,7 @@ QString QAccessibleWidget::text(QAccessible::Text t) const
break;
case QAccessible::Description:
str = widget()->accessibleDescription();
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
if (str.isEmpty())
str = widget()->toolTip();
#endif
@@ -530,4 +483,4 @@ void *QAccessibleWidget::interface_cast(QAccessible::InterfaceType t)
QT_END_NAMESPACE
-#endif //QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
diff --git a/src/widgets/accessible/qaccessiblewidget.h b/src/widgets/accessible/qaccessiblewidget.h
index 63789a595f..c237e25d4a 100644
--- a/src/widgets/accessible/qaccessiblewidget.h
+++ b/src/widgets/accessible/qaccessiblewidget.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QACCESSIBLEWIDGET_H
#define QACCESSIBLEWIDGET_H
@@ -46,7 +10,7 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
class QAccessibleWidgetPrivate;
@@ -59,7 +23,8 @@ public:
QWindow *window() const override;
int childCount() const override;
int indexOfChild(const QAccessibleInterface *child) const override;
- QVector<QPair<QAccessibleInterface*, QAccessible::Relation> > relations(QAccessible::Relation match = QAccessible::AllRelations) const override;
+ QList<QPair<QAccessibleInterface *, QAccessible::Relation>>
+ relations(QAccessible::Relation match = QAccessible::AllRelations) const override;
QAccessibleInterface *focusChild() const override;
QRect rect() const override;
@@ -93,7 +58,7 @@ private:
};
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/qaccessiblewidgetfactory.cpp b/src/widgets/accessible/qaccessiblewidgetfactory.cpp
index d59da86076..e13b7ebcf7 100644
--- a/src/widgets/accessible/qaccessiblewidgetfactory.cpp
+++ b/src/widgets/accessible/qaccessiblewidgetfactory.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qaccessiblewidgets_p.h"
#include "qaccessiblemenu_p.h"
@@ -56,10 +20,12 @@
#include <qvariant.h>
#include <qaccessible.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
QAccessibleInterface *qAccessibleFactory(const QString &classname, QObject *object)
{
QAccessibleInterface *iface = nullptr;
@@ -77,156 +43,156 @@ QAccessibleInterface *qAccessibleFactory(const QString &classname, QObject *obje
if (false) {
#if QT_CONFIG(lineedit)
- } else if (classname == QLatin1String("QLineEdit")) {
- if (widget->objectName() == QLatin1String("qt_spinbox_lineedit"))
+ } else if (classname == "QLineEdit"_L1) {
+ if (widget->objectName() == "qt_spinbox_lineedit"_L1)
iface = nullptr;
else
iface = new QAccessibleLineEdit(widget);
#endif
#if QT_CONFIG(combobox)
- } else if (classname == QLatin1String("QComboBox")) {
+ } else if (classname == "QComboBox"_L1) {
iface = new QAccessibleComboBox(widget);
#endif
#if QT_CONFIG(spinbox)
- } else if (classname == QLatin1String("QAbstractSpinBox")) {
+ } else if (classname == "QAbstractSpinBox"_L1) {
iface = new QAccessibleAbstractSpinBox(widget);
- } else if (classname == QLatin1String("QSpinBox")) {
+ } else if (classname == "QSpinBox"_L1) {
iface = new QAccessibleSpinBox(widget);
- } else if (classname == QLatin1String("QDoubleSpinBox")) {
+ } else if (classname == "QDoubleSpinBox"_L1) {
iface = new QAccessibleDoubleSpinBox(widget);
#endif
#if QT_CONFIG(scrollbar)
- } else if (classname == QLatin1String("QScrollBar")) {
+ } else if (classname == "QScrollBar"_L1) {
iface = new QAccessibleScrollBar(widget);
#endif
#if QT_CONFIG(slider)
- } else if (classname == QLatin1String("QAbstractSlider")) {
+ } else if (classname == "QAbstractSlider"_L1) {
iface = new QAccessibleAbstractSlider(widget);
- } else if (classname == QLatin1String("QSlider")) {
+ } else if (classname == "QSlider"_L1) {
iface = new QAccessibleSlider(widget);
#endif
#if QT_CONFIG(toolbutton)
- } else if (classname == QLatin1String("QToolButton")) {
+ } else if (classname == "QToolButton"_L1) {
iface = new QAccessibleToolButton(widget);
#endif // QT_CONFIG(toolbutton)
#if QT_CONFIG(abstractbutton)
- } else if (classname == QLatin1String("QCheckBox")
- || classname == QLatin1String("QRadioButton")
- || classname == QLatin1String("QPushButton")
- || classname == QLatin1String("QAbstractButton")) {
+ } else if (classname == "QCheckBox"_L1
+ || classname == "QRadioButton"_L1
+ || classname == "QPushButton"_L1
+ || classname == "QAbstractButton"_L1) {
iface = new QAccessibleButton(widget);
#endif
- } else if (classname == QLatin1String("QDialog")) {
+ } else if (classname == "QDialog"_L1) {
iface = new QAccessibleWidget(widget, QAccessible::Dialog);
- } else if (classname == QLatin1String("QMessageBox")) {
- iface = new QAccessibleWidget(widget, QAccessible::AlertMessage);
+#if QT_CONFIG(messagebox)
+ } else if (classname == "QMessageBox"_L1) {
+ iface = new QAccessibleMessageBox(widget);
+#endif
#if QT_CONFIG(mainwindow)
- } else if (classname == QLatin1String("QMainWindow")) {
+ } else if (classname == "QMainWindow"_L1) {
iface = new QAccessibleMainWindow(widget);
#endif
- } else if (classname == QLatin1String("QLabel") || classname == QLatin1String("QLCDNumber")) {
+ } else if (classname == "QLabel"_L1 || classname == "QLCDNumber"_L1) {
iface = new QAccessibleDisplay(widget);
#if QT_CONFIG(groupbox)
- } else if (classname == QLatin1String("QGroupBox")) {
+ } else if (classname == "QGroupBox"_L1) {
iface = new QAccessibleGroupBox(widget);
#endif
- } else if (classname == QLatin1String("QStatusBar")) {
+ } else if (classname == "QStatusBar"_L1) {
iface = new QAccessibleDisplay(widget);
#if QT_CONFIG(progressbar)
- } else if (classname == QLatin1String("QProgressBar")) {
+ } else if (classname == "QProgressBar"_L1) {
iface = new QAccessibleProgressBar(widget);
#endif
- } else if (classname == QLatin1String("QToolBar")) {
+ } else if (classname == "QToolBar"_L1) {
iface = new QAccessibleWidget(widget, QAccessible::ToolBar, widget->windowTitle());
#if QT_CONFIG(menubar)
- } else if (classname == QLatin1String("QMenuBar")) {
+ } else if (classname == "QMenuBar"_L1) {
iface = new QAccessibleMenuBar(widget);
#endif
#if QT_CONFIG(menu)
- } else if (classname == QLatin1String("QMenu")) {
+ } else if (classname == "QMenu"_L1) {
iface = new QAccessibleMenu(widget);
#endif
#if QT_CONFIG(treeview)
- } else if (classname == QLatin1String("QTreeView")) {
+ } else if (classname == "QTreeView"_L1) {
iface = new QAccessibleTree(widget);
#endif // QT_CONFIG(treeview)
#if QT_CONFIG(itemviews)
- } else if (classname == QLatin1String("QTableView") || classname == QLatin1String("QListView")) {
+ } 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 == QLatin1String("QTabBar")) {
+ } else if (classname == "QTabBar"_L1) {
iface = new QAccessibleTabBar(widget);
#endif
- } else if (classname == QLatin1String("QSizeGrip")) {
+ } else if (classname == "QSizeGrip"_L1) {
iface = new QAccessibleWidget(widget, QAccessible::Grip);
#if QT_CONFIG(splitter)
- } else if (classname == QLatin1String("QSplitter")) {
+ } else if (classname == "QSplitter"_L1) {
iface = new QAccessibleWidget(widget, QAccessible::Splitter);
- } else if (classname == QLatin1String("QSplitterHandle")) {
+ } else if (classname == "QSplitterHandle"_L1) {
iface = new QAccessibleWidget(widget, QAccessible::Grip);
#endif
#if QT_CONFIG(textedit) && !defined(QT_NO_CURSOR)
- } else if (classname == QLatin1String("QTextEdit")) {
+ } else if (classname == "QTextEdit"_L1) {
iface = new QAccessibleTextEdit(widget);
- } else if (classname == QLatin1String("QPlainTextEdit")) {
+ } else if (classname == "QPlainTextEdit"_L1) {
iface = new QAccessiblePlainTextEdit(widget);
#endif
- } else if (classname == QLatin1String("QTipLabel")) {
+ } else if (classname == "QTipLabel"_L1) {
iface = new QAccessibleDisplay(widget, QAccessible::ToolTip);
- } else if (classname == QLatin1String("QFrame")) {
+ } else if (classname == "QFrame"_L1) {
iface = new QAccessibleWidget(widget, QAccessible::Border);
#if QT_CONFIG(stackedwidget)
- } else if (classname == QLatin1String("QStackedWidget")) {
+ } else if (classname == "QStackedWidget"_L1) {
iface = new QAccessibleStackedWidget(widget);
#endif
#if QT_CONFIG(toolbox)
- } else if (classname == QLatin1String("QToolBox")) {
+ } else if (classname == "QToolBox"_L1) {
iface = new QAccessibleToolBox(widget);
#endif
#if QT_CONFIG(mdiarea)
- } else if (classname == QLatin1String("QMdiArea")) {
+ } else if (classname == "QMdiArea"_L1) {
iface = new QAccessibleMdiArea(widget);
- } else if (classname == QLatin1String("QMdiSubWindow")) {
+ } else if (classname == "QMdiSubWindow"_L1) {
iface = new QAccessibleMdiSubWindow(widget);
#endif
#if QT_CONFIG(dialogbuttonbox)
- } else if (classname == QLatin1String("QDialogButtonBox")) {
+ } else if (classname == "QDialogButtonBox"_L1) {
iface = new QAccessibleDialogButtonBox(widget);
#endif
#if QT_CONFIG(dial)
- } else if (classname == QLatin1String("QDial")) {
+ } else if (classname == "QDial"_L1) {
iface = new QAccessibleDial(widget);
#endif
#if QT_CONFIG(rubberband)
- } else if (classname == QLatin1String("QRubberBand")) {
+ } else if (classname == "QRubberBand"_L1) {
iface = new QAccessibleWidget(widget, QAccessible::Border);
#endif
#if QT_CONFIG(textbrowser) && !defined(QT_NO_CURSOR)
- } else if (classname == QLatin1String("QTextBrowser")) {
+ } else if (classname == "QTextBrowser"_L1) {
iface = new QAccessibleTextBrowser(widget);
#endif
#if QT_CONFIG(scrollarea)
- } else if (classname == QLatin1String("QAbstractScrollArea")) {
+ } else if (classname == "QAbstractScrollArea"_L1) {
iface = new QAccessibleAbstractScrollArea(widget);
- } else if (classname == QLatin1String("QScrollArea")) {
+ } else if (classname == "QScrollArea"_L1) {
iface = new QAccessibleScrollArea(widget);
#endif
#if QT_CONFIG(calendarwidget)
- } else if (classname == QLatin1String("QCalendarWidget")) {
+ } else if (classname == "QCalendarWidget"_L1) {
iface = new QAccessibleCalendarWidget(widget);
#endif
#if QT_CONFIG(dockwidget)
- } else if (classname == QLatin1String("QDockWidget")) {
+ } else if (classname == "QDockWidget"_L1) {
iface = new QAccessibleDockWidget(widget);
#endif
- } else if (classname == QLatin1String("QDesktopScreenWidget")) {
- iface = nullptr;
- } else if (classname == QLatin1String("QWidget")) {
+ } else if (classname == "QWidget"_L1) {
iface = new QAccessibleWidget(widget);
- } else if (classname == QLatin1String("QWindowContainer")) {
+ } else if (classname == "QWindowContainer"_L1) {
iface = new QAccessibleWindowContainer(widget);
}
@@ -235,4 +201,4 @@ QAccessibleInterface *qAccessibleFactory(const QString &classname, QObject *obje
QT_END_NAMESPACE
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
diff --git a/src/widgets/accessible/qaccessiblewidgetfactory_p.h b/src/widgets/accessible/qaccessiblewidgetfactory_p.h
index 5da609ddca..eb37b33ff7 100644
--- a/src/widgets/accessible/qaccessiblewidgetfactory_p.h
+++ b/src/widgets/accessible/qaccessiblewidgetfactory_p.h
@@ -1,44 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QtWidgets/private/qtwidgetsglobal_p.h>
-#include <QtGui/qaccessible.h>
#ifndef QACCESSIBLEWIDGETFACTORY_H
#define QACCESSIBLEWIDGETFACTORY_H
@@ -56,6 +19,10 @@
QT_BEGIN_NAMESPACE
+class QObject;
+class QAccessibleInterface;
+class QString;
+
QAccessibleInterface *qAccessibleFactory(const QString &classname, QObject *object);
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/qaccessiblewidgets.cpp b/src/widgets/accessible/qaccessiblewidgets.cpp
index 574be1f5ea..5c2a3bd02b 100644
--- a/src/widgets/accessible/qaccessiblewidgets.cpp
+++ b/src/widgets/accessible/qaccessiblewidgets.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qaccessiblewidgets_p.h"
#include "qabstracttextdocumentlayout.h"
@@ -92,14 +56,16 @@
#include <QMenu>
#endif
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QT_BEGIN_NAMESPACE
+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)
@@ -114,8 +80,10 @@ QList<QWidget*> childWidgets(const QWidget *widget)
#if QT_CONFIG(menu)
&& !qobject_cast<QMenu*>(w)
#endif
- && objectName != QLatin1String("qt_rubberband")
- && objectName != QLatin1String("qt_qmainwindow_extended_splitter")) {
+ // Exclude widgets used as implementation details
+ && objectName != "qt_rubberband"_L1
+ && objectName != "qt_qmainwindow_extended_splitter"_L1
+ && objectName != "qt_spinbox_lineedit"_L1) {
widgets.append(w);
}
}
@@ -127,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
@@ -224,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. */
@@ -393,7 +361,7 @@ QAccessibleMdiArea::QAccessibleMdiArea(QWidget *widget)
int QAccessibleMdiArea::childCount() const
{
- return mdiArea()->subWindowList().count();
+ return mdiArea()->subWindowList().size();
}
QAccessibleInterface *QAccessibleMdiArea::child(int index) const
@@ -432,7 +400,7 @@ QString QAccessibleMdiSubWindow::text(QAccessible::Text textType) const
{
if (textType == QAccessible::Name) {
QString title = mdiSubWindow()->windowTitle();
- title.replace(QLatin1String("[*]"), QLatin1String(""));
+ title.remove("[*]"_L1);
return title;
}
return QAccessibleWidget::text(textType);
@@ -570,7 +538,7 @@ QCalendarWidget *QAccessibleCalendarWidget::calendarWidget() const
QAbstractItemView *QAccessibleCalendarWidget::calendarView() const
{
for (QObject *child : calendarWidget()->children()) {
- if (child->objectName() == QLatin1String("qt_calendar_calendarview"))
+ if (child->objectName() == "qt_calendar_calendarview"_L1)
return static_cast<QAbstractItemView *>(child);
}
return nullptr;
@@ -579,7 +547,7 @@ QAbstractItemView *QAccessibleCalendarWidget::calendarView() const
QWidget *QAccessibleCalendarWidget::navigationBar() const
{
for (QObject *child : calendarWidget()->children()) {
- if (child->objectName() == QLatin1String("qt_calendar_navigationbar"))
+ if (child->objectName() == "qt_calendar_navigationbar"_L1)
return static_cast<QWidget *>(child);
}
return nullptr;
@@ -761,7 +729,7 @@ class AttributeFormatterRef {
public:
template <typename RHS>
void operator=(RHS &&rhs)
- { string += QLatin1String(key) + QLatin1Char(':') + std::forward<RHS>(rhs) + QLatin1Char(';'); }
+ { string += QLatin1StringView(key) + u':' + std::forward<RHS>(rhs) + u';'; }
};
/*!
@@ -769,7 +737,7 @@ public:
\brief Small string-builder class that supports a map-like API to serialize key-value pairs.
\code
AttributeFormatter attrs;
- attrs["foo"] = QLatinString("hello") + world + QLatin1Char('!');
+ attrs["foo"] = QLatinString("hello") + world + u'!';
\endcode
The key type is always \c{const char*}, and the right-hand-side can
be any QStringBuilder expression.
@@ -850,15 +818,15 @@ QString QAccessibleTextWidget::attributes(int offset, int *startOffset, int *end
const QFont charFormatFont = charFormat.font();
AttributeFormatter attrs;
- QString family = charFormatFont.family();
+ QString family = charFormatFont.families().value(0, QString());
if (!family.isEmpty()) {
- family = family.replace('\\', QLatin1String("\\\\"));
- family = family.replace(':', QLatin1String("\\:"));
- family = family.replace(',', QLatin1String("\\,"));
- family = family.replace('=', QLatin1String("\\="));
- family = family.replace(';', QLatin1String("\\;"));
- family = family.replace('\"', QLatin1String("\\\""));
- attrs["font-family"] = QLatin1Char('"') + family + QLatin1Char('"');
+ family = family.replace(u'\\', "\\\\"_L1);
+ family = family.replace(u':', "\\:"_L1);
+ family = family.replace(u',', "\\,"_L1);
+ family = family.replace(u'=', "\\="_L1);
+ family = family.replace(u';', "\\;"_L1);
+ family = family.replace(u'\"', "\\\""_L1);
+ attrs["font-family"] = u'"' + family + u'"';
}
int fontSize = int(charFormatFont.pointSize());
@@ -871,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;
@@ -900,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()) {
@@ -966,7 +936,7 @@ QString QAccessibleTextWidget::text(int startOffset, int endOffset) const
cursor.setPosition(startOffset, QTextCursor::MoveAnchor);
cursor.setPosition(endOffset, QTextCursor::KeepAnchor);
- return cursor.selectedText().replace(QChar(QChar::ParagraphSeparator), QLatin1Char('\n'));
+ return cursor.selectedText().replace(QChar(QChar::ParagraphSeparator), u'\n');
}
QPoint QAccessibleTextWidget::scrollBarPosition() const
@@ -1105,8 +1075,8 @@ QAccessibleMainWindow::QAccessibleMainWindow(QWidget *widget)
QAccessibleInterface *QAccessibleMainWindow::child(int index) const
{
- QList<QWidget*> kids = childWidgets(mainWindow());
- if (index >= 0 && index < kids.count()) {
+ QList<QWidget*> kids = _q_ac_childWidgets(mainWindow());
+ if (index >= 0 && index < kids.size()) {
return QAccessible::queryAccessibleInterface(kids.at(index));
}
return nullptr;
@@ -1114,13 +1084,13 @@ QAccessibleInterface *QAccessibleMainWindow::child(int index) const
int QAccessibleMainWindow::childCount() const
{
- QList<QWidget*> kids = childWidgets(mainWindow());
- return kids.count();
+ 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()));
}
@@ -1133,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)) {
@@ -1152,4 +1122,4 @@ QMainWindow *QAccessibleMainWindow::mainWindow() const
QT_END_NAMESPACE
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
diff --git a/src/widgets/accessible/qaccessiblewidgets_p.h b/src/widgets/accessible/qaccessiblewidgets_p.h
index 87f0b888a0..6d06f294e8 100644
--- a/src/widgets/accessible/qaccessiblewidgets_p.h
+++ b/src/widgets/accessible/qaccessiblewidgets_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QACCESSIBLEWIDGETS_H
#define QACCESSIBLEWIDGETS_H
@@ -54,10 +18,9 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtWidgets/qaccessiblewidget.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include <QtCore/QPointer>
-#include <QtCore/QPair>
QT_BEGIN_NAMESPACE
@@ -319,7 +282,7 @@ public:
};
#endif // QT_CONFIG(mainwindow)
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/rangecontrols.cpp b/src/widgets/accessible/rangecontrols.cpp
index b5b8608418..b172c10044 100644
--- a/src/widgets/accessible/rangecontrols.cpp
+++ b/src/widgets/accessible/rangecontrols.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "rangecontrols_p.h"
@@ -65,7 +29,9 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_ACCESSIBILITY
+using namespace Qt::StringLiterals;
+
+#if QT_CONFIG(accessibility)
#if QT_CONFIG(spinbox)
QAccessibleAbstractSpinBox::QAccessibleAbstractSpinBox(QWidget *w)
@@ -253,8 +219,7 @@ QAccessibleSpinBox::QAccessibleSpinBox(QWidget *w)
: QAccessibleAbstractSpinBox(w)
{
Q_ASSERT(spinBox());
- addControllingSignal(QLatin1String("valueChanged(int)"));
- addControllingSignal(QLatin1String("valueChanged(QString)"));
+ addControllingSignal("valueChanged(int)"_L1);
}
/*!
@@ -271,8 +236,7 @@ QAccessibleDoubleSpinBox::QAccessibleDoubleSpinBox(QWidget *widget)
: QAccessibleAbstractSpinBox(widget)
{
Q_ASSERT(qobject_cast<QDoubleSpinBox *>(widget));
- addControllingSignal(QLatin1String("valueChanged(double)"));
- addControllingSignal(QLatin1String("valueChanged(QString)"));
+ addControllingSignal("valueChanged(double)"_L1);
}
/*!
@@ -309,7 +273,7 @@ QAccessibleScrollBar::QAccessibleScrollBar(QWidget *w)
: QAccessibleAbstractSlider(w, QAccessible::ScrollBar)
{
Q_ASSERT(scrollBar());
- addControllingSignal(QLatin1String("valueChanged(int)"));
+ addControllingSignal("valueChanged(int)"_L1);
}
/*! Returns the scroll bar. */
@@ -344,7 +308,7 @@ QAccessibleSlider::QAccessibleSlider(QWidget *w)
: QAccessibleAbstractSlider(w)
{
Q_ASSERT(slider());
- addControllingSignal(QLatin1String("valueChanged(int)"));
+ addControllingSignal("valueChanged(int)"_L1);
}
/*! Returns the slider. */
@@ -412,7 +376,7 @@ QAccessibleDial::QAccessibleDial(QWidget *widget)
: QAccessibleAbstractSlider(widget, QAccessible::Dial)
{
Q_ASSERT(qobject_cast<QDial *>(widget));
- addControllingSignal(QLatin1String("valueChanged(int)"));
+ addControllingSignal("valueChanged(int)"_L1);
}
QString QAccessibleDial::text(QAccessible::Text textType) const
@@ -429,6 +393,6 @@ QDial *QAccessibleDial::dial() const
}
#endif // QT_CONFIG(dial)
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/rangecontrols_p.h b/src/widgets/accessible/rangecontrols_p.h
index 1eada8e456..162cbbdb34 100644
--- a/src/widgets/accessible/rangecontrols_p.h
+++ b/src/widgets/accessible/rangecontrols_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 RANGECONTROLS_H
#define RANGECONTROLS_H
@@ -56,7 +20,7 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
class QAbstractSpinBox;
class QAbstractSlider;
@@ -199,7 +163,7 @@ protected:
};
#endif // QT_CONFIG(dial)
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/simplewidgets.cpp b/src/widgets/accessible/simplewidgets.cpp
index 9dbbe9c608..fbbbab857d 100644
--- a/src/widgets/accessible/simplewidgets.cpp
+++ b/src/widgets/accessible/simplewidgets.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "simplewidgets_p.h"
@@ -76,6 +40,12 @@
#include <qlineedit.h>
#include <private/qlineedit_p.h>
#endif
+#ifndef QT_NO_PICTURE
+#include <QtGui/qpicture.h>
+#endif
+#if QT_CONFIG(messagebox)
+#include <qmessagebox.h>
+#endif
#include <qstyle.h>
#include <qstyleoption.h>
#include <qtextdocument.h>
@@ -90,9 +60,11 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_ACCESSIBILITY
+using namespace Qt::StringLiterals;
-extern QList<QWidget*> childWidgets(const QWidget *widget);
+#if QT_CONFIG(accessibility)
+
+QWidgetList _q_ac_childWidgets(const QWidget *widget);
QString qt_accStripAmp(const QString &text);
QString qt_accHotKey(const QString &text);
@@ -117,9 +89,9 @@ QAccessibleButton::QAccessibleButton(QWidget *w)
// FIXME: The checkable state of the button is dynamic,
// while we only update the controlling signal once :(
if (button()->isCheckable())
- addControllingSignal(QLatin1String("toggled(bool)"));
+ addControllingSignal("toggled(bool)"_L1);
else
- addControllingSignal(QLatin1String("clicked()"));
+ addControllingSignal("clicked()"_L1);
}
/*! Returns the button. */
@@ -244,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;
}
}
@@ -362,7 +332,7 @@ QAccessibleInterface *QAccessibleToolButton::child(int index) const
return QAccessible::queryAccessibleInterface(toolButton()->menu());
}
#else
- Q_UNUSED(index)
+ Q_UNUSED(index);
#endif
return nullptr;
}
@@ -431,10 +401,10 @@ QAccessible::Role QAccessibleDisplay::role() const
#if QT_CONFIG(label)
QLabel *l = qobject_cast<QLabel*>(object());
if (l) {
- if (l->pixmap())
+ if (!l->pixmap().isNull())
return QAccessible::Graphic;
#ifndef QT_NO_PICTURE
- if (l->picture())
+ if (!l->picture().isNull())
return QAccessible::Graphic;
#endif
#if QT_CONFIG(movie)
@@ -516,11 +486,12 @@ QString QAccessibleDisplay::text(QAccessible::Text t) const
}
/*! \reimp */
-QVector<QPair<QAccessibleInterface*, QAccessible::Relation> >
+QList<QPair<QAccessibleInterface *, QAccessible::Relation>>
QAccessibleDisplay::relations(QAccessible::Relation match /* = QAccessible::AllRelations */) const
{
- QVector<QPair<QAccessibleInterface*, QAccessible::Relation> > rels = QAccessibleWidget::relations(match);
-#if QT_CONFIG(shortcut) && QT_CONFIG(label)
+ QList<QPair<QAccessibleInterface *, QAccessible::Relation>> rels =
+ QAccessibleWidget::relations(match);
+# if QT_CONFIG(shortcut) && QT_CONFIG(label)
if (match & QAccessible::Labelled) {
if (QLabel *label = qobject_cast<QLabel*>(object())) {
const QAccessible::Relation rel = QAccessible::Labelled;
@@ -542,7 +513,7 @@ void *QAccessibleDisplay::interface_cast(QAccessible::InterfaceType t)
/*! \internal */
QString QAccessibleDisplay::imageDescription() const
{
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
return widget()->toolTip();
#else
return QString();
@@ -558,10 +529,7 @@ QSize QAccessibleDisplay::imageSize() const
#endif
return QSize();
#if QT_CONFIG(label)
- const QPixmap *pixmap = label->pixmap();
- if (!pixmap)
- return QSize();
- return pixmap->size();
+ return label->pixmap().size();
#endif
}
@@ -574,8 +542,7 @@ QPoint QAccessibleDisplay::imagePosition() const
#endif
return QPoint();
#if QT_CONFIG(label)
- const QPixmap *pixmap = label->pixmap();
- if (!pixmap)
+ if (label->pixmap().isNull())
return QPoint();
return QPoint(label->mapToGlobal(label->pos()));
@@ -631,13 +598,14 @@ QAccessible::Role QAccessibleGroupBox::role() const
return groupBox()->isCheckable() ? QAccessible::CheckBox : QAccessible::Grouping;
}
-QVector<QPair<QAccessibleInterface*, QAccessible::Relation> >
+QList<QPair<QAccessibleInterface *, QAccessible::Relation>>
QAccessibleGroupBox::relations(QAccessible::Relation match /* = QAccessible::AllRelations */) const
{
- QVector<QPair<QAccessibleInterface*, QAccessible::Relation> > rels = QAccessibleWidget::relations(match);
+ QList<QPair<QAccessibleInterface *, QAccessible::Relation>> rels =
+ 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)
@@ -686,8 +654,8 @@ QStringList QAccessibleGroupBox::keyBindingsForAction(const QString &) const
QAccessibleLineEdit::QAccessibleLineEdit(QWidget *w, const QString &name)
: QAccessibleWidget(w, QAccessible::EditableText, name)
{
- addControllingSignal(QLatin1String("textChanged(const QString&)"));
- addControllingSignal(QLatin1String("returnPressed()"));
+ addControllingSignal("textChanged(const QString&)"_L1);
+ addControllingSignal("returnPressed()"_L1);
}
/*! Returns the line edit. */
@@ -704,7 +672,7 @@ QString QAccessibleLineEdit::text(QAccessible::Text t) const
if (lineEdit()->echoMode() == QLineEdit::Normal)
str = lineEdit()->text();
else if (lineEdit()->echoMode() != QLineEdit::NoEcho)
- str = QString(lineEdit()->text().length(), QChar::fromLatin1('*'));
+ str = QString(lineEdit()->text().size(), QChar::fromLatin1('*'));
break;
default:
break;
@@ -810,7 +778,7 @@ void QAccessibleLineEdit::selection(int selectionIndex, int *startOffset, int *e
return;
*startOffset = lineEdit()->selectionStart();
- *endOffset = *startOffset + lineEdit()->selectedText().count();
+ *endOffset = *startOffset + lineEdit()->selectedText().size();
}
QString QAccessibleLineEdit::text(int startOffset, int endOffset) const
@@ -883,7 +851,7 @@ void QAccessibleLineEdit::setSelection(int selectionIndex, int startOffset, int
int QAccessibleLineEdit::characterCount() const
{
- return lineEdit()->text().count();
+ return lineEdit()->text().size();
}
void QAccessibleLineEdit::scrollToSubstring(int startIndex, int endIndex)
@@ -984,6 +952,49 @@ QWindowContainer *QAccessibleWindowContainer::container() const
return static_cast<QWindowContainer *>(widget());
}
-#endif // QT_NO_ACCESSIBILITY
+#if QT_CONFIG(messagebox)
+/*!
+ \internal
+ Implements QAccessibleWidget for QMessageBox
+*/
+QAccessibleMessageBox::QAccessibleMessageBox(QWidget *widget)
+ : QAccessibleWidget(widget, QAccessible::AlertMessage)
+{
+ Q_ASSERT(qobject_cast<QMessageBox *>(widget));
+}
+
+QMessageBox *QAccessibleMessageBox::messageBox() const
+{
+ return static_cast<QMessageBox *>(widget());
+}
+
+QString QAccessibleMessageBox::text(QAccessible::Text t) const
+{
+ QString str;
+
+ switch (t) {
+ case QAccessible::Name:
+ str = QAccessibleWidget::text(t);
+ if (str.isEmpty()) // implies no title text is set
+ str = messageBox()->text();
+ break;
+ case QAccessible::Description:
+ str = widget()->accessibleDescription();
+ break;
+ case QAccessible::Value:
+ str = messageBox()->text();
+ break;
+ case QAccessible::Help:
+ str = messageBox()->informativeText();
+ break;
+ default:
+ break;
+ }
+
+ return str;
+}
+#endif
+
+#endif // QT_CONFIG(accessibility)
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/simplewidgets_p.h b/src/widgets/accessible/simplewidgets_p.h
index 73572e3059..c9c03b00d8 100644
--- a/src/widgets/accessible/simplewidgets_p.h
+++ b/src/widgets/accessible/simplewidgets_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 SIMPLEWIDGETS_H
#define SIMPLEWIDGETS_H
@@ -57,12 +21,13 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
class QAbstractButton;
class QLineEdit;
class QToolButton;
class QGroupBox;
+class QMessageBox;
class QProgressBar;
#if QT_CONFIG(abstractbutton)
@@ -118,7 +83,8 @@ public:
QAccessible::Role role() const override;
QAccessible::State state() const override;
- QVector<QPair<QAccessibleInterface*, QAccessible::Relation> >relations(QAccessible::Relation match = QAccessible::AllRelations) const override;
+ QList<QPair<QAccessibleInterface *, QAccessible::Relation>>
+ relations(QAccessible::Relation match = QAccessible::AllRelations) const override;
void *interface_cast(QAccessible::InterfaceType t) override;
// QAccessibleImageInterface
@@ -137,7 +103,8 @@ public:
QAccessible::Role role() const override;
QString text(QAccessible::Text t) const override;
- QVector<QPair<QAccessibleInterface*, QAccessible::Relation> >relations(QAccessible::Relation match = QAccessible::AllRelations) const override;
+ QList<QPair<QAccessibleInterface *, QAccessible::Relation>>
+ relations(QAccessible::Relation match = QAccessible::AllRelations) const override;
//QAccessibleActionInterface
QStringList actionNames() const override;
@@ -223,7 +190,19 @@ private:
QWindowContainer *container() const;
};
-#endif // QT_NO_ACCESSIBILITY
+#if QT_CONFIG(messagebox)
+class QAccessibleMessageBox : public QAccessibleWidget
+{
+public:
+ explicit QAccessibleMessageBox(QWidget *widget);
+
+ QString text(QAccessible::Text t) const override;
+
+ QMessageBox *messageBox() const;
+};
+#endif
+
+#endif // QT_CONFIG(accessibility)
QT_END_NAMESPACE
diff --git a/src/widgets/accessible/widgets.pro b/src/widgets/accessible/widgets.pro
deleted file mode 100644
index d04d0da3cc..0000000000
--- a/src/widgets/accessible/widgets.pro
+++ /dev/null
@@ -1,25 +0,0 @@
-TARGET = qtaccessiblewidgets
-
-QT += core-private gui-private widgets-private
-
-QTDIR_build:REQUIRES += "qtConfig(accessibility)"
-
-SOURCES += main.cpp \
- simplewidgets.cpp \
- rangecontrols.cpp \
- complexwidgets.cpp \
- qaccessiblewidgets.cpp \
- qaccessiblemenu.cpp \
- itemviews.cpp
-
-HEADERS += qaccessiblewidgets.h \
- simplewidgets.h \
- rangecontrols.h \
- complexwidgets.h \
- qaccessiblemenu.h \
- itemviews.h
-
-PLUGIN_TYPE = accessible
-PLUGIN_EXTENDS = widgets
-PLUGIN_CLASS_NAME = AccessibleFactory
-load(qt_plugin)
diff --git a/src/widgets/compat/removed_api.cpp b/src/widgets/compat/removed_api.cpp
new file mode 100644
index 0000000000..5fcbdba47b
--- /dev/null
+++ b/src/widgets/compat/removed_api.cpp
@@ -0,0 +1,103 @@
+// Copyright (C) 2021 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
+
+#define QT_WIDGETS_BUILD_REMOVED_API
+
+#include "qtwidgetsglobal.h"
+
+QT_USE_NAMESPACE
+
+#if QT_WIDGETS_REMOVED_SINCE(6, 3)
+
+#if QT_CONFIG(menu)
+#include "qmenu.h"
+
+QAction *QMenu::addAction(const QString &text)
+{
+ return QWidget::addAction(text);
+}
+
+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,
+// so remained in qmenu.cpp
+QAction *QMenu::addAction(const QString &text, const QObject *receiver, const char* member)
+{
+ return QWidget::addAction(text, receiver, member);
+}
+
+QAction *QMenu::addAction(const QIcon &icon, const QString &text,
+ const QObject *receiver, const char* member)
+{
+ return QWidget::addAction(icon, text, receiver, member);
+}
+#endif
+
+#if QT_CONFIG(toolbar)
+#include "qtoolbar.h"
+
+QAction *QToolBar::addAction(const QString &text)
+{
+ return QWidget::addAction(text);
+}
+
+QAction *QToolBar::addAction(const QIcon &icon, const QString &text)
+{
+ return QWidget::addAction(icon, text);
+}
+
+QAction *QToolBar::addAction(const QString &text,
+ const QObject *receiver, const char* member)
+{
+ return QWidget::addAction(text, receiver, member);
+}
+
+QAction *QToolBar::addAction(const QIcon &icon, const QString &text,
+ const QObject *receiver, const char* member)
+{
+ return QWidget::addAction(icon, text, receiver, member);
+}
+#endif
+
+#if QT_CONFIG(menubar)
+#include "qmenubar.h"
+
+QAction *QMenuBar::addAction(const QString &text)
+{
+ return QWidget::addAction(text);
+}
+
+QAction *QMenuBar::addAction(const QString &text, const QObject *receiver, const char* member)
+{
+ 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, 7)
diff --git a/src/widgets/configure.cmake b/src/widgets/configure.cmake
new file mode 100644
index 0000000000..745f2d1152
--- /dev/null
+++ b/src/widgets/configure.cmake
@@ -0,0 +1,544 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+
+
+#### Inputs
+
+
+
+#### Libraries
+
+qt_find_package(GTK3 3.6 PROVIDED_TARGETS PkgConfig::GTK3 MODULE_NAME widgets QMAKE_LIB gtk3)
+
+
+#### Tests
+
+
+
+#### Features
+
+qt_feature("gtk3" PRIVATE
+ LABEL "GTK+"
+ AUTODETECT NOT APPLE
+ CONDITION QT_FEATURE_glib AND GTK3_FOUND
+)
+qt_feature("style-fusion" PRIVATE
+ LABEL "Fusion"
+)
+qt_feature("style-mac" PRIVATE
+ LABEL "macOS"
+ CONDITION MACOS AND QT_FEATURE_animation
+)
+qt_feature("style-windows" PRIVATE
+ LABEL "Windows"
+)
+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
+)
+qt_feature("style-stylesheet" PUBLIC
+ SECTION "Styles"
+ LABEL "QStyleSheetStyle"
+ PURPOSE "Provides a widget style which is configurable via CSS."
+ CONDITION QT_FEATURE_style_windows AND QT_FEATURE_cssparser
+)
+qt_feature_definition("style-stylesheet" "QT_NO_STYLE_STYLESHEET" NEGATE VALUE "1")
+qt_feature("effects" PRIVATE
+ SECTION "Kernel"
+ LABEL "Effects"
+ PURPOSE "Provides special widget effects (e.g. fading and scrolling)."
+)
+qt_feature("itemviews" PUBLIC
+ SECTION "ItemViews"
+ LABEL "The Model/View Framework"
+ PURPOSE "Provides the model/view architecture managing the relationship between data and the way it is presented to the user."
+ CONDITION QT_FEATURE_itemmodel AND QT_FEATURE_scrollarea
+)
+qt_feature_definition("itemviews" "QT_NO_ITEMVIEWS" NEGATE VALUE "1")
+qt_feature("treewidget" PUBLIC
+ SECTION "Widgets"
+ LABEL "QTreeWidget"
+ PURPOSE "Provides views using tree models."
+ CONDITION QT_FEATURE_treeview
+)
+qt_feature_definition("treewidget" "QT_NO_TREEWIDGET" NEGATE VALUE "1")
+qt_feature("listwidget" PUBLIC
+ SECTION "Widgets"
+ LABEL "QListWidget"
+ PURPOSE "Provides item-based list widgets."
+ CONDITION QT_FEATURE_listview
+)
+qt_feature_definition("listwidget" "QT_NO_LISTWIDGET" NEGATE VALUE "1")
+qt_feature("tablewidget" PUBLIC
+ SECTION "Widgets"
+ LABEL "QTableWidget"
+ PURPOSE "Provides item-based table views."
+ CONDITION QT_FEATURE_tableview
+)
+qt_feature_definition("tablewidget" "QT_NO_TABLEWIDGET" NEGATE VALUE "1")
+qt_feature("abstractbutton" PUBLIC
+ SECTION "Widgets"
+ LABEL "QAbstractButton"
+ PURPOSE "Abstract base class of button widgets, providing functionality common to buttons."
+)
+qt_feature("commandlinkbutton" PUBLIC
+ SECTION "Widgets"
+ LABEL "QCommandLinkButton"
+ PURPOSE "Provides a Vista style command link button."
+ CONDITION QT_FEATURE_pushbutton
+)
+qt_feature("datetimeedit" PUBLIC
+ SECTION "Widgets"
+ LABEL "QDateTimeEdit"
+ PURPOSE "Supports editing dates and times."
+ CONDITION QT_FEATURE_calendarwidget AND QT_FEATURE_datetimeparser
+)
+qt_feature_definition("datetimeedit" "QT_NO_DATETIMEEDIT" NEGATE VALUE "1")
+qt_feature("stackedwidget" PUBLIC
+ SECTION "Widgets"
+ LABEL "QStackedWidget"
+ PURPOSE "Provides stacked widgets."
+)
+qt_feature_definition("stackedwidget" "QT_NO_STACKEDWIDGET" NEGATE VALUE "1")
+qt_feature("textbrowser" PUBLIC
+ SECTION "Widgets"
+ LABEL "QTextBrowser"
+ PURPOSE "Supports HTML document browsing."
+ CONDITION QT_FEATURE_textedit
+)
+qt_feature_definition("textbrowser" "QT_NO_TEXTBROWSER" NEGATE VALUE "1")
+qt_feature("splashscreen" PUBLIC
+ SECTION "Widgets"
+ LABEL "QSplashScreen"
+ PURPOSE "Supports splash screens that can be shown during application startup."
+)
+qt_feature_definition("splashscreen" "QT_NO_SPLASHSCREEN" NEGATE VALUE "1")
+qt_feature("splitter" PUBLIC
+ SECTION "Widgets"
+ LABEL "QSplitter"
+ PURPOSE "Provides user controlled splitter widgets."
+)
+qt_feature_definition("splitter" "QT_NO_SPLITTER" NEGATE VALUE "1")
+qt_feature("widgettextcontrol" PRIVATE
+ SECTION "Widgets"
+ LABEL "QWidgetTextControl"
+ PURPOSE "Provides text control functionality to other widgets."
+)
+qt_feature("label" PUBLIC
+ SECTION "Widgets"
+ LABEL "QLabel"
+ PURPOSE "Provides a text or image display."
+ CONDITION QT_FEATURE_widgettextcontrol
+)
+qt_feature("formlayout" PUBLIC
+ SECTION "Widgets"
+ LABEL "QFormLayout"
+ PURPOSE "Manages forms of input widgets and their associated labels."
+ CONDITION QT_FEATURE_label
+)
+qt_feature("lcdnumber" PUBLIC
+ SECTION "Widgets"
+ LABEL "QLCDNumber"
+ PURPOSE "Provides LCD-like digits."
+)
+qt_feature_definition("lcdnumber" "QT_NO_LCDNUMBER" NEGATE VALUE "1")
+qt_feature("menu" PUBLIC
+ SECTION "Widgets"
+ LABEL "QMenu"
+ PURPOSE "Provides popup-menus."
+ CONDITION QT_FEATURE_action AND QT_FEATURE_pushbutton
+)
+qt_feature_definition("menu" "QT_NO_MENU" NEGATE VALUE "1")
+qt_feature("lineedit" PUBLIC
+ SECTION "Widgets"
+ LABEL "QLineEdit"
+ PURPOSE "Provides single-line edits."
+ CONDITION QT_FEATURE_widgettextcontrol
+)
+qt_feature_definition("lineedit" "QT_NO_LINEEDIT" NEGATE VALUE "1")
+qt_feature("radiobutton" PUBLIC
+ SECTION "Widgets"
+ LABEL "QRadioButton"
+ PURPOSE "Provides a radio button with a text label."
+ CONDITION QT_FEATURE_abstractbutton
+)
+qt_feature("spinbox" PUBLIC
+ SECTION "Widgets"
+ LABEL "QSpinBox"
+ PURPOSE "Provides spin boxes handling integers and discrete sets of values."
+ CONDITION QT_FEATURE_lineedit AND QT_FEATURE_validator
+)
+qt_feature_definition("spinbox" "QT_NO_SPINBOX" NEGATE VALUE "1")
+qt_feature("tabbar" PUBLIC
+ SECTION "Widgets"
+ LABEL "QTabBar"
+ PURPOSE "Provides tab bars, e.g., for use in tabbed dialogs."
+ CONDITION QT_FEATURE_toolbutton
+)
+qt_feature_definition("tabbar" "QT_NO_TABBAR" NEGATE VALUE "1")
+qt_feature("tabwidget" PUBLIC
+ SECTION "Widgets"
+ LABEL "QTabWidget"
+ PURPOSE "Supports stacking tabbed widgets."
+ CONDITION QT_FEATURE_tabbar AND QT_FEATURE_stackedwidget
+)
+qt_feature_definition("tabwidget" "QT_NO_TABWIDGET" NEGATE VALUE "1")
+qt_feature("combobox" PUBLIC
+ SECTION "Widgets"
+ LABEL "QComboBox"
+ PURPOSE "Provides drop-down boxes presenting a list of options to the user."
+ CONDITION QT_FEATURE_lineedit AND QT_FEATURE_standarditemmodel AND QT_FEATURE_listview
+)
+qt_feature_definition("combobox" "QT_NO_COMBOBOX" NEGATE VALUE "1")
+qt_feature("fontcombobox" PUBLIC
+ SECTION "Widgets"
+ LABEL "QFontComboBox"
+ PURPOSE "Provides a combobox that lets the user select a font family."
+ CONDITION QT_FEATURE_combobox AND QT_FEATURE_stringlistmodel
+)
+qt_feature_definition("fontcombobox" "QT_NO_FONTCOMBOBOX" NEGATE VALUE "1")
+qt_feature("checkbox" PUBLIC
+ SECTION "Widgets"
+ LABEL "QCheckBox("
+ PURPOSE "Provides a checkbox with a text label."
+ CONDITION QT_FEATURE_abstractbutton
+)
+qt_feature("pushbutton" PUBLIC
+ SECTION "Widgets"
+ LABEL "QPushButton"
+ PURPOSE "Provides a command button."
+ CONDITION QT_FEATURE_abstractbutton AND QT_FEATURE_action
+)
+qt_feature("toolbutton" PUBLIC
+ SECTION "Widgets"
+ LABEL "QToolButton"
+ PURPOSE "Provides quick-access buttons to commands and options."
+ CONDITION QT_FEATURE_abstractbutton AND QT_FEATURE_action
+)
+qt_feature_definition("toolbutton" "QT_NO_TOOLBUTTON" NEGATE VALUE "1")
+qt_feature("toolbar" PUBLIC
+ SECTION "Widgets"
+ LABEL "QToolBar"
+ PURPOSE "Provides movable panels containing a set of controls."
+ CONDITION QT_FEATURE_mainwindow
+)
+qt_feature_definition("toolbar" "QT_NO_TOOLBAR" NEGATE VALUE "1")
+qt_feature("toolbox" PUBLIC
+ SECTION "Widgets"
+ LABEL "QToolBox"
+ PURPOSE "Provides columns of tabbed widget items."
+ CONDITION QT_FEATURE_toolbutton AND QT_FEATURE_scrollarea
+)
+qt_feature_definition("toolbox" "QT_NO_TOOLBOX" NEGATE VALUE "1")
+qt_feature("groupbox" PUBLIC
+ SECTION "Widgets"
+ LABEL "QGroupBox"
+ PURPOSE "Provides widget grouping boxes with frames."
+)
+qt_feature_definition("groupbox" "QT_NO_GROUPBOX" NEGATE VALUE "1")
+qt_feature("buttongroup" PUBLIC
+ SECTION "Widgets"
+ LABEL "QButtonGroup"
+ PURPOSE "Supports organizing groups of button widgets."
+ CONDITION QT_FEATURE_abstractbutton AND QT_FEATURE_groupbox
+)
+qt_feature_definition("buttongroup" "QT_NO_BUTTONGROUP" NEGATE VALUE "1")
+qt_feature("mainwindow" PUBLIC
+ SECTION "Widgets"
+ LABEL "QMainWindow"
+ PURPOSE "Provides main application windows."
+ CONDITION QT_FEATURE_menu AND QT_FEATURE_resizehandler AND QT_FEATURE_toolbutton
+)
+qt_feature_definition("mainwindow" "QT_NO_MAINWINDOW" NEGATE VALUE "1")
+qt_feature("dockwidget" PUBLIC
+ SECTION "Widgets"
+ LABEL "QDockwidget"
+ PURPOSE "Supports docking widgets inside a QMainWindow or floated as a top-level window on the desktop."
+ CONDITION QT_FEATURE_mainwindow
+)
+qt_feature_definition("dockwidget" "QT_NO_DOCKWIDGET" NEGATE VALUE "1")
+qt_feature("mdiarea" PUBLIC
+ SECTION "Widgets"
+ LABEL "QMdiArea"
+ PURPOSE "Provides an area in which MDI windows are displayed."
+ CONDITION QT_FEATURE_scrollarea
+)
+qt_feature_definition("mdiarea" "QT_NO_MDIAREA" NEGATE VALUE "1")
+qt_feature("resizehandler" PUBLIC
+ SECTION "Widgets"
+ LABEL "QWidgetResizeHandler"
+ PURPOSE "Provides an internal resize handler for dock widgets."
+)
+qt_feature_definition("resizehandler" "QT_NO_RESIZEHANDLER" NEGATE VALUE "1")
+qt_feature("statusbar" PUBLIC
+ SECTION "Widgets"
+ LABEL "QStatusBar"
+ PURPOSE "Supports presentation of status information."
+)
+qt_feature_definition("statusbar" "QT_NO_STATUSBAR" NEGATE VALUE "1")
+qt_feature("menubar" PUBLIC
+ SECTION "Widgets"
+ LABEL "QMenuBar"
+ PURPOSE "Provides pull-down menu items."
+ CONDITION QT_FEATURE_menu AND QT_FEATURE_toolbutton
+)
+qt_feature_definition("menubar" "QT_NO_MENUBAR" NEGATE VALUE "1")
+qt_feature("contextmenu" PUBLIC
+ SECTION "Widgets"
+ LABEL "Context menus"
+ PURPOSE "Adds pop-up menus on right mouse click to numerous widgets."
+ CONDITION QT_FEATURE_menu
+)
+qt_feature_definition("contextmenu" "QT_NO_CONTEXTMENU" NEGATE VALUE "1")
+qt_feature("progressbar" PUBLIC
+ SECTION "Widgets"
+ LABEL "QProgressBar"
+ PURPOSE "Supports presentation of operation progress."
+)
+qt_feature_definition("progressbar" "QT_NO_PROGRESSBAR" NEGATE VALUE "1")
+qt_feature("abstractslider" PUBLIC
+ SECTION "Widgets"
+ LABEL "QAbstractSlider"
+ PURPOSE "Common super class for widgets like QScrollBar, QSlider and QDial."
+)
+qt_feature("slider" PUBLIC
+ SECTION "Widgets"
+ LABEL "QSlider"
+ PURPOSE "Provides sliders controlling a bounded value."
+ CONDITION QT_FEATURE_abstractslider
+)
+qt_feature_definition("slider" "QT_NO_SLIDER" NEGATE VALUE "1")
+qt_feature("scrollbar" PUBLIC
+ SECTION "Widgets"
+ LABEL "QScrollBar"
+ PURPOSE "Provides scrollbars allowing the user access parts of a document that is larger than the widget used to display it."
+ CONDITION QT_FEATURE_slider
+)
+qt_feature_definition("scrollbar" "QT_NO_SCROLLBAR" NEGATE VALUE "1")
+qt_feature("dial" PUBLIC
+ SECTION "Widgets"
+ LABEL "QDial"
+ PURPOSE "Provides a rounded range control, e.g., like a speedometer."
+ CONDITION QT_FEATURE_slider
+)
+qt_feature_definition("dial" "QT_NO_DIAL" NEGATE VALUE "1")
+qt_feature("scrollarea" PUBLIC
+ SECTION "Widgets"
+ LABEL "QScrollArea"
+ PURPOSE "Supports scrolling views onto widgets."
+ CONDITION QT_FEATURE_scrollbar
+)
+qt_feature_definition("scrollarea" "QT_NO_SCROLLAREA" NEGATE VALUE "1")
+qt_feature("scroller" PUBLIC
+ SECTION "Widgets"
+ LABEL "QScroller"
+ PURPOSE "Enables kinetic scrolling for any scrolling widget or graphics item."
+ CONDITION QT_FEATURE_easingcurve
+)
+qt_feature("graphicsview" PUBLIC
+ SECTION "Widgets"
+ LABEL "QGraphicsView"
+ PURPOSE "Provides a canvas/sprite framework."
+ CONDITION QT_FEATURE_scrollarea AND QT_FEATURE_widgettextcontrol
+)
+qt_feature_definition("graphicsview" "QT_NO_GRAPHICSVIEW" NEGATE VALUE "1")
+qt_feature("graphicseffect" PUBLIC
+ SECTION "Widgets"
+ LABEL "QGraphicsEffect"
+ PURPOSE "Provides various graphics effects."
+ CONDITION QT_FEATURE_graphicsview
+)
+qt_feature_definition("graphicseffect" "QT_NO_GRAPHICSEFFECT" NEGATE VALUE "1")
+qt_feature("textedit" PUBLIC
+ SECTION "Widgets"
+ LABEL "QTextEdit"
+ PURPOSE "Supports rich text editing."
+ CONDITION QT_FEATURE_scrollarea AND QT_FEATURE_widgettextcontrol
+)
+qt_feature_definition("textedit" "QT_NO_TEXTEDIT" NEGATE VALUE "1")
+qt_feature("syntaxhighlighter" PUBLIC
+ SECTION "Widgets"
+ LABEL "QSyntaxHighlighter"
+ PURPOSE "Supports custom syntax highlighting."
+ CONDITION QT_FEATURE_textedit
+)
+qt_feature_definition("syntaxhighlighter" "QT_NO_SYNTAXHIGHLIGHTER" NEGATE VALUE "1")
+qt_feature("rubberband" PUBLIC
+ SECTION "Widgets"
+ LABEL "QRubberBand"
+ PURPOSE "Supports using rubberbands to indicate selections and boundaries."
+)
+qt_feature_definition("rubberband" "QT_NO_RUBBERBAND" NEGATE VALUE "1")
+qt_feature("tooltip" PUBLIC
+ SECTION "Widgets"
+ LABEL "QToolTip"
+ PURPOSE "Supports presentation of tooltips."
+ CONDITION QT_FEATURE_label
+)
+qt_feature_definition("tooltip" "QT_NO_TOOLTIP" NEGATE VALUE "1")
+qt_feature("statustip" PUBLIC
+ SECTION "Widgets"
+ LABEL "Status Tip"
+ PURPOSE "Supports status tip functionality and events."
+)
+qt_feature_definition("statustip" "QT_NO_STATUSTIP" NEGATE VALUE "1")
+qt_feature("sizegrip" PUBLIC
+ SECTION "Widgets"
+ LABEL "QSizeGrip"
+ PURPOSE "Provides corner-grips for resizing top-level windows."
+)
+qt_feature_definition("sizegrip" "QT_NO_SIZEGRIP" NEGATE VALUE "1")
+qt_feature("calendarwidget" PUBLIC
+ SECTION "Widgets"
+ LABEL "QCalendarWidget"
+ PURPOSE "Provides a monthly based calendar widget allowing the user to select a date."
+ CONDITION ( QT_FEATURE_label ) AND ( QT_FEATURE_menu ) AND ( QT_FEATURE_pushbutton ) AND ( QT_FEATURE_spinbox ) AND ( QT_FEATURE_tableview ) AND ( QT_FEATURE_textdate ) AND ( QT_FEATURE_toolbutton )
+)
+qt_feature_definition("calendarwidget" "QT_NO_CALENDARWIDGET" NEGATE VALUE "1")
+qt_feature("keysequenceedit" PUBLIC
+ SECTION "Widgets"
+ LABEL "QKeySequenceEdit"
+ PURPOSE "Provides a widget for editing QKeySequences."
+ CONDITION QT_FEATURE_lineedit AND QT_FEATURE_shortcut
+)
+qt_feature_definition("keysequenceedit" "QT_NO_KEYSEQUENCEEDIT" NEGATE VALUE "1")
+qt_feature("dialog" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QDialog"
+ PURPOSE "Base class of dialog windows."
+)
+qt_feature("dialogbuttonbox" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QDialogButtonBox"
+ PURPOSE "Presents buttons in a layout that is appropriate for the current widget style."
+ CONDITION QT_FEATURE_dialog AND QT_FEATURE_pushbutton
+)
+qt_feature("messagebox" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QMessageBox"
+ PURPOSE "Provides message boxes displaying informative messages and simple questions."
+ CONDITION ( QT_FEATURE_checkbox ) AND ( QT_FEATURE_dialog ) AND ( QT_FEATURE_dialogbuttonbox ) AND ( QT_FEATURE_label ) AND ( QT_FEATURE_pushbutton )
+)
+qt_feature_definition("messagebox" "QT_NO_MESSAGEBOX" NEGATE VALUE "1")
+qt_feature("colordialog" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QColorDialog"
+ PURPOSE "Provides a dialog widget for specifying colors."
+ CONDITION ( QT_FEATURE_dialog ) AND ( QT_FEATURE_dialogbuttonbox ) AND ( QT_FEATURE_label ) AND ( QT_FEATURE_pushbutton ) AND ( QT_FEATURE_spinbox )
+)
+qt_feature_definition("colordialog" "QT_NO_COLORDIALOG" NEGATE VALUE "1")
+qt_feature("filedialog" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QFileDialog"
+ PURPOSE "Provides a dialog widget for selecting files or directories."
+ CONDITION ( QT_FEATURE_buttongroup ) AND ( QT_FEATURE_combobox ) AND ( QT_FEATURE_dialog ) AND ( QT_FEATURE_dialogbuttonbox ) AND ( QT_FEATURE_filesystemmodel ) AND ( QT_FEATURE_label ) AND ( QT_FEATURE_proxymodel ) AND ( QT_FEATURE_splitter ) AND ( QT_FEATURE_stackedwidget ) AND ( QT_FEATURE_treeview ) AND ( QT_FEATURE_toolbutton )
+)
+qt_feature_definition("filedialog" "QT_NO_FILEDIALOG" NEGATE VALUE "1")
+qt_feature("fontdialog" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QFontDialog"
+ PURPOSE "Provides a dialog widget for selecting fonts."
+ CONDITION ( QT_FEATURE_checkbox ) AND ( QT_FEATURE_combobox ) AND ( QT_FEATURE_dialog ) AND ( QT_FEATURE_dialogbuttonbox ) AND ( QT_FEATURE_groupbox ) AND ( QT_FEATURE_label ) AND ( QT_FEATURE_pushbutton ) AND ( QT_FEATURE_stringlistmodel ) AND ( QT_FEATURE_validator )
+)
+qt_feature_definition("fontdialog" "QT_NO_FONTDIALOG" NEGATE VALUE "1")
+qt_feature("progressdialog" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QProgressDialog"
+ PURPOSE "Provides feedback on the progress of a slow operation."
+ CONDITION ( QT_FEATURE_dialog ) AND ( QT_FEATURE_label ) AND ( QT_FEATURE_pushbutton ) AND ( QT_FEATURE_progressbar )
+)
+qt_feature_definition("progressdialog" "QT_NO_PROGRESSDIALOG" NEGATE VALUE "1")
+qt_feature("inputdialog" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QInputDialog"
+ PURPOSE "Provides a simple convenience dialog to get a single value from the user."
+ CONDITION ( QT_FEATURE_combobox ) AND ( QT_FEATURE_dialog ) AND ( QT_FEATURE_dialogbuttonbox ) AND ( QT_FEATURE_label ) AND ( QT_FEATURE_pushbutton ) AND ( QT_FEATURE_spinbox ) AND ( QT_FEATURE_stackedwidget ) AND ( QT_FEATURE_textedit )
+)
+qt_feature_definition("inputdialog" "QT_NO_INPUTDIALOG" NEGATE VALUE "1")
+qt_feature("errormessage" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QErrorMessage"
+ PURPOSE "Provides an error message display dialog."
+ CONDITION ( QT_FEATURE_checkbox ) AND ( QT_FEATURE_dialog ) AND ( QT_FEATURE_textedit ) AND ( QT_FEATURE_label ) AND ( QT_FEATURE_pushbutton ) AND ( QT_FEATURE_textedit )
+)
+qt_feature_definition("errormessage" "QT_NO_ERRORMESSAGE" NEGATE VALUE "1")
+qt_feature("wizard" PUBLIC
+ SECTION "Dialogs"
+ LABEL "QWizard"
+ PURPOSE "Provides a framework for multi-page click-through dialogs."
+ CONDITION ( QT_FEATURE_dialog ) AND ( QT_FEATURE_pushbutton ) AND ( QT_FEATURE_label )
+)
+qt_feature_definition("wizard" "QT_NO_WIZARD" NEGATE VALUE "1")
+qt_feature("listview" PUBLIC
+ SECTION "ItemViews"
+ LABEL "QListView"
+ PURPOSE "Provides a list or icon view onto a model."
+ CONDITION QT_FEATURE_itemviews
+)
+qt_feature_definition("listview" "QT_NO_LISTVIEW" NEGATE VALUE "1")
+qt_feature("tableview" PUBLIC
+ SECTION "ItemViews"
+ LABEL "QTableView"
+ PURPOSE "Provides a default model/view implementation of a table view."
+ CONDITION QT_FEATURE_itemviews
+)
+qt_feature_definition("tableview" "QT_NO_TABLEVIEW" NEGATE VALUE "1")
+qt_feature("treeview" PUBLIC
+ SECTION "ItemViews"
+ LABEL "QTreeView"
+ PURPOSE "Provides a default model/view implementation of a tree view."
+ CONDITION QT_FEATURE_itemviews
+)
+qt_feature_definition("treeview" "QT_NO_TREEVIEW" NEGATE VALUE "1")
+qt_feature("datawidgetmapper" PUBLIC
+ SECTION "ItemViews"
+ LABEL "QDataWidgetMapper"
+ PURPOSE "Provides mapping between a section of a data model to widgets."
+ CONDITION QT_FEATURE_itemviews
+)
+qt_feature_definition("datawidgetmapper" "QT_NO_DATAWIDGETMAPPER" NEGATE VALUE "1")
+qt_feature("columnview" PUBLIC
+ SECTION "ItemViews"
+ LABEL "QColumnView"
+ PURPOSE "Provides a model/view implementation of a column view."
+ CONDITION QT_FEATURE_listview
+)
+qt_feature_definition("columnview" "QT_NO_COLUMNVIEW" NEGATE VALUE "1")
+qt_feature("completer" PUBLIC
+ SECTION "Utilities"
+ LABEL "QCompleter"
+ PURPOSE "Provides completions based on an item model."
+ CONDITION QT_FEATURE_proxymodel AND QT_FEATURE_itemviews
+)
+qt_feature_definition("completer" "QT_NO_COMPLETER" NEGATE VALUE "1")
+qt_feature("fscompleter" PUBLIC
+ SECTION "Utilities"
+ LABEL "QFSCompleter"
+ PURPOSE "Provides file name completion in QFileDialog."
+ CONDITION QT_FEATURE_filesystemmodel AND QT_FEATURE_completer
+)
+qt_feature_definition("fscompleter" "QT_NO_FSCOMPLETER" NEGATE VALUE "1")
+qt_feature("undoview" PUBLIC
+ SECTION "Utilities"
+ LABEL "QUndoView"
+ PURPOSE "Provides a widget which shows the contents of an undo stack."
+ CONDITION QT_FEATURE_undostack AND QT_FEATURE_listview
+)
+qt_feature_definition("undoview" "QT_NO_UNDOVIEW" NEGATE VALUE "1")
+qt_configure_add_summary_section(NAME "Qt Widgets")
+qt_configure_add_summary_entry(ARGS "gtk3")
+qt_configure_add_summary_entry(
+ TYPE "featureList"
+ ARGS "style-fusion style-mac style-windows style-windowsvista style-android"
+ MESSAGE "Styles"
+)
+qt_configure_end_summary_section() # end of "Qt Widgets" section
diff --git a/src/widgets/configure.json b/src/widgets/configure.json
deleted file mode 100644
index cab120098a..0000000000
--- a/src/widgets/configure.json
+++ /dev/null
@@ -1,681 +0,0 @@
-{
- "module": "widgets",
- "depends": [
- "core-private",
- "gui"
- ],
- "testDir": "../../config.tests",
-
- "commandline": {
- "options": {
- "gtk": { "type": "boolean", "name": "gtk3" },
- "style-windows": "boolean",
- "style-windowsvista": "boolean",
- "style-fusion": "boolean",
- "style-mac": "boolean",
- "style-android": "boolean"
- }
- },
-
- "libraries": {
- "gtk3": {
- "label": "GTK+ >= 3.6",
- "sources": [
- { "type": "pkgConfig", "args": "gtk+-3.0 >= 3.6" }
- ]
- }
- },
-
- "features": {
- "gtk3": {
- "label": "GTK+",
- "autoDetect": "!config.darwin",
- "condition": "features.glib && libs.gtk3",
- "output": [ "privateFeature" ]
- },
- "style-fusion": {
- "label": "Fusion",
- "output": [ "privateFeature", "styles" ]
- },
- "style-mac": {
- "label": "macOS",
- "condition": "config.osx && features.animation",
- "output": [ "privateFeature", "styles" ]
- },
- "style-windows": {
- "label": "Windows",
- "output": [ "privateFeature", "styles" ]
- },
- "style-windowsvista": {
- "label": "WindowsVista",
- "condition": "features.style-windows && features.animation && config.win32 && !config.winrt",
- "output": [ "privateFeature", "styles" ]
- },
- "style-android": {
- "label": "Android",
- "autoDetect": "config.android",
- "output": [ "privateFeature", "styles" ]
- },
- "style-stylesheet": {
- "label": "QStyleSheetStyle",
- "purpose": "Provides a widget style which is configurable via CSS.",
- "section": "Styles",
- "condition": "features.style-windows && features.properties && features.cssparser",
- "output": [ "publicFeature", "feature" ]
- },
- "effects": {
- "label": "Effects",
- "purpose": "Provides special widget effects (e.g. fading and scrolling).",
- "section": "Kernel",
- "output": [ "privateFeature" ]
- },
- "filesystemmodel": {
- "label": "QFileSystemModel",
- "purpose": "Provides a data model for the local filesystem.",
- "section": "File I/O",
- "condition": "features.itemmodel",
- "output": [ "publicFeature", "feature" ]
- },
- "itemviews": {
- "label": "The Model/View Framework",
- "purpose": "Provides the model/view architecture managing the relationship between data and the way it is presented to the user.",
- "section": "ItemViews",
- "condition": "features.itemmodel && features.scrollarea",
- "output": [ "publicFeature", "feature" ]
- },
- "treewidget": {
- "label": "QTreeWidget",
- "purpose": "Provides views using tree models.",
- "section": "Widgets",
- "condition": "features.treeview",
- "output": [ "publicFeature", "feature" ]
- },
- "listwidget": {
- "label": "QListWidget",
- "purpose": "Provides item-based list widgets.",
- "section": "Widgets",
- "condition": "features.listview",
- "output": [ "publicFeature", "feature" ]
- },
- "tablewidget": {
- "label": "QTableWidget",
- "purpose": "Provides item-based table views.",
- "section": "Widgets",
- "condition": "features.tableview",
- "output": [ "publicFeature", "feature" ]
- },
- "abstractbutton": {
- "label": "QAbstractButton",
- "purpose": "Abstract base class of button widgets, providing functionality common to buttons.",
- "section": "Widgets",
- "output": [ "publicFeature" ]
- },
- "commandlinkbutton": {
- "label": "QCommandLinkButton",
- "purpose": "Provides a Vista style command link button.",
- "section": "Widgets",
- "condition": "features.pushbutton",
- "output": [ "publicFeature" ]
- },
- "datetimeedit": {
- "label": "QDateTimeEdit",
- "purpose": "Supports editing dates and times.",
- "section": "Widgets",
- "condition": "features.calendarwidget && features.datestring && features.textdate && features.datetimeparser",
- "output": [ "publicFeature", "feature" ]
- },
- "stackedwidget": {
- "label": "QStackedWidget",
- "purpose": "Provides stacked widgets.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "textbrowser": {
- "label": "QTextBrowser",
- "purpose": "Supports HTML document browsing.",
- "section": "Widgets",
- "condition": "features.textedit",
- "output": [ "publicFeature", "feature" ]
- },
- "splashscreen": {
- "label": "QSplashScreen",
- "purpose": "Supports splash screens that can be shown during application startup.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "splitter": {
- "label": "QSplitter",
- "purpose": "Provides user controlled splitter widgets.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "widgettextcontrol": {
- "label": "QWidgetTextControl",
- "purpose": "Provides text control functionality to other widgets.",
- "section": "Widgets",
- "output": [ "privateFeature" ]
- },
- "label": {
- "label": "QLabel",
- "purpose": "Provides a text or image display.",
- "section": "Widgets",
- "condition": "features.widgettextcontrol",
- "output": [ "publicFeature" ]
- },
- "formlayout": {
- "label": "QFormLayout",
- "purpose": "Manages forms of input widgets and their associated labels.",
- "section": "Widgets",
- "condition": "features.label",
- "output": [ "publicFeature" ]
- },
- "lcdnumber": {
- "label": "QLCDNumber",
- "purpose": "Provides LCD-like digits.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "menu": {
- "label": "QMenu",
- "purpose": "Provides popup-menus.",
- "section": "Widgets",
- "condition": "features.action && features.pushbutton",
- "output": [ "publicFeature", "feature" ]
- },
- "lineedit": {
- "label": "QLineEdit",
- "purpose": "Provides single-line edits.",
- "section": "Widgets",
- "condition": "features.widgettextcontrol",
- "output": [ "publicFeature", "feature" ]
- },
- "radiobutton": {
- "label": "QRadioButton",
- "purpose": "Provides a radio button with a text label.",
- "section": "Widgets",
- "condition": "features.abstractbutton",
- "output": [ "publicFeature" ]
- },
- "spinbox": {
- "label": "QSpinBox",
- "purpose": "Provides spin boxes handling integers and discrete sets of values.",
- "section": "Widgets",
- "condition": "features.lineedit && features.validator",
- "output": [ "publicFeature", "feature" ]
- },
- "tabbar": {
- "label": "QTabBar",
- "purpose": "Provides tab bars, e.g., for use in tabbed dialogs.",
- "section": "Widgets",
- "condition": "features.toolbutton",
- "output": [ "publicFeature", "feature" ]
- },
- "tabwidget": {
- "label": "QTabWidget",
- "purpose": "Supports stacking tabbed widgets.",
- "section": "Widgets",
- "condition": "features.tabbar && features.stackedwidget",
- "output": [ "publicFeature", "feature" ]
- },
- "combobox": {
- "label": "QComboBox",
- "purpose": "Provides drop-down boxes presenting a list of options to the user.",
- "section": "Widgets",
- "condition": "features.lineedit && features.standarditemmodel && features.listview",
- "output": [ "publicFeature", "feature" ]
- },
- "fontcombobox": {
- "label": "QFontComboBox",
- "purpose": "Provides a combobox that lets the user select a font family.",
- "section": "Widgets",
- "condition": "features.combobox && features.stringlistmodel",
- "output": [ "publicFeature", "feature" ]
- },
- "checkbox": {
- "label": "QCheckBox(",
- "purpose": "Provides a checkbox with a text label.",
- "section": "Widgets",
- "condition": "features.abstractbutton",
- "output": [ "publicFeature" ]
- },
- "pushbutton": {
- "label": "QPushButton",
- "purpose": "Provides a command button.",
- "section": "Widgets",
- "condition": "features.abstractbutton && features.action",
- "output": [ "publicFeature" ]
- },
- "toolbutton": {
- "label": "QToolButton",
- "purpose": "Provides quick-access buttons to commands and options.",
- "section": "Widgets",
- "condition": "features.abstractbutton && features.action",
- "output": [ "publicFeature", "feature" ]
- },
- "toolbar": {
- "label": "QToolBar",
- "purpose": "Provides movable panels containing a set of controls.",
- "section": "Widgets",
- "condition": "features.mainwindow",
- "output": [ "publicFeature", "feature" ]
- },
- "toolbox": {
- "label": "QToolBox",
- "purpose": "Provides columns of tabbed widget items.",
- "section": "Widgets",
- "condition": "features.toolbutton && features.scrollarea",
- "output": [ "publicFeature", "feature" ]
- },
- "groupbox": {
- "label": "QGroupBox",
- "purpose": "Provides widget grouping boxes with frames.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "buttongroup": {
- "label": "QButtonGroup",
- "purpose": "Supports organizing groups of button widgets.",
- "section": "Widgets",
- "condition": "features.abstractbutton && features.groupbox",
- "output": [ "publicFeature", "feature" ]
- },
- "mainwindow": {
- "label": "QMainWindow",
- "purpose": "Provides main application windows.",
- "section": "Widgets",
- "condition": "features.menu && features.resizehandler && features.toolbutton",
- "output": [ "publicFeature", "feature" ]
- },
- "dockwidget": {
- "label": "QDockwidget",
- "purpose": "Supports docking widgets inside a QMainWindow or floated as a top-level window on the desktop.",
- "section": "Widgets",
- "condition": "features.mainwindow",
- "output": [ "publicFeature", "feature" ]
- },
- "mdiarea": {
- "label": "QMdiArea",
- "purpose": "Provides an area in which MDI windows are displayed.",
- "section": "Widgets",
- "condition": "features.scrollarea",
- "output": [ "publicFeature", "feature" ]
- },
- "resizehandler": {
- "label": "QWidgetResizeHandler",
- "purpose": "Provides an internal resize handler for dock widgets.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "statusbar": {
- "label": "QStatusBar",
- "purpose": "Supports presentation of status information.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "menubar": {
- "label": "QMenuBar",
- "purpose": "Provides pull-down menu items.",
- "section": "Widgets",
- "condition": "features.menu && features.toolbutton",
- "output": [ "publicFeature", "feature" ]
- },
- "contextmenu": {
- "label": "Context menus",
- "purpose": "Adds pop-up menus on right mouse click to numerous widgets.",
- "section": "Widgets",
- "condition": "features.menu",
- "output": [ "publicFeature", "feature" ]
- },
- "progressbar": {
- "label": "QProgressBar",
- "purpose": "Supports presentation of operation progress.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "abstractslider": {
- "label": "QAbstractSlider",
- "purpose": "Common super class for widgets like QScrollBar, QSlider and QDial.",
- "section": "Widgets",
- "output": [ "publicFeature" ]
- },
- "slider": {
- "label": "QSlider",
- "purpose": "Provides sliders controlling a bounded value.",
- "section": "Widgets",
- "condition": "features.abstractslider",
- "output": [ "publicFeature", "feature" ]
- },
- "scrollbar": {
- "label": "QScrollBar",
- "purpose": "Provides scrollbars allowing the user access parts of a document that is larger than the widget used to display it.",
- "section": "Widgets",
- "condition": "features.slider",
- "output": [ "publicFeature", "feature" ]
- },
- "dial": {
- "label": "QDial",
- "purpose": "Provides a rounded range control, e.g., like a speedometer.",
- "section": "Widgets",
- "condition": "features.slider",
- "output": [ "publicFeature", "feature" ]
- },
- "scrollarea": {
- "label": "QScrollArea",
- "purpose": "Supports scrolling views onto widgets.",
- "section": "Widgets",
- "condition": "features.scrollbar",
- "output": [ "publicFeature", "feature" ]
- },
- "scroller": {
- "label": "QScroller",
- "purpose": "Enables kinetic scrolling for any scrolling widget or graphics item.",
- "section": "Widgets",
- "condition": "features.easingcurve",
- "output": [ "publicFeature" ]
- },
- "graphicsview": {
- "label": "QGraphicsView",
- "purpose": "Provides a canvas/sprite framework.",
- "section": "Widgets",
- "condition": "features.scrollarea && features.widgettextcontrol",
- "output": [ "publicFeature", "feature" ]
- },
- "graphicseffect": {
- "label": "QGraphicsEffect",
- "purpose": "Provides various graphics effects.",
- "section": "Widgets",
- "condition": "features.graphicsview",
- "output": [ "publicFeature", "feature" ]
- },
- "textedit": {
- "label": "QTextEdit",
- "purpose": "Supports rich text editing.",
- "section": "Widgets",
- "condition": "features.scrollarea && features.properties && features.widgettextcontrol",
- "output": [ "publicFeature", "feature" ]
- },
- "syntaxhighlighter": {
- "label": "QSyntaxHighlighter",
- "purpose": "Supports custom syntax highlighting.",
- "section": "Widgets",
- "condition": "features.textedit",
- "output": [ "publicFeature", "feature" ]
- },
- "rubberband": {
- "label": "QRubberBand",
- "purpose": "Supports using rubberbands to indicate selections and boundaries.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "tooltip": {
- "label": "QToolTip",
- "purpose": "Supports presentation of tooltips.",
- "section": "Widgets",
- "condition": "features.label",
- "output": [ "publicFeature", "feature" ]
- },
- "statustip": {
- "label": "Status Tip",
- "purpose": "Supports status tip functionality and events.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "sizegrip": {
- "label": "QSizeGrip",
- "purpose": "Provides corner-grips for resizing top-level windows.",
- "section": "Widgets",
- "output": [ "publicFeature", "feature" ]
- },
- "calendarwidget": {
- "label": "QCalendarWidget",
- "purpose": "Provides a monthly based calendar widget allowing the user to select a date.",
- "section": "Widgets",
- "condition": [
- "features.label",
- "features.menu",
- "features.pushbutton",
- "features.spinbox",
- "features.tableview",
- "features.textdate",
- "features.toolbutton"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "keysequenceedit": {
- "label": "QKeySequenceEdit",
- "purpose": "Provides a widget for editing QKeySequences.",
- "section": "Widgets",
- "condition": "features.lineedit && features.shortcut",
- "output": [ "publicFeature", "feature" ]
- },
- "dialog" : {
- "label": "QDialog",
- "purpose": "Base class of dialog windows.",
- "section": "Dialogs",
- "output": [ "publicFeature" ]
- },
- "dialogbuttonbox": {
- "label": "QDialogButtonBox",
- "purpose": "Presents buttons in a layout that is appropriate for the current widget style.",
- "section": "Dialogs",
- "condition": "features.dialog && features.pushbutton",
- "output": [ "publicFeature" ]
- },
- "messagebox": {
- "label": "QMessageBox",
- "purpose": "Provides message boxes displaying informative messages and simple questions.",
- "section": "Dialogs",
- "condition" : [
- "features.checkbox",
- "features.dialog",
- "features.dialogbuttonbox",
- "features.label",
- "features.pushbutton"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "colordialog": {
- "label": "QColorDialog",
- "purpose": "Provides a dialog widget for specifying colors.",
- "section": "Dialogs",
- "condition": [
- "features.dialog",
- "features.dialogbuttonbox",
- "features.label",
- "features.pushbutton",
- "features.spinbox"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "filedialog": {
- "label": "QFileDialog",
- "purpose": "Provides a dialog widget for selecting files or directories.",
- "section": "Dialogs",
- "condition": [
- "features.buttongroup",
- "features.combobox",
- "features.dialog",
- "features.dialogbuttonbox",
- "features.dirmodel",
- "features.label",
- "features.proxymodel",
- "features.splitter",
- "features.stackedwidget",
- "features.treeview",
- "features.toolbutton"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "fontdialog": {
- "label": "QFontDialog",
- "purpose": "Provides a dialog widget for selecting fonts.",
- "section": "Dialogs",
- "condition": [
- "features.checkbox",
- "features.combobox",
- "features.dialog",
- "features.dialogbuttonbox",
- "features.groupbox",
- "features.label",
- "features.pushbutton",
- "features.stringlistmodel",
- "features.validator"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "progressdialog": {
- "label": "QProgressDialog",
- "purpose": "Provides feedback on the progress of a slow operation.",
- "section": "Dialogs",
- "condition": [
- "features.dialog",
- "features.label",
- "features.pushbutton",
- "features.progressbar"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "inputdialog": {
- "label": "QInputDialog",
- "purpose": "Provides a simple convenience dialog to get a single value from the user.",
- "section": "Dialogs",
- "condition": [
- "features.combobox",
- "features.dialog",
- "features.dialogbuttonbox",
- "features.label",
- "features.pushbutton",
- "features.spinbox",
- "features.stackedwidget",
- "features.textedit"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "errormessage": {
- "label": "QErrorMessage",
- "purpose": "Provides an error message display dialog.",
- "section": "Dialogs",
- "condition": [
- "features.checkbox",
- "features.dialog",
- "features.textedit",
- "features.label",
- "features.pushbutton",
- "features.textedit"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "wizard": {
- "label": "QWizard",
- "purpose": "Provides a framework for multi-page click-through dialogs.",
- "section": "Dialogs",
- "condition": [
- "features.dialog",
- "features.pushbutton",
- "features.properties",
- "features.label"
- ],
- "output": [ "publicFeature", "feature" ]
- },
- "dirmodel": {
- "label": "QDirModel",
- "purpose": "Provides a data model for the local filesystem.",
- "section": "ItemViews",
- "condition": "features.itemviews && features.filesystemmodel",
- "output": [ "publicFeature", "feature" ]
- },
- "listview": {
- "label": "QListView",
- "purpose": "Provides a list or icon view onto a model.",
- "section": "ItemViews",
- "condition": "features.itemviews",
- "output": [ "publicFeature", "feature" ]
- },
- "tableview": {
- "label": "QTableView",
- "purpose": "Provides a default model/view implementation of a table view.",
- "section": "ItemViews",
- "condition": "features.itemviews",
- "output": [ "publicFeature", "feature" ]
- },
- "treeview": {
- "label": "QTreeView",
- "purpose": "Provides a default model/view implementation of a tree view.",
- "section": "ItemViews",
- "condition": "features.itemviews",
- "output": [ "publicFeature", "feature" ]
- },
- "datawidgetmapper": {
- "label": "QDataWidgetMapper",
- "purpose": "Provides mapping between a section of a data model to widgets.",
- "section": "ItemViews",
- "condition": "features.itemviews && features.properties",
- "output": [ "publicFeature", "feature" ]
- },
- "columnview": {
- "label": "QColumnView",
- "purpose": "Provides a model/view implementation of a column view.",
- "section": "ItemViews",
- "condition": "features.listview",
- "output": [ "publicFeature", "feature" ]
- },
- "completer": {
- "label": "QCompleter",
- "purpose": "Provides completions based on an item model.",
- "section": "Utilities",
- "condition": "features.proxymodel && features.itemviews",
- "output": [ "publicFeature", "feature" ]
- },
- "fscompleter": {
- "label": "QFSCompleter",
- "purpose": "Provides file name completion in QFileDialog.",
- "section": "Utilities",
- "condition": "features.filesystemmodel && features.completer",
- "output": [ "publicFeature", "feature" ]
- },
- "undocommand": {
- "label": "QUndoCommand",
- "purpose": "Applies (redo or) undo of a single change in a document.",
- "section": "Utilities",
- "output": [ "publicFeature", "feature" ]
- },
- "undostack": {
- "label": "QUndoStack",
- "purpose": "Provides the ability to (redo or) undo a list of changes in a document.",
- "section": "Utilities",
- "condition": "features.undocommand",
- "output": [ "publicFeature", "feature" ]
- },
- "undogroup": {
- "label": "QUndoGroup",
- "purpose": "Provides the ability to cluster QUndoCommands.",
- "section": "Utilities",
- "condition": "features.undostack",
- "output": [ "publicFeature", "feature" ]
- },
- "undoview": {
- "label": "QUndoView",
- "purpose": "Provides a widget which shows the contents of an undo stack.",
- "section": "Utilities",
- "condition": "features.undostack && features.listview",
- "output": [ "publicFeature", "feature" ]
- }
- },
-
- "report": [
- ],
-
- "summary": [
- {
- "section": "Qt Widgets",
- "entries": [
- "gtk3",
- {
- "message": "Styles",
- "type": "featureList",
- "args": "style-fusion style-mac style-windows style-windowsvista style-android"
- }
- ]
- }
- ]
-}
diff --git a/src/widgets/configure.pri b/src/widgets/configure.pri
deleted file mode 100644
index ddb3657700..0000000000
--- a/src/widgets/configure.pri
+++ /dev/null
@@ -1,8 +0,0 @@
-# custom outputs
-
-defineTest(qtConfOutput_styles) {
- !$${2}: return()
-
- style = $$replace($${1}.feature, "style-", "")
- qtConfOutputVar(append, "privatePro", "styles", $$style)
-}
diff --git a/src/widgets/dialogs/dialogs.pri b/src/widgets/dialogs/dialogs.pri
deleted file mode 100644
index a6a6b2d352..0000000000
--- a/src/widgets/dialogs/dialogs.pri
+++ /dev/null
@@ -1,84 +0,0 @@
-# Qt dialogs module
-
-INCLUDEPATH += $$PWD
-
-qtConfig(colordialog) {
- HEADERS += dialogs/qcolordialog.h
- SOURCES += dialogs/qcolordialog.cpp
-}
-
-qtConfig(dialog) {
- HEADERS += \
- dialogs/qdialog.h \
- dialogs/qdialog_p.h
-
- SOURCES += \
- dialogs/qdialog.cpp
-}
-
-qtConfig(errormessage) {
- HEADERS += dialogs/qerrormessage.h
- SOURCES += dialogs/qerrormessage.cpp
-}
-
-qtConfig(filedialog) {
- HEADERS += \
- dialogs/qfiledialog.h \
- dialogs/qfiledialog_p.h \
- dialogs/qsidebar_p.h
-
- SOURCES += \
- dialogs/qfiledialog.cpp \
- dialogs/qsidebar.cpp
-
- FORMS += dialogs/qfiledialog.ui
-}
-
-qtConfig(filesystemmodel) {
- HEADERS += \
- dialogs/qfilesystemmodel.h \
- dialogs/qfilesystemmodel_p.h \
- dialogs/qfileinfogatherer_p.h
-
- SOURCES += \
- dialogs/qfilesystemmodel.cpp \
- dialogs/qfileinfogatherer.cpp
-}
-
-qtConfig(fontdialog) {
- HEADERS += \
- dialogs/qfontdialog.h \
- dialogs/qfontdialog_p.h
-
- SOURCES += dialogs/qfontdialog.cpp
-}
-
-qtConfig(fscompleter) {
- HEADERS += dialogs/qfscompleter_p.h
-}
-
-qtConfig(inputdialog) {
- HEADERS += dialogs/qinputdialog.h
- SOURCES += dialogs/qinputdialog.cpp
-}
-
-qtConfig(messagebox) {
- HEADERS += dialogs/qmessagebox.h
- SOURCES += dialogs/qmessagebox.cpp
- RESOURCES += dialogs/qmessagebox.qrc
-}
-
-qtConfig(progressdialog) {
- HEADERS += dialogs/qprogressdialog.h
- SOURCES += dialogs/qprogressdialog.cpp
-}
-
-qtConfig(wizard) {
- HEADERS += dialogs/qwizard.h
- SOURCES += dialogs/qwizard.cpp
-
- win32 {
- HEADERS += dialogs/qwizard_win_p.h
- SOURCES += dialogs/qwizard_win.cpp
- }
-}
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 689002b589..22efecedc9 100644
--- a/src/widgets/dialogs/qcolordialog.cpp
+++ b/src/widgets/dialogs/qcolordialog.cpp
@@ -1,47 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qcolordialog.h"
#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
#include "qdrawutil.h"
#include "qevent.h"
#include "qimage.h"
@@ -59,8 +21,6 @@
#include "qpushbutton.h"
#if QT_CONFIG(regularexpression)
#include <qregularexpression.h>
-#else
-#include <qregexp.h>
#endif
#if QT_CONFIG(settings)
#include "qsettings.h"
@@ -79,17 +39,33 @@
#include "private/qdialog_p.h"
+#include <qpa/qplatformintegration.h>
+#include <qpa/qplatformservices.h>
+#include <private/qguiapplication_p.h>
+
+#include <QtCore/qpointer.h>
+
#include <algorithm>
QT_BEGIN_NAMESPACE
-namespace {
+using namespace Qt::StringLiterals;
+
+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
{
@@ -126,17 +102,18 @@ public:
void showAlpha(bool b);
bool isAlphaVisible() const;
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();
@@ -145,6 +122,7 @@ public:
bool handleColorPickingKeyPress(QKeyEvent *e);
bool canBeNativeDialog() const override;
+ void setVisible(bool visible) override;
QWellArray *custom;
QWellArray *standard;
@@ -160,7 +138,7 @@ public:
QPushButton *ok;
QPushButton *cancel;
QPushButton *addCusBt;
- QPushButton *screenColorPickerButton;
+ QPushButton *eyeDropperButton = nullptr;
QColor selectedQColor;
int nextCust;
bool smallDisplay;
@@ -183,7 +161,7 @@ private:
//////////// QWellArray BEGIN
-namespace {
+namespace QtPrivate {
class QWellArray : public QWidget
{
@@ -346,7 +324,8 @@ void QWellArray::paintCell(QPainter* p, int row, int col, const QRect &rect)
const QPalette & g = palette();
QStyleOptionFrame opt;
- int dfw = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+ opt.initFrom(this);
+ int dfw = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, this);
opt.lineWidth = dfw;
opt.midLineWidth = 1;
opt.rect = rect.adjusted(b, b, -b, -b);
@@ -383,7 +362,7 @@ void QWellArray::paintCellContents(QPainter *p, int row, int col, const QRect &r
void QWellArray::mousePressEvent(QMouseEvent *e)
{
// The current cell marker is set to the cell the mouse is pressed in
- QPoint pos = e->pos();
+ QPoint pos = e->position().toPoint();
setCurrent(rowAt(pos.y()), columnAt(pos.x()));
}
@@ -463,19 +442,19 @@ void QWellArray::keyPressEvent(QKeyEvent* e)
{
switch(e->key()) { // Look at the key code
case Qt::Key_Left: // If 'left arrow'-key,
- if(curCol > 0) // and cr't not in leftmost col
+ if (curCol > 0) // and cr't not in leftmost col
setCurrent(curRow, curCol - 1); // set cr't to next left column
break;
case Qt::Key_Right: // Correspondingly...
- if(curCol < numCols()-1)
+ if (curCol < numCols()-1)
setCurrent(curRow, curCol + 1);
break;
case Qt::Key_Up:
- if(curRow > 0)
+ if (curRow > 0)
setCurrent(curRow - 1, curCol);
break;
case Qt::Key_Down:
- if(curRow < numRows()-1)
+ if (curRow < numRows()-1)
setCurrent(curRow + 1, curCol);
break;
#if 0
@@ -497,7 +476,7 @@ void QWellArray::keyPressEvent(QKeyEvent* e)
return;
}
-}
+} // namespace QtPrivate
//////////// QWellArray END
@@ -587,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
{
@@ -627,7 +606,7 @@ void QColorWell::mousePressEvent(QMouseEvent *e)
oldCurrent = QPoint(selectedRow(), selectedColumn());
QWellArray::mousePressEvent(e);
mousePressed = true;
- pressPos = e->pos();
+ pressPos = e->position().toPoint();
}
void QColorWell::mouseMoveEvent(QMouseEvent *e)
@@ -636,7 +615,7 @@ void QColorWell::mouseMoveEvent(QMouseEvent *e)
#if QT_CONFIG(draganddrop)
if (!mousePressed)
return;
- if ((pressPos - e->pos()).manhattanLength() > QApplication::startDragDistance()) {
+ if ((pressPos - e->position().toPoint()).manhattanLength() > QApplication::startDragDistance()) {
setCurrent(oldCurrent.x(), oldCurrent.y());
int i = rowAt(pressPos.y()) + columnAt(pressPos.x()) * numRows();
QColor col(values[i]);
@@ -674,7 +653,7 @@ void QColorWell::dragLeaveEvent(QDragLeaveEvent *)
void QColorWell::dragMoveEvent(QDragMoveEvent *e)
{
if (qvariant_cast<QColor>(e->mimeData()->colorData()).isValid()) {
- setCurrent(rowAt(e->pos().y()), columnAt(e->pos().x()));
+ setCurrent(rowAt(e->position().toPoint().y()), columnAt(e->position().toPoint().x()));
e->accept();
} else {
e->ignore();
@@ -685,7 +664,7 @@ void QColorWell::dropEvent(QDropEvent *e)
{
QColor col = qvariant_cast<QColor>(e->mimeData()->colorData());
if (col.isValid()) {
- int i = rowAt(e->pos().y()) + columnAt(e->pos().x()) * numRows();
+ int i = rowAt(e->position().toPoint().y()) + columnAt(e->position().toPoint().x()) * numRows();
emit colorChanged(i, col.rgb());
e->accept();
} else {
@@ -737,9 +716,13 @@ private:
bool crossVisible;
};
+} // namespace QtPrivate
+
static int pWidth = 220;
static int pHeight = 200;
+namespace QtPrivate {
+
class QColorLuminancePicker : public QWidget
{
Q_OBJECT
@@ -800,11 +783,15 @@ QColorLuminancePicker::~QColorLuminancePicker()
void QColorLuminancePicker::mouseMoveEvent(QMouseEvent *m)
{
- setVal(y2val(m->y()));
+ if (m->buttons() == Qt::NoButton) {
+ m->ignore();
+ return;
+ }
+ setVal(y2val(m->position().toPoint().y()));
}
void QColorLuminancePicker::mousePressEvent(QMouseEvent *m)
{
- setVal(y2val(m->y()));
+ setVal(y2val(m->position().toPoint().y()));
}
void QColorLuminancePicker::setVal(int v)
@@ -849,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)
@@ -933,14 +919,18 @@ void QColorPicker::setCol(int h, int s)
void QColorPicker::mouseMoveEvent(QMouseEvent *m)
{
- QPoint p = m->pos() - contentsRect().topLeft();
+ QPoint p = m->position().toPoint() - contentsRect().topLeft();
+ if (m->buttons() == Qt::NoButton) {
+ m->ignore();
+ return;
+ }
setCol(p);
emit newCol(hue, sat);
}
void QColorPicker::mousePressEvent(QMouseEvent *m)
{
- QPoint p = m->pos() - contentsRect().topLeft();
+ QPoint p = m->position().toPoint() - contentsRect().topLeft();
setCol(p);
emit newCol(hue, sat);
}
@@ -1114,7 +1104,7 @@ inline bool QColorShower::isAlphaVisible() const
void QColorShowLabel::mousePressEvent(QMouseEvent *e)
{
mousePressed = true;
- pressPos = e->pos();
+ pressPos = e->position().toPoint();
}
void QColorShowLabel::mouseMoveEvent(QMouseEvent *e)
@@ -1124,7 +1114,7 @@ void QColorShowLabel::mouseMoveEvent(QMouseEvent *e)
#else
if (!mousePressed)
return;
- if ((pressPos - e->pos()).manhattanLength() > QApplication::startDragDistance()) {
+ if ((pressPos - e->position().toPoint()).manhattanLength() > QApplication::startDragDistance()) {
QMimeData *mime = new QMimeData;
mime->setColorData(col);
QPixmap pix(30, 20);
@@ -1200,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);
@@ -1305,18 +1295,15 @@ 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);
-#elif !defined(QT_NO_REGEXP)
- QRegExp regExp(QStringLiteral("#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})"));
- QRegExpValidator *validator = new QRegExpValidator(regExp, this);
- htEd->setValidator(validator);
#else
htEd->setReadOnly(true);
#endif
@@ -1331,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(); }
@@ -1407,11 +1394,20 @@ void QColorShower::hsvEd()
void QColorShower::htmlEd()
{
- QColor c;
QString t = htEd->text();
- c.setNamedColor(t);
+ 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);
@@ -1495,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);
@@ -1509,7 +1505,7 @@ void QColorDialogPrivate::setCurrentRgbColor(QRgb rgb)
{
if (!nativeDialogInUse) {
cs->setRgb(rgb);
- _q_newColorTypedIn(rgb);
+ newColorTypedIn(rgb);
}
}
@@ -1542,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();
@@ -1558,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();
@@ -1570,14 +1566,18 @@ bool QColorDialogPrivate::selectColor(const QColor &col)
QColor QColorDialogPrivate::grabScreenColor(const QPoint &p)
{
- const QDesktopWidget *desktop = QApplication::desktop();
- const QPixmap pixmap = QGuiApplication::primaryScreen()->grabWindow(desktop->winId(), p.x(), p.y(), 1, 1);
- QImage i = pixmap.toImage();
+ QScreen *screen = QGuiApplication::screenAt(p);
+ if (!screen)
+ screen = QGuiApplication::primaryScreen();
+ const QRect screenRect = screen->geometry();
+ const QPixmap pixmap =
+ screen->grabWindow(0, p.x() - screenRect.x(), p.y() - screenRect.y(), 1, 1);
+ const QImage i = pixmap.toImage();
return i.pixel(0, 0);
}
//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;
@@ -1587,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));
@@ -1600,16 +1600,30 @@ 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);
+
+ auto *platformServices = QGuiApplicationPrivate::platformIntegration()->services();
+ if (platformServices->hasCapability(QPlatformServices::Capability::ColorPicking)) {
+ if (auto *colorPicker = platformServices->colorPicker(q->windowHandle())) {
+ q->connect(colorPicker, &QPlatformServiceColorPicker::colorPicked, q,
+ [q, colorPicker](const QColor &color) {
+ colorPicker->deleteLater();
+ q->setCurrentColor(color);
+ });
+ colorPicker->pickColor();
+ return;
+ }
+ }
+
if (!colorPickingEventFilter)
colorPickingEventFilter = new QColorPickingEventFilter(this, q);
q->installEventFilter(colorPickingEventFilter);
@@ -1621,7 +1635,7 @@ void QColorDialogPrivate::_q_pickScreenColor()
q->grabMouse();
#endif
-#ifdef Q_OS_WIN32 // excludes WinRT
+#ifdef Q_OS_WIN32
// On Windows mouse tracking doesn't work over other processes's windows
updateTimer->start(30);
@@ -1638,16 +1652,18 @@ void QColorDialogPrivate::_q_pickScreenColor()
addCusBt->setDisabled(true);
buttons->setDisabled(true);
- screenColorPickerButton->setDisabled(true);
-
- const QPoint globalPos = QCursor::pos();
- q->setCurrentColor(grabScreenColor(globalPos));
- updateColorLabelText(globalPos);
+ if (eyeDropperButton) {
+ eyeDropperButton->setDisabled(true);
+ const QPoint globalPos = QCursor::pos();
+ q->setCurrentColor(grabScreenColor(globalPos));
+ updateColorLabelText(globalPos);
+ }
}
void QColorDialogPrivate::updateColorLabelText(const QPoint &globalPos)
{
- lblScreenColorInfo->setText(QColorDialog::tr("Cursor at %1, %2\nPress ESC to cancel")
+ if (lblScreenColorInfo)
+ lblScreenColorInfo->setText(QColorDialog::tr("Cursor at %1, %2\nPress ESC to cancel")
.arg(globalPos.x())
.arg(globalPos.y()));
}
@@ -1664,10 +1680,10 @@ void QColorDialogPrivate::releaseColorPicking()
#endif
q->releaseKeyboard();
q->setMouseTracking(false);
- lblScreenColorInfo->setText(QLatin1String("\n"));
+ lblScreenColorInfo->setText("\n"_L1);
addCusBt->setDisabled(false);
buttons->setDisabled(false);
- screenColorPickerButton->setDisabled(false);
+ eyeDropperButton->setDisabled(false);
}
void QColorDialogPrivate::init(const QColor &initial)
@@ -1711,7 +1727,7 @@ void QColorDialogPrivate::initWidgets()
#else
// small displays (e.g. PDAs) cannot fit the full color dialog,
// so just use the color picker.
- smallDisplay = (QDesktopWidgetPrivate::width() < 480 || QDesktopWidgetPrivate::height() < 350);
+ smallDisplay = (QGuiApplication::primaryScreen()->virtualGeometry().width() < 480 || QGuiApplication::primaryScreen()->virtualGeometry().height() < 350);
const int lumSpace = topLay->spacing() / 2;
#endif
@@ -1724,17 +1740,23 @@ 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)
- // The screen color picker button
- screenColorPickerButton = new QPushButton();
- leftLay->addWidget(screenColorPickerButton);
- lblScreenColorInfo = new QLabel(QLatin1String("\n"));
- leftLay->addWidget(lblScreenColorInfo);
- q->connect(screenColorPickerButton, SIGNAL(clicked()), SLOT(_q_pickScreenColor()));
+ if (supportsColorPicking()) {
+ eyeDropperButton = new QPushButton();
+ leftLay->addWidget(eyeDropperButton);
+ lblScreenColorInfo = new QLabel("\n"_L1);
+ leftLay->addWidget(lblScreenColorInfo);
+ QObjectPrivate::connect(eyeDropperButton, &QPushButton::clicked,
+ this, &QColorDialogPrivate::pickScreenColor);
+ } else {
+ eyeDropperButton = nullptr;
+ lblScreenColorInfo = nullptr;
+ }
#endif
leftLay->addStretch();
@@ -1742,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();
@@ -1759,15 +1781,15 @@ 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
#if defined(QT_SMALL_COLORDIALOG)
- QSize screenSize = QDesktopWidgetPrivate::availableGeometry(QCursor::pos()).size();
+ QSize screenSize = QGuiApplication::screenAt(QCursor::pos())->availableGeometry().size();
pWidth = pHeight = qMin(screenSize.width(), screenSize.height());
pHeight -= 20;
- if(screenSize.height() > screenSize.width())
+ if (screenSize.height() > screenSize.width())
pWidth -= 20;
#else
pWidth = 150;
@@ -1787,7 +1809,7 @@ void QColorDialogPrivate::initWidgets()
pickLay->addLayout(cLay);
cp = new QColorPicker(q);
- cp->setFrameStyle(QFrame::Panel + QFrame::Sunken);
+ cp->setFrameStyle(QFrame::Panel | QFrame::Sunken);
#if defined(QT_SMALL_COLORDIALOG)
cp->hide();
@@ -1807,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
@@ -1829,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();
}
@@ -1844,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 *)
@@ -1854,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)
@@ -1871,12 +1898,22 @@ void QColorDialogPrivate::retranslateStrings()
lblBasicColors->setText(QColorDialog::tr("&Basic colors"));
lblCustomColors->setText(QColorDialog::tr("&Custom colors"));
addCusBt->setText(QColorDialog::tr("&Add to Custom Colors"));
- screenColorPickerButton->setText(QColorDialog::tr("&Pick Screen Color"));
+#if !defined(QT_SMALL_COLORDIALOG)
+ if (eyeDropperButton)
+ eyeDropperButton->setText(QColorDialog::tr("&Pick Screen Color"));
+#endif
}
cs->retranslateStrings();
}
+bool QColorDialogPrivate::supportsColorPicking() const
+{
+ const auto integration = QGuiApplicationPrivate::platformIntegration();
+ return integration->hasCapability(QPlatformIntegration::ScreenWindowGrabbing)
+ || integration->services()->hasCapability(QPlatformServices::Capability::ColorPicking);
+}
+
bool QColorDialogPrivate::canBeNativeDialog() const
{
// Don't use Q_Q here! This function is called from ~QDialog,
@@ -1890,12 +1927,10 @@ bool QColorDialogPrivate::canBeNativeDialog() const
return false;
}
- QLatin1String staticName(QColorDialog::staticMetaObject.className());
- QLatin1String dynamicName(q->metaObject()->className());
- return (staticName == dynamicName);
+ 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;
@@ -1955,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);
@@ -2061,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));
}
}
@@ -2080,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.
@@ -2110,27 +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) {
- d->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);
+ 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:
+ q->setAttribute(Qt::WA_DontShowOnScreen);
+ } else {
+ initWidgets();
+ }
} else {
- setAttribute(Qt::WA_DontShowOnScreen, false);
+ q->setAttribute(Qt::WA_DontShowOnScreen, false);
}
- QDialog::setVisible(visible);
+ QDialogPrivate::setVisible(visible);
}
/*!
@@ -2172,41 +2220,12 @@ QColor QColorDialog::getColor(const QColor &initial, QWidget *parent, const QStr
return dlg.selectedColor();
}
-#if QT_DEPRECATED_SINCE(5, 12)
-/*!
- \obsolete
-
- Pops up a modal color dialog to allow the user to choose a color
- and an alpha channel (transparency) value. The color+alpha is
- initially set to \a initial. The dialog is a child of \a parent.
-
- If \a ok is non-null, \e {*ok} is set to true if the user clicked
- \uicontrol{OK}, and to false if the user clicked Cancel.
-
- If the user clicks Cancel, the \a initial value is returned.
-
- Use QColorDialog::getColor() instead, passing the
- QColorDialog::ShowAlphaChannel option.
-*/
-
-QRgb QColorDialog::getRgba(QRgb initial, bool *ok, QWidget *parent)
-{
- const QColor color = getColor(QColor::fromRgba(initial), parent, QString(),
- ShowAlphaChannel);
- QRgb result = color.isValid() ? color.rgba() : initial;
- if (ok)
- *ok = color.isValid();
- return result;
-}
-#endif
-
/*!
Destroys the color dialog.
*/
QColorDialog::~QColorDialog()
{
-
}
/*!
@@ -2220,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);
@@ -2246,21 +2265,20 @@ void QColorDialogPrivate::updateColorPicking(const QPoint &globalPos)
// otherwise it is not possible to pre-select a custom cell for assignment.
setCurrentColor(color, ShowColor);
updateColorLabelText(globalPos);
-
}
bool QColorDialogPrivate::handleColorPickingMouseMove(QMouseEvent *e)
{
// If the cross is visible the grabbed color will be black most of the times
- cp->setCrossVisible(!cp->geometry().contains(e->pos()));
+ cp->setCrossVisible(!cp->geometry().contains(e->position().toPoint()));
- updateColorPicking(e->globalPos());
+ updateColorPicking(e->globalPosition().toPoint());
return true;
}
bool QColorDialogPrivate::handleColorPickingMouseButtonRelease(QMouseEvent *e)
{
- setCurrentColor(grabScreenColor(e->globalPos()), SetColorAll);
+ setCurrentColor(grabScreenColor(e->globalPosition().toPoint()), SetColorAll);
releaseColorPicking();
return true;
}
diff --git a/src/widgets/dialogs/qcolordialog.h b/src/widgets/dialogs/qcolordialog.h
index cdbe0e7fb4..824efa8f8c 100644
--- a/src/widgets/dialogs/qcolordialog.h
+++ b/src/widgets/dialogs/qcolordialog.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOLORDIALOG_H
#define QCOLORDIALOG_H
@@ -62,7 +26,8 @@ public:
enum ColorDialogOption {
ShowAlphaChannel = 0x00000001,
NoButtons = 0x00000002,
- DontUseNativeDialog = 0x00000004
+ DontUseNativeDialog = 0x00000004,
+ NoEyeDropperButton = 0x00000008,
};
Q_ENUM(ColorDialogOption)
@@ -92,10 +57,6 @@ public:
const QString &title = QString(),
ColorDialogOptions options = ColorDialogOptions());
-#if QT_DEPRECATED_SINCE(5, 12)
- QT_DEPRECATED_X("Use getColor()") static QRgb getRgba(QRgb rgba = 0xffffffff, bool *ok = nullptr, QWidget *parent = nullptr);
-#endif
-
static int customCount();
static QColor customColor(int index);
static void setCustomColor(int index, QColor color);
@@ -112,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 906022a185..27466d03d6 100644
--- a/src/widgets/dialogs/qdialog.cpp
+++ b/src/widgets/dialogs/qdialog.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QtWidgets/qtwidgetsglobal.h>
#if QT_CONFIG(colordialog)
@@ -49,8 +13,6 @@
#endif
#include "qevent.h"
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
#include "qapplication.h"
#include "qlayout.h"
#if QT_CONFIG(sizegrip)
@@ -72,7 +34,7 @@
#include <qpa/qplatformtheme.h>
#include "private/qdialog_p.h"
#include "private/qguiapplication_p.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
@@ -136,6 +98,9 @@ QPlatformDialogHelper *QDialogPrivate::platformHelper() const
bool QDialogPrivate::canBeNativeDialog() const
{
+ if (QCoreApplication::testAttribute(Qt::AA_DontUseNativeDialogs))
+ return false;
+
QDialogPrivate *ncThis = const_cast<QDialogPrivate *>(this);
QDialog *dialog = ncThis->q_func();
const int type = themeDialogType(dialog);
@@ -148,36 +113,40 @@ bool QDialogPrivate::canBeNativeDialog() const
/*!
\internal
- Properly hides dialog and sets the \a resultCode.
+ Properly closes dialog and sets the \a resultCode.
*/
-void QDialogPrivate::hide(int resultCode)
+void QDialogPrivate::close(int resultCode)
{
Q_Q(QDialog);
q->setResult(resultCode);
- q->hide();
-
- close_helper(QWidgetPrivate::CloseNoEvent);
- 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();
+ if (!data.is_closing) {
+ // Until Qt 6.3 we didn't close dialogs, so they didn't receive a QCloseEvent.
+ // It is likely that subclasses implement closeEvent and handle them as rejection
+ // (like QMessageBox and QProgressDialog do), so eat those events.
+ struct CloseEventEater : QObject
+ {
+ using QObject::QObject;
+ protected:
+ bool eventFilter(QObject *o, QEvent *e) override
+ {
+ if (e->type() == QEvent::Close)
+ return true;
+ return QObject::eventFilter(o, e);
+ }
+ } closeEventEater;
+ q->installEventFilter(&closeEventEater);
+ QWidgetPrivate::close();
+ } else {
+ // If the close was initiated outside of QDialog we will end up
+ // here via QDialog::closeEvent calling reject(), in which case
+ // we need to hide the dialog to ensure QDialog::closeEvent does
+ // not ignore the close event. FIXME: Why is QDialog doing this?
+ q->hide();
+ }
- emit q->finished(resultCode);
+ resetModalitySetByOpen();
}
QWindow *QDialogPrivate::transientParentWindow() const
@@ -211,14 +180,6 @@ QVariant QDialogPrivate::styleHint(QPlatformDialogHelper::StyleHint hint) const
return QPlatformDialogHelper::defaultStyleHint(hint);
}
-void QDialogPrivate::deletePlatformHelper()
-{
- delete m_platformHelper;
- m_platformHelper = nullptr;
- m_platformHelperCreated = false;
- nativeDialogInUse = false;
-}
-
/*!
\class QDialog
\brief The QDialog class is the base class of dialog windows.
@@ -319,7 +280,8 @@ void QDialogPrivate::deletePlatformHelper()
\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
@@ -327,9 +289,8 @@ void QDialogPrivate::deletePlatformHelper()
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)
@@ -359,8 +320,15 @@ void QDialogPrivate::deletePlatformHelper()
\snippet dialogs/dialogs.cpp 0
+ 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,
- {fowler}{GUI Design Handbook: Dialogs, Standard}, {Extension Example},
{Standard Dialogs Example}
*/
@@ -625,7 +593,7 @@ int QDialog::exec()
As with QWidget::close(), done() deletes the dialog if the
Qt::WA_DeleteOnClose flag is set. If the dialog is the application's
main widget, the application terminates. If the dialog is the
- last window closed, the QApplication::lastWindowClosed() signal is
+ last window closed, the QGuiApplication::lastWindowClosed() signal is
emitted.
\sa accept(), reject(), QApplication::activeWindow(), QCoreApplication::quit()
@@ -633,9 +601,22 @@ int QDialog::exec()
void QDialog::done(int r)
{
+ QPointer<QDialog> guard(this);
+
Q_D(QDialog);
- d->hide(r);
- d->finalize(r, r);
+ d->close(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);
}
/*!
@@ -763,104 +744,108 @@ 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);
-#if QT_DEPRECATED_SINCE(5, 13)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- showExtension(d->doShowExtension);
-QT_WARNING_POP
-#endif
- QWidget *fw = window()->focusWidget();
- if (!fw)
- fw = this;
-
- /*
- The following block is to handle a special case, and does not
- really follow propper logic in concern of autoDefault and TAB
- order. However, it's here to ease usage for the users. If a
- dialog has a default QPushButton, and first widget in the TAB
- order also is a QPushButton, then we give focus to the main
- default QPushButton. This simplifies code for the developers,
- and actually catches most cases... If not, then they simply
- have to use [widget*]->setFocus() themselves...
- */
+ 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 (!q->testAttribute(Qt::WA_ShowWithoutActivating)) {
+ QWidget *fw = q->window()->focusWidget();
+ if (!fw)
+ fw = q;
+
+ /*
+ The following block is to handle a special case, and does not
+ really follow proper logic in concern of autoDefault and TAB
+ order. However, it's here to ease usage for the users. If a
+ dialog has a default QPushButton, and first widget in the TAB
+ order also is a QPushButton, then we give focus to the main
+ default QPushButton. This simplifies code for the developers,
+ and actually catches most cases... If not, then they simply
+ have to use [widget*]->setFocus() themselves...
+ */
#if QT_CONFIG(pushbutton)
- if (d->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 (!d->mainDef && isWindow()) {
- QWidget *w = fw;
- while ((w = w->nextInFocusChain()) != fw) {
- QPushButton *pb = qobject_cast<QPushButton *>(w);
- if (pb && pb->autoDefault() && pb->focusPolicy() != Qt::NoFocus) {
- pb->setDefault(true);
- break;
+ if (mainDef && fw->focusPolicy() == Qt::NoFocus) {
+ QWidget *first = fw;
+ while ((first = first->nextInFocusChain()) != fw && first->focusPolicy() == Qt::NoFocus)
+ ;
+ if (first != mainDef && qobject_cast<QPushButton*>(first))
+ mainDef->setFocus();
+ }
+ if (!mainDef && q->isWindow()) {
+ QWidget *w = fw;
+ while ((w = w->nextInFocusChain()) != fw) {
+ QPushButton *pb = qobject_cast<QPushButton *>(w);
+ if (pb && pb->autoDefault() && pb->focusPolicy() != Qt::NoFocus) {
+ pb->setDefault(true);
+ break;
+ }
}
}
- }
#endif
- if (fw && !fw->hasFocus()) {
- QFocusEvent e(QEvent::FocusIn, Qt::TabFocusReason);
- QCoreApplication::sendEvent(fw, &e);
+ if (fw && !fw->hasFocus()) {
+ QFocusEvent e(QEvent::FocusIn, Qt::TabFocusReason);
+ QCoreApplication::sendEvent(fw, &e);
+ }
}
-#ifndef QT_NO_ACCESSIBILITY
- QAccessibleEvent event(this, QAccessible::DialogStart);
+#if QT_CONFIG(accessibility)
+ QAccessibleEvent event(q, QAccessible::DialogStart);
QAccessible::updateAccessibility(&event);
#endif
} else {
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
- return;
-#ifndef QT_NO_ACCESSIBILITY
- if (isVisible()) {
- QAccessibleEvent event(this, QAccessible::DialogEnd);
+#if QT_CONFIG(accessibility)
+ 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
}
@@ -879,23 +864,31 @@ void QDialog::showEvent(QShowEvent *event)
/*! \internal */
void QDialog::adjustPosition(QWidget* w)
{
+ Q_D(QDialog);
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
if (theme->themeHint(QPlatformTheme::WindowAutoPlacement).toBool())
return;
QPoint p(0, 0);
- int extraw = 0, extrah = 0, scrn = 0;
- if (w)
- w = w->window();
- QRect desk;
+ int extraw = 0, extrah = 0;
+ const QWindow *parentWindow = nullptr;
if (w) {
- scrn = QDesktopWidgetPrivate::screenNumber(w);
- } else if (QDesktopWidgetPrivate::isVirtualDesktop()) {
- scrn = QDesktopWidgetPrivate::screenNumber(QCursor::pos());
+ w = w->window();
} else {
- scrn = QDesktopWidgetPrivate::screenNumber(this);
+ parentWindow = d->transientParentWindow();
}
- desk = QDesktopWidgetPrivate::availableGeometry(scrn);
+ QRect desk;
+ QScreen *scrn = nullptr;
+ if (w)
+ scrn = w->screen();
+ else if (parentWindow)
+ scrn = parentWindow->screen();
+ else if (QGuiApplication::primaryScreen()->virtualSiblings().size() > 1)
+ scrn = QGuiApplication::screenAt(QCursor::pos());
+ else
+ scrn = screen();
+ if (scrn)
+ desk = scrn->availableGeometry();
QWidgetList list = QApplication::topLevelWidgets();
for (int i = 0; (extraw == 0 || extrah == 0) && i < list.size(); ++i) {
@@ -926,6 +919,11 @@ void QDialog::adjustPosition(QWidget* w)
pp = w->mapToGlobal(QPoint(0,0));
p = QPoint(pp.x() + w->width()/2,
pp.y() + w->height()/ 2);
+ } else if (parentWindow) {
+ // QTBUG-63406: Widget-based dialog in QML, which has no Widget parent
+ // but a transient parent window.
+ QPoint pp = parentWindow->mapToGlobal(QPoint(0, 0));
+ p = QPoint(pp.x() + parentWindow->width() / 2, pp.y() + parentWindow->height() / 2);
} else {
// p = middle of the desktop
p = QPoint(desk.x() + desk.width()/2, desk.y() + desk.height()/2);
@@ -949,161 +947,14 @@ void QDialog::adjustPosition(QWidget* w)
// QTBUG-52735: Manually set the correct target screen since scaling in a
// subsequent call to QWindow::resize() may otherwise use the wrong factor
// if the screen changed notification is still in an event queue.
- if (scrn >= 0) {
+ if (scrn) {
if (QWindow *window = windowHandle())
- window->setScreen(QGuiApplication::screens().at(scrn));
+ window->setScreen(scrn);
}
move(p);
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \obsolete
-
- If \a orientation is Qt::Horizontal, the extension will be displayed
- to the right of the dialog's main area. If \a orientation is
- Qt::Vertical, the extension will be displayed below the dialog's main
- area.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa setExtension()
-*/
-void QDialog::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QDialog);
- d->orientation = orientation;
-}
-
-/*!
- \obsolete
-
- Returns the dialog's extension orientation.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa extension()
-*/
-Qt::Orientation QDialog::orientation() const
-{
- Q_D(const QDialog);
- return d->orientation;
-}
-
-/*!
- \obsolete
-
- Sets the widget, \a extension, to be the dialog's extension,
- deleting any previous extension. The dialog takes ownership of the
- extension. Note that if \nullptr is passed, any existing extension will be
- deleted. This function must only be called while the dialog is hidden.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa showExtension(), setOrientation()
-*/
-void QDialog::setExtension(QWidget* extension)
-{
- Q_D(QDialog);
- delete d->extension;
- d->extension = extension;
-
- if (!extension)
- return;
-
- if (extension->parentWidget() != this)
- extension->setParent(this);
- extension->hide();
-}
-
-/*!
- \obsolete
-
- Returns the dialog's extension or \nullptr if no extension has been
- defined.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa showExtension(), setOrientation()
-*/
-QWidget* QDialog::extension() const
-{
- Q_D(const QDialog);
- return d->extension;
-}
-
-
-/*!
- \obsolete
-
- If \a showIt is true, the dialog's extension is shown; otherwise the
- extension is hidden.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa show(), setExtension(), setOrientation()
-*/
-void QDialog::showExtension(bool showIt)
-{
- Q_D(QDialog);
- d->doShowExtension = showIt;
- if (!d->extension)
- return;
- if (!testAttribute(Qt::WA_WState_Visible))
- return;
- if (d->extension->isVisible() == showIt)
- return;
-
- if (showIt) {
- d->size = size();
- d->min = minimumSize();
- d->max = maximumSize();
- if (layout())
- layout()->setEnabled(false);
- QSize s(d->extension->sizeHint()
- .expandedTo(d->extension->minimumSize())
- .boundedTo(d->extension->maximumSize()));
- if (d->orientation == Qt::Horizontal) {
- int h = qMax(height(), s.height());
- d->extension->setGeometry(width(), 0, s.width(), h);
- setFixedSize(width() + s.width(), h);
- } else {
- int w = qMax(width(), s.width());
- d->extension->setGeometry(0, height(), w, s.height());
- setFixedSize(w, height() + s.height());
- }
- d->extension->show();
-#if QT_CONFIG(sizegrip)
- const bool sizeGripEnabled = isSizeGripEnabled();
- setSizeGripEnabled(false);
- d->sizeGripEnabled = sizeGripEnabled;
-#endif
- } else {
- d->extension->hide();
- // workaround for CDE window manager that won't shrink with (-1,-1)
- setMinimumSize(d->min.expandedTo(QSize(1, 1)));
- setMaximumSize(d->max);
- resize(d->size);
- if (layout())
- layout()->setEnabled(true);
-#if QT_CONFIG(sizegrip)
- setSizeGripEnabled(d->sizeGripEnabled);
-#endif
- }
-}
-#endif
-
/*! \reimp */
QSize QDialog::sizeHint() const
{
diff --git a/src/widgets/dialogs/qdialog.h b/src/widgets/dialogs/qdialog.h
index ce2194a1de..4d11fe2d8d 100644
--- a/src/widgets/dialogs/qdialog.h
+++ b/src/widgets/dialogs/qdialog.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDIALOG_H
#define QDIALOG_H
@@ -69,13 +33,6 @@ public:
void setVisible(bool visible) override;
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use show/hide on the affected widget instead") void setOrientation(Qt::Orientation orientation);
- QT_DEPRECATED_X("Use show/hide on the affected widget instead") Qt::Orientation orientation() const;
- QT_DEPRECATED_X("Use show/hide on the affected widget instead") void setExtension(QWidget* extension);
- QT_DEPRECATED_X("Use show/hide on the affected widget instead") QWidget* extension() const;
-#endif
-
QSize sizeHint() const override;
QSize minimumSizeHint() const override;
@@ -97,10 +54,6 @@ public Q_SLOTS:
virtual void accept();
virtual void reject();
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use show/hide on the affected widget instead") void showExtension(bool);
-#endif
-
protected:
QDialog(QDialogPrivate &, QWidget *parent, Qt::WindowFlags f = Qt::WindowFlags());
diff --git a/src/widgets/dialogs/qdialog_p.h b/src/widgets/dialogs/qdialog_p.h
index 74f775a0bd..bac33bdea9 100644
--- a/src/widgets/dialogs/qdialog_p.h
+++ b/src/widgets/dialogs/qdialog_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDIALOG_P_H
#define QDIALOG_P_H
@@ -87,10 +51,11 @@ public:
{}
~QDialogPrivate();
+ virtual void setVisible(bool visible);
+
QWindow *transientParentWindow() const;
bool setNativeDialogVisible(bool visible);
QVariant styleHint(QPlatformDialogHelper::StyleHint hint) const;
- void deletePlatformHelper();
#if QT_CONFIG(pushbutton)
QPointer<QPushButton> mainDef;
@@ -122,8 +87,10 @@ public:
QPlatformDialogHelper *platformHelper() const;
virtual bool canBeNativeDialog() const;
- void hide(int resultCode);
- void finalize(int resultCode, int dialogCode);
+ void close(int resultCode);
+
+protected:
+ virtual int dialogCode() const { return rescode; }
private:
virtual void initHelper(QPlatformDialogHelper *) {}
@@ -137,16 +104,14 @@ private:
template <typename T>
class QAutoPointer {
QPointer<T> o;
- struct internal { void func() {} };
- typedef void (internal::*RestrictedBool)();
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(); }
T *get() const noexcept { return o; }
T &operator*() const { return *get(); }
- operator RestrictedBool() const noexcept { return o ? &internal::func : nullptr; }
+ explicit operator bool() const noexcept { return !o.isNull(); }
bool operator!() const noexcept { return !o; }
private:
Q_DISABLE_COPY(QAutoPointer);
diff --git a/src/widgets/dialogs/qerrormessage.cpp b/src/widgets/dialogs/qerrormessage.cpp
index 790d09414b..2b5681f79b 100644
--- a/src/widgets/dialogs/qerrormessage.cpp
+++ b/src/widgets/dialogs/qerrormessage.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qerrormessage.h"
@@ -62,17 +26,17 @@
QT_BEGIN_NAMESPACE
-namespace {
-struct Message {
- QString content;
- QString type;
-};
-}
+using namespace Qt::StringLiterals;
class QErrorMessagePrivate : public QDialogPrivate
{
Q_DECLARE_PUBLIC(QErrorMessage)
public:
+ struct Message {
+ QString content;
+ QString type;
+ };
+
QPushButton * ok;
QCheckBox * again;
QTextEdit * errors;
@@ -86,8 +50,46 @@ public:
bool isMessageToBeShown(const QString &message, const QString &type) const;
bool nextPending();
void retranslateStrings();
+
+ void setVisible(bool) override;
+
+private:
+ void initHelper(QPlatformDialogHelper *) override;
+ void helperPrepareShow(QPlatformDialogHelper *) override;
};
+
+void QErrorMessagePrivate::initHelper(QPlatformDialogHelper *helper)
+{
+ Q_Q(QErrorMessage);
+ auto *messageDialogHelper = static_cast<QPlatformMessageDialogHelper *>(helper);
+ QObject::connect(messageDialogHelper, &QPlatformMessageDialogHelper::checkBoxStateChanged, q,
+ [this](Qt::CheckState state) {
+ again->setCheckState(state);
+ }
+ );
+ QObject::connect(messageDialogHelper, &QPlatformMessageDialogHelper::clicked, q,
+ [this](QPlatformDialogHelper::StandardButton, QPlatformDialogHelper::ButtonRole) {
+ Q_Q(QErrorMessage);
+ q->accept();
+ }
+ );
+}
+
+void QErrorMessagePrivate::helperPrepareShow(QPlatformDialogHelper *helper)
+{
+ Q_Q(QErrorMessage);
+ auto *messageDialogHelper = static_cast<QPlatformMessageDialogHelper *>(helper);
+ QSharedPointer<QMessageDialogOptions> options = QMessageDialogOptions::create();
+ options->setText(currentMessage);
+ options->setWindowTitle(q->windowTitle());
+ options->setText(QErrorMessage::tr("An error occurred"));
+ options->setInformativeText(currentMessage);
+ options->setStandardIcon(QMessageDialogOptions::Critical);
+ options->setCheckBox(again->text(), again->checkState());
+ messageDialogHelper->setOptions(options);
+}
+
namespace {
class QErrorMessageTextView : public QTextEdit
{
@@ -163,11 +165,11 @@ static bool metFatal = false;
static QString msgType2i18nString(QtMsgType t)
{
- Q_STATIC_ASSERT(QtDebugMsg == 0);
- Q_STATIC_ASSERT(QtWarningMsg == 1);
- Q_STATIC_ASSERT(QtCriticalMsg == 2);
- Q_STATIC_ASSERT(QtFatalMsg == 3);
- Q_STATIC_ASSERT(QtInfoMsg == 4);
+ static_assert(QtDebugMsg == 0);
+ static_assert(QtWarningMsg == 1);
+ static_assert(QtCriticalMsg == 2);
+ static_assert(QtFatalMsg == 3);
+ static_assert(QtInfoMsg == 4);
// adjust the array below if any of the above fire...
@@ -183,16 +185,28 @@ static QString msgType2i18nString(QtMsgType t)
return QCoreApplication::translate("QErrorMessage", messages[t]);
}
-static void jump(QtMsgType t, const QMessageLogContext & /*context*/, const QString &m)
+static QtMessageHandler originalMessageHandler = nullptr;
+
+static void jump(QtMsgType t, const QMessageLogContext &context, const QString &m)
{
+ const auto forwardToOriginalHandler = qScopeGuard([&] {
+ if (originalMessageHandler)
+ originalMessageHandler(t, context, m);
+ });
+
if (!qtMessageHandler)
return;
- QString rich = QLatin1String("<p><b>") + msgType2i18nString(t) + QLatin1String("</b></p>")
+ auto *defaultCategory = QLoggingCategory::defaultCategory();
+ if (context.category && defaultCategory
+ && qstrcmp(context.category, defaultCategory->categoryName()) != 0)
+ return;
+
+ QString rich = "<p><b>"_L1 + msgType2i18nString(t) + "</b></p>"_L1
+ Qt::convertFromPlainText(m, Qt::WhiteSpaceNormal);
// ### work around text engine quirk
- if (rich.endsWith(QLatin1String("</p>")))
+ if (rich.endsWith("</p>"_L1))
rich.chop(4);
if (!metFatal) {
@@ -212,6 +226,10 @@ static void jump(QtMsgType t, const QMessageLogContext & /*context*/, const QStr
/*!
Constructs and installs an error handler window with the given \a
parent.
+
+ The default \l{Qt::WindowModality} {window modality} of the dialog
+ depends on the platform. The window modality can be overridden via
+ setWindowModality() before calling showMessage().
*/
QErrorMessage::QErrorMessage(QWidget * parent)
@@ -219,6 +237,10 @@ QErrorMessage::QErrorMessage(QWidget * parent)
{
Q_D(QErrorMessage);
+#if defined(Q_OS_MACOS)
+ setWindowModality(parent ? Qt::WindowModal : Qt::ApplicationModal);
+#endif
+
d->icon = new QLabel(this);
d->errors = new QErrorMessageTextView(this);
d->again = new QCheckBox(this);
@@ -235,7 +257,9 @@ QErrorMessage::QErrorMessage(QWidget * parent)
grid->setRowStretch(0, 42);
#if QT_CONFIG(messagebox)
- d->icon->setPixmap(QMessageBox::standardIcon(QMessageBox::Information));
+ 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);
@@ -253,10 +277,12 @@ QErrorMessage::~QErrorMessage()
{
if (this == qtMessageHandler) {
qtMessageHandler = nullptr;
- QtMessageHandler tmp = qInstallMessageHandler(nullptr);
- // in case someone else has later stuck in another...
- if (tmp != jump)
- qInstallMessageHandler(tmp);
+ QtMessageHandler currentMessagHandler = qInstallMessageHandler(nullptr);
+ if (currentMessagHandler != jump)
+ qInstallMessageHandler(currentMessagHandler);
+ else
+ qInstallMessageHandler(originalMessageHandler);
+ originalMessageHandler = nullptr;
}
}
@@ -276,8 +302,12 @@ void QErrorMessage::done(int a)
}
d->currentMessage.clear();
d->currentType.clear();
- if (!d->nextPending()) {
- QDialog::done(a);
+
+ QDialog::done(a);
+
+ if (d->nextPending()) {
+ show();
+ } else {
if (this == qtMessageHandler && metFatal)
exit(1);
}
@@ -288,6 +318,12 @@ void QErrorMessage::done(int a)
Returns a pointer to a QErrorMessage object that outputs the
default Qt messages. This function creates such an object, if there
isn't one already.
+
+ The object will only output log messages of QLoggingCategory::defaultCategory().
+
+ The object will forward all messages to the original message handler.
+
+ \sa qInstallMessageHandler
*/
QErrorMessage * QErrorMessage::qtHandler()
@@ -296,7 +332,7 @@ QErrorMessage * QErrorMessage::qtHandler()
qtMessageHandler = new QErrorMessage(nullptr);
qAddPostRoutine(deleteStaticcQErrorMessage); // clean up
qtMessageHandler->setWindowTitle(QCoreApplication::applicationName());
- qInstallMessageHandler(jump);
+ originalMessageHandler = qInstallMessageHandler(jump);
}
return qtMessageHandler;
}
@@ -324,6 +360,7 @@ bool QErrorMessagePrivate::nextPending()
#endif
currentMessage = std::move(message);
currentType = std::move(type);
+ again->setChecked(true);
return true;
}
}
@@ -369,6 +406,21 @@ void QErrorMessage::showMessage(const QString &message, const QString &type)
show();
}
+void QErrorMessagePrivate::setVisible(bool visible)
+{
+ Q_Q(QErrorMessage);
+
+ 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.
+ q->setAttribute(Qt::WA_DontShowOnScreen, nativeDialogInUse);
+
+ QDialogPrivate::setVisible(visible);
+}
+
/*!
\reimp
*/
diff --git a/src/widgets/dialogs/qerrormessage.h b/src/widgets/dialogs/qerrormessage.h
index 220694e54e..55f0ac058e 100644
--- a/src/widgets/dialogs/qerrormessage.h
+++ b/src/widgets/dialogs/qerrormessage.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QERRORMESSAGE_H
#define QERRORMESSAGE_H
diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp
index e24d308d65..22e6d44e6f 100644
--- a/src/widgets/dialogs/qfiledialog.cpp
+++ b/src/widgets/dialogs/qfiledialog.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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
#define QT_NO_URL_CAST_FROM_STRING
@@ -48,6 +12,7 @@
#include <private/qguiapplication_p.h>
#include <qfontmetrics.h>
#include <qaction.h>
+#include <qactiongroup.h>
#include <qheaderview.h>
#if QT_CONFIG(shortcut)
# include <qshortcut.h>
@@ -67,6 +32,9 @@
#if QT_CONFIG(mimetype)
#include <qmimedatabase.h>
#endif
+#if QT_CONFIG(regularexpression)
+#include <qregularexpression.h>
+#endif
#include <qapplication.h>
#include <qstylepainter.h>
#include "ui_qfiledialog.h"
@@ -84,18 +52,23 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
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.
+
+ \image qtquickdialogs-filedialog-gtk.png
- The easiest way to create a QFileDialog is to use the static functions.
+ 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
@@ -120,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;
@@ -129,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.
@@ -145,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
@@ -160,15 +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. You can set the \l DontUseNativeDialog option to
- ensure that the widget-based implementation will be used instead of the
- native dialog.
+ 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 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},
- {Application Example}
+ \sa QDir, QFileInfo, QFile, QColorDialog, QFontDialog, {Standard Dialogs Example}
*/
/*!
@@ -181,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.
@@ -196,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.
@@ -206,50 +180,49 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
directory chooser.
\value ExistingFiles The names of zero or more existing files.
- This value is obsolete since Qt 4.5:
-
- \value DirectoryOnly Use \c Directory and setOption(ShowDirsOnly, true) instead.
-
\sa setFileMode()
*/
/*!
\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.)
+ Options that influence the behavior of the dialog.
- \value DontResolveSymlinks Don't resolve symlinks in the file
- dialog. By default symlinks are resolved.
+ \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.
- \value DontConfirmOverwrite Don't ask for confirmation if an
- existing file is selected. By default confirmation is requested.
+ \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.
- \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 DontUseSheet In previous versions of Qt, the static
- functions would create a sheet by default if the static function
- was given a parent. This is no longer supported and does nothing in Qt 4.5, The
- static functions will always be an application modal dialog. If
- you want to use sheets, use QFileDialog::open() instead.
-
- \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
*/
/*!
@@ -360,7 +333,8 @@ QFileDialog::QFileDialog(QWidget *parent, Qt::WindowFlags f)
: QDialog(*new QFileDialogPrivate, parent, f)
{
Q_D(QFileDialog);
- d->init();
+ QFileDialogArgs args;
+ d->init(args);
}
/*!
@@ -377,7 +351,10 @@ QFileDialog::QFileDialog(QWidget *parent,
: QDialog(*new QFileDialogPrivate, parent, { })
{
Q_D(QFileDialog);
- d->init(QUrl::fromLocalFile(directory), filter, caption);
+ QFileDialogArgs args(QUrl::fromLocalFile(directory));
+ args.filter = filter;
+ args.caption = caption;
+ d->init(args);
}
/*!
@@ -387,7 +364,7 @@ QFileDialog::QFileDialog(const QFileDialogArgs &args)
: QDialog(*new QFileDialogPrivate, args.parent, { })
{
Q_D(QFileDialog);
- d->init(args.directory, args.filter, args.caption);
+ d->init(args);
setFileMode(args.mode);
setOptions(args.options);
selectFile(args.selection);
@@ -410,9 +387,9 @@ QFileDialog::~QFileDialog()
For instance:
- \snippet filedialogurls.cpp 0
+ \snippet filedialogurls/filedialogurls.cpp 0
- The file dialog will then look like this:
+ Then the file dialog looks like this:
\image filedialogurls.png
@@ -450,6 +427,7 @@ QByteArray QFileDialog::saveState() const
int version = 4;
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
+ stream.setVersion(QDataStream::Qt_5_0);
stream << qint32(QFileDialogMagic);
stream << qint32(version);
@@ -484,6 +462,7 @@ bool QFileDialog::restoreState(const QByteArray &state)
Q_D(QFileDialog);
QByteArray sd = state;
QDataStream stream(&sd, QIODevice::ReadOnly);
+ stream.setVersion(QDataStream::Qt_5_0);
if (stream.atEnd())
return false;
QStringList history;
@@ -554,14 +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);
- nativeDialogInUse = true;
+ 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 *)
@@ -594,13 +578,10 @@ void QFileDialogPrivate::retranslateWindowTitle()
return;
if (q->acceptMode() == QFileDialog::AcceptOpen) {
const QFileDialog::FileMode fileMode = q->fileMode();
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- if (fileMode == QFileDialog::DirectoryOnly || fileMode == QFileDialog::Directory)
+ if (fileMode == QFileDialog::Directory)
q->setWindowTitle(QFileDialog::tr("Find Directory"));
else
q->setWindowTitle(QFileDialog::tr("Open"));
-QT_WARNING_POP
} else
q->setWindowTitle(QFileDialog::tr("Save As"));
@@ -624,10 +605,6 @@ void QFileDialogPrivate::updateFileNameLabel()
setLabelTextControl(QFileDialog::FileName, options->labelText(QFileDialogOptions::FileName));
} else {
switch (q_func()->fileMode()) {
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- case QFileDialog::DirectoryOnly:
-QT_WARNING_POP
case QFileDialog::Directory:
setLabelTextControl(QFileDialog::FileName, QFileDialog::tr("Directory:"));
break;
@@ -655,10 +632,6 @@ void QFileDialogPrivate::updateOkButtonText(bool saveAsOnFolder)
return;
} else {
switch (q->fileMode()) {
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- case QFileDialog::DirectoryOnly:
-QT_WARNING_POP
case QFileDialog::Directory:
setLabelTextControl(QFileDialog::Accept, QFileDialog::tr("&Choose"));
break;
@@ -693,7 +666,7 @@ void QFileDialogPrivate::retranslateStrings()
if (proxyModel)
abstractModel = proxyModel;
#endif
- int total = qMin(abstractModel->columnCount(QModelIndex()), actions.count() + 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());
}
@@ -714,7 +687,7 @@ void QFileDialogPrivate::emitFilesSelected(const QStringList &files)
{
Q_Q(QFileDialog);
emit q->filesSelected(files);
- if (files.count() == 1)
+ if (files.size() == 1)
emit q->fileSelected(files.first());
}
@@ -731,9 +704,7 @@ bool QFileDialogPrivate::canBeNativeDialog() const
return false;
}
- QLatin1String staticName(QFileDialog::staticMetaObject.className());
- QLatin1String dynamicName(q->metaObject()->className());
- return (staticName == dynamicName);
+ return strcmp(QFileDialog::staticMetaObject.className(), q->metaObject()->className()) == 0;
}
bool QFileDialogPrivate::usingWidgets() const
@@ -746,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
@@ -781,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
@@ -808,8 +779,10 @@ void QFileDialog::setOptions(Options options)
d->options->setOptions(QFileDialogOptions::FileDialogOptions(int(options)));
- if ((options & DontUseNativeDialog) && !d->usingWidgets())
+ if (options & DontUseNativeDialog) {
+ d->nativeDialogInUse = false;
d->createWidgets();
+ }
if (d->usingWidgets()) {
if (changed & DontResolveSymlinks)
@@ -840,17 +813,24 @@ void QFileDialog::setOptions(Options options)
QFileDialog::Options QFileDialog::options() const
{
Q_D(const QFileDialog);
+ static_assert((int)QFileDialog::ShowDirsOnly == (int)QFileDialogOptions::ShowDirsOnly);
+ static_assert((int)QFileDialog::DontResolveSymlinks == (int)QFileDialogOptions::DontResolveSymlinks);
+ static_assert((int)QFileDialog::DontConfirmOverwrite == (int)QFileDialogOptions::DontConfirmOverwrite);
+ static_assert((int)QFileDialog::DontUseNativeDialog == (int)QFileDialogOptions::DontUseNativeDialog);
+ static_assert((int)QFileDialog::ReadOnly == (int)QFileDialogOptions::ReadOnly);
+ static_assert((int)QFileDialog::HideNameFilterDetails == (int)QFileDialogOptions::HideNameFilterDetails);
+ static_assert((int)QFileDialog::DontUseCustomDirectoryIcons == (int)QFileDialogOptions::DontUseCustomDirectoryIcons);
return QFileDialog::Options(int(d->options->options()));
}
/*!
\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)
{
@@ -871,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);
+}
- if (d->canBeNativeDialog()){
- if (d->setNativeDialogVisible(visible)){
- // Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
+/*!
+ \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 (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);
}
/*!
@@ -932,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
@@ -965,10 +952,10 @@ void QFileDialog::setDirectory(const QString &directory)
d->qFileDialogUi->newFolderButton->setEnabled(d->model->flags(root) & Qt::ItemIsDropEnabled);
if (root != d->rootIndex()) {
#if QT_CONFIG(fscompleter)
- if (directory.endsWith(QLatin1Char('/')))
+ if (directory.endsWith(u'/'))
d->completer->setCompletionPrefix(newDirectory);
else
- d->completer->setCompletionPrefix(newDirectory + QLatin1Char('/'));
+ d->completer->setCompletionPrefix(newDirectory + u'/');
#endif
d->setRootIndex(root);
}
@@ -1000,7 +987,7 @@ QDir QFileDialog::directory() const
by the CLSID value with the curly braces removed. For example the URL
\c clsid:374DE290-123F-4565-9164-39C4925E467B denotes the download
location. For a complete list of possible values, see the MSDN documentation on
- \l{https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx}{KNOWNFOLDERID}.
+ \l{https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid}{KNOWNFOLDERID}.
This feature was added in Qt 5.5.
\sa QUuid
@@ -1040,12 +1027,12 @@ QUrl QFileDialog::directoryUrl() const
// FIXME Qt 5.4: Use upcoming QVolumeInfo class to determine this information?
static inline bool isCaseSensitiveFileSystem(const QString &path)
{
- Q_UNUSED(path)
+ Q_UNUSED(path);
#if defined(Q_OS_WIN)
// Return case insensitive unconditionally, even if someone has a case sensitive
// file system mounted, wrongly capitalized drive letters will cause mismatches.
return false;
-#elif defined(Q_OS_OSX)
+#elif defined(Q_OS_MACOS)
return pathconf(QFile::encodeName(path).constData(), _PC_CASE_SENSITIVE);
#else
return true;
@@ -1067,7 +1054,7 @@ static inline QString fileFromPath(const QString &rootPath, QString path)
if (path.at(0) == QDir::separator()
#ifdef Q_OS_WIN
//On Windows both cases can happen
- || path.at(0) == QLatin1Char('/')
+ || path.at(0) == u'/'
#endif
) {
path.remove(0, 1);
@@ -1091,8 +1078,8 @@ void QFileDialog::selectFile(const QString &filename)
if (QFileInfo(filename).isRelative()) {
url = d->options->initialDirectory();
QString path = url.path();
- if (!path.endsWith(QLatin1Char('/')))
- path += QLatin1Char('/');
+ if (!path.endsWith(u'/'))
+ path += u'/';
url.setPath(path + filename);
} else {
url = QUrl::fromLocalFile(filename);
@@ -1139,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(QLatin1Char('~')))
+ if (!path.startsWith(u'~'))
return path;
- int separatorPosition = path.indexOf(QDir::separator());
- if (separatorPosition < 0)
- separatorPosition = path.size();
- if (separatorPosition == 1) {
- return QDir::homePath() + path.midRef(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 = path.midRef(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 + path.midRef(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
@@ -1187,7 +1189,7 @@ QStringList QFileDialogPrivate::typedFiles() const
Q_Q(const QFileDialog);
QStringList files;
QString editText = lineEdit()->text();
- if (!editText.contains(QLatin1Char('"'))) {
+ if (!editText.contains(u'"')) {
#ifdef Q_OS_UNIX
const QString prefix = q->directory().absolutePath() + QDir::separator();
if (QFile::exists(prefix + editText))
@@ -1196,12 +1198,12 @@ QStringList QFileDialogPrivate::typedFiles() const
files << qt_tildeExpansion(editText);
#else
files << editText;
- Q_UNUSED(q)
+ Q_UNUSED(q);
#endif
} else {
// " is used to separate files like so: "file1" "file2" "file3" ...
// ### need escape character for filenames with quotes (")
- QStringList tokens = editText.split(QLatin1Char('\"'));
+ QStringList tokens = editText.split(u'\"');
for (int i=0; i<tokens.size(); ++i) {
if ((i % 2) == 0)
continue; // Every even token is a separator
@@ -1253,8 +1255,9 @@ QStringList QFileDialogPrivate::addDefaultSuffixToFiles(const QStringList &files
QFileInfo info(name);
// if the filename has no suffix, add the default suffix
const QString defaultSuffix = options->defaultSuffix();
- if (!defaultSuffix.isEmpty() && !info.isDir() && name.lastIndexOf(QLatin1Char('.')) == -1)
- name += QLatin1Char('.') + defaultSuffix;
+ if (!defaultSuffix.isEmpty() && !info.isDir() && !info.fileName().contains(u'.'))
+ name += u'.' + defaultSuffix;
+
if (info.isAbsolute()) {
files.append(name);
} else {
@@ -1262,8 +1265,8 @@ QStringList QFileDialogPrivate::addDefaultSuffixToFiles(const QStringList &files
// This check is needed since we might be at the root directory
// and on Windows it already ends with slash.
QString path = rootPath();
- if (!path.endsWith(QLatin1Char('/')))
- path += QLatin1Char('/');
+ if (!path.endsWith(u'/'))
+ path += u'/';
path += name;
files.append(path);
}
@@ -1274,14 +1277,16 @@ 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();
- if (!defaultSuffix.isEmpty() && !url.path().endsWith(QLatin1Char('/')) && url.path().lastIndexOf(QLatin1Char('.')) == -1)
- url.setPath(url.path() + QLatin1Char('.') + 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'/');
+ if (idx != (urlPath.size() - 1) && !QStringView{urlPath}.mid(idx + 1).contains(u'.'))
+ url.setPath(urlPath + u'.' + defaultSuffix);
+ }
urls.append(url);
}
return urls;
@@ -1303,7 +1308,8 @@ QStringList QFileDialog::selectedFiles() const
const QList<QUrl> userSelectedFiles = d->userSelectedFiles();
files.reserve(userSelectedFiles.size());
for (const QUrl &file : userSelectedFiles)
- files.append(file.toLocalFile());
+ files.append(file.toString(QUrl::PreferLocalFile));
+
if (files.isEmpty() && d->usingWidgets()) {
const FileMode fm = fileMode();
if (fm != ExistingFile && fm != ExistingFiles)
@@ -1341,21 +1347,14 @@ QList<QUrl> QFileDialog::selectedUrls() const
*/
QStringList qt_make_filter_list(const QString &filter)
{
- QString f(filter);
-
- if (f.isEmpty())
+ if (filter.isEmpty())
return QStringList();
- QString sep(QLatin1String(";;"));
- int i = f.indexOf(sep, 0);
- if (i == -1) {
- if (f.indexOf(QLatin1Char('\n'), 0) != -1) {
- sep = QLatin1Char('\n');
- i = f.indexOf(sep, 0);
- }
- }
+ auto sep = ";;"_L1;
+ if (!filter.contains(sep) && filter.contains(u'\n'))
+ sep = "\n"_L1;
- return f.split(sep);
+ return filter.split(sep);
}
/*!
@@ -1370,6 +1369,9 @@ QStringList qt_make_filter_list(const QString &filter)
\snippet code/src_gui_dialogs_qfiledialog.cpp 6
+ \note With Android's native file dialog, the mime type matching the given
+ name filter is used because only mime types are supported.
+
\sa setMimeTypeFilters(), setNameFilters()
*/
void QFileDialog::setNameFilter(const QString &filter)
@@ -1378,48 +1380,26 @@ void QFileDialog::setNameFilter(const QString &filter)
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \property QFileDialog::nameFilterDetailsVisible
- \obsolete
- \brief This property holds whether the filter details is shown or not.
- \since 4.4
-
- When this property is \c true (the default), the filter details are shown
- in the combo box. When the property is set to false, these are hidden.
-
- Use setOption(HideNameFilterDetails, !\e enabled) or
- !testOption(HideNameFilterDetails).
-*/
-void QFileDialog::setNameFilterDetailsVisible(bool enabled)
-{
- setOption(HideNameFilterDetails, !enabled);
-}
-
-bool QFileDialog::isNameFilterDetailsVisible() const
-{
- return !testOption(HideNameFilterDetails);
-}
-#endif
-
-
/*
Strip the filters by removing the details, e.g. (*.*).
*/
QStringList qt_strip_filters(const QStringList &filters)
{
+#if QT_CONFIG(regularexpression)
QStringList strippedFilters;
- QRegExp r(QString::fromLatin1(QPlatformFileDialogHelper::filterRegExp));
- const int numFilters = filters.count();
- strippedFilters.reserve(numFilters);
- for (int i = 0; i < numFilters; ++i) {
+ static const QRegularExpression r(QString::fromLatin1(QPlatformFileDialogHelper::filterRegExp));
+ strippedFilters.reserve(filters.size());
+ for (const QString &filter : filters) {
QString filterName;
- int index = r.indexIn(filters[i]);
- if (index >= 0)
- filterName = r.cap(1);
+ auto match = r.match(filter);
+ if (match.hasMatch())
+ filterName = match.captured(1);
strippedFilters.append(filterName.simplified());
}
return strippedFilters;
+#else
+ return filters;
+#endif
}
@@ -1432,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.count();
- 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())
@@ -1465,7 +1444,7 @@ void QFileDialog::setNameFilters(const QStringList &filters)
else
d->qFileDialogUi->fileTypeCombo->addItems(cleanedFilters);
- d->_q_useNameFilter(0);
+ d->useNameFilter(0);
}
/*!
@@ -1505,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());
}
}
@@ -1572,8 +1551,8 @@ static QString nameFilterForMime(const QString &mimeType)
if (mime.isDefault()) {
return QFileDialog::tr("All files (*)");
} else {
- const QString patterns = mime.globPatterns().join(QLatin1Char(' '));
- return mime.comment() + QLatin1String(" (") + patterns + QLatin1Char(')');
+ const QString patterns = mime.globPatterns().join(u' ');
+ return mime.comment() + " ("_L1 + patterns + u')';
}
}
return QString();
@@ -1663,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;
@@ -1677,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.
@@ -1691,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
@@ -1706,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().
@@ -1723,13 +1702,6 @@ void QFileDialog::setFileMode(QFileDialog::FileMode mode)
{
Q_D(QFileDialog);
d->options->setFileMode(static_cast<QFileDialogOptions::FileMode>(mode));
-
- // keep ShowDirsOnly option in sync with fileMode (BTW, DirectoryOnly is obsolete)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- setOption(ShowDirsOnly, mode == DirectoryOnly);
-QT_WARNING_POP
-
if (!d->usingWidgets())
return;
@@ -1746,18 +1718,15 @@ QT_WARNING_POP
// set filter
d->model->setFilter(d->filterForMode(filter()));
// setup file type for directory
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- if (mode == DirectoryOnly || mode == Directory) {
+ if (mode == Directory) {
d->qFileDialogUi->fileTypeCombo->clear();
d->qFileDialogUi->fileTypeCombo->addItem(tr("Directories"));
d->qFileDialogUi->fileTypeCombo->setEnabled(false);
}
-QT_WARNING_POP
d->updateFileNameLabel();
d->updateOkButtonText();
d->qFileDialogUi->fileTypeCombo->setEnabled(!testOption(ShowDirsOnly));
- d->_q_updateOkButton();
+ d->updateOkButton();
}
QFileDialog::FileMode QFileDialog::fileMode() const
@@ -1768,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.
@@ -1787,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);
}
@@ -1796,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.
*/
@@ -1838,13 +1807,10 @@ 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);
-#elif defined(Q_OS_WINRT)
- Q_UNUSED(path);
- return MAX_PATH;
#elif defined(Q_OS_WIN)
DWORD maxLength;
const QString drive = path.left(3);
@@ -1886,74 +1852,12 @@ QFileDialog::AcceptMode QFileDialog::acceptMode() const
return static_cast<AcceptMode>(d->options->acceptMode());
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \property QFileDialog::readOnly
- \obsolete
- \brief Whether the filedialog is read-only
-
- If this property is set to false, the file dialog will allow renaming,
- and deleting of files and directories and creating directories.
-
- Use setOption(ReadOnly, \e enabled) or testOption(ReadOnly) instead.
-*/
-void QFileDialog::setReadOnly(bool enabled)
-{
- setOption(ReadOnly, enabled);
-}
-
-bool QFileDialog::isReadOnly() const
-{
- return testOption(ReadOnly);
-}
-
-/*!
- \property QFileDialog::resolveSymlinks
- \obsolete
- \brief whether the filedialog should resolve shortcuts
-
- If this property is set to true, the file dialog will resolve
- shortcuts or symbolic links.
-
- Use setOption(DontResolveSymlinks, !\a enabled) or
- !testOption(DontResolveSymlinks).
-*/
-void QFileDialog::setResolveSymlinks(bool enabled)
-{
- setOption(DontResolveSymlinks, !enabled);
-}
-
-bool QFileDialog::resolveSymlinks() const
-{
- return !testOption(DontResolveSymlinks);
-}
-
-/*!
- \property QFileDialog::confirmOverwrite
- \obsolete
- \brief whether the filedialog should ask before accepting a selected file,
- when the accept mode is AcceptSave
-
- Use setOption(DontConfirmOverwrite, !\e enabled) or
- !testOption(DontConfirmOverwrite) instead.
-*/
-void QFileDialog::setConfirmOverwrite(bool enabled)
-{
- setOption(DontConfirmOverwrite, !enabled);
-}
-
-bool QFileDialog::confirmOverwrite() const
-{
- return !testOption(DontConfirmOverwrite);
-}
-#endif
-
/*!
\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).
@@ -1987,9 +1891,11 @@ void QFileDialogComboBox::setHistory(const QStringList &paths)
m_history = paths;
// Only populate the first item, showPopup will populate the rest if needed
QList<QUrl> list;
- QModelIndex idx = d_ptr->model->index(d_ptr->rootPath());
+ const QModelIndex idx = d_ptr->model->index(d_ptr->rootPath());
//On windows the popup display the "C:\", convert to nativeSeparators
- QUrl url = QUrl::fromLocalFile(QDir::toNativeSeparators(idx.data(QFileSystemModel::FilePathRole).toString()));
+ const QUrl url = idx.isValid()
+ ? QUrl::fromLocalFile(QDir::toNativeSeparators(idx.data(QFileSystemModel::FilePathRole).toString()))
+ : QUrl("file:"_L1);
if (url.isValid())
list.append(url);
urlModel->setUrls(list);
@@ -2015,6 +1921,9 @@ QStringList QFileDialog::history() const
Sets the item delegate used to render items in the views in the
file dialog to the given \a delegate.
+ Any existing delegate will be removed, but not deleted. QFileDialog
+ does not take ownership of \a delegate.
+
\warning You should not share the same instance of a delegate between views.
Doing so can cause incorrect or unintuitive editing behavior since each
view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
@@ -2049,7 +1958,7 @@ QAbstractItemDelegate *QFileDialog::itemDelegate() const
/*!
Sets the icon provider used by the filedialog to the specified \a provider.
*/
-void QFileDialog::setIconProvider(QFileIconProvider *provider)
+void QFileDialog::setIconProvider(QAbstractFileIconProvider *provider)
{
Q_D(QFileDialog);
if (!d->usingWidgets())
@@ -2062,7 +1971,7 @@ void QFileDialog::setIconProvider(QFileIconProvider *provider)
/*!
Returns the icon provider used by the filedialog.
*/
-QFileIconProvider *QFileDialog::iconProvider() const
+QAbstractFileIconProvider *QFileDialog::iconProvider() const
{
Q_D(const QFileDialog);
if (!d->model)
@@ -2151,40 +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
- native file dialog and not a QFileDialog.
+ 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()
@@ -2197,8 +2107,12 @@ QString QFileDialog::getOpenFileName(QWidget *parent,
Options options)
{
const QStringList schemes = QStringList(QStringLiteral("file"));
- const QUrl selectedUrl = getOpenFileUrl(parent, caption, QUrl::fromLocalFile(dir), filter, selectedFilter, options, schemes);
- return selectedUrl.toLocalFile();
+ const QUrl selectedUrl = getOpenFileUrl(parent, caption, QUrl::fromLocalFile(dir), filter,
+ selectedFilter, options, schemes);
+ if (selectedUrl.isLocalFile() || selectedUrl.isEmpty())
+ return selectedUrl.toLocalFile();
+ else
+ return selectedUrl.toString();
}
/*!
@@ -2208,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()
@@ -2236,11 +2150,9 @@ QUrl QFileDialog::getOpenFileUrl(QWidget *parent,
Options options,
const QStringList &supportedSchemes)
{
- QFileDialogArgs args;
+ QFileDialogArgs args(dir);
args.parent = parent;
args.caption = caption;
- args.directory = QFileDialogPrivate::workingDirectory(dir);
- args.selection = QFileDialogPrivate::initialSelection(dir);
args.filter = filter;
args.mode = ExistingFile;
args.options = options;
@@ -2258,32 +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
- native file dialog and not a QFileDialog.
+ 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
@@ -2294,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()
@@ -2307,22 +2220,23 @@ QStringList QFileDialog::getOpenFileNames(QWidget *parent,
Options options)
{
const QStringList schemes = QStringList(QStringLiteral("file"));
- const QList<QUrl> selectedUrls = getOpenFileUrls(parent, caption, QUrl::fromLocalFile(dir), filter, selectedFilter, options, schemes);
+ const QList<QUrl> selectedUrls = getOpenFileUrls(parent, caption, QUrl::fromLocalFile(dir),
+ filter, selectedFilter, options, schemes);
QStringList fileNames;
fileNames.reserve(selectedUrls.size());
for (const QUrl &url : selectedUrls)
- fileNames << url.toLocalFile();
+ fileNames.append(url.toString(QUrl::PreferLocalFile));
return fileNames;
}
/*!
- 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
@@ -2330,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()
@@ -2351,11 +2265,9 @@ QList<QUrl> QFileDialog::getOpenFileUrls(QWidget *parent,
Options options,
const QStringList &supportedSchemes)
{
- QFileDialogArgs args;
+ QFileDialogArgs args(dir);
args.parent = parent;
args.caption = caption;
- args.directory = QFileDialogPrivate::workingDirectory(dir);
- args.selection = QFileDialogPrivate::initialSelection(dir);
args.filter = filter;
args.mode = ExistingFiles;
args.options = options;
@@ -2373,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
@@ -2390,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;
@@ -2417,37 +2331,27 @@ void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::funct
openFileImpl.reset();
};
- auto qtFilterStringToWebAcceptString = [](const QString &qtString) {
- // The Qt and Web name filter string formats are similar, but
- // not identical.
- return qtString.toStdString(); // ### TODO
- };
-
- QWasmLocalFileAccess::openFile(qtFilterStringToWebAcceptString(nameFilter), fileDialogClosed, acceptFile, fileContentReady);
+ QWasmLocalFileAccess::openFile(nameFilter.toStdString(), fileDialogClosed, acceptFile, fileContentReady);
};
(*openFileImpl)();
#else
- QFileDialog *dialog = new QFileDialog();
- dialog->selectNameFilter(nameFilter);
+ QFileDialog *dialog = new QFileDialog(parent);
+ dialog->setFileMode(QFileDialog::ExistingFile);
+ dialog->setNameFilter(nameFilter);
+ dialog->setAttribute(Qt::WA_DeleteOnClose);
auto fileSelected = [=](const QString &fileName) {
QByteArray fileContent;
if (!fileName.isNull()) {
QFile selectedFile(fileName);
- selectedFile.open(QIODevice::ReadOnly);
- fileContent = selectedFile.readAll();
+ if (selectedFile.open(QIODevice::ReadOnly))
+ fileContent = selectedFile.readAll();
}
fileOpenCompleted(fileName, fileContent);
};
- auto dialogClosed = [=](int code) {
- Q_UNUSED(code);
- delete dialog;
- };
-
- connect(dialog, &QFileDialog::fileSelected, fileSelected);
- connect(dialog, &QFileDialog::finished, dialogClosed);
+ connect(dialog, &QFileDialog::fileSelected, dialog, fileSelected);
dialog->show();
#endif
}
@@ -2457,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
- QWasmLocalFileAccess::saveFile(fileContent.constData(), fileContent.size(), fileNameHint.toStdString());
+ 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);
@@ -2486,19 +2393,14 @@ void QFileDialog::saveFileContent(const QByteArray &fileContent, const QString &
}
};
- auto dialogClosed = [=](int code) {
- Q_UNUSED(code);
- delete dialog;
- };
-
- 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
@@ -2507,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:
@@ -2523,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()
@@ -2553,8 +2455,12 @@ QString QFileDialog::getSaveFileName(QWidget *parent,
Options options)
{
const QStringList schemes = QStringList(QStringLiteral("file"));
- const QUrl selectedUrl = getSaveFileUrl(parent, caption, QUrl::fromLocalFile(dir), filter, selectedFilter, options, schemes);
- return selectedUrl.toLocalFile();
+ const QUrl selectedUrl = getSaveFileUrl(parent, caption, QUrl::fromLocalFile(dir), filter,
+ selectedFilter, options, schemes);
+ if (selectedUrl.isLocalFile() || selectedUrl.isEmpty())
+ return selectedUrl.toLocalFile();
+ else
+ return selectedUrl.toString();
}
/*!
@@ -2564,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()
@@ -2592,11 +2498,9 @@ QUrl QFileDialog::getSaveFileUrl(QWidget *parent,
Options options,
const QStringList &supportedSchemes)
{
- QFileDialogArgs args;
+ QFileDialogArgs args(dir);
args.parent = parent;
args.caption = caption;
- args.directory = QFileDialogPrivate::workingDirectory(dir);
- args.selection = QFileDialogPrivate::initialSelection(dir);
args.filter = filter;
args.mode = AnyFile;
args.options = options;
@@ -2615,42 +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()
@@ -2661,33 +2568,37 @@ QString QFileDialog::getExistingDirectory(QWidget *parent,
Options options)
{
const QStringList schemes = QStringList(QStringLiteral("file"));
- const QUrl selectedUrl = getExistingDirectoryUrl(parent, caption, QUrl::fromLocalFile(dir), options, schemes);
- return selectedUrl.toLocalFile();
+ const QUrl selectedUrl =
+ getExistingDirectoryUrl(parent, caption, QUrl::fromLocalFile(dir), options, schemes);
+ if (selectedUrl.isLocalFile() || selectedUrl.isEmpty())
+ return selectedUrl.toLocalFile();
+ else
+ return selectedUrl.toString();
}
/*!
- 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
@@ -2698,14 +2609,10 @@ QUrl QFileDialog::getExistingDirectoryUrl(QWidget *parent,
Options options,
const QStringList &supportedSchemes)
{
- QFileDialogArgs args;
+ QFileDialogArgs args(dir);
args.parent = parent;
args.caption = caption;
- args.directory = QFileDialogPrivate::workingDirectory(dir);
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- args.mode = (options & ShowDirsOnly ? DirectoryOnly : Directory);
-QT_WARNING_POP
+ args.mode = Directory;
args.options = options;
QFileDialog dialog(args);
@@ -2715,58 +2622,54 @@ QT_WARNING_POP
return QUrl();
}
-inline static QUrl _qt_get_directory(const QUrl &url)
+inline static QUrl _qt_get_directory(const QUrl &url, const QFileInfo &local)
{
if (url.isLocalFile()) {
- QFileInfo info = QFileInfo(QDir::current(), url.toLocalFile());
+ QFileInfo info = local;
+ if (!local.isAbsolute())
+ info = QFileInfo(QDir::current(), url.toLocalFile());
+ const QFileInfo pathInfo(info.absolutePath());
+ if (!pathInfo.exists() || !pathInfo.isDir())
+ return QUrl();
if (info.exists() && info.isDir())
return QUrl::fromLocalFile(QDir::cleanPath(info.absoluteFilePath()));
- info.setFile(info.absolutePath());
- if (info.exists() && info.isDir())
- return QUrl::fromLocalFile(info.absoluteFilePath());
- return QUrl();
+ return QUrl::fromLocalFile(pathInfo.absoluteFilePath());
} else {
return url;
}
}
-/*
- Get the initial directory URL
-
- \sa initialSelection()
- */
-QUrl QFileDialogPrivate::workingDirectory(const QUrl &url)
-{
- if (!url.isEmpty()) {
- QUrl directory = _qt_get_directory(url);
- if (!directory.isEmpty())
- return directory;
- }
- QUrl directory = _qt_get_directory(*lastVisitedDir());
- if (!directory.isEmpty())
- return directory;
- return QUrl::fromLocalFile(QDir::currentPath());
-}
/*
- Get the initial selection given a path. The initial directory
- can contain both the initial directory and initial selection
- /home/user/foo.txt
-
- \sa workingDirectory()
- */
-QString QFileDialogPrivate::initialSelection(const QUrl &url)
-{
- if (url.isEmpty())
- return QString();
- if (url.isLocalFile()) {
- QFileInfo info(url.toLocalFile());
- if (!info.isDir())
- return info.fileName();
- else
- return QString();
+ Initialize working directory and selection from \a url.
+*/
+QFileDialogArgs::QFileDialogArgs(const QUrl &url)
+{
+ // default case, re-use QFileInfo to avoid stat'ing
+ const QFileInfo local(url.toLocalFile());
+ // Get the initial directory URL
+ if (!url.isEmpty())
+ directory = _qt_get_directory(url, local);
+ if (directory.isEmpty()) {
+ const QUrl lastVisited = *lastVisitedDir();
+ if (lastVisited != url)
+ directory = _qt_get_directory(lastVisited, QFileInfo());
+ }
+ if (directory.isEmpty())
+ directory = QUrl::fromLocalFile(QDir::currentPath());
+
+ /*
+ The initial directory can contain both the initial directory
+ and initial selection, e.g. /home/user/foo.txt
+ */
+ if (selection.isEmpty() && !url.isEmpty()) {
+ if (url.isLocalFile()) {
+ if (!local.isDir())
+ selection = local.fileName();
+ } else {
+ // With remote URLs we can only assume.
+ selection = url.fileName();
+ }
}
- // With remote URLs we can only assume.
- return url.fileName();
}
/*!
@@ -2787,6 +2690,32 @@ void QFileDialog::done(int result)
d->signalToDisconnectOnClose.clear();
}
+bool QFileDialogPrivate::itemAlreadyExists(const QString &fileName)
+{
+#if QT_CONFIG(messagebox)
+ Q_Q(QFileDialog);
+ const QString msg = QFileDialog::tr("%1 already exists.\nDo you want to replace it?").arg(fileName);
+ using B = QMessageBox;
+ const auto res = B::warning(q, q->windowTitle(), msg, B::Yes | B::No, B::No);
+ return res == B::Yes;
+#endif
+ return false;
+}
+
+void QFileDialogPrivate::itemNotFound(const QString &fileName, QFileDialog::FileMode mode)
+{
+#if QT_CONFIG(messagebox)
+ Q_Q(QFileDialog);
+ const QString message = mode == QFileDialog::Directory
+ ? QFileDialog::tr("%1\nDirectory not found.\n"
+ "Please verify the correct directory name was given.")
+ : QFileDialog::tr("%1\nFile not found.\nPlease verify the "
+ "correct file name was given.");
+
+ QMessageBox::warning(q, q->windowTitle(), message.arg(fileName));
+#endif // QT_CONFIG(messagebox)
+}
+
/*!
\reimp
*/
@@ -2797,9 +2726,9 @@ void QFileDialog::accept()
const QList<QUrl> urls = selectedUrls();
if (urls.isEmpty())
return;
- d->_q_emitUrlsSelected(urls);
- if (urls.count() == 1)
- d->_q_emitUrlSelected(urls.first());
+ d->emitUrlsSelected(urls);
+ if (urls.size() == 1)
+ d->emitUrlSelected(urls.first());
QDialog::accept();
return;
}
@@ -2810,29 +2739,22 @@ void QFileDialog::accept()
QString lineEditText = d->lineEdit()->text();
// "hidden feature" type .. and then enter, and it will move up a dir
// special case for ".."
- if (lineEditText == QLatin1String("..")) {
- d->_q_navigateToParent();
+ if (lineEditText == ".."_L1) {
+ d->navigateToParent();
const QSignalBlocker blocker(d->qFileDialogUi->fileNameEdit);
d->lineEdit()->selectAll();
return;
}
- switch (fileMode()) {
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- case DirectoryOnly:
-QT_WARNING_POP
+ const auto mode = fileMode();
+ switch (mode) {
case Directory: {
QString fn = files.first();
QFileInfo info(fn);
if (!info.exists())
info = QFileInfo(d->getEnvironmentVariable(fn));
if (!info.exists()) {
-#if QT_CONFIG(messagebox)
- QString message = tr("%1\nDirectory not found.\nPlease verify the "
- "correct directory name was given.");
- QMessageBox::warning(this, windowTitle(), message.arg(info.fileName()));
-#endif // QT_CONFIG(messagebox)
+ d->itemNotFound(info.fileName(), mode);
return;
}
if (info.isDir()) {
@@ -2851,8 +2773,8 @@ QT_WARNING_POP
}
if (!info.exists()) {
- int maxNameLength = d->maxNameLength(info.path());
- if (maxNameLength >= 0 && info.fileName().length() > maxNameLength)
+ const long maxNameLength = d->maxNameLength(info.path());
+ if (maxNameLength >= 0 && info.fileName().size() > maxNameLength)
return;
}
@@ -2860,17 +2782,11 @@ QT_WARNING_POP
if (!info.exists() || testOption(DontConfirmOverwrite) || acceptMode() == AcceptOpen) {
d->emitFilesSelected(QStringList(fn));
QDialog::accept();
-#if QT_CONFIG(messagebox)
} else {
- if (QMessageBox::warning(this, windowTitle(),
- tr("%1 already exists.\nDo you want to replace it?")
- .arg(info.fileName()),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
- == QMessageBox::Yes) {
+ if (d->itemAlreadyExists(info.fileName())) {
d->emitFilesSelected(QStringList(fn));
QDialog::accept();
}
-#endif
}
return;
}
@@ -2882,11 +2798,7 @@ QT_WARNING_POP
if (!info.exists())
info = QFileInfo(d->getEnvironmentVariable(file));
if (!info.exists()) {
-#if QT_CONFIG(messagebox)
- QString message = tr("%1\nFile not found.\nPlease verify the "
- "correct file name was given.");
- QMessageBox::warning(this, windowTitle(), message.arg(info.fileName()));
-#endif // QT_CONFIG(messagebox)
+ d->itemNotFound(info.fileName(), mode);
return;
}
if (info.isDir()) {
@@ -2905,37 +2817,37 @@ QT_WARNING_POP
void QFileDialogPrivate::saveSettings()
{
Q_Q(QFileDialog);
- QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
- settings.beginGroup(QLatin1String("FileDialog"));
+ QSettings settings(QSettings::UserScope, u"QtProject"_s);
+ settings.beginGroup("FileDialog");
if (usingWidgets()) {
- settings.setValue(QLatin1String("sidebarWidth"), qFileDialogUi->splitter->sizes().constFirst());
- settings.setValue(QLatin1String("shortcuts"), QUrl::toStringList(qFileDialogUi->sidebar->urls()));
- settings.setValue(QLatin1String("treeViewHeader"), qFileDialogUi->treeView->header()->saveState());
+ settings.setValue("sidebarWidth", qFileDialogUi->splitter->sizes().constFirst());
+ settings.setValue("shortcuts", QUrl::toStringList(qFileDialogUi->sidebar->urls()));
+ settings.setValue("treeViewHeader", qFileDialogUi->treeView->header()->saveState());
}
QStringList historyUrls;
const QStringList history = q->history();
historyUrls.reserve(history.size());
for (const QString &path : history)
historyUrls << QUrl::fromLocalFile(path).toString();
- settings.setValue(QLatin1String("history"), historyUrls);
- settings.setValue(QLatin1String("lastVisited"), lastVisitedDir()->toString());
+ settings.setValue("history", historyUrls);
+ settings.setValue("lastVisited", lastVisitedDir()->toString());
const QMetaEnum &viewModeMeta = q->metaObject()->enumerator(q->metaObject()->indexOfEnumerator("ViewMode"));
- settings.setValue(QLatin1String("viewMode"), QLatin1String(viewModeMeta.key(q->viewMode())));
- settings.setValue(QLatin1String("qtVersion"), QLatin1String(QT_VERSION_STR));
+ settings.setValue("viewMode", QLatin1StringView(viewModeMeta.key(q->viewMode())));
+ settings.setValue("qtVersion", QT_VERSION_STR ""_L1);
}
bool QFileDialogPrivate::restoreFromSettings()
{
Q_Q(QFileDialog);
- QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
- if (!settings.childGroups().contains(QLatin1String("FileDialog")))
+ QSettings settings(QSettings::UserScope, u"QtProject"_s);
+ if (!settings.childGroups().contains("FileDialog"_L1))
return false;
- settings.beginGroup(QLatin1String("FileDialog"));
+ settings.beginGroup("FileDialog");
- q->setDirectoryUrl(lastVisitedDir()->isEmpty() ? settings.value(QLatin1String("lastVisited")).toUrl() : *lastVisitedDir());
+ q->setDirectoryUrl(lastVisitedDir()->isEmpty() ? settings.value("lastVisited").toUrl() : *lastVisitedDir());
- QByteArray viewModeStr = settings.value(QLatin1String("viewMode")).toString().toLatin1();
+ QByteArray viewModeStr = settings.value("viewMode").toString().toLatin1();
const QMetaEnum &viewModeMeta = q->metaObject()->enumerator(q->metaObject()->indexOfEnumerator("ViewMode"));
bool ok = false;
int viewMode = viewModeMeta.keyToValue(viewModeStr.constData(), &ok);
@@ -2943,21 +2855,21 @@ bool QFileDialogPrivate::restoreFromSettings()
viewMode = QFileDialog::List;
q->setViewMode(static_cast<QFileDialog::ViewMode>(viewMode));
- sidebarUrls = QUrl::fromStringList(settings.value(QLatin1String("shortcuts")).toStringList());
- headerData = settings.value(QLatin1String("treeViewHeader")).toByteArray();
+ sidebarUrls = QUrl::fromStringList(settings.value("shortcuts").toStringList());
+ headerData = settings.value("treeViewHeader").toByteArray();
if (!usingWidgets())
return true;
QStringList history;
- const auto urlStrings = settings.value(QLatin1String("history")).toStringList();
+ const auto urlStrings = settings.value("history").toStringList();
for (const QString &urlStr : urlStrings) {
QUrl url(urlStr);
if (url.isLocalFile())
history << url.toLocalFile();
}
- return restoreWidgetState(history, settings.value(QLatin1String("sidebarWidth"), -1).toInt());
+ return restoreWidgetState(history, settings.value("sidebarWidth", -1).toInt());
}
#endif // settings
@@ -2973,8 +2885,8 @@ bool QFileDialogPrivate::restoreWidgetState(QStringList &history, int splitterPo
if (!qFileDialogUi->splitter->restoreState(splitterState))
return false;
QList<int> list = qFileDialogUi->splitter->sizes();
- if (list.count() >= 2 && (list.at(0) == 0 || list.at(1) == 0)) {
- for (int i = 0; i < list.count(); ++i)
+ if (list.size() >= 2 && (list.at(0) == 0 || list.at(1) == 0)) {
+ for (int i = 0; i < list.size(); ++i)
list[i] = qFileDialogUi->splitter->widget(i)->sizeHint().width();
qFileDialogUi->splitter->setSizes(list);
}
@@ -2997,7 +2909,7 @@ bool QFileDialogPrivate::restoreWidgetState(QStringList &history, int splitterPo
if (proxyModel)
abstractModel = proxyModel;
#endif
- int total = qMin(abstractModel->columnCount(QModelIndex()), actions.count() + 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));
@@ -3009,14 +2921,13 @@ bool QFileDialogPrivate::restoreWidgetState(QStringList &history, int splitterPo
Create widgets, layout and set default values
*/
-void QFileDialogPrivate::init(const QUrl &directory, const QString &nameFilter,
- const QString &caption)
+void QFileDialogPrivate::init(const QFileDialogArgs &args)
{
Q_Q(QFileDialog);
- if (!caption.isEmpty()) {
+ if (!args.caption.isEmpty()) {
useDefaultCaption = false;
- setWindowTitle = caption;
- q->setWindowTitle(caption);
+ setWindowTitle = args.caption;
+ q->setWindowTitle(args.caption);
}
q->setAcceptMode(QFileDialog::AcceptOpen);
@@ -3024,24 +2935,24 @@ void QFileDialogPrivate::init(const QUrl &directory, const QString &nameFilter,
if (!nativeDialogInUse)
createWidgets();
q->setFileMode(QFileDialog::AnyFile);
- if (!nameFilter.isEmpty())
- q->setNameFilter(nameFilter);
+ if (!args.filter.isEmpty())
+ q->setNameFilter(args.filter);
// QTBUG-70798, prevent the default blocking the restore logic.
- const bool dontStoreDir = !directory.isValid() && !lastVisitedDir()->isValid();
- q->setDirectoryUrl(workingDirectory(directory));
+ const bool dontStoreDir = !args.directory.isValid() && !lastVisitedDir()->isValid();
+ q->setDirectoryUrl(args.directory);
if (dontStoreDir)
lastVisitedDir()->clear();
- if (directory.isLocalFile())
- q->selectFile(initialSelection(directory));
+ if (args.directory.isLocalFile())
+ q->selectFile(args.selection);
else
- q->selectUrl(directory);
+ q->selectUrl(args.directory);
#if QT_CONFIG(settings)
// Try to restore from the FileDialog settings group; if it fails, fall back
// to the pre-5.5 QByteArray serialized settings.
if (!restoreFromSettings()) {
- const QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
- q->restoreState(settings.value(QLatin1String("Qt/filedialog")).toByteArray());
+ const QSettings settings(QSettings::UserScope, u"QtProject"_s);
+ q->restoreState(settings.value("Qt/filedialog").toByteArray());
}
#endif
@@ -3075,37 +2986,40 @@ void QFileDialogPrivate::createWidgets()
Qt::WindowStates preState = q->windowState();
model = new QFileSystemModel(q);
+ model->setIconProvider(&defaultIconProvider);
model->setFilter(options->filter());
- model->setObjectName(QLatin1String("qt_filesystem_model"));
+ model->setObjectName("qt_filesystem_model"_L1);
if (QPlatformFileDialogHelper *helper = platformFileDialogHelper())
model->setNameFilterDisables(helper->defaultNameFilterDisables());
else
model->setNameFilterDisables(false);
- if (nativeDialogInUse)
- deletePlatformHelper();
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());
qFileDialogUi->setupUi(q);
QList<QUrl> initialBookmarks;
- initialBookmarks << QUrl(QLatin1String("file:"))
+ 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(activated(QString)), q, SLOT(_q_goToDirectory(QString)));
+ QObjectPrivate::connect(qFileDialogUi->lookInCombo, &QComboBox::textActivated,
+ this, &QFileDialogPrivate::goToDirectory);
qFileDialogUi->lookInCombo->setInsertPolicy(QComboBox::NoInsert);
qFileDialogUi->lookInCombo->setDuplicatesEnabled(false);
@@ -3122,48 +3036,48 @@ 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::AdjustToMinimumContentsLength);
+ 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(activated(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(qFileDialogUi->listView);
- shortcut->setKey(QKeySequence(QLatin1String("Delete")));
- QObject::connect(shortcut, SIGNAL(activated()), q, SLOT(_q_deleteCurrent()));
+ QShortcut *shortcut = new QShortcut(QKeySequence::Delete, qFileDialogUi->listView);
+ QObjectPrivate::connect(shortcut, &QShortcut::activated,
+ this, &QFileDialogPrivate::deleteCurrent);
#endif
qFileDialogUi->treeView->setFileDialogPrivate(this);
qFileDialogUi->treeView->setModel(model);
QHeaderView *treeHeader = qFileDialogUi->treeView->header();
QFontMetrics fm(q->font());
- treeHeader->resizeSection(0, fm.horizontalAdvance(QLatin1String("wwwwwwwwwwwwwwwwwwwwwwwwww")));
- treeHeader->resizeSection(1, fm.horizontalAdvance(QLatin1String("128.88 GB")));
- treeHeader->resizeSection(2, fm.horizontalAdvance(QLatin1String("mp3Folder")));
- treeHeader->resizeSection(3, fm.horizontalAdvance(QLatin1String("10/29/81 02:02PM")));
+ treeHeader->resizeSection(0, fm.horizontalAdvance("wwwwwwwwwwwwwwwwwwwwwwwwww"_L1));
+ treeHeader->resizeSection(1, fm.horizontalAdvance("128.88 GB"_L1));
+ treeHeader->resizeSection(2, fm.horizontalAdvance("mp3Folder"_L1));
+ treeHeader->resizeSection(3, fm.horizontalAdvance("10/29/81 02:02PM"_L1));
treeHeader->setContextMenuPolicy(Qt::ActionsContextMenu);
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)
@@ -3180,22 +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(qFileDialogUi->treeView);
- shortcut->setKey(QKeySequence(QLatin1String("Delete")));
- QObject::connect(shortcut, SIGNAL(activated()), q, SLOT(_q_deleteCurrent()));
+ shortcut = new QShortcut(QKeySequence::Delete, qFileDialogUi->treeView);
+ 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();
@@ -3205,8 +3119,8 @@ void QFileDialogPrivate::createWidgets()
// Try to restore from the FileDialog settings group; if it fails, fall back
// to the pre-5.5 QByteArray serialized settings.
if (!restoreFromSettings()) {
- const QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
- q->restoreState(settings.value(QLatin1String("Qt/filedialog")).toByteArray());
+ const QSettings settings(QSettings::UserScope, u"QtProject"_s);
+ q->restoreState(settings.value("Qt/filedialog").toByteArray());
}
#endif
@@ -3234,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)
@@ -3255,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()
*/
@@ -3270,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);
@@ -3288,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);
@@ -3299,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());
@@ -3309,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);
}
/*!
@@ -3338,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);
@@ -3370,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);
}
/*!
@@ -3384,42 +3304,48 @@ void QFileDialogPrivate::createMenuActions()
QAction *goHomeAction = new QAction(q);
#ifndef QT_NO_SHORTCUT
- goHomeAction->setShortcut(Qt::CTRL + Qt::Key_H + Qt::SHIFT);
+ 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
QAction *goToParent = new QAction(q);
- goToParent->setObjectName(QLatin1String("qt_goto_parent_action"));
+ goToParent->setObjectName("qt_goto_parent_action"_L1);
#ifndef QT_NO_SHORTCUT
- goToParent->setShortcut(Qt::CTRL + Qt::UpArrow);
+ 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(QLatin1String("qt_rename_action"));
- QObject::connect(renameAction, SIGNAL(triggered()), q, SLOT(_q_renameCurrent()));
+ renameAction->setObjectName("qt_rename_action"_L1);
+ QObjectPrivate::connect(renameAction, &QAction::triggered,
+ this, &QFileDialogPrivate::renameCurrent);
deleteAction = new QAction(q);
deleteAction->setEnabled(false);
- deleteAction->setObjectName(QLatin1String("qt_delete_action"));
- QObject::connect(deleteAction, SIGNAL(triggered()), q, SLOT(_q_deleteCurrent()));
+ deleteAction->setObjectName("qt_delete_action"_L1);
+ QObjectPrivate::connect(deleteAction, &QAction::triggered,
+ this, &QFileDialogPrivate::deleteCurrent);
showHiddenAction = new QAction(q);
- showHiddenAction->setObjectName(QLatin1String("qt_show_hidden_action"));
+ 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(QLatin1String("qt_new_folder_action"));
- QObject::connect(newFolderAction, SIGNAL(triggered()), q, SLOT(_q_createDirectory()));
+ newFolderAction->setObjectName("qt_new_folder_action"_L1);
+ QObjectPrivate::connect(newFolderAction, &QAction::triggered,
+ this, &QFileDialogPrivate::createDirectory);
}
-void QFileDialogPrivate::_q_goHome()
+void QFileDialogPrivate::goHome()
{
Q_Q(QFileDialog);
q->setDirectory(QDir::homePath());
@@ -3442,11 +3368,10 @@ 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);
- QDir dir(model->rootDirectory());
- qFileDialogUi->toParentButton->setEnabled(dir.exists());
+ qFileDialogUi->toParentButton->setEnabled(QFileInfo::exists(model->rootPath()));
qFileDialogUi->sidebar->selectUrl(QUrl::fromLocalFile(newPath));
q->setHistory(qFileDialogUi->lookInCombo->history());
@@ -3456,7 +3381,7 @@ void QFileDialogPrivate::_q_pathChanged(const QString &newPath)
if (currentHistoryLocation < 0 || currentHistory.value(currentHistoryLocation).path != newNativePath) {
if (currentHistoryLocation >= 0)
saveHistorySelection();
- while (currentHistoryLocation >= 0 && currentHistoryLocation + 1 < currentHistory.count()) {
+ while (currentHistoryLocation >= 0 && currentHistoryLocation + 1 < currentHistory.size()) {
currentHistory.removeLast();
}
currentHistory.append({newNativePath, PersistentModelIndexList()});
@@ -3487,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());
}
@@ -3498,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();
@@ -3511,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();
@@ -3525,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());
@@ -3545,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();
@@ -3572,7 +3499,7 @@ void QFileDialogPrivate::_q_createDirectory()
}
}
-void QFileDialogPrivate::_q_showListView()
+void QFileDialogPrivate::showListView()
{
qFileDialogUi->listModeButton->setDown(true);
qFileDialogUi->detailModeButton->setDown(false);
@@ -3582,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);
@@ -3597,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);
@@ -3611,30 +3538,33 @@ void QFileDialogPrivate::_q_showContextMenu(const QPoint &position)
QModelIndex index = view->indexAt(position);
index = mapToSource(index.sibling(index.row(), 0));
- QMenu menu(view);
+ QMenu *menu = new QMenu(view);
+ menu->setAttribute(Qt::WA_DeleteOnClose);
+
if (index.isValid()) {
// file context menu
const bool ro = model && model->isReadOnly();
QFile::Permissions p(index.parent().data(QFileSystemModel::FilePermissions).toInt());
renameAction->setEnabled(!ro && p & QFile::WriteUser);
- menu.addAction(renameAction);
+ menu->addAction(renameAction);
deleteAction->setEnabled(!ro && p & QFile::WriteUser);
- menu.addAction(deleteAction);
- menu.addSeparator();
+ menu->addAction(deleteAction);
+ menu->addSeparator();
}
- menu.addAction(showHiddenAction);
+ menu->addAction(showHiddenAction);
if (qFileDialogUi->newFolderButton->isVisible()) {
newFolderAction->setEnabled(qFileDialogUi->newFolderButton->isEnabled());
- menu.addAction(newFolderAction);
+ menu->addAction(newFolderAction);
}
- menu.exec(view->viewport()->mapToGlobal(position));
+ menu->popup(view->viewport()->mapToGlobal(position));
+
#endif // QT_CONFIG(menu)
}
/*!
\internal
*/
-void QFileDialogPrivate::_q_renameCurrent()
+void QFileDialogPrivate::renameCurrent()
{
Q_Q(QFileDialog);
QModelIndex index = qFileDialogUi->listView->currentIndex();
@@ -3656,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.count() - 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;
@@ -3710,27 +3640,27 @@ void QFileDialogPrivate::_q_deleteCurrent()
}
}
-void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text)
+void QFileDialogPrivate::autoCompleteFileName(const QString &text)
{
- if (text.startsWith(QLatin1String("//")) || text.startsWith(QLatin1Char('\\'))) {
+ if (text.startsWith("//"_L1) || text.startsWith(u'\\')) {
qFileDialogUi->listView->selectionModel()->clearSelection();
return;
}
const QStringList multipleFiles = typedFiles();
- if (multipleFiles.count() > 0) {
+ if (multipleFiles.size() > 0) {
QModelIndexList oldFiles = qFileDialogUi->listView->selectionModel()->selectedRows();
- QVector<QModelIndex> newFiles;
+ QList<QModelIndex> newFiles;
for (const auto &file : multipleFiles) {
QModelIndex idx = model->index(file);
if (oldFiles.removeAll(idx) == 0)
newFiles.append(idx);
}
- for (const auto &newFile : qAsConst(newFiles))
+ for (const auto &newFile : std::as_const(newFiles))
select(newFile);
if (lineEdit()->hasFocus()) {
auto *sm = qFileDialogUi->listView->selectionModel();
- for (const auto &oldFile : qAsConst(oldFiles))
+ for (const auto &oldFile : std::as_const(oldFiles))
sm->select(oldFile, QItemSelectionModel::Toggle | QItemSelectionModel::Rows);
}
}
@@ -3739,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)
@@ -3754,7 +3684,7 @@ void QFileDialogPrivate::_q_updateOkButton()
const QStringList files = q->selectedFiles();
QString lineEditText = lineEdit()->text();
- if (lineEditText.startsWith(QLatin1String("//")) || lineEditText.startsWith(QLatin1Char('\\'))) {
+ if (lineEditText.startsWith("//"_L1) || lineEditText.startsWith(u'\\')) {
button->setEnabled(true);
updateOkButtonText();
return;
@@ -3762,14 +3692,10 @@ void QFileDialogPrivate::_q_updateOkButton()
if (files.isEmpty()) {
enableButton = false;
- } else if (lineEditText == QLatin1String("..")) {
+ } else if (lineEditText == ".."_L1) {
isOpenDirectory = true;
} else {
switch (fileMode) {
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- case QFileDialog::DirectoryOnly:
-QT_WARNING_POP
case QFileDialog::Directory: {
QString fn = files.first();
QModelIndex idx = model->index(fn);
@@ -3788,10 +3714,10 @@ QT_WARNING_POP
if (info.isDir()) {
fileDir = info.canonicalFilePath();
} else {
- fileDir = fn.mid(0, fn.lastIndexOf(QLatin1Char('/')));
- fileName = fn.mid(fileDir.length() + 1);
+ fileDir = fn.mid(0, fn.lastIndexOf(u'/'));
+ fileName = fn.mid(fileDir.size() + 1);
}
- if (lineEditText.contains(QLatin1String(".."))) {
+ if (lineEditText.contains(".."_L1)) {
fileDir = info.canonicalFilePath();
fileName = info.fileName();
}
@@ -3806,8 +3732,8 @@ QT_WARNING_POP
break;
}
if (!idx.isValid()) {
- int maxLength = maxNameLength(fileDir);
- enableButton = maxLength < 0 || fileName.length() <= maxLength;
+ const long maxLength = maxNameLength(fileDir);
+ enableButton = maxLength < 0 || fileName.size() <= maxLength;
}
break;
}
@@ -3839,9 +3765,9 @@ QT_WARNING_POP
/*!
\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());
}
@@ -3851,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
@@ -3861,19 +3787,16 @@ void QFileDialogPrivate::_q_enterDirectory(const QModelIndex &index)
const QFileDialog::FileMode fileMode = q->fileMode();
q->setDirectory(path);
emit q->directoryEntered(path);
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- if (fileMode == QFileDialog::Directory
- || fileMode == QFileDialog::DirectoryOnly) {
+ if (fileMode == QFileDialog::Directory) {
// ### find out why you have to do both of these.
lineEdit()->setText(QString());
lineEdit()->clear();
}
-QT_WARNING_POP
} 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();
}
}
@@ -3885,8 +3808,10 @@ QT_WARNING_POP
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
@@ -3905,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 "
@@ -3921,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()) {
@@ -3934,14 +3859,14 @@ void QFileDialogPrivate::_q_useNameFilter(int index)
QStringList newNameFilters = QPlatformFileDialogHelper::cleanFilterList(nameFilter);
if (q_func()->acceptMode() == QFileDialog::AcceptSave) {
QString newNameFilterExtension;
- if (newNameFilters.count() > 0)
+ if (newNameFilters.size() > 0)
newNameFilterExtension = QFileInfo(newNameFilters.at(0)).suffix();
QString fileName = lineEdit()->text();
const QString fileNameExtension = QFileInfo(fileName).suffix();
if (!fileNameExtension.isEmpty() && !newNameFilterExtension.isEmpty()) {
- const int fileNameExtensionLength = fileNameExtension.count();
- fileName.replace(fileName.count() - fileNameExtensionLength,
+ const qsizetype fileNameExtensionLength = fileNameExtension.size();
+ fileName.replace(fileName.size() - fileNameExtensionLength,
fileNameExtensionLength, newNameFilterExtension);
qFileDialogUi->listView->clearSelection();
lineEdit()->setText(fileName);
@@ -3957,14 +3882,11 @@ 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();
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- bool stripDirs = (fileMode != QFileDialog::DirectoryOnly && fileMode != QFileDialog::Directory);
-QT_WARNING_POP
+ bool stripDirs = fileMode != QFileDialog::Directory;
QStringList allFiles;
for (const auto &index : indexes) {
@@ -3972,16 +3894,16 @@ QT_WARNING_POP
continue;
allFiles.append(index.data().toString());
}
- if (allFiles.count() > 1)
- for (int i = 0; i < allFiles.count(); ++i) {
- allFiles.replace(i, QString(QLatin1Char('"') + allFiles.at(i) + QLatin1Char('"')));
+ if (allFiles.size() > 1)
+ for (qsizetype i = 0; i < allFiles.size(); ++i) {
+ allFiles.replace(i, QString(u'"' + allFiles.at(i) + u'"'));
}
- QString finalFiles = allFiles.join(QLatin1Char(' '));
+ QString finalFiles = allFiles.join(u' ');
if (!finalFiles.isEmpty() && !lineEdit()->hasFocus() && lineEdit()->isVisible())
lineEdit()->setText(finalFiles);
else
- _q_updateOkButton();
+ updateOkButton();
}
/*!
@@ -3989,7 +3911,7 @@ QT_WARNING_POP
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();
@@ -4003,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()
@@ -4013,19 +3935,16 @@ 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();
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- if (fileMode == QFileDialog::Directory || fileMode == QFileDialog::DirectoryOnly) {
+ if (fileMode == QFileDialog::Directory) {
if (path == rootPath() && lineEdit()->text() == oldName)
lineEdit()->setText(newName);
}
-QT_WARNING_POP
}
-void QFileDialogPrivate::_q_emitUrlSelected(const QUrl &file)
+void QFileDialogPrivate::emitUrlSelected(const QUrl &file)
{
Q_Q(QFileDialog);
emit q->urlSelected(file);
@@ -4033,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);
@@ -4045,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);
@@ -4053,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);
@@ -4082,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
@@ -4091,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;
@@ -4104,12 +4023,12 @@ bool QFileDialogPrivate::itemViewKeyboardEvent(QKeyEvent *event) {
QString QFileDialogPrivate::getEnvironmentVariable(const QString &string)
{
#ifdef Q_OS_UNIX
- if (string.size() > 1 && string.startsWith(QLatin1Char('$'))) {
- return QString::fromLocal8Bit(qgetenv(string.midRef(1).toLatin1().constData()));
+ if (string.size() > 1 && string.startsWith(u'$')) {
+ return QString::fromLocal8Bit(qgetenv(QStringView{string}.mid(1).toLatin1().constData()));
}
#else
- if (string.size() > 2 && string.startsWith(QLatin1Char('%')) && string.endsWith(QLatin1Char('%'))) {
- return QString::fromLocal8Bit(qgetenv(string.midRef(1, string.size() - 2).toLatin1().constData()));
+ if (string.size() > 2 && string.startsWith(u'%') && string.endsWith(u'%')) {
+ return QString::fromLocal8Bit(qgetenv(QStringView{string}.mid(1, string.size() - 2).toLatin1().constData()));
}
#endif
return string;
@@ -4138,18 +4057,18 @@ void QFileDialogComboBox::showPopup()
idx = idx.parent();
}
// add "my computer"
- list.append(QUrl(QLatin1String("file:")));
+ list.append(QUrl("file:"_L1));
urlModel->addUrls(list, 0);
idx = model()->index(model()->rowCount() - 1, 0);
// append history
QList<QUrl> urls;
- for (int i = 0; i < m_history.count(); ++i) {
+ for (int i = 0; i < m_history.size(); ++i) {
QUrl path = QUrl::fromLocalFile(m_history.at(i));
if (!urls.contains(path))
urls.prepend(path);
}
- if (urls.count() > 0) {
+ if (urls.size() > 0) {
model()->insertRow(model()->rowCount());
idx = model()->index(model()->rowCount()-1, 0);
// ### TODO maybe add a horizontal line before this
@@ -4187,10 +4106,6 @@ void QFileDialogComboBox::paintEvent(QPaintEvent *)
painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
-QFileDialogListView::QFileDialogListView(QWidget *parent) : QListView(parent)
-{
-}
-
void QFileDialogListView::setFileDialogPrivate(QFileDialogPrivate *d_pointer)
{
d_ptr = d_pointer;
@@ -4224,10 +4139,6 @@ void QFileDialogListView::keyPressEvent(QKeyEvent *e)
e->accept();
}
-QFileDialogTreeView::QFileDialogTreeView(QWidget *parent) : QTreeView(parent)
-{
-}
-
void QFileDialogTreeView::setFileDialogPrivate(QFileDialogPrivate *d_pointer)
{
d_ptr = d_pointer;
@@ -4303,12 +4214,12 @@ QString QFSCompleter::pathFromIndex(const QModelIndex &index) const
if (!currentLocation.isEmpty() && path.startsWith(currentLocation)) {
#if defined(Q_OS_UNIX)
if (currentLocation == QDir::separator())
- return path.mid(currentLocation.length());
+ return path.remove(0, currentLocation.size());
#endif
- if (currentLocation.endsWith(QLatin1Char('/')))
- return path.mid(currentLocation.length());
+ if (currentLocation.endsWith(u'/'))
+ return path.remove(0, currentLocation.size());
else
- return path.mid(currentLocation.length()+1);
+ return path.remove(0, currentLocation.size()+1);
}
return index.data(QFileSystemModel::FilePathRole).toString();
}
@@ -4319,11 +4230,11 @@ QStringList QFSCompleter::splitPath(const QString &path) const
return QStringList(completionPrefix());
QString pathCopy = QDir::toNativeSeparators(path);
- QString sep = QDir::separator();
+ QChar sep = QDir::separator();
#if defined(Q_OS_WIN)
- if (pathCopy == QLatin1String("\\") || pathCopy == QLatin1String("\\\\"))
+ if (pathCopy == "\\"_L1 || pathCopy == "\\\\"_L1)
return QStringList(pathCopy);
- QString doubleSlash(QLatin1String("\\\\"));
+ QString doubleSlash("\\\\"_L1);
if (pathCopy.startsWith(doubleSlash))
pathCopy = pathCopy.mid(2);
else
@@ -4343,26 +4254,24 @@ QStringList QFSCompleter::splitPath(const QString &path) const
}
#endif
- QRegExp re(QLatin1Char('[') + QRegExp::escape(sep) + QLatin1Char(']'));
-
#if defined(Q_OS_WIN)
- QStringList parts = pathCopy.split(re, QString::SkipEmptyParts);
+ QStringList parts = pathCopy.split(sep, Qt::SkipEmptyParts);
if (!doubleSlash.isEmpty() && !parts.isEmpty())
parts[0].prepend(doubleSlash);
if (pathCopy.endsWith(sep))
parts.append(QString());
#else
- QStringList parts = pathCopy.split(re);
- if (pathCopy[0] == sep[0]) // read the "/" at the beginning as the split removed it
- parts[0] = sep[0];
+ QStringList parts = pathCopy.split(sep);
+ if (pathCopy[0] == sep) // read the "/" at the beginning as the split removed it
+ parts[0] = sep;
#endif
#if defined(Q_OS_WIN)
- bool startsFromRoot = !parts.isEmpty() && parts[0].endsWith(QLatin1Char(':'));
+ bool startsFromRoot = !parts.isEmpty() && parts[0].endsWith(u':');
#else
- bool startsFromRoot = pathCopy[0] == sep[0];
+ bool startsFromRoot = pathCopy[0] == sep;
#endif
- if (parts.count() == 1 || (parts.count() > 1 && !startsFromRoot)) {
+ if (parts.size() == 1 || (parts.size() > 1 && !startsFromRoot)) {
const QFileSystemModel *dirModel;
if (proxyModel)
dirModel = qobject_cast<const QFileSystemModel *>(proxyModel->sourceModel());
@@ -4370,14 +4279,12 @@ QStringList QFSCompleter::splitPath(const QString &path) const
dirModel = sourceModel;
QString currentLocation = QDir::toNativeSeparators(dirModel->rootPath());
#if defined(Q_OS_WIN)
- if (currentLocation.endsWith(QLatin1Char(':')))
+ if (currentLocation.endsWith(u':'))
currentLocation.append(sep);
#endif
if (currentLocation.contains(sep) && path != currentLocation) {
QStringList currentLocationList = splitPath(currentLocation);
- while (!currentLocationList.isEmpty()
- && parts.count() > 0
- && parts.at(0) == QLatin1String("..")) {
+ while (!currentLocationList.isEmpty() && parts.size() > 0 && parts.at(0) == ".."_L1) {
parts.removeFirst();
currentLocationList.removeLast();
}
diff --git a/src/widgets/dialogs/qfiledialog.h b/src/widgets/dialogs/qfiledialog.h
index 790f52f2e7..d59392753a 100644
--- a/src/widgets/dialogs/qfiledialog.h
+++ b/src/widgets/dialogs/qfiledialog.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFILEDIALOG_H
#define QFILEDIALOG_H
@@ -55,8 +19,8 @@ QT_BEGIN_NAMESPACE
class QModelIndex;
class QItemSelection;
struct QFileDialogArgs;
-class QFileIconProvider;
class QFileDialogPrivate;
+class QAbstractFileIconProvider;
class QAbstractItemDelegate;
class QAbstractProxyModel;
@@ -67,38 +31,28 @@ class Q_WIDGETS_EXPORT QFileDialog : public QDialog
Q_PROPERTY(FileMode fileMode READ fileMode WRITE setFileMode)
Q_PROPERTY(AcceptMode acceptMode READ acceptMode WRITE setAcceptMode)
Q_PROPERTY(QString defaultSuffix READ defaultSuffix WRITE setDefaultSuffix)
-#if QT_DEPRECATED_SINCE(5, 13)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly DESIGNABLE false)
- Q_PROPERTY(bool confirmOverwrite READ confirmOverwrite WRITE setConfirmOverwrite DESIGNABLE false)
- Q_PROPERTY(bool resolveSymlinks READ resolveSymlinks WRITE setResolveSymlinks DESIGNABLE false)
- Q_PROPERTY(bool nameFilterDetailsVisible READ isNameFilterDetailsVisible
- WRITE setNameFilterDetailsVisible DESIGNABLE false)
-#endif
Q_PROPERTY(Options options READ options WRITE setOptions)
Q_PROPERTY(QStringList supportedSchemes READ supportedSchemes WRITE setSupportedSchemes)
public:
enum ViewMode { Detail, List };
Q_ENUM(ViewMode)
- enum FileMode { AnyFile, ExistingFile, Directory, ExistingFiles,
- DirectoryOnly Q_DECL_ENUMERATOR_DEPRECATED_X("Use setOption(ShowDirsOnly, true) instead")};
+ enum FileMode { AnyFile, ExistingFile, Directory, ExistingFiles };
Q_ENUM(FileMode)
enum AcceptMode { AcceptOpen, AcceptSave };
Q_ENUM(AcceptMode)
enum DialogLabel { LookIn, FileName, FileType, Accept, Reject };
+ // keep this in sync with QFileDialogOption::FileDialogOptions
enum Option
{
ShowDirsOnly = 0x00000001,
DontResolveSymlinks = 0x00000002,
DontConfirmOverwrite = 0x00000004,
-#if QT_DEPRECATED_SINCE(5, 14)
- DontUseSheet Q_DECL_ENUMERATOR_DEPRECATED = 0x00000008,
-#endif
- DontUseNativeDialog = 0x00000010,
- ReadOnly = 0x00000020,
- HideNameFilterDetails = 0x00000040,
- DontUseCustomDirectoryIcons = 0x00000080
+ DontUseNativeDialog = 0x00000008,
+ ReadOnly = 0x00000010,
+ HideNameFilterDetails = 0x00000020,
+ DontUseCustomDirectoryIcons = 0x00000040
};
Q_ENUM(Option)
Q_DECLARE_FLAGS(Options, Option)
@@ -124,13 +78,6 @@ public:
void selectUrl(const QUrl &url);
QList<QUrl> selectedUrls() const;
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use setOption(HideNameFilterDetails, !enabled) instead")
- void setNameFilterDetailsVisible(bool enabled);
- QT_DEPRECATED_X("Use !testOption(HideNameFilterDetails) instead")
- bool isNameFilterDetailsVisible() const;
-#endif
-
void setNameFilter(const QString &filter);
void setNameFilters(const QStringList &filters);
QStringList nameFilters() const;
@@ -156,29 +103,12 @@ public:
void setAcceptMode(AcceptMode mode);
AcceptMode acceptMode() const;
-#if QT_DEPRECATED_SINCE(5, 13)
- void setReadOnly(bool enabled);
- bool isReadOnly() const;
-
- QT_DEPRECATED_X("Use setOption(DontResolveSymlinks, !enabled) instead")
- void setResolveSymlinks(bool enabled);
- QT_DEPRECATED_X("Use !testOption(DontResolveSymlinks) instead")
- bool resolveSymlinks() const;
-#endif
-
void setSidebarUrls(const QList<QUrl> &urls);
QList<QUrl> sidebarUrls() const;
QByteArray saveState() const;
bool restoreState(const QByteArray &state);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use setOption(DontConfirmOverwrite, !enabled) instead")
- void setConfirmOverwrite(bool enabled);
- QT_DEPRECATED_X("Use !testOption(DontConfirmOverwrite) instead")
- bool confirmOverwrite() const;
-#endif
-
void setDefaultSuffix(const QString &suffix);
QString defaultSuffix() const;
@@ -188,8 +118,8 @@ public:
void setItemDelegate(QAbstractItemDelegate *delegate);
QAbstractItemDelegate *itemDelegate() const;
- void setIconProvider(QFileIconProvider *provider);
- QFileIconProvider *iconProvider() const;
+ void setIconProvider(QAbstractFileIconProvider *provider);
+ QAbstractFileIconProvider *iconProvider() const;
void setLabelText(DialogLabel label, const QString &text);
QString labelText(DialogLabel label) const;
@@ -283,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);
@@ -296,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.ui b/src/widgets/dialogs/qfiledialog.ui
index e4b4aad6ce..f275e20c63 100644
--- a/src/widgets/dialogs/qfiledialog.ui
+++ b/src/widgets/dialogs/qfiledialog.ui
@@ -1,43 +1,8 @@
-<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
- <comment>*********************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-*********************************************************************</comment>
+<comment>
+* 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
+</comment>
<class>QFileDialog</class>
<widget class="QDialog" name="QFileDialog">
<property name="geometry">
diff --git a/src/widgets/dialogs/qfiledialog_p.h b/src/widgets/dialogs/qfiledialog_p.h
index dcf147348f..d5ee1c537b 100644
--- a/src/widgets/dialogs/qfiledialog_p.h
+++ b/src/widgets/dialogs/qfiledialog_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFILEDIALOG_P_H
#define QFILEDIALOG_P_H
@@ -57,7 +21,7 @@
#include "private/qdialog_p.h"
#include "qplatformdefs.h"
-#include "qfilesystemmodel_p.h"
+#include <QtGui/private/qfilesystemmodel_p.h>
#include <qlistview.h>
#include <qtreeview.h>
#include <qcombobox.h>
@@ -69,6 +33,7 @@
#include <qstackedwidget.h>
#include <qdialogbuttonbox.h>
#include <qabstractproxymodel.h>
+#include <qfileiconprovider.h>
#if QT_CONFIG(completer)
#include <qcompleter.h>
#endif
@@ -98,25 +63,23 @@ class QPlatformDialogHelper;
struct QFileDialogArgs
{
- QFileDialogArgs() : parent(nullptr), mode(QFileDialog::AnyFile) {}
+ QFileDialogArgs(const QUrl &url = {});
- QWidget *parent;
+ QWidget *parent = nullptr;
QString caption;
QUrl directory;
QString selection;
QString filter;
- QFileDialog::FileMode mode;
- QFileDialog::Options options;
+ QFileDialog::FileMode mode = QFileDialog::AnyFile;
+ QFileDialog::Options options = {};
};
-#define UrlRole (Qt::UserRole + 1)
-
class Q_WIDGETS_EXPORT QFileDialogPrivate : public QDialogPrivate
{
Q_DECLARE_PUBLIC(QFileDialog)
public:
- using PersistentModelIndexList = QVector<QPersistentModelIndex>;
+ using PersistentModelIndexList = QList<QPersistentModelIndex>;
struct HistoryItem
{
@@ -133,12 +96,9 @@ public:
void createMenuActions();
void createWidgets();
- void init(const QUrl &directory = QUrl(), const QString &nameFilter = QString(),
- const QString &caption = QString());
+ void init(const QFileDialogArgs &args);
bool itemViewKeyboardEvent(QKeyEvent *event);
QString getEnvironmentVariable(const QString &string);
- static QUrl workingDirectory(const QUrl &path);
- static QString initialSelection(const QUrl &path);
QStringList typedFiles() const;
QList<QUrl> userSelectedFiles() const;
QStringList addDefaultSuffixToFiles(const QStringList &filesToFix) const;
@@ -160,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;
@@ -184,7 +144,7 @@ public:
{
#if defined(Q_OS_WIN)
QString n(path);
- n.replace(QLatin1Char('\\'), QLatin1Char('/'));
+ n.replace(u'\\', u'/');
return n;
#else // the compile should optimize away this
return path;
@@ -203,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)
@@ -261,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);
@@ -288,6 +249,7 @@ public:
QByteArray splitterState;
QByteArray headerData;
QList<QUrl> sidebarUrls;
+ QFileIconProvider defaultIconProvider;
~QFileDialogPrivate();
@@ -296,6 +258,8 @@ private:
virtual void helperPrepareShow(QPlatformDialogHelper *) override;
virtual void helperDone(QDialog::DialogCode, QPlatformDialogHelper *) override;
+ void itemNotFound(const QString &fileName, QFileDialog::FileMode mode);
+ bool itemAlreadyExists(const QString &fileName);
Q_DISABLE_COPY_MOVE(QFileDialogPrivate)
};
@@ -313,7 +277,8 @@ private:
class QFileDialogComboBox : public QComboBox
{
public:
- QFileDialogComboBox(QWidget *parent = nullptr) : QComboBox(parent), urlModel(nullptr) {}
+ QFileDialogComboBox(QWidget *parent = nullptr) :
+ QComboBox(parent), urlModel(nullptr), d_ptr(nullptr) {}
void setFileDialogPrivate(QFileDialogPrivate *d_pointer);
void showPopup() override;
void setHistory(const QStringList &paths);
@@ -329,7 +294,7 @@ private:
class QFileDialogListView : public QListView
{
public:
- QFileDialogListView(QWidget *parent = nullptr);
+ QFileDialogListView(QWidget *parent = nullptr) : QListView(parent), d_ptr(nullptr) {}
void setFileDialogPrivate(QFileDialogPrivate *d_pointer);
QSize sizeHint() const override;
protected:
@@ -341,7 +306,7 @@ private:
class QFileDialogTreeView : public QTreeView
{
public:
- QFileDialogTreeView(QWidget *parent);
+ QFileDialogTreeView(QWidget *parent) : QTreeView(parent), d_ptr(nullptr) {}
void setFileDialogPrivate(QFileDialogPrivate *d_pointer);
QSize sizeHint() const override;
diff --git a/src/widgets/dialogs/qfileinfogatherer.cpp b/src/widgets/dialogs/qfileinfogatherer.cpp
deleted file mode 100644
index 7342efbd0d..0000000000
--- a/src/widgets/dialogs/qfileinfogatherer.cpp
+++ /dev/null
@@ -1,435 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfileinfogatherer_p.h"
-#include <qdebug.h>
-#include <qdiriterator.h>
-#ifndef Q_OS_WIN
-# include <unistd.h>
-# include <sys/types.h>
-#endif
-#if defined(Q_OS_VXWORKS)
-# include "qplatformdefs.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_BUILD_INTERNAL
-static QBasicAtomicInt fetchedRoot = Q_BASIC_ATOMIC_INITIALIZER(false);
-Q_AUTOTEST_EXPORT void qt_test_resetFetchedRoot()
-{
- fetchedRoot.storeRelaxed(false);
-}
-
-Q_AUTOTEST_EXPORT bool qt_test_isFetchedRoot()
-{
- return fetchedRoot.loadRelaxed();
-}
-#endif
-
-static QString translateDriveName(const QFileInfo &drive)
-{
- QString driveName = drive.absoluteFilePath();
-#ifdef Q_OS_WIN
- if (driveName.startsWith(QLatin1Char('/'))) // UNC host
- return drive.fileName();
- if (driveName.endsWith(QLatin1Char('/')))
- driveName.chop(1);
-#endif // Q_OS_WIN
- return driveName;
-}
-
-/*!
- Creates thread
-*/
-QFileInfoGatherer::QFileInfoGatherer(QObject *parent)
- : QThread(parent)
- , m_iconProvider(&defaultProvider)
-{
- start(LowPriority);
-}
-
-/*!
- Destroys thread
-*/
-QFileInfoGatherer::~QFileInfoGatherer()
-{
- abort.storeRelaxed(true);
- QMutexLocker locker(&mutex);
- condition.wakeAll();
- locker.unlock();
- wait();
-}
-
-void QFileInfoGatherer::setResolveSymlinks(bool enable)
-{
- Q_UNUSED(enable);
-#ifdef Q_OS_WIN
- m_resolveSymlinks = enable;
-#endif
-}
-
-void QFileInfoGatherer::driveAdded()
-{
- fetchExtendedInformation(QString(), QStringList());
-}
-
-void QFileInfoGatherer::driveRemoved()
-{
- QStringList drives;
- const QFileInfoList driveInfoList = QDir::drives();
- for (const QFileInfo &fi : driveInfoList)
- drives.append(translateDriveName(fi));
- newListOfFiles(QString(), drives);
-}
-
-bool QFileInfoGatherer::resolveSymlinks() const
-{
-#ifdef Q_OS_WIN
- return m_resolveSymlinks;
-#else
- return false;
-#endif
-}
-
-void QFileInfoGatherer::setIconProvider(QFileIconProvider *provider)
-{
- m_iconProvider = provider;
-}
-
-QFileIconProvider *QFileInfoGatherer::iconProvider() const
-{
- return m_iconProvider;
-}
-
-/*!
- Fetch extended information for all \a files in \a path
-
- \sa updateFile(), update(), resolvedName()
-*/
-void QFileInfoGatherer::fetchExtendedInformation(const QString &path, const QStringList &files)
-{
- QMutexLocker locker(&mutex);
- // See if we already have this dir/file in our queue
- int loc = this->path.lastIndexOf(path);
- while (loc > 0) {
- if (this->files.at(loc) == files) {
- return;
- }
- loc = this->path.lastIndexOf(path, loc - 1);
- }
- this->path.push(path);
- this->files.push(files);
- condition.wakeAll();
-
-#if QT_CONFIG(filesystemwatcher)
- if (files.isEmpty()
- && !path.isEmpty()
- && !path.startsWith(QLatin1String("//")) /*don't watch UNC path*/) {
- if (!watchedDirectories().contains(path))
- watchPaths(QStringList(path));
- }
-#endif
-}
-
-/*!
- Fetch extended information for all \a filePath
-
- \sa fetchExtendedInformation()
-*/
-void QFileInfoGatherer::updateFile(const QString &filePath)
-{
- QString dir = filePath.mid(0, filePath.lastIndexOf(QLatin1Char('/')));
- QString fileName = filePath.mid(dir.length() + 1);
- fetchExtendedInformation(dir, QStringList(fileName));
-}
-
-QStringList QFileInfoGatherer::watchedFiles() const
-{
-#if QT_CONFIG(filesystemwatcher)
- if (m_watcher)
- return m_watcher->files();
-#endif
- return {};
-}
-
-QStringList QFileInfoGatherer::watchedDirectories() const
-{
-#if QT_CONFIG(filesystemwatcher)
- if (m_watcher)
- return m_watcher->directories();
-#endif
- return {};
-}
-
-void QFileInfoGatherer::createWatcher()
-{
-#if QT_CONFIG(filesystemwatcher)
- m_watcher = new QFileSystemWatcher(this);
- connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &QFileInfoGatherer::list);
- connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &QFileInfoGatherer::updateFile);
-# if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
- const QVariant listener = m_watcher->property("_q_driveListener");
- if (listener.canConvert<QObject *>()) {
- if (QObject *driveListener = listener.value<QObject *>()) {
- connect(driveListener, SIGNAL(driveAdded()), this, SLOT(driveAdded()));
- connect(driveListener, SIGNAL(driveRemoved()), this, SLOT(driveRemoved()));
- }
- }
-# endif // Q_OS_WIN && !Q_OS_WINRT
-#endif
-}
-
-void QFileInfoGatherer::watchPaths(const QStringList &paths)
-{
-#if QT_CONFIG(filesystemwatcher)
- if (m_watching) {
- if (m_watcher == nullptr)
- createWatcher();
- m_watcher->addPaths(paths);
- }
-#else
- Q_UNUSED(paths);
-#endif
-}
-
-void QFileInfoGatherer::unwatchPaths(const QStringList &paths)
-{
-#if QT_CONFIG(filesystemwatcher)
- if (m_watcher && !paths.isEmpty())
- m_watcher->removePaths(paths);
-#else
- Q_UNUSED(paths);
-#endif
-}
-
-bool QFileInfoGatherer::isWatching() const
-{
- bool result = false;
-#if QT_CONFIG(filesystemwatcher)
- QMutexLocker locker(&mutex);
- result = m_watching;
-#endif
- return result;
-}
-
-void QFileInfoGatherer::setWatching(bool v)
-{
-#if QT_CONFIG(filesystemwatcher)
- QMutexLocker locker(&mutex);
- if (v != m_watching) {
- if (!v) {
- delete m_watcher;
- m_watcher = nullptr;
- }
- m_watching = v;
- }
-#else
- Q_UNUSED(v);
-#endif
-}
-
-/*
- List all files in \a directoryPath
-
- \sa listed()
-*/
-void QFileInfoGatherer::clear()
-{
-#if QT_CONFIG(filesystemwatcher)
- QMutexLocker locker(&mutex);
- unwatchPaths(watchedFiles());
- unwatchPaths(watchedDirectories());
-#endif
-}
-
-/*
- Remove a \a path from the watcher
-
- \sa listed()
-*/
-void QFileInfoGatherer::removePath(const QString &path)
-{
-#if QT_CONFIG(filesystemwatcher)
- QMutexLocker locker(&mutex);
- unwatchPaths(QStringList(path));
-#else
- Q_UNUSED(path);
-#endif
-}
-
-/*
- List all files in \a directoryPath
-
- \sa listed()
-*/
-void QFileInfoGatherer::list(const QString &directoryPath)
-{
- fetchExtendedInformation(directoryPath, QStringList());
-}
-
-/*
- Until aborted wait to fetch a directory or files
-*/
-void QFileInfoGatherer::run()
-{
- forever {
- QMutexLocker locker(&mutex);
- while (!abort.loadRelaxed() && path.isEmpty())
- condition.wait(&mutex);
- if (abort.loadRelaxed())
- return;
- const QString thisPath = qAsConst(path).front();
- path.pop_front();
- const QStringList thisList = qAsConst(files).front();
- files.pop_front();
- locker.unlock();
-
- getFileInfos(thisPath, thisList);
- }
-}
-
-QExtendedInformation QFileInfoGatherer::getInfo(const QFileInfo &fileInfo) const
-{
- QExtendedInformation info(fileInfo);
- info.icon = m_iconProvider->icon(fileInfo);
- info.displayType = m_iconProvider->type(fileInfo);
-#if QT_CONFIG(filesystemwatcher)
- // ### Not ready to listen all modifications by default
- static const bool watchFiles = qEnvironmentVariableIsSet("QT_FILESYSTEMMODEL_WATCH_FILES");
- if (watchFiles) {
- if (!fileInfo.exists() && !fileInfo.isSymLink()) {
- const_cast<QFileInfoGatherer *>(this)->
- unwatchPaths(QStringList(fileInfo.absoluteFilePath()));
- } else {
- const QString path = fileInfo.absoluteFilePath();
- if (!path.isEmpty() && fileInfo.exists() && fileInfo.isFile() && fileInfo.isReadable()
- && !watchedFiles().contains(path)) {
- const_cast<QFileInfoGatherer *>(this)->watchPaths(QStringList(path));
- }
- }
- }
-#endif // filesystemwatcher
-
-#ifdef Q_OS_WIN
- if (m_resolveSymlinks && info.isSymLink(/* ignoreNtfsSymLinks = */ true)) {
- QFileInfo resolvedInfo(fileInfo.symLinkTarget());
- resolvedInfo = resolvedInfo.canonicalFilePath();
- if (resolvedInfo.exists()) {
- emit nameResolved(fileInfo.filePath(), resolvedInfo.fileName());
- }
- }
-#endif
- return info;
-}
-
-/*
- Get specific file info's, batch the files so update when we have 100
- items and every 200ms after that
- */
-void QFileInfoGatherer::getFileInfos(const QString &path, const QStringList &files)
-{
- // List drives
- if (path.isEmpty()) {
-#ifdef QT_BUILD_INTERNAL
- fetchedRoot.storeRelaxed(true);
-#endif
- QFileInfoList infoList;
- if (files.isEmpty()) {
- infoList = QDir::drives();
- } else {
- infoList.reserve(files.count());
- for (const auto &file : files)
- infoList << QFileInfo(file);
- }
- for (int i = infoList.count() - 1; i >= 0; --i) {
- QString driveName = translateDriveName(infoList.at(i));
- QVector<QPair<QString,QFileInfo> > updatedFiles;
- updatedFiles.append(QPair<QString,QFileInfo>(driveName, infoList.at(i)));
- emit updates(path, updatedFiles);
- }
- return;
- }
-
- QElapsedTimer base;
- base.start();
- QFileInfo fileInfo;
- bool firstTime = true;
- QVector<QPair<QString, QFileInfo> > updatedFiles;
- QStringList filesToCheck = files;
-
- QStringList allFiles;
- if (files.isEmpty()) {
- QDirIterator dirIt(path, QDir::AllEntries | QDir::System | QDir::Hidden);
- while (!abort.loadRelaxed() && dirIt.hasNext()) {
- dirIt.next();
- fileInfo = dirIt.fileInfo();
- allFiles.append(fileInfo.fileName());
- fetch(fileInfo, base, firstTime, updatedFiles, path);
- }
- }
- if (!allFiles.isEmpty())
- emit newListOfFiles(path, allFiles);
-
- QStringList::const_iterator filesIt = filesToCheck.constBegin();
- while (!abort.loadRelaxed() && filesIt != filesToCheck.constEnd()) {
- fileInfo.setFile(path + QDir::separator() + *filesIt);
- ++filesIt;
- fetch(fileInfo, base, firstTime, updatedFiles, path);
- }
- if (!updatedFiles.isEmpty())
- emit updates(path, updatedFiles);
- emit directoryLoaded(path);
-}
-
-void QFileInfoGatherer::fetch(const QFileInfo &fileInfo, QElapsedTimer &base, bool &firstTime, QVector<QPair<QString, QFileInfo> > &updatedFiles, const QString &path) {
- updatedFiles.append(QPair<QString, QFileInfo>(fileInfo.fileName(), fileInfo));
- QElapsedTimer current;
- current.start();
- if ((firstTime && updatedFiles.count() > 100) || base.msecsTo(current) > 1000) {
- emit updates(path, updatedFiles);
- updatedFiles.clear();
- base = current;
- firstTime = false;
- }
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qfileinfogatherer_p.cpp"
diff --git a/src/widgets/dialogs/qfileinfogatherer_p.h b/src/widgets/dialogs/qfileinfogatherer_p.h
deleted file mode 100644
index 3d30a98d04..0000000000
--- a/src/widgets/dialogs/qfileinfogatherer_p.h
+++ /dev/null
@@ -1,229 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QFILEINFOGATHERER_H
-#define QFILEINFOGATHERER_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 <QtWidgets/private/qtwidgetsglobal_p.h>
-
-#include <qthread.h>
-#include <qmutex.h>
-#include <qwaitcondition.h>
-#if QT_CONFIG(filesystemwatcher)
-#include <qfilesystemwatcher.h>
-#endif
-#include <qfileiconprovider.h>
-#include <qpair.h>
-#include <qstack.h>
-#include <qdatetime.h>
-#include <qdir.h>
-#include <qelapsedtimer.h>
-
-#include <private/qfilesystemengine_p.h>
-
-QT_REQUIRE_CONFIG(filesystemmodel);
-
-QT_BEGIN_NAMESPACE
-
-class QExtendedInformation {
-public:
- enum Type { Dir, File, System };
-
- QExtendedInformation() {}
- QExtendedInformation(const QFileInfo &info) : mFileInfo(info) {}
-
- inline bool isDir() { return type() == Dir; }
- inline bool isFile() { return type() == File; }
- inline bool isSystem() { return type() == System; }
-
- bool operator ==(const QExtendedInformation &fileInfo) const {
- return mFileInfo == fileInfo.mFileInfo
- && displayType == fileInfo.displayType
- && permissions() == fileInfo.permissions()
- && lastModified() == fileInfo.lastModified();
- }
-
-#ifndef QT_NO_FSFILEENGINE
- bool isCaseSensitive() const {
- return QFileSystemEngine::isCaseSensitive();
- }
-#endif
-
- QFile::Permissions permissions() const {
- return mFileInfo.permissions();
- }
-
- Type type() const {
- if (mFileInfo.isDir()) {
- return QExtendedInformation::Dir;
- }
- if (mFileInfo.isFile()) {
- return QExtendedInformation::File;
- }
- if (!mFileInfo.exists() && mFileInfo.isSymLink()) {
- return QExtendedInformation::System;
- }
- return QExtendedInformation::System;
- }
-
- bool isSymLink(bool ignoreNtfsSymLinks = false) const
- {
- if (ignoreNtfsSymLinks) {
-#ifdef Q_OS_WIN
- return !mFileInfo.suffix().compare(QLatin1String("lnk"), Qt::CaseInsensitive);
-#endif
- }
- return mFileInfo.isSymLink();
- }
-
- bool isHidden() const {
- return mFileInfo.isHidden();
- }
-
- QFileInfo fileInfo() const {
- return mFileInfo;
- }
-
- QDateTime lastModified() const {
- return mFileInfo.lastModified();
- }
-
- qint64 size() const {
- qint64 size = -1;
- if (type() == QExtendedInformation::Dir)
- size = 0;
- if (type() == QExtendedInformation::File)
- size = mFileInfo.size();
- if (!mFileInfo.exists() && !mFileInfo.isSymLink())
- size = -1;
- return size;
- }
-
- QString displayType;
- QIcon icon;
-
-private :
- QFileInfo mFileInfo;
-};
-
-class QFileIconProvider;
-
-class Q_AUTOTEST_EXPORT QFileInfoGatherer : public QThread
-{
-Q_OBJECT
-
-Q_SIGNALS:
- void updates(const QString &directory, const QVector<QPair<QString, QFileInfo> > &updates);
- void newListOfFiles(const QString &directory, const QStringList &listOfFiles) const;
- void nameResolved(const QString &fileName, const QString &resolvedName) const;
- void directoryLoaded(const QString &path);
-
-public:
- explicit QFileInfoGatherer(QObject *parent = nullptr);
- ~QFileInfoGatherer();
-
- QStringList watchedFiles() const;
- QStringList watchedDirectories() const;
- void watchPaths(const QStringList &paths);
- void unwatchPaths(const QStringList &paths);
-
- bool isWatching() const;
- void setWatching(bool v);
-
- // only callable from this->thread():
- void clear();
- void removePath(const QString &path);
- QExtendedInformation getInfo(const QFileInfo &info) const;
- QFileIconProvider *iconProvider() const;
- bool resolveSymlinks() const;
-
-public Q_SLOTS:
- void list(const QString &directoryPath);
- void fetchExtendedInformation(const QString &path, const QStringList &files);
- void updateFile(const QString &path);
- void setResolveSymlinks(bool enable);
- void setIconProvider(QFileIconProvider *provider);
-
-private Q_SLOTS:
- void driveAdded();
- void driveRemoved();
-
-private:
- void run() override;
- // called by run():
- void getFileInfos(const QString &path, const QStringList &files);
- void fetch(const QFileInfo &info, QElapsedTimer &base, bool &firstTime, QVector<QPair<QString, QFileInfo> > &updatedFiles, const QString &path);
-
-private:
- void createWatcher();
-
- mutable QMutex mutex;
- // begin protected by mutex
- QWaitCondition condition;
- QStack<QString> path;
- QStack<QStringList> files;
- // end protected by mutex
- QAtomicInt abort;
-
-#if QT_CONFIG(filesystemwatcher)
- QFileSystemWatcher *m_watcher = nullptr;
-#endif
- QFileIconProvider *m_iconProvider; // not accessed by run()
- QFileIconProvider defaultProvider;
-#ifdef Q_OS_WIN
- bool m_resolveSymlinks = true; // not accessed by run()
-#endif
-#if QT_CONFIG(filesystemwatcher)
- bool m_watching = true;
-#endif
-};
-
-QT_END_NAMESPACE
-#endif // QFILEINFOGATHERER_H
diff --git a/src/widgets/dialogs/qfilesystemmodel.cpp b/src/widgets/dialogs/qfilesystemmodel.cpp
deleted file mode 100644
index a723c3a955..0000000000
--- a/src/widgets/dialogs/qfilesystemmodel.cpp
+++ /dev/null
@@ -1,2167 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfilesystemmodel_p.h"
-#include "qfilesystemmodel.h"
-#include <qlocale.h>
-#include <qmimedata.h>
-#include <qurl.h>
-#include <qdebug.h>
-#if QT_CONFIG(messagebox)
-#include <qmessagebox.h>
-#endif
-#include <qapplication.h>
-#include <QtCore/qcollator.h>
-#if QT_CONFIG(regularexpression)
-# include <QtCore/qregularexpression.h>
-#endif
-
-#include <algorithm>
-
-#ifdef Q_OS_WIN
-# include <QtCore/QVarLengthArray>
-# include <qt_windows.h>
-# ifndef Q_OS_WINRT
-# include <shlobj.h>
-# endif
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \enum QFileSystemModel::Roles
- \value FileIconRole
- \value FilePathRole
- \value FileNameRole
- \value FilePermissions
-*/
-
-/*!
- \class QFileSystemModel
- \since 4.4
-
- \brief The QFileSystemModel class provides a data model for the local filesystem.
-
- \ingroup model-view
- \inmodule QtWidgets
-
- This class provides access to the local filesystem, providing functions
- for renaming and removing files and directories, and for creating new
- directories. In the simplest case, it can be used with a suitable display
- widget as part of a browser or filter.
-
- QFileSystemModel can be accessed using the standard interface provided by
- QAbstractItemModel, but it also provides some convenience functions that are
- specific to a directory model.
- The fileInfo(), isDir(), fileName() and filePath() functions provide information
- about the underlying files and directories related to items in the model.
- Directories can be created and removed using mkdir(), rmdir().
-
- \note QFileSystemModel requires an instance of \l QApplication.
-
- \section1 Example Usage
-
- A directory model that displays the contents of a default directory
- is usually constructed with a parent object:
-
- \snippet shareddirmodel/main.cpp 2
-
- A tree view can be used to display the contents of the model
-
- \snippet shareddirmodel/main.cpp 4
-
- and the contents of a particular directory can be displayed by
- setting the tree view's root index:
-
- \snippet shareddirmodel/main.cpp 7
-
- The view's root index can be used to control how much of a
- hierarchical model is displayed. QFileSystemModel provides a convenience
- function that returns a suitable model index for a path to a
- directory within the model.
-
- \section1 Caching and Performance
-
- QFileSystemModel will not fetch any files or directories until setRootPath()
- is called. This will prevent any unnecessary querying on the file system
- until that point such as listing the drives on Windows.
-
- Unlike QDirModel, QFileSystemModel uses a separate thread to populate
- itself so it will not cause the main thread to hang as the file system
- is being queried. Calls to rowCount() will return 0 until the model
- populates a directory.
-
- QFileSystemModel keeps a cache with file information. The cache is
- automatically kept up to date using the QFileSystemWatcher.
-
- \sa {Model Classes}
-*/
-
-/*!
- \fn bool QFileSystemModel::rmdir(const QModelIndex &index)
-
- Removes the directory corresponding to the model item \a index in the
- file system model and \b{deletes the corresponding directory from the
- file system}, returning true if successful. If the directory cannot be
- removed, false is returned.
-
- \warning This function deletes directories from the file system; it does
- \b{not} move them to a location where they can be recovered.
-
- \sa remove()
-*/
-
-/*!
- \fn QIcon QFileSystemModel::fileName(const QModelIndex &index) const
-
- Returns the file name for the item stored in the model under the given
- \a index.
-*/
-
-/*!
- \fn QIcon QFileSystemModel::fileIcon(const QModelIndex &index) const
-
- Returns the icon for the item stored in the model under the given
- \a index.
-*/
-
-/*!
- \fn QFileInfo QFileSystemModel::fileInfo(const QModelIndex &index) const
-
- Returns the QFileInfo for the item stored in the model under the given
- \a index.
-*/
-QFileInfo QFileSystemModel::fileInfo(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- return d->node(index)->fileInfo();
-}
-
-/*!
- \fn void QFileSystemModel::rootPathChanged(const QString &newPath);
-
- This signal is emitted whenever the root path has been changed to a \a newPath.
-*/
-
-/*!
- \fn void QFileSystemModel::fileRenamed(const QString &path, const QString &oldName, const QString &newName)
-
- This signal is emitted whenever a file with the \a oldName is successfully
- renamed to \a newName. The file is located in in the directory \a path.
-*/
-
-/*!
- \since 4.7
- \fn void QFileSystemModel::directoryLoaded(const QString &path)
-
- This signal is emitted when the gatherer thread has finished to load the \a path.
-
-*/
-
-/*!
- \fn bool QFileSystemModel::remove(const QModelIndex &index)
-
- Removes the model item \a index from the file system model and \b{deletes the
- corresponding file from the file system}, returning true if successful. If the
- item cannot be removed, false is returned.
-
- \warning This function deletes files from the file system; it does \b{not}
- move them to a location where they can be recovered.
-
- \sa rmdir()
-*/
-
-bool QFileSystemModel::remove(const QModelIndex &aindex)
-{
- Q_D(QFileSystemModel);
-
- const QString path = d->filePath(aindex);
- const QFileInfo fileInfo(path);
-#if QT_CONFIG(filesystemwatcher) && defined(Q_OS_WIN)
- // QTBUG-65683: Remove file system watchers prior to deletion to prevent
- // failure due to locked files on Windows.
- const QStringList watchedPaths = d->unwatchPathsAt(aindex);
-#endif // filesystemwatcher && Q_OS_WIN
- const bool success = (fileInfo.isFile() || fileInfo.isSymLink())
- ? QFile::remove(path) : QDir(path).removeRecursively();
-#if QT_CONFIG(filesystemwatcher) && defined(Q_OS_WIN)
- if (!success)
- d->watchPaths(watchedPaths);
-#endif // filesystemwatcher && Q_OS_WIN
- return success;
-}
-
-/*!
- Constructs a file system model with the given \a parent.
-*/
-QFileSystemModel::QFileSystemModel(QObject *parent) :
- QFileSystemModel(*new QFileSystemModelPrivate, parent)
-{
-}
-
-/*!
- \internal
-*/
-QFileSystemModel::QFileSystemModel(QFileSystemModelPrivate &dd, QObject *parent)
- : QAbstractItemModel(dd, parent)
-{
- Q_D(QFileSystemModel);
- d->init();
-}
-
-/*!
- Destroys this file system model.
-*/
-QFileSystemModel::~QFileSystemModel() = default;
-
-/*!
- \reimp
-*/
-QModelIndex QFileSystemModel::index(int row, int column, const QModelIndex &parent) const
-{
- Q_D(const QFileSystemModel);
- if (row < 0 || column < 0 || row >= rowCount(parent) || column >= columnCount(parent))
- return QModelIndex();
-
- // get the parent node
- QFileSystemModelPrivate::QFileSystemNode *parentNode = (d->indexValid(parent) ? d->node(parent) :
- const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&d->root));
- Q_ASSERT(parentNode);
-
- // now get the internal pointer for the index
- const int i = d->translateVisibleLocation(parentNode, row);
- if (i >= parentNode->visibleChildren.size())
- return QModelIndex();
- const QString &childName = parentNode->visibleChildren.at(i);
- const QFileSystemModelPrivate::QFileSystemNode *indexNode = parentNode->children.value(childName);
- Q_ASSERT(indexNode);
-
- return createIndex(row, column, const_cast<QFileSystemModelPrivate::QFileSystemNode*>(indexNode));
-}
-
-/*!
- \reimp
-*/
-QModelIndex QFileSystemModel::sibling(int row, int column, const QModelIndex &idx) const
-{
- if (row == idx.row() && column < QFileSystemModelPrivate::NumColumns) {
- // cheap sibling operation: just adjust the column:
- return createIndex(row, column, idx.internalPointer());
- } else {
- // for anything else: call the default implementation
- // (this could probably be optimized, too):
- return QAbstractItemModel::sibling(row, column, idx);
- }
-}
-
-/*!
- \overload
-
- Returns the model item index for the given \a path and \a column.
-*/
-QModelIndex QFileSystemModel::index(const QString &path, int column) const
-{
- Q_D(const QFileSystemModel);
- QFileSystemModelPrivate::QFileSystemNode *node = d->node(path, false);
- return d->index(node, column);
-}
-
-/*!
- \internal
-
- Return the QFileSystemNode that goes to index.
- */
-QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QModelIndex &index) const
-{
- if (!index.isValid())
- return const_cast<QFileSystemNode*>(&root);
- QFileSystemModelPrivate::QFileSystemNode *indexNode = static_cast<QFileSystemModelPrivate::QFileSystemNode*>(index.internalPointer());
- Q_ASSERT(indexNode);
- return indexNode;
-}
-
-#ifdef Q_OS_WIN32
-static QString qt_GetLongPathName(const QString &strShortPath)
-{
- if (strShortPath.isEmpty()
- || strShortPath == QLatin1String(".") || strShortPath == QLatin1String(".."))
- return strShortPath;
- if (strShortPath.length() == 2 && strShortPath.endsWith(QLatin1Char(':')))
- return strShortPath.toUpper();
- const QString absPath = QDir(strShortPath).absolutePath();
- if (absPath.startsWith(QLatin1String("//"))
- || absPath.startsWith(QLatin1String("\\\\"))) // unc
- return QDir::fromNativeSeparators(absPath);
- if (absPath.startsWith(QLatin1Char('/')))
- return QString();
- const QString inputString = QLatin1String("\\\\?\\") + QDir::toNativeSeparators(absPath);
- QVarLengthArray<TCHAR, MAX_PATH> buffer(MAX_PATH);
- DWORD result = ::GetLongPathName((wchar_t*)inputString.utf16(),
- buffer.data(),
- buffer.size());
- if (result > DWORD(buffer.size())) {
- buffer.resize(result);
- result = ::GetLongPathName((wchar_t*)inputString.utf16(),
- buffer.data(),
- buffer.size());
- }
- if (result > 4) {
- QString longPath = QString::fromWCharArray(buffer.data() + 4); // ignoring prefix
- longPath[0] = longPath.at(0).toUpper(); // capital drive letters
- return QDir::fromNativeSeparators(longPath);
- } else {
- return QDir::fromNativeSeparators(strShortPath);
- }
-}
-#endif
-
-/*!
- \internal
-
- Given a path return the matching QFileSystemNode or &root if invalid
-*/
-QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QString &path, bool fetch) const
-{
- Q_Q(const QFileSystemModel);
- Q_UNUSED(q);
- if (path.isEmpty() || path == myComputer() || path.startsWith(QLatin1Char(':')))
- return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
-
- // Construct the nodes up to the new root path if they need to be built
- QString absolutePath;
-#ifdef Q_OS_WIN32
- QString longPath = qt_GetLongPathName(path);
-#else
- QString longPath = path;
-#endif
- if (longPath == rootDir.path())
- absolutePath = rootDir.absolutePath();
- else
- absolutePath = QDir(longPath).absolutePath();
-
- // ### TODO can we use bool QAbstractFileEngine::caseSensitive() const?
- QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts);
- if ((pathElements.isEmpty())
-#if !defined(Q_OS_WIN)
- && QDir::fromNativeSeparators(longPath) != QLatin1String("/")
-#endif
- )
- return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
- QModelIndex index = QModelIndex(); // start with "My Computer"
- QString elementPath;
- QChar separator = QLatin1Char('/');
- QString trailingSeparator;
-#if defined(Q_OS_WIN)
- if (absolutePath.startsWith(QLatin1String("//"))) { // UNC path
- QString host = QLatin1String("\\\\") + pathElements.constFirst();
- if (absolutePath == QDir::fromNativeSeparators(host))
- absolutePath.append(QLatin1Char('/'));
- if (longPath.endsWith(QLatin1Char('/')) && !absolutePath.endsWith(QLatin1Char('/')))
- absolutePath.append(QLatin1Char('/'));
- if (absolutePath.endsWith(QLatin1Char('/')))
- trailingSeparator = QLatin1String("\\");
- int r = 0;
- QFileSystemModelPrivate::QFileSystemNode *rootNode = const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
- if (!root.children.contains(host.toLower())) {
- if (pathElements.count() == 1 && !absolutePath.endsWith(QLatin1Char('/')))
- return rootNode;
- QFileInfo info(host);
- if (!info.exists())
- return rootNode;
- QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this);
- p->addNode(rootNode, host,info);
- p->addVisibleFiles(rootNode, QStringList(host));
- }
- r = rootNode->visibleLocation(host);
- r = translateVisibleLocation(rootNode, r);
- index = q->index(r, 0, QModelIndex());
- pathElements.pop_front();
- separator = QLatin1Char('\\');
- elementPath = host;
- elementPath.append(separator);
- } else {
- if (!pathElements.at(0).contains(QLatin1Char(':'))) {
- QString rootPath = QDir(longPath).rootPath();
- pathElements.prepend(rootPath);
- }
- if (pathElements.at(0).endsWith(QLatin1Char('/')))
- pathElements[0].chop(1);
- }
-#else
- // add the "/" item, since it is a valid path element on Unix
- if (absolutePath[0] == QLatin1Char('/'))
- pathElements.prepend(QLatin1String("/"));
-#endif
-
- QFileSystemModelPrivate::QFileSystemNode *parent = node(index);
-
- for (int i = 0; i < pathElements.count(); ++i) {
- QString element = pathElements.at(i);
- if (i != 0)
- elementPath.append(separator);
- elementPath.append(element);
- if (i == pathElements.count() - 1)
- elementPath.append(trailingSeparator);
-#ifdef Q_OS_WIN
- // On Windows, "filename " and "filename" are equivalent and
- // "filename . " and "filename" are equivalent
- // "filename......." and "filename" are equivalent Task #133928
- // whereas "filename .txt" is still "filename .txt"
- // If after stripping the characters there is nothing left then we
- // just return the parent directory as it is assumed that the path
- // is referring to the parent
- while (element.endsWith(QLatin1Char('.')) || element.endsWith(QLatin1Char(' ')))
- element.chop(1);
- // Only filenames that can't possibly exist will be end up being empty
- if (element.isEmpty())
- return parent;
-#endif
- bool alreadyExisted = parent->children.contains(element);
-
- // we couldn't find the path element, we create a new node since we
- // _know_ that the path is valid
- if (alreadyExisted) {
- if ((parent->children.count() == 0)
- || (parent->caseSensitive()
- && parent->children.value(element)->fileName != element)
- || (!parent->caseSensitive()
- && parent->children.value(element)->fileName.toLower() != element.toLower()))
- alreadyExisted = false;
- }
-
- QFileSystemModelPrivate::QFileSystemNode *node;
- if (!alreadyExisted) {
- // Someone might call ::index("file://cookie/monster/doesn't/like/veggies"),
- // a path that doesn't exists, I.E. don't blindly create directories.
- QFileInfo info(elementPath);
- if (!info.exists())
- return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
- QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this);
- node = p->addNode(parent, element,info);
-#if QT_CONFIG(filesystemwatcher)
- node->populate(fileInfoGatherer.getInfo(info));
-#endif
- } else {
- node = parent->children.value(element);
- }
-
- Q_ASSERT(node);
- if (!node->isVisible) {
- // It has been filtered out
- if (alreadyExisted && node->hasInformation() && !fetch)
- return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
-
- QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this);
- p->addVisibleFiles(parent, QStringList(element));
- if (!p->bypassFilters.contains(node))
- p->bypassFilters[node] = 1;
- QString dir = q->filePath(this->index(parent));
- if (!node->hasInformation() && fetch) {
- Fetching f = { std::move(dir), std::move(element), node };
- p->toFetch.append(std::move(f));
- p->fetchingTimer.start(0, const_cast<QFileSystemModel*>(q));
- }
- }
- parent = node;
- }
-
- return parent;
-}
-
-/*!
- \reimp
-*/
-void QFileSystemModel::timerEvent(QTimerEvent *event)
-{
- Q_D(QFileSystemModel);
- if (event->timerId() == d->fetchingTimer.timerId()) {
- d->fetchingTimer.stop();
-#if QT_CONFIG(filesystemwatcher)
- for (int i = 0; i < d->toFetch.count(); ++i) {
- const QFileSystemModelPrivate::QFileSystemNode *node = d->toFetch.at(i).node;
- if (!node->hasInformation()) {
- d->fileInfoGatherer.fetchExtendedInformation(d->toFetch.at(i).dir,
- QStringList(d->toFetch.at(i).file));
- } else {
- // qDebug("yah!, you saved a little gerbil soul");
- }
- }
-#endif
- d->toFetch.clear();
- }
-}
-
-/*!
- Returns \c true if the model item \a index represents a directory;
- otherwise returns \c false.
-*/
-bool QFileSystemModel::isDir(const QModelIndex &index) const
-{
- // This function is for public usage only because it could create a file info
- Q_D(const QFileSystemModel);
- if (!index.isValid())
- return true;
- QFileSystemModelPrivate::QFileSystemNode *n = d->node(index);
- if (n->hasInformation())
- return n->isDir();
- return fileInfo(index).isDir();
-}
-
-/*!
- Returns the size in bytes of \a index. If the file does not exist, 0 is returned.
- */
-qint64 QFileSystemModel::size(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- if (!index.isValid())
- return 0;
- return d->node(index)->size();
-}
-
-/*!
- Returns the type of file \a index such as "Directory" or "JPEG file".
- */
-QString QFileSystemModel::type(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- if (!index.isValid())
- return QString();
- return d->node(index)->type();
-}
-
-/*!
- Returns the date and time when \a index was last modified.
- */
-QDateTime QFileSystemModel::lastModified(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- if (!index.isValid())
- return QDateTime();
- return d->node(index)->lastModified();
-}
-
-/*!
- \reimp
-*/
-QModelIndex QFileSystemModel::parent(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- if (!d->indexValid(index))
- return QModelIndex();
-
- QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(index);
- Q_ASSERT(indexNode != nullptr);
- QFileSystemModelPrivate::QFileSystemNode *parentNode = indexNode->parent;
- if (parentNode == nullptr || parentNode == &d->root)
- return QModelIndex();
-
- // get the parent's row
- QFileSystemModelPrivate::QFileSystemNode *grandParentNode = parentNode->parent;
- Q_ASSERT(grandParentNode->children.contains(parentNode->fileName));
- int visualRow = d->translateVisibleLocation(grandParentNode, grandParentNode->visibleLocation(grandParentNode->children.value(parentNode->fileName)->fileName));
- if (visualRow == -1)
- return QModelIndex();
- return createIndex(visualRow, 0, parentNode);
-}
-
-/*
- \internal
-
- return the index for node
-*/
-QModelIndex QFileSystemModelPrivate::index(const QFileSystemModelPrivate::QFileSystemNode *node, int column) const
-{
- Q_Q(const QFileSystemModel);
- QFileSystemModelPrivate::QFileSystemNode *parentNode = (node ? node->parent : nullptr);
- if (node == &root || !parentNode)
- return QModelIndex();
-
- // get the parent's row
- Q_ASSERT(node);
- if (!node->isVisible)
- return QModelIndex();
-
- int visualRow = translateVisibleLocation(parentNode, parentNode->visibleLocation(node->fileName));
- return q->createIndex(visualRow, column, const_cast<QFileSystemNode*>(node));
-}
-
-/*!
- \reimp
-*/
-bool QFileSystemModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QFileSystemModel);
- if (parent.column() > 0)
- return false;
-
- if (!parent.isValid()) // drives
- return true;
-
- const QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent);
- Q_ASSERT(indexNode);
- return (indexNode->isDir());
-}
-
-/*!
- \reimp
- */
-bool QFileSystemModel::canFetchMore(const QModelIndex &parent) const
-{
- Q_D(const QFileSystemModel);
- const QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent);
- return (!indexNode->populatedChildren);
-}
-
-/*!
- \reimp
- */
-void QFileSystemModel::fetchMore(const QModelIndex &parent)
-{
- Q_D(QFileSystemModel);
- if (!d->setRootPath)
- return;
- QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent);
- if (indexNode->populatedChildren)
- return;
- indexNode->populatedChildren = true;
-#if QT_CONFIG(filesystemwatcher)
- d->fileInfoGatherer.list(filePath(parent));
-#endif
-}
-
-/*!
- \reimp
-*/
-int QFileSystemModel::rowCount(const QModelIndex &parent) const
-{
- Q_D(const QFileSystemModel);
- if (parent.column() > 0)
- return 0;
-
- if (!parent.isValid())
- return d->root.visibleChildren.count();
-
- const QFileSystemModelPrivate::QFileSystemNode *parentNode = d->node(parent);
- return parentNode->visibleChildren.count();
-}
-
-/*!
- \reimp
-*/
-int QFileSystemModel::columnCount(const QModelIndex &parent) const
-{
- return (parent.column() > 0) ? 0 : QFileSystemModelPrivate::NumColumns;
-}
-
-/*!
- Returns the data stored under the given \a role for the item "My Computer".
-
- \sa Qt::ItemDataRole
- */
-QVariant QFileSystemModel::myComputer(int role) const
-{
-#if QT_CONFIG(filesystemwatcher)
- Q_D(const QFileSystemModel);
-#endif
- switch (role) {
- case Qt::DisplayRole:
- return QFileSystemModelPrivate::myComputer();
-#if QT_CONFIG(filesystemwatcher)
- case Qt::DecorationRole:
- return d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::Computer);
-#endif
- }
- return QVariant();
-}
-
-/*!
- \reimp
-*/
-QVariant QFileSystemModel::data(const QModelIndex &index, int role) const
-{
- Q_D(const QFileSystemModel);
- if (!index.isValid() || index.model() != this)
- return QVariant();
-
- switch (role) {
- case Qt::EditRole:
- case Qt::DisplayRole:
- switch (index.column()) {
- case 0: return d->displayName(index);
- case 1: return d->size(index);
- case 2: return d->type(index);
- case 3: return d->time(index);
- default:
- qWarning("data: invalid display value column %d", index.column());
- break;
- }
- break;
- case FilePathRole:
- return filePath(index);
- case FileNameRole:
- return d->name(index);
- case Qt::DecorationRole:
- if (index.column() == 0) {
- QIcon icon = d->icon(index);
-#if QT_CONFIG(filesystemwatcher)
- if (icon.isNull()) {
- if (d->node(index)->isDir())
- icon = d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::Folder);
- else
- icon = d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::File);
- }
-#endif // filesystemwatcher
- return icon;
- }
- break;
- case Qt::TextAlignmentRole:
- if (index.column() == 1)
- return QVariant(Qt::AlignTrailing | Qt::AlignVCenter);
- break;
- case FilePermissions:
- int p = permissions(index);
- return p;
- }
-
- return QVariant();
-}
-
-/*!
- \internal
-*/
-QString QFileSystemModelPrivate::size(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QString();
- const QFileSystemNode *n = node(index);
- if (n->isDir()) {
-#ifdef Q_OS_MAC
- return QLatin1String("--");
-#else
- return QLatin1String("");
-#endif
- // Windows - ""
- // OS X - "--"
- // Konqueror - "4 KB"
- // Nautilus - "9 items" (the number of children)
- }
- return size(n->size());
-}
-
-QString QFileSystemModelPrivate::size(qint64 bytes)
-{
- return QLocale::system().formattedDataSize(bytes);
-}
-
-/*!
- \internal
-*/
-QString QFileSystemModelPrivate::time(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QString();
-#if QT_CONFIG(datestring)
- return node(index)->lastModified().toString(Qt::SystemLocaleDate);
-#else
- Q_UNUSED(index);
- return QString();
-#endif
-}
-
-/*
- \internal
-*/
-QString QFileSystemModelPrivate::type(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QString();
- return node(index)->type();
-}
-
-/*!
- \internal
-*/
-QString QFileSystemModelPrivate::name(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QString();
- QFileSystemNode *dirNode = node(index);
- if (
-#if QT_CONFIG(filesystemwatcher)
- fileInfoGatherer.resolveSymlinks() &&
-#endif
- !resolvedSymLinks.isEmpty() && dirNode->isSymLink(/* ignoreNtfsSymLinks = */ true)) {
- QString fullPath = QDir::fromNativeSeparators(filePath(index));
- return resolvedSymLinks.value(fullPath, dirNode->fileName);
- }
- return dirNode->fileName;
-}
-
-/*!
- \internal
-*/
-QString QFileSystemModelPrivate::displayName(const QModelIndex &index) const
-{
-#if defined(Q_OS_WIN)
- QFileSystemNode *dirNode = node(index);
- if (!dirNode->volumeName.isEmpty())
- return dirNode->volumeName;
-#endif
- return name(index);
-}
-
-/*!
- \internal
-*/
-QIcon QFileSystemModelPrivate::icon(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QIcon();
- return node(index)->icon();
-}
-
-static void displayRenameFailedMessage(const QString &newName)
-{
-#if QT_CONFIG(messagebox)
- const QString message =
- QFileSystemModel::tr("<b>The name \"%1\" cannot be used.</b>"
- "<p>Try using another name, with fewer characters or no punctuation marks.")
- .arg(newName);
- QMessageBox::information(nullptr, QFileSystemModel::tr("Invalid filename"),
- message, QMessageBox::Ok);
-#else
- Q_UNUSED(newName)
-#endif // QT_CONFIG(messagebox)
-}
-
-/*!
- \reimp
-*/
-bool QFileSystemModel::setData(const QModelIndex &idx, const QVariant &value, int role)
-{
- Q_D(QFileSystemModel);
- if (!idx.isValid()
- || idx.column() != 0
- || role != Qt::EditRole
- || (flags(idx) & Qt::ItemIsEditable) == 0) {
- return false;
- }
-
- QString newName = value.toString();
- QString oldName = idx.data().toString();
- if (newName == oldName)
- return true;
-
- const QString parentPath = filePath(parent(idx));
-
- if (newName.isEmpty() || QDir::toNativeSeparators(newName).contains(QDir::separator())) {
- displayRenameFailedMessage(newName);
- return false;
- }
-
-#if QT_CONFIG(filesystemwatcher) && defined(Q_OS_WIN)
- // QTBUG-65683: Remove file system watchers prior to renaming to prevent
- // failure due to locked files on Windows.
- const QStringList watchedPaths = d->unwatchPathsAt(idx);
-#endif // filesystemwatcher && Q_OS_WIN
- if (!QDir(parentPath).rename(oldName, newName)) {
-#if QT_CONFIG(filesystemwatcher) && defined(Q_OS_WIN)
- d->watchPaths(watchedPaths);
-#endif
- displayRenameFailedMessage(newName);
- return false;
- } else {
- /*
- *After re-naming something we don't want the selection to change*
- - can't remove rows and later insert
- - can't quickly remove and insert
- - index pointer can't change because treeview doesn't use persistant index's
-
- - if this get any more complicated think of changing it to just
- use layoutChanged
- */
-
- QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(idx);
- QFileSystemModelPrivate::QFileSystemNode *parentNode = indexNode->parent;
- int visibleLocation = parentNode->visibleLocation(parentNode->children.value(indexNode->fileName)->fileName);
-
- parentNode->visibleChildren.removeAt(visibleLocation);
- QScopedPointer<QFileSystemModelPrivate::QFileSystemNode> nodeToRename(parentNode->children.take(oldName));
- nodeToRename->fileName = newName;
- nodeToRename->parent = parentNode;
-#if QT_CONFIG(filesystemwatcher)
- nodeToRename->populate(d->fileInfoGatherer.getInfo(QFileInfo(parentPath, newName)));
-#endif
- nodeToRename->isVisible = true;
- parentNode->children[newName] = nodeToRename.take();
- parentNode->visibleChildren.insert(visibleLocation, newName);
-
- d->delayedSort();
- emit fileRenamed(parentPath, oldName, newName);
- }
- return true;
-}
-
-/*!
- \reimp
-*/
-QVariant QFileSystemModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- switch (role) {
- case Qt::DecorationRole:
- if (section == 0) {
- // ### TODO oh man this is ugly and doesn't even work all the way!
- // it is still 2 pixels off
- QImage pixmap(16, 1, QImage::Format_ARGB32_Premultiplied);
- pixmap.fill(Qt::transparent);
- return pixmap;
- }
- break;
- case Qt::TextAlignmentRole:
- return Qt::AlignLeft;
- }
-
- if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
- return QAbstractItemModel::headerData(section, orientation, role);
-
- QString returnValue;
- switch (section) {
- case 0: returnValue = tr("Name");
- break;
- case 1: returnValue = tr("Size");
- break;
- case 2: returnValue =
-#ifdef Q_OS_MAC
- tr("Kind", "Match OS X Finder");
-#else
- tr("Type", "All other platforms");
-#endif
- break;
- // Windows - Type
- // OS X - Kind
- // Konqueror - File Type
- // Nautilus - Type
- case 3: returnValue = tr("Date Modified");
- break;
- default: return QVariant();
- }
- return returnValue;
-}
-
-/*!
- \reimp
-*/
-Qt::ItemFlags QFileSystemModel::flags(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (!index.isValid())
- return flags;
-
- QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(index);
- if (d->nameFilterDisables && !d->passNameFilters(indexNode)) {
- flags &= ~Qt::ItemIsEnabled;
- // ### TODO you shouldn't be able to set this as the current item, task 119433
- return flags;
- }
-
- flags |= Qt::ItemIsDragEnabled;
- if (d->readOnly)
- return flags;
- if ((index.column() == 0) && indexNode->permissions() & QFile::WriteUser) {
- flags |= Qt::ItemIsEditable;
- if (indexNode->isDir())
- flags |= Qt::ItemIsDropEnabled;
- else
- flags |= Qt::ItemNeverHasChildren;
- }
- return flags;
-}
-
-/*!
- \internal
-*/
-void QFileSystemModelPrivate::_q_performDelayedSort()
-{
- Q_Q(QFileSystemModel);
- q->sort(sortColumn, sortOrder);
-}
-
-
-/*
- \internal
- Helper functor used by sort()
-*/
-class QFileSystemModelSorter
-{
-public:
- inline QFileSystemModelSorter(int column) : sortColumn(column)
- {
- naturalCompare.setNumericMode(true);
- naturalCompare.setCaseSensitivity(Qt::CaseInsensitive);
- }
-
- bool compareNodes(const QFileSystemModelPrivate::QFileSystemNode *l,
- const QFileSystemModelPrivate::QFileSystemNode *r) const
- {
- switch (sortColumn) {
- case 0: {
-#ifndef Q_OS_MAC
- // place directories before files
- bool left = l->isDir();
- bool right = r->isDir();
- if (left ^ right)
- return left;
-#endif
- return naturalCompare.compare(l->fileName, r->fileName) < 0;
- }
- case 1:
- {
- // Directories go first
- bool left = l->isDir();
- bool right = r->isDir();
- if (left ^ right)
- return left;
-
- qint64 sizeDifference = l->size() - r->size();
- if (sizeDifference == 0)
- return naturalCompare.compare(l->fileName, r->fileName) < 0;
-
- return sizeDifference < 0;
- }
- case 2:
- {
- int compare = naturalCompare.compare(l->type(), r->type());
- if (compare == 0)
- return naturalCompare.compare(l->fileName, r->fileName) < 0;
-
- return compare < 0;
- }
- case 3:
- {
- if (l->lastModified() == r->lastModified())
- return naturalCompare.compare(l->fileName, r->fileName) < 0;
-
- return l->lastModified() < r->lastModified();
- }
- }
- Q_ASSERT(false);
- return false;
- }
-
- bool operator()(const QFileSystemModelPrivate::QFileSystemNode *l,
- const QFileSystemModelPrivate::QFileSystemNode *r) const
- {
- return compareNodes(l, r);
- }
-
-
-private:
- QCollator naturalCompare;
- int sortColumn;
-};
-
-/*
- \internal
-
- Sort all of the children of parent
-*/
-void QFileSystemModelPrivate::sortChildren(int column, const QModelIndex &parent)
-{
- Q_Q(QFileSystemModel);
- QFileSystemModelPrivate::QFileSystemNode *indexNode = node(parent);
- if (indexNode->children.count() == 0)
- return;
-
- QVector<QFileSystemModelPrivate::QFileSystemNode*> values;
-
- for (auto iterator = indexNode->children.constBegin(), cend = indexNode->children.constEnd(); iterator != cend; ++iterator) {
- if (filtersAcceptsNode(iterator.value())) {
- values.append(iterator.value());
- } else {
- iterator.value()->isVisible = false;
- }
- }
- QFileSystemModelSorter ms(column);
- std::sort(values.begin(), values.end(), ms);
- // First update the new visible list
- indexNode->visibleChildren.clear();
- //No more dirty item we reset our internal dirty index
- indexNode->dirtyChildrenIndex = -1;
- const int numValues = values.count();
- indexNode->visibleChildren.reserve(numValues);
- for (int i = 0; i < numValues; ++i) {
- indexNode->visibleChildren.append(values.at(i)->fileName);
- values.at(i)->isVisible = true;
- }
-
- if (!disableRecursiveSort) {
- for (int i = 0; i < q->rowCount(parent); ++i) {
- const QModelIndex childIndex = q->index(i, 0, parent);
- QFileSystemModelPrivate::QFileSystemNode *indexNode = node(childIndex);
- //Only do a recursive sort on visible nodes
- if (indexNode->isVisible)
- sortChildren(column, childIndex);
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QFileSystemModel::sort(int column, Qt::SortOrder order)
-{
- Q_D(QFileSystemModel);
- if (d->sortOrder == order && d->sortColumn == column && !d->forceSort)
- return;
-
- emit layoutAboutToBeChanged();
- QModelIndexList oldList = persistentIndexList();
- QVector<QPair<QFileSystemModelPrivate::QFileSystemNode*, int> > oldNodes;
- const int nodeCount = oldList.count();
- oldNodes.reserve(nodeCount);
- for (int i = 0; i < nodeCount; ++i) {
- const QModelIndex &oldNode = oldList.at(i);
- QPair<QFileSystemModelPrivate::QFileSystemNode*, int> pair(d->node(oldNode), oldNode.column());
- oldNodes.append(pair);
- }
-
- if (!(d->sortColumn == column && d->sortOrder != order && !d->forceSort)) {
- //we sort only from where we are, don't need to sort all the model
- d->sortChildren(column, index(rootPath()));
- d->sortColumn = column;
- d->forceSort = false;
- }
- d->sortOrder = order;
-
- QModelIndexList newList;
- const int numOldNodes = oldNodes.size();
- newList.reserve(numOldNodes);
- for (int i = 0; i < numOldNodes; ++i) {
- const QPair<QFileSystemModelPrivate::QFileSystemNode*, int> &oldNode = oldNodes.at(i);
- newList.append(d->index(oldNode.first, oldNode.second));
- }
- changePersistentIndexList(oldList, newList);
- emit layoutChanged();
-}
-
-/*!
- Returns a list of MIME types that can be used to describe a list of items
- in the model.
-*/
-QStringList QFileSystemModel::mimeTypes() const
-{
- return QStringList(QLatin1String("text/uri-list"));
-}
-
-/*!
- Returns an object that contains a serialized description of the specified
- \a indexes. The format used to describe the items corresponding to the
- indexes is obtained from the mimeTypes() function.
-
- If the list of indexes is empty, \nullptr is returned rather than a
- serialized empty list.
-*/
-QMimeData *QFileSystemModel::mimeData(const QModelIndexList &indexes) const
-{
- QList<QUrl> urls;
- QList<QModelIndex>::const_iterator it = indexes.begin();
- for (; it != indexes.end(); ++it)
- if ((*it).column() == 0)
- urls << QUrl::fromLocalFile(filePath(*it));
- QMimeData *data = new QMimeData();
- data->setUrls(urls);
- return data;
-}
-
-/*!
- Handles the \a data supplied by a drag and drop operation that ended with
- the given \a action over the row in the model specified by the \a row and
- \a column and by the \a parent index. Returns true if the operation was
- successful.
-
- \sa supportedDropActions()
-*/
-bool QFileSystemModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent)
-{
- Q_UNUSED(row);
- Q_UNUSED(column);
- if (!parent.isValid() || isReadOnly())
- return false;
-
- bool success = true;
- QString to = filePath(parent) + QDir::separator();
-
- QList<QUrl> urls = data->urls();
- QList<QUrl>::const_iterator it = urls.constBegin();
-
- switch (action) {
- case Qt::CopyAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::copy(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- case Qt::LinkAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::link(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- case Qt::MoveAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::rename(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- default:
- return false;
- }
-
- return success;
-}
-
-/*!
- \reimp
-*/
-Qt::DropActions QFileSystemModel::supportedDropActions() const
-{
- return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction;
-}
-
-/*!
- \enum QFileSystemModel::Option
- \since 5.14
-
- \value DontWatchForChanges Do not add file watchers to the paths.
- This reduces overhead when using the model for simple tasks
- like line edit completion.
-
- \value DontResolveSymlinks Don't resolve symlinks in the file
- system model. By default, symlinks are resolved.
-
- \value DontUseCustomDirectoryIcons Always use the default directory icon.
- Some platforms allow the user to set a different icon. Custom icon lookup
- causes a big performance impact over network or removable drives.
- This sets the QFileIconProvider::DontUseCustomDirectoryIcons
- option in the icon provider accordingly.
-
- \sa resolveSymlinks
-*/
-
-/*!
- \since 5.14
- Sets the given \a option to be enabled if \a on is true; otherwise,
- clears the given \a option.
-
- Options should be set before changing properties.
-
- \sa options, testOption()
-*/
-void QFileSystemModel::setOption(Option option, bool on)
-{
- QFileSystemModel::Options previousOptions = options();
- setOptions(previousOptions.setFlag(option, on));
-}
-
-/*!
- \since 5.14
-
- Returns \c true if the given \a option is enabled; otherwise, returns
- false.
-
- \sa options, setOption()
-*/
-bool QFileSystemModel::testOption(Option option) const
-{
- return options().testFlag(option);
-}
-
-/*!
- \property QFileSystemModel::options
- \brief the various options that affect the model
- \since 5.14
-
- By default, all options are disabled.
-
- Options should be set before changing properties.
-
- \sa setOption(), testOption()
-*/
-void QFileSystemModel::setOptions(Options options)
-{
- const Options changed = (options ^ QFileSystemModel::options());
-
- if (changed.testFlag(DontResolveSymlinks))
- setResolveSymlinks(!options.testFlag(DontResolveSymlinks));
-
-#if QT_CONFIG(filesystemwatcher)
- Q_D(QFileSystemModel);
- if (changed.testFlag(DontWatchForChanges))
- d->fileInfoGatherer.setWatching(!options.testFlag(DontWatchForChanges));
-#endif
-
- if (changed.testFlag(DontUseCustomDirectoryIcons)) {
- if (auto provider = iconProvider()) {
- QFileIconProvider::Options providerOptions = provider->options();
- providerOptions.setFlag(QFileIconProvider::DontUseCustomDirectoryIcons,
- options.testFlag(QFileSystemModel::DontUseCustomDirectoryIcons));
- provider->setOptions(providerOptions);
- } else {
- qWarning("Setting QFileSystemModel::DontUseCustomDirectoryIcons has no effect when no provider is used");
- }
- }
-}
-
-QFileSystemModel::Options QFileSystemModel::options() const
-{
- QFileSystemModel::Options result;
- result.setFlag(DontResolveSymlinks, !resolveSymlinks());
-#if QT_CONFIG(filesystemwatcher)
- Q_D(const QFileSystemModel);
- result.setFlag(DontWatchForChanges, !d->fileInfoGatherer.isWatching());
-#else
- result.setFlag(DontWatchForChanges);
-#endif
- if (auto provider = iconProvider()) {
- result.setFlag(DontUseCustomDirectoryIcons,
- provider->options().testFlag(QFileIconProvider::DontUseCustomDirectoryIcons));
- }
- return result;
-}
-
-/*!
- Returns the path of the item stored in the model under the
- \a index given.
-*/
-QString QFileSystemModel::filePath(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- QString fullPath = d->filePath(index);
- QFileSystemModelPrivate::QFileSystemNode *dirNode = d->node(index);
- if (dirNode->isSymLink()
-#if QT_CONFIG(filesystemwatcher)
- && d->fileInfoGatherer.resolveSymlinks()
-#endif
- && d->resolvedSymLinks.contains(fullPath)
- && dirNode->isDir()) {
- QFileInfo resolvedInfo(fullPath);
- resolvedInfo = resolvedInfo.canonicalFilePath();
- if (resolvedInfo.exists())
- return resolvedInfo.filePath();
- }
- return fullPath;
-}
-
-QString QFileSystemModelPrivate::filePath(const QModelIndex &index) const
-{
- Q_Q(const QFileSystemModel);
- Q_UNUSED(q);
- if (!index.isValid())
- return QString();
- Q_ASSERT(index.model() == q);
-
- QStringList path;
- QModelIndex idx = index;
- while (idx.isValid()) {
- QFileSystemModelPrivate::QFileSystemNode *dirNode = node(idx);
- if (dirNode)
- path.prepend(dirNode->fileName);
- idx = idx.parent();
- }
- QString fullPath = QDir::fromNativeSeparators(path.join(QDir::separator()));
-#if !defined(Q_OS_WIN)
- if ((fullPath.length() > 2) && fullPath[0] == QLatin1Char('/') && fullPath[1] == QLatin1Char('/'))
- fullPath = fullPath.mid(1);
-#else
- if (fullPath.length() == 2 && fullPath.endsWith(QLatin1Char(':')))
- fullPath.append(QLatin1Char('/'));
-#endif
- return fullPath;
-}
-
-/*!
- Create a directory with the \a name in the \a parent model index.
-*/
-QModelIndex QFileSystemModel::mkdir(const QModelIndex &parent, const QString &name)
-{
- Q_D(QFileSystemModel);
- if (!parent.isValid())
- return parent;
-
- QDir dir(filePath(parent));
- if (!dir.mkdir(name))
- return QModelIndex();
- QFileSystemModelPrivate::QFileSystemNode *parentNode = d->node(parent);
- d->addNode(parentNode, name, QFileInfo());
- Q_ASSERT(parentNode->children.contains(name));
- QFileSystemModelPrivate::QFileSystemNode *node = parentNode->children[name];
-#if QT_CONFIG(filesystemwatcher)
- node->populate(d->fileInfoGatherer.getInfo(QFileInfo(dir.absolutePath() + QDir::separator() + name)));
-#endif
- d->addVisibleFiles(parentNode, QStringList(name));
- return d->index(node);
-}
-
-/*!
- Returns the complete OR-ed together combination of QFile::Permission for the \a index.
- */
-QFile::Permissions QFileSystemModel::permissions(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- return d->node(index)->permissions();
-}
-
-/*!
- Sets the directory that is being watched by the model to \a newPath by
- installing a \l{QFileSystemWatcher}{file system watcher} on it. Any
- changes to files and directories within this directory will be
- reflected in the model.
-
- If the path is changed, the rootPathChanged() signal will be emitted.
-
- \note This function does not change the structure of the model or
- modify the data available to views. In other words, the "root" of
- the model is \e not changed to include only files and directories
- within the directory specified by \a newPath in the file system.
- */
-QModelIndex QFileSystemModel::setRootPath(const QString &newPath)
-{
- Q_D(QFileSystemModel);
-#ifdef Q_OS_WIN
-#ifdef Q_OS_WIN32
- QString longNewPath = qt_GetLongPathName(newPath);
-#else
- QString longNewPath = QDir::fromNativeSeparators(newPath);
-#endif
-#else
- QString longNewPath = newPath;
-#endif
- QDir newPathDir(longNewPath);
- //we remove .. and . from the given path if exist
- if (!newPath.isEmpty()) {
- longNewPath = QDir::cleanPath(longNewPath);
- newPathDir.setPath(longNewPath);
- }
-
- d->setRootPath = true;
-
- //user don't ask for the root path ("") but the conversion failed
- if (!newPath.isEmpty() && longNewPath.isEmpty())
- return d->index(rootPath());
-
- if (d->rootDir.path() == longNewPath)
- return d->index(rootPath());
-
- bool showDrives = (longNewPath.isEmpty() || longNewPath == QFileSystemModelPrivate::myComputer());
- if (!showDrives && !newPathDir.exists())
- return d->index(rootPath());
-
- //We remove the watcher on the previous path
- if (!rootPath().isEmpty() && rootPath() != QLatin1String(".")) {
- //This remove the watcher for the old rootPath
-#if QT_CONFIG(filesystemwatcher)
- d->fileInfoGatherer.removePath(rootPath());
-#endif
- //This line "marks" the node as dirty, so the next fetchMore
- //call on the path will ask the gatherer to install a watcher again
- //But it doesn't re-fetch everything
- d->node(rootPath())->populatedChildren = false;
- }
-
- // We have a new valid root path
- d->rootDir = newPathDir;
- QModelIndex newRootIndex;
- if (showDrives) {
- // otherwise dir will become '.'
- d->rootDir.setPath(QLatin1String(""));
- } else {
- newRootIndex = d->index(newPathDir.path());
- }
- fetchMore(newRootIndex);
- emit rootPathChanged(longNewPath);
- d->forceSort = true;
- d->delayedSort();
- return newRootIndex;
-}
-
-/*!
- The currently set root path
-
- \sa rootDirectory()
-*/
-QString QFileSystemModel::rootPath() const
-{
- Q_D(const QFileSystemModel);
- return d->rootDir.path();
-}
-
-/*!
- The currently set directory
-
- \sa rootPath()
-*/
-QDir QFileSystemModel::rootDirectory() const
-{
- Q_D(const QFileSystemModel);
- QDir dir(d->rootDir);
- dir.setNameFilters(nameFilters());
- dir.setFilter(filter());
- return dir;
-}
-
-/*!
- Sets the \a provider of file icons for the directory model.
-*/
-void QFileSystemModel::setIconProvider(QFileIconProvider *provider)
-{
- Q_D(QFileSystemModel);
-#if QT_CONFIG(filesystemwatcher)
- d->fileInfoGatherer.setIconProvider(provider);
-#endif
- d->root.updateIcon(provider, QString());
-}
-
-/*!
- Returns the file icon provider for this directory model.
-*/
-QFileIconProvider *QFileSystemModel::iconProvider() const
-{
-#if QT_CONFIG(filesystemwatcher)
- Q_D(const QFileSystemModel);
- return d->fileInfoGatherer.iconProvider();
-#else
- return 0;
-#endif
-}
-
-/*!
- Sets the directory model's filter to that specified by \a filters.
-
- Note that the filter you set should always include the QDir::AllDirs enum value,
- otherwise QFileSystemModel won't be able to read the directory structure.
-
- \sa QDir::Filters
-*/
-void QFileSystemModel::setFilter(QDir::Filters filters)
-{
- Q_D(QFileSystemModel);
- if (d->filters == filters)
- return;
- d->filters = filters;
- // CaseSensitivity might have changed
- setNameFilters(nameFilters());
- d->forceSort = true;
- d->delayedSort();
-}
-
-/*!
- Returns the filter specified for the directory model.
-
- If a filter has not been set, the default filter is QDir::AllEntries |
- QDir::NoDotAndDotDot | QDir::AllDirs.
-
- \sa QDir::Filters
-*/
-QDir::Filters QFileSystemModel::filter() const
-{
- Q_D(const QFileSystemModel);
- return d->filters;
-}
-
-/*!
- \property QFileSystemModel::resolveSymlinks
- \brief Whether the directory model should resolve symbolic links
-
- This is only relevant on Windows.
-
- By default, this property is \c true.
-
- \sa QFileSystemModel::Options
-*/
-void QFileSystemModel::setResolveSymlinks(bool enable)
-{
-#if QT_CONFIG(filesystemwatcher)
- Q_D(QFileSystemModel);
- d->fileInfoGatherer.setResolveSymlinks(enable);
-#else
- Q_UNUSED(enable)
-#endif
-}
-
-bool QFileSystemModel::resolveSymlinks() const
-{
-#if QT_CONFIG(filesystemwatcher)
- Q_D(const QFileSystemModel);
- return d->fileInfoGatherer.resolveSymlinks();
-#else
- return false;
-#endif
-}
-
-/*!
- \property QFileSystemModel::readOnly
- \brief Whether the directory model allows writing to the file system
-
- If this property is set to false, the directory model will allow renaming, copying
- and deleting of files and directories.
-
- This property is \c true by default
-*/
-void QFileSystemModel::setReadOnly(bool enable)
-{
- Q_D(QFileSystemModel);
- d->readOnly = enable;
-}
-
-bool QFileSystemModel::isReadOnly() const
-{
- Q_D(const QFileSystemModel);
- return d->readOnly;
-}
-
-/*!
- \property QFileSystemModel::nameFilterDisables
- \brief Whether files that don't pass the name filter are hidden or disabled
-
- This property is \c true by default
-*/
-void QFileSystemModel::setNameFilterDisables(bool enable)
-{
- Q_D(QFileSystemModel);
- if (d->nameFilterDisables == enable)
- return;
- d->nameFilterDisables = enable;
- d->forceSort = true;
- d->delayedSort();
-}
-
-bool QFileSystemModel::nameFilterDisables() const
-{
- Q_D(const QFileSystemModel);
- return d->nameFilterDisables;
-}
-
-/*!
- Sets the name \a filters to apply against the existing files.
-*/
-void QFileSystemModel::setNameFilters(const QStringList &filters)
-{
- // Prep the regexp's ahead of time
-#if QT_CONFIG(regularexpression)
- Q_D(QFileSystemModel);
-
- if (!d->bypassFilters.isEmpty()) {
- // update the bypass filter to only bypass the stuff that must be kept around
- d->bypassFilters.clear();
- // We guarantee that rootPath will stick around
- QPersistentModelIndex root(index(rootPath()));
- const QModelIndexList persistentList = persistentIndexList();
- for (const auto &persistentIndex : persistentList) {
- QFileSystemModelPrivate::QFileSystemNode *node = d->node(persistentIndex);
- while (node) {
- if (d->bypassFilters.contains(node))
- break;
- if (node->isDir())
- d->bypassFilters[node] = true;
- node = node->parent;
- }
- }
- }
-
- d->nameFilters = filters;
- d->forceSort = true;
- d->delayedSort();
-#endif
-}
-
-/*!
- Returns a list of filters applied to the names in the model.
-*/
-QStringList QFileSystemModel::nameFilters() const
-{
-#if QT_CONFIG(regularexpression)
- Q_D(const QFileSystemModel);
- return d->nameFilters;
-#else
- return QStringList();
-#endif
-}
-
-/*!
- \reimp
-*/
-bool QFileSystemModel::event(QEvent *event)
-{
-#if QT_CONFIG(filesystemwatcher)
- Q_D(QFileSystemModel);
- if (event->type() == QEvent::LanguageChange) {
- d->root.retranslateStrings(d->fileInfoGatherer.iconProvider(), QString());
- return true;
- }
-#endif
- return QAbstractItemModel::event(event);
-}
-
-bool QFileSystemModel::rmdir(const QModelIndex &aindex)
-{
- QString path = filePath(aindex);
- const bool success = QDir().rmdir(path);
-#if QT_CONFIG(filesystemwatcher)
- if (success) {
- QFileSystemModelPrivate * d = const_cast<QFileSystemModelPrivate*>(d_func());
- d->fileInfoGatherer.removePath(path);
- }
-#endif
- return success;
-}
-
-/*!
- \internal
-
- Performed quick listing and see if any files have been added or removed,
- then fetch more information on visible files.
- */
-void QFileSystemModelPrivate::_q_directoryChanged(const QString &directory, const QStringList &files)
-{
- QFileSystemModelPrivate::QFileSystemNode *parentNode = node(directory, false);
- if (parentNode->children.count() == 0)
- return;
- QStringList toRemove;
- QStringList newFiles = files;
- std::sort(newFiles.begin(), newFiles.end());
- for (auto i = parentNode->children.constBegin(), cend = parentNode->children.constEnd(); i != cend; ++i) {
- QStringList::iterator iterator = std::lower_bound(newFiles.begin(), newFiles.end(), i.value()->fileName);
- if ((iterator == newFiles.end()) || (i.value()->fileName < *iterator))
- toRemove.append(i.value()->fileName);
- }
- for (int i = 0 ; i < toRemove.count() ; ++i )
- removeNode(parentNode, toRemove[i]);
-}
-
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
-static QString volumeName(const QString &path)
-{
- IShellItem *item = nullptr;
- const QString native = QDir::toNativeSeparators(path);
- HRESULT hr = SHCreateItemFromParsingName(reinterpret_cast<const wchar_t *>(native.utf16()),
- nullptr, IID_IShellItem,
- reinterpret_cast<void **>(&item));
- if (FAILED(hr))
- return QString();
- LPWSTR name = nullptr;
- hr = item->GetDisplayName(SIGDN_NORMALDISPLAY, &name);
- if (FAILED(hr))
- return QString();
- QString result = QString::fromWCharArray(name);
- CoTaskMemFree(name);
- item->Release();
- return result;
-}
-#endif // Q_OS_WIN && !Q_OS_WINRT
-
-/*!
- \internal
-
- Adds a new file to the children of parentNode
-
- *WARNING* this will change the count of children
-*/
-QFileSystemModelPrivate::QFileSystemNode* QFileSystemModelPrivate::addNode(QFileSystemNode *parentNode, const QString &fileName, const QFileInfo& info)
-{
- // In the common case, itemLocation == count() so check there first
- QFileSystemModelPrivate::QFileSystemNode *node = new QFileSystemModelPrivate::QFileSystemNode(fileName, parentNode);
-#if QT_CONFIG(filesystemwatcher)
- node->populate(info);
-#else
- Q_UNUSED(info)
-#endif
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
- //The parentNode is "" so we are listing the drives
- if (parentNode->fileName.isEmpty())
- node->volumeName = volumeName(fileName);
-#endif
- Q_ASSERT(!parentNode->children.contains(fileName));
- parentNode->children.insert(fileName, node);
- return node;
-}
-
-/*!
- \internal
-
- File at parentNode->children(itemLocation) has been removed, remove from the lists
- and emit signals if necessary
-
- *WARNING* this will change the count of children and could change visibleChildren
- */
-void QFileSystemModelPrivate::removeNode(QFileSystemModelPrivate::QFileSystemNode *parentNode, const QString& name)
-{
- Q_Q(QFileSystemModel);
- QModelIndex parent = index(parentNode);
- bool indexHidden = isHiddenByFilter(parentNode, parent);
-
- int vLocation = parentNode->visibleLocation(name);
- if (vLocation >= 0 && !indexHidden)
- q->beginRemoveRows(parent, translateVisibleLocation(parentNode, vLocation),
- translateVisibleLocation(parentNode, vLocation));
- QFileSystemNode * node = parentNode->children.take(name);
- delete node;
- // cleanup sort files after removing rather then re-sorting which is O(n)
- if (vLocation >= 0)
- parentNode->visibleChildren.removeAt(vLocation);
- if (vLocation >= 0 && !indexHidden)
- q->endRemoveRows();
-}
-
-/*!
- \internal
-
- File at parentNode->children(itemLocation) was not visible before, but now should be
- and emit signals if necessary.
-
- *WARNING* this will change the visible count
- */
-void QFileSystemModelPrivate::addVisibleFiles(QFileSystemNode *parentNode, const QStringList &newFiles)
-{
- Q_Q(QFileSystemModel);
- QModelIndex parent = index(parentNode);
- bool indexHidden = isHiddenByFilter(parentNode, parent);
- if (!indexHidden) {
- q->beginInsertRows(parent, parentNode->visibleChildren.count() , parentNode->visibleChildren.count() + newFiles.count() - 1);
- }
-
- if (parentNode->dirtyChildrenIndex == -1)
- parentNode->dirtyChildrenIndex = parentNode->visibleChildren.count();
-
- for (const auto &newFile : newFiles) {
- parentNode->visibleChildren.append(newFile);
- parentNode->children.value(newFile)->isVisible = true;
- }
- if (!indexHidden)
- q->endInsertRows();
-}
-
-/*!
- \internal
-
- File was visible before, but now should NOT be
-
- *WARNING* this will change the visible count
- */
-void QFileSystemModelPrivate::removeVisibleFile(QFileSystemNode *parentNode, int vLocation)
-{
- Q_Q(QFileSystemModel);
- if (vLocation == -1)
- return;
- QModelIndex parent = index(parentNode);
- bool indexHidden = isHiddenByFilter(parentNode, parent);
- if (!indexHidden)
- q->beginRemoveRows(parent, translateVisibleLocation(parentNode, vLocation),
- translateVisibleLocation(parentNode, vLocation));
- parentNode->children.value(parentNode->visibleChildren.at(vLocation))->isVisible = false;
- parentNode->visibleChildren.removeAt(vLocation);
- if (!indexHidden)
- q->endRemoveRows();
-}
-
-/*!
- \internal
-
- The thread has received new information about files,
- update and emit dataChanged if it has actually changed.
- */
-void QFileSystemModelPrivate::_q_fileSystemChanged(const QString &path, const QVector<QPair<QString, QFileInfo> > &updates)
-{
-#if QT_CONFIG(filesystemwatcher)
- Q_Q(QFileSystemModel);
- QVector<QString> rowsToUpdate;
- QStringList newFiles;
- QFileSystemModelPrivate::QFileSystemNode *parentNode = node(path, false);
- QModelIndex parentIndex = index(parentNode);
- for (const auto &update : updates) {
- QString fileName = update.first;
- Q_ASSERT(!fileName.isEmpty());
- QExtendedInformation info = fileInfoGatherer.getInfo(update.second);
- bool previouslyHere = parentNode->children.contains(fileName);
- if (!previouslyHere) {
- addNode(parentNode, fileName, info.fileInfo());
- }
- QFileSystemModelPrivate::QFileSystemNode * node = parentNode->children.value(fileName);
- bool isCaseSensitive = parentNode->caseSensitive();
- if (isCaseSensitive) {
- if (node->fileName != fileName)
- continue;
- } else {
- if (QString::compare(node->fileName,fileName,Qt::CaseInsensitive) != 0)
- continue;
- }
- if (isCaseSensitive) {
- Q_ASSERT(node->fileName == fileName);
- } else {
- node->fileName = fileName;
- }
-
- if (*node != info ) {
- node->populate(info);
- bypassFilters.remove(node);
- // brand new information.
- if (filtersAcceptsNode(node)) {
- if (!node->isVisible) {
- newFiles.append(fileName);
- } else {
- rowsToUpdate.append(fileName);
- }
- } else {
- if (node->isVisible) {
- int visibleLocation = parentNode->visibleLocation(fileName);
- removeVisibleFile(parentNode, visibleLocation);
- } else {
- // The file is not visible, don't do anything
- }
- }
- }
- }
-
- // bundle up all of the changed signals into as few as possible.
- std::sort(rowsToUpdate.begin(), rowsToUpdate.end());
- QString min;
- QString max;
- for (const QString &value : qAsConst(rowsToUpdate)) {
- //##TODO is there a way to bundle signals with QString as the content of the list?
- /*if (min.isEmpty()) {
- min = value;
- if (i != rowsToUpdate.count() - 1)
- continue;
- }
- if (i != rowsToUpdate.count() - 1) {
- if ((value == min + 1 && max.isEmpty()) || value == max + 1) {
- max = value;
- continue;
- }
- }*/
- max = value;
- min = value;
- int visibleMin = parentNode->visibleLocation(min);
- int visibleMax = parentNode->visibleLocation(max);
- if (visibleMin >= 0
- && visibleMin < parentNode->visibleChildren.count()
- && parentNode->visibleChildren.at(visibleMin) == min
- && visibleMax >= 0) {
- QModelIndex bottom = q->index(translateVisibleLocation(parentNode, visibleMin), 0, parentIndex);
- QModelIndex top = q->index(translateVisibleLocation(parentNode, visibleMax), 3, parentIndex);
- emit q->dataChanged(bottom, top);
- }
-
- /*min = QString();
- max = QString();*/
- }
-
- if (newFiles.count() > 0) {
- addVisibleFiles(parentNode, newFiles);
- }
-
- if (newFiles.count() > 0 || (sortColumn != 0 && rowsToUpdate.count() > 0)) {
- forceSort = true;
- delayedSort();
- }
-#else
- Q_UNUSED(path)
- Q_UNUSED(updates)
-#endif // filesystemwatcher
-}
-
-/*!
- \internal
-*/
-void QFileSystemModelPrivate::_q_resolvedName(const QString &fileName, const QString &resolvedName)
-{
- resolvedSymLinks[fileName] = resolvedName;
-}
-
-#if QT_CONFIG(filesystemwatcher) && defined(Q_OS_WIN)
-// Remove file system watchers at/below the index and return a list of previously
-// watched files. This should be called prior to operations like rename/remove
-// which might fail due to watchers on platforms like Windows. The watchers
-// should be restored on failure.
-QStringList QFileSystemModelPrivate::unwatchPathsAt(const QModelIndex &index)
-{
- const QFileSystemModelPrivate::QFileSystemNode *indexNode = node(index);
- if (indexNode == nullptr)
- return QStringList();
- const Qt::CaseSensitivity caseSensitivity = indexNode->caseSensitive()
- ? Qt::CaseSensitive : Qt::CaseInsensitive;
- const QString path = indexNode->fileInfo().absoluteFilePath();
-
- QStringList result;
- const auto filter = [path, caseSensitivity] (const QString &watchedPath)
- {
- const int pathSize = path.size();
- if (pathSize == watchedPath.size()) {
- return path.compare(watchedPath, caseSensitivity) == 0;
- } else if (watchedPath.size() > pathSize) {
- return watchedPath.at(pathSize) == QLatin1Char('/')
- && watchedPath.startsWith(path, caseSensitivity);
- }
- return false;
- };
-
- const QStringList &watchedFiles = fileInfoGatherer.watchedFiles();
- std::copy_if(watchedFiles.cbegin(), watchedFiles.cend(),
- std::back_inserter(result), filter);
-
- const QStringList &watchedDirectories = fileInfoGatherer.watchedDirectories();
- std::copy_if(watchedDirectories.cbegin(), watchedDirectories.cend(),
- std::back_inserter(result), filter);
-
- fileInfoGatherer.unwatchPaths(result);
- return result;
-}
-#endif // filesystemwatcher && Q_OS_WIN
-
-/*!
- \internal
-*/
-void QFileSystemModelPrivate::init()
-{
- Q_Q(QFileSystemModel);
-
- delayedSortTimer.setSingleShot(true);
-
- qRegisterMetaType<QVector<QPair<QString,QFileInfo> > >();
-#if QT_CONFIG(filesystemwatcher)
- q->connect(&fileInfoGatherer, SIGNAL(newListOfFiles(QString,QStringList)),
- q, SLOT(_q_directoryChanged(QString,QStringList)));
- q->connect(&fileInfoGatherer, SIGNAL(updates(QString,QVector<QPair<QString,QFileInfo> >)),
- q, SLOT(_q_fileSystemChanged(QString,QVector<QPair<QString,QFileInfo> >)));
- q->connect(&fileInfoGatherer, SIGNAL(nameResolved(QString,QString)),
- q, SLOT(_q_resolvedName(QString,QString)));
- q->connect(&fileInfoGatherer, SIGNAL(directoryLoaded(QString)),
- q, SIGNAL(directoryLoaded(QString)));
-#endif // filesystemwatcher
- q->connect(&delayedSortTimer, SIGNAL(timeout()), q, SLOT(_q_performDelayedSort()), Qt::QueuedConnection);
-
- roleNames.insert(QFileSystemModel::FileIconRole,
- QByteArrayLiteral("fileIcon")); // == Qt::decoration
- roleNames.insert(QFileSystemModel::FilePathRole, QByteArrayLiteral("filePath"));
- roleNames.insert(QFileSystemModel::FileNameRole, QByteArrayLiteral("fileName"));
- roleNames.insert(QFileSystemModel::FilePermissions, QByteArrayLiteral("filePermissions"));
-}
-
-/*!
- \internal
-
- Returns \c false if node doesn't pass the filters otherwise true
-
- QDir::Modified is not supported
- QDir::Drives is not supported
-*/
-bool QFileSystemModelPrivate::filtersAcceptsNode(const QFileSystemNode *node) const
-{
- // always accept drives
- if (node->parent == &root || bypassFilters.contains(node))
- return true;
-
- // If we don't know anything yet don't accept it
- if (!node->hasInformation())
- return false;
-
- const bool filterPermissions = ((filters & QDir::PermissionMask)
- && (filters & QDir::PermissionMask) != QDir::PermissionMask);
- const bool hideDirs = !(filters & (QDir::Dirs | QDir::AllDirs));
- const bool hideFiles = !(filters & QDir::Files);
- const bool hideReadable = !(!filterPermissions || (filters & QDir::Readable));
- const bool hideWritable = !(!filterPermissions || (filters & QDir::Writable));
- const bool hideExecutable = !(!filterPermissions || (filters & QDir::Executable));
- const bool hideHidden = !(filters & QDir::Hidden);
- const bool hideSystem = !(filters & QDir::System);
- const bool hideSymlinks = (filters & QDir::NoSymLinks);
- const bool hideDot = (filters & QDir::NoDot);
- const bool hideDotDot = (filters & QDir::NoDotDot);
-
- // Note that we match the behavior of entryList and not QFileInfo on this.
- bool isDot = (node->fileName == QLatin1String("."));
- bool isDotDot = (node->fileName == QLatin1String(".."));
- if ( (hideHidden && !(isDot || isDotDot) && node->isHidden())
- || (hideSystem && node->isSystem())
- || (hideDirs && node->isDir())
- || (hideFiles && node->isFile())
- || (hideSymlinks && node->isSymLink())
- || (hideReadable && node->isReadable())
- || (hideWritable && node->isWritable())
- || (hideExecutable && node->isExecutable())
- || (hideDot && isDot)
- || (hideDotDot && isDotDot))
- return false;
-
- return nameFilterDisables || passNameFilters(node);
-}
-
-/*
- \internal
-
- Returns \c true if node passes the name filters and should be visible.
- */
-bool QFileSystemModelPrivate::passNameFilters(const QFileSystemNode *node) const
-{
-#if QT_CONFIG(regularexpression)
- if (nameFilters.isEmpty())
- return true;
-
- // Check the name regularexpression filters
- if (!(node->isDir() && (filters & QDir::AllDirs))) {
- const QRegularExpression::PatternOptions options =
- (filters & QDir::CaseSensitive) ? QRegularExpression::NoPatternOption
- : QRegularExpression::CaseInsensitiveOption;
-
- for (const auto &nameFilter : nameFilters) {
- QRegularExpression rx(QRegularExpression::wildcardToRegularExpression(nameFilter), options);
- QRegularExpressionMatch match = rx.match(node->fileName);
- if (match.hasMatch())
- return true;
- }
- return false;
- }
-#endif
- return true;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qfilesystemmodel.cpp"
diff --git a/src/widgets/dialogs/qfilesystemmodel.h b/src/widgets/dialogs/qfilesystemmodel.h
index b0f289dfcd..9bf7f25945 100644
--- a/src/widgets/dialogs/qfilesystemmodel.h
+++ b/src/widgets/dialogs/qfilesystemmodel.h
@@ -1,187 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QFILESYSTEMMODEL_H
-#define QFILESYSTEMMODEL_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qpair.h>
-#include <QtCore/qdir.h>
-#include <QtGui/qicon.h>
-#include <QtCore/qdiriterator.h>
-
-QT_REQUIRE_CONFIG(filesystemmodel);
+#include <QtGui/QFileSystemModel>
QT_BEGIN_NAMESPACE
-
-class ExtendedInformation;
-class QFileSystemModelPrivate;
-class QFileIconProvider;
-
-class Q_WIDGETS_EXPORT QFileSystemModel : public QAbstractItemModel
-{
- Q_OBJECT
- Q_PROPERTY(bool resolveSymlinks READ resolveSymlinks WRITE setResolveSymlinks)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
- Q_PROPERTY(bool nameFilterDisables READ nameFilterDisables WRITE setNameFilterDisables)
- Q_PROPERTY(Options options READ options WRITE setOptions)
-
-Q_SIGNALS:
- void rootPathChanged(const QString &newPath);
- void fileRenamed(const QString &path, const QString &oldName, const QString &newName);
- void directoryLoaded(const QString &path);
-
-public:
- enum Roles {
- FileIconRole = Qt::DecorationRole,
- FilePathRole = Qt::UserRole + 1,
- FileNameRole = Qt::UserRole + 2,
- FilePermissions = Qt::UserRole + 3
- };
-
- enum Option
- {
- DontWatchForChanges = 0x00000001,
- DontResolveSymlinks = 0x00000002,
- DontUseCustomDirectoryIcons = 0x00000004
- };
- Q_ENUM(Option)
- Q_DECLARE_FLAGS(Options, Option)
-
- explicit QFileSystemModel(QObject *parent = nullptr);
- ~QFileSystemModel();
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
- QModelIndex index(const QString &path, int column = 0) const;
- QModelIndex parent(const QModelIndex &child) const override;
- using QObject::parent;
- QModelIndex sibling(int row, int column, const QModelIndex &idx) const override;
- bool hasChildren(const QModelIndex &parent = QModelIndex()) const override;
- bool canFetchMore(const QModelIndex &parent) const override;
- void fetchMore(const QModelIndex &parent) override;
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const override;
- int columnCount(const QModelIndex &parent = QModelIndex()) const override;
-
- QVariant myComputer(int role = Qt::DisplayRole) const;
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
-
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
-
- Qt::ItemFlags flags(const QModelIndex &index) const override;
-
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override;
-
- QStringList mimeTypes() const override;
- QMimeData *mimeData(const QModelIndexList &indexes) const override;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent) override;
- Qt::DropActions supportedDropActions() const override;
-
- // QFileSystemModel specific API
- QModelIndex setRootPath(const QString &path);
- QString rootPath() const;
- QDir rootDirectory() const;
-
- void setIconProvider(QFileIconProvider *provider);
- QFileIconProvider *iconProvider() const;
-
- void setFilter(QDir::Filters filters);
- QDir::Filters filter() const;
-
- void setResolveSymlinks(bool enable);
- bool resolveSymlinks() const;
-
- void setReadOnly(bool enable);
- bool isReadOnly() const;
-
- void setNameFilterDisables(bool enable);
- bool nameFilterDisables() const;
-
- void setNameFilters(const QStringList &filters);
- QStringList nameFilters() const;
-
- void setOption(Option option, bool on = true);
- bool testOption(Option option) const;
- void setOptions(Options options);
- Options options() const;
-
- QString filePath(const QModelIndex &index) const;
- bool isDir(const QModelIndex &index) const;
- qint64 size(const QModelIndex &index) const;
- QString type(const QModelIndex &index) const;
- QDateTime lastModified(const QModelIndex &index) const;
-
- QModelIndex mkdir(const QModelIndex &parent, const QString &name);
- bool rmdir(const QModelIndex &index);
- inline QString fileName(const QModelIndex &index) const;
- inline QIcon fileIcon(const QModelIndex &index) const;
- QFile::Permissions permissions(const QModelIndex &index) const;
- QFileInfo fileInfo(const QModelIndex &index) const;
- bool remove(const QModelIndex &index);
-
-protected:
- QFileSystemModel(QFileSystemModelPrivate &, QObject *parent = nullptr);
- void timerEvent(QTimerEvent *event) override;
- bool event(QEvent *event) override;
-
-private:
- Q_DECLARE_PRIVATE(QFileSystemModel)
- Q_DISABLE_COPY(QFileSystemModel)
-
- Q_PRIVATE_SLOT(d_func(), void _q_directoryChanged(const QString &directory, const QStringList &list))
- Q_PRIVATE_SLOT(d_func(), void _q_performDelayedSort())
- Q_PRIVATE_SLOT(d_func(), void _q_fileSystemChanged(const QString &path, const QVector<QPair<QString, QFileInfo> > &))
- Q_PRIVATE_SLOT(d_func(), void _q_resolvedName(const QString &fileName, const QString &resolvedName))
-
- friend class QFileDialogPrivate;
-};
-
-inline QString QFileSystemModel::fileName(const QModelIndex &aindex) const
-{ return aindex.data(Qt::DisplayRole).toString(); }
-inline QIcon QFileSystemModel::fileIcon(const QModelIndex &aindex) const
-{ return qvariant_cast<QIcon>(aindex.data(Qt::DecorationRole)); }
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QFileSystemModel::Options)
-
QT_END_NAMESPACE
-
-#endif // QFILESYSTEMMODEL_H
diff --git a/src/widgets/dialogs/qfilesystemmodel_p.h b/src/widgets/dialogs/qfilesystemmodel_p.h
deleted file mode 100644
index ad98b9ef44..0000000000
--- a/src/widgets/dialogs/qfilesystemmodel_p.h
+++ /dev/null
@@ -1,323 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QFILESYSTEMMODEL_P_H
-#define QFILESYSTEMMODEL_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 <QtWidgets/private/qtwidgetsglobal_p.h>
-#include "qfilesystemmodel.h"
-
-#include <private/qabstractitemmodel_p.h>
-#include <qabstractitemmodel.h>
-#include "qfileinfogatherer_p.h"
-#include <qpair.h>
-#include <qdir.h>
-#include <qicon.h>
-#include <qfileinfo.h>
-#include <qtimer.h>
-#include <qhash.h>
-
-QT_REQUIRE_CONFIG(filesystemmodel);
-
-QT_BEGIN_NAMESPACE
-
-class ExtendedInformation;
-class QFileSystemModelPrivate;
-class QFileIconProvider;
-
-#if defined(Q_OS_WIN)
-class QFileSystemModelNodePathKey : public QString
-{
-public:
- QFileSystemModelNodePathKey() {}
- QFileSystemModelNodePathKey(const QString &other) : QString(other) {}
- QFileSystemModelNodePathKey(const QFileSystemModelNodePathKey &other) : QString(other) {}
- bool operator==(const QFileSystemModelNodePathKey &other) const { return !compare(other, Qt::CaseInsensitive); }
-};
-
-Q_DECLARE_TYPEINFO(QFileSystemModelNodePathKey, Q_MOVABLE_TYPE);
-
-inline uint qHash(const QFileSystemModelNodePathKey &key) { return qHash(key.toCaseFolded()); }
-#else // Q_OS_WIN
-typedef QString QFileSystemModelNodePathKey;
-#endif
-
-class Q_AUTOTEST_EXPORT QFileSystemModelPrivate : public QAbstractItemModelPrivate
-{
- Q_DECLARE_PUBLIC(QFileSystemModel)
-
-public:
- enum { NumColumns = 4 };
-
- class QFileSystemNode
- {
- public:
- Q_DISABLE_COPY_MOVE(QFileSystemNode)
-
- explicit QFileSystemNode(const QString &filename = QString(), QFileSystemNode *p = nullptr)
- : fileName(filename), parent(p) {}
- ~QFileSystemNode() {
- qDeleteAll(children);
- delete info;
- }
-
- QString fileName;
-#if defined(Q_OS_WIN)
- QString volumeName;
-#endif
-
- inline qint64 size() const { if (info && !info->isDir()) return info->size(); return 0; }
- inline QString type() const { if (info) return info->displayType; return QLatin1String(""); }
- inline QDateTime lastModified() const { if (info) return info->lastModified(); return QDateTime(); }
- inline QFile::Permissions permissions() const { if (info) return info->permissions(); return { }; }
- inline bool isReadable() const { return ((permissions() & QFile::ReadUser) != 0); }
- inline bool isWritable() const { return ((permissions() & QFile::WriteUser) != 0); }
- inline bool isExecutable() const { return ((permissions() & QFile::ExeUser) != 0); }
- inline bool isDir() const {
- if (info)
- return info->isDir();
- if (children.count() > 0)
- return true;
- return false;
- }
- inline QFileInfo fileInfo() const { if (info) return info->fileInfo(); return QFileInfo(); }
- inline bool isFile() const { if (info) return info->isFile(); return true; }
- inline bool isSystem() const { if (info) return info->isSystem(); return true; }
- inline bool isHidden() const { if (info) return info->isHidden(); return false; }
- inline bool isSymLink(bool ignoreNtfsSymLinks = false) const { return info && info->isSymLink(ignoreNtfsSymLinks); }
- inline bool caseSensitive() const { if (info) return info->isCaseSensitive(); return false; }
- inline QIcon icon() const { if (info) return info->icon; return QIcon(); }
-
- inline bool operator <(const QFileSystemNode &node) const {
- if (caseSensitive() || node.caseSensitive())
- return fileName < node.fileName;
- return QString::compare(fileName, node.fileName, Qt::CaseInsensitive) < 0;
- }
- inline bool operator >(const QString &name) const {
- if (caseSensitive())
- return fileName > name;
- return QString::compare(fileName, name, Qt::CaseInsensitive) > 0;
- }
- inline bool operator <(const QString &name) const {
- if (caseSensitive())
- return fileName < name;
- return QString::compare(fileName, name, Qt::CaseInsensitive) < 0;
- }
- inline bool operator !=(const QExtendedInformation &fileInfo) const {
- return !operator==(fileInfo);
- }
- bool operator ==(const QString &name) const {
- if (caseSensitive())
- return fileName == name;
- return QString::compare(fileName, name, Qt::CaseInsensitive) == 0;
- }
- bool operator ==(const QExtendedInformation &fileInfo) const {
- return info && (*info == fileInfo);
- }
-
- inline bool hasInformation() const { return info != nullptr; }
-
- void populate(const QExtendedInformation &fileInfo) {
- if (!info)
- info = new QExtendedInformation(fileInfo.fileInfo());
- (*info) = fileInfo;
- }
-
- // children shouldn't normally be accessed directly, use node()
- inline int visibleLocation(const QString &childName) {
- return visibleChildren.indexOf(childName);
- }
- void updateIcon(QFileIconProvider *iconProvider, const QString &path) {
- if (info)
- info->icon = iconProvider->icon(QFileInfo(path));
- for (QFileSystemNode *child : qAsConst(children)) {
- //On windows the root (My computer) has no path so we don't want to add a / for nothing (e.g. /C:/)
- if (!path.isEmpty()) {
- if (path.endsWith(QLatin1Char('/')))
- child->updateIcon(iconProvider, path + child->fileName);
- else
- child->updateIcon(iconProvider, path + QLatin1Char('/') + child->fileName);
- } else
- child->updateIcon(iconProvider, child->fileName);
- }
- }
-
- void retranslateStrings(QFileIconProvider *iconProvider, const QString &path) {
- if (info)
- info->displayType = iconProvider->type(QFileInfo(path));
- for (QFileSystemNode *child : qAsConst(children)) {
- //On windows the root (My computer) has no path so we don't want to add a / for nothing (e.g. /C:/)
- if (!path.isEmpty()) {
- if (path.endsWith(QLatin1Char('/')))
- child->retranslateStrings(iconProvider, path + child->fileName);
- else
- child->retranslateStrings(iconProvider, path + QLatin1Char('/') + child->fileName);
- } else
- child->retranslateStrings(iconProvider, child->fileName);
- }
- }
-
- QHash<QFileSystemModelNodePathKey, QFileSystemNode *> children;
- QList<QString> visibleChildren;
- QExtendedInformation *info = nullptr;
- QFileSystemNode *parent;
- int dirtyChildrenIndex = -1;
- bool populatedChildren = false;
- bool isVisible = false;
- };
-
- QFileSystemModelPrivate() = default;
- void init();
- /*
- \internal
-
- Return true if index which is owned by node is hidden by the filter.
- */
- inline bool isHiddenByFilter(QFileSystemNode *indexNode, const QModelIndex &index) const
- {
- return (indexNode != &root && !index.isValid());
- }
- QFileSystemNode *node(const QModelIndex &index) const;
- QFileSystemNode *node(const QString &path, bool fetch = true) const;
- inline QModelIndex index(const QString &path, int column = 0) { return index(node(path), column); }
- QModelIndex index(const QFileSystemNode *node, int column = 0) const;
- bool filtersAcceptsNode(const QFileSystemNode *node) const;
- bool passNameFilters(const QFileSystemNode *node) const;
- void removeNode(QFileSystemNode *parentNode, const QString &name);
- QFileSystemNode* addNode(QFileSystemNode *parentNode, const QString &fileName, const QFileInfo &info);
- void addVisibleFiles(QFileSystemNode *parentNode, const QStringList &newFiles);
- void removeVisibleFile(QFileSystemNode *parentNode, int visibleLocation);
- void sortChildren(int column, const QModelIndex &parent);
-
- inline int translateVisibleLocation(QFileSystemNode *parent, int row) const {
- if (sortOrder != Qt::AscendingOrder) {
- if (parent->dirtyChildrenIndex == -1)
- return parent->visibleChildren.count() - row - 1;
-
- if (row < parent->dirtyChildrenIndex)
- return parent->dirtyChildrenIndex - row - 1;
- }
-
- return row;
- }
-
- inline static QString myComputer() {
- // ### TODO We should query the system to find out what the string should be
- // XP == "My Computer",
- // Vista == "Computer",
- // OS X == "Computer" (sometime user generated) "Benjamin's PowerBook G4"
-#ifdef Q_OS_WIN
- return QFileSystemModel::tr("My Computer");
-#else
- return QFileSystemModel::tr("Computer");
-#endif
- }
-
- inline void delayedSort() {
- if (!delayedSortTimer.isActive())
- delayedSortTimer.start(0);
- }
-
- QIcon icon(const QModelIndex &index) const;
- QString name(const QModelIndex &index) const;
- QString displayName(const QModelIndex &index) const;
- QString filePath(const QModelIndex &index) const;
- QString size(const QModelIndex &index) const;
- static QString size(qint64 bytes);
- QString type(const QModelIndex &index) const;
- QString time(const QModelIndex &index) const;
-
- void _q_directoryChanged(const QString &directory, const QStringList &list);
- void _q_performDelayedSort();
- void _q_fileSystemChanged(const QString &path, const QVector<QPair<QString, QFileInfo> > &);
- void _q_resolvedName(const QString &fileName, const QString &resolvedName);
-
- QDir rootDir;
-#if QT_CONFIG(filesystemwatcher)
-# ifdef Q_OS_WIN
- QStringList unwatchPathsAt(const QModelIndex &);
- void watchPaths(const QStringList &paths) { fileInfoGatherer.watchPaths(paths); }
-# endif // Q_OS_WIN
- QFileInfoGatherer fileInfoGatherer;
-#endif // filesystemwatcher
- QTimer delayedSortTimer;
- QHash<const QFileSystemNode*, bool> bypassFilters;
-#if QT_CONFIG(regularexpression)
- QStringList nameFilters;
-#endif
- QHash<QString, QString> resolvedSymLinks;
-
- QFileSystemNode root;
-
- struct Fetching {
- QString dir;
- QString file;
- const QFileSystemNode *node;
- };
- QVector<Fetching> toFetch;
-
- QBasicTimer fetchingTimer;
-
- QDir::Filters filters = QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs;
- int sortColumn = 0;
- Qt::SortOrder sortOrder = Qt::AscendingOrder;
- bool forceSort = true;
- bool readOnly = true;
- bool setRootPath = false;
- bool nameFilterDisables = true; // false on windows, true on mac and unix
- // This flag is an optimization for QFileDialog. It enables a sort which is
- // not recursive, meaning we sort only what we see.
- bool disableRecursiveSort = false;
-};
-Q_DECLARE_TYPEINFO(QFileSystemModelPrivate::Fetching, Q_MOVABLE_TYPE);
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/widgets/dialogs/qfontdialog.cpp b/src/widgets/dialogs/qfontdialog.cpp
index fe8f88d64f..628297d22b 100644
--- a/src/widgets/dialogs/qfontdialog.cpp
+++ b/src/widgets/dialogs/qfontdialog.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qwindowdefs.h"
#include "qfontdialog.h"
@@ -46,7 +10,6 @@
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qevent.h>
-#include <qfontdatabase.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qlayout.h>
@@ -58,11 +21,14 @@
#include <qlistview.h>
#include <qstringlistmodel.h>
#include <qvalidator.h>
+#include <private/qfontdatabase_p.h>
#include <private/qdialog_p.h>
#include <private/qfont_p.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
class QFontListView : public QListView
{
Q_OBJECT
@@ -103,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()
@@ -153,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();
@@ -228,7 +194,7 @@ void QFontDialogPrivate::init()
sampleEdit->setAlignment(Qt::AlignCenter);
// Note that the sample text is *not* translated with tr(), as the
// characters used depend on the charset encoding.
- sampleEdit->setText(QLatin1String("AaBbYyZz"));
+ sampleEdit->setText("AaBbYyZz"_L1);
hbox->addWidget(sampleEdit);
writingSystemCombo = new QComboBox(q);
@@ -242,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);
@@ -311,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);
@@ -326,7 +299,7 @@ void QFontDialogPrivate::init()
familyList->setFocus();
retranslateStrings();
- sampleEdit->setObjectName(QLatin1String("qt_fontDialog_sampleEdit"));
+ sampleEdit->setObjectName("qt_fontDialog_sampleEdit"_L1);
}
/*!
@@ -424,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 ||
@@ -460,10 +433,14 @@ bool QFontDialog::eventFilter(QObject *o , QEvent *e)
void QFontDialogPrivate::initHelper(QPlatformDialogHelper *h)
{
- QFontDialog *d = q_func();
- QObject::connect(h, SIGNAL(currentFontChanged(QFont)), d, SIGNAL(currentFontChanged(QFont)));
- QObject::connect(h, SIGNAL(fontSelected(QFont)), d, SIGNAL(fontSelected(QFont)));
- static_cast<QPlatformFontDialogHelper *>(h)->setOptions(options);
+ Q_Q(QFontDialog);
+ auto *fontDialogHelper = static_cast<QPlatformFontDialogHelper *>(h);
+ fontDialogHelper->setOptions(options);
+ fontDialogHelper->setCurrentFont(q->currentFont());
+ QObject::connect(fontDialogHelper, &QPlatformFontDialogHelper::currentFontChanged,
+ q, &QFontDialog::currentFontChanged);
+ QObject::connect(fontDialogHelper, &QPlatformFontDialogHelper::fontSelected,
+ q, &QFontDialog::fontSelected);
}
void QFontDialogPrivate::helperPrepareShow(QPlatformDialogHelper *)
@@ -486,20 +463,18 @@ void QFontDialogPrivate::updateFamilies()
const QFontDialog::FontDialogOptions spacingMask = (QFontDialog::ProportionalFonts | QFontDialog::MonospacedFonts);
const QFontDialog::FontDialogOptions options = q->options();
- QFontDatabase fdb;
-
QStringList familyNames;
- const auto families = fdb.families(writingSystem);
+ const auto families = QFontDatabase::families(writingSystem);
for (const QString &family : families) {
- if (fdb.isPrivateFamily(family))
+ if (QFontDatabase::isPrivateFamily(family))
continue;
if ((options & scalableMask) && (options & scalableMask) != scalableMask) {
- if (bool(options & QFontDialog::ScalableFonts) != fdb.isSmoothlyScalable(family))
+ if (bool(options & QFontDialog::ScalableFonts) != QFontDatabase::isSmoothlyScalable(family))
continue;
}
if ((options & spacingMask) && (options & spacingMask) != spacingMask) {
- if (bool(options & QFontDialog::MonospacedFonts) != fdb.isFixedPitch(family))
+ if (bool(options & QFontDialog::MonospacedFonts) != QFontDatabase::isFixedPitch(family))
continue;
}
familyNames << family;
@@ -514,12 +489,12 @@ void QFontDialogPrivate::updateFamilies()
QFont f;
// ##### do the right thing for a list of family names in the font.
- QFontDatabase::parseFontName(family, foundryName1, familyName1);
+ QFontDatabasePrivate::parseFontName(family, foundryName1, familyName1);
QStringList::const_iterator it = familyNames.constBegin();
int i = 0;
for(; it != familyNames.constEnd(); ++it, ++i) {
- QFontDatabase::parseFontName(*it, foundryName2, familyName2);
+ QFontDatabasePrivate::parseFontName(*it, foundryName2, familyName2);
//try to match...
if (familyName1 == familyName2) {
@@ -534,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.family())
+ if (bestFamilyType <= MATCH_LAST_RESORT && familyName2 == f.families().constFirst())
type = MATCH_APP;
// ### add fallback for writingSystem
if (type != MATCH_NONE) {
@@ -564,7 +539,7 @@ void QFontDialogPrivate::updateFamilies()
void QFontDialogPrivate::updateStyles()
{
Q_Q(QFontDialog);
- QStringList styles = fdb.styles(familyList->currentText());
+ QStringList styles = QFontDatabase::styles(familyList->currentText());
styleList->model()->setStringList(styles);
if (styles.isEmpty()) {
@@ -577,7 +552,7 @@ void QFontDialogPrivate::updateStyles()
QString cstyle = style;
redo:
- for (int i = 0; i < (int)styleList->count(); i++) {
+ for (int i = 0; i < static_cast<int>(styleList->count()); i++) {
if (cstyle == styleList->text(i)) {
styleList->setCurrentItem(i);
found = true;
@@ -585,12 +560,20 @@ void QFontDialogPrivate::updateStyles()
}
}
if (!found && first) {
- if (cstyle.contains(QLatin1String("Italic"))) {
- cstyle.replace(QLatin1String("Italic"), QLatin1String("Oblique"));
+ if (cstyle.contains("Italic"_L1)) {
+ cstyle.replace("Italic"_L1, "Oblique"_L1);
+ first = false;
+ goto redo;
+ } else if (cstyle.contains("Oblique"_L1)) {
+ cstyle.replace("Oblique"_L1, "Italic"_L1);
+ first = false;
+ goto redo;
+ } else if (cstyle.contains("Regular"_L1)) {
+ cstyle.replace("Regular"_L1, "Normal"_L1);
first = false;
goto redo;
- } else if (cstyle.contains(QLatin1String("Oblique"))) {
- cstyle.replace(QLatin1String("Oblique"), QLatin1String("Italic"));
+ } else if (cstyle.contains("Normal"_L1)) {
+ cstyle.replace("Normal"_L1, "Regular"_L1);
first = false;
goto redo;
}
@@ -606,7 +589,7 @@ void QFontDialogPrivate::updateStyles()
&& styleList->hasFocus())
styleEdit->selectAll();
- smoothScalable = fdb.isSmoothlyScalable(familyList->currentText(), styleList->currentText());
+ smoothScalable = QFontDatabase::isSmoothlyScalable(familyList->currentText(), styleList->currentText());
}
updateSizes();
@@ -623,7 +606,7 @@ void QFontDialogPrivate::updateSizes()
Q_Q(QFontDialog);
if (!familyList->currentText().isEmpty()) {
- QList<int> sizes = fdb.pointSizes(familyList->currentText(), styleList->currentText());
+ QList<int> sizes = QFontDatabase::pointSizes(familyList->currentText(), styleList->currentText());
int i = 0;
int current = -1;
@@ -648,14 +631,14 @@ void QFontDialogPrivate::updateSizes()
sizeEdit->clear();
}
- _q_updateSample();
+ updateSample();
}
-void QFontDialogPrivate::_q_updateSample()
+void QFontDialogPrivate::updateSample()
{
// compute new font
int pSize = sizeEdit->text().toInt();
- QFont newFont(fdb.font(familyList->currentText(), style, pSize));
+ QFont newFont(QFontDatabase::font(familyList->currentText(), style, pSize));
newFont.setStrikeOut(strikeout->isChecked());
newFont.setUnderline(underline->isChecked());
@@ -677,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));
@@ -687,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);
@@ -704,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);
@@ -723,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);
@@ -733,7 +716,7 @@ void QFontDialogPrivate::_q_sizeHighlighted(int index)
sizeEdit->selectAll();
size = s.toInt();
- _q_updateSample();
+ updateSample();
}
/*!
@@ -742,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();
@@ -762,7 +745,7 @@ void QFontDialogPrivate::_q_sizeChanged(const QString &s)
else
sizeList->clearSelection();
}
- _q_updateSample();
+ updateSample();
}
void QFontDialogPrivate::retranslateStrings()
@@ -806,8 +789,8 @@ void QFontDialog::changeEvent(QEvent *e)
void QFontDialog::setCurrentFont(const QFont &font)
{
Q_D(QFontDialog);
- d->family = font.family();
- d->style = d->fdb.styleString(font);
+ d->family = font.families().value(0);
+ d->style = QFontDatabase::styleString(font);
d->size = font.pointSize();
if (d->size == -1) {
QFontInfo fi(font);
@@ -816,8 +799,11 @@ void QFontDialog::setCurrentFont(const QFont &font)
d->strikeout->setChecked(font.strikeOut());
d->underline->setChecked(font.underline());
d->updateFamilies();
- if (QPlatformFontDialogHelper *helper = d->platformFontDialogHelper())
- helper->setCurrentFont(font);
+
+ if (d->nativeDialogInUse) {
+ if (QPlatformFontDialogHelper *helper = d->platformFontDialogHelper())
+ helper->setCurrentFont(font);
+ }
}
/*!
@@ -830,8 +816,11 @@ void QFontDialog::setCurrentFont(const QFont &font)
QFont QFontDialog::currentFont() const
{
Q_D(const QFontDialog);
- if (const QPlatformFontDialogHelper *helper = d->platformFontDialogHelper())
- return helper->currentFont();
+
+ if (d->nativeDialogInUse) {
+ if (const QPlatformFontDialogHelper *helper = d->platformFontDialogHelper())
+ return helper->currentFont();
+ }
return d->sampleEdit->font();
}
@@ -980,20 +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 {
- d->nativeDialogInUse = false;
- setAttribute(Qt::WA_DontShowOnScreen, false);
+ q->setAttribute(Qt::WA_DontShowOnScreen, false);
}
- QDialog::setVisible(visible);
+ QDialogPrivate::setVisible(visible);
}
/*!
@@ -1006,11 +1006,10 @@ void QFontDialog::setVisible(bool visible)
void QFontDialog::done(int result)
{
Q_D(QFontDialog);
- QDialog::done(result);
if (result == Accepted) {
// We check if this is the same font we had before, if so we emit currentFontChanged
QFont selectedFont = currentFont();
- if(selectedFont != d->selectedFont)
+ if (selectedFont != d->selectedFont)
emit(currentFontChanged(selectedFont));
d->selectedFont = selectedFont;
emit fontSelected(d->selectedFont);
@@ -1022,6 +1021,7 @@ void QFontDialog::done(int result)
d->receiverToDisconnectOnClose = nullptr;
}
d->memberToDisconnectOnClose.clear();
+ QDialog::done(result);
}
bool QFontDialogPrivate::canBeNativeDialog() const
@@ -1037,9 +1037,7 @@ bool QFontDialogPrivate::canBeNativeDialog() const
return false;
}
- QLatin1String staticName(QFontDialog::staticMetaObject.className());
- QLatin1String dynamicName(q->metaObject()->className());
- return (staticName == dynamicName);
+ return strcmp(QFontDialog::staticMetaObject.className(), q->metaObject()->className()) == 0;
}
QT_END_NAMESPACE
diff --git a/src/widgets/dialogs/qfontdialog.h b/src/widgets/dialogs/qfontdialog.h
index ae1320e779..b2900d6a6b 100644
--- a/src/widgets/dialogs/qfontdialog.h
+++ b/src/widgets/dialogs/qfontdialog.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFONTDIALOG_H
#define QFONTDIALOG_H
@@ -106,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 202247a3b4..89b795f35e 100644
--- a/src/widgets/dialogs/qfontdialog_p.h
+++ b/src/widgets/dialogs/qfontdialog_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFONTDIALOG_P_H
#define QFONTDIALOG_P_H
@@ -57,6 +21,8 @@
#include "qfontdatabase.h"
#include "qfontdialog.h"
#include <qpa/qplatformdialoghelper.h>
+
+#include <QtCore/qpointer.h>
#include "qsharedpointer.h"
QT_REQUIRE_CONFIG(fontdialog);
@@ -91,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();
@@ -130,7 +96,6 @@ public:
QDialogButtonBox *buttonBox;
- QFontDatabase fdb;
QString family;
QFontDatabase::WritingSystem writingSystem;
QString style;
@@ -142,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/qfscompleter_p.h b/src/widgets/dialogs/qfscompleter_p.h
index f5110a7622..3981e8a3af 100644
--- a/src/widgets/dialogs/qfscompleter_p.h
+++ b/src/widgets/dialogs/qfscompleter_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFSCOMPLETOR_P_H
#define QFSCOMPLETOR_P_H
@@ -53,7 +17,7 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "qcompleter.h"
-#include <QtWidgets/qfilesystemmodel.h>
+#include <QtGui/qfilesystemmodel.h>
QT_REQUIRE_CONFIG(fscompleter);
diff --git a/src/widgets/dialogs/qinputdialog.cpp b/src/widgets/dialogs/qinputdialog.cpp
index 1cb4be0682..6d1a0b2873 100644
--- a/src/widgets/dialogs/qinputdialog.cpp
+++ b/src/widgets/dialogs/qinputdialog.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qinputdialog.h"
@@ -54,6 +18,8 @@
#include "qevent.h"
#include "qdialog_p.h"
+#include <QtCore/qpointer.h>
+
QT_USE_NAMESPACE
enum CandidateSignal {
@@ -74,8 +40,7 @@ static const char *candidateSignal(int which)
case NumCandidateSignals:
break;
};
- Q_UNREACHABLE();
- return nullptr;
+ Q_UNREACHABLE_RETURN(nullptr);
}
static const char *signalForMember(const char *member)
@@ -105,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:
@@ -118,9 +85,7 @@ private slots:
private:
void keyPressEvent(QKeyEvent *event) override {
if ((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && !hasAcceptableInput()) {
-#ifndef QT_NO_PROPERTIES
setProperty("value", property("value"));
-#endif
} else {
QSpinBox::keyPressEvent(event);
}
@@ -140,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:
@@ -153,9 +120,7 @@ private slots:
private:
void keyPressEvent(QKeyEvent *event) override {
if ((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && !hasAcceptableInput()) {
-#ifndef QT_NO_PROPERTIES
setProperty("value", property("value"));
-#endif
} else {
QDoubleSpinBox::keyPressEvent(event);
}
@@ -202,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;
@@ -248,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);
@@ -269,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);
}
}
@@ -284,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);
}
}
@@ -298,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(currentIndexChanged(QString)),
- q, SLOT(_q_textChanged(QString)));
+ QObjectPrivate::connect(comboBox, &QComboBox::editTextChanged,
+ this, &QInputDialogPrivate::textChanged);
+ QObjectPrivate::connect(comboBox, &QComboBox::currentTextChanged,
+ this, &QInputDialogPrivate::textChanged);
}
}
@@ -316,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);
}
}
@@ -328,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);
}
}
@@ -339,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);
}
}
@@ -415,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());
}
}
@@ -451,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) {
@@ -460,7 +425,7 @@ void QInputDialogPrivate::_q_textChanged(const QString &text)
}
}
-void QInputDialogPrivate::_q_plainTextEditTextChanged()
+void QInputDialogPrivate::plainTextEditTextChanged()
{
Q_Q(QInputDialog);
QString text = plainTextEdit->toPlainText();
@@ -470,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);
}
@@ -1322,67 +1287,6 @@ int QInputDialog::getInt(QWidget *parent, const QString &title, const QString &l
}
/*!
- \fn int QInputDialog::getInteger(QWidget *parent, const QString &title, const QString &label, int value, int min, int max, int step, bool *ok, Qt::WindowFlags flags)
- \deprecated use getInt()
-
- Static convenience function to get an integer input from the user.
-
- \a title is the text which is displayed in the title bar of the dialog.
- \a label is the text which is shown to the user (it should say what should
- be entered).
- \a value is the default integer which the spinbox will be set to.
- \a min and \a max are the minimum and maximum values the user may choose.
- \a step is the amount by which the values change as the user presses the
- arrow buttons to increment or decrement the value.
-
- If \a ok is nonnull *\a ok will be set to true if the user pressed \uicontrol OK
- and to false if the user pressed \uicontrol Cancel. The dialog's parent is
- \a parent. The dialog will be modal and uses the widget \a flags.
-
- On success, this function returns the integer which has been entered by the
- user; on failure, it returns the initial \a value.
-
- Use this static function like this:
-
- \snippet dialogs/standarddialogs/dialog.cpp 0
-
- \sa getText(), getDouble(), getItem(), getMultiLineText()
-*/
-
-/*!
- Static convenience function to get a floating point number from the user.
-
- \a title is the text which is displayed in the title bar of the dialog.
- \a label is the text which is shown to the user (it should say what should
- be entered).
- \a value is the default floating point number that the line edit will be
- set to.
- \a min and \a max are the minimum and maximum values the user may choose.
- \a decimals is the maximum number of decimal places the number may have.
-
- If \a ok is nonnull, *\a ok will be set to true if the user pressed \uicontrol OK
- and to false if the user pressed \uicontrol Cancel. The dialog's parent is
- \a parent. The dialog will be modal and uses the widget \a flags.
-
- This function returns the floating point number which has been entered by
- the user.
-
- Use this static function like this:
-
- \snippet dialogs/standarddialogs/dialog.cpp 1
-
- \sa getText(), getInt(), getItem(), getMultiLineText()
-*/
-
-double QInputDialog::getDouble(QWidget *parent, const QString &title, const QString &label,
- double value, double min, double max, int decimals, bool *ok,
- Qt::WindowFlags flags)
-{
- return QInputDialog::getDouble(parent, title, label, value, min, max, decimals, ok, flags, 1.0);
-}
-
-/*!
- \overload
Static convenience function to get a floating point number from the user.
\a title is the text which is displayed in the title bar of the dialog.
diff --git a/src/widgets/dialogs/qinputdialog.h b/src/widgets/dialogs/qinputdialog.h
index c3a5e59d53..bbf757e6e6 100644
--- a/src/widgets/dialogs/qinputdialog.h
+++ b/src/widgets/dialogs/qinputdialog.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QINPUTDIALOG_H
#define QINPUTDIALOG_H
@@ -56,7 +20,6 @@ class Q_WIDGETS_EXPORT QInputDialog : public QDialog
{
Q_OBJECT
Q_DECLARE_PRIVATE(QInputDialog)
-// Q_ENUMS(InputMode InputDialogOption)
QDOC_PROPERTY(InputMode inputMode READ inputMode WRITE setInputMode)
QDOC_PROPERTY(QString labelText READ labelText WRITE setLabelText)
QDOC_PROPERTY(InputDialogOptions options READ options WRITE setOptions)
@@ -176,28 +139,16 @@ public:
static int getInt(QWidget *parent, const QString &title, const QString &label, int value = 0,
int minValue = -2147483647, int maxValue = 2147483647,
int step = 1, bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags());
+
static double getDouble(QWidget *parent, const QString &title, const QString &label, double value = 0,
double minValue = -2147483647, double maxValue = 2147483647,
- int decimals = 1, bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags());
- // ### Qt 6: merge overloads
- static double getDouble(QWidget *parent, const QString &title, const QString &label, double value,
- double minValue, double maxValue, int decimals, bool *ok, Qt::WindowFlags flags,
- double step);
-
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED static inline int getInteger(QWidget *parent, const QString &title, const QString &label, int value = 0,
- int minValue = -2147483647, int maxValue = 2147483647,
- int step = 1, bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags())
- {
- return getInt(parent, title, label, value, minValue, maxValue, step, ok, flags);
- }
-#endif
+ int decimals = 1, bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags(),
+ double step = 1);
void setDoubleStep(double step);
double doubleStep() const;
Q_SIGNALS:
- // ### emit signals!
void textValueChanged(const QString &text);
void textValueSelected(const QString &text);
void intValueChanged(int value);
@@ -210,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 854fee6e33..bf56b17f55 100644
--- a/src/widgets/dialogs/qmessagebox.cpp
+++ b/src/widgets/dialogs/qmessagebox.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 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 <QtWidgets/qmessagebox.h>
@@ -47,7 +11,6 @@
#include <QtWidgets/qstyle.h>
#include <QtWidgets/qstyleoption.h>
#include <QtWidgets/qgridlayout.h>
-#include <QtWidgets/qdesktopwidget.h>
#include <QtWidgets/qpushbutton.h>
#include <QtWidgets/qcheckbox.h>
#include <QtGui/qaccessible.h>
@@ -65,16 +28,25 @@
#include <QtGui/qfontmetrics.h>
#include <QtGui/qclipboard.h>
#include "private/qabstractbutton_p.h"
-#include <private/qdesktopwidget_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
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+using namespace Qt::StringLiterals;
+
+#if defined(Q_OS_WIN)
HMENU qt_getWindowsSystemMenu(const QWidget *w)
{
if (QWindow *window = QApplicationPrivate::windowForWidget(w))
@@ -84,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 };
@@ -101,9 +87,10 @@ public:
#ifndef QT_NO_CONTEXTMENU
void contextMenuEvent(QContextMenuEvent * e) override
{
- QMenu *menu = createStandardContextMenu();
- menu->setAttribute(Qt::WA_DeleteOnClose);
- menu->popup(e->globalPos());
+ if (QMenu *menu = createStandardContextMenu()) {
+ menu->setAttribute(Qt::WA_DeleteOnClose);
+ menu->popup(e->globalPos());
+ }
}
#endif // QT_NO_CONTEXTMENU
};
@@ -125,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(); }
@@ -182,12 +169,10 @@ public:
const QFontMetrics fm = fontMetrics();
opt.text = label(ShowLabel);
QSize sz = fm.size(Qt::TextShowMnemonic, opt.text);
- QSize ret = style()->sizeFromContents(QStyle::CT_PushButton, &opt, sz, this).
- expandedTo(QApplication::globalStrut());
+ QSize ret = style()->sizeFromContents(QStyle::CT_PushButton, &opt, sz, this);
opt.text = label(HideLabel);
sz = fm.size(Qt::TextShowMnemonic, opt.text);
- ret = ret.expandedTo(style()->sizeFromContents(QStyle::CT_PushButton, &opt, sz, this).
- expandedTo(QApplication::globalStrut()));
+ ret = ret.expandedTo(style()->sizeFromContents(QStyle::CT_PushButton, &opt, sz, this));
return ret;
}
};
@@ -207,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);
@@ -217,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);
@@ -240,6 +226,7 @@ public:
QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton);
static QPixmap standardIcon(QMessageBox::Icon icon, QMessageBox *mb);
+ static QMessageBox::StandardButton standardButtonForRole(QMessageBox::ButtonRole role);
QLabel *label;
QMessageBox::Icon icon;
@@ -265,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)
@@ -273,19 +260,19 @@ void QMessageBoxPrivate::init(const QString &title, const QString &text)
Q_Q(QMessageBox);
label = new QLabel;
- label->setObjectName(QLatin1String("qt_msgbox_label"));
+ label->setObjectName("qt_msgbox_label"_L1);
label->setTextInteractionFlags(Qt::TextInteractionFlags(q->style()->styleHint(QStyle::SH_MessageBox_TextInteractionFlags, nullptr, q)));
label->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
label->setOpenExternalLinks(true);
iconLabel = new QLabel(q);
- iconLabel->setObjectName(QLatin1String("qt_msgboxex_icon_label"));
+ iconLabel->setObjectName("qt_msgboxex_icon_label"_L1);
iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
buttonBox = new QDialogButtonBox;
- buttonBox->setObjectName(QLatin1String("qt_msgbox_buttonbox"));
+ 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);
@@ -305,7 +292,7 @@ void QMessageBoxPrivate::setupLayout()
Q_Q(QMessageBox);
delete q->layout();
QGridLayout *grid = new QGridLayout;
- bool hasIcon = iconLabel->pixmap() && !iconLabel->pixmap()->isNull();
+ const bool hasIcon = !iconLabel->pixmap().isNull();
if (hasIcon)
grid->addWidget(iconLabel, 0, 0, 2, 1, Qt::AlignTop);
@@ -333,7 +320,7 @@ void QMessageBoxPrivate::setupLayout()
}
#ifdef Q_OS_MAC
grid->addWidget(buttonBox, grid->rowCount(), hasIcon ? 2 : 1, 1, 1);
- grid->setMargin(0);
+ grid->setContentsMargins(0, 0, 0, 0);
grid->setVerticalSpacing(8);
grid->setHorizontalSpacing(0);
q->setContentsMargins(24, 15, 24, 20);
@@ -366,7 +353,7 @@ void QMessageBoxPrivate::updateSize()
if (!q->isVisible())
return;
- QSize screenSize = QDesktopWidgetPrivate::availableGeometry(QCursor::pos()).size();
+ const QSize screenSize = q->screen()->availableGeometry().size();
int hardLimit = qMin(screenSize.width() - 480, 1000); // can never get bigger than this
// on small screens allows the messagebox be the same size as the screen
if (screenSize.width() <= 1024)
@@ -460,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)
@@ -521,23 +521,26 @@ void QMessageBoxPrivate::setClickedButton(QAbstractButton *button)
emit q->buttonClicked(clickedButton);
auto resultCode = execReturnCode(button);
- hide(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();
}
/*!
@@ -551,10 +554,11 @@ void QMessageBoxPrivate::_q_clicked(QPlatformDialogHelper::StandardButton button
A message box displays a primary \l{QMessageBox::text}{text} to
alert the user to a situation, an \l{QMessageBox::informativeText}
- {informative text} to further explain the alert or to ask the user
- a question, and an optional \l{QMessageBox::detailedText}
- {detailed text} to provide even more data if the user requests
- it. A message box can also display an \l{QMessageBox::icon} {icon}
+ {informative text} to further explain the situation, and an optional
+ \l{QMessageBox::detailedText} {detailed text} to provide even more data
+ if the user requests it.
+
+ A message box can also display an \l{QMessageBox::icon} {icon}
and \l{QMessageBox::standardButtons} {standard buttons} for
accepting a user response.
@@ -580,27 +584,21 @@ void QMessageBoxPrivate::_q_clicked(QPlatformDialogHelper::StandardButton button
\image msgbox1.png
A better approach than just alerting the user to an event is to
- also ask the user what to do about it. Store the question in the
- \l{QMessageBox::informativeText} {informative text} property, and
- set the \l{QMessageBox::standardButtons} {standard buttons}
+ also ask the user what to do about it.
+
+ Set the \l{QMessageBox::standardButtons} {standard buttons}
property to the set of buttons you want as the set of user
responses. The buttons are specified by combining values from
StandardButtons using the bitwise OR operator. The display order
for the buttons is platform-dependent. For example, on Windows,
\uicontrol{Save} is displayed to the left of \uicontrol{Cancel}, whereas on
- Mac OS, the order is reversed.
-
- Mark one of your standard buttons to be your
+ \macos, the order is reversed. Mark one of your standard buttons to be your
\l{QMessageBox::defaultButton()} {default button}.
- \snippet code/src_gui_dialogs_qmessagebox.cpp 6
+ The \l{QMessageBox::informativeText} {informative text} property can
+ be used to add additional context to help the user choose the appropriate action.
- This is the approach recommended in the
- \l{http://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/AppleHIGuidelines/Windows/Windows.html#//apple_ref/doc/uid/20000961-BABCAJID}
- {\macos Guidelines}. Similar guidelines apply for the other
- platforms, but note the different ways the
- \l{QMessageBox::informativeText} {informative text} is handled for
- different platforms.
+ \snippet code/src_gui_dialogs_qmessagebox.cpp 6
\image msgbox2.png
@@ -609,10 +607,10 @@ void QMessageBoxPrivate::_q_clicked(QPlatformDialogHelper::StandardButton button
\snippet code/src_gui_dialogs_qmessagebox.cpp 7
- To give the user more information to help him answer the question,
- set the \l{QMessageBox::detailedText} {detailed text} property. If
- the \l{QMessageBox::detailedText} {detailed text} property is set,
- the \uicontrol{Show Details...} button will be shown.
+ To give the user more information to help them choose the appropriate,
+ action, set the \l{QMessageBox::detailedText} {detailed text} property.
+ Depending on the platform the \l{QMessageBox::detailedText} {detailed text},
+ may require the user to click a \uicontrol{Show Details...} button to be shown.
\image msgbox3.png
@@ -752,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, {fowler}{GUI Design Handbook: Message Box}, {Standard Dialogs Example}, {Application Example}
+ \sa QDialogButtonBox, {Standard Dialogs Example}
*/
/*!
@@ -808,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.
@@ -815,14 +819,21 @@ void QMessageBoxPrivate::_q_clicked(QPlatformDialogHelper::StandardButton button
*/
/*!
- Constructs a message box with no text and no buttons. \a parent is
- passed to the QDialog constructor.
+ Constructs an \l{Qt::ApplicationModal} {application modal} message box with no text and no buttons.
+ \a parent is passed to the QDialog constructor.
+
+ The window modality can be overridden via setWindowModality() before calling show().
+
+ \note Using open() or exec() to show the message box affects the window modality.
+ Please see the detailed documentation for each function for more information.
On \macos, if you want your message box to appear
as a Qt::Sheet of its \a parent, set the message box's
\l{setWindowModality()} {window modality} to Qt::WindowModal or use open().
Otherwise, the message box will be a standard dialog.
+ \sa setWindowTitle(), setText(), setIcon(), setStandardButtons(), setWindowModality()
+
*/
QMessageBox::QMessageBox(QWidget *parent)
: QDialog(*new QMessageBoxPrivate, parent, Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint)
@@ -832,20 +843,22 @@ QMessageBox::QMessageBox(QWidget *parent)
}
/*!
- Constructs a message box with the given \a icon, \a title, \a
- text, and standard \a buttons. Standard or custom buttons can be
+ Constructs an \l{Qt::ApplicationModal} {application modal} message box with the given \a icon,
+ \a title, \a text, and standard \a buttons. Standard or custom buttons can be
added at any time using addButton(). The \a parent and \a f
arguments are passed to the QDialog constructor.
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
+ The window modality can be overridden via setWindowModality() before calling show().
+
+ \note Using open() or exec() to show the message box affects the window modality.
+ Please see the detailed documentation for each function for more information.
On \macos, if \a parent is not \nullptr and you want your message box
to appear as a Qt::Sheet of that parent, set the message box's
\l{setWindowModality()} {window modality} to Qt::WindowModal
(default). Otherwise, the message box will be a standard dialog.
- \sa setWindowTitle(), setText(), setIcon(), setStandardButtons()
+ \sa setWindowTitle(), setText(), setIcon(), setStandardButtons(), setWindowModality()
*/
QMessageBox::QMessageBox(Icon icon, const QString &title, const QString &text,
StandardButtons buttons, QWidget *parent,
@@ -880,13 +893,39 @@ void QMessageBox::addButton(QAbstractButton *button, ButtonRole role)
if (!button)
return;
removeButton(button);
- d->options->addButton(button->text(), static_cast<QPlatformDialogHelper::ButtonRole>(role),
- button);
+
+ if (button->text().isEmpty()) {
+ if (auto *platformTheme = QGuiApplicationPrivate::platformTheme()) {
+ if (auto standardButton = QMessageBoxPrivate::standardButtonForRole(role))
+ button->setText(platformTheme->standardButtonText(standardButton));
+ }
+
+ if (button->text().isEmpty()) {
+ qWarning() << "Cannot add" << button << "without title";
+ return;
+ }
+ }
+
d->buttonBox->addButton(button, (QDialogButtonBox::ButtonRole)role);
d->customButtonList.append(button);
d->autoAddOkButton = false;
}
+QMessageBox::StandardButton QMessageBoxPrivate::standardButtonForRole(QMessageBox::ButtonRole role)
+{
+ switch (role) {
+ case QMessageBox::AcceptRole: return QMessageBox::Ok;
+ case QMessageBox::RejectRole: return QMessageBox::Cancel;
+ case QMessageBox::DestructiveRole: return QMessageBox::Discard;
+ case QMessageBox::HelpRole: return QMessageBox::Help;
+ case QMessageBox::ApplyRole: return QMessageBox::Apply;
+ case QMessageBox::YesRole: return QMessageBox::Yes;
+ case QMessageBox::NoRole: return QMessageBox::No;
+ case QMessageBox::ResetRole: return QMessageBox::Reset;
+ default: return QMessageBox::NoButton;
+ }
+}
+
/*!
\since 4.2
\overload
@@ -991,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
@@ -1068,14 +1113,14 @@ void QMessageBoxPrivate::detectEscapeButton()
// If there is only one button, make it the escape button
const QList<QAbstractButton *> buttons = buttonBox->buttons();
- if (buttons.count() == 1) {
+ if (buttons.size() == 1) {
detectedEscapeButton = buttons.first();
return;
}
// If there are two buttons and one of them is the "Show Details..."
// button, then make the other one the escape button
- if (buttons.count() == 2 && detailsButton) {
+ if (buttons.size() == 2 && detailsButton) {
auto idx = buttons.indexOf(detailsButton);
if (idx != -1) {
detectedEscapeButton = buttons.at(1 - idx);
@@ -1222,9 +1267,84 @@ 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.
+ The text should be a brief sentence or phrase that describes the situation,
+ ideally formulated as a neutral statement, or a call-to-action question.
+
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
@@ -1323,9 +1443,7 @@ void QMessageBox::setIcon(Icon icon)
QPixmap QMessageBox::iconPixmap() const
{
Q_D(const QMessageBox);
- if (d->iconLabel && d->iconLabel->pixmap())
- return *d->iconLabel->pixmap();
- return QPixmap();
+ return d->iconLabel->pixmap();
}
void QMessageBox::setIconPixmap(const QPixmap &pixmap)
@@ -1359,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();
}
@@ -1424,8 +1544,10 @@ void QMessageBox::closeEvent(QCloseEvent *e)
return;
}
QDialog::closeEvent(e);
- d->clickedButton = d->detectedEscapeButton;
- setResult(d->execReturnCode(d->detectedEscapeButton));
+ if (!d->clickedButton) {
+ d->clickedButton = d->detectedEscapeButton;
+ setResult(d->execReturnCode(d->detectedEscapeButton));
+ }
}
/*!
@@ -1498,21 +1620,21 @@ void QMessageBox::keyPressEvent(QKeyEvent *e)
#if defined(Q_OS_WIN)
if (e == QKeySequence::Copy) {
- const QLatin1String separator("---------------------------\n");
+ const auto separator = "---------------------------\n"_L1;
QString textToCopy;
- textToCopy += separator + windowTitle() + QLatin1Char('\n') + separator // title
- + d->label->text() + QLatin1Char('\n') + separator; // text
+ textToCopy += separator + windowTitle() + u'\n' + separator // title
+ + d->label->text() + u'\n' + separator; // text
if (d->informativeLabel)
- textToCopy += d->informativeLabel->text() + QLatin1Char('\n') + separator;
+ textToCopy += d->informativeLabel->text() + u'\n' + separator;
const QList<QAbstractButton *> buttons = d->buttonBox->buttons();
for (const auto *button : buttons)
- textToCopy += button->text() + QLatin1String(" ");
- textToCopy += QLatin1Char('\n') + separator;
+ textToCopy += button->text() + " "_L1;
+ textToCopy += u'\n' + separator;
#if QT_CONFIG(textedit)
if (d->detailsText)
- textToCopy += d->detailsText->text() + QLatin1Char('\n') + separator;
+ textToCopy += d->detailsText->text() + u'\n' + separator;
#endif
QGuiApplication::clipboard()->setText(textToCopy);
return;
@@ -1528,7 +1650,7 @@ void QMessageBox::keyPressEvent(QKeyEvent *e)
const QList<QAbstractButton *> buttons = d->buttonBox->buttons();
for (auto *pb : buttons) {
QKeySequence shortcut = pb->shortcut();
- if (!shortcut.isEmpty() && key == int(shortcut[0] & ~Qt::MODIFIER_MASK)) {
+ if (!shortcut.isEmpty() && key == shortcut[0].key()) {
pb->animateClick();
return;
}
@@ -1559,6 +1681,26 @@ void QMessageBox::open(QObject *receiver, const char *member)
QDialog::open();
}
+void QMessageBoxPrivate::setVisible(bool visible)
+{
+ Q_Q(QMessageBox);
+
+ // 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.
+ q->setAttribute(Qt::WA_DontShowOnScreen, nativeDialogInUse);
+
+ QDialogPrivate::setVisible(visible);
+}
+
/*!
\since 4.5
@@ -1592,19 +1734,14 @@ 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->detectEscapeButton();
+ d->clickedButton = nullptr;
d->updateSize();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleEvent event(this, QAccessible::Alert);
QAccessible::updateAccessibility(&event);
#endif
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+#if defined(Q_OS_WIN)
if (const HMENU systemMenu = qt_getWindowsSystemMenu(this)) {
EnableMenuItem(systemMenu, SC_CLOSE, d->detectedEscapeButton ?
MF_BYCOMMAND|MF_ENABLED : MF_BYCOMMAND|MF_GRAYED);
@@ -1622,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*>();
@@ -1795,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()
*/
@@ -1814,7 +1955,7 @@ void QMessageBox::about(QWidget *parent, const QString &title, const QString &te
}
#endif
- QMessageBox *msgBox = new QMessageBox(title, text, Information, 0, 0, 0, parent
+ QMessageBox *msgBox = new QMessageBox(Information, title, text, NoButton, parent
#ifdef Q_OS_MAC
, Qt::WindowTitleHint | Qt::WindowSystemMenuHint
#endif
@@ -1827,11 +1968,12 @@ 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);
+ msgBox->setModal(false);
#endif
msgBox->show();
#else
@@ -1849,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()
@@ -1871,7 +2013,7 @@ void QMessageBox::aboutQt(QWidget *parent, const QString &title)
translatedTextAboutQtCaption = QMessageBox::tr(
"<h3>About Qt</h3>"
"<p>This program uses Qt version %1.</p>"
- ).arg(QLatin1String(QT_VERSION_STR));
+ ).arg(QT_VERSION_STR ""_L1);
//: Leave this text untranslated or include a verbatim copy of it below
//: and note that it is the authoritative version in case of doubt.
const QString translatedTextAboutQtText = QMessageBox::tr(
@@ -1889,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("2020"),
- 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);
@@ -1905,18 +2046,19 @@ void QMessageBox::aboutQt(QWidget *parent, const QString &title)
msgBox->setText(translatedTextAboutQtCaption);
msgBox->setInformativeText(translatedTextAboutQtText);
- QPixmap pm(QLatin1String(":/qt-project.org/qmessagebox/images/qtlogo-64.png"));
+ QPixmap pm(":/qt-project.org/qmessagebox/images/qtlogo-64.png"_L1);
if (!pm.isNull())
msgBox->setIconPixmap(pm);
// 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);
+ msgBox->setModal(false);
#endif
msgBox->show();
#else
@@ -1933,33 +2075,7 @@ static QMessageBox::StandardButton newButton(int button)
if (button == QMessageBox::NoButton || (button & NewButtonMask))
return QMessageBox::StandardButton(button & QMessageBox::ButtonMask);
-#if QT_VERSION < 0x050000
- // this is needed for binary compatibility with Qt 4.0 and 4.1
- switch (button & Old_ButtonMask) {
- case Old_Ok:
- return QMessageBox::Ok;
- case Old_Cancel:
- return QMessageBox::Cancel;
- case Old_Yes:
- return QMessageBox::Yes;
- case Old_No:
- return QMessageBox::No;
- case Old_Abort:
- return QMessageBox::Abort;
- case Old_Retry:
- return QMessageBox::Retry;
- case Old_Ignore:
- return QMessageBox::Ignore;
- case Old_YesAll:
- return QMessageBox::YesToAll;
- case Old_NoAll:
- return QMessageBox::NoToAll;
- default:
- return QMessageBox::NoButton;
- }
-#else
return QMessageBox::NoButton;
-#endif
}
static bool detectedCompat(int button0, int button1, int button2)
@@ -2048,13 +2164,14 @@ int QMessageBoxPrivate::showOldMessageBox(QWidget *parent, QMessageBox::Icon ico
void QMessageBoxPrivate::retranslateStrings()
{
#if QT_CONFIG(textedit)
- if (detailsButton)
+ if (detailsButton && detailsText)
detailsButton->setLabel(detailsText->isHidden() ? ShowLabel : HideLabel);
#endif
}
+#if QT_DEPRECATED_SINCE(6,2)
/*!
- \obsolete
+ \deprecated
Constructs a message box with a \a title, a \a text, an \a icon,
and up to three buttons.
@@ -2118,7 +2235,7 @@ QMessageBox::QMessageBox(const QString &title, const QString &text, Icon icon,
}
/*!
- \obsolete
+ \deprecated [6.2]. Use the overload taking StandardButtons instead.
Opens an information message box with the given \a title and the
\a text. The dialog may have up to three buttons. Each of the
@@ -2164,7 +2281,7 @@ int QMessageBox::information(QWidget *parent, const QString &title, const QStrin
}
/*!
- \obsolete
+ \deprecated [6.2] Use the overload taking StandardButtons instead.
\overload
Displays an information message box with the given \a title and
@@ -2204,7 +2321,8 @@ int QMessageBox::information(QWidget *parent, const QString &title, const QStrin
}
/*!
- \obsolete
+ \deprecated [6.2]. Use the overload taking StandardButtons
+ instead.
Opens a question message box with the given \a title and \a text.
The dialog may have up to three buttons. Each of the buttons, \a
@@ -2250,7 +2368,7 @@ int QMessageBox::question(QWidget *parent, const QString &title, const QString&
}
/*!
- \obsolete
+ \deprecated [6.2]. Use the overload taking StandardButtons instead.
\overload
Displays a question message box with the given \a title and \a
@@ -2290,7 +2408,7 @@ int QMessageBox::question(QWidget *parent, const QString &title, const QString&
/*!
- \obsolete
+ \deprecated [6.2]. Use the overload taking StandardButtons instead.
Opens a warning message box with the given \a title and \a text.
The dialog may have up to three buttons. Each of the button
@@ -2336,7 +2454,7 @@ int QMessageBox::warning(QWidget *parent, const QString &title, const QString& t
}
/*!
- \obsolete
+ \deprecated [6.2]. Use the overload taking StandardButtons instead.
\overload
Displays a warning message box with the given \a title and \a
@@ -2375,7 +2493,7 @@ int QMessageBox::warning(QWidget *parent, const QString &title, const QString& t
}
/*!
- \obsolete
+ \deprecated [6.2]. Use the overload taking StandardButtons instead.
Opens a critical message box with the given \a title and \a text.
The dialog may have up to three buttons. Each of the button
@@ -2422,7 +2540,7 @@ int QMessageBox::critical(QWidget *parent, const QString &title, const QString&
}
/*!
- \obsolete
+ \deprecated [6.2]. Use the overload taking StandardButtons instead.
\overload
Displays a critical error message box with the given \a title and
@@ -2462,7 +2580,7 @@ int QMessageBox::critical(QWidget *parent, const QString &title, const QString&
/*!
- \obsolete
+ \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
}
/*!
- \obsolete
+ \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
@@ -2501,6 +2619,8 @@ void QMessageBox::setButtonText(int button, const QString &text)
addButton(QMessageBox::Ok)->setText(text);
}
}
+#endif // QT_DEPRECATED_SINCE(6,2)
+
#if QT_CONFIG(textedit)
/*!
@@ -2560,14 +2680,18 @@ void QMessageBox::setDetailedText(const QString &text)
\since 4.2
- Infromative text can be used to expand upon the text() to give more
- information to the user. On the Mac, this text appears in small
- system font below the text(). On other platforms, it is simply
- appended to the existing text.
+ Informative text can be used to expand upon the text() to give more
+ 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
{
@@ -2587,16 +2711,16 @@ void QMessageBox::setInformativeText(const QString &text)
} else {
if (!d->informativeLabel) {
QLabel *label = new QLabel;
- label->setObjectName(QLatin1String("qt_msgbox_informativelabel"));
+ label->setObjectName("qt_msgbox_informativelabel"_L1);
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);
@@ -2664,27 +2788,34 @@ QPixmap QMessageBoxPrivate::standardIcon(QMessageBox::Icon icon, QMessageBox *mb
break;
case QMessageBox::Question:
tmpIcon = style->standardIcon(QStyle::SP_MessageBoxQuestion, nullptr, mb);
+ break;
default:
break;
}
if (!tmpIcon.isNull()) {
- QWindow *window = mb
- ? qt_widget_private(mb)->windowHandle(QWidgetPrivate::WindowHandleMode::Closest)
- : nullptr;
- return tmpIcon.pixmap(window, QSize(iconSize, iconSize));
+ qreal dpr = mb ? mb->devicePixelRatio() : qApp->devicePixelRatio();
+ return tmpIcon.pixmap(QSize(iconSize, iconSize), dpr);
}
return QPixmap();
}
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:
@@ -2707,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);
@@ -2716,22 +2877,80 @@ void QMessageBoxPrivate::helperPrepareShow(QPlatformDialogHelper *)
#if QT_CONFIG(textedit)
options->setDetailedText(q->detailedText());
#endif
- options->setIcon(helperIcon(q->icon()));
- options->setStandardButtons(helperStandardButtons(q));
+ options->setStandardIcon(helperIcon(q->icon()));
+ options->setIconPixmap(q->iconPixmap());
+
+ // 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)
/*!
- \obsolete
+ \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
@@ -2747,10 +2966,11 @@ QPixmap QMessageBox::standardIcon(Icon icon)
{
return QMessageBoxPrivate::standardIcon(icon, nullptr);
}
+#endif
/*!
\typedef QMessageBox::Button
- \obsolete
+ \deprecated
Use QMessageBox::StandardButton instead.
*/
@@ -2794,6 +3014,25 @@ QPixmap QMessageBox::standardIcon(Icon icon)
\sa show(), result()
*/
+/*!
+ \macro QT_REQUIRE_VERSION(int argc, char **argv, const char *version)
+ \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
+ if your application depends on a specific bug fix introduced in a
+ bug-fix release (for example, 6.1.2).
+
+ The \a argc and \a argv parameters are the \c main() function's
+ \c argc and \c argv parameters. The \a version parameter is a
+ string literal that specifies which version of Qt the application
+ requires (for example, "6.1.2").
+
+ Example:
+
+ \snippet code/src_gui_dialogs_qmessagebox.cpp 4
+*/
+
QT_END_NAMESPACE
#include "moc_qmessagebox.cpp"
diff --git a/src/widgets/dialogs/qmessagebox.h b/src/widgets/dialogs/qmessagebox.h
index 0a2edb1eee..751674466c 100644
--- a/src/widgets/dialogs/qmessagebox.h
+++ b/src/widgets/dialogs/qmessagebox.h
@@ -1,53 +1,18 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMESSAGEBOX_H
#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;
@@ -65,11 +30,18 @@ class Q_WIDGETS_EXPORT QMessageBox : public QDialog
Q_PROPERTY(QString detailedText READ detailedText WRITE setDetailedText)
#endif
Q_PROPERTY(QString informativeText READ informativeText WRITE setInformativeText)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
-
+ 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,
@@ -93,6 +65,7 @@ public:
NRoles
};
+ Q_ENUM(ButtonRole)
enum StandardButton {
// keep this in sync with QDialogButtonBox::StandardButton and QPlatformDialogHelper::StandardButton
@@ -127,9 +100,14 @@ public:
FlagMask = 0x00000300, // obsolete
ButtonMask = ~FlagMask // obsolete
};
- typedef StandardButton Button; // 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);
@@ -182,31 +160,67 @@ 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);
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) // needed as long as we have int overloads
+ inline static StandardButton information(QWidget *parent, const QString &title,
+ const QString& text,
+ StandardButton button0, StandardButton button1 = NoButton)
+ { return information(parent, title, text, StandardButtons(button0), button1); }
+#endif
+
static StandardButton question(QWidget *parent, const QString &title,
const QString &text, StandardButtons buttons = StandardButtons(Yes | No),
StandardButton defaultButton = NoButton);
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
+ inline static int question(QWidget *parent, const QString &title,
+ const QString& text,
+ StandardButton button0, StandardButton button1)
+ { return question(parent, title, text, StandardButtons(button0), button1); }
+#endif
+
static StandardButton warning(QWidget *parent, const QString &title,
const QString &text, StandardButtons buttons = Ok,
StandardButton defaultButton = NoButton);
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
+ inline static int warning(QWidget *parent, const QString &title,
+ const QString& text,
+ StandardButton button0, StandardButton button1)
+ { return warning(parent, title, text, StandardButtons(button0), button1); }
+#endif
+
static StandardButton critical(QWidget *parent, const QString &title,
const QString &text, StandardButtons buttons = Ok,
StandardButton defaultButton = NoButton);
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
+ inline static int critical(QWidget *parent, const QString &title,
+ const QString& text,
+ StandardButton button0, StandardButton button1)
+ { return critical(parent, title, text, StandardButtons(button0), button1); }
+#endif
+
static void about(QWidget *parent, const QString &title, const QString &text);
static void aboutQt(QWidget *parent, const QString &title = QString());
+#if QT_DEPRECATED_SINCE(6,2)
// the following functions are obsolete:
-
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
QMessageBox(const QString &title, const QString &text, Icon icon,
int button0, int button1, int button2,
QWidget *parent = nullptr,
Qt::WindowFlags f = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
static int information(QWidget *parent, const QString &title,
const QString& text,
int button0, int button1 = 0, int button2 = 0);
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
static int information(QWidget *parent, const QString &title,
const QString& text,
const QString& button0Text,
@@ -214,14 +228,12 @@ public:
const QString& button2Text = QString(),
int defaultButtonNumber = 0,
int escapeButtonNumber = -1);
- inline static StandardButton information(QWidget *parent, const QString &title,
- const QString& text,
- StandardButton button0, StandardButton button1 = NoButton)
- { return information(parent, title, text, StandardButtons(button0), button1); }
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
static int question(QWidget *parent, const QString &title,
const QString& text,
int button0, int button1 = 0, int button2 = 0);
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
static int question(QWidget *parent, const QString &title,
const QString& text,
const QString& button0Text,
@@ -229,14 +241,12 @@ public:
const QString& button2Text = QString(),
int defaultButtonNumber = 0,
int escapeButtonNumber = -1);
- inline static int question(QWidget *parent, const QString &title,
- const QString& text,
- StandardButton button0, StandardButton button1)
- { return question(parent, title, text, StandardButtons(button0), button1); }
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
static int warning(QWidget *parent, const QString &title,
const QString& text,
int button0, int button1, int button2 = 0);
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
static int warning(QWidget *parent, const QString &title,
const QString& text,
const QString& button0Text,
@@ -244,14 +254,12 @@ public:
const QString& button2Text = QString(),
int defaultButtonNumber = 0,
int escapeButtonNumber = -1);
- inline static int warning(QWidget *parent, const QString &title,
- const QString& text,
- StandardButton button0, StandardButton button1)
- { return warning(parent, title, text, StandardButtons(button0), button1); }
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
static int critical(QWidget *parent, const QString &title,
const QString& text,
int button0, int button1, int button2 = 0);
+ QT_DEPRECATED_VERSION_X_6_2("Use the overload taking StandardButtons instead.")
static int critical(QWidget *parent, const QString &title,
const QString& text,
const QString& button0Text,
@@ -259,13 +267,12 @@ public:
const QString& button2Text = QString(),
int defaultButtonNumber = 0,
int escapeButtonNumber = -1);
- inline static int critical(QWidget *parent, const QString &title,
- const QString& text,
- StandardButton button0, StandardButton button1)
- { return critical(parent, title, text, StandardButtons(button0), button1); }
+ QT_DEPRECATED_VERSION_X_6_2("Use button() and QPushButton::text() instead.")
QString buttonText(int button) const;
+ QT_DEPRECATED_VERSION_X_6_2("Use addButton() instead.")
void setButtonText(int button, const QString &text);
+#endif
QString informativeText() const;
void setInformativeText(const QString &text);
@@ -278,13 +285,15 @@ public:
void setWindowTitle(const QString &title);
void setWindowModality(Qt::WindowModality windowModality);
-
+#if QT_DEPRECATED_SINCE(6,2)
+ QT_DEPRECATED_VERSION_X_6_2("Use QStyle::standardIcon() instead.")
static QPixmap standardIcon(Icon icon);
+#endif
Q_SIGNALS:
void buttonClicked(QAbstractButton *button);
-#ifdef Q_CLANG_QDOC
+#ifdef Q_QDOC
public Q_SLOTS:
int exec() override;
#endif
@@ -298,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/qmessagebox.qrc b/src/widgets/dialogs/qmessagebox.qrc
deleted file mode 100644
index de217773ec..0000000000
--- a/src/widgets/dialogs/qmessagebox.qrc
+++ /dev/null
@@ -1,5 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/qt-project.org/qmessagebox">
- <file>images/qtlogo-64.png</file>
-</qresource>
-</RCC>
diff --git a/src/widgets/dialogs/qprogressdialog.cpp b/src/widgets/dialogs/qprogressdialog.cpp
index aaa4430c39..9761bcc828 100644
--- a/src/widgets/dialogs/qprogressdialog.cpp
+++ b/src/widgets/dialogs/qprogressdialog.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qprogressdialog.h"
@@ -51,33 +15,29 @@
#include "qpushbutton.h"
#include "qtimer.h"
#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
{
Q_DECLARE_PUBLIC(QProgressDialog)
public:
- QProgressDialogPrivate() : label(nullptr), cancel(nullptr), bar(nullptr),
- shown_once(false),
- cancellation_flag(false),
- setValue_called(false),
- showTime(defaultShowTime),
-#ifndef QT_NO_SHORTCUT
- escapeShortcut(nullptr),
-#endif
- useDefaultCancelText(false)
- {
- }
+ QProgressDialogPrivate() = default;
void init(const QString &labelText, const QString &cancelText, int min, int max);
void layout();
@@ -87,24 +47,25 @@ public:
void ensureSizeIsAtLeastSizeHint();
void _q_disconnectOnClose();
- QLabel *label;
- QPushButton *cancel;
- QProgressBar *bar;
- QTimer *forceTimer;
- bool shown_once;
- bool cancellation_flag;
- bool setValue_called;
- QElapsedTimer starttime;
- int showTime;
- bool autoClose;
- bool autoReset;
- bool forceHide;
+ QLabel *label = nullptr;
+ QPushButton *cancel = nullptr;
+ QProgressBar *bar = nullptr;
+ QTimer *forceTimer = nullptr;
#ifndef QT_NO_SHORTCUT
- QShortcut *escapeShortcut;
+ QShortcut *escapeShortcut = nullptr;
#endif
- bool useDefaultCancelText;
QPointer<QObject> receiverToDisconnectOnClose;
+ QElapsedTimer starttime;
QByteArray memberToDisconnectOnClose;
+ std::chrono::milliseconds showTime = defaultShowTime;
+ bool processingEvents = false;
+ bool shownOnce = false;
+ bool autoClose = true;
+ bool autoReset = true;
+ bool forceHide = false;
+ bool cancellationFlag = false;
+ bool setValueCalled = false;
+ bool useDefaultCancelText = false;
};
void QProgressDialogPrivate::init(const QString &labelText, const QString &cancelText,
@@ -116,9 +77,6 @@ void QProgressDialogPrivate::init(const QString &labelText, const QString &cance
bar->setRange(min, max);
int align = q->style()->styleHint(QStyle::SH_ProgressDialog_TextLabelAlignment, nullptr, q);
label->setAlignment(Qt::Alignment(align));
- autoClose = true;
- autoReset = true;
- forceHide = false;
QObject::connect(q, SIGNAL(canceled()), q, SLOT(cancel()));
forceTimer = new QTimer(q);
QObject::connect(forceTimer, SIGNAL(timeout()), q, SLOT(forceShow()));
@@ -239,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
@@ -262,8 +221,7 @@ void QProgressDialogPrivate::_q_disconnectOnClose()
\image fusion-progressdialog.png A progress dialog shown in the Fusion widget style.
- \sa QDialog, QProgressBar, {fowler}{GUI Design Handbook: Progress Indicator},
- {Find Files Example}, {Pixelator Example}
+ \sa QDialog, QProgressBar
*/
@@ -414,7 +372,6 @@ void QProgressDialog::setCancelButton(QPushButton *cancelButton)
if (cancelButton) {
connect(d->cancel, SIGNAL(clicked()), this, SIGNAL(canceled()));
#ifndef QT_NO_SHORTCUT
- // FIXME: This only registers the primary key sequence of the cancel action
d->escapeShortcut = new QShortcut(QKeySequence::Cancel, this, SIGNAL(canceled()));
#endif
} else {
@@ -497,6 +454,8 @@ void QProgressDialogPrivate::adoptChildWidget(QWidget *c)
c->setParent(q, { });
}
ensureSizeIsAtLeastSizeHint();
+ //The layout should be updated again to prevent layout errors when the new 'widget' is replaced
+ layout();
if (c)
c->show();
}
@@ -520,7 +479,7 @@ void QProgressDialogPrivate::ensureSizeIsAtLeastSizeHint()
bool QProgressDialog::wasCanceled() const
{
Q_D(const QProgressDialog);
- return d->cancellation_flag;
+ return d->cancellationFlag;
}
@@ -598,9 +557,9 @@ void QProgressDialog::reset()
if (d->autoClose || d->forceHide)
hide();
d->bar->reset();
- d->cancellation_flag = false;
- d->shown_once = false;
- d->setValue_called = false;
+ d->cancellationFlag = false;
+ d->shownOnce = false;
+ d->setValueCalled = false;
d->forceTimer->stop();
/*
@@ -624,7 +583,7 @@ void QProgressDialog::cancel()
d->forceHide = true;
reset();
d->forceHide = false;
- d->cancellation_flag = true;
+ d->cancellationFlag = true;
}
@@ -654,45 +613,46 @@ int QProgressDialog::value() const
void QProgressDialog::setValue(int progress)
{
Q_D(QProgressDialog);
- if (d->setValue_called && progress == d->bar->value())
+ if (d->setValueCalled && progress == d->bar->value())
return;
d->bar->setValue(progress);
- if (d->shown_once) {
- if (isModal())
+ if (d->shownOnce) {
+ if (isModal() && !d->processingEvents) {
+ const QScopedValueRollback guard(d->processingEvents, true);
QCoreApplication::processEvents();
+ }
} else {
- if ((!d->setValue_called && progress == 0 /* for compat with Qt < 5.4 */) || progress == minimum()) {
+ if ((!d->setValueCalled && progress == 0 /* for compat with Qt < 5.4 */) || progress == minimum()) {
d->starttime.start();
d->forceTimer->start(d->showTime);
- d->setValue_called = true;
+ d->setValueCalled = true;
return;
} else {
- d->setValue_called = true;
- bool need_show;
- int elapsed = d->starttime.elapsed();
+ d->setValueCalled = true;
+ 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) {
d->ensureSizeIsAtLeastSizeHint();
show();
- d->shown_once = true;
+ d->shownOnce = true;
}
}
}
@@ -762,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());
}
@@ -788,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.
@@ -851,11 +812,11 @@ void QProgressDialog::forceShow()
{
Q_D(QProgressDialog);
d->forceTimer->stop();
- if (d->shown_once || d->cancellation_flag)
+ if (d->shownOnce || d->cancellationFlag)
return;
show();
- d->shown_once = true;
+ d->shownOnce = true;
}
/*!
diff --git a/src/widgets/dialogs/qprogressdialog.h b/src/widgets/dialogs/qprogressdialog.h
index 74adb6bd84..132dffa480 100644
--- a/src/widgets/dialogs/qprogressdialog.h
+++ b/src/widgets/dialogs/qprogressdialog.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPROGRESSDIALOG_H
#define QPROGRESSDIALOG_H
diff --git a/src/widgets/dialogs/qsidebar.cpp b/src/widgets/dialogs/qsidebar.cpp
index dfb707eda0..581e659a44 100644
--- a/src/widgets/dialogs/qsidebar.cpp
+++ b/src/widgets/dialogs/qsidebar.cpp
@@ -1,44 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qsidebar_p.h"
-#include "qfilesystemmodel.h"
#include <qaction.h>
#include <qurl.h>
@@ -48,11 +11,14 @@
#include <qmimedata.h>
#include <qevent.h>
#include <qdebug.h>
-#include <qfileiconprovider.h>
+#include <qfilesystemmodel.h>
+#include <qabstractfileiconprovider.h>
#include <qfiledialog.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
void QSideBarDelegate::initStyleOption(QStyleOptionViewItem *option,
const QModelIndex &index) const
{
@@ -77,12 +43,18 @@ QUrlModel::QUrlModel(QObject *parent) : QStandardItemModel(parent), showFullPath
{
}
+QUrlModel::~QUrlModel()
+{
+ for (const auto &conn : std::as_const(modelConnections))
+ disconnect(conn);
+}
+
/*!
\reimp
*/
QStringList QUrlModel::mimeTypes() const
{
- return QStringList(QLatin1String("text/uri-list"));
+ return QStringList("text/uri-list"_L1);
}
/*!
@@ -163,7 +135,7 @@ bool QUrlModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
*/
bool QUrlModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
- if (value.type() == QVariant::Url) {
+ if (value.userType() == QMetaType::QUrl) {
QUrl url = value.toUrl();
QModelIndex dirIndex = fileSystemModel->index(url.toLocalFile());
//On windows the popup display the "C:\", convert to nativeSeparators
@@ -198,9 +170,9 @@ void QUrlModel::setUrl(const QModelIndex &index, const QUrl &url, const QModelIn
QIcon newIcon = qvariant_cast<QIcon>(dirIndex.data(Qt::DecorationRole));
if (!dirIndex.isValid()) {
- const QFileIconProvider *provider = fileSystemModel->iconProvider();
+ const QAbstractFileIconProvider *provider = fileSystemModel->iconProvider();
if (provider)
- newIcon = provider->icon(QFileIconProvider::Folder);
+ newIcon = provider->icon(QAbstractFileIconProvider::Folder);
newName = QFileInfo(url.toLocalFile()).fileName();
if (!invalidUrls.contains(url))
invalidUrls.append(url);
@@ -211,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)
@@ -245,9 +220,10 @@ void QUrlModel::addUrls(const QList<QUrl> &list, int row, bool move)
if (row == -1)
row = rowCount();
row = qMin(row, rowCount());
- for (int i = list.count() - 1; i >= 0; --i) {
- QUrl url = list.at(i);
- if (!url.isValid() || url.scheme() != QLatin1String("file"))
+ 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
const QString cleanUrl = QDir::cleanPath(url.toLocalFile());
@@ -299,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);
@@ -325,7 +299,7 @@ void QUrlModel::setFileSystemModel(QFileSystemModel *model)
void QUrlModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
QModelIndex parent = topLeft.parent();
- for (int i = 0; i < watching.count(); ++i) {
+ for (int i = 0; i < watching.size(); ++i) {
QModelIndex index = watching.at(i).index;
if (index.model() && topLeft.model()) {
Q_ASSERT(index.model() == topLeft.model());
@@ -346,13 +320,11 @@ void QUrlModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &botto
void QUrlModel::layoutChanged()
{
QStringList paths;
- const int numPaths = watching.count();
- 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())
@@ -387,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));
}
@@ -420,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) {
@@ -431,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)
@@ -448,10 +422,10 @@ 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.count() > 0)
+ if (actions.size() > 0)
QMenu::exec(actions, mapToGlobal(position));
}
#endif // QT_CONFIG(menu)
@@ -463,16 +437,13 @@ void QSidebar::showContextMenu(const QPoint &position)
*/
void QSidebar::removeEntry()
{
- QList<QModelIndex> idxs = selectionModel()->selectedIndexes();
- QList<QPersistentModelIndex> indexes;
- const int numIndexes = idxs.count();
- 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());
}
}
@@ -504,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 6056f19452..ed17a2ff31 100644
--- a/src/widgets/dialogs/qsidebar_p.h
+++ b/src/widgets/dialogs/qsidebar_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSIDEBAR_H
#define QSIDEBAR_H
@@ -52,11 +16,11 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include <qlist.h>
#include <qlistview.h>
#include <qstandarditemmodel.h>
#include <qstyleditemdelegate.h>
#include <qurl.h>
-#include <qvector.h>
QT_REQUIRE_CONFIG(filedialog);
@@ -83,6 +47,7 @@ public:
};
QUrlModel(QObject *parent = nullptr);
+ ~QUrlModel();
QStringList mimeTypes() const override;
QMimeData *mimeData(const QModelIndexList &indexes) const override;
@@ -114,10 +79,11 @@ private:
};
friend class QTypeInfo<WatchItem>;
- QVector<WatchItem> watching;
+ QList<WatchItem> watching;
QList<QUrl> invalidUrls;
+ std::array<QMetaObject::Connection, 3> modelConnections;
};
-Q_DECLARE_TYPEINFO(QUrlModel::WatchItem, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QUrlModel::WatchItem, Q_RELOCATABLE_TYPE);
class Q_AUTOTEST_EXPORT QSidebar : public QListView
{
diff --git a/src/widgets/dialogs/qwizard.cpp b/src/widgets/dialogs/qwizard.cpp
index a4789f40b1..ec082b9a85 100644
--- a/src/widgets/dialogs/qwizard.cpp
+++ b/src/widgets/dialogs/qwizard.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qwizard.h"
#include <QtWidgets/private/qtwidgetsglobal_p.h>
@@ -47,8 +11,6 @@
#include "qapplication.h"
#include "qboxlayout.h"
#include "qlayoutitem.h"
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
#include "qevent.h"
#include "qframe.h"
#include "qlabel.h"
@@ -56,7 +18,7 @@
#include "qlineedit.h"
#endif
#include <qpointer.h>
-#include "qpainter.h"
+#include "qstylepainter.h"
#include "qwindow.h"
#include "qpushbutton.h"
#include "qset.h"
@@ -64,11 +26,11 @@
# include "qshortcut.h"
#endif
#include "qstyle.h"
+#include "qstyleoption.h"
#include "qvarlengtharray.h"
-#if defined(Q_OS_MACX)
-#include <QtCore/QMetaMethod>
-#include <QtGui/QGuiApplication>
-#include <qpa/qplatformnativeinterface.h>
+#if defined(Q_OS_MACOS)
+#include <AppKit/AppKit.h>
+#include <QtGui/private/qcoregraphics_p.h>
#elif QT_CONFIG(style_windowsvista)
#include "qwizard_win_p.h"
#include "qtimer.h"
@@ -82,6 +44,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
// These fudge terms were needed a few places to obtain pixel-perfect results
const int GapBetweenLogoAndRightEdge = 5;
const int ModernHeaderTopMargin = 2;
@@ -163,9 +127,8 @@ static const char *changed_signal(int which)
case 5: return SIGNAL(currentRowChanged(int));
case 6: return SIGNAL(valueChanged(int));
};
- Q_STATIC_ASSERT(7 == NFallbackDefaultProperties);
- Q_UNREACHABLE();
- return nullptr;
+ static_assert(7 == NFallbackDefaultProperties);
+ Q_UNREACHABLE_RETURN(nullptr);
}
class QWizardDefaultProperty
@@ -180,7 +143,7 @@ public:
const char *changedSignal)
: className(className), property(property), changedSignal(changedSignal) {}
};
-Q_DECLARE_TYPEINFO(QWizardDefaultProperty, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QWizardDefaultProperty, Q_RELOCATABLE_TYPE);
class QWizardField
{
@@ -189,7 +152,7 @@ public:
QWizardField(QWizardPage *page, const QString &spec, QObject *object, const char *property,
const char *changedSignal);
- void resolve(const QVector<QWizardDefaultProperty> &defaultPropertyTable);
+ void resolve(const QList<QWizardDefaultProperty> &defaultPropertyTable);
void findProperty(const QWizardDefaultProperty *properties, int propertyCount);
QWizardPage *page;
@@ -200,23 +163,23 @@ public:
QByteArray changedSignal;
QVariant initialValue;
};
-Q_DECLARE_TYPEINFO(QWizardField, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QWizardField, Q_RELOCATABLE_TYPE);
QWizardField::QWizardField(QWizardPage *page, const QString &spec, QObject *object,
const char *property, const char *changedSignal)
: page(page), name(spec), mandatory(false), object(object), property(property),
changedSignal(changedSignal)
{
- if (name.endsWith(QLatin1Char('*'))) {
+ if (name.endsWith(u'*')) {
name.chop(1);
mandatory = true;
}
}
-void QWizardField::resolve(const QVector<QWizardDefaultProperty> &defaultPropertyTable)
+void QWizardField::resolve(const QList<QWizardDefaultProperty> &defaultPropertyTable)
{
if (property.isEmpty())
- findProperty(defaultPropertyTable.constData(), defaultPropertyTable.count());
+ findProperty(defaultPropertyTable.constData(), defaultPropertyTable.size());
initialValue = object->property(property);
}
@@ -255,11 +218,11 @@ public:
bool extension = false;
bool sideWidget = false;
- bool operator==(const QWizardLayoutInfo &other);
- inline bool operator!=(const QWizardLayoutInfo &other) { return !operator==(other); }
+ bool operator==(const QWizardLayoutInfo &other) const;
+ inline bool operator!=(const QWizardLayoutInfo &other) const { return !operator==(other); }
};
-bool QWizardLayoutInfo::operator==(const QWizardLayoutInfo &other)
+bool QWizardLayoutInfo::operator==(const QWizardLayoutInfo &other) const
{
return topLevelMarginLeft == other.topLevelMarginLeft
&& topLevelMarginRight == other.topLevelMarginRight
@@ -349,7 +312,7 @@ bool QWizardHeader::vistaDisabled() const
bool styleDisabled = false;
QWizard *wiz = parentWidget() ? qobject_cast <QWizard *>(parentWidget()->parentWidget()) : 0;
if (wiz) {
- // Designer dosen't support the Vista style for Wizards. This property is used to turn
+ // Designer doesn't support the Vista style for Wizards. This property is used to turn
// off the Vista style.
const QVariant v = wiz->property("_q_wizard_vista_off");
styleDisabled = v.isValid() && v.toBool();
@@ -364,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
);
@@ -384,7 +346,7 @@ void QWizardHeader::setup(const QWizardLayoutInfo &info, const QString &title,
logoLabel->setPixmap(logo);
subTitleLabel->setTextFormat(subTitleFormat);
- subTitleLabel->setText(QLatin1String("Pq\nPq"));
+ subTitleLabel->setText("Pq\nPq"_L1);
int desiredSubTitleHeight = subTitleLabel->sizeHint().height();
subTitleLabel->setText(subTitle);
@@ -398,7 +360,7 @@ void QWizardHeader::setup(const QWizardLayoutInfo &info, const QString &title,
/*
There is no widthForHeight() function, so we simulate it with a loop.
*/
- int candidateSubTitleWidth = qMin(512, 2 * QDesktopWidgetPrivate::width() / 3);
+ int candidateSubTitleWidth = qMin(512, 2 * QGuiApplication::primaryScreen()->virtualGeometry().width() / 3);
int delta = candidateSubTitleWidth >> 1;
while (delta > 0) {
if (subTitleLabel->heightForWidth(candidateSubTitleWidth - delta)
@@ -421,7 +383,7 @@ void QWizardHeader::setup(const QWizardLayoutInfo &info, const QString &title,
void QWizardHeader::paintEvent(QPaintEvent * /* event */)
{
- QPainter painter(this);
+ QStylePainter painter(this);
painter.drawPixmap(0, 0, bannerPixmap);
int x = width() - 2;
@@ -452,8 +414,8 @@ public:
}
QSize minimumSizeHint() const override {
- if (pixmap() && !pixmap()->isNull())
- return pixmap()->size() / pixmap()->devicePixelRatio();
+ if (!pixmap().isNull())
+ return pixmap().deviceIndependentSize().toSize();
return QFrame::minimumSizeHint();
}
@@ -491,7 +453,7 @@ public:
QString title;
QString subTitle;
QPixmap pixmaps[QWizard::NPixmaps];
- QVector<QWizardField> pendingFields;
+ QList<QWizardField> pendingFields;
mutable TriState completeState = Tri_Unknown;
bool explicitlyFinal = false;
bool commit = false;
@@ -530,7 +492,7 @@ public:
: QWidget(wizard)
, wizardPrivate(wizardPrivate) {}
protected:
- void paintEvent(QPaintEvent *);
+ void paintEvent(QPaintEvent *) override;
#else
QWizardAntiFlickerWidget(QWizard *wizard, QWizardPrivate *)
: QWidget(wizard)
@@ -559,6 +521,7 @@ public:
QWizardLayoutInfo layoutInfoForCurrentPage();
void recreateLayout(const QWizardLayoutInfo &info);
void updateLayout();
+ void updatePalette();
void updateMinMaxSizes(const QWizardLayoutInfo &info);
void updateCurrentPage();
bool ensureButton(QWizard::WizardButton which) const;
@@ -570,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;
@@ -580,14 +542,14 @@ public:
void _q_updateButtonStates();
void _q_handleFieldObjectDestroyed(QObject *);
void setStyle(QStyle *style);
-#ifdef Q_OS_MACX
+#ifdef Q_OS_MACOS
static QPixmap findDefaultBackgroundPixmap();
#endif
PageMap pageMap;
- QVector<QWizardField> fields;
+ QList<QWizardField> fields;
QMap<QString, int> fieldIndexMap;
- QVector<QWizardDefaultProperty> defaultPropertyTable;
+ QList<QWizardDefaultProperty> defaultPropertyTable;
QList<int> history;
int start = -1;
bool startSetByUser = false;
@@ -639,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
@@ -729,10 +691,11 @@ void QWizardPrivate::reset()
if (current != -1) {
q->currentPage()->hide();
cleanupPagesNotInHistory();
- for (int i = history.count() - 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 : qAsConst(pageMap))
+ for (QWizardPage *page : std::as_const(pageMap))
page->d_func()->initialized = false;
current = -1;
@@ -766,7 +729,7 @@ void QWizardPrivate::addField(const QWizardField &field)
return;
}
- fieldIndexMap.insert(myField.name, fields.count());
+ fieldIndexMap.insert(myField.name, fields.size());
fields += myField;
if (myField.mandatory && !myField.changedSignal.isEmpty())
QObject::connect(myField.object, myField.changedSignal,
@@ -861,6 +824,7 @@ void QWizardPrivate::switchToPage(int newId, Direction direction)
enableUpdates();
updateLayout();
+ updatePalette();
emit q->currentIdChanged(current);
}
@@ -897,7 +861,9 @@ QWizardLayoutInfo QWizardPrivate::layoutInfoForCurrentPage()
QWizardLayoutInfo info;
- const int layoutHorizontalSpacing = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing);
+ QStyleOption option;
+ option.initFrom(q);
+ 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);
@@ -909,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);
+ info.vspacing = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing, &option, q);
info.buttonSpacing = (layoutHorizontalSpacing == -1)
? style->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal)
: layoutHorizontalSpacing;
@@ -920,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;
@@ -1046,7 +1012,7 @@ void QWizardPrivate::recreateLayout(const QWizardLayoutInfo &info)
if (aero) {
// ### hardcoded for now:
- titleFont = QFont(QLatin1String("Segoe UI"), 12);
+ titleFont = QFont("Segoe UI"_L1, 12);
QPalette pal(titleLabel->palette());
pal.setColor(QPalette::Text, QColor(0x00, 0x33, 0x99));
titleLabel->setPalette(pal);
@@ -1142,16 +1108,8 @@ void QWizardPrivate::recreateLayout(const QWizardLayoutInfo &info)
pageFrame->palette().brush(QPalette::Window).color().alpha() < 255
|| pageFrame->palette().brush(QPalette::Base).color().alpha() < 255;
if (mac) {
- if (!wasSemiTransparent) {
- QPalette pal = pageFrame->palette();
- pal.setBrush(QPalette::Window, QColor(255, 255, 255, 153));
- // ### The next line is required to ensure visual semitransparency when
- // ### switching from ModernStyle to MacStyle. See TAG1 below.
- pal.setBrush(QPalette::Base, QColor(255, 255, 255, 153));
- pageFrame->setPalette(pal);
- pageFrame->setAutoFillBackground(true);
- antiFlickerWidget->setAutoFillBackground(false);
- }
+ pageFrame->setAutoFillBackground(true);
+ antiFlickerWidget->setAutoFillBackground(false);
} else {
if (wasSemiTransparent)
pageFrame->setPalette(QPalette());
@@ -1292,6 +1250,30 @@ void QWizardPrivate::updateLayout()
updateMinMaxSizes(info);
}
+void QWizardPrivate::updatePalette() {
+ if (wizStyle == QWizard::MacStyle) {
+ // This is required to ensure visual semitransparency when
+ // switching from ModernStyle to MacStyle.
+ // See TAG1 in recreateLayout
+ // This additionally ensures that the colors are correct
+ // when the theme is changed.
+
+ // we should base the new palette on the default one
+ // so theme colors will be correct
+ QPalette newPalette = QApplication::palette(pageFrame);
+
+ QColor windowColor = newPalette.brush(QPalette::Window).color();
+ windowColor.setAlpha(153);
+ newPalette.setBrush(QPalette::Window, windowColor);
+
+ QColor baseColor = newPalette.brush(QPalette::Base).color();
+ baseColor.setAlpha(153);
+ newPalette.setBrush(QPalette::Base, baseColor);
+
+ pageFrame->setPalette(newPalette);
+ }
+}
+
void QWizardPrivate::updateMinMaxSizes(const QWizardLayoutInfo &info)
{
Q_Q(QWizard);
@@ -1346,11 +1328,11 @@ static QString object_name_for_button(QWizard::WizardButton which)
{
switch (which) {
case QWizard::CommitButton:
- return QLatin1String("qt_wizard_") + QLatin1String("commit");
+ return u"qt_wizard_commit"_s;
case QWizard::FinishButton:
- return QLatin1String("qt_wizard_") + QLatin1String("finish");
+ return u"qt_wizard_finish"_s;
case QWizard::CancelButton:
- return QLatin1String("qt_wizard_") + QLatin1String("cancel");
+ return u"qt_wizard_cancel"_s;
case QWizard::BackButton:
case QWizard::NextButton:
case QWizard::HelpButton:
@@ -1358,15 +1340,14 @@ static QString object_name_for_button(QWizard::WizardButton which)
case QWizard::CustomButton2:
case QWizard::CustomButton3:
// Make navigation buttons detectable as passive interactor in designer
- return QLatin1String("__qt__passive_wizardbutton") + QString::number(which);
+ return "__qt__passive_wizardbutton"_L1 + QString::number(which);
case QWizard::Stretch:
case QWizard::NoButton:
//case QWizard::NStandardButtons:
//case QWizard::NButtons:
;
}
- Q_UNREACHABLE();
- return QString();
+ Q_UNREACHABLE_RETURN(QString());
}
bool QWizardPrivate::ensureButton(QWizard::WizardButton which) const
@@ -1381,7 +1362,7 @@ bool QWizardPrivate::ensureButton(QWizard::WizardButton which) const
if (style != QApplication::style()) // Propagate style
pushButton->setStyle(style);
pushButton->setObjectName(object_name_for_button(which));
-#ifdef Q_OS_MACX
+#ifdef Q_OS_MACOS
pushButton->setAutoDefault(false);
#endif
pushButton->hide();
@@ -1440,10 +1421,9 @@ void QWizardPrivate::updateButtonTexts()
void QWizardPrivate::updateButtonLayout()
{
if (buttonsHaveCustomLayout) {
- QVarLengthArray<QWizard::WizardButton, QWizard::NButtons> array(buttonsCustomLayout.count());
- for (int i = 0; i < buttonsCustomLayout.count(); ++i)
- array[i] = buttonsCustomLayout.at(i);
- setButtonLayout(array.constData(), array.count());
+ 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
@@ -1537,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);
@@ -1567,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(
@@ -1614,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
@@ -1660,15 +1624,15 @@ void QWizardPrivate::_q_updateButtonStates()
const QWizardPage *page = q->currentPage();
bool complete = page && page->isComplete();
- btn.back->setEnabled(history.count() > 1
- && !q->page(history.at(history.count() - 2))->isCommitPage()
+ btn.back->setEnabled(history.size() > 1
+ && !q->page(history.at(history.size() - 2))->isCommitPage()
&& (!canFinish || !(opts & QWizard::DisabledBackButtonOnLastPage)));
btn.next->setEnabled(canContinue && complete);
btn.commit->setEnabled(canContinue && complete);
btn.finish->setEnabled(canFinish && complete);
const bool backButtonVisible = buttonLayoutContains(QWizard::BackButton)
- && (history.count() > 1 || !(opts & QWizard::NoBackButtonOnStartPage))
+ && (history.size() > 1 || !(opts & QWizard::NoBackButtonOnStartPage))
&& (canContinue || !(opts & QWizard::NoBackButtonOnLastPage));
bool commitPage = page && page->isCommitPage();
btn.back->setVisible(backButtonVisible);
@@ -1705,7 +1669,7 @@ void QWizardPrivate::_q_updateButtonStates()
void QWizardPrivate::_q_handleFieldObjectDestroyed(QObject *object)
{
int destroyed_index = -1;
- QVector<QWizardField>::iterator it = fields.begin();
+ QList<QWizardField>::iterator it = fields.begin();
while (it != fields.end()) {
const QWizardField &field = *it;
if (field.object == object) {
@@ -1739,24 +1703,20 @@ void QWizardPrivate::setStyle(QStyle *style)
it.value()->setStyle(style);
}
-#ifdef Q_OS_MACX
-
+#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)
@@ -1772,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
@@ -1808,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
@@ -1939,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
@@ -1955,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
@@ -2002,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
@@ -2080,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}
*/
/*!
@@ -2206,7 +2151,7 @@ int QWizard::addPage(QWizardPage *page)
Q_D(QWizard);
int theid = 0;
if (!d->pageMap.isEmpty())
- theid = (d->pageMap.constEnd() - 1).key() + 1;
+ theid = d->pageMap.lastKey() + 1;
setPage(theid, page);
return theid;
}
@@ -2242,9 +2187,9 @@ void QWizard::setPage(int theid, QWizardPage *page)
page->setParent(d->pageFrame);
- QVector<QWizardField> &pendingFields = page->d_func()->pendingFields;
- for (int i = 0; i < pendingFields.count(); ++i)
- d->addField(pendingFields.at(i));
+ QList<QWizardField> &pendingFields = page->d_func()->pendingFields;
+ for (const auto &field : std::as_const(pendingFields))
+ d->addField(field);
pendingFields.clear();
connect(page, SIGNAL(completeChanged()), this, SLOT(_q_updateButtonStates()));
@@ -2284,11 +2229,11 @@ void QWizard::removePage(int id)
QWizardPage *removedPage = nullptr;
// update startItem accordingly
- if (d->pageMap.count() > 0) { // only if we have any pages
+ if (d->pageMap.size() > 0) { // only if we have any pages
if (d->start == id) {
const int firstId = d->pageMap.constBegin().key();
if (firstId == id) {
- if (d->pageMap.count() > 1)
+ if (d->pageMap.size() > 1)
d->start = (++d->pageMap.constBegin()).key(); // secondId
else
d->start = -1; // removing the last page
@@ -2311,7 +2256,7 @@ void QWizard::removePage(int id)
removedPage = d->pageMap.take(id);
d->history.removeOne(id);
d->_q_updateButtonStates();
- } else if (d->history.count() == 1) {
+ } else if (d->history.size() == 1) {
// Case 3: removing the current page which is the first (and only) one in the history
d->reset();
removedPage = d->pageMap.take(id);
@@ -2334,7 +2279,7 @@ void QWizard::removePage(int id)
d->pageVBoxLayout->removeWidget(removedPage);
- for (int i = d->fields.count() - 1; i >= 0; --i) {
+ for (int i = d->fields.size() - 1; i >= 0; --i) {
if (d->fields.at(i).page == removedPage) {
removedPage->d_func()->pendingFields += d->fields.at(i);
d->removeFieldAt(i);
@@ -2365,7 +2310,7 @@ QWizardPage *QWizard::page(int theid) const
Pressing \uicontrol Back marks the current page as "unvisited" again.
- \sa visitedPages()
+ \sa visitedIds()
*/
bool QWizard::hasVisitedPage(int theid) const
{
@@ -2374,14 +2319,14 @@ bool QWizard::hasVisitedPage(int theid) const
}
/*!
+ \since 5.15
+
Returns the list of IDs of visited pages, in the order in which the pages
were visited.
- Pressing \uicontrol Back marks the current page as "unvisited" again.
-
\sa hasVisitedPage()
*/
-QList<int> QWizard::visitedPages() const
+QList<int> QWizard::visitedIds() const
{
Q_D(const QWizard);
return d->history;
@@ -2412,7 +2357,7 @@ void QWizard::setStartId(int theid)
Q_D(QWizard);
int newStart = theid;
if (theid == -1)
- newStart = d->pageMap.count() ? d->pageMap.constBegin().key() : -1;
+ newStart = d->pageMap.size() ? d->pageMap.constBegin().key() : -1;
if (d->start == newStart) {
d->startSetByUser = theid != -1;
@@ -2693,7 +2638,7 @@ QString QWizard::buttonText(WizardButton which) const
return d->buttonCustomTexts.value(which);
const QString defText = buttonDefaultText(d->wizStyle, which, d);
- if(!defText.isNull())
+ if (!defText.isNull())
return defText;
return d->btns[which]->text();
@@ -2721,7 +2666,7 @@ void QWizard::setButtonLayout(const QList<WizardButton> &layout)
{
Q_D(QWizard);
- for (int i = 0; i < layout.count(); ++i) {
+ for (int i = 0; i < layout.size(); ++i) {
WizardButton button1 = layout.at(i);
if (button1 == NoButton || button1 == Stretch)
@@ -2862,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}
*/
@@ -2870,7 +2815,7 @@ QPixmap QWizard::pixmap(WizardPixmap which) const
{
Q_D(const QWizard);
Q_ASSERT(uint(which) < NPixmaps);
-#ifdef Q_OS_MACX
+#ifdef Q_OS_MACOS
if (which == BackgroundPixmap && d->defaultPixmaps[BackgroundPixmap].isNull())
d->defaultPixmaps[BackgroundPixmap] = d->findDefaultBackgroundPixmap();
#endif
@@ -2906,7 +2851,7 @@ void QWizard::setDefaultProperty(const char *className, const char *property,
const char *changedSignal)
{
Q_D(QWizard);
- for (int i = d->defaultPropertyTable.count() - 1; i >= 0; --i) {
+ for (int i = d->defaultPropertyTable.size() - 1; i >= 0; --i) {
if (qstrcmp(d->defaultPropertyTable.at(i).className, className) == 0) {
d->defaultPropertyTable.remove(i);
break;
@@ -2924,7 +2869,7 @@ void QWizard::setDefaultProperty(const char *className, const char *property,
or when the watermark is not provided the side widget is displayed
on the left side of the wizard.
- Passing 0 shows no side widget.
+ Passing \nullptr shows no side widget.
When the \a widget is not \nullptr the wizard reparents it.
@@ -3086,7 +3031,7 @@ QSize QWizard::sizeHint() const
void QWizard::back()
{
Q_D(QWizard);
- int n = d->history.count() - 2;
+ int n = d->history.size() - 2;
if (n < 0)
return;
d->switchToPage(d->history.at(n), QWizardPrivate::Backward);
@@ -3123,6 +3068,42 @@ void QWizard::next()
}
/*!
+ Sets currentId to \a id, without visiting the pages between currentId and \a id.
+
+ Returns without page change, if
+ \list
+ \li wizard holds no pages
+ \li current page is invalid
+ \li given page equals currentId()
+ \li given page is out of range
+ \endlist
+
+ Note: If pages have been forward skipped and \a id is 0, page visiting history
+ will be deleted
+*/
+
+void QWizard::setCurrentId(int id)
+{
+ Q_D(QWizard);
+
+ if (d->current == -1)
+ return;
+
+ if (currentId() == id)
+ return;
+
+ if (!validateCurrentPage())
+ return;
+
+ if (id < 0 || Q_UNLIKELY(!d->pageMap.contains(id))) {
+ qWarning("QWizard::setCurrentId: No such page: %d", id);
+ return;
+ }
+
+ d->switchToPage(id, (id < currentId()) ? QWizardPrivate::Backward : QWizardPrivate::Forward);
+}
+
+/*!
Restarts the wizard at the start page. This function is called automatically when the
wizard is shown.
@@ -3146,16 +3127,13 @@ bool QWizard::event(QEvent *event)
if (event->type() == QEvent::StyleChange) { // Propagate style
d->setStyle(style());
d->updateLayout();
+ } else if (event->type() == QEvent::PaletteChange) { // Emitted on theme change
+ d->updatePalette();
}
#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()) {
@@ -3185,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);
@@ -3208,16 +3185,11 @@ void QWizard::paintEvent(QPaintEvent * event)
if (backgroundPixmap.isNull())
return;
- QPainter painter(this);
+ QStylePainter painter(this);
painter.drawPixmap(0, (height() - backgroundPixmap.height()) / 2, backgroundPixmap);
}
#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
@@ -3225,27 +3197,23 @@ void QWizard::paintEvent(QPaintEvent * event)
#endif
}
-#if defined(Q_OS_WIN) || defined(Q_CLANG_QDOC)
+#if defined(Q_OS_WIN) || defined(Q_QDOC)
/*!
\reimp
*/
-# if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool QWizard::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
-# else
-bool QWizard::nativeEvent(const QByteArray &eventType, void *message, long *result)
-# endif
{
#if QT_CONFIG(style_windowsvista)
Q_D(QWizard);
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);
}
}
@@ -3431,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}
*/
/*!
@@ -3574,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.
@@ -3599,7 +3567,7 @@ void QWizardPage::cleanupPage()
{
Q_D(QWizardPage);
if (d->wizard) {
- const QVector<QWizardField> &fields = d->wizard->d_func()->fields;
+ const QList<QWizardField> &fields = d->wizard->d_func()->fields;
for (const auto &field : fields) {
if (field.page == this)
field.object->setProperty(field.property, field.initialValue);
@@ -3650,9 +3618,10 @@ bool QWizardPage::isComplete() const
if (!d->wizard)
return true;
- const QVector<QWizardField> &wizardFields = d->wizard->d_func()->fields;
- for (int i = wizardFields.count() - 1; i >= 0; --i) {
- const QWizardField &field = wizardFields.at(i);
+ const QList<QWizardField> &wizardFields = d->wizard->d_func()->fields;
+ 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)
@@ -3878,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.h b/src/widgets/dialogs/qwizard.h
index ef71efa0cb..0ec973b0d2 100644
--- a/src/widgets/dialogs/qwizard.h
+++ b/src/widgets/dialogs/qwizard.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIZARD_H
#define QWIZARD_H
@@ -59,7 +23,7 @@ class Q_WIDGETS_EXPORT QWizard : public QDialog
Q_PROPERTY(Qt::TextFormat titleFormat READ titleFormat WRITE setTitleFormat)
Q_PROPERTY(Qt::TextFormat subTitleFormat READ subTitleFormat WRITE setSubTitleFormat)
Q_PROPERTY(int startId READ startId WRITE setStartId)
- Q_PROPERTY(int currentId READ currentId NOTIFY currentIdChanged)
+ Q_PROPERTY(int currentId READ currentId WRITE setCurrentId NOTIFY currentIdChanged)
public:
enum WizardButton {
@@ -128,7 +92,7 @@ public:
void removePage(int id);
QWizardPage *page(int id) const;
bool hasVisitedPage(int id) const;
- QList<int> visitedPages() const; // ### Qt 6: visitedIds()?
+ QList<int> visitedIds() const;
QList<int> pageIds() const;
void setStartId(int id);
int startId() const;
@@ -181,18 +145,15 @@ Q_SIGNALS:
public Q_SLOTS:
void back();
void next();
+ void setCurrentId(int id);
void restart();
protected:
bool event(QEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void paintEvent(QPaintEvent *event) override;
-#if defined(Q_OS_WIN) || defined(Q_CLANG_QDOC)
-# if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+#if defined(Q_OS_WIN) || defined(Q_QDOC)
bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override;
-# else
- bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
-# endif
#endif
void done(int result) override;
virtual void initializePage(int id);
diff --git a/src/widgets/dialogs/qwizard_win.cpp b/src/widgets/dialogs/qwizard_win.cpp
index 47ac41a791..2c4f049e88 100644
--- a/src/widgets/dialogs/qwizard_win.cpp
+++ b/src/widgets/dialogs/qwizard_win.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QtWidgets/private/qtwidgetsglobal_p.h>
@@ -43,7 +7,9 @@
#include "qwizard_win_p.h"
#include <private/qapplication_p.h>
-#include <qpa/qplatformnativeinterface.h>
+#include <private/qwindowsfontdatabasebase_p.h>
+#include <qpa/qplatformwindow.h>
+#include <qpa/qplatformwindow_p.h>
#include "qwizard.h"
#include "qpaintengine.h"
#include "qapplication.h"
@@ -52,12 +18,13 @@
#include <QtCore/QDebug>
#include <QtGui/QMouseEvent>
#include <QtGui/QWindow>
-#include <QtWidgets/QDesktopWidget>
+#include <QtGui/private/qhighdpiscaling_p.h>
#include <uxtheme.h>
#include <vssym32.h>
#include <dwmapi.h>
+// ### move to qmargins.h
Q_DECLARE_METATYPE(QMargins)
#ifndef WM_DWMCOMPOSITIONCHANGED
@@ -66,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
@@ -92,7 +57,7 @@ QSize QVistaBackButton::sizeHint() const
return QSize(width, height);
}
-void QVistaBackButton::enterEvent(QEvent *event)
+void QVistaBackButton::enterEvent(QEnterEvent *event)
{
if (isEnabled())
update();
@@ -117,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;
@@ -151,21 +116,19 @@ 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)
{
+ using namespace QNativeInterface::Private;
+
if (QWindow *window = wizard->windowHandle()) {
// Reduce top frame to zero since we paint it ourselves. Use
// device pixel to avoid rounding errors.
@@ -176,33 +139,11 @@ void QVistaHelper::updateCustomMargins(bool vistaMargins)
// The dynamic property takes effect when creating the platform window.
window->setProperty("_q_windowsCustomMargins", customMarginsV);
// If a platform window exists, change via native interface.
- if (QPlatformWindow *platformWindow = window->handle()) {
- QGuiApplication::platformNativeInterface()->
- setWindowProperty(platformWindow, QStringLiteral("WindowsCustomMargins"),
- customMarginsV);
- }
+ if (auto platformWindow = dynamic_cast<QWindowsWindow *>(window->handle()))
+ platformWindow->setCustomMargins(customMarginsDp);
}
}
-bool QVistaHelper::isCompositionEnabled()
-{
- BOOL bEnabled;
- return SUCCEEDED(DwmIsCompositionEnabled(&bEnabled)) && bEnabled;
-}
-
-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.
@@ -223,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 &);
@@ -259,11 +198,8 @@ static bool getCaptionQFont(int dpi, QFont *result)
return false;
// Call into QWindowsNativeInterface to convert the LOGFONT into a QFont.
const LOGFONT logFont = getCaptionLogFont(hTheme);
- QPlatformNativeInterface *ni = QGuiApplication::platformNativeInterface();
- return ni && QMetaObject::invokeMethod(ni, "logFontToQFont", Qt::DirectConnection,
- Q_RETURN_ARG(QFont, *result),
- Q_ARG(const void*, &logFont),
- Q_ARG(int, dpi));
+ *result = QWindowsFontDatabaseBase::LOGFONT_to_QFont(logFont, dpi);
+ return true;
}
void QVistaHelper::drawTitleBar(QPainter *painter)
@@ -273,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(),
@@ -288,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
@@ -339,11 +269,7 @@ void QVistaHelper::setTitleBarIconAndCaptionVisible(bool visible)
SetWindowThemeAttribute(handle, WTA_NONCLIENT, &opt, sizeof(WTA_OPTIONS));
}
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool QVistaHelper::winEvent(MSG* msg, qintptr *result)
-#else
-bool QVistaHelper::winEvent(MSG* msg, long* result)
-#endif
{
switch (msg->message) {
case WM_NCHITTEST: {
@@ -405,17 +331,10 @@ void QVistaHelper::mouseEvent(QEvent *event)
}
}
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool QVistaHelper::handleWinEvent(MSG *message, qintptr *result)
-#else
-bool QVistaHelper::handleWinEvent(MSG *message, long *result)
-#endif
{
- 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();
@@ -428,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);
}
@@ -468,7 +385,7 @@ void QVistaHelper::mouseMoveEvent(QMouseEvent *event)
}
wizard->setGeometry(rect);
- } else if (vistaState() == VistaAero) {
+ } else {
setMouseCursor(event->pos());
}
event->ignore();
@@ -486,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 {
@@ -504,12 +420,17 @@ void QVistaHelper::mouseReleaseEvent(QMouseEvent *event)
if (pressed) {
pressed = false;
wizard->releaseMouse();
- if (vistaState() == VistaAero)
- setMouseCursor(event->pos());
+ setMouseCursor(event->pos());
}
event->ignore();
}
+static inline LPARAM pointToLParam(const QPointF &p, const QWidget *w)
+{
+ const auto point = QHighDpi::toNativePixels(p, w->screen()).toPoint();
+ return MAKELPARAM(point.x(), point.y());
+}
+
bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
{
if (obj != wizard)
@@ -517,15 +438,11 @@ bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
if (event->type() == QEvent::MouseMove) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
qintptr result;
-#else
- long result;
-#endif
MSG msg;
msg.message = WM_NCHITTEST;
msg.wParam = 0;
- msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
+ msg.lParam = pointToLParam(mouseEvent->globalPosition(), wizard);
msg.hwnd = wizardHWND();
winEvent(&msg, &result);
msg.wParam = result;
@@ -535,15 +452,11 @@ bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton) {
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
qintptr result;
-#else
- long result;
-#endif
MSG msg;
msg.message = WM_NCHITTEST;
msg.wParam = 0;
- msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
+ msg.lParam = pointToLParam(mouseEvent->globalPosition(), wizard);
msg.hwnd = wizardHWND();
winEvent(&msg, &result);
msg.wParam = result;
@@ -554,15 +467,11 @@ bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton) {
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
qintptr result;
-#else
- long result;
-#endif
MSG msg;
msg.message = WM_NCHITTEST;
msg.wParam = 0;
- msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
+ msg.lParam = pointToLParam(mouseEvent->globalPosition(), wizard);
msg.hwnd = wizardHWND();
winEvent(&msg, &result);
msg.wParam = result;
@@ -599,112 +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);
-#ifndef Q_CC_MSVC
-static inline int getWindowBottomMargin()
-{
- return GetSystemMetrics(SM_CYSIZEFRAME);
-}
-#else
-// QTBUG-36192, GetSystemMetrics(SM_CYSIZEFRAME) returns bogus values
-// for MSVC2012 which leads to the custom margin having no effect since
-// that only works when removing the entire margin.
-static inline int getWindowBottomMargin()
-{
- RECT rect = {0, 0, 0, 0};
- AdjustWindowRectEx(&rect, WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_THICKFRAME | WS_DLGFRAME, FALSE, 0);
- return qAbs(rect.bottom);
+ 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);
}
-#endif // Q_CC_MSVC
int QVistaHelper::frameSizeDp()
{
- return getWindowBottomMargin();
+ return GetSystemMetrics(SM_CXSIZEFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER);
}
int QVistaHelper::captionSizeDp()
@@ -730,11 +615,7 @@ int QVistaHelper::glowSize(const QPaintDevice *device)
int QVistaHelper::topOffset(const QPaintDevice *device)
{
- if (vistaState() != VistaAero)
- return titleBarSize() + 3;
- static const int aeroOffset =
- QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows8 ?
- QStyleHelper::dpiScaled(4, device) : QStyleHelper::dpiScaled(13, device);
+ 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 2469496b61..ce0f7b85b3 100644
--- a/src/widgets/dialogs/qwizard_win_p.h
+++ b/src/widgets/dialogs/qwizard_win_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIZARD_WIN_P_H
#define QWIZARD_WIN_P_H
@@ -75,7 +39,7 @@ public:
inline QSize minimumSizeHint() const override
{ return sizeHint(); }
- void enterEvent(QEvent *event) override;
+ void enterEvent(QEnterEvent *event) override;
void leaveEvent(QEvent *event) override;
void paintEvent(QPaintEvent *event) override;
};
@@ -93,19 +57,13 @@ public:
bool setDWMTitleBar(TitleBarChangeType type);
void setTitleBarIconAndCaptionVisible(bool visible);
void mouseEvent(QEvent *event);
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool handleWinEvent(MSG *message, qintptr *result);
-#else
- bool handleWinEvent(MSG *message, long *result);
-#endif
void resizeEvent(QResizeEvent *event);
void paintEvent(QPaintEvent *event);
QVistaBackButton *backButton() const { return backButton_; }
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
@@ -117,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();
@@ -136,20 +94,12 @@ private:
void drawTitleBar(QPainter *painter);
void setMouseCursor(QPoint pos);
void collapseTopFrameStrut();
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool winEvent(MSG *message, qintptr *result);
-#else
- bool winEvent(MSG *message, long *result);
-#endif
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
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;
@@ -160,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/msgbox1.png b/src/widgets/doc/images/msgbox1.png
index 1380e20a5f..ded1d295b6 100644
--- a/src/widgets/doc/images/msgbox1.png
+++ b/src/widgets/doc/images/msgbox1.png
Binary files differ
diff --git a/src/widgets/doc/images/msgbox2.png b/src/widgets/doc/images/msgbox2.png
index e7946996e4..9afd3282f3 100644
--- a/src/widgets/doc/images/msgbox2.png
+++ b/src/widgets/doc/images/msgbox2.png
Binary files differ
diff --git a/src/widgets/doc/images/msgbox3.png b/src/widgets/doc/images/msgbox3.png
index bd81f4d4da..50a4a124c4 100644
--- a/src/widgets/doc/images/msgbox3.png
+++ b/src/widgets/doc/images/msgbox3.png
Binary files differ
diff --git a/src/widgets/doc/images/msgbox4.png b/src/widgets/doc/images/msgbox4.png
index dbe6701cdd..337b3553e9 100644
--- a/src/widgets/doc/images/msgbox4.png
+++ b/src/widgets/doc/images/msgbox4.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 548224bf61..5f68179a36 100644
--- a/src/widgets/doc/qtwidgets.qdocconf
+++ b/src/widgets/doc/qtwidgets.qdocconf
@@ -18,10 +18,6 @@ qhp.QtWidgets.virtualFolder = qtwidgets
qhp.QtWidgets.indexTitle = Qt Widgets
qhp.QtWidgets.indexRoot =
-qhp.QtWidgets.filterAttributes = qtwidgets $QT_VERSION qtrefdoc
-qhp.QtWidgets.customFilters.Qt.name = QtWidgets $QT_VERSION
-qhp.QtWidgets.customFilters.Qt.filterAttributes = qtwidgets $QT_VERSION
-
qhp.QtWidgets.subprojects = classes
qhp.QtWidgets.subprojects.classes.title = C++ Classes
qhp.QtWidgets.subprojects.classes.indexTitle = Qt Widgets C++ Classes
@@ -30,7 +26,21 @@ qhp.QtWidgets.subprojects.classes.sortPages = true
tagfile = ../../../doc/qtwidgets/qtwidgets.tags
-depends += qtcore qtgui qtdoc qtsql qtdesigner qtquick qmake qtplatformheaders qtsvg qtlinguist
+depends += \
+ qtcore \
+ qtgui \
+ qtdoc \
+ qtsql \
+ qtdesigner \
+ qtquick \
+ qmake \
+ qtcmake \
+ qtsvg \
+ qtlinguist \
+ qthelp \
+ qtopengl \
+ qtshadertools \
+ qttestlib
headerdirs += ..
@@ -39,7 +49,8 @@ sourcedirs += .. \
exampledirs += ../../../examples/widgets \
../../../doc/src/snippets \
- ../ \
+ .. \
+ . \
snippets
excludedirs += snippets
@@ -47,6 +58,15 @@ excludedirs += snippets
# Included in qttestlib.qdocconf instead
excludefiles += ../kernel/qtestsupport_widgets.cpp
+# Exclude forwarding headers to QtGUI to avoid duplicates in the node tree
+excludefiles += \
+ ../dialogs/qfilesystemmodel.h \
+ ../kernel/qaction.h \
+ ../kernel/qactiongroup.h \
+ ../kernel/qshortcut.h \
+ ../util/qundogroup.h \
+ ../util/qundostack.h
+
imagedirs += images \
../../../doc/src/images \
../../../examples/widgets/doc/images \
@@ -54,7 +74,16 @@ imagedirs += images \
navigation.landingpage = "Qt Widgets"
navigation.cppclassespage = "Qt Widgets C++ Classes"
-manifestmeta.highlighted.names = "QtWidgets/Calendar Widget Example" \
- "QtWidgets/Editable Tree Model Example" \
- "QtWidgets/Address Book Example" \
- "QtWidgets/Application Example"
+
+# 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
new file mode 100644
index 0000000000..6274244db0
--- /dev/null
+++ b/src/widgets/doc/snippets/CMakeLists.txt
@@ -0,0 +1,7 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#! [cmake_use]
+find_package(Qt6 REQUIRED COMPONENTS Widgets)
+target_link_libraries(mytarget PRIVATE Qt6::Widgets)
+#! [cmake_use]
diff --git a/src/widgets/doc/snippets/cmake-macros/examples.cmake b/src/widgets/doc/snippets/cmake-macros/examples.cmake
index 61ec7aed54..3c58509fdf 100644
--- a/src/widgets/doc/snippets/cmake-macros/examples.cmake
+++ b/src/widgets/doc/snippets/cmake-macros/examples.cmake
@@ -1,5 +1,8 @@
-#! [qt5_wrap_ui]
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#! [qt_wrap_ui]
set(SOURCES mainwindow.cpp main.cpp)
-qt5_wrap_ui(SOURCES mainwindow.ui)
-add_executable(myapp ${SOURCES})
-#! [qt5_wrap_ui]
+qt_wrap_ui(SOURCES mainwindow.ui)
+qt_add_executable(myapp ${SOURCES})
+#! [qt_wrap_ui]
diff --git a/src/widgets/doc/snippets/code/doc_gui_widgets_qopenglwidget.cpp b/src/widgets/doc/snippets/code/doc_gui_widgets_qopenglwidget.cpp
deleted file mode 100644
index 633a413b4f..0000000000
--- a/src/widgets/doc/snippets/code/doc_gui_widgets_qopenglwidget.cpp
+++ /dev/null
@@ -1,209 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//! [0]
-class MyGLWidget : public QOpenGLWidget
-{
-public:
- MyGLWidget(QWidget *parent) : QOpenGLWidget(parent) { }
-
-protected:
- void initializeGL() override
- {
- // Set up the rendering context, load shaders and other resources, etc.:
- QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
- f->glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
- ...
- }
-
- void resizeGL(int w, int h) override
- {
- // Update projection matrix and other size related settings:
- m_projection.setToIdentity();
- m_projection.perspective(45.0f, w / float(h), 0.01f, 100.0f);
- ...
- }
-
- void paintGL() override
- {
- // Draw the scene:
- QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
- f->glClear(GL_COLOR_BUFFER_BIT);
- ...
- }
-
-};
-//! [0]
-
-//! [1]
-class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions
-{
- ...
- void initializeGL() override
- {
- initializeOpenGLFunctions();
- glClearColor(...);
- ...
- }
- ...
-};
-//! [1]
-
-//! [2]
-QOpenGLWidget *widget = new QOpenGLWidget(parent);
-QSurfaceFormat format;
-format.setDepthBufferSize(24);
-format.setStencilBufferSize(8);
-format.setVersion(3, 2);
-format.setProfile(QSurfaceFormat::CoreProfile);
-widget->setFormat(format); // must be called before the widget or its parent window gets shown
-//! [2]
-
-//! [3]
- ...
- void paintGL() override
- {
- QOpenGLFunctions_3_2_Core *f = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_3_2_Core>();
- ...
- f->glDrawArraysInstanced(...);
- ...
- }
- ...
-//! [3]
-
-//! [4]
-class MyGLWidget : public QOpenGLWidget
-{
- ...
-
-private:
- QOpenGLVertexArrayObject m_vao;
- QOpenGLBuffer m_vbo;
- QOpenGLShaderProgram *m_program;
- QOpenGLShader *m_shader;
- QOpenGLTexture *m_texture;
-};
-
-MyGLWidget::MyGLWidget()
- : m_program(0), m_shader(0), m_texture(0)
-{
- // No OpenGL resource initialization is done here.
-}
-
-MyGLWidget::~MyGLWidget()
-{
- // Make sure the context is current and then explicitly
- // destroy all underlying OpenGL resources.
- makeCurrent();
-
- delete m_texture;
- delete m_shader;
- delete m_program;
-
- m_vbo.destroy();
- m_vao.destroy();
-
- doneCurrent();
-}
-
-void MyGLWidget::initializeGL()
-{
- m_vao.create();
- if (m_vao.isCreated())
- m_vao.bind();
-
- m_vbo.create();
- m_vbo.bind();
- m_vbo.allocate(...);
-
- m_texture = new QOpenGLTexture(QImage(...));
-
- m_shader = new QOpenGLShader(...);
- m_program = new QOpenGLShaderProgram(...);
-
- ...
-}
-//! [4]
-
-//! [5]
-void MyGLWidget::initializeGL()
-{
- // context() and QOpenGLContext::currentContext() are equivalent when called from initializeGL or paintGL.
- connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &MyGLWidget::cleanup);
-}
-
-void MyGLWidget::cleanup()
-{
- makeCurrent();
- delete m_texture;
- m_texture = 0;
- ...
- doneCurrent();
-}
-//! [5]
-
-//! [6]
-int main(int argc, char **argv)
-{
- QApplication app(argc, argv);
-
- QSurfaceFormat format;
- format.setDepthBufferSize(24);
- format.setStencilBufferSize(8);
- format.setVersion(3, 2);
- format.setProfile(QSurfaceFormat::CoreProfile);
- QSurfaceFormat::setDefaultFormat(format);
-
- MyWidget widget;
- widget.show();
-
- return app.exec();
-}
-//! [6]
diff --git a/src/widgets/doc/snippets/code/doc_src_layout.cpp b/src/widgets/doc/snippets/code/doc_src_layout.cpp
index 7bbd781bb2..816a59725a 100644
--- a/src/widgets/doc/snippets/code/doc_src_layout.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_layout.cpp
@@ -1,59 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
#ifndef CARD_H
#define CARD_H
#include <QtWidgets>
-#include <QVector>
+#include <QList>
class CardLayout : public QLayout
{
@@ -73,7 +26,7 @@ public:
void setGeometry(const QRect &rect) override;
private:
- QVector<QLayoutItem*> m_items;
+ QList<QLayoutItem *> m_items;
};
#endif
//! [0]
@@ -86,7 +39,7 @@ private:
//! [2]
int CardLayout::count() const
{
- // QVector::size() returns the number of QLayoutItems in m_items
+ // QList::size() returns the number of QLayoutItems in m_items
return m_items.size();
}
//! [2]
@@ -94,14 +47,14 @@ int CardLayout::count() const
//! [3]
QLayoutItem *CardLayout::itemAt(int idx) const
{
- // QVector::value() performs index checking, and returns nullptr if we are
+ // QList::value() performs index checking, and returns nullptr if we are
// outside the valid range
return m_items.value(idx);
}
QLayoutItem *CardLayout::takeAt(int idx)
{
- // QVector::take does not do index checking
+ // QList::take does not do index checking
return idx >= 0 && idx < m_items.size() ? m_items.takeAt(idx) : 0;
}
//! [3]
diff --git a/src/widgets/doc/snippets/code/doc_src_model-view-programming.cpp b/src/widgets/doc/snippets/code/doc_src_model-view-programming.cpp
index 74d235e344..f63578f66e 100644
--- a/src/widgets/doc/snippets/code/doc_src_model-view-programming.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_model-view-programming.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QAbstractItemModel *model = index.model();
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 133acf657a..2c8a892511 100644
--- a/src/widgets/doc/snippets/code/doc_src_qt4-mainwindow.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_qt4-mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
MainWindow::MainWindow(QWidget *parent)
@@ -73,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 f550ee36ce..2ec3afba01 100644
--- a/src/widgets/doc/snippets/code/doc_src_qt4-styles.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_qt4-styles.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
const QStyleOptionFocusRect *focusRectOption =
@@ -71,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 = 0) const;
-//! [3]
diff --git a/src/widgets/doc/snippets/code/doc_src_qtwidgets.cpp b/src/widgets/doc/snippets/code/doc_src_qtwidgets.cpp
deleted file mode 100644
index c0a57e527c..0000000000
--- a/src/widgets/doc/snippets/code/doc_src_qtwidgets.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//! [1]
-#include <QtWidgets>
-//! [1]
diff --git a/src/widgets/doc/snippets/code/doc_src_qtwidgets.pro b/src/widgets/doc/snippets/code/doc_src_qtwidgets.pro
deleted file mode 100644
index 2fee715c24..0000000000
--- a/src/widgets/doc/snippets/code/doc_src_qtwidgets.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-#! [0]
-QT += widgets
-#! [0]
diff --git a/src/widgets/doc/snippets/code/doc_src_styles.cpp b/src/widgets/doc/snippets/code/doc_src_styles.cpp
index 3536be6e7b..72382217a2 100644
--- a/src/widgets/doc/snippets/code/doc_src_styles.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_styles.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
opt.initFrom(q);
diff --git a/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp b/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp
index 749d62a588..91851f8f07 100644
--- a/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [21]
qApp->setStyleSheet("QPushButton { color: white }");
@@ -98,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 b0d042566f..388e9d1f7c 100644
--- a/src/widgets/doc/snippets/code/doc_src_stylesheet.qdoc
+++ b/src/widgets/doc/snippets/code/doc_src_stylesheet.qdoc
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
//! [0]
QLineEdit { background: yellow }
@@ -497,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]
@@ -1270,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;
@@ -1314,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;
@@ -1896,3 +1865,6 @@ QTableView::indicator:unchecked {
* { widget-animation-duration: 100 }
//! [162]
+//! [163]
+QLineEdit { placeholder-text-color: #800000ff } /* semi-transparent blue */
+//! [163]
diff --git a/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp b/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
index ed6043564b..197c23f247 100644
--- a/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
fileName = QFileDialog::getOpenFileName(this,
@@ -157,5 +110,7 @@ QFileDialog::getOpenFileContent("Images (*.png *.xpm *.jpg)", fileContentReady)
//! [16]
QByteArray imageData; // obtained from e.g. QImage::save()
-QFileDialog::saveFile("myimage.png", imageData);
+QFileDialog::saveFileContent(imageData, "myimage.png"); // with filename hint
+// OR
+QFileDialog::saveFileContent(imageData); // no filename hint
//! [16]
diff --git a/src/widgets/doc/snippets/code/src_gui_dialogs_qfontdialog.cpp b/src/widgets/doc/snippets/code/src_gui_dialogs_qfontdialog.cpp
index 2c13131ae6..ae6b69cbe8 100644
--- a/src/widgets/doc/snippets/code/src_gui_dialogs_qfontdialog.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_dialogs_qfontdialog.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
bool ok;
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 82f916581e..ebc07025ec 100644
--- a/src/widgets/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
int ret = QMessageBox::warning(this, tr("My Application"),
@@ -58,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);
@@ -147,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_dialogs_qwizard.cpp b/src/widgets/doc/snippets/code/src_gui_dialogs_qwizard.cpp
index 1274827799..328b99e108 100644
--- a/src/widgets/doc/snippets/code/src_gui_dialogs_qwizard.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_dialogs_qwizard.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
int LicenseWizard::nextId() const
diff --git a/src/widgets/doc/snippets/code/src_gui_effects_qgraphicseffect.cpp b/src/widgets/doc/snippets/code/src_gui_effects_qgraphicseffect.cpp
index 60d7cc1d71..3fd61f5c72 100644
--- a/src/widgets/doc/snippets/code/src_gui_effects_qgraphicseffect.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_effects_qgraphicseffect.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
MyGraphicsOpacityEffect::draw(QPainter *painter)
diff --git a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp
index 9f64299190..3b46c54bad 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp
@@ -1,63 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QGraphicsScene scene;
QGraphicsWidget *textEdit = scene.addWidget(new QTextEdit);
QGraphicsWidget *pushButton = scene.addWidget(new QPushButton);
-QGraphicsGridLayout *layout = new QGraphicsGridLayout;
-layout->addItem(textEdit, 0, 0);
-layout->addItem(pushButton, 0, 1);
-
QGraphicsWidget *form = new QGraphicsWidget;
-form->setLayout(layout);
scene.addItem(form);
+
+QGraphicsGridLayout *layout = new QGraphicsGridLayout(form);
+layout->addItem(textEdit, 0, 0);
+layout->addItem(pushButton, 0, 1);
//! [0]
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 ebca9d5368..bcf675d8af 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
class SimpleItem : public QGraphicsItem
@@ -118,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
{
@@ -270,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_qgraphicslinearlayout.cpp b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicslinearlayout.cpp
index 22a283675b..cc3b1678d0 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicslinearlayout.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicslinearlayout.cpp
@@ -1,63 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QGraphicsScene scene;
QGraphicsWidget *textEdit = scene.addWidget(new QTextEdit);
QGraphicsWidget *pushButton = scene.addWidget(new QPushButton);
-QGraphicsLinearLayout *layout = new QGraphicsLinearLayout;
-layout->addItem(textEdit);
-layout->addItem(pushButton);
-
QGraphicsWidget *form = new QGraphicsWidget;
-form->setLayout(layout);
scene.addItem(form);
+
+QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(form);
+layout->addItem(textEdit);
+layout->addItem(pushButton);
//! [0]
diff --git a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp
index 52f452112b..b8cb7b493c 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
int main(int argc, char **argv)
@@ -70,9 +23,8 @@ QGroupBox *groupBox = new QGroupBox("Contact Details");
QLabel *numberLabel = new QLabel("Telephone number");
QLineEdit *numberEdit = new QLineEdit;
-QFormLayout *layout = new QFormLayout;
+QFormLayout *layout = new QFormLayout(groupBox);
layout->addRow(numberLabel, numberEdit);
-groupBox->setLayout(layout);
QGraphicsScene scene;
QGraphicsProxyWidget *proxy = scene.addWidget(groupBox);
diff --git a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp
index f052435b06..d80271cfe2 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QGraphicsScene scene;
diff --git a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp
index d508a95f1e..7ddcf5938a 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
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 35cb6b2168..0b757cf0a2 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsview.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicsview.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QGraphicsScene scene;
@@ -74,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_graphicsview_qgraphicswidget.cpp b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp
index e078e87844..58ef7a33de 100644
--- a/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void MyGroupBoxWidget::initStyleOption(QStyleOption *option) const
diff --git a/src/widgets/doc/snippets/code/src_gui_image_qpixmapfilter.cpp b/src/widgets/doc/snippets/code/src_gui_image_qpixmapfilter.cpp
index 183b091927..386daa2a0c 100644
--- a/src/widgets/doc/snippets/code/src_gui_image_qpixmapfilter.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_image_qpixmapfilter.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QPixmapColorizeFilter *myFilter = new QPixmapColorFilter;
diff --git a/src/widgets/doc/snippets/code/src_gui_itemviews_qabstractitemview.cpp b/src/widgets/doc/snippets/code/src_gui_itemviews_qabstractitemview.cpp
index a650bf81e8..e260476e3f 100644
--- a/src/widgets/doc/snippets/code/src_gui_itemviews_qabstractitemview.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_itemviews_qabstractitemview.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void MyView::resizeEvent(QResizeEvent *event) {
diff --git a/src/widgets/doc/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp b/src/widgets/doc/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp
index cc1568cb9d..c9b9193b2a 100644
--- a/src/widgets/doc/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QDataWidgetMapper *mapper = new QDataWidgetMapper;
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 9745700b07..d314c88fd9 100644
--- a/src/widgets/doc/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
Q_PROPERTY(QColor color READ color WRITE setColor USER true)
@@ -64,7 +17,7 @@ QItemEditorFactory *factory = new QItemEditorFactory;
//! [2]
QItemEditorFactory *editorFactory = new QItemEditorFactory;
QItemEditorCreatorBase *creator = new QStandardItemEditorCreator<MyFancyDateTimeEdit>();
-editorFactory->registerEditor(QVariant::DateType, creator);
+editorFactory->registerEditor(QMetaType::QDateTime, creator);
//! [2]
diff --git a/src/widgets/doc/snippets/code/src_gui_itemviews_qtablewidget.cpp b/src/widgets/doc/snippets/code/src_gui_itemviews_qtablewidget.cpp
index c40152ff49..6be31be6d8 100644
--- a/src/widgets/doc/snippets/code/src_gui_itemviews_qtablewidget.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_itemviews_qtablewidget.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
setCellWidget(row, column, new QLineEdit);
diff --git a/src/widgets/doc/snippets/code/src_gui_itemviews_qtreewidget.cpp b/src/widgets/doc/snippets/code/src_gui_itemviews_qtreewidget.cpp
index f1e3b6ea45..55136f1d37 100644
--- a/src/widgets/doc/snippets/code/src_gui_itemviews_qtreewidget.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_itemviews_qtreewidget.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QTreeWidget *treeWidget = new QTreeWidget();
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qaction.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qaction.cpp
deleted file mode 100644
index 763238076c..0000000000
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qaction.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//! [0]
-QApplication app(argc, argv);
-app.setAttribute(Qt::AA_DontShowIconsInMenus); // Icons are *no longer shown* in menus
-// ...
-QAction *myAction = new QAction();
-// ...
-myAction->setIcon(SomeIcon);
-myAction->setIconVisibleInMenu(true); // Icon *will* be shown in menus for *this* action.
-//! [0]
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp
index 5e1f0883e7..0d14b086cc 100644
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_kernel_qapplication.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QCoreApplication* createApplication(int &argc, char *argv[])
@@ -78,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).expandedTo(QApplication::globalStrut());
-}
-//! [3]
-
-
//! [4]
void showAllHiddenTopLevelWidgets()
{
@@ -120,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 a2ac780a82..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,63 +1,19 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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;
+QFormLayout *formLayout = new QFormLayout(this);
formLayout->addRow(tr("&Name:"), nameLineEdit);
formLayout->addRow(tr("&Email:"), emailLineEdit);
formLayout->addRow(tr("&Age:"), ageSpinBox);
-setLayout(formLayout);
//! [0]
//! [1]
+QGridLayout *gridLayout = new QGridLayout(this);
+
nameLabel = new QLabel(tr("&Name:"));
nameLabel->setBuddy(nameLineEdit);
@@ -67,14 +23,12 @@ emailLabel->setBuddy(emailLineEdit);
ageLabel = new QLabel(tr("&Name:"));
ageLabel->setBuddy(ageSpinBox);
-QGridLayout *gridLayout = new QGridLayout;
gridLayout->addWidget(nameLabel, 0, 0);
gridLayout->addWidget(nameLineEdit, 0, 1);
gridLayout->addWidget(emailLabel, 1, 0);
gridLayout->addWidget(emailLineEdit, 1, 1);
gridLayout->addWidget(ageLabel, 2, 0);
gridLayout->addWidget(ageSpinBox, 2, 1);
-setLayout(gridLayout);
//! [1]
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qlayout.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qlayout.cpp
index c55834ebfb..60b669a228 100644
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qlayout.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_kernel_qlayout.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
static void paintLayout(QPainter *painter, QLayoutItem *item)
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qlayoutitem.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qlayoutitem.cpp
index dd0f860c01..fe857d1047 100644
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qlayoutitem.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_kernel_qlayoutitem.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
int MyLayout::heightForWidth(int w) const
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qshortcut.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qshortcut.cpp
deleted file mode 100644
index bac264fcfc..0000000000
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qshortcut.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//! [0]
-shortcut = new QShortcut(QKeySequence(tr("Ctrl+O", "File|Open")),
- parent);
-//! [0]
-
-
-//! [1]
-setKey(0); // no signal emitted
-setKey(QKeySequence()); // no signal emitted
-setKey(0x3b1); // Greek letter alpha
-setKey(Qt::Key_D); // 'd', e.g. to delete
-setKey('q'); // 'q', e.g. to quit
-setKey(Qt::CTRL + Qt::Key_P); // Ctrl+P, e.g. to print document
-setKey("Ctrl+P"); // Ctrl+P, e.g. to print document
-//! [1]
diff --git a/src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp b/src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp
index f2db73226b..21703c7395 100644
--- a/src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_kernel_qwidget.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
w->setWindowState(w->windowState() ^ Qt::WindowFullScreen);
@@ -69,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]
@@ -108,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_painting_qdrawutil.cpp b/src/widgets/doc/snippets/code/src_gui_painting_qdrawutil.cpp
index 6f39086c8d..75af4fcc62 100644
--- a/src/widgets/doc/snippets/code/src_gui_painting_qdrawutil.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_painting_qdrawutil.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QFrame frame:
diff --git a/src/widgets/doc/snippets/code/src_gui_qproxystyle.cpp b/src/widgets/doc/snippets/code/src_gui_qproxystyle.cpp
index 98dc0ff55b..a2f3e4d8f9 100644
--- a/src/widgets/doc/snippets/code/src_gui_qproxystyle.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_qproxystyle.cpp
@@ -1,68 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//! [0]
-class MyProxyStyle : public QProxyStyle
-{
-public:
-
- int styleHint(StyleHint hint, const QStyleOption *option = nullptr,
- const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const override
- {
- if (hint == QStyle::SH_UnderlineShortcut)
- return 1;
- return QProxyStyle::styleHint(hint, option, widget, returnData);
- }
-};
-
-//! [0]
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [1]
#include "textedit.h"
@@ -93,3 +30,11 @@ int main(int argc, char **argv)
//...
}
//! [1]
+
+//! [2]
+...
+auto proxy = new MyProxyStyle(QApplication::style()->name());
+proxy->setParent(widget); // take ownership to avoid memleak
+widget->setStyle(proxy);
+...
+//! [2]
diff --git a/src/widgets/doc/snippets/code/src_gui_styles_qstyle.cpp b/src/widgets/doc/snippets/code/src_gui_styles_qstyle.cpp
index bb3f62969a..d4b8a45b36 100644
--- a/src/widgets/doc/snippets/code/src_gui_styles_qstyle.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_styles_qstyle.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
./myapplication -style windows
diff --git a/src/widgets/doc/snippets/code/src_gui_styles_qstyleoption.cpp b/src/widgets/doc/snippets/code/src_gui_styles_qstyleoption.cpp
index 26f9ace28d..44cb0b35eb 100644
--- a/src/widgets/doc/snippets/code/src_gui_styles_qstyleoption.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_styles_qstyleoption.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
int MyStyle::styleHint(StyleHint stylehint, const QStyleOption *opt,
diff --git a/src/widgets/doc/snippets/code/src_gui_util_qcompleter.cpp b/src/widgets/doc/snippets/code/src_gui_util_qcompleter.cpp
index 7d003e4886..4c95c05b26 100644
--- a/src/widgets/doc/snippets/code/src_gui_util_qcompleter.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_util_qcompleter.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QStringList wordList;
diff --git a/src/widgets/doc/snippets/code/src_gui_util_qundostack.cpp b/src/widgets/doc/snippets/code/src_gui_util_qundostack.cpp
deleted file mode 100644
index 8f59fe9cb3..0000000000
--- a/src/widgets/doc/snippets/code/src_gui_util_qundostack.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//! [0]
-class AppendText : public QUndoCommand
-{
-public:
- AppendText(QString *doc, const QString &text)
- : m_document(doc), m_text(text) { setText("append text"); }
- void undo() override
- { m_document->chop(m_text.length()); }
- void redo() override
- { m_document->append(m_text); }
-private:
- QString *m_document;
- QString m_text;
-};
-//! [0]
-
-
-//! [1]
-MyCommand *command1 = new MyCommand();
-stack->push(command1);
-MyCommand *command2 = new MyCommand();
-stack->push(command2);
-
-stack->undo();
-
-MyCommand *command3 = new MyCommand();
-stack->push(command3); // command2 gets deleted
-//! [1]
-
-
-//! [2]
-QUndoCommand *insertRed = new QUndoCommand(); // an empty command
-insertRed->setText("insert red text");
-
-new InsertText(document, idx, text, insertRed); // becomes child of insertRed
-new SetColor(document, idx, text.length(), Qt::red, insertRed);
-
-stack.push(insertRed);
-//! [2]
-
-
-//! [3]
-bool AppendText::mergeWith(const QUndoCommand *other)
-{
- if (other->id() != id()) // make sure other is also an AppendText command
- return false;
- m_text += static_cast<const AppendText*>(other)->m_text;
- return true;
-}
-//! [3]
-
-
-//! [4]
-stack.beginMacro("insert red text");
-stack.push(new InsertText(document, idx, text));
-stack.push(new SetColor(document, idx, text.length(), Qt::red));
-stack.endMacro(); // indexChanged() is emitted
-//! [4]
-
-
-//! [5]
-QUndoCommand *insertRed = new QUndoCommand(); // an empty command
-insertRed->setText("insert red text");
-
-new InsertText(document, idx, text, insertRed); // becomes child of insertRed
-new SetColor(document, idx, text.length(), Qt::red, insertRed);
-
-stack.push(insertRed);
-//! [5]
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qabstractbutton.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qabstractbutton.cpp
index bc171824af..099f0708ec 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qabstractbutton.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qabstractbutton.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QPushButton *button = new QPushButton(tr("Ro&ck && Roll"), this);
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qabstractspinbox.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qabstractspinbox.cpp
index c8a4c29f91..bb5badea38 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qabstractspinbox.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qabstractspinbox.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QSpinBox *spinBox = new QSpinBox(this);
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qcalendarwidget.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qcalendarwidget.cpp
index 763a5cb1fb..712a84ac2a 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qcalendarwidget.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qcalendarwidget.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QCalendarWidget *calendar;
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qcheckbox.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qcheckbox.cpp
index e076cada9a..c62f73dfca 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qcheckbox.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qcheckbox.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QCheckBox *checkbox = new QCheckBox("C&ase sensitive", this);
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qdatetimeedit.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qdatetimeedit.cpp
index 085acc422a..c70a3017b3 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qdatetimeedit.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qdatetimeedit.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QDateTimeEdit *dateEdit = new QDateTimeEdit(QDate::currentDate());
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qdockwidget.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qdockwidget.cpp
index bf3c549cb6..99fff8bdeb 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qdockwidget.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qdockwidget.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QDockWidget *dockWidget = qobject_cast<QDockWidget*>(parentWidget());
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qframe.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qframe.cpp
index ec01bc0d81..0aac71ff4a 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qframe.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qframe.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QLabel label(...);
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 e1f707672e..cff537c862 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qgroupbox.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qgroupbox.cpp
@@ -1,53 +1,23 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [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_qlabel.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qlabel.cpp
index 9f3ca992bf..5e4cc64198 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qlabel.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qlabel.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QLabel *label = new QLabel(this);
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qlineedit.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qlineedit.cpp
index 5b293e6533..5017678af4 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qlineedit.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qlineedit.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void LineEdit::contextMenuEvent(QContextMenuEvent *event)
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qmainwindow.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qmainwindow.cpp
index 7bff9ce8d9..878daffcf7 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qmainwindow.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qmainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void MyMainWindow::closeEvent(QCloseEvent *event)
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 da3fd28056..eb0897d5c5 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
exec(QCursor::pos());
@@ -59,7 +12,7 @@ exec(somewidget.mapToGlobal(QPoint(0,0)));
//! [2]
-exec(e->globalPos());
+exec(e->globalPosition().toPoint());
//! [2]
@@ -74,14 +27,14 @@ exec(somewidget.mapToGlobal(QPoint(0, 0)));
//! [5]
-exec(e->globalPos());
+exec(e->globalPosition().toPoint());
//! [5]
//! [6]
QMenu menu;
QAction *at = actions[0]; // Assumes actions is not empty
-for (QAction *a : qAsConst(actions))
+for (QAction *a : std::as_const(actions))
menu.addAction(a);
menu.exec(pos, at);
//! [6]
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qmenubar.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qmenubar.cpp
index b52b0064ad..d096336cf7 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qmenubar.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qmenubar.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
menubar->addMenu(fileMenu);
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qplaintextedit.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qplaintextedit.cpp
index 4f86f2ae31..f0593aa6de 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qplaintextedit.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qplaintextedit.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void MyQPlainTextEdit::contextMenuEvent(QContextMenuEvent *event)
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qpushbutton.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qpushbutton.cpp
index a64d085ba2..35827bcba2 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qpushbutton.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qpushbutton.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QPushButton *button = new QPushButton("&Download", this);
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qradiobutton.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qradiobutton.cpp
index 85ba1c300a..96d0fe018b 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qradiobutton.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qradiobutton.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QRadioButton *button = new QRadioButton("Search from the &cursor", this);
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qrubberband.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qrubberband.cpp
index c63d675b35..e6f6ab0c0a 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qrubberband.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qrubberband.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void Widget::mousePressEvent(QMouseEvent *event)
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qscrollarea.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qscrollarea.cpp
index 328b5fbd57..b05258883a 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qscrollarea.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qscrollarea.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QLabel *imageLabel = new QLabel;
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 aab9bee62a..ec4b5bf27f 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qspinbox.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qspinbox.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
sb->setPrefix("$");
@@ -88,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_qsplashscreen.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qsplashscreen.cpp
index 91aa8a9c4e..fa7d25da4d 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qsplashscreen.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qsplashscreen.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QPixmap pixmap(":/splash.png");
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qsplitter.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qsplitter.cpp
index 3e30b38521..cab65b35f3 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qsplitter.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qsplitter.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
QWidget *widget = splitter->widget(index);
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 1f8edacff4..e05d27353a 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qstatusbar.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qstatusbar.cpp
@@ -1,53 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [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_gui_widgets_qtextbrowser.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qtextbrowser.cpp
index 2c17a0761b..96faf13299 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qtextbrowser.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qtextbrowser.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
backaction.setToolTip(browser.historyTitle(-1));
diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qtextedit.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qtextedit.cpp
index cace028c68..4ee48a545d 100644
--- a/src/widgets/doc/snippets/code/src_gui_widgets_qtextedit.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_widgets_qtextedit.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void MyTextEdit::contextMenuEvent(QContextMenuEvent *event)
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 2b3d825266..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,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// 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 8ebaaf3991..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,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [0]
void MainWindow::createMenus()
diff --git a/src/widgets/doc/snippets/common-table-model/model.cpp b/src/widgets/doc/snippets/common-table-model/model.cpp
index 2f6e9f1144..5dcec124bb 100644
--- a/src/widgets/doc/snippets/common-table-model/model.cpp
+++ b/src/widgets/doc/snippets/common-table-model/model.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
model.cpp
diff --git a/src/widgets/doc/snippets/common-table-model/model.h b/src/widgets/doc/snippets/common-table-model/model.h
index 5f152e0e78..cc994bd8e1 100644
--- a/src/widgets/doc/snippets/common-table-model/model.h
+++ b/src/widgets/doc/snippets/common-table-model/model.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MODEL_H
#define MODEL_H
diff --git a/src/widgets/doc/snippets/customstyle/customstyle.cpp b/src/widgets/doc/snippets/customstyle/customstyle.cpp
index 61a8ec5600..74de2705be 100644
--- a/src/widgets/doc/snippets/customstyle/customstyle.cpp
+++ b/src/widgets/doc/snippets/customstyle/customstyle.cpp
@@ -1,58 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "customstyle.h"
-CustomStyle::CustomStyle()
+CustomStyle::CustomStyle(const QWidget *widget)
{
//! [0]
const QSpinBox *spinBox = qobject_cast<const QSpinBox *>(widget);
@@ -94,7 +47,7 @@ void CustomStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *op
}
painter->drawPolygon(points);
} else {
- QProxyStyle::drawPrimitive(element, option, painter, widget);
+ QProxyStyle::drawPrimitive(element, option, painter, widget);
//! [2] //! [3]
}
//! [3] //! [4]
diff --git a/src/widgets/doc/snippets/customstyle/customstyle.h b/src/widgets/doc/snippets/customstyle/customstyle.h
index be9edf0bf4..370065c2b3 100644
--- a/src/widgets/doc/snippets/customstyle/customstyle.h
+++ b/src/widgets/doc/snippets/customstyle/customstyle.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef CUSTOMSTYLE_H
#define CUSTOMSTYLE_H
@@ -59,7 +12,7 @@ class CustomStyle : public QProxyStyle
Q_OBJECT
public:
- CustomStyle();
+ CustomStyle(const QWidget *widget);
~CustomStyle() {}
void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
diff --git a/src/widgets/doc/snippets/customstyle/customstyle.pro b/src/widgets/doc/snippets/customstyle/customstyle.pro
deleted file mode 100644
index 02b9b2791d..0000000000
--- a/src/widgets/doc/snippets/customstyle/customstyle.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-QT += widgets
-HEADERS += customstyle.h
-SOURCES += customstyle.cpp main.cpp
diff --git a/src/widgets/doc/snippets/customstyle/main.cpp b/src/widgets/doc/snippets/customstyle/main.cpp
index 7ebd1ed1c3..41bc886d8b 100644
--- a/src/widgets/doc/snippets/customstyle/main.cpp
+++ b/src/widgets/doc/snippets/customstyle/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [using a custom style]
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/customviewstyle.cpp b/src/widgets/doc/snippets/customviewstyle.cpp
deleted file mode 100644
index b9c10cb31d..0000000000
--- a/src/widgets/doc/snippets/customviewstyle.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtWidgets>
-
-#include "customviewstyle.h"
-
-
-
-void CustomViewStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
-{
-
-//![0]
- switch (element) {
- case (PE_PanelItemViewItem): {
- painter->save();
-
- QPoint topLeft = option->rect.topLeft();
- QPoint bottomRight = option->rect.topRight();
- QLinearGradient backgroundGradient(topLeft, bottomRight);
- backgroundGradient.setColorAt(0.0, QColor(Qt::yellow).lighter(190));
- backgroundGradient.setColorAt(1.0, Qt::white);
- painter->fillRect(option->rect, QBrush(backgroundGradient));
-
- painter->restore();
- break;
- }
- default:
- QProxyStyle::drawPrimitive(element, option, painter, widget);
- }
-//![0]
-}
diff --git a/src/widgets/doc/snippets/customviewstyle/CMakeLists.txt b/src/widgets/doc/snippets/customviewstyle/CMakeLists.txt
new file mode 100644
index 0000000000..f37de58edc
--- /dev/null
+++ b/src/widgets/doc/snippets/customviewstyle/CMakeLists.txt
@@ -0,0 +1,16 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+add_library(widgets_customviewstyle_snippets OBJECT
+ ../customstyle/customstyle.h
+ ../customstyle/customstyle.cpp
+ customviewstyle.cpp
+)
+
+target_link_libraries(widgets_customviewstyle_snippets PRIVATE
+ Qt::Core
+ Qt::Gui
+ Qt::Widgets
+)
+
+set_target_properties(widgets_customviewstyle_snippets PROPERTIES UNITY_BUILD OFF)
diff --git a/src/widgets/doc/snippets/customviewstyle/customviewstyle.cpp b/src/widgets/doc/snippets/customviewstyle/customviewstyle.cpp
new file mode 100644
index 0000000000..7c690cab9f
--- /dev/null
+++ b/src/widgets/doc/snippets/customviewstyle/customviewstyle.cpp
@@ -0,0 +1,31 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QtWidgets>
+
+#include "../customstyle/customstyle.h"
+
+void CustomStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
+ QPainter *painter, const QWidget *widget) const
+{
+
+//![0]
+ switch (element) {
+ case (PE_PanelItemViewItem): {
+ painter->save();
+
+ QPoint topLeft = option->rect.topLeft();
+ QPoint bottomRight = option->rect.topRight();
+ QLinearGradient backgroundGradient(topLeft, bottomRight);
+ backgroundGradient.setColorAt(0.0, QColor(Qt::yellow).lighter(190));
+ backgroundGradient.setColorAt(1.0, Qt::white);
+ painter->fillRect(option->rect, QBrush(backgroundGradient));
+
+ painter->restore();
+ break;
+ }
+ default:
+ QProxyStyle::drawPrimitive(element, option, painter, widget);
+ }
+//![0]
+}
diff --git a/src/widgets/doc/snippets/dialogs/dialogs.cpp b/src/widgets/doc/snippets/dialogs/dialogs.cpp
index 7fa793c70f..0990d7d7c4 100644
--- a/src/widgets/doc/snippets/dialogs/dialogs.cpp
+++ b/src/widgets/doc/snippets/dialogs/dialogs.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
@@ -274,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/dockwidgets/mainwindow.cpp b/src/widgets/doc/snippets/dockwidgets/mainwindow.cpp
index 53f91589bf..96cba8aec7 100644
--- a/src/widgets/doc/snippets/dockwidgets/mainwindow.cpp
+++ b/src/widgets/doc/snippets/dockwidgets/mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
@@ -79,7 +32,7 @@ void MainWindow::setupContents()
do {
QString line = titlesFile.readLine().trimmed();
- QStringList parts = line.split("\t", QString::SkipEmptyParts);
+ QStringList parts = line.split(u'\t', Qt::SkipEmptyParts);
if (parts.size() != 2)
break;
@@ -119,7 +72,7 @@ void MainWindow::setupMenus()
QAction *exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
exitAct->setStatusTip(tr("Exit the application"));
- connect(exitAct, &QAction::triggered, qApp, &QApplication::closeAllWindows);
+ connect(exitAct, &QAction::triggered, qApp, &QApplication::quit);
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(exitAct);
diff --git a/src/widgets/doc/snippets/filedialogurls.cpp b/src/widgets/doc/snippets/filedialogurls.cpp
deleted file mode 100644
index cd91e797e7..0000000000
--- a/src/widgets/doc/snippets/filedialogurls.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtGui>
-
-int main(int argv, char **args)
-{
- QApplication app(argv, args);
-
-//![0]
- QList<QUrl> urls;
- urls << QUrl::fromLocalFile("/Users/foo/Code/qt5")
- << QUrl::fromLocalFile(QStandardPaths::standardLocations(QStandardPaths::MusicLocation).first());
-
- QFileDialog dialog;
- dialog.setSidebarUrls(urls);
- dialog.setFileMode(QFileDialog::AnyFile);
- if(dialog.exec()) {
- // ...
- }
-//![0]
-
- return app.exec();
-}
diff --git a/src/widgets/doc/snippets/filedialogurls/CMakeLists.txt b/src/widgets/doc/snippets/filedialogurls/CMakeLists.txt
new file mode 100644
index 0000000000..4c64ff3288
--- /dev/null
+++ b/src/widgets/doc/snippets/filedialogurls/CMakeLists.txt
@@ -0,0 +1,12 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+add_library(widgets_filedialogurl_snippets OBJECT
+ filedialogurls.cpp
+)
+
+target_link_libraries(widgets_filedialogurl_snippets PRIVATE
+ Qt::Core
+ Qt::Gui
+ Qt::Widgets
+)
diff --git a/src/widgets/doc/snippets/filedialogurls/filedialogurls.cpp b/src/widgets/doc/snippets/filedialogurls/filedialogurls.cpp
new file mode 100644
index 0000000000..40db71b5a7
--- /dev/null
+++ b/src/widgets/doc/snippets/filedialogurls/filedialogurls.cpp
@@ -0,0 +1,22 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QFileDialog>
+#include <QtGui>
+
+int loadFileDialog()
+{
+//![0]
+ QList<QUrl> urls;
+ urls << QUrl::fromLocalFile("/Users/foo/Code/qt5")
+ << QUrl::fromLocalFile(QStandardPaths::standardLocations(QStandardPaths::MusicLocation).first());
+
+ QFileDialog dialog;
+ dialog.setSidebarUrls(urls);
+ dialog.setFileMode(QFileDialog::AnyFile);
+ if (dialog.exec()) {
+ // ...
+ }
+//![0]
+ return 1;
+}
diff --git a/src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt b/src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt
new file mode 100644
index 0000000000..a2d391d629
--- /dev/null
+++ b/src/widgets/doc/snippets/graphicssceneadditem/CMakeLists.txt
@@ -0,0 +1,12 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+add_library(widgets_graphicssceneadditem_snippets OBJECT
+ graphicssceneadditemsnippet.cpp
+)
+
+target_link_libraries(widgets_graphicssceneadditem_snippets PRIVATE
+ Qt::Core
+ Qt::Gui
+ Qt::Widgets
+)
diff --git a/src/widgets/doc/snippets/graphicssceneadditem/graphicssceneadditemsnippet.cpp b/src/widgets/doc/snippets/graphicssceneadditem/graphicssceneadditemsnippet.cpp
new file mode 100644
index 0000000000..8ea5a5e74c
--- /dev/null
+++ b/src/widgets/doc/snippets/graphicssceneadditem/graphicssceneadditemsnippet.cpp
@@ -0,0 +1,34 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QGraphicsEllipseItem>
+#include <QGraphicsScene>
+#include <QStyleOptionGraphicsItem>
+#include <QtGui>
+
+class CustomScene : public QGraphicsScene
+{
+public:
+ CustomScene()
+ { addItem(new QGraphicsEllipseItem(QRect(10, 10, 30, 30))); }
+
+ void drawItems(QPainter *painter, int numItems, QGraphicsItem *items[],
+ const QStyleOptionGraphicsItem options[],
+ QWidget *widget = nullptr) override;
+};
+
+//! [0]
+void CustomScene::drawItems(QPainter *painter, int numItems,
+ QGraphicsItem *items[],
+ const QStyleOptionGraphicsItem options[],
+ QWidget *widget)
+{
+ for (int i = 0; i < numItems; ++i) {
+ // Draw the item
+ painter->save();
+ painter->setTransform(items[i]->sceneTransform(), true);
+ items[i]->paint(painter, &options[i], widget);
+ painter->restore();
+ }
+}
+//! [0]
diff --git a/src/widgets/doc/snippets/graphicssceneadditemsnippet.cpp b/src/widgets/doc/snippets/graphicssceneadditemsnippet.cpp
deleted file mode 100644
index 96e6bd650c..0000000000
--- a/src/widgets/doc/snippets/graphicssceneadditemsnippet.cpp
+++ /dev/null
@@ -1,90 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtGui>
-
-class CustomScene : public QGraphicsScene
-{
-public:
- CustomScene()
- { addItem(new QGraphicsEllipseItem(QRect(10, 10, 30, 30))); }
-
- void drawItems(QPainter *painter, int numItems, QGraphicsItem *items[],
- const QStyleOptionGraphicsItem options[],
- QWidget *widget = 0) override;
-};
-
-//! [0]
-void CustomScene::drawItems(QPainter *painter, int numItems,
- QGraphicsItem *items[],
- const QStyleOptionGraphicsItem options[],
- QWidget *widget)
-{
- for (int i = 0; i < numItems; ++i) {
- // Draw the item
- painter->save();
- painter->setMatrix(items[i]->sceneMatrix(), true);
- items[i]->paint(painter, &options[i], widget);
- painter->restore();
- }
-}
-//! [0]
-
-int main(int argv, char **args)
-{
- QApplication app(argv, args);
-
- CustomScene scene;
- QGraphicsView view(&scene);
-
- view.show();
-
- return app.exec();
-}
diff --git a/src/widgets/doc/snippets/graphicsview.cpp b/src/widgets/doc/snippets/graphicsview.cpp
deleted file mode 100644
index 371cff24a4..0000000000
--- a/src/widgets/doc/snippets/graphicsview.cpp
+++ /dev/null
@@ -1,127 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//! [0]
-QGraphicsScene scene;
-QGraphicsRectItem *rect = scene.addRect(QRectF(0, 0, 100, 100));
-
-QGraphicsItem *item = scene.itemAt(50, 50);
-// item == rect
-//! [0]
-
-
-//! [1]
-QGraphicsScene scene;
-myPopulateScene(&scene);
-
-QGraphicsView view(&scene);
-view.show();
-//! [1]
-
-
-//! [2]
-class View : public QGraphicsView
-{
-Q_OBJECT
- ...
-public slots:
- void zoomIn() { scale(1.2, 1.2); }
- void zoomOut() { scale(1 / 1.2, 1 / 1.2); }
- void rotateLeft() { rotate(-10); }
- void rotateRight() { rotate(10); }
- ...
-};
-//! [2]
-
-
-//! [3]
-QGraphicsScene scene;
-scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt::black), QBrush(Qt::green));
-
-QPrinter printer;
-if (QPrintDialog(&printer).exec() == QDialog::Accepted) {
- QPainter painter(&printer);
- painter.setRenderHint(QPainter::Antialiasing);
- scene.render(&painter);
-}
-//! [3]
-
-
-//! [4]
-QGraphicsScene scene;
-scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt::black), QBrush(Qt::green));
-
-QPixmap pixmap;
-QPainter painter(&pixmap);
-painter.setRenderHint(QPainter::Antialiasing);
-scene.render(&painter);
-painter.end();
-
-pixmap.save("scene.png");
-//! [4]
-
-
-//! [5]
-void CustomItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
-{
- QMimeData *data = new QMimeData;
- data->setColor(Qt::green);
-
- QDrag *drag = new QDrag(event->widget());
- drag->setMimeData(data);
- drag->start();
-}
-//! [5]
-
-
-//! [6]
-QGraphicsView view(&scene);
-view.setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
-//! [6]
diff --git a/src/widgets/doc/snippets/graphicsview/CMakeLists.txt b/src/widgets/doc/snippets/graphicsview/CMakeLists.txt
new file mode 100644
index 0000000000..e395eda045
--- /dev/null
+++ b/src/widgets/doc/snippets/graphicsview/CMakeLists.txt
@@ -0,0 +1,15 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+add_library(widgets_graphicsview_snippets OBJECT
+ graphicsview.cpp
+)
+
+target_link_libraries(widgets_graphicsview_snippets PRIVATE
+ Qt::Core
+ Qt::Gui
+ Qt::Widgets
+ Qt::OpenGL
+ Qt::OpenGLWidgets
+ Qt::PrintSupport
+)
diff --git a/src/widgets/doc/snippets/graphicsview/graphicsview.cpp b/src/widgets/doc/snippets/graphicsview/graphicsview.cpp
new file mode 100644
index 0000000000..e66d2d84fb
--- /dev/null
+++ b/src/widgets/doc/snippets/graphicsview/graphicsview.cpp
@@ -0,0 +1,103 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+#include <QStandardItem>
+#include <QtCore/qmimedata.h>
+#include <QtGui/qdrag.h>
+#include <QtOpenGLWidgets/qopenglwidget.h>
+#include <QtPrintSupport/qprintdialog.h>
+#include <QtPrintSupport/qprinter.h>
+#include <QtWidgets/QGraphicsSceneMouseEvent>
+#include <QtWidgets/qdialog.h>
+#include <QtWidgets/qgraphicsview.h>
+
+void graphicsview_snippet_main()
+{
+//! [0]
+QGraphicsScene scene;
+QGraphicsRectItem *rect = scene.addRect(QRectF(0, 0, 100, 100));
+
+QGraphicsItem *item = scene.itemAt(50, 50, QTransform());
+//! [0]
+Q_UNUSED(rect);
+Q_UNUSED(item);
+}
+
+void myPopulateScene(QGraphicsScene *)
+{
+ // Intentionally left empty
+}
+
+void snippetThatUsesMyPopulateScene()
+{
+//! [1]
+QGraphicsScene scene;
+myPopulateScene(&scene);
+QGraphicsView view(&scene);
+view.show();
+//! [1]
+}
+
+class CustomItem : public QStandardItem
+{
+public:
+ using QStandardItem::QStandardItem;
+
+ int type() const override { return UserType; }
+ void mousePressEvent(QGraphicsSceneMouseEvent *event);
+ QStandardItem *clone() const override { return new CustomItem; }
+};
+
+
+void printScene()
+{
+//! [3]
+QGraphicsScene scene;
+QPrinter printer;
+scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt::black), QBrush(Qt::green));
+
+if (QPrintDialog(&printer).exec() == QDialog::Accepted) {
+ QPainter painter(&printer);
+ painter.setRenderHint(QPainter::Antialiasing);
+ scene.render(&painter);
+}
+//! [3]
+}
+
+void pixmapScene()
+{
+//! [4]
+QGraphicsScene scene;
+scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt::black), QBrush(Qt::green));
+
+QPixmap pixmap;
+QPainter painter(&pixmap);
+painter.setRenderHint(QPainter::Antialiasing);
+scene.render(&painter);
+painter.end();
+
+pixmap.save("scene.png");
+//! [4]
+}
+
+//! [5]
+void CustomItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
+{
+ QMimeData *data = new QMimeData;
+ QDrag *drag = new QDrag(event->widget());
+ drag->setMimeData(data);
+ drag->exec();
+}
+//! [5]
+
+void viewScene()
+{
+QGraphicsScene scene;
+//! [6]
+QGraphicsView view(&scene);
+QOpenGLWidget *gl = new QOpenGLWidget();
+QSurfaceFormat format;
+format.setSamples(4);
+gl->setFormat(format);
+view.setViewport(gl);
+//! [6]
+}
diff --git a/src/widgets/doc/snippets/graphicsview/graphicsview_snippet.cpp b/src/widgets/doc/snippets/graphicsview/graphicsview_snippet.cpp
new file mode 100644
index 0000000000..303f2fa9e2
--- /dev/null
+++ b/src/widgets/doc/snippets/graphicsview/graphicsview_snippet.cpp
@@ -0,0 +1,16 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+//! [2]
+class View : public QGraphicsView
+{
+Q_OBJECT
+ ...
+public slots:
+ void zoomIn() { scale(1.2, 1.2); }
+ void zoomOut() { scale(1 / 1.2, 1 / 1.2); }
+ void rotateLeft() { rotate(-10); }
+ void rotateRight() { rotate(10); }
+ ...
+};
+//! [2]
diff --git a/src/widgets/doc/snippets/itemselection/itemselection.pro b/src/widgets/doc/snippets/itemselection/itemselection.pro
deleted file mode 100644
index 57f752f0b0..0000000000
--- a/src/widgets/doc/snippets/itemselection/itemselection.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-QT += widgets
-HEADERS = ../common-table-model/model.h
-SOURCES = main.cpp \
- ../common-table-model/model.cpp
-INCLUDEPATH += ../common-table-model
diff --git a/src/widgets/doc/snippets/itemselection/main.cpp b/src/widgets/doc/snippets/itemselection/main.cpp
index c63bc55b5a..4c74e07496 100644
--- a/src/widgets/doc/snippets/itemselection/main.cpp
+++ b/src/widgets/doc/snippets/itemselection/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
main.cpp
diff --git a/src/widgets/doc/snippets/javastyle.cpp b/src/widgets/doc/snippets/javastyle.cpp
index 54a4ade921..deb77cbe4e 100644
--- a/src/widgets/doc/snippets/javastyle.cpp
+++ b/src/widgets/doc/snippets/javastyle.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
@@ -380,10 +333,10 @@ void JavaStyle::drawControl(ControlElement control, const QStyleOption *option,
QRect rect = bar->rect;
if (bar->orientation == Qt::Vertical) {
rect = QRect(rect.left(), rect.top(), rect.height(), rect.width());
- QMatrix m;
+ QTransform m;
m.translate(rect.height()-1, 0);
m.rotate(90.0);
- painter->setMatrix(m);
+ painter->setTransform(m);
}
painter->setPen(bar->palette.color(QPalette::Mid));
@@ -670,7 +623,7 @@ void JavaStyle::drawControl(ControlElement control, const QStyleOption *option,
textRect);
QString s = menuitem->text;
if (!s.isEmpty()) {
- int t = s.indexOf(QLatin1Char('\t'));
+ qsizetype t = s.indexOf(u'\t');
int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic |
Qt::TextDontClip | Qt::TextSingleLine;
if (!styleHint(SH_UnderlineShortcut, menuitem, widget))
@@ -2727,7 +2680,7 @@ QSize JavaStyle::sizeFromContents(ContentsType type,
if (!menuItem->text.isEmpty()) {
QFontMetrics metrics(menuItem->font);
QString text = menuItem->text;
- text.remove(QLatin1Char('\t'));
+ text.remove(u'\t');
QRect textRect = metrics.boundingRect(text);
width += textRect.width();
if (height < textRect.height())
diff --git a/src/widgets/doc/snippets/layouts/layouts.cpp b/src/widgets/doc/snippets/layouts/layouts.cpp
index 6d2ea580b4..a45eb47f84 100644
--- a/src/widgets/doc/snippets/layouts/layouts.cpp
+++ b/src/widgets/doc/snippets/layouts/layouts.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
@@ -67,7 +20,7 @@ int main(int argc, char *argv[])
//! [2]
//! [3]
- QHBoxLayout *layout = new QHBoxLayout;
+ QHBoxLayout *layout = new QHBoxLayout(window);
//! [3] //! [4]
layout->addWidget(button1);
layout->addWidget(button2);
@@ -75,7 +28,6 @@ int main(int argc, char *argv[])
layout->addWidget(button4);
layout->addWidget(button5);
- window->setLayout(layout);
//! [4]
window->setWindowTitle("QHBoxLayout");
//! [5]
@@ -96,7 +48,7 @@ int main(int argc, char *argv[])
//! [8]
//! [9]
- QVBoxLayout *layout = new QVBoxLayout;
+ QVBoxLayout *layout = new QVBoxLayout(window);
//! [9] //! [10]
layout->addWidget(button1);
layout->addWidget(button2);
@@ -104,7 +56,6 @@ int main(int argc, char *argv[])
layout->addWidget(button4);
layout->addWidget(button5);
- window->setLayout(layout);
//! [10]
window->setWindowTitle("QVBoxLayout");
//! [11]
@@ -125,7 +76,7 @@ int main(int argc, char *argv[])
//! [14]
//! [15]
- QGridLayout *layout = new QGridLayout;
+ QGridLayout *layout = new QGridLayout(window);
//! [15] //! [16]
layout->addWidget(button1, 0, 0);
layout->addWidget(button2, 0, 1);
@@ -133,7 +84,6 @@ int main(int argc, char *argv[])
layout->addWidget(button4, 2, 0);
layout->addWidget(button5, 2, 1);
- window->setLayout(layout);
//! [16]
window->setWindowTitle("QGridLayout");
//! [17]
@@ -156,14 +106,13 @@ int main(int argc, char *argv[])
QLineEdit *lineEdit3 = new QLineEdit();
//! [20]
//! [21]
- QFormLayout *layout = new QFormLayout;
+ QFormLayout *layout = new QFormLayout(window);
//! [21]
//! [22]
layout->addRow(button1, lineEdit1);
layout->addRow(button2, lineEdit2);
layout->addRow(button3, lineEdit3);
- window->setLayout(layout);
//! [22]
window->setWindowTitle("QFormLayout");
//! [23]
diff --git a/src/widgets/doc/snippets/mainwindowsnippet.cpp b/src/widgets/doc/snippets/mainwindowsnippet.cpp
index 49363bd366..5608dc96ba 100644
--- a/src/widgets/doc/snippets/mainwindowsnippet.cpp
+++ b/src/widgets/doc/snippets/mainwindowsnippet.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
@@ -88,9 +41,8 @@ void MainWindow::createToolBars()
void MainWindow::createDockWidgets()
{
QWidget *dockWidgetContents = new QWidget;
- QVBoxLayout *layout = new QVBoxLayout;
+ QVBoxLayout *layout = new QVBoxLayout(dockWidgetContents);
layout->addWidget(new QPushButton("My Button."));
- dockWidgetContents->setLayout(layout);
//! [0]
QDockWidget *dockWidget = new QDockWidget(tr("Dock Widget"), this);
diff --git a/src/widgets/doc/snippets/mdiarea/CMakeLists.txt b/src/widgets/doc/snippets/mdiarea/CMakeLists.txt
new file mode 100644
index 0000000000..3edb2d1b36
--- /dev/null
+++ b/src/widgets/doc/snippets/mdiarea/CMakeLists.txt
@@ -0,0 +1,12 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+add_library(widgets_mdiarea_snippets OBJECT
+ mdiareasnippets.cpp
+)
+
+target_link_libraries(widgets_mdiarea_snippets PRIVATE
+ Qt::Core
+ Qt::Gui
+ Qt::Widgets
+)
diff --git a/src/widgets/doc/snippets/mdiarea/mdiareasnippets.cpp b/src/widgets/doc/snippets/mdiarea/mdiareasnippets.cpp
new file mode 100644
index 0000000000..7d455d78eb
--- /dev/null
+++ b/src/widgets/doc/snippets/mdiarea/mdiareasnippets.cpp
@@ -0,0 +1,39 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QtWidgets>
+
+void mainWindowExample()
+{
+ QMdiArea *mdiArea = new QMdiArea;
+//! [0]
+ QMainWindow *mainWindow = new QMainWindow;
+ mainWindow->setCentralWidget(mdiArea);
+//! [0]
+
+ mdiArea->addSubWindow(new QPushButton("Push Me Now!"));
+
+ mainWindow->show();
+}
+
+void addingSubWindowsExample()
+{
+ QWidget *internalWidget1 = new QWidget;
+ QWidget *internalWidget2 = new QWidget;
+
+//! [1]
+ QMdiArea mdiArea;
+ QMdiSubWindow *subWindow1 = new QMdiSubWindow;
+ subWindow1->setWidget(internalWidget1);
+ subWindow1->setAttribute(Qt::WA_DeleteOnClose);
+ mdiArea.addSubWindow(subWindow1);
+
+ QMdiSubWindow *subWindow2 =
+ mdiArea.addSubWindow(internalWidget2);
+
+//! [1]
+ subWindow1->show();
+ subWindow2->show();
+
+ mdiArea.show();
+}
diff --git a/src/widgets/doc/snippets/mdiareasnippets.cpp b/src/widgets/doc/snippets/mdiareasnippets.cpp
deleted file mode 100644
index dec7aaa1e7..0000000000
--- a/src/widgets/doc/snippets/mdiareasnippets.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtWidgets>
-
-void mainWindowExample()
-{
- QMdiArea *mdiArea = new QMdiArea;
-//! [0]
- QMainWindow *mainWindow = new QMainWindow;
- mainWindow->setCentralWidget(mdiArea);
-//! [0]
-
- mdiArea->addSubWindow(new QPushButton("Push Me Now!"));
-
- mainWindow->show();
-}
-
-void addingSubWindowsExample()
-{
- QWidget *internalWidget1 = new QWidget;
- QWidget *internalWidget2 = new QWidget;
-
-//! [1]
- QMdiArea mdiArea;
- QMdiSubWindow *subWindow1 = new QMdiSubWindow;
- subWindow1->setWidget(internalWidget1);
- subWindow1->setAttribute(Qt::WA_DeleteOnClose);
- mdiArea.addSubWindow(subWindow1);
-
- QMdiSubWindow *subWindow2 =
- mdiArea.addSubWindow(internalWidget2);
-
-//! [1]
- subWindow1->show();
- subWindow2->show();
-
- mdiArea.show();
-}
-
-int main(int argv, char **args)
-{
- QApplication app(argv, args);
-
- mainWindowExample();
- //addingSubWindowsExample();
-
- QAction *act = new QAction(qApp);
- act->setShortcut(Qt::ALT + Qt::Key_S);
- act->setShortcutContext( Qt::ApplicationShortcut );
- QObject::connect(act, &QAction::triggered, qApp, &QApplication::aboutQt);
-
- QWidget widget5;
- widget5.show();
- widget5.addAction(act);
-
- return app.exec();
-}
-
-
diff --git a/src/widgets/doc/snippets/myscrollarea.cpp b/src/widgets/doc/snippets/myscrollarea.cpp
deleted file mode 100644
index dbf8da1603..0000000000
--- a/src/widgets/doc/snippets/myscrollarea.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtGui>
-
-class MyScrollArea : public QAbstractScrollArea
-{
-public:
- MyScrollArea(QWidget *w);
- void setWidget(QWidget *w);
-
-protected:
- void scrollContentsBy(int dx, int dy) override;
- void resizeEvent(QResizeEvent *event) override;
-
-private:
- void updateWidgetPosition();
- void updateArea();
-
- QWidget *widget;
-};
-
-MyScrollArea::MyScrollArea(QWidget *widget)
- : QAbstractScrollArea()
-{
- setWidget(widget);
-}
-
-void MyScrollArea::setWidget(QWidget *w)
-{
- widget = w;
- widget->setParent(viewport());
- if (!widget->testAttribute(Qt::WA_Resized))
- widget->resize(widget->sizeHint());
-
- verticalScrollBar()->setValue(0);
- verticalScrollBar()->setValue(0);
-
- updateArea();
-}
-
-void MyScrollArea::updateWidgetPosition()
-{
-//! [0]
- int hvalue = horizontalScrollBar()->value();
- int vvalue = verticalScrollBar()->value();
- QPoint topLeft = viewport()->rect().topLeft();
-
- widget->move(topLeft.x() - hvalue, topLeft.y() - vvalue);
-//! [0]
-}
-
-void MyScrollArea::scrollContentsBy(int /*dx*/, int /*dy*/)
-{
- updateWidgetPosition();
-}
-
-void MyScrollArea::updateArea()
-{
-//! [1]
- QSize areaSize = viewport()->size();
- QSize widgetSize = widget->size();
-
- verticalScrollBar()->setPageStep(areaSize.height());
- horizontalScrollBar()->setPageStep(areaSize.width());
- verticalScrollBar()->setRange(0, widgetSize.height() - areaSize.height());
- horizontalScrollBar()->setRange(0, widgetSize.width() - areaSize.width());
- updateWidgetPosition();
-//! [1]
-}
-
-void MyScrollArea::resizeEvent(QResizeEvent *event)
-{
- updateArea();
-}
-
-int main(int argv, char **args)
-{
- QApplication app(argv, args);
-
- QPixmap pixmap("mypixmap.png");
- QLabel label;
- label.setPixmap(pixmap);
- MyScrollArea area(&label);
- area.resize(300, 300);
- area.show();
-
- area.setWidget(&label);
-
- return app.exec();
-}
diff --git a/src/widgets/doc/snippets/myscrollarea/CMakeLists.txt b/src/widgets/doc/snippets/myscrollarea/CMakeLists.txt
new file mode 100644
index 0000000000..9e7e14dc8d
--- /dev/null
+++ b/src/widgets/doc/snippets/myscrollarea/CMakeLists.txt
@@ -0,0 +1,12 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+add_library(widgets_myscrollarea_snippets OBJECT
+ myscrollarea.cpp
+)
+
+target_link_libraries(widgets_myscrollarea_snippets PRIVATE
+ Qt::Core
+ Qt::Gui
+ Qt::Widgets
+)
diff --git a/src/widgets/doc/snippets/myscrollarea/myscrollarea.cpp b/src/widgets/doc/snippets/myscrollarea/myscrollarea.cpp
new file mode 100644
index 0000000000..85cd1ccce7
--- /dev/null
+++ b/src/widgets/doc/snippets/myscrollarea/myscrollarea.cpp
@@ -0,0 +1,78 @@
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
+
+#include <QtWidgets>
+
+class MyScrollArea : public QAbstractScrollArea
+{
+public:
+ MyScrollArea(QWidget *w);
+ void setWidget(QWidget *w);
+
+protected:
+ void scrollContentsBy(int dx, int dy) override;
+ void resizeEvent(QResizeEvent *event) override;
+
+private:
+ void updateWidgetPosition();
+ void updateArea();
+
+ QWidget *widget;
+};
+
+MyScrollArea::MyScrollArea(QWidget *widget)
+ : QAbstractScrollArea()
+{
+ setWidget(widget);
+}
+
+void MyScrollArea::setWidget(QWidget *w)
+{
+ widget = w;
+ widget->setParent(viewport());
+ if (!widget->testAttribute(Qt::WA_Resized))
+ widget->resize(widget->sizeHint());
+
+ verticalScrollBar()->setValue(0);
+ verticalScrollBar()->setValue(0);
+
+ updateArea();
+}
+
+void MyScrollArea::updateWidgetPosition()
+{
+//! [0]
+ int hvalue = horizontalScrollBar()->value();
+ int vvalue = verticalScrollBar()->value();
+ QPoint topLeft = viewport()->rect().topLeft();
+
+ widget->move(topLeft.x() - hvalue, topLeft.y() - vvalue);
+//! [0]
+}
+
+void MyScrollArea::scrollContentsBy(int dx, int dy)
+{
+ Q_UNUSED(dx);
+ Q_UNUSED(dy);
+ updateWidgetPosition();
+}
+
+void MyScrollArea::updateArea()
+{
+//! [1]
+ QSize areaSize = viewport()->size();
+ QSize widgetSize = widget->size();
+
+ verticalScrollBar()->setPageStep(areaSize.height());
+ horizontalScrollBar()->setPageStep(areaSize.width());
+ verticalScrollBar()->setRange(0, widgetSize.height() - areaSize.height());
+ horizontalScrollBar()->setRange(0, widgetSize.width() - areaSize.width());
+ updateWidgetPosition();
+//! [1]
+}
+
+void MyScrollArea::resizeEvent(QResizeEvent *event)
+{
+ Q_UNUSED(event);
+ updateArea();
+}
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/qlistview-dnd/main.cpp b/src/widgets/doc/snippets/qlistview-dnd/main.cpp
index 49dd7a6930..07d6ff9b10 100644
--- a/src/widgets/doc/snippets/qlistview-dnd/main.cpp
+++ b/src/widgets/doc/snippets/qlistview-dnd/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/qlistview-dnd/mainwindow.cpp b/src/widgets/doc/snippets/qlistview-dnd/mainwindow.cpp
index 45f1eb7aa3..e87df93ebf 100644
--- a/src/widgets/doc/snippets/qlistview-dnd/mainwindow.cpp
+++ b/src/widgets/doc/snippets/qlistview-dnd/mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/qlistview-dnd/mainwindow.h b/src/widgets/doc/snippets/qlistview-dnd/mainwindow.h
index 8b564b7f3e..3177334d56 100644
--- a/src/widgets/doc/snippets/qlistview-dnd/mainwindow.h
+++ b/src/widgets/doc/snippets/qlistview-dnd/mainwindow.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef WINDOW_H
#define WINDOW_H
diff --git a/src/widgets/doc/snippets/qlistview-dnd/model.cpp b/src/widgets/doc/snippets/qlistview-dnd/model.cpp
index 6835479e7a..be2189d1be 100644
--- a/src/widgets/doc/snippets/qlistview-dnd/model.cpp
+++ b/src/widgets/doc/snippets/qlistview-dnd/model.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
model.cpp
@@ -66,7 +19,7 @@ DragDropListModel::DragDropListModel(const QStringList &strings,
//! [0]
bool DragDropListModel::canDropMimeData(const QMimeData *data,
- Qt::DropAction action, int row, int column, const QModelIndex &parent)
+ Qt::DropAction action, int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(action);
Q_UNUSED(row);
@@ -121,7 +74,7 @@ bool DragDropListModel::dropMimeData(const QMimeData *data,
//! [6]
insertRows(beginRow, rows, QModelIndex());
- for (const QString &text : qAsConst(newItems)) {
+ for (const QString &text : std::as_const(newItems)) {
QModelIndex idx = index(beginRow, 0, QModelIndex());
setData(idx, text);
beginRow++;
diff --git a/src/widgets/doc/snippets/qlistview-dnd/model.h b/src/widgets/doc/snippets/qlistview-dnd/model.h
index 3d418dca14..45c442691b 100644
--- a/src/widgets/doc/snippets/qlistview-dnd/model.h
+++ b/src/widgets/doc/snippets/qlistview-dnd/model.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MODEL_H
#define MODEL_H
@@ -59,12 +12,12 @@ class DragDropListModel : public QStringListModel
Q_OBJECT
public:
- DragDropListModel(const QStringList &strings, QObject *parent = 0);
+ DragDropListModel(const QStringList &strings, QObject *parent = nullptr);
Qt::ItemFlags flags(const QModelIndex &index) const override;
bool canDropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent) override;
+ int row, int column, const QModelIndex &parent) const override;
bool dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent) override;
QMimeData *mimeData(const QModelIndexList &indexes) const override;
diff --git a/src/widgets/doc/snippets/qlistview-dnd/qlistview-dnd.pro b/src/widgets/doc/snippets/qlistview-dnd/qlistview-dnd.pro
deleted file mode 100644
index bc2a1f0dce..0000000000
--- a/src/widgets/doc/snippets/qlistview-dnd/qlistview-dnd.pro
+++ /dev/null
@@ -1,6 +0,0 @@
-SOURCES = main.cpp \
- mainwindow.cpp \
- model.cpp
-HEADERS = mainwindow.h \
- model.h
-QT += widgets
diff --git a/src/widgets/doc/snippets/qlistwidget-dnd/main.cpp b/src/widgets/doc/snippets/qlistwidget-dnd/main.cpp
index b08a18b894..a266be0fb9 100644
--- a/src/widgets/doc/snippets/qlistwidget-dnd/main.cpp
+++ b/src/widgets/doc/snippets/qlistwidget-dnd/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
diff --git a/src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.cpp b/src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.cpp
index 70df2b112e..2661416db7 100644
--- a/src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.cpp
+++ b/src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.h b/src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.h
index cb069673d8..59415eb934 100644
--- a/src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.h
+++ b/src/widgets/doc/snippets/qlistwidget-dnd/mainwindow.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef WINDOW_H
#define WINDOW_H
diff --git a/src/widgets/doc/snippets/qlistwidget-dnd/qlistwidget-dnd.pro b/src/widgets/doc/snippets/qlistwidget-dnd/qlistwidget-dnd.pro
deleted file mode 100644
index 12a900a7c6..0000000000
--- a/src/widgets/doc/snippets/qlistwidget-dnd/qlistwidget-dnd.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-SOURCES = main.cpp \
- mainwindow.cpp
-HEADERS = mainwindow.h
diff --git a/src/widgets/doc/snippets/qlistwidget-using/mainwindow.cpp b/src/widgets/doc/snippets/qlistwidget-using/mainwindow.cpp
index 13b20bb856..9fb1b4caee 100644
--- a/src/widgets/doc/snippets/qlistwidget-using/mainwindow.cpp
+++ b/src/widgets/doc/snippets/qlistwidget-using/mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/qmacnativewidget/main.mm b/src/widgets/doc/snippets/qmacnativewidget/main.mm
deleted file mode 100644
index 45e39c4953..0000000000
--- a/src/widgets/doc/snippets/qmacnativewidget/main.mm
+++ /dev/null
@@ -1,94 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtGui/QtGui>
-#include <QtGui/qmacnativewidget_mac.h>
-#import <AppKit/AppKit.h>
-
-int main(int argc, char **argv)
-{
- QApplication app(argc, argv);
-//![0]
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(200, app.desktop()->height() - 200, 239, 200)
- styleMask:NSTitledWindowMask | NSClosableWindowMask
- | NSMiniaturizableWindowMask | NSResizableWindowMask
- backing:NSBackingStoreBuffered defer:NO];
-
- QMacNativeWidget *nativeWidget = new QMacNativeWidget();
- nativeWidget->move(0, 0);
- nativeWidget->setPalette(QPalette(Qt::red));
- nativeWidget->setAutoFillBackground(true);
- QVBoxLayout *layout = new QVBoxLayout();
- QPushButton *pushButton = new QPushButton("An Embedded Qt Button!", nativeWidget);
- pushButton->setAttribute(Qt::WA_LayoutUsesWidgetRect); // Don't use the layout rect calculated from QMacStyle.
- layout->addWidget(pushButton);
- nativeWidget->setLayout(layout);
-
- // Adjust Cocoa layouts
- NSView *nativeWidgetView = reinterpret_cast<NSView *>(nativeWidget->winId());
- NSView *contentView = [window contentView];
- [contentView setAutoresizesSubviews:YES];
- [nativeWidgetView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
- [nativeWidgetView setAutoresizesSubviews:YES];
- NSView *pushButtonView = reinterpret_cast<NSView *>(pushButton->winId());
- [pushButtonView setAutoresizingMask:NSViewWidthSizable];
-
- // Add the nativeWidget to the window.
- [contentView addSubview:nativeWidgetView positioned:NSWindowAbove relativeTo:nil];
- nativeWidget->show();
- pushButton->show();
-
- // Show the window.
- [window makeKeyAndOrderFront:window];
- [pool release];
-//![0]
- return app.exec(); // gives us the same behavior in both
-}
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/qsortfilterproxymodel/main.cpp b/src/widgets/doc/snippets/qsortfilterproxymodel/main.cpp
index 2d4b1023f1..bdd3f08ed4 100644
--- a/src/widgets/doc/snippets/qsortfilterproxymodel/main.cpp
+++ b/src/widgets/doc/snippets/qsortfilterproxymodel/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/qsortfilterproxymodel/qsortfilterproxymodel.pro b/src/widgets/doc/snippets/qsortfilterproxymodel/qsortfilterproxymodel.pro
deleted file mode 100644
index 16181f21cf..0000000000
--- a/src/widgets/doc/snippets/qsortfilterproxymodel/qsortfilterproxymodel.pro
+++ /dev/null
@@ -1 +0,0 @@
-SOURCES = main.cpp
diff --git a/src/widgets/doc/snippets/qsplashscreen/main.cpp b/src/widgets/doc/snippets/qsplashscreen/main.cpp
index 2512035879..afcd9aad9f 100644
--- a/src/widgets/doc/snippets/qsplashscreen/main.cpp
+++ b/src/widgets/doc/snippets/qsplashscreen/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
#include <stdlib.h>
diff --git a/src/widgets/doc/snippets/qstackedlayout/main.cpp b/src/widgets/doc/snippets/qstackedlayout/main.cpp
index 9c61939dee..e436a62fce 100644
--- a/src/widgets/doc/snippets/qstackedlayout/main.cpp
+++ b/src/widgets/doc/snippets/qstackedlayout/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
@@ -74,7 +27,7 @@ Widget::Widget(QWidget *parent)
pageComboBox->addItem(tr("Page 1"));
pageComboBox->addItem(tr("Page 2"));
pageComboBox->addItem(tr("Page 3"));
- connect(pageComboBox, QOverload<int>::of(&QComboBox::activated),
+ connect(pageComboBox, &QComboBox::activated,
stackedLayout, &QStackedLayout::setCurrentIndex);
//! [1]
diff --git a/src/widgets/doc/snippets/qstackedwidget/main.cpp b/src/widgets/doc/snippets/qstackedwidget/main.cpp
index 077c281830..bac2066ee8 100644
--- a/src/widgets/doc/snippets/qstackedwidget/main.cpp
+++ b/src/widgets/doc/snippets/qstackedwidget/main.cpp
@@ -1,59 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
class Widget : public QWidget
{
public:
- Widget(QWidget *parent = 0);
+ Widget(QWidget *parent = nullptr);
};
Widget::Widget(QWidget *parent)
@@ -74,7 +27,7 @@ Widget::Widget(QWidget *parent)
pageComboBox->addItem(tr("Page 1"));
pageComboBox->addItem(tr("Page 2"));
pageComboBox->addItem(tr("Page 3"));
- connect(pageComboBox, QOverload<int>::of(&QComboBox::activated),
+ connect(pageComboBox, &QComboBox::activated,
stackedWidget, &QStackedWidget::setCurrentIndex);
//! [1] //! [2]
diff --git a/src/widgets/doc/snippets/qstyleoption/main.cpp b/src/widgets/doc/snippets/qstyleoption/main.cpp
index 529f88f1d9..28c00c1788 100644
--- a/src/widgets/doc/snippets/qstyleoption/main.cpp
+++ b/src/widgets/doc/snippets/qstyleoption/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
#include <QApplication>
@@ -54,7 +7,7 @@
class MyPushButton : public QPushButton
{
public:
- MyPushButton(QWidget *parent = 0);
+ MyPushButton(QWidget *parent = nullptr);
void paintEvent(QPaintEvent *) override;
};
diff --git a/src/widgets/doc/snippets/qstyleplugin/main.cpp b/src/widgets/doc/snippets/qstyleplugin/main.cpp
index 1c61581572..f4f0ca11c2 100644
--- a/src/widgets/doc/snippets/qstyleplugin/main.cpp
+++ b/src/widgets/doc/snippets/qstyleplugin/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include <QtGui>
@@ -57,7 +10,7 @@ class MyStylePlugin : public QStylePlugin
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QStyleFactoryInterface" FILE "mystyleplugin.json")
public:
- MyStylePlugin(QObject *parent = 0);
+ MyStylePlugin(QObject *parent = nullptr);
QStyle *create(const QString &key) override;
};
@@ -95,7 +48,7 @@ QStyle *MyStylePlugin::create(const QString &key)
} else if (lcKey == "starbuster") {
return new StarBusterStyle;
}
- return 0;
+ return nullptr;
}
//! [1]
diff --git a/src/widgets/doc/snippets/qtablewidget-resizing/mainwindow.cpp b/src/widgets/doc/snippets/qtablewidget-resizing/mainwindow.cpp
index d2c50336f6..9c754af783 100644
--- a/src/widgets/doc/snippets/qtablewidget-resizing/mainwindow.cpp
+++ b/src/widgets/doc/snippets/qtablewidget-resizing/mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/qtablewidget-using/main.cpp b/src/widgets/doc/snippets/qtablewidget-using/main.cpp
index b08a18b894..a266be0fb9 100644
--- a/src/widgets/doc/snippets/qtablewidget-using/main.cpp
+++ b/src/widgets/doc/snippets/qtablewidget-using/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
diff --git a/src/widgets/doc/snippets/qtablewidget-using/mainwindow.cpp b/src/widgets/doc/snippets/qtablewidget-using/mainwindow.cpp
index 47b63b2b3f..76056ab6a0 100644
--- a/src/widgets/doc/snippets/qtablewidget-using/mainwindow.cpp
+++ b/src/widgets/doc/snippets/qtablewidget-using/mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include <math.h>
diff --git a/src/widgets/doc/snippets/qtablewidget-using/mainwindow.h b/src/widgets/doc/snippets/qtablewidget-using/mainwindow.h
index 6bd2d49534..cb2e2aa936 100644
--- a/src/widgets/doc/snippets/qtablewidget-using/mainwindow.h
+++ b/src/widgets/doc/snippets/qtablewidget-using/mainwindow.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef WINDOW_H
#define WINDOW_H
diff --git a/src/widgets/doc/snippets/qtablewidget-using/qtablewidget-using.pro b/src/widgets/doc/snippets/qtablewidget-using/qtablewidget-using.pro
deleted file mode 100644
index ffe134cbb6..0000000000
--- a/src/widgets/doc/snippets/qtablewidget-using/qtablewidget-using.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-SOURCES = main.cpp \
- mainwindow.cpp
-HEADERS = mainwindow.h
-RESOURCES += images.qrc
diff --git a/src/widgets/doc/snippets/qtreewidget-using/mainwindow.cpp b/src/widgets/doc/snippets/qtreewidget-using/mainwindow.cpp
index b9e258cb03..8042f4549a 100644
--- a/src/widgets/doc/snippets/qtreewidget-using/mainwindow.cpp
+++ b/src/widgets/doc/snippets/qtreewidget-using/mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/qtreewidgetitemiterator-using/mainwindow.cpp b/src/widgets/doc/snippets/qtreewidgetitemiterator-using/mainwindow.cpp
index bfe099bbb4..9e32a23326 100644
--- a/src/widgets/doc/snippets/qtreewidgetitemiterator-using/mainwindow.cpp
+++ b/src/widgets/doc/snippets/qtreewidgetitemiterator-using/mainwindow.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
diff --git a/src/widgets/doc/snippets/reading-selections/main.cpp b/src/widgets/doc/snippets/reading-selections/main.cpp
index a6ac4d70df..a87b55f1f7 100644
--- a/src/widgets/doc/snippets/reading-selections/main.cpp
+++ b/src/widgets/doc/snippets/reading-selections/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
main.cpp
diff --git a/src/widgets/doc/snippets/reading-selections/reading-selections.pro b/src/widgets/doc/snippets/reading-selections/reading-selections.pro
deleted file mode 100644
index b9350172f5..0000000000
--- a/src/widgets/doc/snippets/reading-selections/reading-selections.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-QT += widgets
-HEADERS += ../common-table-model/model.h window.h
-SOURCES += main.cpp ../common-table-model/model.cpp window.cpp
-INCLUDEPATH += ../common-table-model
diff --git a/src/widgets/doc/snippets/reading-selections/window.cpp b/src/widgets/doc/snippets/reading-selections/window.cpp
index 045d66a199..fe1a79e331 100644
--- a/src/widgets/doc/snippets/reading-selections/window.cpp
+++ b/src/widgets/doc/snippets/reading-selections/window.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
window.cpp
diff --git a/src/widgets/doc/snippets/reading-selections/window.h b/src/widgets/doc/snippets/reading-selections/window.h
index a3e6cd42b3..a4cdb0cc08 100644
--- a/src/widgets/doc/snippets/reading-selections/window.h
+++ b/src/widgets/doc/snippets/reading-selections/window.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef WINDOW_H
#define WINDOW_H
@@ -61,7 +14,7 @@ class MainWindow : public QMainWindow
{
Q_OBJECT
public:
- MainWindow(QWidget *parent = 0);
+ MainWindow(QWidget *parent = nullptr);
private slots:
void fillSelection();
diff --git a/src/widgets/doc/snippets/shareddirmodel/main.cpp b/src/widgets/doc/snippets/shareddirmodel/main.cpp
index d71b27f459..ed65165e31 100644
--- a/src/widgets/doc/snippets/shareddirmodel/main.cpp
+++ b/src/widgets/doc/snippets/shareddirmodel/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
main.cpp
diff --git a/src/widgets/doc/snippets/sharedtablemodel/main.cpp b/src/widgets/doc/snippets/sharedtablemodel/main.cpp
index 6fa003558f..d9bc7bdd5a 100644
--- a/src/widgets/doc/snippets/sharedtablemodel/main.cpp
+++ b/src/widgets/doc/snippets/sharedtablemodel/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
main.cpp
diff --git a/src/widgets/doc/snippets/sharedtablemodel/sharedtablemodel.pro b/src/widgets/doc/snippets/sharedtablemodel/sharedtablemodel.pro
deleted file mode 100644
index 57f752f0b0..0000000000
--- a/src/widgets/doc/snippets/sharedtablemodel/sharedtablemodel.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-QT += widgets
-HEADERS = ../common-table-model/model.h
-SOURCES = main.cpp \
- ../common-table-model/model.cpp
-INCLUDEPATH += ../common-table-model
diff --git a/src/widgets/doc/snippets/simplemodel-use/main.cpp b/src/widgets/doc/snippets/simplemodel-use/main.cpp
index 940669e101..5a3d6ecce0 100644
--- a/src/widgets/doc/snippets/simplemodel-use/main.cpp
+++ b/src/widgets/doc/snippets/simplemodel-use/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
main.cpp
@@ -54,55 +7,61 @@
A simple example of how to access items from an existing model.
*/
-#include <QtGui>
+#include <QApplication>
+#include <QLabel>
+#include <QVBoxLayout>
+#include <QWidget>
+
+#include <QFileSystemModel>
+#include <QPalette>
+
+#include <QDir>
+#include <QModelIndex>
/*!
Create a default directory model and, using the index-based interface to
the model and some QLabel widgets, populate the window's layout with the
names of objects in the directory.
-
- Note that we only want to read the filenames in the highest level of the
- directory, so we supply a default (invalid) QModelIndex to the model in
- order to indicate that we want top-level items.
*/
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
- QWidget *window = new QWidget;
- QVBoxLayout *layout = new QVBoxLayout(window);
- QLabel *title = new QLabel("Some items from the directory model", window);
+ QWidget window;
+ auto *layout = new QVBoxLayout(&window);
+ auto *title = new QLabel("Some items from the directory model", &window);
title->setBackgroundRole(QPalette::Base);
title->setMargin(8);
layout->addWidget(title);
//! [0]
- QFileSystemModel *model = new QFileSystemModel;
- connect(model, &QFileSystemModel::directoryLoaded, [model](const QString &directory) {
- QModelIndex parentIndex = model->index(directory);
- int numRows = model->rowCount(parentIndex);
- });
- model->setRootPath(QDir::currentPath);
-//! [0]
+ auto *model = new QFileSystemModel;
+ auto onDirectoryLoaded = [model, layout, &window](const QString &directory) {
+ QModelIndex parentIndex = model->index(directory);
+ const int numRows = model->rowCount(parentIndex);
//! [1]
- for (int row = 0; row < numRows; ++row) {
- QModelIndex index = model->index(row, 0, parentIndex);
+ for (int row = 0; row < numRows; ++row) {
+ QModelIndex index = model->index(row, 0, parentIndex);
//! [1]
//! [2]
- QString text = model->data(index, Qt::DisplayRole).toString();
- // Display the text in a widget.
+ QString text = model->data(index, Qt::DisplayRole).toString();
//! [2]
-
- QLabel *label = new QLabel(text, window);
- layout->addWidget(label);
+ // Display the text in a widget.
+ auto *label = new QLabel(text, &window);
+ layout->addWidget(label);
//! [3]
- }
+ }
//! [3]
+ };
+
+ QObject::connect(model, &QFileSystemModel::directoryLoaded, onDirectoryLoaded);
+ model->setRootPath(QDir::currentPath());
+//! [0]
- window->setWindowTitle("A simple model example");
- window->show();
+ window.setWindowTitle("A simple model example");
+ window.show();
return app.exec();
}
diff --git a/src/widgets/doc/snippets/simplemodel-use/simplemodel-use.pro b/src/widgets/doc/snippets/simplemodel-use/simplemodel-use.pro
deleted file mode 100644
index 28dcadcbfa..0000000000
--- a/src/widgets/doc/snippets/simplemodel-use/simplemodel-use.pro
+++ /dev/null
@@ -1 +0,0 @@
-SOURCES += main.cpp
diff --git a/src/widgets/doc/snippets/snippets.pro b/src/widgets/doc/snippets/snippets.pro
new file mode 100644
index 0000000000..6e5c07edf7
--- /dev/null
+++ b/src/widgets/doc/snippets/snippets.pro
@@ -0,0 +1,3 @@
+#! [qmake_use]
+QT += widgets
+#! [qmake_use]
diff --git a/src/widgets/doc/snippets/splitter/splitter.cpp b/src/widgets/doc/snippets/splitter/splitter.cpp
index 0a86f5f759..662ac30eda 100644
--- a/src/widgets/doc/snippets/splitter/splitter.cpp
+++ b/src/widgets/doc/snippets/splitter/splitter.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
@@ -56,7 +9,7 @@ void processSize(int)
int main()
{
- QWidget *parent = 0;
+ QWidget *parent = nullptr;
//! [0]
QSplitter *splitter = new QSplitter(parent);
@@ -84,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/splitterhandle/splitter.cpp b/src/widgets/doc/snippets/splitterhandle/splitter.cpp
index 15d1814b90..b2f4d42071 100644
--- a/src/widgets/doc/snippets/splitterhandle/splitter.cpp
+++ b/src/widgets/doc/snippets/splitterhandle/splitter.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
diff --git a/src/widgets/doc/snippets/splitterhandle/splitter.h b/src/widgets/doc/snippets/splitterhandle/splitter.h
index 8df7bc14a2..d0d945bb52 100644
--- a/src/widgets/doc/snippets/splitterhandle/splitter.h
+++ b/src/widgets/doc/snippets/splitterhandle/splitter.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef SPLITTER_H
#define SPLITTER_H
@@ -61,7 +14,7 @@ class QPaintEvent;
class Splitter : public QSplitter
{
public:
- Splitter(Qt::Orientation orientation, QWidget *parent = 0);
+ Splitter(Qt::Orientation orientation, QWidget *parent = nullptr);
protected:
QSplitterHandle *createHandle() override;
diff --git a/src/widgets/doc/snippets/stringlistmodel/main.cpp b/src/widgets/doc/snippets/stringlistmodel/main.cpp
index 94ea7f00a7..56b5090551 100644
--- a/src/widgets/doc/snippets/stringlistmodel/main.cpp
+++ b/src/widgets/doc/snippets/stringlistmodel/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*!
The main function for the string list model example. This creates and
diff --git a/src/widgets/doc/snippets/stringlistmodel/model.cpp b/src/widgets/doc/snippets/stringlistmodel/model.cpp
index 52e78847d2..74b1aa4b26 100644
--- a/src/widgets/doc/snippets/stringlistmodel/model.cpp
+++ b/src/widgets/doc/snippets/stringlistmodel/model.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
model.cpp
diff --git a/src/widgets/doc/snippets/stringlistmodel/model.h b/src/widgets/doc/snippets/stringlistmodel/model.h
index 7012152b27..fca467a97d 100644
--- a/src/widgets/doc/snippets/stringlistmodel/model.h
+++ b/src/widgets/doc/snippets/stringlistmodel/model.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MODEL_H
#define MODEL_H
diff --git a/src/widgets/doc/snippets/stringlistmodel/stringlistmodel.pro b/src/widgets/doc/snippets/stringlistmodel/stringlistmodel.pro
deleted file mode 100644
index b1126bfe73..0000000000
--- a/src/widgets/doc/snippets/stringlistmodel/stringlistmodel.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-HEADERS = model.h
-SOURCES = main.cpp \
- model.cpp
diff --git a/src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp b/src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp
index e1233a3afd..67dedb147c 100644
--- a/src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp
+++ b/src/widgets/doc/snippets/styles/qcustompixmapstyle.cpp
@@ -1,82 +1,48 @@
-/***************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "qcustompixmapstyle.h"
#include <QtGui>
+using namespace Qt::StringLiterals;
+
//! [0]
QCustomPixmapStyle::QCustomPixmapStyle() :
QPixmapStyle()
{
//! [1]
addDescriptor(PB_Enabled,
- QLatin1String("://button/core_button_inactive.png"),
+ "://button/core_button_inactive.png"_L1,
QMargins(13, 13, 13, 13),
QTileRules(Qt::RepeatTile, Qt::StretchTile));
//! [1]
addDescriptor(PB_Checked,
- QLatin1String("://button/core_button_enabled_selected.png"),
+ "://button/core_button_enabled_selected.png"_L1,
QMargins(13, 13, 13, 13),
QTileRules(Qt::RepeatTile, Qt::StretchTile));
addDescriptor(PB_Pressed,
- QLatin1String("://button/core_button_pressed.png"),
+ "://button/core_button_pressed.png"_L1,
QMargins(13, 13, 13, 13),
QTileRules(Qt::RepeatTile, Qt::StretchTile));
addDescriptor(PB_Disabled,
- QLatin1String("://button/core_button_disabled.png"),
+ "://button/core_button_disabled.png"_L1,
QMargins(13, 13, 13, 13),
QTileRules(Qt::RepeatTile, Qt::StretchTile));
addDescriptor(PB_PressedDisabled,
- QLatin1String("://button/core_button_disabled_selected.png"),
+ "://button/core_button_disabled_selected.png"_L1,
QMargins(13, 13, 13, 13),
QTileRules(Qt::RepeatTile, Qt::StretchTile));
//! [2]
addDescriptor(LE_Enabled,
- QLatin1String("://lineedit/core_textinput_bg.png"),
+ "://lineedit/core_textinput_bg.png"_L1,
QMargins(8, 8, 8, 8));
addDescriptor(LE_Disabled,
- QLatin1String("://lineedit/core_textinput_bg_disabled.png"),
+ "://lineedit/core_textinput_bg_disabled.png"_L1,
QMargins(8, 8, 8, 8));
addDescriptor(LE_Focused,
- QLatin1String("://lineedit/core_textinput_bg_highlight.png"),
+ "://lineedit/core_textinput_bg_highlight.png"_L1,
QMargins(8, 8, 8, 8));
copyDescriptor(LE_Enabled, TE_Enabled);
diff --git a/src/widgets/doc/snippets/styles/styles.cpp b/src/widgets/doc/snippets/styles/styles.cpp
index 77fde0693d..06fa19a89c 100644
--- a/src/widgets/doc/snippets/styles/styles.cpp
+++ b/src/widgets/doc/snippets/styles/styles.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QStyleOption>
#include <QStylePainter>
diff --git a/src/widgets/doc/snippets/stylesheet/common-mistakes.cpp b/src/widgets/doc/snippets/stylesheet/common-mistakes.cpp
index eb6fde482b..b285acebf8 100644
--- a/src/widgets/doc/snippets/stylesheet/common-mistakes.cpp
+++ b/src/widgets/doc/snippets/stylesheet/common-mistakes.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [1]
QPushButton {
diff --git a/src/widgets/doc/snippets/textdocument-imagedrop/textedit.cpp b/src/widgets/doc/snippets/textdocument-imagedrop/textedit.cpp
index efd05c919a..13a869cf67 100644
--- a/src/widgets/doc/snippets/textdocument-imagedrop/textedit.cpp
+++ b/src/widgets/doc/snippets/textdocument-imagedrop/textedit.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "textedit.h"
#include <QtGui>
diff --git a/src/widgets/doc/snippets/timeline/main.cpp b/src/widgets/doc/snippets/timeline/main.cpp
index 4dfa2400d0..f3e1447e40 100644
--- a/src/widgets/doc/snippets/timeline/main.cpp
+++ b/src/widgets/doc/snippets/timeline/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include <math.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/snippets/updating-selections/main.cpp b/src/widgets/doc/snippets/updating-selections/main.cpp
index a6ac4d70df..a87b55f1f7 100644
--- a/src/widgets/doc/snippets/updating-selections/main.cpp
+++ b/src/widgets/doc/snippets/updating-selections/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
main.cpp
diff --git a/src/widgets/doc/snippets/updating-selections/updating-selections.pro b/src/widgets/doc/snippets/updating-selections/updating-selections.pro
deleted file mode 100644
index b9350172f5..0000000000
--- a/src/widgets/doc/snippets/updating-selections/updating-selections.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-QT += widgets
-HEADERS += ../common-table-model/model.h window.h
-SOURCES += main.cpp ../common-table-model/model.cpp window.cpp
-INCLUDEPATH += ../common-table-model
diff --git a/src/widgets/doc/snippets/updating-selections/window.cpp b/src/widgets/doc/snippets/updating-selections/window.cpp
index 26e9b56ae4..b965b81008 100644
--- a/src/widgets/doc/snippets/updating-selections/window.cpp
+++ b/src/widgets/doc/snippets/updating-selections/window.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
/*
window.cpp
@@ -89,7 +42,7 @@ void MainWindow::updateSelection(const QItemSelection &selected,
{
QModelIndexList items = selected.indexes();
- for (const QModelIndex &index : qAsConst(items)) {
+ for (const QModelIndex &index : std::as_const(items)) {
QString text = QString("(%1,%2)").arg(index.row()).arg(index.column());
model->setData(index, text);
//! [0] //! [1]
@@ -99,7 +52,7 @@ void MainWindow::updateSelection(const QItemSelection &selected,
//! [2]
items = deselected.indexes();
- for (const QModelIndex &index : qAsConst(items)) {
+ for (const QModelIndex &index : std::as_const(items)) {
model->setData(index, QString());
}
//! [2]
diff --git a/src/widgets/doc/snippets/updating-selections/window.h b/src/widgets/doc/snippets/updating-selections/window.h
index 0fb9c7eba8..3776453721 100644
--- a/src/widgets/doc/snippets/updating-selections/window.h
+++ b/src/widgets/doc/snippets/updating-selections/window.h
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef WINDOW_H
#define WINDOW_H
@@ -61,7 +14,7 @@ class MainWindow : public QMainWindow
{
Q_OBJECT
public:
- MainWindow(QWidget *parent = 0);
+ MainWindow(QWidget *parent = nullptr);
public slots:
void updateSelection(const QItemSelection &selected,
diff --git a/src/widgets/doc/snippets/whatsthis/whatsthis.cpp b/src/widgets/doc/snippets/whatsthis/whatsthis.cpp
index 8a92c813a0..c0ec07df7c 100644
--- a/src/widgets/doc/snippets/whatsthis/whatsthis.cpp
+++ b/src/widgets/doc/snippets/whatsthis/whatsthis.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
diff --git a/src/widgets/doc/snippets/widget-mask/main.cpp b/src/widgets/doc/snippets/widget-mask/main.cpp
index 519f84f28a..90841bf3da 100644
--- a/src/widgets/doc/snippets/widget-mask/main.cpp
+++ b/src/widgets/doc/snippets/widget-mask/main.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
diff --git a/src/widgets/doc/snippets/widgetdelegate.cpp b/src/widgets/doc/snippets/widgetdelegate.cpp
index 7854a3b278..837fb25917 100644
--- a/src/widgets/doc/snippets/widgetdelegate.cpp
+++ b/src/widgets/doc/snippets/widgetdelegate.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtGui>
diff --git a/src/widgets/doc/snippets/widgets-tutorial/template.cpp b/src/widgets/doc/snippets/widgets-tutorial/template.cpp
index 0e3dc26a63..856c4dbee1 100644
--- a/src/widgets/doc/snippets/widgets-tutorial/template.cpp
+++ b/src/widgets/doc/snippets/widgets-tutorial/template.cpp
@@ -1,52 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, you may use this file under the terms of the BSD license
-** as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in
-** the documentation and/or other materials provided with the
-** distribution.
-** * Neither the name of The Qt Company Ltd nor the names of its
-** contributors may be used to endorse or promote products derived
-** from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [main.cpp body]
#include <QtWidgets>
diff --git a/src/widgets/doc/src/cmake-macros.qdoc b/src/widgets/doc/src/cmake-macros.qdoc
index 36579576a9..13bdcca67b 100644
--- a/src/widgets/doc/src/cmake-macros.qdoc
+++ b/src/widgets/doc/src/cmake-macros.qdoc
@@ -1,50 +1,31 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
-\page qtwidgets-cmake-qt5-wrap-ui.html
+\page qt-wrap-ui.html
\ingroup cmake-macros-qtwidgets
-\title qt5_wrap_ui
+\title qt_wrap_ui
+\keyword qt6_wrap_ui
-\brief Creates sources for \c{.ui} files.
+\summary {Creates sources for .ui files.}
+
+\include cmake-find-package-widgets.qdocinc
\section1 Synopsis
\badcode
-qt5_wrap_ui(<VAR> ui_file1 [ui_file2 ...]
- [OPTIONS ...])
+qt_wrap_ui(<VAR> ui_file1 [ui_file2 ...]
+ [OPTIONS ...])
\endcode
+\versionlessCMakeCommandsNote qt6_wrap_ui()
+
\section1 Description
-Creates rules for calling \l{uic}{User Interface Compiler (uic)} on the given
+Creates rules for calling the \l{uic}{User Interface Compiler (uic)} on the given
\c{.ui} files. For each input file, an header file is generated in the build
-directory. The paths of the generated header files are added to\c{<VAR>}.
+directory. The paths of the generated header files are added to \c{<VAR>}.
\note This is a low-level macro. See the \l{CMake AUTOUIC Documentation} for a
more convenient way to process \c{.ui} files with \c{uic}.
@@ -56,5 +37,5 @@ You can find possible options in the \l{uic}{uic documentation}.
\section1 Examples
-\snippet cmake-macros/examples.cmake qt5_wrap_ui
+\snippet cmake-macros/examples.cmake qt_wrap_ui
*/
diff --git a/src/widgets/doc/src/dontdocument.qdoc b/src/widgets/doc/src/dontdocument.qdoc
index 9de8b5e62d..7e605ede20 100644
--- a/src/widgets/doc/src/dontdocument.qdoc
+++ b/src/widgets/doc/src/dontdocument.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\dontdocument (QTypeInfo QMetaTypeId)
diff --git a/src/widgets/doc/src/external-resources.qdoc b/src/widgets/doc/src/external-resources.qdoc
index 7e60e995a1..17459b6a5b 100644
--- a/src/widgets/doc/src/external-resources.qdoc
+++ b/src/widgets/doc/src/external-resources.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
@@ -35,3 +11,7 @@
\externalpage http://www.nvg.ntnu.no/sinclair/computers/zxspectrum/zxspectrum.htm
\title Sinclair Spectrum
*/
+/*!
+ \externalpage https://www.pearson.com/us/higher-education/program/Gamma-Design-Patterns-Elements-of-Reusable-Object-Oriented-Software/PGM14333.html
+ \title Design Patterns
+*/
diff --git a/src/widgets/doc/src/gestures.qdoc b/src/widgets/doc/src/gestures.qdoc
index 019712fde3..e53b825074 100644
--- a/src/widgets/doc/src/gestures.qdoc
+++ b/src/widgets/doc/src/gestures.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page gestures-overview.html
diff --git a/src/widgets/doc/src/graphicsview.qdoc b/src/widgets/doc/src/graphicsview.qdoc
index 33f480b0bf..81c9f344bb 100644
--- a/src/widgets/doc/src/graphicsview.qdoc
+++ b/src/widgets/doc/src/graphicsview.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page graphicsview.html
@@ -89,7 +65,7 @@
descending stacking order (i.e., the first returned item is topmost,
and the last item is bottom-most).
- \snippet graphicsview.cpp 0
+ \snippet graphicsview/graphicsview.cpp 0
QGraphicsScene's event propagation architecture schedules scene events
for delivery to items, and also manages propagation between items. If
@@ -117,10 +93,10 @@
of a scene. You can attach several views to the same scene, to provide
several viewports into the same data set. The view widget is a scroll
area, and provides scroll bars for navigating through large scenes. To
- enable OpenGL support, you can set a QGLWidget as the viewport by
+ enable OpenGL support, you can set a QOpenGLWidget as the viewport by
calling QGraphicsView::setViewport().
- \snippet graphicsview.cpp 1
+ \snippet graphicsview/graphicsview.cpp 1
The view receives input events from the keyboard and mouse, and
translates these to scene events (converting the coordinates used
@@ -327,7 +303,7 @@
Here is an example of how to implement zoom and rotate slots in a
subclass of QGraphicsView:
- \snippet graphicsview.cpp 2
+ \snippet graphicsview/graphicsview_snippet.cpp 2
The slots could be connected to \l{QToolButton}{QToolButtons} with
\l{QAbstractButton::autoRepeat}{autoRepeat} enabled.
@@ -347,7 +323,7 @@
a QPainter to either of the rendering functions. This example shows
how to print the whole scene into a full page, using QPrinter.
- \snippet graphicsview.cpp 3
+ \snippet graphicsview/graphicsview.cpp 3
The difference between the scene and view rendering functions is that
one operates in scene coordinates, and the other in view coordinates.
@@ -358,7 +334,7 @@
is to render the exact contents of the viewport using the provided
painter.
- \snippet graphicsview.cpp 4
+ \snippet graphicsview/graphicsview.cpp 4
When the source and target areas' sizes do not match, the source
contents are stretched to fit into the target area. By passing a
@@ -384,7 +360,7 @@
so in mousePressEvent() or mouseMoveEvent(), you can get the
originating widget pointer from the event. For example:
- \snippet graphicsview.cpp 5
+ \snippet graphicsview/graphicsview.cpp 5
To intercept drag and drop events for the scene, you reimplement
QGraphicsScene::dragEnterEvent() and whichever event handlers your
@@ -436,14 +412,14 @@
\section2 OpenGL Rendering
- To enable OpenGL rendering, you simply set a new QGLWidget as the
+ To enable OpenGL rendering, you simply set a new QOpenGLWidget as the
viewport of QGraphicsView by calling QGraphicsView::setViewport(). If
- you want OpenGL with antialiasing, you need OpenGL sample buffer
- support (see QGLFormat::sampleBuffers()).
+ you want OpenGL with antialiasing, you need to set a QSurfaceFormat
+ with the needed sample count (see QSurfaceFormat::setSamples()).
Example:
- \snippet graphicsview.cpp 6
+ \snippet graphicsview/graphicsview.cpp 6
\section2 Item Groups
diff --git a/src/widgets/doc/src/guibooks.qdoc b/src/widgets/doc/src/guibooks.qdoc
deleted file mode 100644
index 30ffd0b5ec..0000000000
--- a/src/widgets/doc/src/guibooks.qdoc
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*!
- \page guibooks.html
- \title Books about GUI Design
- \ingroup best-practices
- \brief Some recommended books about GUI design.
-
- This is not a comprehensive list -- there are many other books worth
- buying. Here we mention just a few user interface books that don't
- gather dust on our shelves.
-
- \b{\l{http://www.amazon.com/gp/product/0132354160/ref=ase_trolltech/}{C++
- GUI Programming with Qt 4, Second Edition}}
- by Jasmin Blanchette and Mark
- Summerfield, ISBN 0-13-235416-0. This is the official Qt book written
- by two veteran Qt Developers. The first edition, which is based on Qt 4.1, is
- \l{http://www.qtrac.eu/C++-GUI-Programming-with-Qt-4-1st-ed.zip}{available for free online}.
- The second edition, based on Qt 4.3, is
- \l{http://www.informit.com/store/product.aspx?isbn=0132354160}{available for purchase as an eBook}.
- The book predates QML and only covers widget based user interfaces.
-
- \b{\l{http://www.amazon.com/exec/obidos/ASIN/0385267746/trolltech/t}{The Design of Everyday Things}}
- by Donald Norman, ISBN 0-38526774-6, is one of the classics of human
- interface design. Norman shows how badly something as simple as a
- kitchen stove can be designed, and everyone should read it who will
- design a dialog box, write an error message, or design just about
- anything else humans are supposed to use.
-
- \target fowler
- \b{\l{http://www.amazon.com/exec/obidos/ASIN/0070592748/trolltech/t}{GUI Design Handbook}}
- by Susan Fowler, ISBN 0-07-059274-8, is an
- alphabetical dictionary of widgets and other user interface elements,
- with comprehensive coverage of each. Each chapter covers one widget
- or other element, contains the most important recommendation from the
- \macos, Windows and Motif style guides, notes about common
- problems, comparison with other widgets that can serve some of the
- same roles as this one, etc.
-
- \target Design Patterns
- \b{\l{http://www.amazon.com/exec/obidos/ASIN/0201633612/103-8144203-3273444}
- {Design Patterns - Elements of Reusable Object-Oriented Software}}
- by Gamma, Helm, Johnson, and Vlissides, ISBN 0-201-63361-2, provides
- more information on the Model-View-Controller (MVC) paradigm, explaining
- MVC and its sub-patterns in detail.
-
- \b{\l{http://www.amazon.com/exec/obidos/ASIN/0201622165/trolltech/t}{Macintosh
- Human Interface Guidelines}}, Second Edition, ISBN
- 0-201-62216-5, is worth buying for the \e {don't}s alone. Even
- if you are not writing software for \macos, avoiding most of what it
- advises against will produce more easily comprehensible software.
- Doing what it tells you to do may also help.
-
- \b{\l{http://www.amazon.com/New-Windows-Interface-Microsoft-Press/dp/1556156790/}{The
- Microsoft Windows User Experience}}, ISBN 1-55615-679-0,
- is Microsoft's look and feel bible. Indispensable for everyone who
- has customers that worship Microsoft, and it's quite good, too.
-
- \b{\l{http://www.amazon.com/exec/obidos/ASIN/047159900X/trolltech/t}{The Icon Book}}
- by William Horton, ISBN 0-471-59900-X, is perhaps the only thorough
- coverage of icons and icon use in software. In order for icons to be
- successful, people must be able to do four things with them: decode,
- recognize, find and activate them. This book explains these goals
- from scratch and how to reach them, both with single icons and icon
- families. Some 500 examples are scattered throughout the text.
-
-
- \section1 Buying these Books from Amazon.com
-
- These books are made available in association with Amazon.com, our
- favorite online bookstore. Here is more information about
- \link http://www.amazon.com/exec/obidos/subst/help/shipping-policy.html/t
- Amazon.com's shipping options\endlink and its
- \link http://www.amazon.com/exec/obidos/subst/help/desk.html/t
- customer service.\endlink When you buy a book by following one of these
- links, Amazon.com gives about 15% of the purchase price to
- \link http://www.amnesty.org/ Amnesty International.\endlink
-
-*/
diff --git a/src/widgets/doc/src/includes/cmake-find-package-widgets.qdocinc b/src/widgets/doc/src/includes/cmake-find-package-widgets.qdocinc
new file mode 100644
index 0000000000..3911ee80b6
--- /dev/null
+++ b/src/widgets/doc/src/includes/cmake-find-package-widgets.qdocinc
@@ -0,0 +1,5 @@
+The command is defined in the \c Widgets component of the \c Qt6 package. Load the package with:
+
+\code
+find_package(Qt6 REQUIRED COMPONENTS Widgets)
+\endcode
diff --git a/src/widgets/doc/src/model-view-programming.qdoc b/src/widgets/doc/src/model-view-programming.qdoc
index ede1ebf932..5461619a4d 100644
--- a/src/widgets/doc/src/model-view-programming.qdoc
+++ b/src/widgets/doc/src/model-view-programming.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page model-view-programming.html
\ingroup qt-basic-concepts
@@ -473,11 +449,13 @@
\snippet simplemodel-use/main.cpp 0
In this case, we start by setting up a default QFileSystemModel. We connect
- it to a lambda, in which we will obtain a parent index using a specific
+ its signal \c directoryLoaded(QString) to a lambda, in which we will
+ obtain a parent index for the directory using a specific
implementation of \l{QFileSystemModel::}{index()} provided by that model.
- In the lambda, we count the number of rows in the model using the
- \l{QFileSystemModel::}{rowCount()} function. Finally, we set the root path
- of the QFileSystemModel so it starts loading data and triggers the lambda.
+
+ In the lambda, we determine the number of rows in the model using the
+ \l{QFileSystemModel::}{rowCount()} function.
+
For simplicity, we are only interested in the items in the first column
of the model. We examine each row in turn, obtaining a model index for
@@ -498,6 +476,9 @@
\codeline
\snippet simplemodel-use/main.cpp 3
+ Finally, we set the root path of the QFileSystemModel so it starts
+ loading data and triggers the lambda.
+
The above example demonstrates the basic principles used to retrieve
data from a model:
@@ -705,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
@@ -740,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.
@@ -760,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
@@ -784,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
@@ -797,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.
@@ -808,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
@@ -828,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
@@ -1837,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
@@ -2332,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 1c0bb5195a..7dd7503d29 100644
--- a/src/widgets/doc/src/modelview.qdoc
+++ b/src/widgets/doc/src/modelview.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page modelview.html
@@ -493,8 +469,7 @@
\li QStandardItemModel
\li Stores arbitrary hierarchical items
\row
- \li QFileSystemModel\br
- QDirModel
+ \li QFileSystemModel
\li Encapsulate the local file system
\row
\li QSqlQueryModel
@@ -536,7 +511,7 @@
{
Q_OBJECT
public:
- StarDelegate(QWidget *parent = 0);
+ StarDelegate(QWidget *parent = nullptr);
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option,
@@ -559,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}
@@ -627,12 +602,6 @@
\li
\li Book 1, Chapter 10, Figure 10.6
\row
- \li Directory Viewer
- \li QTreeView
- \li QDirModel
- \li
- \li Book 1, Chapter 10, Figure 10.7
- \row
\li Color Names
\li QListView
\li QSortFilterProxyModel
@@ -667,14 +636,6 @@
\li Book 1, Chapter 10, Figure 10.15
\row
- \li Four directory views
- \li QListView
- QTableView
- QTreeView
- \li QDirModel
- \li Demonstrates the use of multiple views
- \li Book2, Chapter 8.2
- \row
\li Address Book
\li QListView
QTableView
@@ -866,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
new file mode 100644
index 0000000000..c4d757fe6d
--- /dev/null
+++ b/src/widgets/doc/src/qt6-changes.qdoc
@@ -0,0 +1,113 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
+
+/*!
+ \page widgets-changes-qt6.html
+ \title Changes to Qt Widgets
+ \ingroup changes-qt-5-to-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.
+
+ We try to maintain binary and source compatibility for all the public
+ APIs in each release. But some changes were inevitable in an effort to
+ make Qt a better framework.
+
+ In this topic we summarize those changes in Qt Widgets, and provide
+ guidance to handle them.
+
+ \section1 Kernel classes
+
+ \section2 The QWidget class
+
+ The virtual QWidget::enterEvent() handler now receives a QEnterEvent*
+ parameter which has information about the pointer position, rather than
+ a plain QEvent*.
+
+ \section2 QDesktopWidget and QApplication::desktop()
+
+ QDesktopWidget was already deprecated in Qt 5, and has been removed in
+ Qt 6, together with QApplication::desktop().
+
+ QScreen provides equivalent functionality to query for information about
+ available screens, screen that form a virtual desktop, and screen
+ geometries.
+
+ Use QWidget::setScreen() to create a QWidget on a specific display;
+ note that this does not move a widget to a screen in a virtual desktop
+ setup.
+
+ \section2 QAction, QActionGroup
+
+ These classes have been moved into the QtGui module. Member functions that
+ depend on types defined in QtWidgets (such as QAction::menu() and
+ QAction::setMenu()) are implemented as templates that will be instantiated
+ only when called.
+
+ \section1 Widgets
+
+ \section2 The QAbstractButton class
+
+ The default timeout parameter for QAbstractButton::animateClick() is
+ removed to allow modern connection syntax without the need for qOverload.
+
+ \section2 The QComboBox class
+
+ The QComboBox::setModel() function is now virtual.
+
+ \section2 The QDateTimeEdit class
+
+ When QDateTimeEdit::setDateTime() is called with a date-time whose
+ time-spec doesn't match that of the QDateTimeEdit instance, the
+ date-time is converted to the time-spec of the QDateTimeEdit. This
+ gives a date-time that describes the same instant in time, but
+ does so in the same terms as the QDateTimeEdit uses. Previously,
+ the date and time from the passed date-time were combined with the
+ time-spec of the widget, ignoring the time-spec of the date-time;
+ this could describe a different point in time than the one
+ described by the date-time passed.
+
+ \section1 ItemViews
+
+ \section2 The QAbstractItemView class
+
+ The virtual viewOptions() method that previously returned a QStyleOptionViewItem
+ object has been renamed to initViewItemOption, and initializes a
+ QStyleOptionViewItem object that's passed in through a pointer.
+
+ \section1 Styling Classes and related APIs
+
+ All versioned QStyleOption subclasses are consolidated, and the version
+ numbers are reset to 1.
+
+ The various initStyleOption() methods in widget classes are now virtual.
+
+ \section2 Style sheet changes
+
+ Styling a widget by its property in Qt 5 vs Qt 6 is different, especially if the
+ property is an enum. In Qt 5, the selector value for such a property is the integer
+ equivalent of the enum value, while in Qt 6 the string value is used. The following
+ example demonstrates this difference:
+
+ \code
+ // Qt 5 style sheet
+ QToolButton[popupMode="1"] {
+ padding-right: 20px;
+ }
+ \endcode
+
+ \code
+ // Qt 6 style sheet
+ QToolButton[popupMode=MenuButtonPopup] {
+ padding-right: 20px;
+ }
+ \endcode
+
+ \section1 Utility Classes
+
+ \section2 QUndoCommand, QUndoStack, and QUndoGroup
+
+ The widget independent classes of the Undo/Redo framework have been moved
+ into the QtGui module.
+*/
diff --git a/src/widgets/doc/src/qtwidgets-examples.qdoc b/src/widgets/doc/src/qtwidgets-examples.qdoc
index 979e0589b8..d1daa843f8 100644
--- a/src/widgets/doc/src/qtwidgets-examples.qdoc
+++ b/src/widgets/doc/src/qtwidgets-examples.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\title Qt Widgets Examples
diff --git a/src/widgets/doc/src/qtwidgets-index.qdoc b/src/widgets/doc/src/qtwidgets-index.qdoc
index 1a23d172dd..3894467ccf 100644
--- a/src/widgets/doc/src/qtwidgets-index.qdoc
+++ b/src/widgets/doc/src/qtwidgets-index.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page qtwidgets-index.html
@@ -35,21 +11,6 @@ interfaces
elements to create classic desktop-style user interfaces. See the
\l {User Interfaces} overview for more information on using widgets.
-\section1 Getting Started
-
- To include the definitions of the module's classes, use the
- following directive:
-
- \snippet code/doc_src_qtwidgets.cpp 1
-
- To link against the module, add this line to your \l qmake \c
- .pro file:
-
- \snippet code/doc_src_qtwidgets.pro 0
-
-
-
-
\section1 Widgets
Widgets are the primary elements for creating user interfaces in Qt.
@@ -61,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}
@@ -88,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
@@ -106,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.
@@ -128,35 +89,36 @@ interfaces
\image graphicsview-items.png
- \section1 Licenses
+ \section1 Using the Module
- The Qt Widgets module is available under commercial licenses from \l{The Qt Company}.
- In addition, it is available under free software licenses. Since Qt 5.4,
- these free software licenses are
- \l{GNU Lesser General Public License, version 3}, or
- the \l{GNU General Public License, version 2}.
- See \l{Qt Licensing} for further details.
+ \include {module-use.qdocinc} {using the c++ api}
+
+ \section2 Building with CMake
- \section1 Related Information
+ \include {module-use.qdocinc} {building with cmake} {Widgets}
+
+ \section2 Building with qmake
+
+ \include {module-use.qdocinc} {building_with_qmake} {widgets}
+
+ \section1 Articles and Guides
- \section2 Tutorials
\list
\li \l{Widgets Tutorial}
\li \l{Getting Started Programming with Qt Widgets}
\li \l{Creating a Qt Widget Based Application}
-
-
\li \l{Model/View Tutorial}
\endlist
- \section2 Examples
+ \section1 Examples
+
\list
\li \l{Qt Widgets Examples}
\li \l{Layout Examples}
+ \li \l{Tools Examples}
\endlist
\section1 API Reference
- These are links to the API reference materials.
\list
\li \l{Qt Widgets C++ Classes}
@@ -174,4 +136,16 @@ interfaces
\li \l{Qt Style Sheets Reference}
\endlist
+ \section1 Module Evolution
+
+ \l{Changes to Qt Widgets} lists important changes in the module API
+ and functionality that were done for the Qt 6 series of Qt.
+
+ \section1 Licenses
+
+ The Qt Widgets module is available under commercial licenses from \l{The Qt Company}.
+ In addition, it is available under free software licenses:
+ The \l{GNU Lesser General Public License, version 3}, or
+ the \l{GNU General Public License, version 2}.
+ See \l{Qt Licensing} for further details.
*/
diff --git a/src/widgets/doc/src/qtwidgets.qdoc b/src/widgets/doc/src/qtwidgets.qdoc
index 72ba22681c..b72eb72d9b 100644
--- a/src/widgets/doc/src/qtwidgets.qdoc
+++ b/src/widgets/doc/src/qtwidgets.qdoc
@@ -1,48 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\module QtWidgets
\title Qt Widgets C++ Classes
\ingroup modules
+ \qtcmakepackage Widgets
\qtvariable widgets
\brief The Qt Widgets module extends Qt GUI with C++ widget functionality.
- To include the definitions of the module's classes, use the
- following directive:
-
- \snippet code/doc_src_qtwidgets.cpp 1
-
- \if !defined(qtforpython)
- To link against the module, add this line to your \l qmake \c
- .pro file:
-
- \snippet code/doc_src_qtwidgets.pro 0
- \endif
+ The \l{Qt Widgets} page contains information about how to use the module.
*/
diff --git a/src/widgets/doc/src/widgets-and-layouts/focus.qdoc b/src/widgets/doc/src/widgets-and-layouts/focus.qdoc
index 9ce3c8472f..b49fc89993 100644
--- a/src/widgets/doc/src/widgets-and-layouts/focus.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/focus.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page focus.html
@@ -33,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
@@ -46,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
@@ -78,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
@@ -87,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:
@@ -150,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 a82462a432..822cf1efff 100644
--- a/src/widgets/doc/src/widgets-and-layouts/gallery.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/gallery.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page gallery.html
@@ -35,25 +11,22 @@
The widgets examples show how some of the widgets available in Qt might
appear when configured to use the a particular style. Each style is only
- available on the respective platfom, and provides native look and feel by
+ available on the respective platform, and provides native look and feel by
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 ("macintosh") 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 e42e6d42ec..5f1d5a7ea9 100644
--- a/src/widgets/doc/src/widgets-and-layouts/layout.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/layout.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page layout.html
\title Layout Management
@@ -33,7 +9,6 @@
layouts.
\previouspage Qt Widgets
- \contentspage Qt Widgets
\nextpage {Styles and Style Aware Widgets}{Styles}
\ingroup frameworks-technologies
@@ -73,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.
@@ -288,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
@@ -300,7 +275,7 @@
\list
\li A data structure to store the items handled by the layout. Each
item is a \l{QLayoutItem}{QLayoutItem}. We will use a
- QVector in this example.
+ QList in this example.
\li \l{QLayout::}{addItem()}, how to add items to the layout.
\li \l{QLayout::}{setGeometry()}, how to perform the layout.
\li \l{QLayout::}{sizeHint()}, the preferred size of the layout.
diff --git a/src/widgets/doc/src/widgets-and-layouts/styles.qdoc b/src/widgets/doc/src/widgets-and-layouts/styles.qdoc
index faaf4e5479..62e433814b 100644
--- a/src/widgets/doc/src/widgets-and-layouts/styles.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/styles.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page style-reference.html
\title Styles and Style Aware Widgets
@@ -780,7 +756,7 @@
\li Set if the widget has focus (see
QWidget::hasFocus())
\row
- \li \c State_KeyobordFocusChange
+ \li \c State_KeyboardFocusChange
\li Set when the user changes focus with the keyboard
(see Qt::WA_KeyboardFocusChange)
\row
@@ -888,7 +864,7 @@
\li Button is not flat and not pressed down
\endtable
- Other members of QStyleOptionButton is:
+ Other members of QStyleOptionButton are:
\table 90%
\header
@@ -941,7 +917,7 @@
\endtable
See \l{Push Buttons} for a table over other members in the
- QStyleOptionButtonClass.
+ QStyleOptionButton class.
\section3 Tabs
@@ -969,7 +945,7 @@
\image javastyle/tab.png
The dotted lines indicate that the QTabWidget contains a tab bar,
- but does not draw it itself. QTabBar only draws its base line
+ but does not draw the tab bar itself. QTabBar only draws its base line
when not part of a tab widget, and it keeps two tool
buttons that scroll the bar when all tabs do not fit; see \l{Tool
Buttons} for their element tree. Also note that since the buttons
@@ -1761,7 +1737,7 @@
\li maxIconWidth
\li The maximum width allowed for the icon.
\row
- \li menuHasChecableItem
+ \li menuHasCheckableItems
\li Boolean which is \c true if at least one item in the
menu is checkable.
\row
diff --git a/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc b/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
index 35bad6786a..05000024e1 100644
--- a/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page stylesheet.html
@@ -35,7 +11,6 @@
\ingroup qt-gui-concepts
\previouspage {Styles and Style Aware Widgets}{Styles}
- \contentspage Widgets and Layouts
\nextpage The Style Sheet Syntax
\keyword style sheet
@@ -53,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}
@@ -100,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}.
@@ -110,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
@@ -139,9 +99,8 @@
/*!
\page stylesheet-syntax.html
- \contentspage {Qt Style Sheets}{Contents}
\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
@@ -521,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
@@ -539,7 +507,7 @@
the QObject::className() returns <namespace>::<classname>. This conflicts
with the syntax for \l{Sub-Controls}. To overcome this problem,
when using the Type Selector for widgets inside namespaces, we must
- replace the "::" with "--". For example,
+ replace the \c{::} with \c{--}. For example,
\snippet code/doc_src_stylesheet.cpp 27
@@ -551,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
@@ -562,25 +530,24 @@
/*!
\page stylesheet-designer.html
- \contentspage {Qt Style Sheets}{Contents}
\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
@@ -588,8 +555,7 @@
/*!
\page stylesheet-customizing.html
- \contentspage {Qt Style Sheets}{Contents}
- \previouspage Qt Designer Integration
+ \previouspage Qt Widgets Designer Integration
\nextpage Qt Style Sheets Reference
\title Customizing Qt Widgets Using Style Sheets
@@ -692,7 +658,6 @@
/*!
\page stylesheet-reference.html
- \contentspage {Qt Style Sheets}{Contents}
\previouspage Customizing Qt Widgets Using Style Sheets
\nextpage Qt Style Sheets Examples
\title Qt Style Sheets Reference
@@ -716,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
@@ -725,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.
@@ -735,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.
@@ -753,14 +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.
@@ -789,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
@@ -817,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},
@@ -849,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.
@@ -861,54 +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 Support the \l{box model}.
-
+ \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.
@@ -918,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.
@@ -975,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
@@ -1014,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 contraints for the slider depending on the orientation.
-
+ 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.
@@ -1066,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.
@@ -1092,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,
@@ -1101,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,
@@ -1110,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.
@@ -1118,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.
@@ -1128,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).
@@ -1175,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.
@@ -1194,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.
@@ -1225,12 +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.
@@ -1241,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
@@ -1293,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},
@@ -1306,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).
@@ -1317,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.
@@ -1350,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
@@ -1364,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
@@ -1394,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.
@@ -1428,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.
@@ -1448,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
@@ -1461,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
@@ -1474,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.
@@ -1487,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.
@@ -1511,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
@@ -1533,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.
@@ -1550,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.
@@ -1604,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.
@@ -1642,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.
@@ -1668,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,
@@ -1712,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.
@@ -1755,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}}.
@@ -1796,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
@@ -1815,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.
@@ -1834,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.
@@ -1866,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.
@@ -1883,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
@@ -1929,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.
@@ -1948,24 +2175,30 @@
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.
- \note It's the application's responsibilty to assign an icon to a
+ \note It's the application's responsibility to assign an icon to a
button (using the QAbstractButton API), and not the style's. So be
careful setting it unless your stylesheet is targeting a specific
application.
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.
@@ -1980,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
@@ -2008,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.
@@ -2035,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
@@ -2048,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.
@@ -2087,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,
@@ -2127,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,
@@ -2147,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
@@ -2163,16 +2427,19 @@
\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,
QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu,
QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox,
- QSplitter, QStatusBar, QTextEdit, and QToolTip.
+ QSplitter, QStatusBar, QTextEdit, QToolButton, and QToolTip.
If this property is not specified, the minimum height is
derived based on the widget's contents and the style.
@@ -2184,18 +2451,24 @@
\snippet code/doc_src_stylesheet.qdoc 66
+ \note Setting this property might allow widgets to shrink
+ smaller than the space required for the contents.
+
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,
QComboBox, QFrame, QGroupBox, QLabel, QLineEdit, QMenu,
QMenuBar, QPushButton, QRadioButton, QSizeGrip, QSpinBox,
- QSplitter, QStatusBar, QTextEdit, and QToolTip.
+ QSplitter, QStatusBar, QTextEdit, QToolButton, and QToolTip.
If this property is not specified, the minimum width is
derived based on the widget's contents and the style.
@@ -2207,12 +2480,18 @@
\snippet code/doc_src_stylesheet.qdoc 67
+ \note Setting this property might allow widgets to shrink
+ smaller than the space required for the contents.
+
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}.
@@ -2224,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.
@@ -2294,38 +2584,69 @@
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 position} \target position-prop
- \li \c relative \br
- | \c absolute
- \li Whether offsets specified using \l{Qt Style Sheets Reference#left-prop}{left},
+ \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}
+ role.
+
+ Example:
+
+ \snippet code/doc_src_stylesheet.qdoc 163
+
+ Available since 6.5.
+
+ \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.
@@ -2333,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}}.
@@ -2353,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.
@@ -2372,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.
@@ -2392,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
@@ -2407,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.
@@ -2425,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
@@ -2441,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}.
@@ -2458,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.
@@ -2495,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.
@@ -2524,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.
@@ -2543,8 +2907,25 @@
See also \l{#height-prop}{height}.
+
+ \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.
+
+ \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.
+
+
\target list of icons
\section1 List of Icons
@@ -2711,6 +3092,10 @@
\li QStyle::SP_DirHomeIcon
\row
+ \li lineedit-clear-button-icon
+ \li QStyle::SP_LineEditClearButton
+
+ \row
\li leftarrow-icon
\li QStyle::SP_ArrowLeft
@@ -2910,7 +3295,7 @@
| \tt{hsl(\e{h}, \e{s}, \e{l})} \br
| \tt{hsla(\e{h}, \e{s}, \e{l}, \e{a})} \br
| \tt{#\e{rrggbb}} \br
- | \l{QColor::setNamedColor()}{Color Name} \br
+ | \l{QColor::fromString()}{Color Name} \br
\li Specifies a color as RGB (red, green, blue), RGBA (red,
green, blue, alpha), HSV (hue, saturation, value), HSVA
(hue, saturation, value, alpha), HSL (hue, saturation,
@@ -3010,8 +3395,9 @@
\list
\li \c px: pixels
\li \c pt: the size of one point (i.e., 1/72 of an inch)
- \li \c em: the em width of the font (i.e., the width of 'M')
- \li \c ex: the ex width of the font (i.e., the height of 'x')
+ \li \c em: the size relative to the font size of the element
+ (e.g., 2em means 2 times the size of the font)
+ \li \c ex: the x-height of the font (i.e., the height of 'x')
\endlist
However, Qt is limited to font sizes in \c pt and \c px and any other
@@ -3046,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
@@ -3494,7 +3881,6 @@
/*!
\page stylesheet-examples.html
- \contentspage {Qt Style Sheets}{Contents}
\previouspage Qt Style Sheets Reference
\title Qt Style Sheets Examples
@@ -3924,8 +4310,10 @@
\image tabWidget-stylesheet2.png
For a tab widget that looks like above, we make use of
- \l{http://www.communitymx.com/content/article.cfm?cid=B0029}
- {negative margins}. The resulting stylesheet looks like this:
+ \l{https://doc.qt.io/qt-5/stylesheet-customizing.html#the-box-model}
+ {negative margins}. Negative values draw the element closer to its
+ neighbors than it would be by default. The resulting stylesheet
+ looks like this:
\snippet code/doc_src_stylesheet.qdoc 146
@@ -4046,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-and-layouts/widgets.qdoc b/src/widgets/doc/src/widgets-and-layouts/widgets.qdoc
index 3b134a3f96..7ec226b396 100644
--- a/src/widgets/doc/src/widgets-and-layouts/widgets.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/widgets.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page widget-classes.html
diff --git a/src/widgets/doc/src/widgets-tutorial.qdoc b/src/widgets/doc/src/widgets-tutorial.qdoc
index d7b68a6f67..e0ad4d850c 100644
--- a/src/widgets/doc/src/widgets-tutorial.qdoc
+++ b/src/widgets/doc/src/widgets-tutorial.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page widgets-tutorial.html
@@ -74,7 +50,7 @@
\section1 Simple Widget Examples
- Each of theses simple widget examples is written entirely within
+ Each of these simple widget examples is written entirely within
the \c main() function.
\list
@@ -125,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
@@ -151,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
@@ -173,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
@@ -207,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
@@ -235,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/dialogs.qdoc b/src/widgets/doc/src/windows-and-dialogs/dialogs.qdoc
index 81bc6dd279..4bd86e9f36 100644
--- a/src/widgets/doc/src/windows-and-dialogs/dialogs.qdoc
+++ b/src/widgets/doc/src/windows-and-dialogs/dialogs.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\group standard-dialogs
@@ -39,7 +15,6 @@
\brief An overview over dialog windows.
\previouspage Application Main Window
- \contentspage Application Windows and Dialogs
\nextpage Desktop Integration
Dialogs can be \e{modal}, in which case the user is required to provide
diff --git a/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc b/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
index 9935c3ca7f..6b0315f10a 100644
--- a/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
+++ b/src/widgets/doc/src/windows-and-dialogs/mainwindow.qdoc
@@ -1,47 +1,25 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page application-windows.html
\title Window and Dialog Widgets
\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
@@ -51,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
@@ -61,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!
@@ -83,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
@@ -123,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
@@ -139,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).
*/
/*!
@@ -152,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
@@ -163,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
@@ -181,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
@@ -196,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
@@ -210,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
@@ -227,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:
@@ -236,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:
@@ -249,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/effects.pri b/src/widgets/effects/effects.pri
deleted file mode 100644
index a21f941866..0000000000
--- a/src/widgets/effects/effects.pri
+++ /dev/null
@@ -1,6 +0,0 @@
-HEADERS += effects/qgraphicseffect.h \
- effects/qgraphicseffect_p.h \
- effects/qpixmapfilter_p.h
-
-SOURCES += effects/qgraphicseffect.cpp \
- effects/qpixmapfilter.cpp
diff --git a/src/widgets/effects/qgraphicseffect.cpp b/src/widgets/effects/qgraphicseffect.cpp
index 2eb74ce2a8..43e7d952e7 100644
--- a/src/widgets/effects/qgraphicseffect.cpp
+++ b/src/widgets/effects/qgraphicseffect.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsEffect
@@ -86,7 +50,7 @@
any other existing effects) and reimplement the virtual function draw().
This function is called whenever the effect needs to redraw. The draw()
function takes the painter with which to draw as an argument. For more
- information, refer to the documenation for draw(). In the draw() function
+ information, refer to the documentation for draw(). In the draw() function
you can call sourcePixmap() to get a pixmap of the graphics effect source
which you can then process.
@@ -750,7 +714,7 @@ void QGraphicsColorizeEffect::draw(QPainter *painter)
at the potential cost of lower performance.
\value AnimationHint Indicates that the blur radius is going to be animated, hinting
- that the implementation can keep a cache of blurred verisons of the source.
+ that the implementation can keep a cache of blurred versions of the source.
Do not use this hint if the source is going to be dynamically changing.
\sa blurHints(), setBlurHints()
diff --git a/src/widgets/effects/qgraphicseffect.h b/src/widgets/effects/qgraphicseffect.h
index f7c0769778..0077e6266a 100644
--- a/src/widgets/effects/qgraphicseffect.h
+++ b/src/widgets/effects/qgraphicseffect.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSEFFECT_H
#define QGRAPHICSEFFECT_H
@@ -163,7 +127,7 @@ public:
QualityHint = 0x01,
AnimationHint = 0x02
};
- Q_FLAG(BlurHint)
+ Q_ENUM(BlurHint)
Q_DECLARE_FLAGS(BlurHints, BlurHint)
Q_FLAG(BlurHints)
diff --git a/src/widgets/effects/qgraphicseffect_p.h b/src/widgets/effects/qgraphicseffect_p.h
index 7e342a9f3c..378258148c 100644
--- a/src/widgets/effects/qgraphicseffect_p.h
+++ b/src/widgets/effects/qgraphicseffect_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSEFFECT_P_H
#define QGRAPHICSEFFECT_P_H
@@ -157,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 1f899c2660..fc3ea8bba3 100644
--- a/src/widgets/effects/qpixmapfilter.cpp
+++ b/src/widgets/effects/qpixmapfilter.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <qglobal.h>
@@ -51,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>
@@ -353,17 +316,17 @@ static void convolute(
int kernely = -kernelHeight/2;
int starty = 0;
int endy = kernelHeight;
- if(yk+kernely+endy >= srcImage.height())
+ if (yk+kernely+endy >= srcImage.height())
endy = kernelHeight-((yk+kernely+endy)-srcImage.height())-1;
- if(yk+kernely < 0)
+ if (yk+kernely < 0)
starty = -(yk+kernely);
int kernelx = -kernelWidth/2;
int startx = 0;
int endx = kernelWidth;
- if(xk+kernelx+endx >= srcImage.width())
+ if (xk+kernelx+endx >= srcImage.width())
endx = kernelWidth-((xk+kernelx+endx)-srcImage.width())-1;
- if(xk+kernelx < 0)
+ if (xk+kernelx < 0)
startx = -(xk+kernelx);
for (int ys = starty; ys < endy; ys ++) {
@@ -385,7 +348,7 @@ static void convolute(
b = qBound((int)0, b >> 16, (int)255);
a = qBound((int)0, a >> 16, (int)255);
// composition mode checking could be moved outside of loop
- if(mode == QPainter::CompositionMode_Source) {
+ if (mode == QPainter::CompositionMode_Source) {
uint color = (a<<24)+(r<<16)+(g<<8)+b;
*output++ = color;
} else {
@@ -399,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++;
}
@@ -416,7 +379,7 @@ void QPixmapConvolutionFilter::draw(QPainter *painter, const QPointF &p, const Q
if (!painter->isActive())
return;
- if(d->kernelWidth<=0 || d->kernelHeight <= 0)
+ if (d->kernelWidth<=0 || d->kernelHeight <= 0)
return;
if (src.isNull())
@@ -591,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.devicePixelRatioF());
- 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.devicePixelRatioF());
-
- const uchar *src = reinterpret_cast<const uchar*>(const_cast<const QImage &>(srcImage).bits());
- int sx = srcImage.bytesPerLine();
- int sx2 = sx << 1;
-
- uchar *dst = reinterpret_cast<uchar*>(dest.bits());
- int 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.devicePixelRatioF());
-
- const uchar *src = reinterpret_cast<const uchar*>(const_cast<const QImage &>(srcImage).bits());
- int sx = srcImage.bytesPerLine();
- int sx2 = sx << 1;
-
- uchar *dst = reinterpret_cast<uchar*>(dest.bits());
- int 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.devicePixelRatioF());
-
- const quint32 *src = reinterpret_cast<const quint32*>(const_cast<const QImage &>(srcImage).bits());
- int sx = srcImage.bytesPerLine() >> 2;
- int sx2 = sx << 1;
-
- quint32 *dst = reinterpret_cast<quint32*>(dest.bits());
- int 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.size() / blurImage.devicePixelRatioF()), 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
*/
@@ -1032,8 +691,6 @@ QPixmapColorizeFilter::QPixmapColorizeFilter(QObject *parent)
*/
QPixmapColorizeFilter::~QPixmapColorizeFilter()
{
- // was inline until Qt 5.6, so essentially
- // must stay empty until ### Qt 6
}
/*!
@@ -1116,7 +773,7 @@ void QPixmapColorizeFilter::draw(QPainter *painter, const QPointF &dest, const Q
srcImage = std::move(srcImage).convertToFormat(format);
destImage = QImage(rect.size(), srcImage.format());
}
- destImage.setDevicePixelRatio(src.devicePixelRatioF());
+ destImage.setDevicePixelRatio(src.devicePixelRatio());
// do colorizing
QPainter destPainter(&destImage);
@@ -1325,7 +982,7 @@ void QPixmapDropShadowFilter::draw(QPainter *p,
return;
QImage tmp(px.size(), QImage::Format_ARGB32_Premultiplied);
- tmp.setDevicePixelRatio(px.devicePixelRatioF());
+ tmp.setDevicePixelRatio(px.devicePixelRatio());
tmp.fill(0);
QPainter tmpPainter(&tmp);
tmpPainter.setCompositionMode(QPainter::CompositionMode_Source);
@@ -1334,7 +991,7 @@ void QPixmapDropShadowFilter::draw(QPainter *p,
// blur the alpha channel
QImage blurred(tmp.size(), QImage::Format_ARGB32_Premultiplied);
- blurred.setDevicePixelRatio(px.devicePixelRatioF());
+ blurred.setDevicePixelRatio(px.devicePixelRatio());
blurred.fill(0);
QPainter blurPainter(&blurred);
qt_blurImage(&blurPainter, tmp, d->radius, false, true);
diff --git a/src/widgets/effects/qpixmapfilter_p.h b/src/widgets/effects/qpixmapfilter_p.h
index c56acb8a24..f5c0528c8a 100644
--- a/src/widgets/effects/qpixmapfilter_p.h
+++ b/src/widgets/effects/qpixmapfilter_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPIXMAPFILTER_H
#define QPIXMAPFILTER_H
@@ -109,7 +73,6 @@ public:
void draw(QPainter *painter, const QPointF &dest, const QPixmap &src, const QRectF &srcRect = QRectF()) const override;
private:
- friend class QGLPixmapConvolutionFilter;
friend class QVGPixmapConvolutionFilter;
const qreal *convolutionKernel() const;
int rows() const;
@@ -135,9 +98,6 @@ public:
QRectF boundingRectFor(const QRectF &rect) const override;
void draw(QPainter *painter, const QPointF &dest, const QPixmap &src, const QRectF &srcRect = QRectF()) const override;
-
-private:
- friend class QGLPixmapBlurFilter;
};
class QPixmapColorizeFilterPrivate;
diff --git a/src/widgets/graphicsview/graphicsview.pri b/src/widgets/graphicsview/graphicsview.pri
deleted file mode 100644
index d69a6f5c3f..0000000000
--- a/src/widgets/graphicsview/graphicsview.pri
+++ /dev/null
@@ -1,61 +0,0 @@
-# Qt graphicsview module
-
-qtConfig(graphicsview) {
-HEADERS += graphicsview/qgraphicsgridlayout.h \
- graphicsview/qgraphicsitem.h \
- graphicsview/qgraphicsitem_p.h \
- graphicsview/qgraphicslayout.h \
- graphicsview/qgraphicslayout_p.h \
- graphicsview/qgraphicslayoutitem.h \
- graphicsview/qgraphicslayoutitem_p.h \
- graphicsview/qgraphicslinearlayout.h \
- graphicsview/qgraphicsproxywidget.h \
- graphicsview/qgraphicsproxywidget_p.h \
- graphicsview/qgraphicsscene.h \
- graphicsview/qgraphicsscene_bsp_p.h \
- graphicsview/qgraphicsscene_p.h \
- graphicsview/qgraphicsscenebsptreeindex_p.h \
- graphicsview/qgraphicssceneevent.h \
- graphicsview/qgraphicssceneindex_p.h \
- graphicsview/qgraphicsscenelinearindex_p.h \
- graphicsview/qgraphicstransform.h \
- graphicsview/qgraphicstransform_p.h \
- graphicsview/qgraphicsview.h \
- graphicsview/qgraphicsview_p.h \
- graphicsview/qgraphicswidget.h \
- graphicsview/qgraphicswidget_p.h \
- graphicsview/qgraphicslayoutstyleinfo_p.h \
- graphicsview/qgraphicsgridlayoutengine_p.h \
- graphicsview/qgraph_p.h \
- graphicsview/qsimplex_p.h \
- graphicsview/qgraphicsanchorlayout_p.h \
- graphicsview/qgraphicsanchorlayout.h
-
-SOURCES += graphicsview/qgraphicsgridlayout.cpp \
- graphicsview/qgraphicsitem.cpp \
- graphicsview/qgraphicslayout.cpp \
- graphicsview/qgraphicslayout_p.cpp \
- graphicsview/qgraphicslayoutitem.cpp \
- graphicsview/qgraphicslinearlayout.cpp \
- graphicsview/qgraphicsproxywidget.cpp \
- graphicsview/qgraphicsscene.cpp \
- graphicsview/qgraphicsscene_bsp.cpp \
- graphicsview/qgraphicsscenebsptreeindex.cpp \
- graphicsview/qgraphicssceneevent.cpp \
- graphicsview/qgraphicssceneindex.cpp \
- graphicsview/qgraphicsscenelinearindex.cpp \
- graphicsview/qgraphicstransform.cpp \
- graphicsview/qgraphicsview.cpp \
- graphicsview/qgraphicswidget.cpp \
- graphicsview/qgraphicswidget_p.cpp \
- graphicsview/qgraphicslayoutstyleinfo.cpp \
- graphicsview/qgraphicsgridlayoutengine.cpp \
- graphicsview/qsimplex_p.cpp \
- graphicsview/qgraphicsanchorlayout_p.cpp \
- graphicsview/qgraphicsanchorlayout.cpp
-
- qtConfig(easingcurve) {
- HEADERS += graphicsview/qgraphicsitemanimation.h
- SOURCES += graphicsview/qgraphicsitemanimation.cpp
- }
-}
diff --git a/src/widgets/graphicsview/qgraph_p.h b/src/widgets/graphicsview/qgraph_p.h
index dfe9d8fdd3..10c742d42e 100644
--- a/src/widgets/graphicsview/qgraph_p.h
+++ b/src/widgets/graphicsview/qgraph_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPH_P_H
#define QGRAPH_P_H
@@ -56,6 +20,7 @@
#include <QtCore/QQueue>
#include <QtCore/QString>
#include <QtCore/QDebug>
+#include <QtCore/QSet>
#include <functional> // for std::less
@@ -214,8 +179,9 @@ public:
return setOfVertices;
}
- QVector<QPair<Vertex*, Vertex*> > connections() const {
- QVector<QPair<Vertex*, Vertex*> > conns;
+ QList<QPair<Vertex *, Vertex *>> connections() const
+ {
+ QList<QPair<Vertex *, Vertex *>> conns;
for (const_iterator it = constBegin(); it != constEnd(); ++it) {
Vertex *from = it.from();
Vertex *to = it.to();
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout.cpp b/src/widgets/graphicsview/qgraphicsanchorlayout.cpp
index 4f1855a606..4cb7165f37 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout.cpp
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsAnchorLayout
@@ -234,12 +198,12 @@ QGraphicsAnchorLayout::~QGraphicsAnchorLayout()
}
}
- d->removeCenterConstraints(this, QGraphicsAnchorLayoutPrivate::Horizontal);
- d->removeCenterConstraints(this, QGraphicsAnchorLayoutPrivate::Vertical);
+ d->removeCenterConstraints(this, Qt::Horizontal);
+ d->removeCenterConstraints(this, Qt::Vertical);
d->deleteLayoutEdges();
- Q_ASSERT(d->itemCenterConstraints[0].isEmpty());
- Q_ASSERT(d->itemCenterConstraints[1].isEmpty());
+ Q_ASSERT(d->itemCenterConstraints[Qt::Horizontal].isEmpty());
+ Q_ASSERT(d->itemCenterConstraints[Qt::Vertical].isEmpty());
Q_ASSERT(d->items.isEmpty());
Q_ASSERT(d->m_vertexList.isEmpty());
}
@@ -372,7 +336,7 @@ void QGraphicsAnchorLayout::setHorizontalSpacing(qreal spacing)
{
Q_D(QGraphicsAnchorLayout);
- d->spacings[0] = spacing;
+ d->spacings[Qt::Horizontal] = spacing;
invalidate();
}
@@ -385,7 +349,7 @@ void QGraphicsAnchorLayout::setVerticalSpacing(qreal spacing)
{
Q_D(QGraphicsAnchorLayout);
- d->spacings[1] = spacing;
+ d->spacings[Qt::Vertical] = spacing;
invalidate();
}
@@ -404,7 +368,7 @@ void QGraphicsAnchorLayout::setSpacing(qreal spacing)
{
Q_D(QGraphicsAnchorLayout);
- d->spacings[0] = d->spacings[1] = spacing;
+ d->spacings = {spacing, spacing};
invalidate();
}
@@ -438,8 +402,8 @@ void QGraphicsAnchorLayout::setGeometry(const QRectF &geom)
Q_D(QGraphicsAnchorLayout);
QGraphicsLayout::setGeometry(geom);
- d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Horizontal);
- d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Vertical);
+ d->calculateVertexPositions(Qt::Horizontal);
+ d->calculateVertexPositions(Qt::Vertical);
d->setItemsGeometries(geom);
}
@@ -460,8 +424,8 @@ void QGraphicsAnchorLayout::removeAt(int index)
return;
// Removing an item affects both horizontal and vertical graphs
- d->removeCenterConstraints(item, QGraphicsAnchorLayoutPrivate::Horizontal);
- d->removeCenterConstraints(item, QGraphicsAnchorLayoutPrivate::Vertical);
+ d->removeCenterConstraints(item, Qt::Horizontal);
+ d->removeCenterConstraints(item, Qt::Vertical);
d->removeAnchors(item);
d->items.remove(index);
@@ -518,9 +482,8 @@ QSizeF QGraphicsAnchorLayout::sizeHint(Qt::SizeHint which, const QSizeF &constra
const_cast<QGraphicsAnchorLayoutPrivate *>(d)->calculateGraphs();
// ### apply constraint!
- QSizeF engineSizeHint(
- d->sizeHints[QGraphicsAnchorLayoutPrivate::Horizontal][which],
- d->sizeHints[QGraphicsAnchorLayoutPrivate::Vertical][which]);
+ QSizeF engineSizeHint{d->sizeHints[Qt::Horizontal][which],
+ d->sizeHints[Qt::Vertical][which]};
qreal left, top, right, bottom;
getContentsMargins(&left, &top, &right, &bottom);
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout.h b/src/widgets/graphicsview/qgraphicsanchorlayout.h
index 9bea43dd8e..5ddbd83e13 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout.h
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSANCHORLAYOUT_H
#define QGRAPHICSANCHORLAYOUT_H
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
index af0ee3d38c..8a5280d44c 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
@@ -1,47 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgraphicsanchorlayout_p.h"
#include <QtWidgets/qwidget.h>
#include <QtWidgets/qapplication.h>
-#include <QtCore/qlinkedlist.h>
#include <QtCore/qstack.h>
#ifdef QT_DEBUG
@@ -52,6 +15,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
// To ensure that all variables inside the simplex solver are non-negative,
// we limit the size of anchors in the interval [-limit, limit]. Then before
// sending them to the simplex solver we add "limit" as an offset, so that
@@ -194,7 +159,7 @@ void AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo)
maxPrefSize = maxSize;
return;
} else {
- if (orientation == QGraphicsAnchorLayoutPrivate::Horizontal) {
+ if (!isVertical) {
policy = item->sizePolicy().horizontalPolicy();
minSizeHint = item->effectiveSizeHint(Qt::MinimumSize).width();
prefSizeHint = item->effectiveSizeHint(Qt::PreferredSize).width();
@@ -226,9 +191,9 @@ void AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo)
if (anchorPrivate->hasSize) {
// Anchor has user-defined size
prefSizeHint = anchorPrivate->preferredSize;
- } else {
+ } else if (styleInfo) {
// Fetch size information from style
- const Qt::Orientation orient = Qt::Orientation(QGraphicsAnchorLayoutPrivate::edgeOrientation(from->m_edge) + 1);
+ const Qt::Orientation orient = QGraphicsAnchorLayoutPrivate::edgeOrientation(from->m_edge);
qreal s = styleInfo->defaultSpacing(orient);
if (s < 0) {
QSizePolicy::ControlType controlTypeFrom = from->m_item->sizePolicy().controlType();
@@ -242,6 +207,8 @@ void AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo)
s = 0;
}
prefSizeHint = s;
+ } else {
+ prefSizeHint = 0;
}
}
@@ -492,9 +459,7 @@ void SequentialAnchorData::updateChildrenSizes()
// "from" or "to", that _contains_ one of them.
AnchorVertex *prev = from;
- for (int i = 0; i < m_edges.count(); ++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,
@@ -529,9 +494,7 @@ void SequentialAnchorData::calculateSizeHints()
AnchorVertex *prev = from;
- for (int i = 0; i < m_edges.count(); ++i) {
- AnchorData *edge = m_edges.at(i);
-
+ for (AnchorData *edge : m_edges) {
const bool edgeIsForward = (edge->from == prev);
if (edgeIsForward) {
minSize += edge->minSize;
@@ -565,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, "");
}
@@ -608,7 +569,9 @@ QSimplexConstraint *GraphPath::constraint(const GraphPath &path) const
#ifdef QT_DEBUG
QString GraphPath::toString() const
{
- QString string(QLatin1String("Path: "));
+ QString string;
+ string += "Path: "_L1;
+
for (AnchorData *edge : positives)
string += QString::fromLatin1(" (+++) %1").arg(edge->toString());
@@ -622,19 +585,6 @@ QString GraphPath::toString() const
QGraphicsAnchorLayoutPrivate::QGraphicsAnchorLayoutPrivate()
: calculateGraphCacheDirty(true), styleInfoDirty(true)
{
- for (int i = 0; i < NOrientations; ++i) {
- for (int j = 0; j < 3; ++j) {
- sizeHints[i][j] = -1;
- }
- interpolationProgress[i] = -1;
-
- spacings[i] = -1;
- graphHasConflicts[i] = false;
-
- layoutFirstVertex[i] = nullptr;
- layoutCentralVertex[i] = nullptr;
- layoutLastVertex[i] = nullptr;
- }
}
Qt::AnchorPoint QGraphicsAnchorLayoutPrivate::oppositeEdge(Qt::AnchorPoint edge)
@@ -674,7 +624,7 @@ Qt::AnchorPoint QGraphicsAnchorLayoutPrivate::oppositeEdge(Qt::AnchorPoint edge)
*/
AnchorData *QGraphicsAnchorLayoutPrivate::addAnchorMaybeParallel(AnchorData *newAnchor, bool *feasible)
{
- Orientation orientation = Orientation(newAnchor->orientation);
+ const Qt::Orientation orientation = newAnchor->isVertical ? Qt::Vertical : Qt::Horizontal;
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
*feasible = true;
@@ -710,7 +660,7 @@ AnchorData *QGraphicsAnchorLayoutPrivate::addAnchorMaybeParallel(AnchorData *new
parallel->isCenterAnchor = true;
- for (int j = 0; j < constraints.count(); ++j) {
+ for (int j = 0; j < constraints.size(); ++j) {
QSimplexConstraint *c = constraints[j];
if (c->variables.contains(child)) {
childConstraints->append(c);
@@ -742,10 +692,8 @@ AnchorData *QGraphicsAnchorLayoutPrivate::addAnchorMaybeParallel(AnchorData *new
Note that this function doesn't add the created anchor to the graph. This should be done by
the caller.
*/
-static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph,
- AnchorVertex *before,
- const QVector<AnchorVertex*> &vertices,
- AnchorVertex *after)
+static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph, AnchorVertex *before,
+ const QList<AnchorVertex *> &vertices, AnchorVertex *after)
{
#if defined(QT_DEBUG) && 0
QString strVertices;
@@ -757,10 +705,10 @@ static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph,
#endif
AnchorVertex *prev = before;
- QVector<AnchorData *> edges;
- edges.reserve(vertices.count() + 1);
+ QList<AnchorData *> edges;
+ edges.reserve(vertices.size() + 1);
- const int numVertices = vertices.count();
+ const int numVertices = vertices.size();
edges.reserve(numVertices + 1);
// Take from the graph, the edges that will be simplificated
for (int i = 0; i < numVertices; ++i) {
@@ -823,7 +771,7 @@ static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph,
When creating the parallel anchors, the algorithm might identify unfeasible situations. In this
case the simplification process stops and returns \c false. Otherwise returns \c true.
*/
-bool QGraphicsAnchorLayoutPrivate::simplifyGraph(Orientation orientation)
+bool QGraphicsAnchorLayoutPrivate::simplifyGraph(Qt::Orientation orientation)
{
if (items.isEmpty())
return true;
@@ -880,13 +828,13 @@ static AnchorVertex *replaceVertex_helper(AnchorData *data, AnchorVertex *oldV,
return other;
}
-bool QGraphicsAnchorLayoutPrivate::replaceVertex(Orientation orientation, AnchorVertex *oldV,
+bool QGraphicsAnchorLayoutPrivate::replaceVertex(Qt::Orientation orientation, AnchorVertex *oldV,
AnchorVertex *newV, const QList<AnchorData *> &edges)
{
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
bool feasible = true;
- for (int i = 0; i < edges.count(); ++i) {
+ for (int i = 0; i < edges.size(); ++i) {
AnchorData *ad = edges[i];
AnchorVertex *otherV = replaceVertex_helper(ad, oldV, newV);
@@ -914,7 +862,7 @@ bool QGraphicsAnchorLayoutPrivate::replaceVertex(Orientation orientation, Anchor
/*!
\internal
*/
-bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Orientation orientation)
+bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Qt::Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
@@ -934,7 +882,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Orientation orientation)
QList<AnchorVertex *> adjacents = g.adjacentVertices(v);
int index = 0;
- while (index < adjacents.count()) {
+ while (index < adjacents.size()) {
AnchorVertex *next = adjacents.at(index);
index++;
@@ -954,7 +902,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Orientation orientation)
const QList<AnchorVertex *> &vAdjacents = g.adjacentVertices(v);
const QList<AnchorVertex *> &nextAdjacents = g.adjacentVertices(next);
- for (int i = 0; i < vAdjacents.count(); ++i) {
+ for (int i = 0; i < vAdjacents.size(); ++i) {
AnchorVertex *adjacent = vAdjacents.at(i);
if (adjacent != next) {
AnchorData *ad = g.edgeData(v, adjacent);
@@ -962,7 +910,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Orientation orientation)
}
}
- for (int i = 0; i < nextAdjacents.count(); ++i) {
+ for (int i = 0; i < nextAdjacents.size(); ++i) {
AnchorVertex *adjacent = nextAdjacents.at(i);
if (adjacent != v) {
AnchorData *ad = g.edgeData(next, adjacent);
@@ -1027,7 +975,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Orientation orientation)
Note that there are some catches to this that are not covered by the above explanation, see
the function comments for more details.
*/
-bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutPrivate::Orientation orientation,
+bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(Qt::Orientation orientation,
bool *feasible)
{
Q_Q(QGraphicsAnchorLayout);
@@ -1036,7 +984,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP
QSet<AnchorVertex *> visited;
QStack<QPair<AnchorVertex *, AnchorVertex *> > stack;
stack.push(qMakePair(static_cast<AnchorVertex *>(nullptr), layoutFirstVertex[orientation]));
- QVector<AnchorVertex*> candidates;
+ QList<AnchorVertex *> candidates;
// Walk depth-first, in the stack we store start of the candidate sequence (beforeSequence)
// and the vertex to be visited.
@@ -1065,7 +1013,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP
//
// Identifies cases (a) and (b)
- endOfSequence = isLayoutVertex || adjacents.count() != 2;
+ endOfSequence = isLayoutVertex || adjacents.size() != 2;
if (!endOfSequence) {
// This is a tricky part. We peek at the next vertex to find out whether
@@ -1107,7 +1055,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP
//
// Add next non-visited vertices to the stack.
//
- for (int i = 0; i < adjacents.count(); ++i) {
+ for (int i = 0; i < adjacents.size(); ++i) {
AnchorVertex *next = adjacents.at(i);
if (visited.contains(next))
continue;
@@ -1146,7 +1094,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP
const AnchorData *lastAnchor = g.edgeData(candidates.constLast(), afterSequence);
if (lastAnchor->isCenterAnchor) {
afterSequence = candidates.constLast();
- candidates.remove(candidates.count() - 1);
+ candidates.remove(candidates.size() - 1);
if (candidates.isEmpty())
continue;
@@ -1185,6 +1133,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP
void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge)
{
+ const Qt::Orientation orientation = edge->isVertical ? Qt::Vertical : Qt::Horizontal;
#if 0
static const char *anchortypes[] = {"Normal",
"Sequential",
@@ -1192,18 +1141,16 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge)
qDebug("Restoring %s edge.", anchortypes[int(edge->type)]);
#endif
- Graph<AnchorVertex, AnchorData> &g = graph[edge->orientation];
+ Graph<AnchorVertex, AnchorData> &g = graph[orientation];
if (edge->type == AnchorData::Normal) {
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.count(); ++i) {
- AnchorData *data = sequence->m_edges.at(i);
+ for (AnchorData *data : sequence->m_edges)
restoreSimplifiedAnchor(data);
- }
delete sequence;
@@ -1212,7 +1159,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge)
// Skip parallel anchors that were created by vertex simplification, they will be processed
// later, when restoring vertex simplification.
// ### we could improve this check bit having a bit inside 'edge'
- if (anchorsFromSimplifiedVertices[edge->orientation].contains(edge))
+ if (anchorsFromSimplifiedVertices[orientation].contains(edge))
return;
ParallelAnchorData* parallel = static_cast<ParallelAnchorData*>(edge);
@@ -1235,7 +1182,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorDa
if (!parallel->isCenterAnchor)
return;
- for (int i = 0; i < parallel->m_firstConstraints.count(); ++i) {
+ for (int i = 0; i < parallel->m_firstConstraints.size(); ++i) {
QSimplexConstraint *c = parallel->m_firstConstraints.at(i);
qreal v = c->variables[parallel];
c->variables.remove(parallel);
@@ -1246,7 +1193,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorDa
// addAnchorMaybeParallel().
const bool needsReverse = !parallel->secondForward();
- for (int i = 0; i < parallel->m_secondConstraints.count(); ++i) {
+ for (int i = 0; i < parallel->m_secondConstraints.size(); ++i) {
QSimplexConstraint *c = parallel->m_secondConstraints.at(i);
qreal v = c->variables[parallel];
if (needsReverse)
@@ -1256,7 +1203,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorDa
}
}
-void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Qt::Orientation orientation)
{
#if 0
qDebug("Restoring Simplified Graph for %s",
@@ -1265,8 +1212,8 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Orientation orientatio
// Restore anchor simplification
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- QVector<QPair<AnchorVertex*, AnchorVertex*> > connections = g.connections();
- for (int i = 0; i < connections.count(); ++i) {
+ QList<QPair<AnchorVertex *, AnchorVertex *>> connections = g.connections();
+ for (int i = 0; i < connections.size(); ++i) {
AnchorVertex *v1 = connections.at(i).first;
AnchorVertex *v2 = connections.at(i).second;
AnchorData *edge = g.edgeData(v1, v2);
@@ -1285,7 +1232,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Orientation orientatio
restoreVertices(orientation);
}
-void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::restoreVertices(Qt::Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
@@ -1302,14 +1249,14 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
// In the next step, we'll change the anchors vertices so that would not be possible anymore.
QList<AnchorData *> &parallelAnchors = anchorsFromSimplifiedVertices[orientation];
- for (int i = parallelAnchors.count() - 1; i >= 0; --i) {
+ for (int i = parallelAnchors.size() - 1; i >= 0; --i) {
ParallelAnchorData *parallel = static_cast<ParallelAnchorData *>(parallelAnchors.at(i));
restoreSimplifiedConstraints(parallel);
}
// Then, we will restore the vertices in the inverse order of creation, this way we ensure that
// the vertex being restored was not wrapped by another simplification.
- for (int i = toRestore.count() - 1; i >= 0; --i) {
+ for (int i = toRestore.size() - 1; i >= 0; --i) {
AnchorVertexPair *pair = toRestore.at(i);
QList<AnchorVertex *> adjacents = g.adjacentVertices(pair);
@@ -1320,7 +1267,7 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
g.createEdge(first, second, pair->m_removedAnchor);
// Restore the anchors for the first child vertex
- for (int j = 0; j < pair->m_firstAnchors.count(); ++j) {
+ for (int j = 0; j < pair->m_firstAnchors.size(); ++j) {
AnchorData *ad = pair->m_firstAnchors.at(j);
Q_ASSERT(ad->from == pair || ad->to == pair);
@@ -1329,7 +1276,7 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
}
// Restore the anchors for the second child vertex
- for (int j = 0; j < pair->m_secondAnchors.count(); ++j) {
+ for (int j = 0; j < pair->m_secondAnchors.size(); ++j) {
AnchorData *ad = pair->m_secondAnchors.at(j);
Q_ASSERT(ad->from == pair || ad->to == pair);
@@ -1337,7 +1284,7 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
g.createEdge(ad->from, ad->to, ad);
}
- for (int j = 0; j < adjacents.count(); ++j) {
+ for (int j = 0; j < adjacents.size(); ++j) {
g.takeEdge(pair, adjacents.at(j));
}
@@ -1356,10 +1303,10 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
toRestore.clear();
}
-QGraphicsAnchorLayoutPrivate::Orientation
-QGraphicsAnchorLayoutPrivate::edgeOrientation(Qt::AnchorPoint edge)
+Qt::Orientation
+QGraphicsAnchorLayoutPrivate::edgeOrientation(Qt::AnchorPoint edge) noexcept
{
- return edge > Qt::AnchorRight ? Vertical : Horizontal;
+ return edge > Qt::AnchorRight ? Qt::Vertical : Qt::Horizontal;
}
/*!
@@ -1383,9 +1330,9 @@ void QGraphicsAnchorLayoutPrivate::createLayoutEdges()
data->maxSize = QWIDGETSIZE_MAX;
// Save a reference to layout vertices
- layoutFirstVertex[Horizontal] = internalVertex(layout, Qt::AnchorLeft);
- layoutCentralVertex[Horizontal] = nullptr;
- layoutLastVertex[Horizontal] = internalVertex(layout, Qt::AnchorRight);
+ layoutFirstVertex[Qt::Horizontal] = internalVertex(layout, Qt::AnchorLeft);
+ layoutCentralVertex[Qt::Horizontal] = nullptr;
+ layoutLastVertex[Qt::Horizontal] = internalVertex(layout, Qt::AnchorRight);
// Vertical
data = new AnchorData;
@@ -1394,9 +1341,9 @@ void QGraphicsAnchorLayoutPrivate::createLayoutEdges()
data->maxSize = QWIDGETSIZE_MAX;
// Save a reference to layout vertices
- layoutFirstVertex[Vertical] = internalVertex(layout, Qt::AnchorTop);
- layoutCentralVertex[Vertical] = nullptr;
- layoutLastVertex[Vertical] = internalVertex(layout, Qt::AnchorBottom);
+ layoutFirstVertex[Qt::Vertical] = internalVertex(layout, Qt::AnchorTop);
+ layoutCentralVertex[Qt::Vertical] = nullptr;
+ layoutLastVertex[Qt::Vertical] = internalVertex(layout, Qt::AnchorBottom);
}
void QGraphicsAnchorLayoutPrivate::deleteLayoutEdges()
@@ -1443,13 +1390,13 @@ void QGraphicsAnchorLayoutPrivate::createCenterAnchors(
{
Q_Q(QGraphicsAnchorLayout);
- Orientation orientation;
+ Qt::Orientation orientation;
switch (centerEdge) {
case Qt::AnchorHorizontalCenter:
- orientation = Horizontal;
+ orientation = Qt::Horizontal;
break;
case Qt::AnchorVerticalCenter:
- orientation = Vertical;
+ orientation = Qt::Vertical;
break;
default:
// Don't create center edges unless needed
@@ -1464,7 +1411,7 @@ void QGraphicsAnchorLayoutPrivate::createCenterAnchors(
Qt::AnchorPoint firstEdge;
Qt::AnchorPoint lastEdge;
- if (orientation == Horizontal) {
+ if (orientation == Qt::Horizontal) {
firstEdge = Qt::AnchorLeft;
lastEdge = Qt::AnchorRight;
} else {
@@ -1509,13 +1456,13 @@ void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
{
Q_Q(QGraphicsAnchorLayout);
- Orientation orientation;
+ Qt::Orientation orientation;
switch (centerEdge) {
case Qt::AnchorHorizontalCenter:
- orientation = Horizontal;
+ orientation = Qt::Horizontal;
break;
case Qt::AnchorVerticalCenter:
- orientation = Vertical;
+ orientation = Qt::Vertical;
break;
default:
// Don't remove edges that not the center ones
@@ -1526,7 +1473,7 @@ void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
Qt::AnchorPoint firstEdge;
Qt::AnchorPoint lastEdge;
- if (orientation == Horizontal) {
+ if (orientation == Qt::Horizontal) {
firstEdge = Qt::AnchorLeft;
lastEdge = Qt::AnchorRight;
} else {
@@ -1547,7 +1494,7 @@ void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
AnchorData *oldData = g.edgeData(first, center);
// Remove center constraint
- for (int i = itemCenterConstraints[orientation].count() - 1; i >= 0; --i) {
+ for (int i = itemCenterConstraints[orientation].size() - 1; i >= 0; --i) {
if (itemCenterConstraints[orientation].at(i)->variables.contains(oldData)) {
delete itemCenterConstraints[orientation].takeAt(i);
break;
@@ -1568,7 +1515,7 @@ void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
// this is only called from removeAnchors()
// first, remove all non-internal anchors
QList<AnchorVertex*> adjacents = g.adjacentVertices(center);
- for (int i = 0; i < adjacents.count(); ++i) {
+ for (int i = 0; i < adjacents.size(); ++i) {
AnchorVertex *v = adjacents.at(i);
if (v->m_item != item) {
removeAnchor_helper(center, internalVertex(v->m_item, v->m_edge));
@@ -1587,17 +1534,17 @@ void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
void QGraphicsAnchorLayoutPrivate::removeCenterConstraints(QGraphicsLayoutItem *item,
- Orientation orientation)
+ Qt::Orientation orientation)
{
// Remove the item center constraints associated to this item
// ### This is a temporary solution. We should probably use a better
// data structure to hold items and/or their associated constraints
// so that we can remove those easily
- AnchorVertex *first = internalVertex(item, orientation == Horizontal ?
+ AnchorVertex *first = internalVertex(item, orientation == Qt::Horizontal ?
Qt::AnchorLeft :
Qt::AnchorTop);
- AnchorVertex *center = internalVertex(item, orientation == Horizontal ?
+ AnchorVertex *center = internalVertex(item, orientation == Qt::Horizontal ?
Qt::AnchorHorizontalCenter :
Qt::AnchorVerticalCenter);
@@ -1703,7 +1650,7 @@ QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::addAnchor(QGraphicsLayoutItem *fi
// Right ? 0 0
if (firstItem == q
|| secondItem == q
- || pickEdge(firstEdge, Horizontal) == Qt::AnchorHorizontalCenter
+ || pickEdge(firstEdge, Qt::Horizontal) == Qt::AnchorHorizontalCenter
|| oppositeEdge(firstEdge) != secondEdge) {
graphicsAnchor->setSpacing(0);
} else {
@@ -1731,7 +1678,7 @@ void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstIt
{
Q_Q(QGraphicsAnchorLayout);
- const Orientation orientation = edgeOrientation(firstEdge);
+ const Qt::Orientation orientation = edgeOrientation(firstEdge);
// Create or increase the reference count for the related vertices.
AnchorVertex *v1 = addInternalVertex(firstItem, firstEdge);
@@ -1746,7 +1693,7 @@ void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstIt
if (firstItem == secondItem)
data->item = firstItem;
- data->orientation = orientation;
+ data->isVertical = orientation == Qt::Vertical;
// Create a bi-directional edge in the sense it can be transversed both
// from v1 or v2. "data" however is shared between the two references
@@ -1772,7 +1719,7 @@ QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::getAnchor(QGraphicsLayoutItem *fi
if (firstItem == secondItem)
return nullptr;
- const Orientation orientation = edgeOrientation(firstEdge);
+ const Qt::Orientation orientation = edgeOrientation(firstEdge);
AnchorVertex *v1 = internalVertex(firstItem, firstEdge);
AnchorVertex *v2 = internalVertex(secondItem, secondEdge);
@@ -1877,7 +1824,7 @@ void QGraphicsAnchorLayoutPrivate::removeAnchor_helper(AnchorVertex *v1, AnchorV
Q_ASSERT(v1 && v2);
// Remove edge from graph
- const Orientation o = edgeOrientation(v1->m_edge);
+ const Qt::Orientation o = edgeOrientation(v1->m_edge);
graph[o].removeEdge(v1, v2);
// Decrease vertices reference count (may trigger a deletion)
@@ -1938,7 +1885,7 @@ void QGraphicsAnchorLayoutPrivate::removeVertex(QGraphicsLayoutItem *item, Qt::A
{
if (AnchorVertex *v = internalVertex(item, edge)) {
Graph<AnchorVertex, AnchorData> &g = graph[edgeOrientation(edge)];
- const QList<AnchorVertex *> allVertices = graph[edgeOrientation(edge)].adjacentVertices(v);
+ const auto allVertices = g.adjacentVertices(v);
for (auto *v2 : allVertices) {
g.removeEdge(v, v2);
removeInternalVertex(item, edge);
@@ -2032,8 +1979,8 @@ QLayoutStyleInfo &QGraphicsAnchorLayoutPrivate::styleInfo() const
QStyle *style = w ? w->style() : QApplication::style();
cachedStyleInfo = QLayoutStyleInfo(style, wid);
- cachedStyleInfo.setDefaultSpacing(Qt::Horizontal, spacings[0]);
- cachedStyleInfo.setDefaultSpacing(Qt::Vertical, spacings[1]);
+ cachedStyleInfo.setDefaultSpacing(Qt::Horizontal, spacings[Qt::Horizontal]);
+ cachedStyleInfo.setDefaultSpacing(Qt::Vertical, spacings[Qt::Vertical]);
styleInfoDirty = false;
}
@@ -2051,8 +1998,8 @@ void QGraphicsAnchorLayoutPrivate::calculateGraphs()
{
if (!calculateGraphCacheDirty)
return;
- calculateGraphs(Horizontal);
- calculateGraphs(Vertical);
+ calculateGraphs(Qt::Horizontal);
+ calculateGraphs(Qt::Vertical);
calculateGraphCacheDirty = false;
}
@@ -2061,7 +2008,7 @@ void QGraphicsAnchorLayoutPrivate::calculateGraphs()
QList<AnchorData *> getVariables(const QList<QSimplexConstraint *> &constraints)
{
QSet<AnchorData *> variableSet;
- for (int i = 0; i < constraints.count(); ++i) {
+ for (int i = 0; i < constraints.size(); ++i) {
const QSimplexConstraint *c = constraints.at(i);
for (auto it = c->variables.cbegin(), end = c->variables.cend(); it != end; ++it)
variableSet.insert(static_cast<AnchorData *>(it.key()));
@@ -2078,7 +2025,7 @@ QList<AnchorData *> getVariables(const QList<QSimplexConstraint *> &constraints)
In a nutshell it should do:
1) Refresh anchor nominal sizes, that is, the size that each anchor would
- have if no other restrictions applied. This is done by quering the
+ have if no other restrictions applied. This is done by querying the
layout style and the sizeHints of the items belonging to the layout.
2) Simplify the graph by grouping together parallel and sequential anchors
@@ -2092,8 +2039,7 @@ QList<AnchorData *> getVariables(const QList<QSimplexConstraint *> &constraints)
4) Once the root anchors had its sizes calculated, propagate that to the
anchors they represent.
*/
-void QGraphicsAnchorLayoutPrivate::calculateGraphs(
- QGraphicsAnchorLayoutPrivate::Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::calculateGraphs(Qt::Orientation orientation)
{
#if defined(QT_DEBUG) || defined(QT_BUILD_INTERNAL)
lastCalculationUsedSimplex[orientation] = false;
@@ -2177,7 +2123,7 @@ void QGraphicsAnchorLayoutPrivate::calculateGraphs(
*/
static void shiftConstraints(const QList<QSimplexConstraint *> &constraints, qreal amount)
{
- for (int i = 0; i < constraints.count(); ++i) {
+ for (int i = 0; i < constraints.size(); ++i) {
QSimplexConstraint *c = constraints.at(i);
const qreal multiplier = std::accumulate(c->variables.cbegin(), c->variables.cend(), qreal(0));
c->constant += multiplier * amount;
@@ -2190,7 +2136,7 @@ static void shiftConstraints(const QList<QSimplexConstraint *> &constraints, qre
Calculate the sizes for all anchors which are part of the trunk. This works
on top of a (possibly) simplified graph.
*/
-bool QGraphicsAnchorLayoutPrivate::calculateTrunk(Orientation orientation, const GraphPath &path,
+bool QGraphicsAnchorLayoutPrivate::calculateTrunk(Qt::Orientation orientation, const GraphPath &path,
const QList<QSimplexConstraint *> &constraints,
const QList<AnchorData *> &variables)
{
@@ -2199,7 +2145,7 @@ bool QGraphicsAnchorLayoutPrivate::calculateTrunk(Orientation orientation, const
#if 0
qDebug("Simplex %s for trunk of %s", needsSimplex ? "used" : "NOT used",
- orientation == Horizontal ? "Horizontal" : "Vertical");
+ orientation == Qt::Horizontal ? "Horizontal" : "Vertical");
#endif
if (needsSimplex) {
@@ -2235,8 +2181,8 @@ bool QGraphicsAnchorLayoutPrivate::calculateTrunk(Orientation orientation, const
} else {
// No Simplex is necessary because the path was simplified all the way to a single
// anchor.
- Q_ASSERT(path.positives.count() == 1);
- Q_ASSERT(path.negatives.count() == 0);
+ Q_ASSERT(path.positives.size() == 1);
+ Q_ASSERT(path.negatives.size() == 0);
AnchorData *ad = *path.positives.cbegin();
ad->sizeAtMinimum = ad->minSize;
@@ -2267,7 +2213,7 @@ bool QGraphicsAnchorLayoutPrivate::calculateNonTrunk(const QList<QSimplexConstra
if (feasible) {
// Propagate size at preferred to other sizes. Semi-floats always will be
// in their sizeAtPreferred.
- for (int j = 0; j < variables.count(); ++j) {
+ for (int j = 0; j < variables.size(); ++j) {
AnchorData *ad = variables.at(j);
Q_ASSERT(ad);
ad->sizeAtMinimum = ad->sizeAtPreferred;
@@ -2285,13 +2231,13 @@ bool QGraphicsAnchorLayoutPrivate::calculateNonTrunk(const QList<QSimplexConstra
Traverse the graph refreshing the size hints. Edges will query their associated
item or graphicsAnchor for their size hints.
*/
-void QGraphicsAnchorLayoutPrivate::refreshAllSizeHints(Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::refreshAllSizeHints(Qt::Orientation orientation)
{
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- QVector<QPair<AnchorVertex *, AnchorVertex *> > vertices = g.connections();
+ QList<QPair<AnchorVertex *, AnchorVertex *>> vertices = g.connections();
QLayoutStyleInfo styleInf = styleInfo();
- for (int i = 0; i < vertices.count(); ++i) {
+ for (int i = 0; i < vertices.size(); ++i) {
AnchorData *data = g.edgeData(vertices.at(i).first, vertices.at(i).second);
data->refreshSizeHints(&styleInf);
}
@@ -2307,7 +2253,7 @@ void QGraphicsAnchorLayoutPrivate::refreshAllSizeHints(Orientation orientation)
The list of paths is used later to generate a list of constraints.
*/
-void QGraphicsAnchorLayoutPrivate::findPaths(Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::findPaths(Qt::Orientation orientation)
{
QQueue<QPair<AnchorVertex *, AnchorVertex *> > queue;
@@ -2359,7 +2305,7 @@ void QGraphicsAnchorLayoutPrivate::findPaths(Orientation orientation)
the constraints and store them in a list so they can be used later
by the Simplex solver.
*/
-void QGraphicsAnchorLayoutPrivate::constraintsFromPaths(Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::constraintsFromPaths(Qt::Orientation orientation)
{
const auto vertices = graphPaths[orientation].uniqueKeys();
for (AnchorVertex *vertex : vertices) {
@@ -2378,12 +2324,12 @@ void QGraphicsAnchorLayoutPrivate::constraintsFromPaths(Orientation orientation)
/*!
\internal
*/
-void QGraphicsAnchorLayoutPrivate::updateAnchorSizes(Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::updateAnchorSizes(Qt::Orientation orientation)
{
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- const QVector<QPair<AnchorVertex *, AnchorVertex *> > &vertices = g.connections();
+ const QList<QPair<AnchorVertex *, AnchorVertex *>> &vertices = g.connections();
- for (int i = 0; i < vertices.count(); ++i) {
+ for (int i = 0; i < vertices.size(); ++i) {
AnchorData *ad = g.edgeData(vertices.at(i).first, vertices.at(i).second);
ad->updateChildrenSizes();
}
@@ -2403,7 +2349,7 @@ QList<QSimplexConstraint *> QGraphicsAnchorLayoutPrivate::constraintsFromSizeHin
// Look for the layout edge. That can be either the first half in case the
// layout is split in two, or the whole layout anchor.
- Orientation orient = Orientation(anchors.first()->orientation);
+ const Qt::Orientation orient = anchors.first()->isVertical ? Qt::Vertical : Qt::Horizontal;
AnchorData *layoutEdge = nullptr;
if (layoutCentralVertex[orient]) {
layoutEdge = graph[orient].edgeData(layoutFirstVertex[orient], layoutCentralVertex[orient]);
@@ -2490,7 +2436,7 @@ QList<QSimplexConstraint *> QGraphicsAnchorLayoutPrivate::constraintsFromSizeHin
\internal
*/
QGraphicsAnchorLayoutPrivate::GraphParts
-QGraphicsAnchorLayoutPrivate::getGraphParts(Orientation orientation)
+QGraphicsAnchorLayoutPrivate::getGraphParts(Qt::Orientation orientation)
{
GraphParts result;
@@ -2526,7 +2472,7 @@ QGraphicsAnchorLayoutPrivate::getGraphParts(Orientation orientation)
// Check if this constraint have some overlap with current
// trunk variables...
- for (QSimplexVariable *ad : qAsConst(trunkVariables)) {
+ for (QSimplexVariable *ad : std::as_const(trunkVariables)) {
if (c->variables.contains(ad)) {
match = true;
break;
@@ -2567,7 +2513,7 @@ QGraphicsAnchorLayoutPrivate::getGraphParts(Orientation orientation)
Use all visited Anchors on findPaths() so we can identify non-float Items.
*/
-void QGraphicsAnchorLayoutPrivate::identifyFloatItems(const QSet<AnchorData *> &visited, Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::identifyFloatItems(const QSet<AnchorData *> &visited, Qt::Orientation orientation)
{
QSet<QGraphicsLayoutItem *> nonFloating;
@@ -2575,7 +2521,7 @@ void QGraphicsAnchorLayoutPrivate::identifyFloatItems(const QSet<AnchorData *> &
identifyNonFloatItems_helper(ad, &nonFloating);
QSet<QGraphicsLayoutItem *> floatItems;
- for (QGraphicsLayoutItem *item : qAsConst(items)) {
+ for (QGraphicsLayoutItem *item : std::as_const(items)) {
if (!nonFloating.contains(item))
floatItems.insert(item);
}
@@ -2600,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:
@@ -2634,10 +2580,10 @@ void QGraphicsAnchorLayoutPrivate::setItemsGeometries(const QRectF &geom)
top += geom.top();
right = geom.right() - right;
- foreach (QGraphicsLayoutItem *item, items) {
+ for (QGraphicsLayoutItem *item : std::as_const(items)) {
QRectF newGeom;
QSizeF itemPreferredSize = item->effectiveSizeHint(Qt::PreferredSize);
- if (m_floatItems[Horizontal].contains(item)) {
+ if (m_floatItems[Qt::Horizontal].contains(item)) {
newGeom.setLeft(0);
newGeom.setRight(itemPreferredSize.width());
} else {
@@ -2653,7 +2599,7 @@ void QGraphicsAnchorLayoutPrivate::setItemsGeometries(const QRectF &geom)
}
}
- if (m_floatItems[Vertical].contains(item)) {
+ if (m_floatItems[Qt::Vertical].contains(item)) {
newGeom.setTop(0);
newGeom.setBottom(itemPreferredSize.height());
} else {
@@ -2674,8 +2620,7 @@ void QGraphicsAnchorLayoutPrivate::setItemsGeometries(const QRectF &geom)
Calculate the position of each vertex based on the paths to each of
them as well as the current edges sizes.
*/
-void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(
- QGraphicsAnchorLayoutPrivate::Orientation orientation)
+void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(Qt::Orientation orientation)
{
QQueue<QPair<AnchorVertex *, AnchorVertex *> > queue;
QSet<AnchorVertex *> visited;
@@ -2706,7 +2651,7 @@ void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(
interpolateEdge(pair.first, edge);
QList<AnchorVertex *> adjacents = graph[orientation].adjacentVertices(pair.second);
- for (int i = 0; i < adjacents.count(); ++i) {
+ for (int i = 0; i < adjacents.size(); ++i) {
if (!visited.contains(adjacents.at(i)))
queue.enqueue(qMakePair(pair.second, adjacents.at(i)));
}
@@ -2721,12 +2666,12 @@ void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(
the edges.
*/
void QGraphicsAnchorLayoutPrivate::setupEdgesInterpolation(
- Orientation orientation)
+ Qt::Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
qreal current;
- current = (orientation == Horizontal) ? q->contentsRect().width() : q->contentsRect().height();
+ current = (orientation == Qt::Horizontal) ? q->contentsRect().width() : q->contentsRect().height();
QPair<Interval, qreal> result;
result = getFactor(current,
@@ -2757,7 +2702,7 @@ void QGraphicsAnchorLayoutPrivate::setupEdgesInterpolation(
*/
void QGraphicsAnchorLayoutPrivate::interpolateEdge(AnchorVertex *base, AnchorData *edge)
{
- const Orientation orientation = Orientation(edge->orientation);
+ const Qt::Orientation orientation = edge->isVertical ? Qt::Vertical : Qt::Horizontal;
const QPair<Interval, qreal> factor(interpolationInterval[orientation],
interpolationProgress[orientation]);
@@ -2790,7 +2735,7 @@ bool QGraphicsAnchorLayoutPrivate::solveMinMax(const QList<QSimplexConstraint *>
for (iter = path.negatives.constBegin(); iter != path.negatives.constEnd(); ++iter)
objective.variables.insert(*iter, -1.0);
- const qreal objectiveOffset = (path.positives.count() - path.negatives.count()) * g_offset;
+ const qreal objectiveOffset = (path.positives.size() - path.negatives.size()) * g_offset;
simplex.setObjective(&objective);
// Calculate minimum values
@@ -2953,9 +2898,9 @@ bool QGraphicsAnchorLayoutPrivate::hasConflicts() const
QGraphicsAnchorLayoutPrivate *that = const_cast<QGraphicsAnchorLayoutPrivate*>(this);
that->calculateGraphs();
- bool floatConflict = !m_floatItems[0].isEmpty() || !m_floatItems[1].isEmpty();
+ bool floatConflict = !m_floatItems[Qt::Horizontal].isEmpty() || !m_floatItems[Qt::Vertical].isEmpty();
- return graphHasConflicts[0] || graphHasConflicts[1] || floatConflict;
+ return graphHasConflicts[Qt::Horizontal] || graphHasConflicts[Qt::Vertical] || floatConflict;
}
#ifdef QT_DEBUG
@@ -2966,8 +2911,8 @@ void QGraphicsAnchorLayoutPrivate::dumpGraph(const QString &name)
qWarning("Could not write to %ls", qUtf16Printable(file.fileName()));
QString str = QString::fromLatin1("digraph anchorlayout {\nnode [shape=\"rect\"]\n%1}");
- QString dotContents = graph[0].serializeToDot();
- dotContents += graph[1].serializeToDot();
+ QString dotContents = graph[Qt::Horizontal].serializeToDot();
+ dotContents += graph[Qt::Vertical].serializeToDot();
file.write(str.arg(dotContents).toLocal8Bit());
file.close();
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.h b/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
index b5f14948ac..880e262d34 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSANCHORLAYOUT_P_H
#define QGRAPHICSANCHORLAYOUT_P_H
@@ -60,6 +24,10 @@
#include "qgraph_p.h"
#include "qsimplex_p.h"
+#include <QtGui/private/qgridlayoutengine_p.h>
+
+#include <array>
+
QT_REQUIRE_CONFIG(graphicsview);
QT_BEGIN_NAMESPACE
@@ -79,25 +47,22 @@ namespace QtGraphicsAnchorLayout {
Represents a vertex (anchorage point) in the internal graph
*/
-struct AnchorVertex {
- enum Type {
- Normal = 0,
- Pair
- };
-
+struct AnchorVertex
+{
AnchorVertex(QGraphicsLayoutItem *item, Qt::AnchorPoint edge)
- : m_item(item), m_edge(edge), m_type(Normal) {}
+ : m_item(item), m_edge(edge) {}
AnchorVertex()
- : m_item(nullptr), m_edge(Qt::AnchorPoint(0)), m_type(Normal) {}
+ : m_item(nullptr), m_edge(Qt::AnchorPoint(0)) {}
+
+ virtual ~AnchorVertex() = default;
#ifdef QT_DEBUG
- inline QString toString() const;
+ virtual inline QString toString() const;
#endif
QGraphicsLayoutItem *m_item;
Qt::AnchorPoint m_edge;
- uint m_type : 1;
// Current distance from this vertex to the layout edge (Left or Top)
// Value is calculated from the current anchors sizes.
@@ -129,7 +94,7 @@ struct AnchorData : public QSimplexVariable {
sizeAtMinimum(0), sizeAtPreferred(0),
sizeAtMaximum(0), item(nullptr), graphicsAnchor(nullptr),
type(Normal), isLayoutAnchor(false),
- isCenterAnchor(false), orientation(0),
+ isCenterAnchor(false), isVertical(false),
dependency(Independent) {}
virtual ~AnchorData();
@@ -168,7 +133,7 @@ struct AnchorData : public QSimplexVariable {
qreal sizeAtMaximum;
// References to the classes that represent this anchor in the public world
- // An anchor may represent a LayoutItem, it may also be acessible externally
+ // An anchor may represent a LayoutItem, it may also be accessible externally
// through a GraphicsAnchor "handler".
QGraphicsLayoutItem *item;
QGraphicsAnchor *graphicsAnchor;
@@ -176,7 +141,7 @@ struct AnchorData : public QSimplexVariable {
uint type : 2; // either Normal, Sequential or Parallel
uint isLayoutAnchor : 1; // if this anchor is an internal layout anchor
uint isCenterAnchor : 1;
- uint orientation : 1;
+ uint isVertical : 1;
uint dependency : 2; // either Independent, Master or Slave
};
@@ -189,21 +154,22 @@ inline QString AnchorData::toString() const
struct SequentialAnchorData : public AnchorData
{
- SequentialAnchorData(const QVector<AnchorVertex *> &vertices, const QVector<AnchorData *> &edges)
- : AnchorData(), m_children(vertices), m_edges(edges)
+ SequentialAnchorData(const QList<AnchorVertex *> &vertices, const QList<AnchorData *> &edges)
+ : AnchorData(), m_edges(edges)
{
type = AnchorData::Sequential;
- orientation = m_edges.at(0)->orientation;
+ 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();
- QVector<AnchorVertex*> m_children; // list of vertices in the sequence
- QVector<AnchorData*> m_edges; // keep the list of edges too.
+ const QList<AnchorData *> m_edges; // keep the list of edges too.
};
struct ParallelAnchorData : public AnchorData
@@ -212,7 +178,7 @@ struct ParallelAnchorData : public AnchorData
: AnchorData(), firstEdge(first), secondEdge(second)
{
type = AnchorData::Parallel;
- orientation = first->orientation;
+ isVertical = first->isVertical;
// This assert whether the child anchors share their vertices
Q_ASSERT(((first->from == second->from) && (first->to == second->to)) ||
@@ -246,8 +212,8 @@ struct ParallelAnchorData : public AnchorData
struct AnchorVertexPair : public AnchorVertex {
AnchorVertexPair(AnchorVertex *v1, AnchorVertex *v2, AnchorData *data)
- : AnchorVertex(), m_first(v1), m_second(v2), m_removedAnchor(data) {
- m_type = AnchorVertex::Pair;
+ : AnchorVertex(), m_first(v1), m_second(v2), m_removedAnchor(data)
+ {
}
AnchorVertex *m_first;
@@ -256,50 +222,56 @@ struct AnchorVertexPair : public AnchorVertex {
AnchorData *m_removedAnchor;
QList<AnchorData *> m_firstAnchors;
QList<AnchorData *> m_secondAnchors;
+
+#ifdef QT_DEBUG
+ inline QString toString() const override
+ {
+ return QString::fromLatin1("(%1, %2)").arg(m_first->toString(), m_second->toString());
+ }
+#endif
};
#ifdef QT_DEBUG
inline QString AnchorVertex::toString() const
{
- if (m_type == Pair) {
- const AnchorVertexPair *vp = static_cast<const AnchorVertexPair *>(this);
- return QString::fromLatin1("(%1, %2)").arg(vp->m_first->toString(), vp->m_second->toString());
- } else if (!m_item) {
+ using namespace Qt::StringLiterals;
+
+ if (!m_item)
return QString::fromLatin1("NULL_%1").arg(quintptr(this));
- }
+
QString edge;
switch (m_edge) {
case Qt::AnchorLeft:
- edge = QLatin1String("Left");
+ edge = "Left"_L1;
break;
case Qt::AnchorHorizontalCenter:
- edge = QLatin1String("HorizontalCenter");
+ edge = "HorizontalCenter"_L1;
break;
case Qt::AnchorRight:
- edge = QLatin1String("Right");
+ edge = "Right"_L1;
break;
case Qt::AnchorTop:
- edge = QLatin1String("Top");
+ edge = "Top"_L1;
break;
case Qt::AnchorVerticalCenter:
- edge = QLatin1String("VerticalCenter");
+ edge = "VerticalCenter"_L1;
break;
case Qt::AnchorBottom:
- edge = QLatin1String("Bottom");
+ edge = "Bottom"_L1;
break;
default:
- edge = QLatin1String("None");
+ edge = "None"_L1;
break;
}
QString itemName;
if (m_item->isLayout()) {
- itemName = QLatin1String("layout");
+ itemName = "layout"_L1;
} else {
if (QGraphicsItem *item = m_item->graphicsItem()) {
itemName = item->data(0).toString();
}
}
- edge.insert(0, QLatin1String("%1_"));
+ edge.insert(0, "%1_"_L1);
return edge.arg(itemName);
}
#endif
@@ -330,7 +302,7 @@ public:
} // namespace QtGraphicsAnchorLayout
using namespace QtGraphicsAnchorLayout;
-Q_DECLARE_TYPEINFO(GraphPath, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(GraphPath, Q_RELOCATABLE_TYPE);
class QGraphicsAnchorLayoutPrivate;
/*!
@@ -388,15 +360,9 @@ public:
MaxPreferredToMaximum
};
- // Several structures internal to the layout are duplicated to handle
- // both Horizontal and Vertical restrictions.
- //
- // Orientation is used to reference the right structure in each context
- enum Orientation {
- Horizontal = 0,
- Vertical,
- NOrientations
- };
+ typedef Qt::Orientation Orientation [[deprecated]];
+ [[deprecated]] static inline constexpr Qt::Orientation Horizontal = Qt::Horizontal;
+ [[deprecated]] static inline constexpr Qt::Orientation Vertical = Qt::Vertical;
QGraphicsAnchorLayoutPrivate();
@@ -408,13 +374,13 @@ public:
static Qt::AnchorPoint oppositeEdge(
Qt::AnchorPoint edge);
- static Orientation edgeOrientation(Qt::AnchorPoint edge);
+ static Qt::Orientation edgeOrientation(Qt::AnchorPoint edge) noexcept;
- static Qt::AnchorPoint pickEdge(Qt::AnchorPoint edge, Orientation orientation)
+ static Qt::AnchorPoint pickEdge(Qt::AnchorPoint edge, Qt::Orientation orientation)
{
- if (orientation == Vertical && int(edge) <= 2)
+ if (orientation == Qt::Vertical && int(edge) <= 2)
return (Qt::AnchorPoint)(edge + 3);
- else if (orientation == Horizontal && int(edge) >= 3) {
+ else if (orientation == Qt::Horizontal && int(edge) >= 3) {
return (Qt::AnchorPoint)(edge - 3);
}
return edge;
@@ -426,7 +392,7 @@ public:
void createItemEdges(QGraphicsLayoutItem *item);
void createCenterAnchors(QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge);
void removeCenterAnchors(QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge, bool substitute = true);
- void removeCenterConstraints(QGraphicsLayoutItem *item, Orientation orientation);
+ void removeCenterConstraints(QGraphicsLayoutItem *item, Qt::Orientation orientation);
QGraphicsAnchor *acquireGraphicsAnchor(AnchorData *data)
{
@@ -473,40 +439,40 @@ public:
// Activation
void calculateGraphs();
- void calculateGraphs(Orientation orientation);
+ void calculateGraphs(Qt::Orientation orientation);
// Simplification
- bool simplifyGraph(Orientation orientation);
- bool simplifyVertices(Orientation orientation);
- bool simplifyGraphIteration(Orientation orientation, bool *feasible);
+ bool simplifyGraph(Qt::Orientation orientation);
+ bool simplifyVertices(Qt::Orientation orientation);
+ bool simplifyGraphIteration(Qt::Orientation orientation, bool *feasible);
- bool replaceVertex(Orientation orientation, AnchorVertex *oldV,
+ bool replaceVertex(Qt::Orientation orientation, AnchorVertex *oldV,
AnchorVertex *newV, const QList<AnchorData *> &edges);
- void restoreSimplifiedGraph(Orientation orientation);
+ void restoreSimplifiedGraph(Qt::Orientation orientation);
void restoreSimplifiedAnchor(AnchorData *edge);
void restoreSimplifiedConstraints(ParallelAnchorData *parallel);
- void restoreVertices(Orientation orientation);
+ void restoreVertices(Qt::Orientation orientation);
- bool calculateTrunk(Orientation orientation, const GraphPath &trunkPath,
+ bool calculateTrunk(Qt::Orientation orientation, const GraphPath &trunkPath,
const QList<QSimplexConstraint *> &constraints,
const QList<AnchorData *> &variables);
bool calculateNonTrunk(const QList<QSimplexConstraint *> &constraints,
const QList<AnchorData *> &variables);
// Support functions for calculateGraph()
- void refreshAllSizeHints(Orientation orientation);
- void findPaths(Orientation orientation);
- void constraintsFromPaths(Orientation orientation);
- void updateAnchorSizes(Orientation orientation);
+ void refreshAllSizeHints(Qt::Orientation orientation);
+ void findPaths(Qt::Orientation orientation);
+ void constraintsFromPaths(Qt::Orientation orientation);
+ void updateAnchorSizes(Qt::Orientation orientation);
QList<QSimplexConstraint *> constraintsFromSizeHints(const QList<AnchorData *> &anchors);
struct GraphParts {
QList<QSimplexConstraint *> trunkConstraints;
QList<QSimplexConstraint *> nonTrunkConstraints;
};
- GraphParts getGraphParts(Orientation orientation);
- void identifyFloatItems(const QSet<AnchorData *> &visited, Orientation orientation);
+ GraphParts getGraphParts(Qt::Orientation orientation);
+ void identifyFloatItems(const QSet<AnchorData *> &visited, Qt::Orientation orientation);
void identifyNonFloatItems_helper(const AnchorData *ad, QSet<QGraphicsLayoutItem *> *nonFloatingItemsIdentifiedSoFar);
inline AnchorVertex *internalVertex(const QPair<QGraphicsLayoutItem*, Qt::AnchorPoint> &itemEdge) const
@@ -519,7 +485,7 @@ public:
return internalVertex(qMakePair(const_cast<QGraphicsLayoutItem *>(item), edge));
}
- inline void changeLayoutVertex(Orientation orientation, AnchorVertex *oldV, AnchorVertex *newV)
+ inline void changeLayoutVertex(Qt::Orientation orientation, AnchorVertex *oldV, AnchorVertex *newV)
{
if (layoutFirstVertex[orientation] == oldV)
layoutFirstVertex[orientation] = newV;
@@ -536,8 +502,8 @@ public:
// Geometry interpolation methods
void setItemsGeometries(const QRectF &geom);
- void calculateVertexPositions(Orientation orientation);
- void setupEdgesInterpolation(Orientation orientation);
+ void calculateVertexPositions(Qt::Orientation orientation);
+ void setupEdgesInterpolation(Qt::Orientation orientation);
void interpolateEdge(AnchorVertex *base, AnchorData *edge);
// Linear Programming solver methods
@@ -552,12 +518,12 @@ public:
#endif
- qreal spacings[NOrientations];
+ QHVContainer<qreal> spacings = {-1, -1};
// Size hints from simplex engine
- qreal sizeHints[2][3];
+ QHVContainer<std::array<qreal, 3>> sizeHints = {{-1, -1, -1}, {-1, -1, -1}};
// Items
- QVector<QGraphicsLayoutItem *> items;
+ QList<QGraphicsLayoutItem *> items;
// Mapping between high level anchorage points (Item, Edge) to low level
// ones (Graph Vertices)
@@ -565,31 +531,31 @@ public:
QHash<QPair<QGraphicsLayoutItem*, Qt::AnchorPoint>, QPair<AnchorVertex *, int> > m_vertexList;
// Internal graph of anchorage points and anchors, for both orientations
- Graph<AnchorVertex, AnchorData> graph[2];
+ QHVContainer<Graph<AnchorVertex, AnchorData>> graph;
- AnchorVertex *layoutFirstVertex[2];
- AnchorVertex *layoutCentralVertex[2];
- AnchorVertex *layoutLastVertex[2];
+ QHVContainer<AnchorVertex *> layoutFirstVertex = {};
+ QHVContainer<AnchorVertex *> layoutCentralVertex = {};
+ QHVContainer<AnchorVertex *> layoutLastVertex = {};
// Combined anchors in order of creation
- QList<AnchorVertexPair *> simplifiedVertices[2];
- QList<AnchorData *> anchorsFromSimplifiedVertices[2];
+ QHVContainer<QList<AnchorVertexPair *>> simplifiedVertices;
+ QHVContainer<QList<AnchorData *>> anchorsFromSimplifiedVertices;
// Graph paths and constraints, for both orientations
- QMultiHash<AnchorVertex *, GraphPath> graphPaths[2];
- QList<QSimplexConstraint *> constraints[2];
- QList<QSimplexConstraint *> itemCenterConstraints[2];
+ QHVContainer<QMultiHash<AnchorVertex *, GraphPath>> graphPaths;
+ QHVContainer<QList<QSimplexConstraint *>> constraints;
+ QHVContainer<QList<QSimplexConstraint *>> itemCenterConstraints;
// The interpolation interval and progress based on the current size
// as well as the key values (minimum, preferred and maximum)
- Interval interpolationInterval[2];
- qreal interpolationProgress[2];
+ QHVContainer<Interval> interpolationInterval;
+ QHVContainer<qreal> interpolationProgress = {-1, -1};
- bool graphHasConflicts[2];
- QSet<QGraphicsLayoutItem *> m_floatItems[2];
+ QHVContainer<bool> graphHasConflicts = {};
+ QHVContainer<QSet<QGraphicsLayoutItem *>> m_floatItems;
#if defined(QT_DEBUG) || defined(QT_BUILD_INTERNAL)
- bool lastCalculationUsedSimplex[2];
+ QHVContainer<bool> lastCalculationUsedSimplex;
#endif
uint calculateGraphCacheDirty : 1;
diff --git a/src/widgets/graphicsview/qgraphicsgridlayout.cpp b/src/widgets/graphicsview/qgraphicsgridlayout.cpp
index 260e1861c7..e4599d20bb 100644
--- a/src/widgets/graphicsview/qgraphicsgridlayout.cpp
+++ b/src/widgets/graphicsview/qgraphicsgridlayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsGridLayout
@@ -47,13 +11,16 @@
\inmodule QtWidgets
The most common way to use QGraphicsGridLayout is to construct an object
- on the heap with no parent, add widgets and layouts by calling addItem(),
- and finally assign the layout to a widget by calling
- QGraphicsWidget::setLayout(). QGraphicsGridLayout automatically computes
+ on the heap, passing a parent widget to the constructor, then add widgets
+ and layouts by calling addItem(). QGraphicsGridLayout automatically computes
the dimensions of the grid as you add items.
\snippet code/src_gui_graphicsview_qgraphicsgridlayout.cpp 0
+ Alternatively, if you do not pass a parent widget to the layout's constructor,
+ you will need to call QGraphicsWidget::setLayout() to set this layout as the
+ top-level layout for that widget, the widget will take ownership of the layout.
+
The layout takes ownership of the items. In some cases when the layout
item also inherits from QGraphicsItem (such as QGraphicsWidget) there will be a
ambiguity in ownership because the layout item belongs to two ownership hierarchies.
@@ -179,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.
@@ -587,9 +554,7 @@ void QGraphicsGridLayout::removeAt(int index)
d->engine.removeItem(gridItem);
// recalculate rowInfo.count if we remove an item that is on the right/bottommost row
- for (int j = 0; j < NOrientations; ++j) {
- // 0: Hor, 1: Ver
- const Qt::Orientation orient = (j == 0 ? Qt::Horizontal : Qt::Vertical);
+ for (const Qt::Orientation orient : {Qt::Horizontal, Qt::Vertical}) {
const int oldCount = d->engine.rowCount(orient);
if (gridItem->lastRow(orient) == oldCount - 1) {
const int newCount = d->engine.effectiveLastRow(orient) + 1;
diff --git a/src/widgets/graphicsview/qgraphicsgridlayout.h b/src/widgets/graphicsview/qgraphicsgridlayout.h
index 4c0a1b4527..bf2cf383d8 100644
--- a/src/widgets/graphicsview/qgraphicsgridlayout.h
+++ b/src/widgets/graphicsview/qgraphicsgridlayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSGRIDLAYOUT_H
#define QGRAPHICSGRIDLAYOUT_H
diff --git a/src/widgets/graphicsview/qgraphicsgridlayoutengine.cpp b/src/widgets/graphicsview/qgraphicsgridlayoutengine.cpp
index 5797d9e539..db0818d93e 100644
--- a/src/widgets/graphicsview/qgraphicsgridlayoutengine.cpp
+++ b/src/widgets/graphicsview/qgraphicsgridlayoutengine.cpp
@@ -1,70 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgraphicsgridlayoutengine_p.h"
#include "qgraphicslayoutitem_p.h"
#include "qgraphicslayout_p.h"
#include "qgraphicswidget.h"
-#include <private/qgraphicswidget_p.h>
QT_BEGIN_NAMESPACE
-bool QGraphicsGridLayoutEngineItem::isHidden() const
-{
- if (QGraphicsItem *item = q_layoutItem->graphicsItem())
- return QGraphicsItemPrivate::get(item)->explicitlyHidden;
- return false;
-}
-
-/*!
- \internal
-
- If this returns true, the layout will arrange just as if the item was never added to the layout.
- (Note that this shouldn't lead to a "double spacing" where the item was hidden)
- ### Qt6: Move to QGraphicsLayoutItem and make virtual
-*/
-bool QGraphicsGridLayoutEngineItem::isIgnored() const
-{
- return isHidden() && !q_layoutItem->sizePolicy().retainSizeWhenHidden();
-}
-
/*
returns \c true if the size policy returns \c true for either hasHeightForWidth()
or hasWidthForHeight()
@@ -83,6 +27,16 @@ Qt::Orientation QGraphicsGridLayoutEngineItem::dynamicConstraintOrientation() co
return Qt::Horizontal;
}
+/*!
+ \internal
+
+ If this returns true, the layout will arrange just as if the item was never added to the layout.
+ (Note that this shouldn't lead to a "double spacing" where the item was hidden)
+*/
+bool QGraphicsGridLayoutEngineItem::isEmpty() const
+{
+ return q_layoutItem->isEmpty();
+}
void QGraphicsGridLayoutEngine::setAlignment(QGraphicsLayoutItem *graphicsLayoutItem, Qt::Alignment alignment)
{
diff --git a/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h b/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h
index 2f2c547977..f3b2ec3731 100644
--- a/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h
+++ b/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSGRIDLAYOUTENGINE_P_H
#define QGRAPHICSGRIDLAYOUTENGINE_P_H
@@ -89,10 +53,6 @@ public:
return q_layoutItem->effectiveSizeHint(which, constraint);
}
- bool isHidden() const;
-
- virtual bool isIgnored() const override;
-
virtual void setGeometry(const QRectF &rect) override
{
q_layoutItem->setGeometry(rect);
@@ -101,6 +61,8 @@ public:
virtual bool hasDynamicConstraint() const override;
virtual Qt::Orientation dynamicConstraintOrientation() const override;
+ virtual bool isEmpty() const override;
+
QGraphicsLayoutItem *layoutItem() const { return q_layoutItem; }
protected:
@@ -121,7 +83,7 @@ public:
int indexOf(QGraphicsLayoutItem *item) const
{
- for (int i = 0; i < q_items.count(); ++i) {
+ for (int i = 0; i < q_items.size(); ++i) {
if (item == static_cast<QGraphicsGridLayoutEngineItem*>(q_items.at(i))->layoutItem())
return i;
}
diff --git a/src/widgets/graphicsview/qgraphicsitem.cpp b/src/widgets/graphicsview/qgraphicsitem.cpp
index b410ba82c2..17ea830cab 100644
--- a/src/widgets/graphicsview/qgraphicsitem.cpp
+++ b/src/widgets/graphicsview/qgraphicsitem.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 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
/*!
\class QGraphicsItem
@@ -132,7 +96,6 @@
\image graphicsview-parentchild.png
- \target Transformations
\section1 Transformations
QGraphicsItem supports projective transformations in addition to its base
@@ -244,7 +207,7 @@
\li keyPressEvent() and keyReleaseEvent() handle key press and release events
\li mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(), and
mouseDoubleClickEvent() handles mouse press, move, release, click and
- doubleclick events
+ double-click events
\endlist
You can filter events for any other item by installing event filters. This
@@ -429,16 +392,12 @@
in Qt 4.5.
\value ItemUsesExtendedStyleOption The item makes use of either
- \l{QStyleOptionGraphicsItem::} {exposedRect} or
- \l{QStyleOptionGraphicsItem::} {matrix} in
+ \l{QStyleOptionGraphicsItem::} {exposedRect} in
QStyleOptionGraphicsItem. By default, the
\l{QStyleOptionGraphicsItem::} {exposedRect} is initialized to the
- item's boundingRect() and the
- \l{QStyleOptionGraphicsItem::}{matrix} is untransformed. You can
+ item's boundingRect(). You can
enable this flag for the style options to be set up with more
- fine-grained values. Note that
- QStyleOptionGraphicsItem::levelOfDetail is unaffected by this flag
- and always initialized to 1. Use
+ fine-grained values. Use
QStyleOptionGraphicsItem::levelOfDetailFromTransform() if you need
a higher value. This flag was introduced in Qt 4.6.
@@ -530,9 +489,6 @@
setEnabled() in itemChange() as this notification is delivered. The return
value is ignored.
- \value ItemMatrixChange The item's affine transformation matrix is
- changing. This value is obsolete; you can use ItemTransformChange instead.
-
\value ItemPositionChange The item's position changes. This notification
is sent if the ItemSendsGeometryChanges flag is enabled, and when the
item's local position changes, relative to its parent (i.e., as a result
@@ -836,6 +792,8 @@
QT_BEGIN_NAMESPACE
+QT_IMPL_METATYPE_EXTERN_TAGGED(QGraphicsItem*, QGraphicsItem_ptr)
+
static inline void _q_adjustRect(QRect *rect)
{
Q_ASSERT(rect);
@@ -946,7 +904,6 @@ QGraphicsItemPrivate::QGraphicsItemPrivate()
scenePosDescendants(false),
pendingPolish(false),
mayHaveChildWithGraphicsEffect(false),
- isDeclarativeItem(false),
sendParentChangeNotification(false),
dirtyChildrenBoundingRect(true),
globalStackingOrder(-1),
@@ -1078,7 +1035,7 @@ void QGraphicsItemPrivate::setIsMemberOfGroup(bool enabled)
Q_Q(QGraphicsItem);
isMemberOfGroup = enabled;
if (!qgraphicsitem_cast<QGraphicsItemGroup *>(q)) {
- foreach (QGraphicsItem *child, children)
+ for (QGraphicsItem *child : std::as_const(children))
child->d_func()->setIsMemberOfGroup(enabled);
}
}
@@ -1479,7 +1436,6 @@ void QGraphicsItemPrivate::initStyleOption(QStyleOptionGraphicsItem *option, con
const QRectF brect = q->boundingRect();
option->state = QStyle::State_None;
option->rect = brect.toRect();
- option->levelOfDetail = 1;
option->exposedRect = brect;
// Style animations require a QObject-based animation target.
@@ -1505,9 +1461,6 @@ void QGraphicsItemPrivate::initStyleOption(QStyleOptionGraphicsItem *option, con
if (!(flags & QGraphicsItem::ItemUsesExtendedStyleOption))
return;
- // Initialize QStyleOptionGraphicsItem specific values (matrix, exposedRect).
- option->matrix = worldTransform.toAffine(); //### discards perspective
-
if (!allItems) {
// Determine the item's exposed area
option->exposedRect = QRectF();
@@ -1594,9 +1547,8 @@ QGraphicsItem::~QGraphicsItem()
if (d_ptr->isObject && !d_ptr->gestureContext.isEmpty()) {
QGraphicsObject *o = static_cast<QGraphicsObject *>(this);
if (QGestureManager *manager = QGestureManager::instance(QGestureManager::DontForceCreation)) {
- const auto types = d_ptr->gestureContext.keys(); // FIXME: iterate over the map directly?
- for (Qt::GestureType type : types)
- manager->cleanupCachedGestures(o, type);
+ for (auto it = d_ptr->gestureContext.constBegin(); it != d_ptr->gestureContext.constEnd(); ++it)
+ manager->cleanupCachedGestures(o, it.key());
}
}
#endif
@@ -1854,15 +1806,6 @@ void QGraphicsItem::setParentItem(QGraphicsItem *newParent)
}
/*!
- \fn QList<QGraphicsItem *> QGraphicsItem::children() const
- \obsolete
-
- Use childItems() instead.
-
- \sa setParentItem()
-*/
-
-/*!
\since 4.4
Returns a list of this item's children.
@@ -2231,7 +2174,7 @@ bool QGraphicsItem::isBlockedByModalPanel(QGraphicsItem **blockingPanel) const
if (!scene_d->popupWidgets.isEmpty() && scene_d->popupWidgets.first() == this)
return false;
- for (int i = 0; i < scene_d->modalPanels.count(); ++i) {
+ for (int i = 0; i < scene_d->modalPanels.size(); ++i) {
QGraphicsItem *modalPanel = scene_d->modalPanels.at(i);
if (modalPanel->panelModality() == QGraphicsItem::SceneModal) {
// Scene modal panels block all non-descendents.
@@ -2252,7 +2195,7 @@ bool QGraphicsItem::isBlockedByModalPanel(QGraphicsItem **blockingPanel) const
return false;
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
/*!
Returns the item's tool tip, or an empty QString if no tool tip has been
set.
@@ -2276,7 +2219,7 @@ void QGraphicsItem::setToolTip(const QString &toolTip)
d_ptr->setExtra(QGraphicsItemPrivate::ExtraToolTip, toolTipVariant.toString());
itemChange(ItemToolTipHasChanged, toolTipVariant);
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
#ifndef QT_NO_CURSOR
/*!
@@ -2292,7 +2235,7 @@ void QGraphicsItem::setToolTip(const QString &toolTip)
If no cursor has been set, the cursor of the item beneath is used.
\sa setCursor(), hasCursor(), unsetCursor(), QWidget::cursor,
- QApplication::overrideCursor()
+ QGuiApplication::overrideCursor()
*/
QCursor QGraphicsItem::cursor() const
{
@@ -2312,7 +2255,7 @@ QCursor QGraphicsItem::cursor() const
If no cursor has been set, the cursor of the item beneath is used.
\sa cursor(), hasCursor(), unsetCursor(), QWidget::cursor,
- QApplication::overrideCursor()
+ QGuiApplication::overrideCursor()
*/
void QGraphicsItem::setCursor(const QCursor &cursor)
{
@@ -2326,12 +2269,17 @@ void QGraphicsItem::setCursor(const QCursor &cursor)
view->viewport()->setMouseTracking(true);
// Note: Some of this logic is duplicated in QGraphicsView's mouse events.
if (view->underMouse()) {
- const auto itemsUnderCursor = view->items(view->mapFromGlobal(QCursor::pos()));
- for (QGraphicsItem *itemUnderCursor : itemsUnderCursor) {
- if (itemUnderCursor->hasCursor()) {
- QMetaObject::invokeMethod(view, "_q_setViewportCursor",
- Q_ARG(QCursor, itemUnderCursor->cursor()));
- break;
+ const QPoint viewPoint = view->mapFromGlobal(QCursor::pos());
+ const QPointF cursorPos = mapFromScene(view->mapToScene(viewPoint));
+ // the cursor can only change if the current item is under the mouse
+ if (boundingRect().contains(cursorPos)) {
+ const auto itemsUnderCursor = view->items(viewPoint);
+ for (QGraphicsItem *itemUnderCursor : itemsUnderCursor) {
+ if (itemUnderCursor->hasCursor()) {
+ QMetaObject::invokeMethod(view, "_q_setViewportCursor",
+ Q_ARG(QCursor, itemUnderCursor->cursor()));
+ break;
+ }
}
}
break;
@@ -2509,7 +2457,7 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly,
const bool updateChildren = update && !((flags & QGraphicsItem::ItemClipsChildrenToShape
|| flags & QGraphicsItem::ItemContainsChildrenInShape)
&& !(flags & QGraphicsItem::ItemHasNoContents));
- foreach (QGraphicsItem *child, children) {
+ for (QGraphicsItem *child : std::as_const(children)) {
if (!newVisible || !child->d_ptr->explicitlyHidden)
child->d_ptr->setVisibleHelper(newVisible, false, updateChildren, hiddenByPanel);
}
@@ -2668,23 +2616,25 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo
// Certain properties are dropped when an item is disabled.
if (!newEnabled) {
- if (scene && scene->mouseGrabberItem() == q_ptr)
- q_ptr->ungrabMouse();
- if (q_ptr->hasFocus()) {
- // Disabling the closest non-panel ancestor of the focus item
- // causes focus to pop to the next item, otherwise it's cleared.
- QGraphicsItem *focusItem = scene->focusItem();
- bool clear = true;
- if (isWidget && !focusItem->isPanel() && q_ptr->isAncestorOf(focusItem)) {
- do {
- if (focusItem == q_ptr) {
- clear = !static_cast<QGraphicsWidget *>(q_ptr)->focusNextPrevChild(true);
- break;
- }
- } while ((focusItem = focusItem->parentWidget()) && !focusItem->isPanel());
+ if (scene) {
+ if (scene->mouseGrabberItem() == q_ptr)
+ q_ptr->ungrabMouse();
+ if (q_ptr->hasFocus()) {
+ // Disabling the closest non-panel ancestor of the focus item
+ // causes focus to pop to the next item, otherwise it's cleared.
+ QGraphicsItem *focusItem = scene->focusItem();
+ bool clear = true;
+ if (isWidget && !focusItem->isPanel() && q_ptr->isAncestorOf(focusItem)) {
+ do {
+ if (focusItem == q_ptr) {
+ clear = !static_cast<QGraphicsWidget *>(q_ptr)->focusNextPrevChild(true);
+ break;
+ }
+ } while ((focusItem = focusItem->parentWidget()) && !focusItem->isPanel());
+ }
+ if (clear)
+ q_ptr->clearFocus();
}
- if (clear)
- q_ptr->clearFocus();
}
if (q_ptr->isSelected())
q_ptr->setSelected(false);
@@ -2699,7 +2649,7 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo
if (update)
q_ptr->update();
- foreach (QGraphicsItem *child, children) {
+ for (QGraphicsItem *child : std::as_const(children)) {
if (!newEnabled || !child->d_ptr->explicitlyDisabled)
child->d_ptr->setEnabledHelper(newEnabled, /* explicitly = */ false);
}
@@ -2728,7 +2678,7 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo
If you disable a parent item, all its children will also be disabled. If
you enable a parent item, all children will be enabled, unless they have
been explicitly disabled (i.e., if you call setEnabled(false) on a child,
- it will not be reenabled if its parent is disabled, and then enabled
+ it will not be re-enabled if its parent is disabled, and then enabled
again).
Items are enabled by default.
@@ -3021,7 +2971,7 @@ QRectF QGraphicsItemPrivate::effectiveBoundingRect(const QRectF &rect) const
Returns the effective bounding rect of the item.
If the item has no effect, this is the same as the item's bounding rect.
If the item has an effect, the effective rect can be larger than the item's
- bouding rect, depending on the effect.
+ bounding rect, depending on the effect.
\sa boundingRect()
*/
@@ -3140,7 +3090,7 @@ Qt::MouseButtons QGraphicsItem::acceptedMouseButtons() const
mouse events to the first item beneath it that does.
To disable mouse events for an item (i.e., make it transparent for mouse
- events), call setAcceptedMouseButtons(0).
+ events), call setAcceptedMouseButtons(Qt::NoButton).
\sa acceptedMouseButtons(), mousePressEvent()
*/
@@ -3169,12 +3119,6 @@ bool QGraphicsItem::acceptHoverEvents() const
return d_ptr->acceptsHover;
}
-/*!
- \fn bool QGraphicsItem::acceptsHoverEvents() const
- \obsolete
-
- Call acceptHoverEvents() instead.
-*/
/*!
\since 4.4
@@ -3218,13 +3162,6 @@ void QGraphicsItem::setAcceptHoverEvents(bool enabled)
}
}
-/*!
- \fn void QGraphicsItem::setAcceptsHoverEvents(bool enabled)
- \obsolete
-
- Use setAcceptHoverEvents(\a enabled) instead.
-*/
-
/*! \since 4.6
Returns \c true if an item accepts \l{QTouchEvent}{touch events};
@@ -3275,7 +3212,7 @@ bool QGraphicsItem::filtersChildEvents() const
\since 4.6
If \a enabled is true, this item is set to filter all events for
- all its children (i.e., all events intented for any of its
+ all its children (i.e., all events intended for any of its
children are instead sent to this item); otherwise, if \a enabled
is false, this item will only handle its own events. The default
value is false.
@@ -3292,7 +3229,7 @@ void QGraphicsItem::setFiltersChildEvents(bool enabled)
}
/*!
- \obsolete
+ \deprecated
Returns \c true if this item handles child events (i.e., all events
intended for any of its children are instead sent to this item);
@@ -3314,10 +3251,10 @@ bool QGraphicsItem::handlesChildEvents() const
}
/*!
- \obsolete
+ \deprecated
If \a enabled is true, this item is set to handle all events for
- all its children (i.e., all events intented for any of its
+ all its children (i.e., all events intended for any of its
children are instead sent to this item); otherwise, if \a enabled
is false, this item will only handle its own events. The default
value is false.
@@ -3979,7 +3916,7 @@ void QGraphicsItem::ensureVisible(const QRectF &rect, int xmargin, int ymargin)
sceneRect = sceneTransform().mapRect(rect);
else
sceneRect = sceneBoundingRect();
- foreach (QGraphicsView *view, d_ptr->scene->d_func()->views)
+ for (QGraphicsView *view : std::as_const(d_ptr->scene->d_func()->views))
view->ensureVisible(sceneRect, xmargin, ymargin);
}
}
@@ -3992,24 +3929,6 @@ void QGraphicsItem::ensureVisible(const QRectF &rect, int xmargin, int ymargin)
ensureVisible(QRectF(\a x, \a y, \a w, \a h), \a xmargin, \a ymargin).
*/
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \obsolete
-
- Returns the item's affine transformation matrix. This is a subset or the
- item's full transformation matrix, and might not represent the item's full
- transformation.
-
- Use transform() instead.
-
- \sa setTransform(), sceneTransform()
-*/
-QMatrix QGraphicsItem::matrix() const
-{
- return transform().toAffine();
-}
-#endif
-
/*!
\since 4.3
@@ -4318,22 +4237,6 @@ void QGraphicsItem::setTransformOriginPoint(const QPointF &origin)
\sa setTransformOriginPoint(), {Transformations}
*/
-
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \obsolete
-
- Use sceneTransform() instead.
-
- \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System}
-*/
-QMatrix QGraphicsItem::sceneMatrix() const
-{
- d_ptr->ensureSceneTransform();
- return d_ptr->sceneTransform.toAffine();
-}
-#endif
-
/*!
\since 4.3
@@ -4347,7 +4250,8 @@ QMatrix QGraphicsItem::sceneMatrix() const
\snippet code/src_gui_graphicsview_qgraphicsitem.cpp 4
Unlike transform(), which returns only an item's local transformation, this
- function includes the item's (and any parents') position, and all the transfomation properties.
+ function includes the item's (and any parents') position, and all the
+ transformation properties.
\sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System}, {Transformations}
*/
@@ -4544,50 +4448,6 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co
return x;
}
-#if QT_DEPRECATED_SINCE(5, 13)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
-/*!
- \obsolete
-
- Sets the item's affine transformation matrix. This is a subset or the
- item's full transformation matrix, and might not represent the item's full
- transformation.
-
- Use setTransform() instead.
-
- \sa transform(), {The Graphics View Coordinate System}
-*/
-void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine)
-{
- if (!d_ptr->transformData)
- d_ptr->transformData = new QGraphicsItemPrivate::TransformData;
-
- QTransform newTransform(combine ? QTransform(matrix) * d_ptr->transformData->transform : QTransform(matrix));
- if (d_ptr->transformData->transform == newTransform)
- return;
-
- // Update and set the new transformation.
- if (!(d_ptr->flags & ItemSendsGeometryChanges)) {
- d_ptr->setTransformHelper(newTransform);
- return;
- }
-
- // Notify the item that the transformation matrix is changing.
- const QVariant newMatrixVariant = QVariant::fromValue<QMatrix>(newTransform.toAffine());
- newTransform = QTransform(qvariant_cast<QMatrix>(itemChange(ItemMatrixChange, newMatrixVariant)));
- if (d_ptr->transformData->transform == newTransform)
- return;
-
- // Update and set the new transformation.
- d_ptr->setTransformHelper(newTransform);
-
- // Send post-notification.
- itemChange(ItemTransformHasChanged, QVariant::fromValue<QTransform>(newTransform));
-}
-QT_WARNING_POP
-#endif
-
/*!
\since 4.3
@@ -4600,7 +4460,7 @@ QT_WARNING_POP
To simplify interaction with items using a transformed view, QGraphicsItem
provides mapTo... and mapFrom... functions that can translate between
items' and the scene's coordinates. For example, you can call mapToScene()
- to map an item coordiate to a scene coordinate, or mapFromScene() to map
+ to map an item coordinate to a scene coordinate, or mapFromScene() to map
from scene coordinates to item coordinates.
The transformation matrix is combined with the item's rotation(), scale()
@@ -4641,18 +4501,6 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine)
d_ptr->sendScenePosChange();
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \obsolete
-
- Use resetTransform() instead.
-*/
-void QGraphicsItem::resetMatrix()
-{
- resetTransform();
-}
-#endif
-
/*!
\since 4.3
@@ -4668,81 +4516,6 @@ void QGraphicsItem::resetTransform()
}
/*!
- \fn void QGraphicsItem::rotate(qreal angle)
- \obsolete
-
- Use
-
- \snippet code/src_gui_graphicsview_qgraphicsitem.cpp 20
-
- instead.
-
- Rotates the current item transformation \a angle degrees clockwise around
- its origin. To translate around an arbitrary point (x, y), you need to
- combine translation and rotation with setTransform().
-
- Example:
-
- \snippet code/src_gui_graphicsview_qgraphicsitem.cpp 6
-
- \sa setTransform(), transform(), scale(), shear(), translate()
-*/
-
-/*!
- \fn void QGraphicsItem::scale(qreal sx, qreal sy)
- \obsolete
-
- Use
-
- \snippet code/src_gui_graphicsview_qgraphicsitem.cpp 21
-
- instead.
-
- Scales the current item transformation by (\a sx, \a sy) around its
- origin. To scale from an arbitrary point (x, y), you need to combine
- translation and scaling with setTransform().
-
- Example:
-
- \snippet code/src_gui_graphicsview_qgraphicsitem.cpp 7
-
- \sa setTransform(), transform()
-*/
-
-/*!
- \fn void QGraphicsItem::shear(qreal sh, qreal sv)
- \obsolete
-
- Use
-
- \snippet code/src_gui_graphicsview_qgraphicsitem.cpp 22
-
- instead.
-
- Shears the current item transformation by (\a sh, \a sv).
-
- \sa setTransform(), transform()
-*/
-
-/*!
- \fn void QGraphicsItem::translate(qreal dx, qreal dy)
- \obsolete
-
- Use setPos() or setTransformOriginPoint() instead. For identical
- behavior, use
-
- \snippet code/src_gui_graphicsview_qgraphicsitem.cpp 23
-
- Translates the current item transformation by (\a dx, \a dy).
-
- If all you want is to move an item, you should call moveBy() or
- setPos() instead; this function changes the item's translation,
- which is conceptually separate from its position.
-
- \sa setTransform(), transform()
-*/
-
-/*!
This virtual function is called twice for all items by the
QGraphicsScene::advance() slot. In the first phase, all items are called
with \a phase == 0, indicating that items on the scene are about to
@@ -4853,7 +4626,7 @@ inline void QGraphicsItemPrivate::sendScenePosChange()
if (flags & QGraphicsItem::ItemSendsScenePositionChanges)
q->itemChange(QGraphicsItem::ItemScenePositionHasChanged, q->scenePos());
if (scenePosDescendants) {
- foreach (QGraphicsItem *item, scene->d_func()->scenePosItems) {
+ for (QGraphicsItem *item : std::as_const(scene->d_func()->scenePosItems)) {
if (q->isAncestorOf(item))
item->itemChange(QGraphicsItem::ItemScenePositionHasChanged, item->scenePos());
}
@@ -5157,7 +4930,7 @@ bool QGraphicsItem::contains(const QPointF &point) const
The default implementation is based on shape intersection, and it calls
shape() on both items. Because the complexity of arbitrary shape-shape
intersection grows with an order of magnitude when the shapes are complex,
- this operation can be noticably time consuming. You have the option of
+ this operation can be noticeably time-consuming. You have the option of
reimplementing this function in a subclass of QGraphicsItem to provide a
custom algorithm. This allows you to make use of natural constraints in
the shapes of your own items, in order to improve the performance of the
@@ -5227,7 +5000,7 @@ bool QGraphicsItem::collidesWithPath(const QPainterPath &path, Qt::ItemSelection
_q_adjustRect(&rectB);
if (!rectA.intersects(rectB)) {
// This we can determine efficiently. If the two rects neither
- // intersect nor contain eachother, then the two items do not collide.
+ // intersect nor contain each other, then the two items do not collide.
return false;
}
@@ -5488,7 +5261,7 @@ void QGraphicsItem::setBoundingRegionGranularity(qreal granularity)
/*!
\fn virtual void QGraphicsItem::paint(QPainter *painter, const
- QStyleOptionGraphicsItem *option, QWidget *widget = 0) = 0
+ QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) = 0
This function, which is usually called by QGraphicsView, paints the
contents of an item in local coordinates.
@@ -6728,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
@@ -7221,7 +6994,7 @@ void QGraphicsItem::keyReleaseEvent(QKeyEvent *event)
If you do reimplement this function, \a event will by default be
accepted (see QEvent::accept()), and this item is then the mouse
grabber. This allows the item to receive future move, release and
- doubleclick events. If you call QEvent::ignore() on \a event, this
+ double-click events. If you call QEvent::ignore() on \a event, this
item will lose the mouse grab, and \a event will propagate to any
topmost item beneath. No further mouse events will be delivered to
this item unless a new mouse press event is received.
@@ -7309,7 +7082,7 @@ void QGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
selectedItems = d_ptr->scene->selectedItems();
initialPositions = d_ptr->scene->d_func()->movingItemsInitialPositions;
if (initialPositions.isEmpty()) {
- for (QGraphicsItem *item : qAsConst(selectedItems))
+ for (QGraphicsItem *item : std::as_const(selectedItems))
initialPositions[item] = item->pos();
initialPositions[this] = pos();
}
@@ -7343,14 +7116,14 @@ void QGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
if ((item->flags() & ItemIsMovable) && !QGraphicsItemPrivate::movableAncestorIsSelected(item)) {
QPointF currentParentPos;
QPointF buttonDownParentPos;
- if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations) {
+ if (view && (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations)) {
// Items whose ancestors ignore transformations need to
// map screen coordinates to local coordinates, then map
// those to the parent.
QTransform viewToItemTransform = (item->deviceTransform(view->viewportTransform())).inverted();
currentParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->screenPos()))));
buttonDownParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton)))));
- } else if (item->flags() & ItemIgnoresTransformations) {
+ } else if (view && (item->flags() & ItemIgnoresTransformations)) {
// Root items that ignore transformations need to
// calculate their diff by mapping viewport coordinates
// directly to parent coordinates.
@@ -7418,7 +7191,7 @@ void QGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
// temporarily removing this item from the selection list.
if (d_ptr->selected) {
scene->d_func()->selectedItems.remove(this);
- foreach (QGraphicsItem *item, scene->d_func()->selectedItems) {
+ for (QGraphicsItem *item : std::as_const(scene->d_func()->selectedItems)) {
if (item->isSelected()) {
selectionChanged = true;
break;
@@ -7442,11 +7215,11 @@ void QGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
/*!
This event handler, for event \a event, can be reimplemented to
- receive mouse doubleclick events for this item.
+ receive mouse double-click events for this item.
When doubleclicking an item, the item will first receive a mouse
press event, followed by a release event (i.e., a click), then a
- doubleclick event, and finally a release event.
+ double-click event, and finally a release event.
Calling QEvent::ignore() or QEvent::accept() on \a event has no
effect.
@@ -7716,11 +7489,8 @@ void QGraphicsItem::prepareGeometryChange()
\internal
Highlights \a item as selected.
-
- NOTE: This function is a duplicate of qt_graphicsItem_highlightSelected() in
- qgraphicssvgitem.cpp!
*/
-static void qt_graphicsItem_highlightSelected(
+void Q_WIDGETS_EXPORT qt_graphicsItem_highlightSelected(
QGraphicsItem *item, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
const QRectF murect = painter->transform().mapRect(QRectF(0, 0, 1, 1));
@@ -7879,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.count();
-}
-
-QGraphicsObject *QGraphicsItemPrivate::children_at(QDeclarativeListProperty<QGraphicsObject> *list, int index)
-{
- QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object));
- if (index >= 0 && index < d->children.count())
- 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.count();
- 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
@@ -8108,7 +7818,7 @@ void QGraphicsItemPrivate::resetHeight()
/*!
\property QGraphicsObject::rotation
- This property holds the rotation of the item in degrees.
+ \brief the rotation of the item in degrees.
This specifies how many degrees to rotate the item around its transformOrigin.
The default rotation is 0 degrees (i.e. not rotated at all).
@@ -8117,12 +7827,12 @@ void QGraphicsItemPrivate::resetHeight()
/*!
\fn QGraphicsObject::rotationChanged()
- This signal gets emitted whenever the roation of the item changes.
+ This signal gets emitted whenever the rotation of the item changes.
*/
/*!
\property QGraphicsObject::scale
- This property holds the scale of the item.
+ \brief the scale of the item.
A scale of less than 1 means the item will be displayed smaller than
normal, and a scale of greater than 1 means the item will be
@@ -8156,7 +7866,7 @@ void QGraphicsItemPrivate::resetHeight()
/*!
\fn void QGraphicsObject::enabledChanged()
- This signal gets emitted whenever the item get's enabled or disabled.
+ This signal gets emitted whenever the item gets enabled or disabled.
\sa isEnabled()
*/
@@ -8184,7 +7894,7 @@ void QGraphicsItemPrivate::resetHeight()
\property QGraphicsObject::transformOriginPoint
\brief the transformation origin
- This property sets a specific point in the items coordiante system as the
+ This property sets a specific point in the item's coordinate system as the
origin for scale and rotation.
\sa scale, rotation, QGraphicsItem::transformOriginPoint()
@@ -9780,9 +9490,9 @@ QRectF QGraphicsPixmapItem::boundingRect() const
return QRectF();
if (d->flags & ItemIsSelectable) {
qreal pw = 1.0;
- return QRectF(d->offset, QSizeF(d->pixmap.size()) / d->pixmap.devicePixelRatio()).adjusted(-pw/2, -pw/2, pw/2, pw/2);
+ return QRectF(d->offset, d->pixmap.deviceIndependentSize()).adjusted(-pw/2, -pw/2, pw/2, pw/2);
} else {
- return QRectF(d->offset, QSizeF(d->pixmap.size()) / d->pixmap.devicePixelRatio());
+ return QRectF(d->offset, d->pixmap.deviceIndependentSize());
}
}
@@ -10287,6 +9997,7 @@ bool QGraphicsTextItem::sceneEvent(QEvent *event)
case QEvent::GraphicsSceneMouseRelease:
case QEvent::KeyPress:
case QEvent::KeyRelease:
+ case QEvent::InputMethod:
// Reset the focus widget's input context, regardless
// of how this item gained or lost focus.
if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) {
@@ -10502,18 +10213,22 @@ void QGraphicsTextItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
QVariant QGraphicsTextItem::inputMethodQuery(Qt::InputMethodQuery query) const
{
QVariant v;
- if (query == Qt::ImHints)
+ if (query == Qt::ImEnabled)
+ return isEnabled();
+ else if (query == Qt::ImHints)
v = int(inputMethodHints());
else if (dd->control)
v = dd->control->inputMethodQuery(query, QVariant());
- if (v.type() == QVariant::RectF)
- v = v.toRectF().translated(-dd->controlOffset());
- else if (v.type() == QVariant::PointF)
- v = v.toPointF() - dd->controlOffset();
- else if (v.type() == QVariant::Rect)
- v = v.toRect().translated(-dd->controlOffset().toPoint());
- else if (v.type() == QVariant::Point)
- v = v.toPoint() - dd->controlOffset().toPoint();
+ if (dd->control) {
+ if (v.userType() == QMetaType::QRectF)
+ v = v.toRectF().translated(-dd->controlOffset());
+ else if (v.userType() == QMetaType::QPointF)
+ v = v.toPointF() - dd->controlOffset();
+ else if (v.userType() == QMetaType::QRect)
+ v = v.toRect().translated(-dd->controlOffset().toPoint());
+ else if (v.userType() == QMetaType::QPoint)
+ v = v.toPoint() - dd->controlOffset().toPoint();
+ }
return v;
}
@@ -10588,16 +10303,16 @@ QWidgetTextControl *QGraphicsTextItemPrivate::textControl() const
control = new QWidgetTextControl(that);
control->setTextInteractionFlags(Qt::NoTextInteraction);
- QObject::connect(control, SIGNAL(updateRequest(QRectF)),
- qq, SLOT(_q_update(QRectF)));
- QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)),
- qq, SLOT(_q_updateBoundingRect(QSizeF)));
- QObject::connect(control, SIGNAL(visibilityRequest(QRectF)),
- qq, SLOT(_q_ensureVisible(QRectF)));
- QObject::connect(control, SIGNAL(linkActivated(QString)),
- qq, SIGNAL(linkActivated(QString)));
- QObject::connect(control, SIGNAL(linkHovered(QString)),
- qq, SIGNAL(linkHovered(QString)));
+ QObject::connect(control, &QWidgetTextControl::updateRequest, qq,
+ [dd = that->dd](const QRectF &rect) { dd->_q_update(rect); });
+ QObject::connect(control, &QWidgetTextControl::documentSizeChanged, qq,
+ [dd = that->dd](QSizeF size) { dd->_q_updateBoundingRect(size); });
+ QObject::connect(control, &QWidgetTextControl::visibilityRequest, qq,
+ [dd = that->dd](const QRectF &rect) { dd->_q_ensureVisible(rect); });
+ QObject::connect(control, &QWidgetTextControl::linkActivated, qq,
+ &QGraphicsTextItem::linkActivated);
+ QObject::connect(control, &QWidgetTextControl::linkHovered, qq,
+ &QGraphicsTextItem::linkHovered);
const QSizeF pgSize = control->document()->pageSize();
if (pgSize.height() != -1) {
@@ -10800,7 +10515,7 @@ void QGraphicsSimpleTextItemPrivate::updateBoundingRect()
br = QRectF();
} else {
QString tmp = text;
- tmp.replace(QLatin1Char('\n'), QChar::LineSeparator);
+ tmp.replace(u'\n', QChar::LineSeparator);
QStackTextEngine engine(tmp, font);
QTextLayout layout(&engine);
br = setupTextLayout(&layout);
@@ -10961,7 +10676,7 @@ void QGraphicsSimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphic
painter->setFont(d->font);
QString tmp = d->text;
- tmp.replace(QLatin1Char('\n'), QChar::LineSeparator);
+ tmp.replace(u'\n', QChar::LineSeparator);
QStackTextEngine engine(tmp, d->font);
QTextLayout layout(&engine);
@@ -10973,9 +10688,9 @@ void QGraphicsSimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphic
} else {
QTextLayout::FormatRange range;
range.start = 0;
- range.length = layout.text().length();
+ range.length = layout.text().size();
range.format.setTextOutline(d->pen);
- layout.setFormats(QVector<QTextLayout::FormatRange>(1, range));
+ layout.setFormats(QList<QTextLayout::FormatRange>(1, range));
}
setupTextLayout(&layout);
@@ -11391,7 +11106,7 @@ QPixmap QGraphicsItemEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QP
if (effectRect.isEmpty())
return QPixmap();
- const auto dpr = info ? info->painter->device()->devicePixelRatioF() : 1.0;
+ const auto dpr = info ? info->painter->device()->devicePixelRatio() : 1.0;
QPixmap pixmap(QRectF(effectRectF.topLeft(), effectRectF.size() * dpr).toAlignedRect().size());
pixmap.setDevicePixelRatio(dpr);
pixmap.fill(Qt::transparent);
@@ -11442,8 +11157,7 @@ static void formatGraphicsItemHelper(QDebug debug, const QGraphicsItem *item)
debug << ", flags=" << item->flags();
}
-// FIXME: Qt 6: Make this QDebug operator<<(QDebug debug, const QGraphicsItem *item)
-QDebug operator<<(QDebug debug, QGraphicsItem *item)
+QDebug operator<<(QDebug debug, const QGraphicsItem *item)
{
QDebugStateSaver saver(debug);
debug.nospace();
@@ -11453,7 +11167,7 @@ QDebug operator<<(QDebug debug, QGraphicsItem *item)
return debug;
}
- if (QGraphicsObject *o = item->toGraphicsObject())
+ if (const QGraphicsObject *o = item->toGraphicsObject())
debug << o->metaObject()->className();
else
debug << "QGraphicsItem";
@@ -11474,8 +11188,7 @@ QDebug operator<<(QDebug debug, QGraphicsItem *item)
return debug;
}
-// FIXME: Qt 6: Make this QDebug operator<<(QDebug debug, const QGraphicsObject *item)
-QDebug operator<<(QDebug debug, QGraphicsObject *item)
+QDebug operator<<(QDebug debug, const QGraphicsObject *item)
{
QDebugStateSaver saver(debug);
debug.nospace();
@@ -11521,14 +11234,6 @@ QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change)
case QGraphicsItem::ItemFlagsHaveChanged:
str = "ItemFlagsHaveChanged";
break;
-#if QT_DEPRECATED_SINCE(5, 14)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- case QGraphicsItem::ItemMatrixChange:
- str = "ItemMatrixChange";
- break;
-QT_WARNING_POP
-#endif
case QGraphicsItem::ItemParentChange:
str = "ItemParentChange";
break;
diff --git a/src/widgets/graphicsview/qgraphicsitem.h b/src/widgets/graphicsview/qgraphicsitem.h
index d66a4917e5..f82c600b3a 100644
--- a/src/widgets/graphicsview/qgraphicsitem.h
+++ b/src/widgets/graphicsview/qgraphicsitem.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSITEM_H
#define QGRAPHICSITEM_H
@@ -71,7 +35,6 @@ class QGraphicsTransform;
class QGraphicsWidget;
class QInputMethodEvent;
class QKeyEvent;
-class QMatrix;
class QMenu;
class QPainter;
class QPen;
@@ -110,9 +73,6 @@ public:
enum GraphicsItemChange {
ItemPositionChange,
-#if QT_DEPRECATED_SINCE(5, 14)
- ItemMatrixChange Q_DECL_ENUMERATOR_DEPRECATED_X("Use ItemTransformChange instead"),
-#endif
ItemVisibleChange = 2,
ItemEnabledChange,
ItemSelectedChange,
@@ -173,9 +133,6 @@ public:
QGraphicsWidget *window() const;
QGraphicsItem *panel() const;
void setParentItem(QGraphicsItem *parent);
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline QList<QGraphicsItem *> children() const { return childItems(); }
-#endif
QList<QGraphicsItem *> childItems() const;
bool isWidget() const;
bool isWindow() const;
@@ -198,7 +155,7 @@ public:
void setPanelModality(PanelModality panelModality);
bool isBlockedByModalPanel(QGraphicsItem **blockingPanel = nullptr) const;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
QString toolTip() const;
void setToolTip(const QString &toolTip);
#endif
@@ -237,10 +194,6 @@ public:
Qt::MouseButtons acceptedMouseButtons() const;
void setAcceptedMouseButtons(Qt::MouseButtons buttons);
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline bool acceptsHoverEvents() const { return acceptHoverEvents(); }
- QT_DEPRECATED inline void setAcceptsHoverEvents(bool enabled) { setAcceptHoverEvents(enabled); }
-#endif
bool acceptHoverEvents() const;
void setAcceptHoverEvents(bool enabled);
bool acceptTouchEvents() const;
@@ -285,28 +238,12 @@ public:
inline void ensureVisible(qreal x, qreal y, qreal w, qreal h, int xmargin = 50, int ymargin = 50);
// Local transformation
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use transform() instead")
- QMatrix matrix() const;
- QT_DEPRECATED_X("Use sceneTransform() instead")
- QMatrix sceneMatrix() const;
- QT_DEPRECATED_X("Use setTransform() instead")
- void setMatrix(const QMatrix &matrix, bool combine = false);
- QT_DEPRECATED_X("Use resetTransform() instead")
- void resetMatrix();
-#endif
QTransform transform() const;
QTransform sceneTransform() const;
QTransform deviceTransform(const QTransform &viewportTransform) const;
QTransform itemTransform(const QGraphicsItem *other, bool *ok = nullptr) const;
void setTransform(const QTransform &matrix, bool combine = false);
void resetTransform();
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline void rotate(qreal angle) { setTransform(QTransform().rotate(angle), true); }
- QT_DEPRECATED inline void scale(qreal sx, qreal sy) { setTransform(QTransform::fromScale(sx, sy), true); }
- QT_DEPRECATED inline void shear(qreal sh, qreal sv) { setTransform(QTransform().shear(sh, sv), true); }
- QT_DEPRECATED inline void translate(qreal dx, qreal dy) { setTransform(QTransform::fromTranslate(dx, dy), true); }
-#endif
void setRotation(qreal angle);
qreal rotation() const;
@@ -495,7 +432,7 @@ private:
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsItem::GraphicsItemFlags)
-#ifndef Q_CLANG_QDOC
+#ifndef Q_QDOC
Q_DECLARE_INTERFACE(QGraphicsItem, "org.qt-project.Qt.QGraphicsItem")
#endif
@@ -548,7 +485,8 @@ inline QRectF QGraphicsItem::mapRectFromScene(qreal ax, qreal ay, qreal w, qreal
class Q_WIDGETS_EXPORT QGraphicsObject : public QObject, public QGraphicsItem
{
Q_OBJECT
- Q_PROPERTY(QGraphicsObject* parent READ parentObject WRITE setParentItem NOTIFY parentChanged DESIGNABLE false)
+ Q_PROPERTY(QGraphicsObject* parent READ parentObject WRITE setParentItem NOTIFY parentChanged
+ DESIGNABLE false)
Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged FINAL)
Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged)
Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged FINAL)
@@ -562,10 +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_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_INTERFACES(QGraphicsItem)
public:
explicit QGraphicsObject(QGraphicsItem *parent = nullptr);
@@ -964,9 +902,6 @@ protected:
private:
Q_DISABLE_COPY(QGraphicsTextItem)
- Q_PRIVATE_SLOT(dd, void _q_updateBoundingRect(const QSizeF &))
- Q_PRIVATE_SLOT(dd, void _q_update(QRectF))
- Q_PRIVATE_SLOT(dd, void _q_ensureVisible(QRectF))
QGraphicsTextItemPrivate *dd;
friend class QGraphicsTextItemPrivate;
};
@@ -1035,19 +970,19 @@ template <class T> inline T qgraphicsitem_cast(QGraphicsItem *item)
{
typedef typename std::remove_cv<typename std::remove_pointer<T>::type>::type Item;
return int(Item::Type) == int(QGraphicsItem::Type)
- || (item && int(Item::Type) == item->type()) ? static_cast<T>(item) : 0;
+ || (item && int(Item::Type) == item->type()) ? static_cast<T>(item) : nullptr;
}
template <class T> inline T qgraphicsitem_cast(const QGraphicsItem *item)
{
typedef typename std::remove_cv<typename std::remove_pointer<T>::type>::type Item;
return int(Item::Type) == int(QGraphicsItem::Type)
- || (item && int(Item::Type) == item->type()) ? static_cast<T>(item) : 0;
+ || (item && int(Item::Type) == item->type()) ? static_cast<T>(item) : nullptr;
}
#ifndef QT_NO_DEBUG_STREAM
-Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem *item);
-Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, QGraphicsObject *item);
+Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, const QGraphicsItem *item);
+Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, const QGraphicsObject *item);
Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change);
Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag);
Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlags flags);
@@ -1055,10 +990,6 @@ Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag
QT_END_NAMESPACE
-Q_DECLARE_METATYPE(QGraphicsItem *)
-
-QT_BEGIN_NAMESPACE
-
-QT_END_NAMESPACE
+QT_DECL_METATYPE_EXTERN_TAGGED(QGraphicsItem*, QGraphicsItem_ptr, Q_WIDGETS_EXPORT)
#endif // QGRAPHICSITEM_H
diff --git a/src/widgets/graphicsview/qgraphicsitem_p.h b/src/widgets/graphicsview/qgraphicsitem_p.h
index 92d85f7125..bf6ebb96a2 100644
--- a/src/widgets/graphicsview/qgraphicsitem_p.h
+++ b/src/widgets/graphicsview/qgraphicsitem_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSITEM_P_H
#define QGRAPHICSITEM_P_H
@@ -67,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 = 0, AtFunction t = 0,
- ClearFunction r = 0)
- : 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:
@@ -144,7 +51,7 @@ public:
QHash<QPaintDevice *, DeviceData> deviceData;
// List of logical exposed rects
- QVector<QRectF> exposed;
+ QList<QRectF> exposed;
bool allExposed;
// Empty cache
@@ -226,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);
@@ -289,7 +195,7 @@ public:
}
struct ExtraStruct {
- ExtraStruct() {} // for QVector, don't use
+ ExtraStruct() { } // for QList, don't use
ExtraStruct(Extra type, const QVariant &value)
: type(type), value(value)
{ }
@@ -301,7 +207,7 @@ public:
{ return type < extra; }
};
- QVector<ExtraStruct> extras;
+ QList<ExtraStruct> extras;
QGraphicsItemCache *maybeExtraItemCache() const;
QGraphicsItemCache *extraItemCache() const;
@@ -414,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);
@@ -514,16 +415,15 @@ 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;
QGraphicsItem *q_ptr;
};
-Q_DECLARE_TYPEINFO(QGraphicsItemPrivate::ExtraStruct, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QGraphicsItemPrivate::ExtraStruct, Q_RELOCATABLE_TYPE);
struct QGraphicsItemPrivate::TransformData
{
@@ -624,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/qgraphicsitemanimation.cpp b/src/widgets/graphicsview/qgraphicsitemanimation.cpp
index 1c5dbf265c..23dd9fcc7d 100644
--- a/src/widgets/graphicsview/qgraphicsitemanimation.cpp
+++ b/src/widgets/graphicsview/qgraphicsitemanimation.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsItemAnimation
@@ -87,7 +51,6 @@
#include <QtCore/qpoint.h>
#include <QtCore/qpointer.h>
#include <QtCore/qpair.h>
-#include <QtGui/qmatrix.h>
#include <algorithm>
@@ -127,22 +90,23 @@ public:
qreal step;
qreal value;
};
- QVector<Pair> xPosition;
- QVector<Pair> yPosition;
- QVector<Pair> rotation;
- QVector<Pair> verticalScale;
- QVector<Pair> horizontalScale;
- QVector<Pair> verticalShear;
- QVector<Pair> horizontalShear;
- QVector<Pair> xTranslation;
- QVector<Pair> yTranslation;
-
- qreal linearValueForStep(qreal step, const QVector<Pair> &source, qreal defaultValue = 0);
- void insertUniquePair(qreal step, qreal value, QVector<Pair> *binList, const char* method);
+ QList<Pair> xPosition;
+ QList<Pair> yPosition;
+ QList<Pair> rotation;
+ QList<Pair> verticalScale;
+ QList<Pair> horizontalScale;
+ QList<Pair> verticalShear;
+ QList<Pair> horizontalShear;
+ QList<Pair> xTranslation;
+ QList<Pair> yTranslation;
+
+ qreal linearValueForStep(qreal step, const QList<Pair> &source, qreal defaultValue = 0);
+ void insertUniquePair(qreal step, qreal value, QList<Pair> *binList, const char *method);
};
Q_DECLARE_TYPEINFO(QGraphicsItemAnimationPrivate::Pair, Q_PRIMITIVE_TYPE);
-qreal QGraphicsItemAnimationPrivate::linearValueForStep(qreal step, const QVector<Pair> &source, qreal defaultValue)
+qreal QGraphicsItemAnimationPrivate::linearValueForStep(qreal step, const QList<Pair> &source,
+ qreal defaultValue)
{
if (source.isEmpty())
return defaultValue;
@@ -172,14 +136,15 @@ qreal QGraphicsItemAnimationPrivate::linearValueForStep(qreal step, const QVecto
return valueBefore + (valueAfter - valueBefore) * ((step - stepBefore) / (stepAfter - stepBefore));
}
-void QGraphicsItemAnimationPrivate::insertUniquePair(qreal step, qreal value, QVector<Pair> *binList, const char* method)
+void QGraphicsItemAnimationPrivate::insertUniquePair(qreal step, qreal value, QList<Pair> *binList,
+ const char *method)
{
if (!check_step_valid(step, method))
return;
const Pair pair = { step, value };
- const QVector<Pair>::iterator result = std::lower_bound(binList->begin(), binList->end(), pair);
+ const QList<Pair>::iterator result = std::lower_bound(binList->begin(), binList->end(), pair);
if (result == binList->end() || pair < *result)
binList->insert(result, pair);
else
@@ -294,19 +259,6 @@ QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::posList() const
return list;
}
-#if QT_DEPRECATED_SINCE(5, 14)
-/*!
- Returns the matrix used to transform the item at the specified \a step value.
-
- \obsolete Use transformAt() instead
-*/
-QMatrix QGraphicsItemAnimation::matrixAt(qreal step) const
-{
- check_step_valid(step, "matrixAt");
- return transformAt(step).toAffine();
-}
-#endif
-
/*!
Returns the transform used for the item at the specified \a step value.
@@ -564,23 +516,6 @@ void QGraphicsItemAnimation::setStep(qreal step)
afterAnimationStep(step);
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- Resets the item to its starting position and transformation.
-
- \obsolete
-
- You can call setStep(0) instead.
-*/
-void QGraphicsItemAnimation::reset()
-{
- if (!d->item)
- return;
- d->startPos = d->item->pos();
- d->startTransform = d->item->transform();
-}
-#endif
-
/*!
\fn void QGraphicsItemAnimation::beforeAnimationStep(qreal step)
diff --git a/src/widgets/graphicsview/qgraphicsitemanimation.h b/src/widgets/graphicsview/qgraphicsitemanimation.h
index 3051fb2e2b..5fb6484c74 100644
--- a/src/widgets/graphicsview/qgraphicsitemanimation.h
+++ b/src/widgets/graphicsview/qgraphicsitemanimation.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSITEMANIMATION_H
#define QGRAPHICSITEMANIMATION_H
@@ -48,11 +12,9 @@ QT_REQUIRE_CONFIG(graphicsview);
QT_BEGIN_NAMESPACE
class QGraphicsItem;
-class QMatrix;
class QPointF;
class QTimeLine;
class QTransform;
-template <class T1, class T2> struct QPair;
class QGraphicsItemAnimationPrivate;
class Q_WIDGETS_EXPORT QGraphicsItemAnimation : public QObject
@@ -72,10 +34,6 @@ public:
QList<QPair<qreal, QPointF> > posList() const;
void setPosAt(qreal step, const QPointF &pos);
-#if QT_DEPRECATED_SINCE(5, 14)
- QT_DEPRECATED_X("Use transformAt() instead")
- QMatrix matrixAt(qreal step) const;
-#endif
QTransform transformAt(qreal step) const;
qreal rotationAt(qreal step) const;
@@ -101,10 +59,6 @@ public:
public Q_SLOTS:
void setStep(qreal x);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use setStep(0) instead")
- void reset();
-#endif
protected:
virtual void beforeAnimationStep(qreal step);
diff --git a/src/widgets/graphicsview/qgraphicslayout.cpp b/src/widgets/graphicsview/qgraphicslayout.cpp
index 8b52b57580..672f78afb8 100644
--- a/src/widgets/graphicsview/qgraphicslayout.cpp
+++ b/src/widgets/graphicsview/qgraphicslayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qapplication.h"
@@ -146,7 +110,7 @@ QT_BEGIN_NAMESPACE
*/
/*!
- Contructs a QGraphicsLayout object.
+ Constructs a QGraphicsLayout object.
\a parent is passed to QGraphicsLayoutItem's constructor and the
QGraphicsLayoutItem's isLayout argument is set to \e true.
diff --git a/src/widgets/graphicsview/qgraphicslayout.h b/src/widgets/graphicsview/qgraphicslayout.h
index efcafa5e6a..b95a6b839f 100644
--- a/src/widgets/graphicsview/qgraphicslayout.h
+++ b/src/widgets/graphicsview/qgraphicslayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSLAYOUT_H
#define QGRAPHICSLAYOUT_H
@@ -83,7 +47,7 @@ private:
friend class QGraphicsWidget;
};
-#ifndef Q_CLANG_QDOC
+#ifndef Q_QDOC
Q_DECLARE_INTERFACE(QGraphicsLayout, "org.qt-project.Qt.QGraphicsLayout")
#endif
diff --git a/src/widgets/graphicsview/qgraphicslayout_p.cpp b/src/widgets/graphicsview/qgraphicslayout_p.cpp
index c10763d065..e902ed8612 100644
--- a/src/widgets/graphicsview/qgraphicslayout_p.cpp
+++ b/src/widgets/graphicsview/qgraphicslayout_p.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qglobal.h"
diff --git a/src/widgets/graphicsview/qgraphicslayout_p.h b/src/widgets/graphicsview/qgraphicslayout_p.h
index 0d91151e22..06eab2ba50 100644
--- a/src/widgets/graphicsview/qgraphicslayout_p.h
+++ b/src/widgets/graphicsview/qgraphicslayout_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSLAYOUT_P_H
#define QGRAPHICSLAYOUT_P_H
@@ -70,7 +34,7 @@ class QGraphicsWidget;
inline bool qt_graphicsLayoutDebug()
{
static int checked_env = -1;
- if(checked_env == -1)
+ if (checked_env == -1)
checked_env = !!qEnvironmentVariableIntValue("QT_GRAPHICSLAYOUT_DEBUG");
return checked_env;
}
@@ -87,8 +51,8 @@ public:
Q_ASSERT(style);
if (widget) //###
m_styleOption.initFrom(widget);
- m_defaultSpacing[0] = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing);
- m_defaultSpacing[1] = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing);
+ 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; }
@@ -103,11 +67,11 @@ public:
inline void setDefaultSpacing(Qt::Orientation o, qreal spacing){
if (spacing >= 0)
- m_defaultSpacing[o - 1] = spacing;
+ m_defaultSpacing[int(o) - 1] = spacing;
}
inline qreal defaultSpacing(Qt::Orientation o) const {
- return m_defaultSpacing[o - 1];
+ return m_defaultSpacing[int(o) - 1];
}
inline qreal perItemSpacing(QSizePolicy::ControlType control1,
diff --git a/src/widgets/graphicsview/qgraphicslayoutitem.cpp b/src/widgets/graphicsview/qgraphicslayoutitem.cpp
index 8694dcb36b..f6aad09810 100644
--- a/src/widgets/graphicsview/qgraphicslayoutitem.cpp
+++ b/src/widgets/graphicsview/qgraphicslayoutitem.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qglobal.h"
@@ -45,6 +9,7 @@
#include "qgraphicslayoutitem_p.h"
#include "qwidget.h"
#include "qgraphicswidget.h"
+#include "qgraphicsitem_p.h"
#include <QtDebug>
@@ -826,6 +791,26 @@ void QGraphicsLayoutItem::updateGeometry()
}
/*!
+ \since 6.0
+
+ Returns \c true if this item is empty, i.e whether it has no content and
+ should not occupy any space.
+
+ The default implementation returns \c true true if the item has been hidden,
+ unless its \l{sizePolicy()}{size policy} has retainSizeWhenHidden set to \c true
+
+ \sa sizePolicy()
+*/
+bool QGraphicsLayoutItem::isEmpty() const
+{
+ bool isHidden = false;
+ if (QGraphicsItem *item = graphicsItem())
+ isHidden = QGraphicsItemPrivate::get(item)->explicitlyHidden;
+
+ return isHidden && !sizePolicy().retainSizeWhenHidden();
+}
+
+/*!
Returns the parent of this QGraphicsLayoutItem, or \nullptr if there is
no parent, or if the parent does not inherit from QGraphicsLayoutItem
(QGraphicsLayoutItem is often used through multiple inheritance with
diff --git a/src/widgets/graphicsview/qgraphicslayoutitem.h b/src/widgets/graphicsview/qgraphicslayoutitem.h
index 86a0a87361..43194ee729 100644
--- a/src/widgets/graphicsview/qgraphicslayoutitem.h
+++ b/src/widgets/graphicsview/qgraphicslayoutitem.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSLAYOUTITEM_H
#define QGRAPHICSLAYOUTITEM_H
@@ -94,6 +58,7 @@ public:
virtual void updateGeometry();
+ virtual bool isEmpty() const;
QGraphicsLayoutItem *parentLayoutItem() const;
void setParentLayoutItem(QGraphicsLayoutItem *parent);
@@ -116,7 +81,7 @@ private:
friend class QGraphicsLayout;
};
-#ifndef Q_CLANG_QDOC
+#ifndef Q_QDOC
Q_DECLARE_INTERFACE(QGraphicsLayoutItem, "org.qt-project.Qt.QGraphicsLayoutItem")
#endif
diff --git a/src/widgets/graphicsview/qgraphicslayoutitem_p.h b/src/widgets/graphicsview/qgraphicslayoutitem_p.h
index 6aaa85381e..70fb82c78c 100644
--- a/src/widgets/graphicsview/qgraphicslayoutitem_p.h
+++ b/src/widgets/graphicsview/qgraphicslayoutitem_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSLAYOUTITEM_P_H
#define QGRAPHICSLAYOUTITEM_P_H
diff --git a/src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp b/src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp
index 2f1526cc78..6bd57470f3 100644
--- a/src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp
+++ b/src/widgets/graphicsview/qgraphicslayoutstyleinfo.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgraphicslayoutstyleinfo_p.h"
@@ -80,7 +44,9 @@ qreal QGraphicsLayoutStyleInfo::perItemSpacing(QLayoutPolicy::ControlType contro
qreal QGraphicsLayoutStyleInfo::spacing(Qt::Orientation orientation) const
{
Q_ASSERT(style());
- return style()->pixelMetric(orientation == Qt::Horizontal ? QStyle::PM_LayoutHorizontalSpacing : QStyle::PM_LayoutVerticalSpacing);
+ return style()->pixelMetric(orientation == Qt::Horizontal
+ ? QStyle::PM_LayoutHorizontalSpacing : QStyle::PM_LayoutVerticalSpacing,
+ &m_styleOption, widget());
}
qreal QGraphicsLayoutStyleInfo::windowMargin(Qt::Orientation orientation) const
diff --git a/src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h b/src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h
index 9807efb26e..a3c0c22606 100644
--- a/src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h
+++ b/src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSLAYOUTSTYLEINFO_P_H
#define QGRAPHICSLAYOUTSTYLEINFO_P_H
diff --git a/src/widgets/graphicsview/qgraphicslinearlayout.cpp b/src/widgets/graphicsview/qgraphicslinearlayout.cpp
index f76cc61586..04693734d2 100644
--- a/src/widgets/graphicsview/qgraphicslinearlayout.cpp
+++ b/src/widgets/graphicsview/qgraphicslinearlayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsLinearLayout
@@ -50,12 +14,16 @@
passing Qt::Vertical to QGraphicsLinearLayout's constructor.
The most common way to use QGraphicsLinearLayout is to construct an object
- on the heap with no parent, add widgets and layouts by calling addItem(),
- and finally assign the layout to a widget by calling
- QGraphicsWidget::setLayout().
+ on the heap, passing a parent widget to the constructor, then add widgets
+ and layouts by calling addItem().
\snippet code/src_gui_graphicsview_qgraphicslinearlayout.cpp 0
+ Alternatively, if you do not pass a parent widget to the layout's constructor,
+ you will need to call QGraphicsWidget::setLayout() to set this layout as the
+ top-level layout for that widget, the widget will take ownership of
+ the layout.
+
You can add widgets, layouts, stretches (addStretch(), insertStretch() or
setStretchFactor()), and spacings (setItemSpacing()) to a linear
layout. The layout takes ownership of the items. In some cases when the layout
diff --git a/src/widgets/graphicsview/qgraphicslinearlayout.h b/src/widgets/graphicsview/qgraphicslinearlayout.h
index d27191adb3..d71c64aa5f 100644
--- a/src/widgets/graphicsview/qgraphicslinearlayout.h
+++ b/src/widgets/graphicsview/qgraphicslinearlayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSLINEARLAYOUT_H
#define QGRAPHICSLINEARLAYOUT_H
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget.cpp b/src/widgets/graphicsview/qgraphicsproxywidget.cpp
index 4d4958c674..1ff4814142 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget.cpp
+++ b/src/widgets/graphicsview/qgraphicsproxywidget.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qglobal.h"
@@ -183,7 +147,9 @@ QT_BEGIN_NAMESPACE
\warning This class is provided for convenience when bridging
QWidgets and QGraphicsItems, it should not be used for
- high-performance scenarios.
+ high-performance scenarios. In particular, embedding widgets into a scene
+ that is then displayed through a QGraphicsView that uses an OpenGL viewport
+ will not work for all combinations.
\sa QGraphicsScene::addWidget(), QGraphicsWidget
*/
@@ -237,6 +203,7 @@ void QGraphicsProxyWidgetPrivate::sendWidgetMouseEvent(QGraphicsSceneHoverEvent
mouseEvent.setButton(Qt::NoButton);
mouseEvent.setButtons({ });
mouseEvent.setModifiers(event->modifiers());
+ mouseEvent.setTimestamp(event->timestamp());
sendWidgetMouseEvent(&mouseEvent);
event->setAccepted(mouseEvent.isAccepted());
}
@@ -302,6 +269,7 @@ void QGraphicsProxyWidgetPrivate::sendWidgetMouseEvent(QGraphicsSceneMouseEvent
QMouseEvent mouseEvent(type, pos, receiver->mapTo(receiver->topLevelWidget(), pos.toPoint()),
receiver->mapToGlobal(pos.toPoint()),
event->button(), event->buttons(), event->modifiers(), event->source());
+ mouseEvent.setTimestamp(event->timestamp());
QWidget *embeddedMouseGrabberPtr = (QWidget *)embeddedMouseGrabber;
QApplicationPrivate::sendMouseEvent(receiver, &mouseEvent, alienWidget, widget,
@@ -372,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;
}
}
@@ -392,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;
}
@@ -493,7 +461,7 @@ void QGraphicsProxyWidgetPrivate::embedSubWindow(QWidget *subWin)
*/
void QGraphicsProxyWidgetPrivate::unembedSubWindow(QWidget *subWin)
{
- foreach (QGraphicsItem *child, children) {
+ for (QGraphicsItem *child : std::as_const(children)) {
if (child->isWidget()) {
if (QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(child))) {
if (proxy->widget() == subWin) {
@@ -554,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.
@@ -570,8 +538,8 @@ QGraphicsProxyWidget::~QGraphicsProxyWidget()
After this function returns, QGraphicsProxyWidget will keep its state
synchronized with that of \a widget whenever possible.
- If a widget is already embedded by this proxy when this function is
- called, that widget will first be automatically unembedded. Passing 0 for
+ If a widget is already embedded by this proxy when this function is called,
+ that widget will first be automatically unembedded. Passing \nullptr for
the \a widget argument will only unembed the widget, and the ownership of
the currently embedded widget will be passed on to the caller.
Every child widget that are embedded will also be embedded and their proxy
@@ -579,7 +547,7 @@ QGraphicsProxyWidget::~QGraphicsProxyWidget()
Note that widgets with the Qt::WA_PaintOnScreen widget attribute
set and widgets that wrap an external application or controller
- cannot be embedded. Examples are QGLWidget and QAxWidget.
+ cannot be embedded. Examples are QOpenGLWidget and QAxWidget.
\sa widget()
*/
@@ -830,6 +798,10 @@ bool QGraphicsProxyWidget::event(QEvent *event)
return QGraphicsWidget::event(event);
switch (event->type()) {
+ case QEvent::WindowActivate:
+ case QEvent::WindowDeactivate:
+ QCoreApplication::sendEvent(d->widget, event);
+ break;
case QEvent::StyleChange:
// Propagate style changes to the embedded widget.
if (!d->styleChangeMode) {
@@ -841,7 +813,7 @@ bool QGraphicsProxyWidget::event(QEvent *event)
case QEvent::FontChange: {
// Propagate to widget.
QWidgetPrivate *wd = d->widget->d_func();
- int mask = d->font.resolve() | d->inheritedFontResolveMask;
+ int mask = d->font.resolveMask() | d->inheritedFontResolveMask;
wd->inheritedFontResolveMask = mask;
wd->resolveFont();
break;
@@ -849,7 +821,7 @@ bool QGraphicsProxyWidget::event(QEvent *event)
case QEvent::PaletteChange: {
// Propagate to widget.
QWidgetPrivate *wd = d->widget->d_func();
- int mask = d->palette.resolve() | d->inheritedPaletteResolveMask;
+ int mask = d->palette.resolveMask() | d->inheritedPaletteResolveMask;
wd->inheritedPaletteResolveMask = mask;
wd->resolvePalette();
break;
@@ -888,7 +860,7 @@ bool QGraphicsProxyWidget::event(QEvent *event)
}
break;
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::GraphicsSceneHelp: {
// Propagate the help event (for tooltip) to the widget under mouse
if (d->lastWidgetUnderMouse) {
@@ -914,16 +886,13 @@ bool QGraphicsProxyWidget::event(QEvent *event)
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd: {
- if (event->spontaneous())
- qt_sendSpontaneousEvent(d->widget, event);
- else
- QCoreApplication::sendEvent(d->widget, event);
-
- if (event->isAccepted())
+ QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
+ bool res = QApplicationPrivate::translateRawTouchEvent(d->widget, touchEvent);
+ if (res & touchEvent->isAccepted())
return true;
break;
- }
+ }
default:
break;
}
@@ -979,7 +948,7 @@ bool QGraphicsProxyWidget::eventFilter(QObject *object, QEvent *event)
d->styleChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
}
break;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::ToolTipChange:
// Propagate tooltip change to the proxy.
if (!d->tooltipChangeMode) {
@@ -1042,6 +1011,7 @@ void QGraphicsProxyWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent *even
// Send mouse event. ### Doesn't propagate the event.
QContextMenuEvent contextMenuEvent(QContextMenuEvent::Reason(event->reason()),
pos.toPoint(), globalPos, event->modifiers());
+ contextMenuEvent.setTimestamp(event->timestamp());
QCoreApplication::sendEvent(receiver, &contextMenuEvent);
event->setAccepted(contextMenuEvent.isAccepted());
@@ -1287,6 +1257,19 @@ void QGraphicsProxyWidget::wheelEvent(QGraphicsSceneWheelEvent *event)
if (!receiver)
receiver = d->widget;
+ // high precision event streams go to the grabber, which will be the
+ // QGraphicsView's viewport. We need to change that temporarily, otherwise
+ // the event we send to the receiver get grabbed by the viewport, resulting
+ // in infinite recursion
+ QPointer<QWidget> prev_grabber = QApplicationPrivate::wheel_widget;
+ if (event->phase() == Qt::ScrollBegin) {
+ QApplicationPrivate::wheel_widget = receiver;
+ } else if (event->phase() != Qt::NoScrollPhase && QApplicationPrivate::wheel_widget != receiver) {
+ // this event is part of a stream that didn't start here, so ignore
+ event->ignore();
+ return;
+ }
+
// Map event position from us to the receiver
pos = d->mapToReceiver(pos, receiver);
@@ -1298,13 +1281,21 @@ void QGraphicsProxyWidget::wheelEvent(QGraphicsSceneWheelEvent *event)
angleDelta.setY(event->delta());
// pixelDelta, inverted, scrollPhase and source from the original QWheelEvent
// were not preserved in the QGraphicsSceneWheelEvent unfortunately
- QWheelEvent wheelEvent(pos, event->screenPos(), QPoint(), angleDelta,
- event->buttons(), event->modifiers(), Qt::NoScrollPhase, false);
+ QWheelEvent wheelEvent(pos, event->screenPos(), event->pixelDelta(), angleDelta,
+ event->buttons(), event->modifiers(), event->phase(),
+ event->isInverted(), Qt::MouseEventSynthesizedByQt,
+ QPointingDevice::primaryPointingDevice());
QPointer<QWidget> focusWidget = d->widget->focusWidget();
extern bool qt_sendSpontaneousEvent(QObject *, QEvent *);
qt_sendSpontaneousEvent(receiver, &wheelEvent);
event->setAccepted(wheelEvent.isAccepted());
+ if (event->phase() == Qt::ScrollBegin) {
+ // reset the wheel grabber if the event wasn't accepted
+ if (!wheelEvent.isAccepted())
+ QApplicationPrivate::wheel_widget = prev_grabber;
+ }
+
// ### Remove, this should be done by proper focusIn/focusOut events.
if (focusWidget && !focusWidget->hasFocus()) {
focusWidget->update();
@@ -1387,6 +1378,11 @@ void QGraphicsProxyWidget::focusInEvent(QFocusEvent *event)
break;
}
+ // QTBUG-88016
+ if (d->widget && d->widget->focusWidget()
+ && d->widget->focusWidget()->testAttribute(Qt::WA_InputMethodEnabled))
+ QApplication::inputMethod()->reset();
+
d->proxyIsGivingFocus = false;
}
@@ -1402,8 +1398,14 @@ void QGraphicsProxyWidget::focusOutEvent(QFocusEvent *event)
if (d->widget) {
// We need to explicitly remove subfocus from the embedded widget's
// focus widget.
- if (QWidget *focusWidget = d->widget->focusWidget())
+ 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->testAttribute(Qt::WA_InputMethodEnabled))
+ QApplication::inputMethod()->reset();
+
d->removeSubFocusHelper(focusWidget, event->reason());
+ }
}
}
@@ -1441,17 +1443,17 @@ QVariant QGraphicsProxyWidget::inputMethodQuery(Qt::InputMethodQuery query) cons
focusWidget = d->widget;
QVariant v = focusWidget->inputMethodQuery(query);
QPointF focusWidgetPos = subWidgetRect(focusWidget).topLeft();
- switch (v.type()) {
- case QVariant::RectF:
+ switch (v.userType()) {
+ case QMetaType::QRectF:
v = v.toRectF().translated(focusWidgetPos);
break;
- case QVariant::PointF:
+ case QMetaType::QPointF:
v = v.toPointF() + focusWidgetPos;
break;
- case QVariant::Rect:
+ case QMetaType::QRect:
v = v.toRect().translated(focusWidgetPos.toPoint());
break;
- case QVariant::Point:
+ case QMetaType::QPoint:
v = v.toPoint() + focusWidgetPos.toPoint();
break;
default:
@@ -1538,6 +1540,10 @@ void QGraphicsProxyWidget::paint(QPainter *painter, const QStyleOptionGraphicsIt
if (exposedWidgetRect.isEmpty())
return;
+ // When rendering to pdf etc. painting may go outside widget boundaries unless clipped
+ if (painter->device()->devType() != QInternal::Widget && (flags() & ItemClipsChildrenToShape))
+ painter->setClipRect(d->widget->geometry(), Qt::IntersectClip);
+
d->widget->render(painter, exposedWidgetRect.topLeft(), exposedWidgetRect);
}
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget.h b/src/widgets/graphicsview/qgraphicsproxywidget.h
index aa51500ecb..7149f5701a 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget.h
+++ b/src/widgets/graphicsview/qgraphicsproxywidget.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSPROXYWIDGET_H
#define QGRAPHICSPROXYWIDGET_H
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget_p.h b/src/widgets/graphicsview/qgraphicsproxywidget_p.h
index 593b686e0e..328faad0be 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget_p.h
+++ b/src/widgets/graphicsview/qgraphicsproxywidget_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSPROXYWIDGET_P_H
#define QGRAPHICSPROXYWIDGET_P_H
@@ -55,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 1c6e68def1..c022af6fc0 100644
--- a/src/widgets/graphicsview/qgraphicsscene.cpp
+++ b/src/widgets/graphicsview/qgraphicsscene.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsScene
@@ -226,22 +190,25 @@
#include <QtCore/qvarlengtharray.h>
#include <QtCore/QMetaMethod>
#include <QtWidgets/qapplication.h>
-#include <QtWidgets/qdesktopwidget.h>
#include <QtGui/qevent.h>
#include <QtWidgets/qgraphicslayout.h>
#include <QtWidgets/qgraphicsproxywidget.h>
#include <QtWidgets/qgraphicswidget.h>
-#include <QtGui/qmatrix.h>
#include <QtGui/qpaintengine.h>
#include <QtGui/qpainter.h>
+#include <QtGui/qpainterpath.h>
#include <QtGui/qpixmapcache.h>
#include <QtGui/qpolygon.h>
-#include <QtGui/qtouchdevice.h>
+#include <QtGui/qpointingdevice.h>
#include <QtWidgets/qstyleoption.h>
+#if QT_CONFIG(tooltip)
#include <QtWidgets/qtooltip.h>
+#endif
#include <QtGui/qtransform.h>
#include <QtGui/qinputmethod.h>
#include <private/qapplication_p.h>
+#include <private/qevent_p.h>
+#include <QtGui/private/qeventpoint_p.h>
#include <private/qobject_p.h>
#if QT_CONFIG(graphicseffect)
#include <private/qgraphicseffect_p.h>
@@ -249,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
@@ -363,12 +332,11 @@ void QGraphicsScenePrivate::_q_emitUpdated()
// needs to happen in order to keep compatibility with the behavior from
// Qt 4.4 and backward.
if (isSignalConnected(changedSignalIndex)) {
- for (int i = 0; i < views.size(); ++i) {
- QGraphicsView *view = views.at(i);
+ for (auto view : std::as_const(views)) {
if (!view->d_func()->connectedToScene) {
view->d_func()->connectedToScene = true;
q->connect(q, SIGNAL(changed(QList<QRectF>)),
- views.at(i), SLOT(updateScene(QList<QRectF>)));
+ view, SLOT(updateScene(QList<QRectF>)));
}
}
} else {
@@ -376,11 +344,11 @@ void QGraphicsScenePrivate::_q_emitUpdated()
updateAll = false;
return;
}
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->processPendingUpdates();
+ for (auto view : std::as_const(views))
+ view->d_func()->processPendingUpdates();
// It's important that we update all views before we dispatch, hence two for-loops.
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->dispatchPendingUpdateRequests();
+ for (auto view : std::as_const(views))
+ view->d_func()->dispatchPendingUpdateRequests();
return;
}
@@ -445,7 +413,7 @@ void QGraphicsScenePrivate::_q_polishItems()
const QVariant booleanTrueVariant(true);
QGraphicsItem *item = nullptr;
QGraphicsItemPrivate *itemd = nullptr;
- const int oldUnpolishedCount = unpolishedItems.count();
+ const int oldUnpolishedCount = unpolishedItems.size();
for (int i = 0; i < oldUnpolishedCount; ++i) {
item = unpolishedItems.at(i);
@@ -463,7 +431,7 @@ void QGraphicsScenePrivate::_q_polishItems()
}
}
- if (unpolishedItems.count() == oldUnpolishedCount) {
+ if (unpolishedItems.size() == oldUnpolishedCount) {
// No new items were added to the vector.
unpolishedItems.clear();
} else {
@@ -482,8 +450,8 @@ void QGraphicsScenePrivate::_q_processDirtyItems()
Q_ASSERT(calledEmitUpdated);
// No need for further processing (except resetting the dirty states).
// The growingItemsBoundingRect is updated in _q_emitUpdated.
- for (int i = 0; i < topLevelItems.size(); ++i)
- resetDirtyItem(topLevelItems.at(i), /*recursive=*/true);
+ for (auto topLevelItem : std::as_const(topLevelItems))
+ resetDirtyItem(topLevelItem, /*recursive=*/true);
return;
}
@@ -491,8 +459,8 @@ void QGraphicsScenePrivate::_q_processDirtyItems()
const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
// Process items recursively.
- for (int i = 0; i < topLevelItems.size(); ++i)
- processDirtyItemsRecursive(topLevelItems.at(i));
+ for (auto topLevelItem : std::as_const(topLevelItems))
+ processDirtyItemsRecursive(topLevelItem);
dirtyGrowingItemsBoundingRect = false;
if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect)
@@ -501,8 +469,8 @@ void QGraphicsScenePrivate::_q_processDirtyItems()
if (wasPendingSceneUpdate)
return;
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->processPendingUpdates();
+ for (auto view : std::as_const(views))
+ view->d_func()->processPendingUpdates();
if (calledEmitUpdated) {
// We did a compatibility QGraphicsScene::update in processDirtyItemsRecursive
@@ -512,8 +480,8 @@ void QGraphicsScenePrivate::_q_processDirtyItems()
}
// Immediately dispatch all pending update requests on the views.
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->dispatchPendingUpdateRequests();
+ for (auto view : std::as_const(views))
+ view->d_func()->dispatchPendingUpdateRequests();
}
/*!
@@ -555,7 +523,7 @@ void QGraphicsScenePrivate::unregisterScenePosItem(QGraphicsItem *item)
*/
void QGraphicsScenePrivate::_q_updateScenePosDescendants()
{
- foreach (QGraphicsItem *item, scenePosItems) {
+ for (QGraphicsItem *item : std::as_const(scenePosItems)) {
QGraphicsItem *p = item->d_ptr->parent;
while (p) {
p->d_ptr->scenePosDescendants = 1;
@@ -608,8 +576,8 @@ void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item)
//attributes (e.g. sceneTransform).
if (!item->d_ptr->inDestructor) {
// Remove all children recursively
- for (int i = 0; i < item->d_ptr->children.size(); ++i)
- q->removeItem(item->d_ptr->children.at(i));
+ for (auto child : std::as_const(item->d_ptr->children))
+ q->removeItem(child);
}
if (!item->d_ptr->inDestructor && !item->parentItem() && item->isWidget()) {
@@ -711,14 +679,13 @@ void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item)
if (item == dragDropItem)
dragDropItem = nullptr;
- // Reenable selectionChanged() for individual items
+ // Re-enable selectionChanged() for individual items
--selectionChanging;
if (!selectionChanging && selectedItems.size() != oldSelectedItemsSize)
emit q->selectionChanged();
#ifndef QT_NO_GESTURES
- QHash<QGesture *, QGraphicsObject *>::iterator it;
- for (it = gestureTargets.begin(); it != gestureTargets.end();) {
+ for (auto it = gestureTargets.begin(); it != gestureTargets.end();) {
if (it.value() == item)
it = gestureTargets.erase(it);
else
@@ -731,8 +698,9 @@ void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item)
cachedAlreadyDeliveredGestures.remove(dummy);
}
- foreach (Qt::GestureType gesture, item->d_ptr->gestureContext.keys())
- ungrabGesture(item, gesture);
+ for (auto it = item->d_ptr->gestureContext.constBegin();
+ it != item->d_ptr->gestureContext.constEnd(); ++it)
+ ungrabGesture(item, it.key());
#endif // QT_NO_GESTURES
}
@@ -1038,7 +1006,7 @@ void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
void QGraphicsScenePrivate::clearMouseGrabber()
{
if (!mouseGrabberItems.isEmpty())
- mouseGrabberItems.first()->ungrabMouse();
+ mouseGrabberItems.constFirst()->ungrabMouse();
lastMouseGrabberItem = nullptr;
}
@@ -1114,7 +1082,7 @@ void QGraphicsScenePrivate::clearKeyboardGrabber()
void QGraphicsScenePrivate::enableMouseTrackingOnViews()
{
- foreach (QGraphicsView *view, views)
+ for (QGraphicsView *view : std::as_const(views))
view->viewport()->setMouseTracking(true);
}
@@ -1253,7 +1221,7 @@ bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
bool spont = event->spontaneous();
if (spont ? qt_sendSpontaneousEvent(o, event) : QCoreApplication::sendEvent(o, event))
return true;
- event->spont = spont;
+ event->m_spont = spont;
}
return item->sceneEvent(event);
}
@@ -1377,7 +1345,7 @@ void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mou
// Set focus on the topmost enabled item that can take focus.
bool setFocus = false;
- foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
+ for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) {
if (item->isBlockedByModalPanel()
|| (item->d_ptr->flags & QGraphicsItem::ItemStopsFocusHandling)) {
// Make sure we don't clear focus.
@@ -1400,8 +1368,8 @@ void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mou
// Check for scene modality.
bool sceneModality = false;
- for (int i = 0; i < modalPanels.size(); ++i) {
- if (modalPanels.at(i)->panelModality() == QGraphicsItem::SceneModal) {
+ for (auto modalPanel : std::as_const(modalPanels)) {
+ if (modalPanel->panelModality() == QGraphicsItem::SceneModal) {
sceneModality = true;
break;
}
@@ -1419,7 +1387,7 @@ void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mou
// candidates one at a time, until the event is accepted. It's accepted by
// default, so the receiver has to explicitly ignore it for it to pass
// through.
- foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
+ for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) {
if (!(item->acceptedMouseButtons() & mouseEvent->button())) {
// Skip items that don't accept the event's mouse button.
continue;
@@ -1438,11 +1406,11 @@ void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mou
if (mouseEvent->type() == QEvent::GraphicsSceneMouseDoubleClick
&& item != lastMouseGrabberItem && lastMouseGrabberItem) {
// If this item is different from the item that received the last
- // mouse event, and mouseEvent is a doubleclick event, then the
+ // mouse event, and mouseEvent is a double-click event, then the
// event is converted to a press. Known limitation:
- // Triple-clicking will not generate a doubleclick, though.
+ // Triple-clicking will not generate a double-click, though.
QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress);
- mousePress.spont = mouseEvent->spont;
+ mousePress.m_spont = mouseEvent->spontaneous();
mousePress.accept();
mousePress.setButton(mouseEvent->button());
mousePress.setButtons(mouseEvent->buttons());
@@ -1531,7 +1499,7 @@ void QGraphicsScenePrivate::ensureSequentialTopLevelSiblingIndexes()
*/
void QGraphicsScenePrivate::setFont_helper(const QFont &font)
{
- if (this->font == font && this->font.resolve() == font.resolve())
+ if (this->font == font && this->font.resolveMask() == font.resolveMask())
return;
updateFont(font);
}
@@ -1545,7 +1513,7 @@ void QGraphicsScenePrivate::setFont_helper(const QFont &font)
void QGraphicsScenePrivate::resolveFont()
{
QFont naturalFont = QApplication::font();
- naturalFont.resolve(0);
+ naturalFont.setResolveMask(0);
QFont resolvedFont = font.resolve(naturalFont);
updateFont(resolvedFont);
}
@@ -1571,7 +1539,7 @@ void QGraphicsScenePrivate::updateFont(const QFont &font)
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
- item->d_ptr->resolveFont(font.resolve());
+ item->d_ptr->resolveFont(font.resolveMask());
}
}
@@ -1588,7 +1556,7 @@ void QGraphicsScenePrivate::updateFont(const QFont &font)
*/
void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
{
- if (this->palette == palette && this->palette.resolve() == palette.resolve())
+ if (this->palette == palette && this->palette.resolveMask() == palette.resolveMask())
return;
updatePalette(palette);
}
@@ -1602,7 +1570,7 @@ void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
void QGraphicsScenePrivate::resolvePalette()
{
QPalette naturalPalette = QGuiApplication::palette();
- naturalPalette.resolve(0);
+ naturalPalette.setResolveMask(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
updatePalette(resolvedPalette);
}
@@ -1628,7 +1596,7 @@ void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
// ResolvePalette for an item is a noop operation, but
// every item can be a widget, or can have a widget
// children.
- item->d_ptr->resolvePalette(palette.resolve());
+ item->d_ptr->resolvePalette(palette.resolveMask());
}
}
@@ -1693,8 +1661,10 @@ QGraphicsScene::~QGraphicsScene()
clear();
// Remove this scene from all associated views.
- for (int j = 0; j < d->views.size(); ++j)
- d->views.at(j)->setScene(nullptr);
+ // Note: d->views is modified by QGraphicsView::setScene, so must make a copy
+ const auto views = d->views;
+ for (auto view : std::as_const(views))
+ view->setScene(nullptr);
}
/*!
@@ -1812,8 +1782,8 @@ void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRect
// in reverse order).
QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect);
QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
- int numItems = itemList.size();
- for (int i = 0; i < numItems; ++i)
+ const qsizetype numItems = itemList.size();
+ for (qsizetype i = 0; i < numItems; ++i)
itemArray[numItems - i - 1] = itemList.at(i);
itemList.clear();
@@ -1830,7 +1800,7 @@ void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRect
// Generate the style options
QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems];
- for (int i = 0; i < numItems; ++i)
+ for (qsizetype i = 0; i < numItems; ++i)
itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterTransform, targetRect.toRect());
// Render the scene.
@@ -1852,7 +1822,7 @@ void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRect
item discovery functions like items() and itemAt(). Indexing is most
efficient for static scenes (i.e., where items don't move around). For
dynamic scenes, or scenes with many animated items, the index bookkeeping
- can outweight the fast lookup speeds.
+ can outweigh the fast lookup speeds.
For the common case, the default index method BspTreeIndex works fine. If
your scene uses many animations and you are experiencing slowness, you can
@@ -1937,29 +1907,6 @@ void QGraphicsScene::setBspTreeDepth(int depth)
bspTree->setBspTreeDepth(depth);
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \property QGraphicsScene::sortCacheEnabled
- \brief whether sort caching is enabled
- \since 4.5
- \obsolete
-
- Since Qt 4.6, this property has no effect.
-*/
-bool QGraphicsScene::isSortCacheEnabled() const
-{
- Q_D(const QGraphicsScene);
- return d->sortCacheEnabled;
-}
-void QGraphicsScene::setSortCacheEnabled(bool enabled)
-{
- Q_D(QGraphicsScene);
- if (d->sortCacheEnabled == enabled)
- return;
- d->sortCacheEnabled = enabled;
-}
-#endif
-
/*!
Calculates and returns the bounding rect of all items on the scene. This
function works by iterating over all items, and because of this, it can
@@ -1990,18 +1937,6 @@ QList<QGraphicsItem *> QGraphicsScene::items(Qt::SortOrder order) const
}
/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode) const
- \obsolete
- \since 4.3
-
- This convenience function is equivalent to calling items(QRectF(\a x, \a y, \a w, \a h), \a mode).
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-*/
-
-/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
\overload
\since 4.6
@@ -2150,23 +2085,6 @@ QList<QGraphicsItem *> QGraphicsScene::collidingItems(const QGraphicsItem *item,
}
/*!
- \fn QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position) const
- \overload
- \obsolete
-
- Returns the topmost visible item at the specified \a position, or
- \nullptr if there are no items at this position.
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-
- Note: See items() for a definition of which items are considered visible by this function.
-
- \sa items(), collidingItems(), {QGraphicsItem#Sorting}{Sorting}
-*/
-
-/*!
\since 4.6
Returns the topmost visible item at the specified \a position, or \nullptr
@@ -2204,24 +2122,6 @@ QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position, const QTransform
*/
/*!
- \fn QGraphicsScene::itemAt(qreal x, qreal y) const
- \overload
- \obsolete
-
- Returns the topmost visible item at the position specified by (\a x, \a
- y), or \nullptr if there are no items at this position.
-
- This convenience function is equivalent to calling \c
- {itemAt(QPointF(x, y))}.
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-
- Note: See items() for a definition of which items are considered visible by this function.
-*/
-
-/*!
Returns a list of all currently selected items. The items are
returned in no particular order.
@@ -2234,7 +2134,7 @@ QList<QGraphicsItem *> QGraphicsScene::selectedItems() const
// Optimization: Lazily removes items that are not selected.
QGraphicsScene *that = const_cast<QGraphicsScene *>(this);
QSet<QGraphicsItem *> actuallySelectedSet;
- foreach (QGraphicsItem *item, that->d_func()->selectedItems) {
+ for (QGraphicsItem *item : std::as_const(that->d_func()->selectedItems)) {
if (item->isSelected())
actuallySelectedSet << item;
}
@@ -2274,25 +2174,7 @@ QPainterPath QGraphicsScene::selectionArea() const
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path, const QTransform &deviceTransform)
{
- setSelectionArea(path, Qt::IntersectsItemShape, deviceTransform);
-}
-
-/*!
- \overload
- \since 4.6
-
- Sets the selection area to \a path using \a mode to determine if items are
- included in the selection area.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- \sa clearSelection(), selectionArea()
-*/
-void QGraphicsScene::setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode,
- const QTransform &deviceTransform)
-{
- setSelectionArea(path, Qt::ReplaceSelection, mode, deviceTransform);
+ setSelectionArea(path, Qt::ReplaceSelection, Qt::IntersectsItemShape, deviceTransform);
}
/*!
@@ -2342,7 +2224,7 @@ void QGraphicsScene::setSelectionArea(const QPainterPath &path,
switch (selectionOperation) {
case Qt::ReplaceSelection:
// Deselect all items outside path.
- foreach (QGraphicsItem *item, unselectItems) {
+ for (QGraphicsItem *item : std::as_const(unselectItems)) {
item->setSelected(false);
changed = true;
}
@@ -2351,7 +2233,7 @@ void QGraphicsScene::setSelectionArea(const QPainterPath &path,
break;
}
- // Reenable emitting selectionChanged() for individual items.
+ // Re-enable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
@@ -2369,13 +2251,20 @@ void QGraphicsScene::clearSelection()
// Disable emitting selectionChanged
++d->selectionChanging;
- bool changed = !d->selectedItems.isEmpty();
+ // iterate over a copy, as clearing selection might invalidate selectedItems
+ const auto selectedItems = d->selectedItems;
+ QSet<QGraphicsItem *> stillSelectedSet;
- foreach (QGraphicsItem *item, d->selectedItems)
+ for (QGraphicsItem *item : selectedItems) {
item->setSelected(false);
- d->selectedItems.clear();
+ // items might override itemChange to prevent deselection
+ if (item->isSelected())
+ stillSelectedSet << item;
+ }
+ const bool changed = stillSelectedSet != selectedItems;
+ d->selectedItems = stillSelectedSet;
- // Reenable emitting selectionChanged() for individual items.
+ // Re-enable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
@@ -2480,7 +2369,7 @@ void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup *group)
}
/*!
- Adds or moves the \a item and all its childen to this scene.
+ Adds or moves the \a item and all its children to this scene.
This scene takes ownership of the \a item.
If the item is visible (i.e., QGraphicsItem::isVisible() returns
@@ -2530,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.
@@ -2596,9 +2481,9 @@ void QGraphicsScene::addItem(QGraphicsItem *item)
}
#ifndef QT_NO_GESTURES
- const auto gestures = item->d_ptr->gestureContext.keys(); // FIXME: iterate over hash directly?
- for (Qt::GestureType gesture : gestures)
- d->grabGesture(item, gesture);
+ for (auto it = item->d_ptr->gestureContext.constBegin();
+ it != item->d_ptr->gestureContext.constEnd(); ++it)
+ d->grabGesture(item, it.key());
#endif
// Update selection lists
@@ -2629,15 +2514,15 @@ void QGraphicsScene::addItem(QGraphicsItem *item)
// Add all children recursively
item->d_ptr->ensureSortedChildren();
- for (int i = 0; i < item->d_ptr->children.size(); ++i)
- addItem(item->d_ptr->children.at(i));
+ for (auto child : std::as_const(item->d_ptr->children))
+ addItem(child);
// Resolve font and palette.
- item->d_ptr->resolveFont(d->font.resolve());
- item->d_ptr->resolvePalette(d->palette.resolve());
+ item->d_ptr->resolveFont(d->font.resolveMask());
+ item->d_ptr->resolvePalette(d->palette.resolveMask());
- // Reenable selectionChanged() for individual items
+ // Re-enable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemSize)
emit selectionChanged();
@@ -2904,7 +2789,7 @@ QGraphicsSimpleTextItem *QGraphicsScene::addSimpleText(const QString &text, cons
Note that widgets with the Qt::WA_PaintOnScreen widget attribute
set and widgets that wrap an external application or controller
- are not supported. Examples are QGLWidget and QAxWidget.
+ are not supported. Examples are QOpenGLWidget and QAxWidget.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addText(), addSimpleText(), addItem()
@@ -3001,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()
@@ -3132,7 +3017,7 @@ void QGraphicsScene::setBackgroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->backgroundBrush = brush;
- foreach (QGraphicsView *view, d->views) {
+ for (QGraphicsView *view : std::as_const(d->views)) {
view->resetCachedContent();
view->viewport()->update();
}
@@ -3190,13 +3075,13 @@ QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const
return QVariant();
const QTransform matrix = d->focusItem->sceneTransform();
QVariant value = d->focusItem->inputMethodQuery(query);
- if (value.type() == QVariant::RectF)
+ if (value.userType() == QMetaType::QRectF)
value = matrix.mapRect(value.toRectF());
- else if (value.type() == QVariant::PointF)
+ else if (value.userType() == QMetaType::QPointF)
value = matrix.map(value.toPointF());
- else if (value.type() == QVariant::Rect)
+ else if (value.userType() == QMetaType::QRect)
value = matrix.mapRect(value.toRect());
- else if (value.type() == QVariant::Point)
+ else if (value.userType() == QMetaType::QPoint)
value = matrix.map(value.toPoint());
return value;
}
@@ -3221,14 +3106,13 @@ void QGraphicsScene::update(const QRectF &rect)
d->updatedRects.clear();
if (directUpdates) {
// Update all views.
- for (int i = 0; i < d->views.size(); ++i)
- d->views.at(i)->d_func()->fullUpdatePending = true;
+ for (auto view : std::as_const(d->views))
+ view->d_func()->fullUpdatePending = true;
}
} else {
if (directUpdates) {
// Update all views.
- for (int i = 0; i < d->views.size(); ++i) {
- QGraphicsView *view = d->views.at(i);
+ for (auto view : std::as_const(d->views)) {
if (view->isTransformed())
view->d_func()->updateRectF(view->viewportTransform().mapRect(rect));
else
@@ -3369,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;
}
@@ -3457,9 +3342,15 @@ bool QGraphicsScene::event(QEvent *event)
break;
}
case QEvent::Leave:
- // hackieshly unpacking the viewport pointer from the leave event.
- d->leaveScene(reinterpret_cast<QWidget *>(event->d));
+ Q_ASSERT_X(false, "QGraphicsScene::event",
+ "QGraphicsScene must not receive QEvent::Leave, use GraphicsSceneLeave");
+ break;
+ case QEvent::GraphicsSceneLeave:
+ {
+ auto *leaveEvent = static_cast<QGraphicsSceneEvent*>(event);
+ d->leaveScene(leaveEvent->widget());
break;
+ }
case QEvent::GraphicsSceneHelp:
helpEvent(static_cast<QGraphicsSceneHelpEvent *>(event));
break;
@@ -3817,25 +3708,24 @@ void QGraphicsScene::focusOutEvent(QFocusEvent *focusEvent)
*/
void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
{
-#ifdef QT_NO_TOOLTIP
+#if !QT_CONFIG(tooltip)
Q_UNUSED(helpEvent);
#else
// Find the first item that does tooltips
Q_D(QGraphicsScene);
- QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
- helpEvent->scenePos(),
- helpEvent->widget());
+ const QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
+ helpEvent->scenePos(),
+ helpEvent->widget());
QGraphicsItem *toolTipItem = nullptr;
- for (int i = 0; i < itemsAtPos.size(); ++i) {
- QGraphicsItem *tmp = itemsAtPos.at(i);
- if (tmp->d_func()->isProxyWidget()) {
+ for (auto item : itemsAtPos) {
+ if (item->d_func()->isProxyWidget()) {
// if the item is a proxy widget, the event is forwarded to it
- sendEvent(tmp, helpEvent);
+ sendEvent(item, helpEvent);
if (helpEvent->isAccepted())
return;
}
- if (!tmp->toolTip().isEmpty()) {
- toolTipItem = tmp;
+ if (!item->toolTip().isEmpty()) {
+ toolTipItem = item;
break;
}
}
@@ -3884,8 +3774,7 @@ bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEv
}
QGraphicsItem *item = nullptr;
- for (int i = 0; i < cachedItemsUnderMouse.size(); ++i) {
- QGraphicsItem *tmp = cachedItemsUnderMouse.at(i);
+ for (auto tmp : std::as_const(cachedItemsUnderMouse)) {
if (itemAcceptsHoverEvents_helper(tmp)) {
item = tmp;
break;
@@ -3950,7 +3839,7 @@ bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEv
*/
void QGraphicsScenePrivate::leaveScene(QWidget *viewport)
{
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
QToolTip::hideText();
#endif
QGraphicsView *view = qobject_cast<QGraphicsView *>(viewport->parent());
@@ -4142,15 +4031,15 @@ void QGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
/*!
This event handler, for event \a mouseEvent, can be reimplemented
- in a subclass to receive mouse doubleclick events for the scene.
+ in a subclass to receive mouse double-click events for the scene.
If someone doubleclicks on the scene, the scene will first receive
a mouse press event, followed by a release event (i.e., a click),
- then a doubleclick event, and finally a release event. If the
- doubleclick event is delivered to a different item than the one
+ then a double-click event, and finally a release event. If the
+ double-click event is delivered to a different item than the one
that received the first press and release, it will be delivered as
a press event. However, tripleclick events are not delivered as
- doubleclick events in this case.
+ double-click events in this case.
The default implementation is similar to mousePressEvent().
@@ -4189,7 +4078,8 @@ void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
// Remove all popups after the one found, or all or them if no popup is under the mouse.
// Then continue with the event.
QList<QGraphicsWidget *>::const_iterator iter = d->popupWidgets.constEnd();
- while (--iter >= d->popupWidgets.constBegin() && !wheelCandidates.isEmpty()) {
+ while (iter > d->popupWidgets.constBegin() && !wheelCandidates.isEmpty()) {
+ --iter;
if (wheelCandidates.first() == *iter || (*iter)->isAncestorOf(wheelCandidates.first()))
break;
d->removePopup(*iter);
@@ -4230,8 +4120,12 @@ void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event)
{
Q_D(QGraphicsScene);
- if (d->focusItem && (d->focusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod))
+ if (d->focusItem && (d->focusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod)) {
d->sendEvent(d->focusItem, event);
+ return;
+ }
+ if (d->lastFocusItem && d->lastFocusItem != d->focusItem && (d->lastFocusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod))
+ d->sendEvent(d->lastFocusItem, event);
}
/*!
@@ -4503,10 +4397,9 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte
QRegion pixmapExposed;
QRectF exposedRect;
if (!itemCache->allExposed) {
- for (int i = 0; i < itemCache->exposed.size(); ++i) {
- QRectF r = itemCache->exposed.at(i);
- exposedRect |= r;
- pixmapExposed += itemToPixmap.mapRect(r).toAlignedRect();
+ for (const auto &rect : std::as_const(itemCache->exposed)) {
+ exposedRect |= rect;
+ pixmapExposed += itemToPixmap.mapRect(rect).toAlignedRect();
}
} else {
exposedRect = brect;
@@ -4664,9 +4557,8 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte
// Map the item's logical expose to pixmap coordinates.
QRegion pixmapExposed = scrollExposure;
if (!itemCache->allExposed) {
- const QVector<QRectF> &exposed = itemCache->exposed;
- for (int i = 0; i < exposed.size(); ++i)
- pixmapExposed += itemToPixmap.mapRect(exposed.at(i)).toRect().adjusted(-1, -1, 1, 1);
+ for (const auto &rect : std::as_const(itemCache->exposed))
+ pixmapExposed += itemToPixmap.mapRect(rect).toRect().adjusted(-1, -1, 1, 1);
}
// Calculate the style option's exposedRect.
@@ -4674,11 +4566,10 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte
if (itemCache->allExposed) {
br = item->boundingRect();
} else {
- const QVector<QRectF> &exposed = itemCache->exposed;
- for (int i = 0; i < exposed.size(); ++i)
- br |= exposed.at(i);
+ for (const auto &rect : std::as_const(itemCache->exposed))
+ br |= rect;
QTransform pixmapToItem = itemToPixmap.inverted();
- for (const QRect &r : scrollExposure)
+ for (const QRect &r : std::as_const(scrollExposure))
br |= pixmapToItem.mapRect(r);
}
styleOptionTmp = *option;
@@ -4731,8 +4622,8 @@ void QGraphicsScenePrivate::drawItems(QPainter *painter, const QTransform *const
exposedSceneRect = viewTransform->inverted().mapRect(exposedSceneRect);
}
const QList<QGraphicsItem *> tli = index->estimateTopLevelItems(exposedSceneRect, Qt::AscendingOrder);
- for (int i = 0; i < tli.size(); ++i)
- drawSubtreeRecursive(tli.at(i), painter, viewTransform, exposedRegion, widget);
+ for (const auto subTree : tli)
+ drawSubtreeRecursive(subTree, painter, viewTransform, exposedRegion, widget);
}
void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter,
@@ -4814,7 +4705,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *
if (itemIsTooSmallToRender || itemIsOutsideVisibleRect) {
// We cannot simply use !drawItem here. If we did it is possible
- // to enter the outter if statement with drawItem == false and minimumRenderSize > 0
+ // to enter the outer if statement with drawItem == false and minimumRenderSize > 0
// and finally end up inside this inner if, even though none of the above two
// conditions are met. In that case we should not return from this function
// but call draw() instead.
@@ -4901,9 +4792,11 @@ void QGraphicsScenePrivate::draw(QGraphicsItem *item, QPainter *painter, const Q
qreal opacity, const QTransform *effectTransform,
bool wasDirtyParentSceneTransform, bool drawItem)
{
+ const auto &children = item->d_ptr->children;
+
const bool itemIsFullyTransparent = QGraphicsItemPrivate::isOpacityNull(opacity);
const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape);
- const bool itemHasChildren = !item->d_ptr->children.isEmpty();
+ const bool itemHasChildren = !children.isEmpty();
bool setChildClip = itemClipsChildrenToShape;
bool itemHasChildrenStackedBehind = false;
@@ -4915,7 +4808,7 @@ void QGraphicsScenePrivate::draw(QGraphicsItem *item, QPainter *painter, const Q
item->d_ptr->ensureSortedChildren();
// Items with the 'ItemStacksBehindParent' flag are put in front of the list
// so all we have to do is to check the first item.
- itemHasChildrenStackedBehind = (item->d_ptr->children.at(0)->d_ptr->flags
+ itemHasChildrenStackedBehind = (children.at(0)->d_ptr->flags
& QGraphicsItem::ItemStacksBehindParent);
if (itemHasChildrenStackedBehind) {
@@ -4925,8 +4818,8 @@ void QGraphicsScenePrivate::draw(QGraphicsItem *item, QPainter *painter, const Q
}
// Draw children behind
- for (i = 0; i < item->d_ptr->children.size(); ++i) {
- QGraphicsItem *child = item->d_ptr->children.at(i);
+ for (i = 0; i < children.size(); ++i) {
+ QGraphicsItem *child = children.at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
@@ -5004,8 +4897,8 @@ void QGraphicsScenePrivate::draw(QGraphicsItem *item, QPainter *painter, const Q
if (setChildClip)
setClip(painter, item);
- for (; i < item->d_ptr->children.size(); ++i) {
- QGraphicsItem *child = item->d_ptr->children.at(i);
+ for (; i < children.size(); ++i) {
+ QGraphicsItem *child = children.at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
@@ -5083,8 +4976,8 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b
return;
}
- for (int i = 0; i < views.size(); ++i) {
- QGraphicsViewPrivate *viewPrivate = views.at(i)->d_func();
+ for (auto view : std::as_const(views)) {
+ QGraphicsViewPrivate *viewPrivate = view->d_func();
QRect rect = item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport);
rect.translate(viewPrivate->dirtyScrollOffset);
viewPrivate->updateRect(rect);
@@ -5239,8 +5132,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool
QRectF dirtyRect;
bool uninitializedDirtyRect = true;
- for (int j = 0; j < views.size(); ++j) {
- QGraphicsView *view = views.at(j);
+ for (auto view : std::as_const(views)) {
QGraphicsViewPrivate *viewPrivate = view->d_func();
QRect &paintedViewBoundingRect = item->d_ptr->paintedViewBoundingRects[viewPrivate->viewport];
if (viewPrivate->fullUpdatePending
@@ -5298,8 +5190,8 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool
const bool bypassUpdateClip = !itemHasContents && wasDirtyParentViewBoundingRects;
if (itemClipsChildrenToShape && !bypassUpdateClip) {
// Make sure child updates are clipped to the item's bounding rect.
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->setUpdateClip(item);
+ for (auto view : std::as_const(views))
+ view->d_func()->setUpdateClip(item);
}
if (!dirtyAncestorContainsChildren) {
dirtyAncestorContainsChildren = item->d_ptr->fullUpdatePending
@@ -5308,8 +5200,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool
const bool allChildrenDirty = item->d_ptr->allChildrenDirty;
const bool parentIgnoresVisible = item->d_ptr->ignoreVisible;
const bool parentIgnoresOpacity = item->d_ptr->ignoreOpacity;
- for (int i = 0; i < item->d_ptr->children.size(); ++i) {
- QGraphicsItem *child = item->d_ptr->children.at(i);
+ for (auto child : std::as_const(item->d_ptr->children)) {
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (wasDirtyParentViewBoundingRects)
@@ -5329,8 +5220,8 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool
if (itemClipsChildrenToShape) {
// Reset updateClip.
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->setUpdateClip(nullptr);
+ for (auto view : std::as_const(views))
+ view->d_func()->setUpdateClip(nullptr);
}
} else if (wasDirtyParentSceneTransform) {
item->d_ptr->invalidateChildrenSceneTransform();
@@ -5340,7 +5231,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool
}
/*!
- \obsolete
+ \deprecated
Paints the given \a items using the provided \a painter, after the
background has been drawn, and before the foreground has been
@@ -5362,7 +5253,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool
Example:
- \snippet graphicssceneadditemsnippet.cpp 0
+ \snippet graphicssceneadditem/graphicssceneadditemsnippet.cpp 0
Since Qt 4.6, this function is not called anymore unless
the QGraphicsView::IndirectPainting flag is given as an Optimization
@@ -5410,8 +5301,8 @@ void QGraphicsScene::drawItems(QPainter *painter,
d->rectAdjust = oldRectAdjust;
// Reset discovery bits.
- for (int i = 0; i < topLevelItems.size(); ++i)
- topLevelItems.at(i)->d_ptr->itemDiscovered = 0;
+ for (auto topLevelItem : std::as_const(topLevelItems))
+ topLevelItem->d_ptr->itemDiscovered = 0;
painter->setWorldTransform(viewTransform);
painter->setOpacity(opacity);
@@ -5652,7 +5543,7 @@ void QGraphicsScene::setFont(const QFont &font)
{
Q_D(QGraphicsScene);
QFont naturalFont = QApplication::font();
- naturalFont.resolve(0);
+ naturalFont.setResolveMask(0);
QFont resolvedFont = font.resolve(naturalFont);
d->setFont_helper(resolvedFont);
}
@@ -5689,7 +5580,7 @@ void QGraphicsScene::setPalette(const QPalette &palette)
{
Q_D(QGraphicsScene);
QPalette naturalPalette = QGuiApplication::palette();
- naturalPalette.resolve(0);
+ naturalPalette.setResolveMask(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
d->setPalette_helper(resolvedPalette);
}
@@ -5903,9 +5794,9 @@ void QGraphicsScenePrivate::addView(QGraphicsView *view)
{
views << view;
#ifndef QT_NO_GESTURES
- const auto gestures = grabbedGestures.keys();
- for (Qt::GestureType gesture : gestures)
- view->viewport()->grabGesture(gesture);
+ for (auto it = grabbedGestures.constBegin();
+ it != grabbedGestures.constEnd(); ++it)
+ view->viewport()->grabGesture(it.key());
#endif
}
@@ -5919,14 +5810,9 @@ void QGraphicsScenePrivate::updateTouchPointsForItem(QGraphicsItem *item, QTouch
const QTransform mapFromScene =
item->d_ptr->genericMapFromSceneTransform(static_cast<const QWidget *>(touchEvent->target()));
- for (auto &touchPoint : touchEvent->_touchPoints) {
- // Deprecated TouchPoint::setRect clobbers ellipseDiameters, restore
- const QSizeF ellipseDiameters = touchPoint.ellipseDiameters();
- touchPoint.setRect(mapFromScene.map(touchPoint.sceneRect()).boundingRect());
- touchPoint.setEllipseDiameters(ellipseDiameters);
- touchPoint.setPos(mapFromScene.map(touchPoint.scenePos()));
- touchPoint.setStartPos(mapFromScene.map(touchPoint.startScenePos()));
- touchPoint.setLastPos(mapFromScene.map(touchPoint.lastScenePos()));
+ for (int i = 0; i < touchEvent->pointCount(); ++i) {
+ auto &pt = touchEvent->point(i);
+ QMutableEventPoint::setPosition(pt, mapFromScene.map(pt.scenePosition()));
}
}
@@ -5934,8 +5820,8 @@ int QGraphicsScenePrivate::findClosestTouchPointId(const QPointF &scenePos)
{
int closestTouchPointId = -1;
qreal closestDistance = qreal(0.);
- foreach (const QTouchEvent::TouchPoint &touchPoint, sceneCurrentTouchPoints) {
- qreal distance = QLineF(scenePos, touchPoint.scenePos()).length();
+ for (const QEventPoint &touchPoint : std::as_const(sceneCurrentTouchPoints)) {
+ qreal distance = QLineF(scenePos, touchPoint.scenePosition()).length();
if (closestTouchPointId == -1|| distance < closestDistance) {
closestTouchPointId = touchPoint.id();
closestDistance = distance;
@@ -5946,16 +5832,15 @@ int QGraphicsScenePrivate::findClosestTouchPointId(const QPointF &scenePos)
void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
{
- typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints;
+ typedef QPair<QEventPoint::States, QList<QEventPoint> > StatesAndTouchPoints;
QHash<QGraphicsItem *, StatesAndTouchPoints> itemsNeedingEvents;
- for (int i = 0; i < sceneTouchEvent->touchPoints().count(); ++i) {
- const QTouchEvent::TouchPoint &touchPoint = sceneTouchEvent->touchPoints().at(i);
-
+ const auto &touchPoints = sceneTouchEvent->points();
+ for (const auto &touchPoint : touchPoints) {
// update state
QGraphicsItem *item = nullptr;
- if (touchPoint.state() == Qt::TouchPointPressed) {
- if (sceneTouchEvent->device()->type() == QTouchDevice::TouchPad) {
+ if (touchPoint.state() == QEventPoint::State::Pressed) {
+ if (sceneTouchEvent->pointingDevice()->type() == QInputDevice::DeviceType::TouchPad) {
// on touch-pad devices, send all touch points to the same item
item = itemForTouchPointId.isEmpty()
? 0
@@ -5964,15 +5849,15 @@ void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
if (!item) {
// determine which item this touch point will go to
- cachedItemsUnderMouse = itemsAtPosition(touchPoint.screenPos().toPoint(),
- touchPoint.scenePos(),
+ cachedItemsUnderMouse = itemsAtPosition(touchPoint.globalPosition().toPoint(),
+ touchPoint.scenePosition(),
static_cast<QWidget *>(sceneTouchEvent->target()));
item = cachedItemsUnderMouse.isEmpty() ? 0 : cachedItemsUnderMouse.constFirst();
}
- if (sceneTouchEvent->device()->type() == QTouchDevice::TouchScreen) {
+ if (sceneTouchEvent->pointingDevice()->type() == QInputDevice::DeviceType::TouchScreen) {
// on touch-screens, combine this touch point with the closest one we find
- int closestTouchPointId = findClosestTouchPointId(touchPoint.scenePos());
+ int closestTouchPointId = findClosestTouchPointId(touchPoint.scenePosition());
QGraphicsItem *closestItem = itemForTouchPointId.value(closestTouchPointId);
if (!item || (closestItem && cachedItemsUnderMouse.contains(closestItem)))
item = closestItem;
@@ -5982,7 +5867,7 @@ void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
itemForTouchPointId.insert(touchPoint.id(), item);
sceneCurrentTouchPoints.insert(touchPoint.id(), touchPoint);
- } else if (touchPoint.state() == Qt::TouchPointReleased) {
+ } else if (touchPoint.state() == QEventPoint::State::Released) {
item = itemForTouchPointId.take(touchPoint.id());
if (!item)
continue;
@@ -5997,7 +5882,7 @@ void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
}
StatesAndTouchPoints &statesAndTouchPoints = itemsNeedingEvents[item];
- statesAndTouchPoints.first |= touchPoint.state();
+ statesAndTouchPoints.first = QEventPoint::States(statesAndTouchPoints.first | touchPoint.state());
statesAndTouchPoints.second.append(touchPoint);
}
@@ -6017,15 +5902,15 @@ void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
// determine event type from the state mask
QEvent::Type eventType;
switch (it.value().first) {
- case Qt::TouchPointPressed:
+ case QEventPoint::State::Pressed:
// all touch points have pressed state
eventType = QEvent::TouchBegin;
break;
- case Qt::TouchPointReleased:
+ case QEventPoint::State::Released:
// all touch points have released state
eventType = QEvent::TouchEnd;
break;
- case Qt::TouchPointStationary:
+ case QEventPoint::State::Stationary:
// don't send the event if nothing changed
continue;
default:
@@ -6034,13 +5919,9 @@ void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
break;
}
- QTouchEvent touchEvent(eventType);
- touchEvent.setWindow(sceneTouchEvent->window());
+ QMutableTouchEvent touchEvent(eventType, sceneTouchEvent->pointingDevice(), sceneTouchEvent->modifiers(), it.value().second);
touchEvent.setTarget(sceneTouchEvent->target());
- touchEvent.setDevice(sceneTouchEvent->device());
touchEvent.setModifiers(sceneTouchEvent->modifiers());
- touchEvent.setTouchPointStates(it.value().first);
- touchEvent.setTouchPoints(it.value().second);
touchEvent.setTimestamp(sceneTouchEvent->timestamp());
switch (touchEvent.type()) {
@@ -6049,12 +5930,11 @@ void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
// if the TouchBegin handler recurses, we assume that means the event
// has been implicitly accepted and continue to send touch events
item->d_ptr->acceptedTouchBeginEvent = true;
- bool res = sendTouchBeginEvent(item, &touchEvent)
- && touchEvent.isAccepted();
+ bool res = sendTouchBeginEvent(item, &touchEvent) && touchEvent.isAccepted();
if (!res) {
// forget about these touch points, we didn't handle them
- for (int i = 0; i < touchEvent.touchPoints().count(); ++i) {
- const QTouchEvent::TouchPoint &touchPoint = touchEvent.touchPoints().at(i);
+ const auto &unhandledTouchPoints = touchEvent.points();
+ for (const auto &touchPoint : unhandledTouchPoints) {
itemForTouchPointId.remove(touchPoint.id());
sceneCurrentTouchPoints.remove(touchPoint.id());
}
@@ -6071,7 +5951,8 @@ void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
break;
}
}
- sceneTouchEvent->setAccepted(ignoreSceneTouchEvent);
+ // don't override the acceptance state of the individual points
+ sceneTouchEvent->QInputEvent::setAccepted(ignoreSceneTouchEvent);
}
bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEvent *touchEvent)
@@ -6080,16 +5961,16 @@ bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEve
if (focusOnTouch) {
if (cachedItemsUnderMouse.isEmpty() || cachedItemsUnderMouse.constFirst() != origin) {
- const QTouchEvent::TouchPoint &firstTouchPoint = touchEvent->touchPoints().first();
- cachedItemsUnderMouse = itemsAtPosition(firstTouchPoint.screenPos().toPoint(),
- firstTouchPoint.scenePos(),
+ const QEventPoint &firstTouchPoint = touchEvent->points().first();
+ cachedItemsUnderMouse = itemsAtPosition(firstTouchPoint.globalPosition().toPoint(),
+ firstTouchPoint.scenePosition(),
static_cast<QWidget *>(touchEvent->target()));
}
// Set focus on the topmost enabled item that can take focus.
bool setFocus = false;
- foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
+ for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) {
if (item->isEnabled() && ((item->flags() & QGraphicsItem::ItemIsFocusable) && item->d_ptr->mouseSetsFocus)) {
if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
setFocus = true;
@@ -6116,46 +5997,46 @@ bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEve
bool res = false;
bool eventAccepted = touchEvent->isAccepted();
- foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
+ for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) {
// first, try to deliver the touch event
updateTouchPointsForItem(item, touchEvent);
bool acceptTouchEvents = item->acceptTouchEvents();
touchEvent->setAccepted(acceptTouchEvents);
res = acceptTouchEvents && sendEvent(item, touchEvent);
eventAccepted = touchEvent->isAccepted();
- if (itemForTouchPointId.value(touchEvent->touchPoints().first().id()) == 0) {
+ if (itemForTouchPointId.value(touchEvent->points().first().id()) == 0) {
// item was deleted
item = nullptr;
} else {
item->d_ptr->acceptedTouchBeginEvent = (res && eventAccepted);
}
- touchEvent->spont = false;
+ touchEvent->m_spont = false;
if (res && eventAccepted) {
// the first item to accept the TouchBegin gets an implicit grab.
- for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
- const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i);
+ const auto &touchPoints = touchEvent->points();
+ for (const auto &touchPoint : touchPoints)
itemForTouchPointId[touchPoint.id()] = item; // can be zero
- }
break;
}
if (item && item->isPanel())
break;
}
- touchEvent->setAccepted(eventAccepted);
+ // don't override the acceptance state of the touch points
+ touchEvent->QInputEvent::setAccepted(eventAccepted);
return res;
}
void QGraphicsScenePrivate::enableTouchEventsOnViews()
{
- foreach (QGraphicsView *view, views)
+ for (QGraphicsView *view : std::as_const(views))
view->viewport()->setAttribute(Qt::WA_AcceptTouchEvents, true);
}
void QGraphicsScenePrivate::updateInputMethodSensitivityInViews()
{
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->updateInputMethodSensitivity();
+ for (auto view : std::as_const(views))
+ view->d_func()->updateInputMethodSensitivity();
}
void QGraphicsScenePrivate::enterModal(QGraphicsItem *panel, QGraphicsItem::PanelModality previousModality)
@@ -6171,11 +6052,12 @@ void QGraphicsScenePrivate::enterModal(QGraphicsItem *panel, QGraphicsItem::Pane
}
QSet<QGraphicsItem *> blockedPanels;
- QList<QGraphicsItem *> items = q->items(); // ### store panels separately
- for (int i = 0; i < items.count(); ++i) {
- QGraphicsItem *item = items.at(i);
- if (item->isPanel() && item->isBlockedByModalPanel())
- blockedPanels.insert(item);
+ {
+ const auto items_ = q->items();
+ for (const auto &item : items_) {
+ if (item->isPanel() && item->isBlockedByModalPanel())
+ blockedPanels.insert(item);
+ }
}
// blockedPanels contains all currently blocked panels
@@ -6203,8 +6085,8 @@ void QGraphicsScenePrivate::enterModal(QGraphicsItem *panel, QGraphicsItem::Pane
QEvent windowBlockedEvent(QEvent::WindowBlocked);
QEvent windowUnblockedEvent(QEvent::WindowUnblocked);
- for (int i = 0; i < items.count(); ++i) {
- QGraphicsItem *item = items.at(i);
+ const auto items_ = q->items();
+ for (const auto &item : items_) {
if (item->isPanel()) {
if (!blockedPanels.contains(item) && item->isBlockedByModalPanel()) {
// send QEvent::WindowBlocked to newly blocked panels
@@ -6224,20 +6106,23 @@ void QGraphicsScenePrivate::leaveModal(QGraphicsItem *panel)
Q_ASSERT(panel && panel->isPanel());
QSet<QGraphicsItem *> blockedPanels;
- QList<QGraphicsItem *> items = q->items(); // ### same as above
- for (int i = 0; i < items.count(); ++i) {
- QGraphicsItem *item = items.at(i);
- if (item->isPanel() && item->isBlockedByModalPanel())
- blockedPanels.insert(item);
+ {
+ const auto items_ = q->items();
+ for (const auto &item : items_) {
+ if (item->isPanel() && item->isBlockedByModalPanel())
+ blockedPanels.insert(item);
+ }
}
modalPanels.removeAll(panel);
- QEvent e(QEvent::WindowUnblocked);
- for (int i = 0; i < items.count(); ++i) {
- QGraphicsItem *item = items.at(i);
- if (item->isPanel() && blockedPanels.contains(item) && !item->isBlockedByModalPanel())
- sendEvent(item, &e);
+ {
+ QEvent e(QEvent::WindowUnblocked);
+ const auto items_ = q->items();
+ for (const auto &item : items_) {
+ if (item->isPanel() && blockedPanels.contains(item) && !item->isBlockedByModalPanel())
+ sendEvent(item, &e);
+ }
}
// send GraphicsSceneHoverEnter events to newly unblocked items
@@ -6259,7 +6144,7 @@ void QGraphicsScenePrivate::gestureTargetsAtHotSpots(const QSet<QGesture *> &ges
if (!gesture->hasHotSpot())
continue;
const Qt::GestureType gestureType = gesture->gestureType();
- QList<QGraphicsItem *> items = itemsAtPosition(QPoint(), gesture->d_func()->sceneHotSpot, nullptr);
+ const QList<QGraphicsItem *> items = itemsAtPosition(QPoint(), gesture->d_func()->sceneHotSpot, nullptr);
for (int j = 0; j < items.size(); ++j) {
QGraphicsItem *item = items.at(j);
@@ -6431,9 +6316,9 @@ void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
std::sort(cachedTargetItems.begin(), cachedTargetItems.end(), qt_closestItemFirst);
for (int i = 0; i < cachedTargetItems.size(); ++i) {
QPointer<QGraphicsObject> receiver = cachedTargetItems.at(i);
- QSet<QGesture *> gestures =
- undeliveredGestures & cachedItemGestures.value(receiver.data());
- gestures -= cachedAlreadyDeliveredGestures.value(receiver.data());
+ const QSet<QGesture *> gestures = (undeliveredGestures
+ & cachedItemGestures.value(receiver.data()))
+ - cachedAlreadyDeliveredGestures.value(receiver.data());
if (gestures.isEmpty())
continue;
@@ -6448,7 +6333,7 @@ void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
ev.setWidget(event->widget());
sendEvent(receiver.data(), &ev);
QSet<QGesture *> ignoredGestures;
- for (QGesture *g : qAsConst(gestures)) {
+ for (QGesture *g : gestures) {
if (!ev.isAccepted() && !ev.isAccepted(g)) {
// if the gesture was ignored by its target, we will update the
// targetItems list with a possible target items (items that
@@ -6516,7 +6401,7 @@ void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
}
}
- foreach (QGesture *g, startedGestures) {
+ for (QGesture *g : std::as_const(startedGestures)) {
if (g->gestureCancelPolicy() == QGesture::CancelAllInContext) {
DEBUG() << "lets try to cancel some";
// find gestures in context in Qt::GestureStarted or Qt::GestureUpdated state and cancel them
@@ -6598,17 +6483,17 @@ void QGraphicsScenePrivate::cancelGesturesForChildren(QGesture *original)
if (!g->hasHotSpot())
continue;
- QList<QGraphicsItem *> items = itemsAtPosition(QPoint(), g->d_func()->sceneHotSpot, nullptr);
- for (int j = 0; j < items.size(); ++j) {
- QGraphicsObject *item = items.at(j)->toGraphicsObject();
- if (!item)
+ const QList<QGraphicsItem *> items = itemsAtPosition(QPoint(), g->d_func()->sceneHotSpot, nullptr);
+ for (const auto &item : items) {
+ QGraphicsObject *object = item->toGraphicsObject();
+ if (!object)
continue;
- QGraphicsItemPrivate *d = item->QGraphicsItem::d_func();
+ QGraphicsItemPrivate *d = object->QGraphicsItem::d_func();
if (d->gestureContext.contains(g->gestureType())) {
QList<QGesture *> list;
list << g;
QGestureEvent ev(list);
- sendEvent(item, &ev);
+ sendEvent(object, &ev);
if (ev.isAccepted() || ev.isAccepted(g))
break; // successfully delivered
}
@@ -6629,7 +6514,7 @@ void QGraphicsScenePrivate::grabGesture(QGraphicsItem *, Qt::GestureType gesture
{
(void)QGestureManager::instance(); // create a gesture manager
if (!grabbedGestures[gesture]++) {
- foreach (QGraphicsView *view, views)
+ for (QGraphicsView *view : std::as_const(views))
view->viewport()->grabGesture(gesture);
}
}
@@ -6641,7 +6526,7 @@ void QGraphicsScenePrivate::ungrabGesture(QGraphicsItem *item, Qt::GestureType g
QGraphicsObject *obj = static_cast<QGraphicsObject *>(item);
QGestureManager::instance()->cleanupCachedGestures(obj, gesture);
if (!--grabbedGestures[gesture]) {
- foreach (QGraphicsView *view, views)
+ for (QGraphicsView *view : std::as_const(views))
view->viewport()->ungrabGesture(gesture);
}
}
diff --git a/src/widgets/graphicsview/qgraphicsscene.h b/src/widgets/graphicsview/qgraphicsscene.h
index e72ed99a7b..33fb747277 100644
--- a/src/widgets/graphicsview/qgraphicsscene.h
+++ b/src/widgets/graphicsview/qgraphicsscene.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSSCENE_H
#define QGRAPHICSSCENE_H
@@ -47,7 +11,6 @@
#include <QtGui/qbrush.h>
#include <QtGui/qfont.h>
#include <QtGui/qtransform.h>
-#include <QtGui/qmatrix.h>
#include <QtGui/qpen.h>
QT_REQUIRE_CONFIG(graphicsview);
@@ -102,9 +65,6 @@ class Q_WIDGETS_EXPORT QGraphicsScene : public QObject
Q_PROPERTY(int bspTreeDepth READ bspTreeDepth WRITE setBspTreeDepth)
Q_PROPERTY(QPalette palette READ palette WRITE setPalette)
Q_PROPERTY(QFont font READ font WRITE setFont)
-#if QT_DEPRECATED_SINCE(5, 13)
- Q_PROPERTY(bool sortCacheEnabled READ isSortCacheEnabled WRITE setSortCacheEnabled)
-#endif
Q_PROPERTY(bool stickyFocus READ stickyFocus WRITE setStickyFocus)
Q_PROPERTY(qreal minimumRenderSize READ minimumRenderSize WRITE setMinimumRenderSize)
Q_PROPERTY(bool focusOnTouch READ focusOnTouch WRITE setFocusOnTouch)
@@ -142,11 +102,6 @@ public:
ItemIndexMethod itemIndexMethod() const;
void setItemIndexMethod(ItemIndexMethod method);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED bool isSortCacheEnabled() const;
- QT_DEPRECATED void setSortCacheEnabled(bool enabled);
-#endif
-
int bspTreeDepth() const;
void setBspTreeDepth(int depth);
@@ -158,37 +113,19 @@ public:
QList<QGraphicsItem *> items(const QRectF &rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, Qt::SortOrder order = Qt::DescendingOrder, const QTransform &deviceTransform = QTransform()) const;
QList<QGraphicsItem *> items(const QPolygonF &polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, Qt::SortOrder order = Qt::DescendingOrder, const QTransform &deviceTransform = QTransform()) const;
QList<QGraphicsItem *> items(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, Qt::SortOrder order = Qt::DescendingOrder, const QTransform &deviceTransform = QTransform()) const;
-
- QList<QGraphicsItem *> collidingItems(const QGraphicsItem *item, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline QGraphicsItem *itemAt(const QPointF &position) const {
- QList<QGraphicsItem *> itemsAtPoint = items(position);
- return itemsAtPoint.isEmpty() ? nullptr : itemsAtPoint.first();
- }
-#endif
- QGraphicsItem *itemAt(const QPointF &pos, const QTransform &deviceTransform) const;
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline QList<QGraphicsItem *> items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
- { return items(QRectF(x, y, w, h), mode); }
-#endif
inline QList<QGraphicsItem *> items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode, Qt::SortOrder order,
const QTransform &deviceTransform = QTransform()) const
{ return items(QRectF(x, y, w, h), mode, order, deviceTransform); }
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED inline QGraphicsItem *itemAt(qreal x, qreal y) const {
- QList<QGraphicsItem *> itemsAtPoint = items(QPointF(x, y));
- return itemsAtPoint.isEmpty() ? nullptr : itemsAtPoint.first();
- }
-#endif
+
+ QList<QGraphicsItem *> collidingItems(const QGraphicsItem *item, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
+ QGraphicsItem *itemAt(const QPointF &pos, const QTransform &deviceTransform) const;
inline QGraphicsItem *itemAt(qreal x, qreal y, const QTransform &deviceTransform) const
{ return itemAt(QPointF(x, y), deviceTransform); }
QList<QGraphicsItem *> selectedItems() const;
QPainterPath selectionArea() const;
void setSelectionArea(const QPainterPath &path, const QTransform &deviceTransform);
- void setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, const QTransform &deviceTransform = QTransform());
- void setSelectionArea(const QPainterPath &path, Qt::ItemSelectionOperation selectionOperation, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, const QTransform &deviceTransform = QTransform());
- // ### Qt6 merge the last 2 functions and add a default: Qt::ItemSelectionOperation selectionOperation = Qt::ReplaceSelection
+ void setSelectionArea(const QPainterPath &path, Qt::ItemSelectionOperation selectionOperation = Qt::ReplaceSelection, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, const QTransform &deviceTransform = QTransform());
QGraphicsItemGroup *createItemGroup(const QList<QGraphicsItem *> &items);
void destroyItemGroup(QGraphicsItemGroup *group);
@@ -295,7 +232,7 @@ protected:
QWidget *widget = nullptr);
protected Q_SLOTS:
- QT6_VIRTUAL bool focusNextPrevChild(bool next);
+ virtual bool focusNextPrevChild(bool next);
Q_SIGNALS:
void changed(const QList<QRectF> &region);
diff --git a/src/widgets/graphicsview/qgraphicsscene_bsp.cpp b/src/widgets/graphicsview/qgraphicsscene_bsp.cpp
index 75eb50a3ac..1ba6fe787a 100644
--- a/src/widgets/graphicsview/qgraphicsscene_bsp.cpp
+++ b/src/widgets/graphicsview/qgraphicsscene_bsp.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgraphicsscene_bsp_p.h"
@@ -44,57 +8,14 @@
QT_BEGIN_NAMESPACE
-class QGraphicsSceneInsertItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
-{
-public:
- QGraphicsItem *item;
-
- void visit(QList<QGraphicsItem *> *items) override
- { items->prepend(item); }
-};
-
-class QGraphicsSceneRemoveItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
-{
-public:
- QGraphicsItem *item;
-
- void visit(QList<QGraphicsItem *> *items) override
- { items->removeAll(item); }
-};
-
-class QGraphicsSceneFindItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
-{
-public:
- QList<QGraphicsItem *> *foundItems;
- bool onlyTopLevelItems;
-
- void visit(QList<QGraphicsItem *> *items) override
- {
- for (int i = 0; i < items->size(); ++i) {
- QGraphicsItem *item = items->at(i);
- if (onlyTopLevelItems && item->d_ptr->parent)
- item = item->topLevelItem();
- if (!item->d_func()->itemDiscovered && item->d_ptr->visible) {
- item->d_func()->itemDiscovered = 1;
- foundItems->prepend(item);
- }
- }
- }
-};
QGraphicsSceneBspTree::QGraphicsSceneBspTree()
: leafCnt(0)
{
- insertVisitor = new QGraphicsSceneInsertItemBspTreeVisitor;
- removeVisitor = new QGraphicsSceneRemoveItemBspTreeVisitor;
- findVisitor = new QGraphicsSceneFindItemBspTreeVisitor;
}
QGraphicsSceneBspTree::~QGraphicsSceneBspTree()
{
- delete insertVisitor;
- delete removeVisitor;
- delete findVisitor;
}
void QGraphicsSceneBspTree::initialize(const QRectF &rect, int depth)
@@ -103,7 +24,7 @@ void QGraphicsSceneBspTree::initialize(const QRectF &rect, int depth)
leafCnt = 0;
nodes.resize((1 << (depth + 1)) - 1);
nodes.fill(Node());
- leaves.resize(1 << depth);
+ leaves.resize(1ll << depth);
leaves.fill(QList<QGraphicsItem *>());
initialize(rect, depth, 0);
@@ -118,14 +39,16 @@ void QGraphicsSceneBspTree::clear()
void QGraphicsSceneBspTree::insertItem(QGraphicsItem *item, const QRectF &rect)
{
- insertVisitor->item = item;
- climbTree(insertVisitor, rect);
+ climbTree([item](QList<QGraphicsItem *> *items){
+ items->prepend(item);
+ }, rect);
}
void QGraphicsSceneBspTree::removeItem(QGraphicsItem *item, const QRectF &rect)
{
- removeVisitor->item = item;
- climbTree(removeVisitor, rect);
+ climbTree([item](QList<QGraphicsItem *> *items){
+ items->removeAll(item);
+ }, rect);
}
void QGraphicsSceneBspTree::removeItems(const QSet<QGraphicsItem *> &items)
@@ -144,14 +67,22 @@ void QGraphicsSceneBspTree::removeItems(const QSet<QGraphicsItem *> &items)
QList<QGraphicsItem *> QGraphicsSceneBspTree::items(const QRectF &rect, bool onlyTopLevelItems) const
{
- QList<QGraphicsItem *> tmp;
- findVisitor->foundItems = &tmp;
- findVisitor->onlyTopLevelItems = onlyTopLevelItems;
- climbTree(findVisitor, rect);
+ QList<QGraphicsItem *> foundItems;
+ climbTree([&foundItems, onlyTopLevelItems](QList<QGraphicsItem *> *items) {
+ for (int i = 0; i < items->size(); ++i) {
+ QGraphicsItem *item = items->at(i);
+ if (onlyTopLevelItems && item->d_ptr->parent)
+ item = item->topLevelItem();
+ if (!item->d_func()->itemDiscovered && item->d_ptr->visible) {
+ item->d_func()->itemDiscovered = 1;
+ foundItems.prepend(item);
+ }
+ }
+ }, rect);
// Reset discovery bits.
- for (int i = 0; i < tmp.size(); ++i)
- tmp.at(i)->d_ptr->itemDiscovered = 0;
- return tmp;
+ for (const auto &foundItem : std::as_const(foundItems))
+ foundItem->d_ptr->itemDiscovered = 0;
+ return foundItems;
}
int QGraphicsSceneBspTree::leafCount() const
@@ -190,7 +121,7 @@ void QGraphicsSceneBspTree::initialize(const QRectF &rect, int depth, int index)
Node *node = &nodes[index];
if (index == 0) {
node->type = Node::Horizontal;
- node->offset = rect.center().x();
+ node->offset = rect.center().y();
}
if (depth) {
@@ -230,7 +161,8 @@ void QGraphicsSceneBspTree::initialize(const QRectF &rect, int depth, int index)
}
}
-void QGraphicsSceneBspTree::climbTree(QGraphicsSceneBspTreeVisitor *visitor, const QRectF &rect, int index) const
+template<typename Visitor>
+void QGraphicsSceneBspTree::climbTree(Visitor &&visitor, const QRectF &rect, int index) const
{
if (nodes.isEmpty())
return;
@@ -240,7 +172,7 @@ void QGraphicsSceneBspTree::climbTree(QGraphicsSceneBspTreeVisitor *visitor, con
switch (node.type) {
case Node::Leaf: {
- visitor->visit(const_cast<QList<QGraphicsItem*>*>(&leaves[node.leafIndex]));
+ visitor(const_cast<QList<QGraphicsItem*>*>(&leaves[node.leafIndex]));
break;
}
case Node::Vertical:
@@ -272,7 +204,7 @@ QRectF QGraphicsSceneBspTree::rectForIndex(int index) const
QRectF rect = rectForIndex(parentIdx);
const Node *parent = &nodes.at(parentIdx);
- if (parent->type == Node::Horizontal) {
+ if (parent->type == Node::Vertical) {
if (index & 1)
rect.setRight(parent->offset);
else
diff --git a/src/widgets/graphicsview/qgraphicsscene_bsp_p.h b/src/widgets/graphicsview/qgraphicsscene_bsp_p.h
index 26e612b2dd..9e0fa919b7 100644
--- a/src/widgets/graphicsview/qgraphicsscene_bsp_p.h
+++ b/src/widgets/graphicsview/qgraphicsscene_bsp_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSSCENEBSPTREE_P_H
#define QGRAPHICSSCENEBSPTREE_P_H
@@ -53,20 +17,14 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtCore/qlist.h>
-
#include <QtCore/qrect.h>
#include <QtCore/qset.h>
-#include <QtCore/qvector.h>
QT_REQUIRE_CONFIG(graphicsview);
QT_BEGIN_NAMESPACE
class QGraphicsItem;
-class QGraphicsSceneBspTreeVisitor;
-class QGraphicsSceneInsertItemBspTreeVisitor;
-class QGraphicsSceneRemoveItemBspTreeVisitor;
-class QGraphicsSceneFindItemBspTreeVisitor;
class QGraphicsSceneBspTree
{
@@ -104,24 +62,14 @@ public:
private:
void initialize(const QRectF &rect, int depth, int index);
- void climbTree(QGraphicsSceneBspTreeVisitor *visitor, const QRectF &rect, int index = 0) const;
+ template<typename Visitor>
+ void climbTree(Visitor &&visitor, const QRectF &rect, int index = 0) const;
QRectF rectForIndex(int index) const;
- QVector<Node> nodes;
- QVector<QList<QGraphicsItem *> > leaves;
+ QList<Node> nodes;
+ QList<QList<QGraphicsItem *>> leaves;
int leafCnt;
QRectF rect;
-
- QGraphicsSceneInsertItemBspTreeVisitor *insertVisitor;
- QGraphicsSceneRemoveItemBspTreeVisitor *removeVisitor;
- QGraphicsSceneFindItemBspTreeVisitor *findVisitor;
-};
-
-class QGraphicsSceneBspTreeVisitor
-{
-public:
- virtual ~QGraphicsSceneBspTreeVisitor() { }
- virtual void visit(QList<QGraphicsItem *> *items) = 0;
};
QT_END_NAMESPACE
diff --git a/src/widgets/graphicsview/qgraphicsscene_p.h b/src/widgets/graphicsview/qgraphicsscene_p.h
index 9ecfca8ebf..c4b8b4e867 100644
--- a/src/widgets/graphicsview/qgraphicsscene_p.h
+++ b/src/widgets/graphicsview/qgraphicsscene_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSSCENE_P_H
#define QGRAPHICSSCENE_P_H
@@ -142,7 +106,7 @@ public:
QPainterPath selectionArea;
int selectionChanging;
QSet<QGraphicsItem *> selectedItems;
- QVector<QGraphicsItem *> unpolishedItems;
+ QList<QGraphicsItem *> unpolishedItems;
QList<QGraphicsItem *> topLevelItems;
QHash<QGraphicsItem *, QPointF> movingItemsInitialPositions;
@@ -309,7 +273,7 @@ public:
QStyleOptionGraphicsItem styleOptionTmp;
- QMap<int, QTouchEvent::TouchPoint> sceneCurrentTouchPoints;
+ QMap<int, QEventPoint> sceneCurrentTouchPoints;
QMap<int, QGraphicsItem *> itemForTouchPointId;
static void updateTouchPointsForItem(QGraphicsItem *item, QTouchEvent *touchEvent);
int findClosestTouchPointId(const QPointF &scenePos);
diff --git a/src/widgets/graphicsview/qgraphicsscenebsptreeindex.cpp b/src/widgets/graphicsview/qgraphicsscenebsptreeindex.cpp
index 69ddf54bc7..8a11489308 100644
--- a/src/widgets/graphicsview/qgraphicsscenebsptreeindex.cpp
+++ b/src/widgets/graphicsview/qgraphicsscenebsptreeindex.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsSceneBspTreeIndex
diff --git a/src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h b/src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h
index 7e0e525a6b..bd9894d5fe 100644
--- a/src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h
+++ b/src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtCore module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
//
// W A R N I N G
diff --git a/src/widgets/graphicsview/qgraphicssceneevent.cpp b/src/widgets/graphicsview/qgraphicssceneevent.cpp
index 048ea6dc7d..0ace03b553 100644
--- a/src/widgets/graphicsview/qgraphicssceneevent.cpp
+++ b/src/widgets/graphicsview/qgraphicssceneevent.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsSceneEvent
@@ -287,6 +251,7 @@ public:
QWidget *widget;
QGraphicsSceneEvent *q_ptr;
+ quint64 timestamp = 0;
};
/*!
@@ -339,6 +304,26 @@ void QGraphicsSceneEvent::setWidget(QWidget *widget)
d_ptr->widget = widget;
}
+/*!
+ \since 6.2
+
+ Returns the timestamp of the original event, or 0 if the
+ original event does not report a time stamp.
+*/
+quint64 QGraphicsSceneEvent::timestamp() const
+{
+ return d_ptr->timestamp;
+}
+/*!
+ \internal
+
+ Sets the timestamp for the event to \a ts.
+*/
+void QGraphicsSceneEvent::setTimestamp(quint64 ts)
+{
+ d_ptr->timestamp = ts;
+}
+
class QGraphicsSceneMouseEventPrivate : public QGraphicsSceneEventPrivate
{
Q_DECLARE_PUBLIC(QGraphicsSceneMouseEvent)
@@ -695,10 +680,13 @@ public:
QPointF pos;
QPointF scenePos;
QPoint screenPos;
+ QPoint pixelDelta;
Qt::MouseButtons buttons;
Qt::KeyboardModifiers modifiers;
int delta = 0;
Qt::Orientation orientation = Qt::Horizontal;
+ Qt::ScrollPhase scrollPhase = Qt::NoScrollPhase;
+ bool inverted = false;
};
/*!
@@ -865,6 +853,73 @@ void QGraphicsSceneWheelEvent::setOrientation(Qt::Orientation orientation)
d->orientation = orientation;
}
+/*!
+ \since 6.2
+
+ Returns the scrolling phase of this wheel event.
+
+ \sa QWheelEvent::phase
+*/
+Qt::ScrollPhase QGraphicsSceneWheelEvent::phase() const
+{
+ Q_D(const QGraphicsSceneWheelEvent);
+ return d->scrollPhase;
+}
+
+/*!
+ \internal
+*/
+void QGraphicsSceneWheelEvent::setPhase(Qt::ScrollPhase scrollPhase)
+{
+ Q_D(QGraphicsSceneWheelEvent);
+ d->scrollPhase = scrollPhase;
+}
+
+/*!
+ \since 6.2
+
+ Returns the scrolling distance in pixels on screen. This value is
+ provided on platforms that support high-resolution pixel-based
+ delta values, such as \macos. The value should be used directly
+ to scroll content on screen.
+
+ \sa QWheelEvent::pixelDelta
+*/
+QPoint QGraphicsSceneWheelEvent::pixelDelta() const
+{
+ Q_D(const QGraphicsSceneWheelEvent);
+ return d->pixelDelta;
+}
+
+/*!
+ \internal
+*/
+void QGraphicsSceneWheelEvent::setPixelDelta(QPoint pixelDelta)
+{
+ Q_D(QGraphicsSceneWheelEvent);
+ d->pixelDelta = pixelDelta;
+}
+
+/*!
+ Returns whether the delta values delivered with the event are inverted.
+
+ \since 6.2
+*/
+bool QGraphicsSceneWheelEvent::isInverted() const
+{
+ Q_D(const QGraphicsSceneWheelEvent);
+ return d->inverted;
+}
+
+/*!
+ \internal
+*/
+void QGraphicsSceneWheelEvent::setInverted(bool inverted)
+{
+ Q_D(QGraphicsSceneWheelEvent);
+ d->inverted = inverted;
+}
+
class QGraphicsSceneContextMenuEventPrivate : public QGraphicsSceneEventPrivate
{
Q_DECLARE_PUBLIC(QGraphicsSceneContextMenuEvent)
diff --git a/src/widgets/graphicsview/qgraphicssceneevent.h b/src/widgets/graphicsview/qgraphicssceneevent.h
index 9d940be2c0..ca9dd639a3 100644
--- a/src/widgets/graphicsview/qgraphicssceneevent.h
+++ b/src/widgets/graphicsview/qgraphicssceneevent.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSSCENEEVENT_H
#define QGRAPHICSSCENEEVENT_H
@@ -47,9 +11,6 @@
#include <QtCore/qrect.h>
#include <QtGui/qpolygon.h>
#include <QtCore/qset.h>
-#if QT_DEPRECATED_SINCE(5, 5)
-#include <QtCore/qhash.h>
-#endif
QT_REQUIRE_CONFIG(graphicsview);
@@ -70,6 +31,9 @@ public:
QWidget *widget() const;
void setWidget(QWidget *widget);
+ quint64 timestamp() const;
+ void setTimestamp(quint64 ts);
+
protected:
QGraphicsSceneEvent(QGraphicsSceneEventPrivate &dd, Type type = None);
QScopedPointer<QGraphicsSceneEventPrivate> d_ptr;
@@ -160,6 +124,15 @@ public:
Qt::Orientation orientation() const;
void setOrientation(Qt::Orientation orientation);
+ Qt::ScrollPhase phase() const;
+ void setPhase(Qt::ScrollPhase scrollPhase);
+
+ QPoint pixelDelta() const;
+ void setPixelDelta(QPoint delta);
+
+ bool isInverted() const;
+ void setInverted(bool inverted);
+
private:
Q_DECLARE_PRIVATE(QGraphicsSceneWheelEvent)
Q_DISABLE_COPY(QGraphicsSceneWheelEvent)
diff --git a/src/widgets/graphicsview/qgraphicssceneindex.cpp b/src/widgets/graphicsview/qgraphicssceneindex.cpp
index c2e9cb4729..7c54bfe179 100644
--- a/src/widgets/graphicsview/qgraphicssceneindex.cpp
+++ b/src/widgets/graphicsview/qgraphicssceneindex.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsSceneIndex
\brief The QGraphicsSceneIndex class provides a base class to implement
@@ -60,6 +24,7 @@
#include "qgraphicswidget.h"
#include "qgraphicssceneindex_p.h"
#include "qgraphicsscenebsptreeindex_p.h"
+#include <QtGui/qpainterpath.h>
QT_BEGIN_NAMESPACE
@@ -580,7 +545,7 @@ void QGraphicsSceneIndex::clear()
/*!
This method is called when an \a item has been deleted.
- The default implementation call removeItem. Be carefull,
+ The default implementation calls removeItem. Be careful,
if your implementation of removeItem use pure virtual method
of QGraphicsItem like boundingRect(), then you should reimplement
this method.
diff --git a/src/widgets/graphicsview/qgraphicssceneindex_p.h b/src/widgets/graphicsview/qgraphicssceneindex_p.h
index e13c2a3cd3..8bd2ef4854 100644
--- a/src/widgets/graphicsview/qgraphicssceneindex_p.h
+++ b/src/widgets/graphicsview/qgraphicssceneindex_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtCore module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSSCENEINDEX_H
#define QGRAPHICSSCENEINDEX_H
diff --git a/src/widgets/graphicsview/qgraphicsscenelinearindex.cpp b/src/widgets/graphicsview/qgraphicsscenelinearindex.cpp
index 06f9125612..c014783438 100644
--- a/src/widgets/graphicsview/qgraphicsscenelinearindex.cpp
+++ b/src/widgets/graphicsview/qgraphicsscenelinearindex.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsSceneLinearIndex
@@ -54,7 +18,7 @@
#include <private/qgraphicsscenelinearindex_p.h>
/*!
- \fn QGraphicsSceneLinearIndex::QGraphicsSceneLinearIndex(QGraphicsScene *scene = 0):
+ \fn QGraphicsSceneLinearIndex::QGraphicsSceneLinearIndex(QGraphicsScene *scene = nullptr):
Construct a linear index for the given \a scene.
*/
diff --git a/src/widgets/graphicsview/qgraphicsscenelinearindex_p.h b/src/widgets/graphicsview/qgraphicsscenelinearindex_p.h
index ead52c1fb0..e0a038a927 100644
--- a/src/widgets/graphicsview/qgraphicsscenelinearindex_p.h
+++ b/src/widgets/graphicsview/qgraphicsscenelinearindex_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtCore module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSSCENELINEARINDEX_H
#define QGRAPHICSSCENELINEARINDEX_H
diff --git a/src/widgets/graphicsview/qgraphicstransform.cpp b/src/widgets/graphicsview/qgraphicstransform.cpp
index fa763de05d..172bdff081 100644
--- a/src/widgets/graphicsview/qgraphicstransform.cpp
+++ b/src/widgets/graphicsview/qgraphicstransform.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtDeclarative module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QGraphicsTransform
@@ -593,6 +557,6 @@ void QGraphicsRotation::applyTo(QMatrix4x4 *matrix) const
\sa QGraphicsRotation::axis
*/
-#include "moc_qgraphicstransform.cpp"
-
QT_END_NAMESPACE
+
+#include "moc_qgraphicstransform.cpp"
diff --git a/src/widgets/graphicsview/qgraphicstransform.h b/src/widgets/graphicsview/qgraphicstransform.h
index b8455781c5..903320cb62 100644
--- a/src/widgets/graphicsview/qgraphicstransform.h
+++ b/src/widgets/graphicsview/qgraphicstransform.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSTRANSFORM_H
#define QGRAPHICSTRANSFORM_H
diff --git a/src/widgets/graphicsview/qgraphicstransform_p.h b/src/widgets/graphicsview/qgraphicstransform_p.h
index 05e12c3e64..4c08c1c106 100644
--- a/src/widgets/graphicsview/qgraphicstransform_p.h
+++ b/src/widgets/graphicsview/qgraphicstransform_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSTRANSFORM_P_H
#define QGRAPHICSTRANSFORM_P_H
@@ -60,8 +24,7 @@ QT_BEGIN_NAMESPACE
class QGraphicsItem;
-// ### Qt 6: unexport again, if QtQuick1's QDeclarativeTranslatePrivate is gone by then
-class Q_WIDGETS_EXPORT QGraphicsTransformPrivate : public QObjectPrivate {
+class QGraphicsTransformPrivate : public QObjectPrivate {
public:
Q_DECLARE_PUBLIC(QGraphicsTransform)
diff --git a/src/widgets/graphicsview/qgraphicsview.cpp b/src/widgets/graphicsview/qgraphicsview.cpp
index 7589a1ebbd..9505e2529a 100644
--- a/src/widgets/graphicsview/qgraphicsview.cpp
+++ b/src/widgets/graphicsview/qgraphicsview.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 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
static const int QGRAPHICSVIEW_REGION_RECT_THRESHOLD = 50;
@@ -89,15 +53,15 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime <
By default, QGraphicsView provides a regular QWidget for the viewport
widget. You can access this widget by calling viewport(), or you can
replace it by calling setViewport(). To render using OpenGL, simply call
- setViewport(new QGLWidget). QGraphicsView takes ownership of the viewport
- widget.
+ setViewport(new QOpenGLWidget). QGraphicsView takes ownership of the
+ viewport widget.
QGraphicsView supports affine transformations, using QTransform. You can
either pass a matrix to setTransform(), or you can call one of the
convenience functions rotate(), scale(), translate() or shear(). The most
two common transformations are scaling, which is used to implement
zooming, and rotation. QGraphicsView keeps the center of the view fixed
- during a transformation. Because of the scene alignment (setAligment()),
+ during a transformation. Because of the scene alignment (setAlignment()),
translating the view will have no visual impact.
You can interact with the items on the scene by using the mouse and
@@ -107,7 +71,7 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime <
the events and reacts to them. For example, if you click on a selectable
item, the item will typically let the scene know that it has been
selected, and it will also redraw itself to display a selection
- rectangle. Similiary, if you click and drag the mouse to move a movable
+ rectangle. Similarly, if you click and drag the mouse to move a movable
item, it's the item that handles the mouse moves and moves itself. Item
interaction is enabled by default, and you can toggle it by calling
setInteractive().
@@ -121,8 +85,22 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime <
view coordinates and scene coordinates, and to find items on the scene
using view coordinates.
+ When using a QOpenGLWidget as a viewport, stereoscopic rendering is
+ supported. This is done using the same pattern as QOpenGLWidget::paintGL.
+ To enable it, enable the QSurfaceFormat::StereoBuffers flag. Because of
+ how the flag is handled internally, set QSurfaceFormat::StereoBuffers flag
+ globally before the window is created using QSurfaceFormat::setDefaultFormat().
+ If the flag is enabled and there is hardware support for stereoscopic
+ rendering, then drawBackground() and drawForeground() will be triggered twice
+ each frame. Call QOpenGLWidget::currentTargetBuffer() to query which buffer
+ is currently being drawn to.
+
\image graphicsview-view.png
+ \note Using an OpenGL viewport limits the ability to use QGraphicsProxyWidget.
+ Not all combinations of widgets and styles can be supported with such a setup.
+ You should carefully test your UI and make the necessary adjustments.
+
\sa QGraphicsScene, QGraphicsItem, QGraphicsSceneEvent
*/
@@ -155,8 +133,8 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime <
fastest when QGraphicsView spends more time figuring out what to draw than
it would spend drawing (e.g., when very many small items are repeatedly
updated). This is the preferred update mode for viewports that do not
- support partial updates, such as QGLWidget, and for viewports that need to
- disable scroll optimization.
+ support partial updates, such as QOpenGLWidget, and for viewports that
+ need to disable scroll optimization.
\value MinimalViewportUpdate QGraphicsView will determine the minimal
viewport region that requires a redraw, minimizing the time spent drawing
@@ -194,8 +172,6 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime <
Note that setting a flag usually imposes a side effect, and this effect
can vary between paint devices and platforms.
- \value DontClipPainter This value is obsolete and has no effect.
-
\value DontSavePainterState When rendering, QGraphicsView protects the
painter state (see QPainter::save()) when rendering the background or
foreground, and when rendering each item. This allows you to leave the
@@ -283,17 +259,16 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime <
#include <QtCore/qmath.h>
#include <QtCore/qscopedvaluerollback.h>
#include <QtWidgets/qapplication.h>
-#include <QtWidgets/qdesktopwidget.h>
-#include <private/qdesktopwidget_p.h>
#include <QtGui/qevent.h>
#include <QtWidgets/qlayout.h>
#include <QtGui/qtransform.h>
-#include <QtGui/qmatrix.h>
#include <QtGui/qpainter.h>
+#include <QtGui/qpainterpath.h>
#include <QtWidgets/qscrollbar.h>
#include <QtWidgets/qstyleoption.h>
#include <private/qevent_p.h>
+#include <QtGui/private/qeventpoint_p.h>
QT_BEGIN_NAMESPACE
@@ -310,21 +285,13 @@ inline int q_round_bound(qreal d) //### (int)(qreal) INT_MAX != INT_MAX for sing
void QGraphicsViewPrivate::translateTouchEvent(QGraphicsViewPrivate *d, QTouchEvent *touchEvent)
{
- QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
- for (int i = 0; i < touchPoints.count(); ++i) {
- QTouchEvent::TouchPoint &touchPoint = touchPoints[i];
- const QSizeF ellipseDiameters = touchPoint.ellipseDiameters();
+ for (int i = 0; i < touchEvent->pointCount(); ++i) {
+ auto &pt = touchEvent->point(i);
// the scene will set the item local pos, startPos, lastPos, and rect before delivering to
// an item, but for now those functions are returning the view's local coordinates
- touchPoint.setScenePos(d->mapToScene(touchPoint.pos()));
- touchPoint.setStartScenePos(d->mapToScene(touchPoint.startPos()));
- touchPoint.setLastScenePos(d->mapToScene(touchPoint.lastPos()));
- touchPoint.setEllipseDiameters(ellipseDiameters);
-
+ QMutableEventPoint::setScenePosition(pt, d->mapToScene(pt.position()));
// screenPos, startScreenPos, and lastScreenPos are already set
}
-
- touchEvent->setTouchPoints(touchPoints);
}
/*!
@@ -348,7 +315,6 @@ QGraphicsViewPrivate::QGraphicsViewPrivate()
hasUpdateClip(false),
mousePressButton(Qt::NoButton),
leftIndent(0), topIndent(0),
- lastMouseEvent(QEvent::None, QPointF(), QPointF(), QPointF(), Qt::NoButton, { }, { }),
alignment(Qt::AlignCenter),
transformationAnchor(QGraphicsView::AnchorViewCenter), resizeAnchor(QGraphicsView::NoAnchor),
viewportUpdateMode(QGraphicsView::MinimalViewportUpdate),
@@ -379,10 +345,10 @@ void QGraphicsViewPrivate::recalculateContentSize()
{
Q_Q(QGraphicsView);
- QSize maxSize = q->maximumViewportSize();
+ const QSize maxSize = q->maximumViewportSize();
int width = maxSize.width();
int height = maxSize.height();
- QRectF viewRect = matrix.mapRect(q->sceneRect());
+ const QRectF viewRect = matrix.mapRect(q->sceneRect());
bool frameOnlyAround = (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, nullptr, q));
if (frameOnlyAround) {
@@ -394,9 +360,8 @@ void QGraphicsViewPrivate::recalculateContentSize()
// Adjust the maximum width and height of the viewport based on the width
// of visible scroll bars.
- int scrollBarExtent = q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, nullptr, q);
- if (frameOnlyAround)
- scrollBarExtent += frameWidth * 2;
+ const int scrollBarExtent = q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, nullptr, q)
+ + (frameOnlyAround ? frameWidth * 2 : 0);
// We do not need to subtract the width scrollbars whose policy is
// Qt::ScrollBarAlwaysOn, this was already done by maximumViewportSize().
@@ -418,62 +383,70 @@ void QGraphicsViewPrivate::recalculateContentSize()
// Setting the ranges of these scroll bars can/will cause the values to
// change, and scrollContentsBy() will be called correspondingly. This
// will reset the last center point.
- QPointF savedLastCenterPoint = lastCenterPoint;
+ const QPointF savedLastCenterPoint = lastCenterPoint;
// Remember the former indent settings
- qreal oldLeftIndent = leftIndent;
- qreal oldTopIndent = topIndent;
+ const qreal oldLeftIndent = leftIndent;
+ const qreal oldTopIndent = topIndent;
// If the whole scene fits horizontally, we center the scene horizontally,
// and ignore the horizontal scroll bars.
- int left = q_round_bound(viewRect.left());
- int right = q_round_bound(viewRect.right() - width);
+ const int left = q_round_bound(viewRect.left());
+ const int right = q_round_bound(viewRect.right() - width);
if (left >= right) {
- hbar->setRange(0, 0);
-
switch (alignment & Qt::AlignHorizontal_Mask) {
case Qt::AlignLeft:
leftIndent = -viewRect.left();
break;
case Qt::AlignRight:
- leftIndent = width - viewRect.width() - viewRect.left() - 1;
+ leftIndent = maxSize.width() - viewRect.width() - viewRect.left() - 1;
break;
case Qt::AlignHCenter:
default:
- leftIndent = width / 2 - (viewRect.left() + viewRect.right()) / 2;
+ leftIndent = maxSize.width() / 2 - (viewRect.left() + viewRect.right()) / 2;
break;
}
+
+ hbar->setRange(0, 0);
} else {
+ leftIndent = 0;
+
hbar->setRange(left, right);
hbar->setPageStep(width);
hbar->setSingleStep(width / 20);
- leftIndent = 0;
+
+ if (oldLeftIndent != 0)
+ hbar->setValue(-oldLeftIndent);
}
// If the whole scene fits vertically, we center the scene vertically, and
// ignore the vertical scroll bars.
- int top = q_round_bound(viewRect.top());
- int bottom = q_round_bound(viewRect.bottom() - height);
+ const int top = q_round_bound(viewRect.top());
+ const int bottom = q_round_bound(viewRect.bottom() - height);
if (top >= bottom) {
- vbar->setRange(0, 0);
-
switch (alignment & Qt::AlignVertical_Mask) {
case Qt::AlignTop:
topIndent = -viewRect.top();
break;
case Qt::AlignBottom:
- topIndent = height - viewRect.height() - viewRect.top() - 1;
+ topIndent = maxSize.height() - viewRect.height() - viewRect.top() - 1;
break;
case Qt::AlignVCenter:
default:
- topIndent = height / 2 - (viewRect.top() + viewRect.bottom()) / 2;
+ topIndent = maxSize.height() / 2 - (viewRect.top() + viewRect.bottom()) / 2;
break;
}
+
+ vbar->setRange(0, 0);
} else {
+ topIndent = 0;
+
vbar->setRange(top, bottom);
vbar->setPageStep(height);
vbar->setSingleStep(height / 20);
- topIndent = 0;
+
+ if (oldTopIndent != 0)
+ vbar->setValue(-oldTopIndent);
}
// Restorethe center point from before the ranges changed.
@@ -510,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);
@@ -531,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());
}
/*!
@@ -611,12 +583,33 @@ void QGraphicsViewPrivate::updateScroll()
/*!
\internal
+
+ * don't start scrolling when a drag mode has been set
+ * don't start scrolling on a movable item
+*/
+bool QGraphicsViewPrivate::canStartScrollingAt(const QPoint &startPos) const
+{
+ Q_Q(const QGraphicsView);
+ if (q->dragMode() != QGraphicsView::NoDrag)
+ return false;
+
+ const QGraphicsItem *childItem = q->itemAt(startPos);
+
+ if (!startPos.isNull() && childItem && (childItem->flags() & QGraphicsItem::ItemIsMovable))
+ return false;
+
+ return QAbstractScrollAreaPrivate::canStartScrollingAt(startPos);
+}
+
+/*!
+ \internal
*/
void QGraphicsViewPrivate::replayLastMouseEvent()
{
if (!useLastMouseEvent || !scene)
return;
- mouseMoveEventHandler(&lastMouseEvent);
+ QSinglePointEvent *spe = static_cast<QSinglePointEvent *>(&lastMouseEvent);
+ mouseMoveEventHandler(static_cast<QMouseEvent *>(spe));
}
/*!
@@ -625,8 +618,7 @@ void QGraphicsViewPrivate::replayLastMouseEvent()
void QGraphicsViewPrivate::storeMouseEvent(QMouseEvent *event)
{
useLastMouseEvent = true;
- lastMouseEvent = QMouseEvent(QEvent::MouseMove, event->localPos(), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers());
+ lastMouseEvent = *event;
}
void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event)
@@ -651,8 +643,8 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event)
mouseEvent.setWidget(viewport);
mouseEvent.setButtonDownScenePos(mousePressButton, mousePressScenePoint);
mouseEvent.setButtonDownScreenPos(mousePressButton, mousePressScreenPoint);
- mouseEvent.setScenePos(q->mapToScene(event->pos()));
- mouseEvent.setScreenPos(event->globalPos());
+ mouseEvent.setScenePos(q->mapToScene(event->position().toPoint()));
+ mouseEvent.setScreenPos(event->globalPosition().toPoint());
mouseEvent.setLastScenePos(lastMouseMoveScenePoint);
mouseEvent.setLastScreenPos(lastMouseMoveScreenPoint);
mouseEvent.setButtons(event->buttons());
@@ -660,6 +652,7 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event)
mouseEvent.setModifiers(event->modifiers());
mouseEvent.setSource(event->source());
mouseEvent.setFlags(event->flags());
+ mouseEvent.setTimestamp(event->timestamp());
lastMouseMoveScenePoint = mouseEvent.scenePos();
lastMouseMoveScreenPoint = mouseEvent.screenPos();
mouseEvent.setAccepted(false);
@@ -689,7 +682,7 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event)
mouseEvent.widget());
}
// Find the topmost item under the mouse with a cursor.
- foreach (QGraphicsItem *item, scene->d_func()->cachedItemsUnderMouse) {
+ for (QGraphicsItem *item : std::as_const(scene->d_func()->cachedItemsUnderMouse)) {
if (item->isEnabled() && item->hasCursor()) {
_q_setViewportCursor(item->cursor());
return;
@@ -719,7 +712,7 @@ QRegion QGraphicsViewPrivate::rubberBandRegion(const QWidget *widget, const QRec
option.shape = QRubberBand::Rectangle;
QRegion tmp;
- tmp += rect;
+ tmp += rect.adjusted(-1, -1, 1, 1);
if (widget->style()->styleHint(QStyle::SH_RubberBand_Mask, &option, widget, &mask))
tmp &= mask.region;
return tmp;
@@ -731,7 +724,7 @@ void QGraphicsViewPrivate::updateRubberBand(const QMouseEvent *event)
if (dragMode != QGraphicsView::RubberBandDrag || !sceneInteractionAllowed || !rubberBanding)
return;
// Check for enough drag distance
- if ((mousePressViewPoint - event->pos()).manhattanLength() < QApplication::startDragDistance())
+ if ((mousePressViewPoint - event->position().toPoint()).manhattanLength() < QApplication::startDragDistance())
return;
// Update old rubberband
@@ -758,7 +751,7 @@ void QGraphicsViewPrivate::updateRubberBand(const QMouseEvent *event)
// Update rubberband position
const QPoint mp = q->mapFromScene(mousePressScenePoint);
- const QPoint ep = event->pos();
+ const QPoint ep = event->position().toPoint();
rubberBandRect = QRect(qMin(mp.x(), ep.x()), qMin(mp.y(), ep.y()),
qAbs(mp.x() - ep.x()) + 1, qAbs(mp.y() - ep.y()) + 1);
@@ -782,6 +775,27 @@ void QGraphicsViewPrivate::updateRubberBand(const QMouseEvent *event)
if (scene)
scene->setSelectionArea(selectionArea, rubberBandSelectionOperation, rubberBandSelectionMode, q->viewportTransform());
}
+
+void QGraphicsViewPrivate::clearRubberBand()
+{
+ Q_Q(QGraphicsView);
+ if (dragMode != QGraphicsView::RubberBandDrag || !sceneInteractionAllowed || !rubberBanding)
+ return;
+
+ if (viewportUpdateMode != QGraphicsView::NoViewportUpdate) {
+ if (viewportUpdateMode != QGraphicsView::FullViewportUpdate)
+ q->viewport()->update(rubberBandRegion(q->viewport(), rubberBandRect));
+ else
+ updateAll();
+ }
+
+ rubberBanding = false;
+ rubberBandSelectionOperation = Qt::ReplaceSelection;
+ if (!rubberBandRect.isNull()) {
+ rubberBandRect = QRect();
+ emit q->rubberBandChanged(rubberBandRect, QPointF(), QPointF());
+ }
+}
#endif
/*!
@@ -805,7 +819,7 @@ void QGraphicsViewPrivate::_q_setViewportCursor(const QCursor &cursor)
void QGraphicsViewPrivate::_q_unsetViewportCursor()
{
Q_Q(QGraphicsView);
- const auto items = q->items(lastMouseEvent.pos());
+ const auto items = q->items(lastMouseEvent.position().toPoint());
for (QGraphicsItem *item : items) {
if (item->isEnabled() && item->hasCursor()) {
_q_setViewportCursor(item->cursor());
@@ -841,6 +855,7 @@ void QGraphicsViewPrivate::storeDragDropEvent(const QGraphicsSceneDragDropEvent
lastDragDropEvent->setMimeData(event->mimeData());
lastDragDropEvent->setWidget(event->widget());
lastDragDropEvent->setSource(event->source());
+ lastDragDropEvent->setTimestamp(event->timestamp());
}
/*!
@@ -851,10 +866,10 @@ void QGraphicsViewPrivate::populateSceneDragDropEvent(QGraphicsSceneDragDropEven
{
#if QT_CONFIG(draganddrop)
Q_Q(QGraphicsView);
- dest->setScenePos(q->mapToScene(source->pos()));
- dest->setScreenPos(q->mapToGlobal(source->pos()));
- dest->setButtons(source->mouseButtons());
- dest->setModifiers(source->keyboardModifiers());
+ dest->setScenePos(q->mapToScene(source->position().toPoint()));
+ dest->setScreenPos(q->mapToGlobal(source->position().toPoint()));
+ dest->setButtons(source->buttons());
+ dest->setModifiers(source->modifiers());
dest->setPossibleActions(source->possibleActions());
dest->setProposedAction(source->proposedAction());
dest->setDropAction(source->dropAction());
@@ -862,8 +877,8 @@ void QGraphicsViewPrivate::populateSceneDragDropEvent(QGraphicsSceneDragDropEven
dest->setWidget(viewport);
dest->setSource(qobject_cast<QWidget *>(source->source()));
#else
- Q_UNUSED(dest)
- Q_UNUSED(source)
+ Q_UNUSED(dest);
+ Q_UNUSED(source);
#endif
}
@@ -963,7 +978,7 @@ static inline void QRect_unite(QRect *rect, const QRect &other)
/*
Calling this function results in update rects being clipped to the item's
bounding rect. Note that updates prior to this function call is not clipped.
- The clip is removed by passing 0.
+ The clip is removed by passing \nullptr.
*/
void QGraphicsViewPrivate::setUpdateClip(QGraphicsItem *item)
{
@@ -1250,7 +1265,7 @@ QSize QGraphicsView::sizeHint() const
if (d->scene) {
QSizeF baseSize = d->matrix.mapRect(sceneRect()).size();
baseSize += QSizeF(d->frameWidth * 2, d->frameWidth * 2);
- return baseSize.boundedTo((3 * QDesktopWidgetPrivate::size()) / 4).toSize();
+ return baseSize.boundedTo((3 * QGuiApplication::primaryScreen()->virtualSize()) / 4).toSize();
}
return QAbstractScrollArea::sizeHint();
}
@@ -1485,6 +1500,10 @@ void QGraphicsView::setDragMode(DragMode mode)
if (d->dragMode == mode)
return;
+#if QT_CONFIG(rubberband)
+ d->clearRubberBand();
+#endif
+
#ifndef QT_NO_CURSOR
if (d->dragMode == ScrollHandDrag)
viewport()->unsetCursor();
@@ -1539,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()
@@ -1717,7 +1736,7 @@ void QGraphicsView::setScene(QGraphicsScene *scene)
QEvent windowDeactivate(QEvent::WindowDeactivate);
QCoreApplication::sendEvent(d->scene, &windowDeactivate);
}
- if(hasFocus())
+ if (hasFocus())
d->scene->clearFocus();
}
@@ -1796,59 +1815,6 @@ void QGraphicsView::setSceneRect(const QRectF &rect)
}
/*!
- Returns the current transformation matrix for the view. If no current
- transformation is set, the identity matrix is returned.
-
- \sa setMatrix(), transform(), rotate(), scale(), shear(), translate()
-*/
-QMatrix QGraphicsView::matrix() const
-{
- Q_D(const QGraphicsView);
- return d->matrix.toAffine();
-}
-
-/*!
- Sets the view's current transformation matrix to \a matrix.
-
- If \a combine is true, then \a matrix is combined with the current matrix;
- otherwise, \a matrix \e replaces the current matrix. \a combine is false
- by default.
-
- The transformation matrix tranforms the scene into view coordinates. Using
- the default transformation, provided by the identity matrix, one pixel in
- the view represents one unit in the scene (e.g., a 10x10 rectangular item
- is drawn using 10x10 pixels in the view). If a 2x2 scaling matrix is
- applied, the scene will be drawn in 1:2 (e.g., a 10x10 rectangular item is
- then drawn using 20x20 pixels in the view).
-
- Example:
-
- \snippet code/src_gui_graphicsview_qgraphicsview.cpp 3
-
- To simplify interation with items using a transformed view, QGraphicsView
- provides mapTo... and mapFrom... functions that can translate between
- scene and view coordinates. For example, you can call mapToScene() to map
- a view coordinate to a floating point scene coordinate, or mapFromScene()
- to map from floating point scene coordinates to view coordinates.
-
- \sa matrix(), setTransform(), rotate(), scale(), shear(), translate()
-*/
-void QGraphicsView::setMatrix(const QMatrix &matrix, bool combine)
-{
- setTransform(QTransform(matrix), combine);
-}
-
-/*!
- Resets the view transformation matrix to the identity matrix.
-
- \sa resetTransform()
-*/
-void QGraphicsView::resetMatrix()
-{
- resetTransform();
-}
-
-/*!
Rotates the current view transformation \a angle degrees clockwise.
\sa setTransform(), transform(), scale(), shear(), translate()
@@ -1925,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;
}
@@ -2376,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();
}
/*!
@@ -2463,7 +2429,7 @@ QPolygonF QGraphicsView::mapToScene(const QRect &rect) const
QPolygonF QGraphicsView::mapToScene(const QPolygon &polygon) const
{
QPolygonF poly;
- poly.reserve(polygon.count());
+ poly.reserve(polygon.size());
for (const QPoint &point : polygon)
poly << mapToScene(point);
return poly;
@@ -2559,7 +2525,7 @@ QPolygon QGraphicsView::mapFromScene(const QRectF &rect) const
QPolygon QGraphicsView::mapFromScene(const QPolygonF &polygon) const
{
QPolygon poly;
- poly.reserve(polygon.count());
+ poly.reserve(polygon.size());
for (const QPointF &point : polygon)
poly << mapFromScene(point);
return poly;
@@ -2589,13 +2555,13 @@ QVariant QGraphicsView::inputMethodQuery(Qt::InputMethodQuery query) const
return QVariant();
QVariant value = d->scene->inputMethodQuery(query);
- if (value.type() == QVariant::RectF)
+ if (value.userType() == QMetaType::QRectF)
value = d->mapRectFromScene(value.toRectF());
- else if (value.type() == QVariant::PointF)
+ else if (value.userType() == QMetaType::QPointF)
value = mapFromScene(value.toPointF());
- else if (value.type() == QVariant::Rect)
+ else if (value.userType() == QMetaType::QRect)
value = d->mapRectFromScene(value.toRect()).toRect();
- else if (value.type() == QVariant::Point)
+ else if (value.userType() == QMetaType::QPoint)
value = mapFromScene(value.toPoint());
return value;
}
@@ -2672,8 +2638,8 @@ void QGraphicsView::updateScene(const QList<QRectF> &rects)
return;
// Extract and reset dirty scene rect info.
- QVector<QRect> dirtyViewportRects;
- dirtyViewportRects.reserve(d->dirtyRegion.rectCount() + rects.count());
+ QList<QRect> dirtyViewportRects;
+ dirtyViewportRects.reserve(d->dirtyRegion.rectCount() + rects.size());
for (const QRect &dirtyRect : d->dirtyRegion)
dirtyViewportRects += dirtyRect;
d->dirtyRegion = QRegion();
@@ -2702,7 +2668,7 @@ void QGraphicsView::updateScene(const QList<QRectF> &rects)
dirtyViewportRects << xrect;
}
- for (const QRect &rect : qAsConst(dirtyViewportRects)) {
+ for (const QRect &rect : std::as_const(dirtyViewportRects)) {
// Add the exposed rect to the update region. In rect update
// mode, we only count the bounding rect of items.
if (!boundingRectUpdate) {
@@ -2761,12 +2727,15 @@ void QGraphicsView::setupViewport(QWidget *widget)
return;
}
- const bool isGLWidget = widget->inherits("QGLWidget") || widget->inherits("QOpenGLWidget");
+ const bool isGLWidget = widget->inherits("QOpenGLWidget");
d->accelerateScrolling = !(isGLWidget);
widget->setFocusPolicy(Qt::StrongFocus);
+ if (isGLWidget)
+ d->stereoEnabled = QWidgetPrivate::get(widget)->isStereoEnabled();
+
if (!isGLWidget) {
// autoFillBackground enables scroll acceleration.
widget->setAutoFillBackground(true);
@@ -2887,14 +2856,13 @@ bool QGraphicsView::viewportEvent(QEvent *event)
d->scene->d_func()->removePopup(d->scene->d_func()->popupWidgets.constFirst());
}
d->useLastMouseEvent = false;
- // a hack to pass a viewport pointer to the scene inside the leave event
- Q_ASSERT(event->d == nullptr);
- QScopedValueRollback<QEventPrivate *> rb(event->d);
- event->d = reinterpret_cast<QEventPrivate *>(viewport());
- QCoreApplication::sendEvent(d->scene, event);
+ QGraphicsSceneEvent leaveEvent(QEvent::GraphicsSceneLeave);
+ leaveEvent.setWidget(viewport());
+ QCoreApplication::sendEvent(d->scene, &leaveEvent);
+ event->setAccepted(leaveEvent.isAccepted());
break;
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::ToolTip: {
QHelpEvent *toolTip = static_cast<QHelpEvent *>(event);
QGraphicsSceneHelpEvent helpEvent(QEvent::GraphicsSceneHelp);
@@ -2937,7 +2905,7 @@ bool QGraphicsView::viewportEvent(QEvent *event)
if (d->scene && d->sceneInteractionAllowed) {
// Convert and deliver the touch event to the scene.
QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
- touchEvent->setTarget(viewport());
+ QMutableTouchEvent::from(touchEvent)->setTarget(viewport());
QGraphicsViewPrivate::translateTouchEvent(d, touchEvent);
QCoreApplication::sendEvent(d->scene, touchEvent);
} else {
@@ -2991,6 +2959,7 @@ void QGraphicsView::contextMenuEvent(QContextMenuEvent *event)
contextEvent.setModifiers(event->modifiers());
contextEvent.setReason((QGraphicsSceneContextMenuEvent::Reason)(event->reason()));
contextEvent.setAccepted(event->isAccepted());
+ contextEvent.setTimestamp(event->timestamp());
QCoreApplication::sendEvent(d->scene, &contextEvent);
event->setAccepted(contextEvent.isAccepted());
}
@@ -3185,9 +3154,9 @@ void QGraphicsView::mouseDoubleClickEvent(QMouseEvent *event)
return;
d->storeMouseEvent(event);
- d->mousePressViewPoint = event->pos();
+ d->mousePressViewPoint = event->position().toPoint();
d->mousePressScenePoint = mapToScene(d->mousePressViewPoint);
- d->mousePressScreenPoint = event->globalPos();
+ d->mousePressScreenPoint = event->globalPosition().toPoint();
d->lastMouseMoveScenePoint = d->mousePressScenePoint;
d->lastMouseMoveScreenPoint = d->mousePressScreenPoint;
d->mousePressButton = event->button();
@@ -3206,6 +3175,7 @@ void QGraphicsView::mouseDoubleClickEvent(QMouseEvent *event)
mouseEvent.setModifiers(event->modifiers());
mouseEvent.setSource(event->source());
mouseEvent.setFlags(event->flags());
+ mouseEvent.setTimestamp(event->timestamp());
if (event->spontaneous())
qt_sendSpontaneousEvent(d->scene, &mouseEvent);
else
@@ -3234,9 +3204,9 @@ void QGraphicsView::mousePressEvent(QMouseEvent *event)
if (d->sceneInteractionAllowed) {
// Store some of the event's button-down data.
- d->mousePressViewPoint = event->pos();
+ d->mousePressViewPoint = event->position().toPoint();
d->mousePressScenePoint = mapToScene(d->mousePressViewPoint);
- d->mousePressScreenPoint = event->globalPos();
+ d->mousePressScreenPoint = event->globalPosition().toPoint();
d->lastMouseMoveScenePoint = d->mousePressScenePoint;
d->lastMouseMoveScreenPoint = d->mousePressScreenPoint;
d->mousePressButton = event->button();
@@ -3257,6 +3227,7 @@ void QGraphicsView::mousePressEvent(QMouseEvent *event)
mouseEvent.setSource(event->source());
mouseEvent.setFlags(event->flags());
mouseEvent.setAccepted(false);
+ mouseEvent.setTimestamp(event->timestamp());
if (event->spontaneous())
qt_sendSpontaneousEvent(d->scene, &mouseEvent);
else
@@ -3316,7 +3287,7 @@ void QGraphicsView::mouseMoveEvent(QMouseEvent *event)
if (d->handScrolling) {
QScrollBar *hBar = horizontalScrollBar();
QScrollBar *vBar = verticalScrollBar();
- QPoint delta = event->pos() - d->lastMouseEvent.pos();
+ QPoint delta = event->position().toPoint() - d->lastMouseEvent.position().toPoint();
hBar->setValue(hBar->value() + (isRightToLeft() ? delta.x() : -delta.x()));
vBar->setValue(vBar->value() - delta.y());
@@ -3338,20 +3309,7 @@ void QGraphicsView::mouseReleaseEvent(QMouseEvent *event)
#if QT_CONFIG(rubberband)
if (d->dragMode == QGraphicsView::RubberBandDrag && d->sceneInteractionAllowed && !event->buttons()) {
- if (d->rubberBanding) {
- if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate){
- if (d->viewportUpdateMode != FullViewportUpdate)
- viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect));
- else
- d->updateAll();
- }
- d->rubberBanding = false;
- d->rubberBandSelectionOperation = Qt::ReplaceSelection;
- if (!d->rubberBandRect.isNull()) {
- d->rubberBandRect = QRect();
- emit rubberBandChanged(d->rubberBandRect, QPointF(), QPointF());
- }
- }
+ d->clearRubberBand();
} else
#endif
if (d->dragMode == QGraphicsView::ScrollHandDrag && event->button() == Qt::LeftButton) {
@@ -3383,8 +3341,8 @@ void QGraphicsView::mouseReleaseEvent(QMouseEvent *event)
mouseEvent.setWidget(viewport());
mouseEvent.setButtonDownScenePos(d->mousePressButton, d->mousePressScenePoint);
mouseEvent.setButtonDownScreenPos(d->mousePressButton, d->mousePressScreenPoint);
- mouseEvent.setScenePos(mapToScene(event->pos()));
- mouseEvent.setScreenPos(event->globalPos());
+ mouseEvent.setScenePos(mapToScene(event->position().toPoint()));
+ mouseEvent.setScreenPos(event->globalPosition().toPoint());
mouseEvent.setLastScenePos(d->lastMouseMoveScenePoint);
mouseEvent.setLastScreenPos(d->lastMouseMoveScreenPoint);
mouseEvent.setButtons(event->buttons());
@@ -3393,6 +3351,7 @@ void QGraphicsView::mouseReleaseEvent(QMouseEvent *event)
mouseEvent.setSource(event->source());
mouseEvent.setFlags(event->flags());
mouseEvent.setAccepted(false);
+ mouseEvent.setTimestamp(event->timestamp());
if (event->spontaneous())
qt_sendSpontaneousEvent(d->scene, &mouseEvent);
else
@@ -3431,8 +3390,12 @@ void QGraphicsView::wheelEvent(QWheelEvent *event)
wheelEvent.setModifiers(event->modifiers());
const bool horizontal = qAbs(event->angleDelta().x()) > qAbs(event->angleDelta().y());
wheelEvent.setDelta(horizontal ? event->angleDelta().x() : event->angleDelta().y());
+ wheelEvent.setPixelDelta(event->pixelDelta());
+ wheelEvent.setPhase(event->phase());
+ wheelEvent.setInverted(event->isInverted());
wheelEvent.setOrientation(horizontal ? Qt::Horizontal : Qt::Vertical);
wheelEvent.setAccepted(false);
+ wheelEvent.setTimestamp(event->timestamp());
QCoreApplication::sendEvent(d->scene, &wheelEvent);
event->setAccepted(wheelEvent.isAccepted());
if (!event->isAccepted())
@@ -3474,132 +3437,146 @@ void QGraphicsView::paintEvent(QPaintEvent *event)
painter.setWorldTransform(viewportTransform());
const QTransform viewTransform = painter.worldTransform();
- // Draw background
- if (d->cacheMode & CacheBackground) {
- // Recreate the background pixmap, and flag the whole background as
- // exposed.
- if (d->mustResizeBackgroundPixmap) {
- const qreal dpr = d->viewport->devicePixelRatioF();
- d->backgroundPixmap = QPixmap(viewport()->size() * dpr);
- d->backgroundPixmap.setDevicePixelRatio(dpr);
- QBrush bgBrush = viewport()->palette().brush(viewport()->backgroundRole());
- if (!bgBrush.isOpaque())
- d->backgroundPixmap.fill(Qt::transparent);
- QPainter p(&d->backgroundPixmap);
- p.fillRect(0, 0, d->backgroundPixmap.width(), d->backgroundPixmap.height(), bgBrush);
- d->backgroundPixmapExposed = QRegion(viewport()->rect());
- d->mustResizeBackgroundPixmap = false;
- }
+ const auto actuallyDraw = [&]() {
+ // Draw background
+ if (d->cacheMode & CacheBackground) {
+ // Recreate the background pixmap, and flag the whole background as
+ // exposed.
+ if (d->mustResizeBackgroundPixmap) {
+ const qreal dpr = d->viewport->devicePixelRatio();
+ d->backgroundPixmap = QPixmap(viewport()->size() * dpr);
+ d->backgroundPixmap.setDevicePixelRatio(dpr);
+ QBrush bgBrush = viewport()->palette().brush(viewport()->backgroundRole());
+ if (!bgBrush.isOpaque())
+ d->backgroundPixmap.fill(Qt::transparent);
+ QPainter p(&d->backgroundPixmap);
+ p.fillRect(0, 0, d->backgroundPixmap.width(), d->backgroundPixmap.height(), bgBrush);
+ d->backgroundPixmapExposed = QRegion(viewport()->rect());
+ d->mustResizeBackgroundPixmap = false;
+ }
- // Redraw exposed areas
- if (!d->backgroundPixmapExposed.isEmpty()) {
- QPainter backgroundPainter(&d->backgroundPixmap);
- backgroundPainter.setClipRegion(d->backgroundPixmapExposed, Qt::ReplaceClip);
- if (viewTransformed)
- backgroundPainter.setTransform(viewTransform);
- QRectF backgroundExposedSceneRect = mapToScene(d->backgroundPixmapExposed.boundingRect()).boundingRect();
- drawBackground(&backgroundPainter, backgroundExposedSceneRect);
- d->backgroundPixmapExposed = QRegion();
- }
+ // Redraw exposed areas
+ if (!d->backgroundPixmapExposed.isEmpty()) {
+ QPainter backgroundPainter(&d->backgroundPixmap);
+ backgroundPainter.setClipRegion(d->backgroundPixmapExposed, Qt::ReplaceClip);
+ if (viewTransformed)
+ backgroundPainter.setTransform(viewTransform);
+ QRectF backgroundExposedSceneRect = mapToScene(d->backgroundPixmapExposed.boundingRect()).boundingRect();
+ drawBackground(&backgroundPainter, backgroundExposedSceneRect);
+ d->backgroundPixmapExposed = QRegion();
+ }
- // Blit the background from the background pixmap
- if (viewTransformed) {
- painter.setWorldTransform(QTransform());
- painter.drawPixmap(QPoint(), d->backgroundPixmap);
- painter.setWorldTransform(viewTransform);
+ // Blit the background from the background pixmap
+ if (viewTransformed) {
+ painter.setWorldTransform(QTransform());
+ painter.drawPixmap(QPoint(), d->backgroundPixmap);
+ painter.setWorldTransform(viewTransform);
+ } else {
+ painter.drawPixmap(QPoint(), d->backgroundPixmap);
+ }
} else {
- painter.drawPixmap(QPoint(), d->backgroundPixmap);
+ if (!(d->optimizationFlags & DontSavePainterState))
+ painter.save();
+
+ drawBackground(&painter, exposedSceneRect);
+ if (!(d->optimizationFlags & DontSavePainterState))
+ painter.restore();
}
- } else {
- if (!(d->optimizationFlags & DontSavePainterState))
- painter.save();
- drawBackground(&painter, exposedSceneRect);
- if (!(d->optimizationFlags & DontSavePainterState))
- painter.restore();
- }
- // Items
- if (!(d->optimizationFlags & IndirectPainting)) {
- const quint32 oldRectAdjust = d->scene->d_func()->rectAdjust;
- if (d->optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)
- d->scene->d_func()->rectAdjust = 1;
- else
- d->scene->d_func()->rectAdjust = 2;
- d->scene->d_func()->drawItems(&painter, viewTransformed ? &viewTransform : nullptr,
- &d->exposedRegion, viewport());
- d->scene->d_func()->rectAdjust = oldRectAdjust;
- // Make sure the painter's world transform is restored correctly when
- // drawing without painter state protection (DontSavePainterState).
- // We only change the worldTransform() so there's no need to do a full-blown
- // save() and restore(). Also note that we don't have to do this in case of
- // IndirectPainting (the else branch), because in that case we always save()
- // and restore() in QGraphicsScene::drawItems().
- if (!d->scene->d_func()->painterStateProtection)
- painter.setOpacity(1.0);
- painter.setWorldTransform(viewTransform);
- } else {
- // Make sure we don't have unpolished items before we draw
- if (!d->scene->d_func()->unpolishedItems.isEmpty())
- d->scene->d_func()->_q_polishItems();
- // We reset updateAll here (after we've issued polish events)
- // so that we can discard update requests coming from polishEvent().
- d->scene->d_func()->updateAll = false;
-
- // Find all exposed items
- bool allItems = false;
- QList<QGraphicsItem *> itemList = d->findItems(d->exposedRegion, &allItems, viewTransform);
- if (!itemList.isEmpty()) {
- // Generate the style options.
- const int numItems = itemList.size();
- QGraphicsItem **itemArray = &itemList[0]; // Relies on QList internals, but is perfectly valid.
- QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems);
- QTransform transform(Qt::Uninitialized);
- for (int i = 0; i < numItems; ++i) {
- QGraphicsItem *item = itemArray[i];
- QGraphicsItemPrivate *itemd = item->d_ptr.data();
- itemd->initStyleOption(&styleOptionArray[i], viewTransform, d->exposedRegion, allItems);
- // Cache the item's area in view coordinates.
- // Note that we have to do this here in case the base class implementation
- // (QGraphicsScene::drawItems) is not called. If it is, we'll do this
- // operation twice, but that's the price one has to pay for using indirect
- // painting :-/.
- const QRectF brect = adjustedItemEffectiveBoundingRect(item);
- if (!itemd->itemIsUntransformable()) {
- transform = item->sceneTransform();
- if (viewTransformed)
- transform *= viewTransform;
- } else {
- transform = item->deviceTransform(viewTransform);
+ // Items
+ if (!(d->optimizationFlags & IndirectPainting)) {
+ const quint32 oldRectAdjust = d->scene->d_func()->rectAdjust;
+ if (d->optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)
+ d->scene->d_func()->rectAdjust = 1;
+ else
+ d->scene->d_func()->rectAdjust = 2;
+ d->scene->d_func()->drawItems(&painter, viewTransformed ? &viewTransform : nullptr,
+ &d->exposedRegion, viewport());
+ d->scene->d_func()->rectAdjust = oldRectAdjust;
+ // Make sure the painter's world transform is restored correctly when
+ // drawing without painter state protection (DontSavePainterState).
+ // We only change the worldTransform() so there's no need to do a full-blown
+ // save() and restore(). Also note that we don't have to do this in case of
+ // IndirectPainting (the else branch), because in that case we always save()
+ // and restore() in QGraphicsScene::drawItems().
+ if (!d->scene->d_func()->painterStateProtection)
+ painter.setOpacity(1.0);
+ painter.setWorldTransform(viewTransform);
+ } else {
+ // Make sure we don't have unpolished items before we draw
+ if (!d->scene->d_func()->unpolishedItems.isEmpty())
+ d->scene->d_func()->_q_polishItems();
+ // We reset updateAll here (after we've issued polish events)
+ // so that we can discard update requests coming from polishEvent().
+ d->scene->d_func()->updateAll = false;
+
+ // Find all exposed items
+ bool allItems = false;
+ QList<QGraphicsItem *> itemList = d->findItems(d->exposedRegion, &allItems, viewTransform);
+ if (!itemList.isEmpty()) {
+ // Generate the style options.
+ const int numItems = itemList.size();
+ QGraphicsItem **itemArray = &itemList[0]; // Relies on QList internals, but is perfectly valid.
+ QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems);
+ QTransform transform(Qt::Uninitialized);
+ for (int i = 0; i < numItems; ++i) {
+ QGraphicsItem *item = itemArray[i];
+ QGraphicsItemPrivate *itemd = item->d_ptr.data();
+ itemd->initStyleOption(&styleOptionArray[i], viewTransform, d->exposedRegion, allItems);
+ // Cache the item's area in view coordinates.
+ // Note that we have to do this here in case the base class implementation
+ // (QGraphicsScene::drawItems) is not called. If it is, we'll do this
+ // operation twice, but that's the price one has to pay for using indirect
+ // painting :-/.
+ const QRectF brect = adjustedItemEffectiveBoundingRect(item);
+ if (!itemd->itemIsUntransformable()) {
+ transform = item->sceneTransform();
+ if (viewTransformed)
+ transform *= viewTransform;
+ } else {
+ transform = item->deviceTransform(viewTransform);
+ }
+ itemd->paintedViewBoundingRects.insert(d->viewport, transform.mapRect(brect).toRect());
}
- itemd->paintedViewBoundingRects.insert(d->viewport, transform.mapRect(brect).toRect());
+ // Draw the items.
+ drawItems(&painter, numItems, itemArray, styleOptionArray);
+ d->freeStyleOptionsArray(styleOptionArray);
}
- // Draw the items.
- drawItems(&painter, numItems, itemArray, styleOptionArray);
- d->freeStyleOptionsArray(styleOptionArray);
}
- }
- // Foreground
- drawForeground(&painter, exposedSceneRect);
+ // Foreground
+ drawForeground(&painter, exposedSceneRect);
-#if QT_CONFIG(rubberband)
- // Rubberband
- if (d->rubberBanding && !d->rubberBandRect.isEmpty()) {
- painter.restore();
- QStyleOptionRubberBand option;
- option.initFrom(viewport());
- option.rect = d->rubberBandRect;
- option.shape = QRubberBand::Rectangle;
-
- QStyleHintReturnMask mask;
- if (viewport()->style()->styleHint(QStyle::SH_RubberBand_Mask, &option, viewport(), &mask)) {
- // painter clipping for masked rubberbands
- painter.setClipRegion(mask.region, Qt::IntersectClip);
+ #if QT_CONFIG(rubberband)
+ // Rubberband
+ if (d->rubberBanding && !d->rubberBandRect.isEmpty()) {
+ painter.restore();
+ QStyleOptionRubberBand option;
+ option.initFrom(viewport());
+ option.rect = d->rubberBandRect;
+ option.shape = QRubberBand::Rectangle;
+
+ QStyleHintReturnMask mask;
+ if (viewport()->style()->styleHint(QStyle::SH_RubberBand_Mask, &option, viewport(), &mask)) {
+ // painter clipping for masked rubberbands
+ painter.setClipRegion(mask.region, Qt::IntersectClip);
+ }
+
+ viewport()->style()->drawControl(QStyle::CE_RubberBand, &option, &painter, viewport());
}
+ #endif
+ };
- viewport()->style()->drawControl(QStyle::CE_RubberBand, &option, &painter, viewport());
+ actuallyDraw();
+
+ // For stereo we want to draw everything twice, once to each buffer
+ if (d->stereoEnabled) {
+ QWidgetPrivate* w = QWidgetPrivate::get(viewport());
+ if (w->toggleStereoTargetBuffer()) {
+ actuallyDraw();
+ w->toggleStereoTargetBuffer();
+ }
}
-#endif
painter.end();
@@ -3740,7 +3717,12 @@ void QGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
return;
}
+ const bool wasAa = painter->testRenderHint(QPainter::Antialiasing);
+ if (wasAa)
+ painter->setRenderHints(QPainter::Antialiasing, false);
painter->fillRect(rect, d->backgroundBrush);
+ if (wasAa)
+ painter->setRenderHints(QPainter::Antialiasing, true);
}
/*!
@@ -3772,7 +3754,7 @@ void QGraphicsView::drawForeground(QPainter *painter, const QRectF &rect)
}
/*!
- \obsolete
+ \deprecated
Draws the items \a items in the scene using \a painter, after the
background and before the foreground are drawn. \a numItems is the number
@@ -3844,7 +3826,7 @@ bool QGraphicsView::isTransformed() const
otherwise, \a matrix \e replaces the current matrix. \a combine is false
by default.
- The transformation matrix tranforms the scene into view coordinates. Using
+ The transformation matrix transforms the scene into view coordinates. Using
the default transformation, provided by the identity matrix, one pixel in
the view represents one unit in the scene (e.g., a 10x10 rectangular item
is drawn using 10x10 pixels in the view). If a 2x2 scaling matrix is
@@ -3855,13 +3837,13 @@ bool QGraphicsView::isTransformed() const
\snippet code/src_gui_graphicsview_qgraphicsview.cpp 7
- To simplify interation with items using a transformed view, QGraphicsView
+ To simplify interaction with items using a transformed view, QGraphicsView
provides mapTo... and mapFrom... functions that can translate between
scene and view coordinates. For example, you can call mapToScene() to map
- a view coordiate to a floating point scene coordinate, or mapFromScene()
+ 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.h b/src/widgets/graphicsview/qgraphicsview.h
index 1389796c3f..554c5a4b4e 100644
--- a/src/widgets/graphicsview/qgraphicsview.h
+++ b/src/widgets/graphicsview/qgraphicsview.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSVIEW_H
#define QGRAPHICSVIEW_H
@@ -68,13 +32,17 @@ class Q_WIDGETS_EXPORT QGraphicsView : public QAbstractScrollArea
Q_PROPERTY(QPainter::RenderHints renderHints READ renderHints WRITE setRenderHints)
Q_PROPERTY(DragMode dragMode READ dragMode WRITE setDragMode)
Q_PROPERTY(CacheMode cacheMode READ cacheMode WRITE setCacheMode)
- Q_PROPERTY(ViewportAnchor transformationAnchor READ transformationAnchor WRITE setTransformationAnchor)
+ Q_PROPERTY(ViewportAnchor transformationAnchor READ transformationAnchor
+ WRITE setTransformationAnchor)
Q_PROPERTY(ViewportAnchor resizeAnchor READ resizeAnchor WRITE setResizeAnchor)
- Q_PROPERTY(ViewportUpdateMode viewportUpdateMode READ viewportUpdateMode WRITE setViewportUpdateMode)
+ Q_PROPERTY(ViewportUpdateMode viewportUpdateMode READ viewportUpdateMode
+ WRITE setViewportUpdateMode)
#if QT_CONFIG(rubberband)
- Q_PROPERTY(Qt::ItemSelectionMode rubberBandSelectionMode READ rubberBandSelectionMode WRITE setRubberBandSelectionMode)
+ Q_PROPERTY(Qt::ItemSelectionMode rubberBandSelectionMode READ rubberBandSelectionMode
+ WRITE setRubberBandSelectionMode)
#endif
- Q_PROPERTY(OptimizationFlags optimizationFlags READ optimizationFlags WRITE setOptimizationFlags)
+ Q_PROPERTY(OptimizationFlags optimizationFlags READ optimizationFlags
+ WRITE setOptimizationFlags)
public:
enum ViewportAnchor {
@@ -107,12 +75,9 @@ public:
Q_ENUM(ViewportUpdateMode)
enum OptimizationFlag {
-#if QT_DEPRECATED_SINCE(5, 14)
- DontClipPainter Q_DECL_ENUMERATOR_DEPRECATED_X("This flag is unused") = 0x1, // obsolete
-#endif
- DontSavePainterState = 0x2,
- DontAdjustForAntialiasing = 0x4,
- IndirectPainting = 0x8
+ DontSavePainterState = 0x1,
+ DontAdjustForAntialiasing = 0x2,
+ IndirectPainting = 0x4
};
Q_DECLARE_FLAGS(OptimizationFlags, OptimizationFlag)
@@ -165,9 +130,6 @@ public:
void setSceneRect(const QRectF &rect);
inline void setSceneRect(qreal x, qreal y, qreal w, qreal h);
- QMatrix matrix() const;
- void setMatrix(const QMatrix &matrix, bool combine = false);
- void resetMatrix();
QTransform transform() const;
QTransform viewportTransform() const;
bool isTransformed() const;
diff --git a/src/widgets/graphicsview/qgraphicsview_p.h b/src/widgets/graphicsview/qgraphicsview_p.h
index 01af61d6ba..7f1682beca 100644
--- a/src/widgets/graphicsview/qgraphicsview_p.h
+++ b/src/widgets/graphicsview/qgraphicsview_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSVIEW_P_H
#define QGRAPHICSVIEW_P_H
@@ -54,13 +18,15 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "qgraphicsview.h"
-#include <QtGui/qevent.h>
+#include <QtGui/private/qevent_p.h>
#include <QtCore/qcoreapplication.h>
#include "qgraphicssceneevent.h"
#include <QtWidgets/qstyleoption.h>
#include <private/qabstractscrollarea_p.h>
#include <private/qapplication_p.h>
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(graphicsview);
QT_BEGIN_NAMESPACE
@@ -117,12 +83,13 @@ public:
QTransform matrix;
qint64 scrollX, scrollY;
void updateScroll();
+ bool canStartScrollingAt(const QPoint &startPos) const override;
qreal leftIndent;
qreal topIndent;
// Replaying mouse events
- QMouseEvent lastMouseEvent;
+ QMutableSinglePointEvent lastMouseEvent;
void replayLastMouseEvent();
void storeMouseEvent(QMouseEvent *event);
void mouseMoveEventHandler(QMouseEvent *event);
@@ -135,11 +102,14 @@ public:
QGraphicsView::ViewportUpdateMode viewportUpdateMode;
QGraphicsView::OptimizationFlags optimizationFlags;
+ bool stereoEnabled = false; // Set in setupViewport()
+
QPointer<QGraphicsScene> scene;
#if QT_CONFIG(rubberband)
QRect rubberBandRect;
QRegion rubberBandRegion(const QWidget *widget, const QRect &rect) const;
void updateRubberBand(const QMouseEvent *event);
+ void clearRubberBand();
bool rubberBanding;
Qt::ItemSelectionMode rubberBandSelectionMode;
Qt::ItemSelectionOperation rubberBandSelectionOperation;
@@ -148,7 +118,7 @@ public:
QGraphicsView::CacheMode cacheMode;
- QVector<QStyleOptionGraphicsItem> styleOptions;
+ QList<QStyleOptionGraphicsItem> styleOptions;
QStyleOptionGraphicsItem *allocStyleOptionsArray(int numItems);
void freeStyleOptionsArray(QStyleOptionGraphicsItem *array);
diff --git a/src/widgets/graphicsview/qgraphicswidget.cpp b/src/widgets/graphicsview/qgraphicswidget.cpp
index 1035ed3575..3679723bc4 100644
--- a/src/widgets/graphicsview/qgraphicswidget.cpp
+++ b/src/widgets/graphicsview/qgraphicswidget.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 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 "qglobal.h"
@@ -55,16 +19,20 @@
#include <private/qshortcutmap_p.h>
#endif
#include <QtCore/qmutex.h>
+#include <QtCore/QScopeGuard>
#include <QtWidgets/qapplication.h>
#include <QtWidgets/qgraphicsview.h>
#include <QtWidgets/qgraphicsproxywidget.h>
#include <QtGui/qpalette.h>
+#include <QtGui/qpainterpath.h>
#include <QtWidgets/qstyleoption.h>
#include <qdebug.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
\class QGraphicsWidget
\brief The QGraphicsWidget class is the base class for all widget
@@ -231,9 +199,9 @@ QGraphicsWidget::~QGraphicsWidget()
Q_D(QGraphicsWidget);
#ifndef QT_NO_ACTION
// Remove all actions from this widget
- for (int i = 0; i < d->actions.size(); ++i) {
- QActionPrivate *apriv = d->actions.at(i)->d_func();
- apriv->graphicsWidgets.removeAll(this);
+ for (auto action : std::as_const(d->actions)) {
+ QActionPrivate *apriv = action->d_func();
+ apriv->associatedObjects.removeAll(this);
}
d->actions.clear();
#endif
@@ -351,6 +319,19 @@ void QGraphicsWidget::resize(const QSizeF &size)
void QGraphicsWidget::setGeometry(const QRectF &rect)
{
QGraphicsWidgetPrivate *wd = QGraphicsWidget::d_func();
+ // Package relayout of children in a scope guard so we can just return early
+ // when this widget's geometry is sorted out.
+ const auto relayoutChildren = qScopeGuard([this, wd]() {
+ if (QGraphicsLayout::instantInvalidatePropagation()) {
+ if (QGraphicsLayout *lay = wd->layout) {
+ if (!lay->isActivated()) {
+ QEvent layoutRequest(QEvent::LayoutRequest);
+ QCoreApplication::sendEvent(this, &layoutRequest);
+ }
+ }
+ }
+ });
+
QGraphicsLayoutItemPrivate *d = QGraphicsLayoutItem::d_ptr.data();
QRectF newGeom;
QPointF oldPos = d->geom.topLeft();
@@ -360,9 +341,8 @@ void QGraphicsWidget::setGeometry(const QRectF &rect)
newGeom.setSize(rect.size().expandedTo(effectiveSizeHint(Qt::MinimumSize))
.boundedTo(effectiveSizeHint(Qt::MaximumSize)));
- if (newGeom == d->geom) {
- goto relayoutChildrenAndReturn;
- }
+ if (newGeom == d->geom)
+ return;
// setPos triggers ItemPositionChange, which can adjust position
wd->inSetGeometry = 1;
@@ -370,67 +350,48 @@ void QGraphicsWidget::setGeometry(const QRectF &rect)
wd->inSetGeometry = 0;
newGeom.moveTopLeft(pos());
- if (newGeom == d->geom) {
- goto relayoutChildrenAndReturn;
- }
+ if (newGeom == d->geom)
+ return;
- // Update and prepare to change the geometry (remove from index) if the size has changed.
- if (wd->scene) {
- if (rect.topLeft() == d->geom.topLeft()) {
- prepareGeometryChange();
- }
- }
+ // Update and prepare to change the geometry (remove from index) if
+ // the size has changed.
+ if (wd->scene && rect.topLeft() == d->geom.topLeft())
+ prepareGeometryChange();
}
// Update the layout item geometry
- {
- bool moved = oldPos != pos();
- if (moved) {
- // Send move event.
- QGraphicsSceneMoveEvent event;
- event.setOldPos(oldPos);
- event.setNewPos(pos());
- QCoreApplication::sendEvent(this, &event);
- if (wd->inSetPos) {
- //set the new pos
- d->geom.moveTopLeft(pos());
- emit geometryChanged();
- goto relayoutChildrenAndReturn;
- }
+ if (oldPos != pos()) {
+ // Send move event.
+ QGraphicsSceneMoveEvent event;
+ event.setOldPos(oldPos);
+ event.setNewPos(pos());
+ QCoreApplication::sendEvent(this, &event);
+ if (wd->inSetPos) {
+ // Set the new position:
+ d->geom.moveTopLeft(pos());
+ emit geometryChanged();
+ return;
}
- QSizeF oldSize = size();
- QGraphicsLayoutItem::setGeometry(newGeom);
- // Send resize event
- bool resized = newGeom.size() != oldSize;
- if (resized) {
+ }
+
+ QSizeF oldSize = size();
+ QGraphicsLayoutItem::setGeometry(newGeom);
+ // Send resize event, if appropriate:
+ if (newGeom.size() != oldSize) {
+ if (oldSize.width() != newGeom.size().width())
+ emit widthChanged();
+ if (oldSize.height() != newGeom.size().height())
+ emit heightChanged();
+ QGraphicsLayout *lay = wd->layout;
+ if (!QGraphicsLayout::instantInvalidatePropagation() || !lay || lay->isActivated()) {
QGraphicsSceneResizeEvent re;
re.setOldSize(oldSize);
re.setNewSize(newGeom.size());
- if (oldSize.width() != newGeom.size().width())
- emit widthChanged();
- if (oldSize.height() != newGeom.size().height())
- emit heightChanged();
- QGraphicsLayout *lay = wd->layout;
- if (QGraphicsLayout::instantInvalidatePropagation()) {
- if (!lay || lay->isActivated()) {
- QCoreApplication::sendEvent(this, &re);
- }
- } else {
- QCoreApplication::sendEvent(this, &re);
- }
+ QCoreApplication::sendEvent(this, &re);
}
}
emit geometryChanged();
-relayoutChildrenAndReturn:
- if (QGraphicsLayout::instantInvalidatePropagation()) {
- if (QGraphicsLayout *lay = wd->layout) {
- if (!lay->isActivated()) {
- QEvent layoutRequest(QEvent::LayoutRequest);
- QCoreApplication::sendEvent(this, &layoutRequest);
- }
- }
- }
}
/*!
@@ -615,7 +576,7 @@ void QGraphicsWidget::unsetWindowFrameMargins()
QStyleOptionTitleBar bar;
d->initStyleOptionTitleBar(&bar);
QStyle *style = this->style();
- qreal margin = style->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth);
+ const qreal margin = style->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, &bar);
qreal titleBarHeight = d->titleBarHeight(bar);
setWindowFrameMargins(margin, titleBarHeight, margin, margin);
} else {
@@ -976,13 +937,13 @@ QFont QGraphicsWidget::font() const
{
Q_D(const QGraphicsWidget);
QFont fnt = d->font;
- fnt.resolve(fnt.resolve() | d->inheritedFontResolveMask);
+ fnt.setResolveMask(fnt.resolveMask() | d->inheritedFontResolveMask);
return fnt;
}
void QGraphicsWidget::setFont(const QFont &font)
{
Q_D(QGraphicsWidget);
- setAttribute(Qt::WA_SetFont, font.resolve() != 0);
+ setAttribute(Qt::WA_SetFont, font.resolveMask() != 0);
QFont naturalFont = d->naturalWidgetFont();
QFont resolvedFont = font.resolve(naturalFont);
@@ -1022,7 +983,7 @@ QPalette QGraphicsWidget::palette() const
void QGraphicsWidget::setPalette(const QPalette &palette)
{
Q_D(QGraphicsWidget);
- setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
+ setAttribute(Qt::WA_SetPalette, palette.resolveMask() != 0);
QPalette naturalPalette = d->naturalWidgetPalette();
QPalette resolvedPalette = palette.resolve(naturalPalette);
@@ -2005,13 +1966,9 @@ void QGraphicsWidget::addAction(QAction *action)
\sa removeAction(), QMenu, addAction(), QWidget::addActions()
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void QGraphicsWidget::addActions(const QList<QAction *> &actions)
-#else
-void QGraphicsWidget::addActions(QList<QAction *> actions)
-#endif
{
- for (int i = 0; i < actions.count(); ++i)
+ for (int i = 0; i < actions.size(); ++i)
insertAction(nullptr, actions.at(i));
}
@@ -2048,7 +2005,7 @@ void QGraphicsWidget::insertAction(QAction *before, QAction *action)
if (index == -1) {
QActionPrivate *apriv = action->d_func();
- apriv->graphicsWidgets.append(this);
+ apriv->associatedObjects.append(this);
}
QActionEvent e(QEvent::ActionAdded, action, before);
@@ -2066,13 +2023,9 @@ void QGraphicsWidget::insertAction(QAction *before, QAction *action)
\sa removeAction(), QMenu, insertAction(), QWidget::insertActions()
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void QGraphicsWidget::insertActions(QAction *before, const QList<QAction *> &actions)
-#else
-void QGraphicsWidget::insertActions(QAction *before, QList<QAction *> actions)
-#endif
{
- for (int i = 0; i < actions.count(); ++i)
+ for (int i = 0; i < actions.size(); ++i)
insertAction(before, actions.at(i));
}
@@ -2091,7 +2044,7 @@ void QGraphicsWidget::removeAction(QAction *action)
Q_D(QGraphicsWidget);
QActionPrivate *apriv = action->d_func();
- apriv->graphicsWidgets.removeAll(this);
+ apriv->associatedObjects.removeAll(this);
if (d->actions.removeAll(action)) {
QActionEvent e(QEvent::ActionRemoved, action);
@@ -2150,7 +2103,7 @@ void QGraphicsWidget::setTabOrder(QGraphicsWidget *first, QGraphicsWidget *secon
return;
}
QGraphicsScene *scene = first ? first->scene() : second->scene();
- if (!scene && (!first || !second)) {
+ if (!scene) {
qWarning("QGraphicsWidget::setTabOrder: assigning tab order from/to the"
" scene requires the item to be in a scene.");
return;
@@ -2414,7 +2367,7 @@ void QGraphicsWidget::dumpFocusChain()
qWarning("Found a focus chain that is not circular, (next == 0)");
break;
}
- qDebug() << i++ << QString::number(uint(next), 16) << next->className() << next->data(0) << QString::fromLatin1("focusItem:%1").arg(next->hasFocus() ? '1' : '0') << QLatin1String("next:") << next->d_func()->focusNext->data(0) << QLatin1String("prev:") << next->d_func()->focusPrev->data(0);
+ qDebug() << i++ << QString::number(uint(next), 16) << next->className() << next->data(0) << QString::fromLatin1("focusItem:%1").arg(next->hasFocus() ? '1' : '0') << "next:"_L1 << next->d_func()->focusNext->data(0) << "prev:"_L1 << next->d_func()->focusPrev->data(0);
if (visited.contains(next)) {
qWarning("Already visited this node. However, I expected to dump until I found myself.");
break;
diff --git a/src/widgets/graphicsview/qgraphicswidget.h b/src/widgets/graphicsview/qgraphicswidget.h
index 6c5171cc02..3e2c93b6cc 100644
--- a/src/widgets/graphicsview/qgraphicswidget.h
+++ b/src/widgets/graphicsview/qgraphicswidget.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSWIDGET_H
#define QGRAPHICSWIDGET_H
@@ -43,7 +7,7 @@
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtGui/qfont.h>
#if QT_CONFIG(action)
-# include <QtWidgets/qaction.h>
+# include <QtGui/qaction.h>
#endif
#include <QtWidgets/qgraphicslayoutitem.h>
#include <QtWidgets/qgraphicsitem.h>
@@ -70,7 +34,8 @@ class Q_WIDGETS_EXPORT QGraphicsWidget : public QGraphicsObject, public QGraphic
Q_INTERFACES(QGraphicsItem QGraphicsLayoutItem)
Q_PROPERTY(QPalette palette READ palette WRITE setPalette)
Q_PROPERTY(QFont font READ font WRITE setFont)
- Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection RESET unsetLayoutDirection)
+ Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection
+ RESET unsetLayoutDirection)
Q_PROPERTY(QSizeF size READ size WRITE resize NOTIFY geometryChanged)
Q_PROPERTY(QSizeF minimumSize READ minimumSize WRITE setMinimumSize)
Q_PROPERTY(QSizeF preferredSize READ preferredSize WRITE setPreferredSize)
@@ -148,13 +113,8 @@ public:
#ifndef QT_NO_ACTION
//actions
void addAction(QAction *action);
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void addActions(const QList<QAction*> &actions);
void insertActions(QAction *before, const QList<QAction*> &actions);
-#else
- void addActions(QList<QAction*> actions);
- void insertActions(QAction *before, QList<QAction*> actions);
-#endif
void insertAction(QAction *before, QAction *action);
void removeAction(QAction *action);
QList<QAction*> actions() const;
diff --git a/src/widgets/graphicsview/qgraphicswidget_p.cpp b/src/widgets/graphicsview/qgraphicswidget_p.cpp
index e6f39d6803..6c12dc7754 100644
--- a/src/widgets/graphicsview/qgraphicswidget_p.cpp
+++ b/src/widgets/graphicsview/qgraphicswidget_p.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qglobal.h"
@@ -51,8 +15,6 @@
#include <QtWidgets/QStyleOptionTitleBar>
#include <QtWidgets/QGraphicsSceneMouseEvent>
-#include <private/qmemory_p.h>
-
QT_BEGIN_NAMESPACE
void QGraphicsWidgetPrivate::init(QGraphicsItem *parentItem, Qt::WindowFlags wFlags)
@@ -121,7 +83,7 @@ QGraphicsWidgetPrivate::~QGraphicsWidgetPrivate()
void QGraphicsWidgetPrivate::ensureMargins() const
{
if (!margins)
- margins = qt_make_unique<QMarginsF>();
+ margins = std::make_unique<QMarginsF>();
}
/*!
@@ -133,7 +95,7 @@ void QGraphicsWidgetPrivate::ensureMargins() const
void QGraphicsWidgetPrivate::ensureWindowFrameMargins() const
{
if (!windowFrameMargins)
- windowFrameMargins = qt_make_unique<QMarginsF>();
+ windowFrameMargins = std::make_unique<QMarginsF>();
}
/*!
@@ -145,12 +107,12 @@ void QGraphicsWidgetPrivate::ensureWindowFrameMargins() const
void QGraphicsWidgetPrivate::ensureWindowData()
{
if (!windowData)
- windowData = qt_make_unique<WindowData>();
+ windowData = std::make_unique<WindowData>();
}
void QGraphicsWidgetPrivate::setPalette_helper(const QPalette &palette)
{
- if (this->palette == palette && this->palette.resolve() == palette.resolve())
+ if (this->palette == palette && this->palette.resolveMask() == palette.resolveMask())
return;
updatePalette(palette);
}
@@ -172,7 +134,7 @@ void QGraphicsWidgetPrivate::updatePalette(const QPalette &palette)
// Calculate new mask.
if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation))
inheritedPaletteResolveMask = 0;
- int mask = palette.resolve() | inheritedPaletteResolveMask;
+ int mask = palette.resolveMask() | inheritedPaletteResolveMask;
// Propagate to children.
for (int i = 0; i < children.size(); ++i) {
@@ -239,13 +201,13 @@ QPalette QGraphicsWidgetPrivate::naturalWidgetPalette() const
} else if (scene) {
palette = scene->palette();
}
- palette.resolve(0);
+ palette.setResolveMask(0);
return palette;
}
void QGraphicsWidgetPrivate::setFont_helper(const QFont &font)
{
- if (this->font == font && this->font.resolve() == font.resolve())
+ if (this->font == font && this->font.resolveMask() == font.resolveMask())
return;
updateFont(font);
}
@@ -270,7 +232,7 @@ void QGraphicsWidgetPrivate::updateFont(const QFont &font)
// Calculate new mask.
if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation))
inheritedFontResolveMask = 0;
- int mask = font.resolve() | inheritedFontResolveMask;
+ int mask = font.resolveMask() | inheritedFontResolveMask;
// Propagate to children.
for (int i = 0; i < children.size(); ++i) {
@@ -300,7 +262,7 @@ QFont QGraphicsWidgetPrivate::naturalWidgetFont() const
} else if (scene) {
naturalFont = scene->font();
}
- naturalFont.resolve(0);
+ naturalFont.setResolveMask(0);
return naturalFont;
}
@@ -786,7 +748,8 @@ void QGraphicsWidgetPrivate::fixFocusChainBeforeReparenting(QGraphicsWidget *new
// detach from current focus chain; skip this widget subtree.
focusBefore->d_func()->focusNext = focusAfter;
- focusAfter->d_func()->focusPrev = focusBefore;
+ if (focusAfter)
+ focusAfter->d_func()->focusPrev = focusBefore;
if (newParent) {
// attach to new parent's focus chain as the last element
@@ -802,7 +765,8 @@ void QGraphicsWidgetPrivate::fixFocusChainBeforeReparenting(QGraphicsWidget *new
newFocusLast->d_func()->focusNext = q;
focusLast->d_func()->focusNext = newFocusAfter;
- newFocusAfter->d_func()->focusPrev = focusLast;
+ if (newFocusAfter)
+ newFocusAfter->d_func()->focusPrev = focusLast;
focusPrev = newFocusLast;
} else {
// no new parent, so just link up our own prev->last widgets.
diff --git a/src/widgets/graphicsview/qgraphicswidget_p.h b/src/widgets/graphicsview/qgraphicswidget_p.h
index e4cc2c3016..868969cc94 100644
--- a/src/widgets/graphicsview/qgraphicswidget_p.h
+++ b/src/widgets/graphicsview/qgraphicswidget_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRAPHICSWIDGET_P_H
#define QGRAPHICSWIDGET_P_H
diff --git a/src/widgets/graphicsview/qsimplex_p.cpp b/src/widgets/graphicsview/qsimplex_p.cpp
index 38c2df5fc6..948437bf68 100644
--- a/src/widgets/graphicsview/qsimplex_p.cpp
+++ b/src/widgets/graphicsview/qsimplex_p.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qsimplex_p.h"
@@ -46,6 +10,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
\internal
\class QSimplex
@@ -354,7 +320,7 @@ void QSimplex::dumpMatrix()
{
qDebug("---- Simplex Matrix ----\n");
- QString str(QLatin1String(" "));
+ QString str(" "_L1);
for (int j = 0; j < columns; ++j)
str += QString::fromLatin1(" <%1 >").arg(j, 2);
qDebug("%s", qPrintable(str));
@@ -551,7 +517,7 @@ qreal QSimplex::solver(SolverFactor factor)
// Return the value calculated by the simplex plus the value of the
// fixed variables.
- return (factor * valueAt(0, columns - 1)) + resultOffset;
+ return (qToUnderlying(factor) * valueAt(0, columns - 1)) + resultOffset;
}
/*!
@@ -614,7 +580,7 @@ bool QSimplex::simplifyConstraints(QList<QSimplexConstraint *> *constraints)
QList<QSimplexConstraint *>::iterator iter = constraints->begin();
while (iter != constraints->end()) {
QSimplexConstraint *c = *iter;
- if ((c->ratio == QSimplexConstraint::Equal) && (c->variables.count() == 1)) {
+ if ((c->ratio == QSimplexConstraint::Equal) && (c->variables.size() == 1)) {
// Check whether this is a constraint of type Var == K
// If so, save its value to "results".
QSimplexVariable *variable = c->variables.constBegin().key();
diff --git a/src/widgets/graphicsview/qsimplex_p.h b/src/widgets/graphicsview/qsimplex_p.h
index a69cef6115..800c8fe934 100644
--- a/src/widgets/graphicsview/qsimplex_p.h
+++ b/src/widgets/graphicsview/qsimplex_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSIMPLEX_P_H
#define QSIMPLEX_P_H
diff --git a/src/widgets/itemviews/itemviews.pri b/src/widgets/itemviews/itemviews.pri
deleted file mode 100644
index e95b640d18..0000000000
--- a/src/widgets/itemviews/itemviews.pri
+++ /dev/null
@@ -1,105 +0,0 @@
-# Qt gui library, itemviews
-
-qtConfig(itemviews) {
-HEADERS += \
- itemviews/qabstractitemview.h \
- itemviews/qabstractitemview_p.h \
- itemviews/qheaderview.h \
- itemviews/qheaderview_p.h \
- itemviews/qbsptree_p.h \
- itemviews/qabstractitemdelegate.h \
- itemviews/qabstractitemdelegate_p.h \
- itemviews/qitemdelegate.h \
- itemviews/qwidgetitemdata_p.h \
- itemviews/qitemeditorfactory.h \
- itemviews/qitemeditorfactory_p.h \
- itemviews/qstyleditemdelegate.h
-
-SOURCES += \
- itemviews/qabstractitemview.cpp \
- itemviews/qheaderview.cpp \
- itemviews/qbsptree.cpp \
- itemviews/qabstractitemdelegate.cpp \
- itemviews/qitemdelegate.cpp \
- itemviews/qitemeditorfactory.cpp \
- itemviews/qstyleditemdelegate.cpp
-}
-
-qtConfig(columnview) {
- HEADERS += \
- itemviews/qcolumnviewgrip_p.h \
- itemviews/qcolumnview.h \
- itemviews/qcolumnview_p.h
-
- SOURCES += \
- itemviews/qcolumnview.cpp \
- itemviews/qcolumnviewgrip.cpp
-}
-
-qtConfig(datawidgetmapper) {
- HEADERS += itemviews/qdatawidgetmapper.h
- SOURCES += itemviews/qdatawidgetmapper.cpp
-}
-
-qtConfig(dirmodel) {
- HEADERS += itemviews/qdirmodel.h
- SOURCES += itemviews/qdirmodel.cpp
-}
-
-qtConfig(listview) {
- HEADERS += \
- itemviews/qlistview.h \
- itemviews/qlistview_p.h
-
- SOURCES += itemviews/qlistview.cpp
-}
-
-qtConfig(listwidget) {
- HEADERS += \
- itemviews/qlistwidget.h \
- itemviews/qlistwidget_p.h
-
- SOURCES += itemviews/qlistwidget.cpp
-}
-
-qtConfig(tableview) {
- HEADERS += \
- itemviews/qtableview.h \
- itemviews/qtableview_p.h
-
- SOURCES += itemviews/qtableview.cpp
-}
-
-qtConfig(tablewidget) {
- HEADERS += \
- itemviews/qtablewidget.h \
- itemviews/qtablewidget_p.h
-
- SOURCES += itemviews/qtablewidget.cpp
-}
-
-qtConfig(treeview) {
- HEADERS += \
- itemviews/qtreeview.h \
- itemviews/qtreeview_p.h
-
- SOURCES += itemviews/qtreeview.cpp
-}
-
-qtConfig(treewidget) {
- HEADERS += \
- itemviews/qtreewidget.h \
- itemviews/qtreewidget_p.h \
- itemviews/qtreewidgetitemiterator.h
-
- SOURCES += \
- itemviews/qtreewidget.cpp \
- itemviews/qtreewidgetitemiterator.cpp
-}
-
-HEADERS += \
- itemviews/qfileiconprovider.h \
- itemviews/qfileiconprovider_p.h \
-
-SOURCES += \
- itemviews/qfileiconprovider.cpp
diff --git a/src/widgets/itemviews/qabstractitemdelegate.cpp b/src/widgets/itemviews/qabstractitemdelegate.cpp
index bb47881c03..23e8ef0901 100644
--- a/src/widgets/itemviews/qabstractitemdelegate.cpp
+++ b/src/widgets/itemviews/qabstractitemdelegate.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qabstractitemdelegate.h"
@@ -45,7 +9,9 @@
#if QT_CONFIG(whatsthis)
#include <qwhatsthis.h>
#endif
+#if QT_CONFIG(tooltip)
#include <qtooltip.h>
+#endif
#include <qevent.h>
#include <qstring.h>
#include <qdebug.h>
@@ -115,8 +81,8 @@ QT_BEGIN_NAMESPACE
The second approach is to handle user events directly by reimplementing
editorEvent().
- \sa {model-view-programming}{Model/View Programming}, QStyledItemDelegate,
- {Pixelator Example}, QStyledItemDelegate, QStyle
+ \sa {model-view-programming}{Model/View Programming},
+ QStyledItemDelegate, QStyle
*/
/*!
@@ -345,28 +311,6 @@ bool QAbstractItemDelegate::editorEvent(QEvent *,
return false;
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \obsolete
-
- Use QFontMetrics::elidedText() instead.
-
- \oldcode
- QFontMetrics fm = ...
- QString str = QAbstractItemDelegate::elidedText(fm, width, mode, text);
- \newcode
- QFontMetrics fm = ...
- QString str = fm.elidedText(text, mode, width);
- \endcode
-*/
-
-QString QAbstractItemDelegate::elidedText(const QFontMetrics &fontMetrics, int width,
- Qt::TextElideMode mode, const QString &text)
-{
- return fontMetrics.elidedText(text, mode, width);
-}
-#endif
-
/*!
\since 4.3
Whenever a help event occurs, this function is called with the \a event
@@ -389,21 +333,18 @@ bool QAbstractItemDelegate::helpEvent(QHelpEvent *event,
{
if (!event || !view)
return false;
- Q_D(QAbstractItemDelegate);
+ Q_UNUSED(index);
+ Q_UNUSED(option);
switch (event->type()) {
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::ToolTip: {
+ Q_D(QAbstractItemDelegate);
QHelpEvent *he = static_cast<QHelpEvent*>(event);
const int precision = inherits("QItemDelegate") ? 10 : 6; // keep in sync with DBL_DIG in qitemdelegate.cpp
const QString tooltip = index.isValid() ?
d->textForRole(Qt::ToolTipRole, index.data(Qt::ToolTipRole), option.locale, precision) :
QString();
- QRect rect;
- if (index.isValid()) {
- const QRect r = view->visualRect(index);
- rect = QRect(view->mapToGlobal(r.topLeft()), r.size());
- }
- QToolTip::showText(he->globalPos(), tooltip, view, rect);
+ QToolTip::showText(he->globalPos(), tooltip, view->viewport(), option.rect);
event->setAccepted(!tooltip.isEmpty());
break;
}
@@ -413,6 +354,7 @@ bool QAbstractItemDelegate::helpEvent(QHelpEvent *event,
event->setAccepted(index.data(Qt::WhatsThisRole).isValid());
break;
case QEvent::WhatsThis: {
+ Q_D(QAbstractItemDelegate);
QHelpEvent *he = static_cast<QHelpEvent*>(event);
const int precision = inherits("QItemDelegate") ? 10 : 6; // keep in sync with DBL_DIG in qitemdelegate.cpp
const QString whatsthis = index.isValid() ?
@@ -423,6 +365,7 @@ bool QAbstractItemDelegate::helpEvent(QHelpEvent *event,
break;
}
#endif
+ case QEvent::None:
default:
break;
}
@@ -434,9 +377,9 @@ bool QAbstractItemDelegate::helpEvent(QHelpEvent *event,
This virtual method is reserved and will be used in Qt 5.1.
*/
-QVector<int> QAbstractItemDelegate::paintingRoles() const
+QList<int> QAbstractItemDelegate::paintingRoles() const
{
- return QVector<int>();
+ return QList<int>();
}
QAbstractItemDelegatePrivate::QAbstractItemDelegatePrivate()
@@ -537,12 +480,13 @@ bool QAbstractItemDelegatePrivate::editorEventFilter(QObject *object, QEvent *ev
// If the application loses focus while editing, then the focus needs to go back
// to the itemview when the editor closes. This ensures that when the application
// is active again it will have the focus on the itemview as expected.
+ QWidget *editorParent = editor->parentWidget();
const bool manuallyFixFocus = (event->type() == QEvent::FocusOut) && !editor->hasFocus() &&
- editor->parentWidget() &&
+ editorParent &&
(static_cast<QFocusEvent *>(event)->reason() == Qt::ActiveWindowFocusReason);
emit q->closeEditor(editor, QAbstractItemDelegate::NoHint);
if (manuallyFixFocus)
- editor->parentWidget()->setFocus();
+ editorParent->setFocus();
}
#ifndef QT_NO_SHORTCUT
} else if (event->type() == QEvent::ShortcutOverride) {
@@ -570,8 +514,16 @@ 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)
+ Q_UNUSED(editor);
#endif // QT_CONFIG(lineedit)
return true;
@@ -585,27 +537,27 @@ QString QAbstractItemDelegatePrivate::textForRole(Qt::ItemDataRole role, const Q
case QMetaType::Float:
text = locale.toString(value.toFloat());
break;
- case QVariant::Double:
+ case QMetaType::Double:
text = locale.toString(value.toDouble(), 'g', precision);
break;
- case QVariant::Int:
- case QVariant::LongLong:
+ case QMetaType::Int:
+ case QMetaType::LongLong:
text = locale.toString(value.toLongLong());
break;
- case QVariant::UInt:
- case QVariant::ULongLong:
+ case QMetaType::UInt:
+ case QMetaType::ULongLong:
text = locale.toString(value.toULongLong());
break;
- case QVariant::Date:
+ case QMetaType::QDate:
text = locale.toString(value.toDate(), formatType);
break;
- case QVariant::Time:
+ case QMetaType::QTime:
text = locale.toString(value.toTime(), formatType);
break;
- case QVariant::DateTime:
+ case QMetaType::QDateTime:
text = locale.toString(value.toDateTime(), formatType);
break;
- case QVariant::Type(QMetaType::QJsonValue): {
+ case QMetaType::QJsonValue: {
const QJsonValue val = value.toJsonValue();
if (val.isBool()) {
text = QVariant(val.toBool()).toString();
@@ -621,7 +573,7 @@ QString QAbstractItemDelegatePrivate::textForRole(Qt::ItemDataRole role, const Q
default: {
text = value.toString();
if (role == Qt::DisplayRole)
- text.replace(QLatin1Char('\n'), QChar::LineSeparator);
+ text.replace(u'\n', QChar::LineSeparator);
break;
}
}
diff --git a/src/widgets/itemviews/qabstractitemdelegate.h b/src/widgets/itemviews/qabstractitemdelegate.h
index 5696e55691..b28a1c4f80 100644
--- a/src/widgets/itemviews/qabstractitemdelegate.h
+++ b/src/widgets/itemviews/qabstractitemdelegate.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTITEMDELEGATE_H
#define QABSTRACTITEMDELEGATE_H
@@ -103,18 +67,12 @@ public:
const QStyleOptionViewItem &option,
const QModelIndex &index);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use QFontMetrics::elidedText() instead")
- static QString elidedText(const QFontMetrics &fontMetrics, int width,
- Qt::TextElideMode mode, const QString &text);
-#endif
-
virtual bool helpEvent(QHelpEvent *event,
QAbstractItemView *view,
const QStyleOptionViewItem &option,
const QModelIndex &index);
- virtual QVector<int> paintingRoles() const;
+ virtual QList<int> paintingRoles() const;
Q_SIGNALS:
void commitData(QWidget *editor);
diff --git a/src/widgets/itemviews/qabstractitemdelegate_p.h b/src/widgets/itemviews/qabstractitemdelegate_p.h
index da76d31e8b..e720f4d105 100644
--- a/src/widgets/itemviews/qabstractitemdelegate_p.h
+++ b/src/widgets/itemviews/qabstractitemdelegate_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTITEMDELEGATE_P_H
#define QABSTRACTITEMDELEGATE_P_H
@@ -55,6 +19,9 @@
#include "qabstractitemdelegate.h"
#include <private/qobject_p.h>
+#include <qvariant.h>
+#include <qmetatype.h>
+
QT_REQUIRE_CONFIG(itemviews);
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/itemviews/qabstractitemview.cpp b/src/widgets/itemviews/qabstractitemview.cpp
index 0e54cf235f..85e478a71e 100644
--- a/src/widgets/itemviews/qabstractitemview.cpp
+++ b/src/widgets/itemviews/qabstractitemview.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qabstractitemview.h"
@@ -49,7 +13,9 @@
#endif
#include <qevent.h>
#include <qscrollbar.h>
+#if QT_CONFIG(tooltip)
#include <qtooltip.h>
+#endif
#include <qdatetime.h>
#if QT_CONFIG(lineedit)
#include <qlineedit.h>
@@ -64,7 +30,7 @@
#include <private/qapplication_p.h>
#include <private/qguiapplication_p.h>
#include <private/qscrollbar_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include <qaccessible.h>
#endif
#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
@@ -84,9 +50,12 @@ QAbstractItemViewPrivate::QAbstractItemViewPrivate()
selectionMode(QAbstractItemView::ExtendedSelection),
selectionBehavior(QAbstractItemView::SelectItems),
currentlyCommittingEditor(nullptr),
+ pressClosedEditor(false),
+ waitForIMCommit(false),
pressedModifiers(Qt::NoModifier),
pressedPosition(QPoint(-1, -1)),
pressedAlreadySelected(false),
+ releaseFromDoubleClick(false),
viewportEnteredNeeded(false),
state(QAbstractItemView::NoState),
stateBeforeAnimation(QAbstractItemView::NoState),
@@ -98,6 +67,7 @@ QAbstractItemViewPrivate::QAbstractItemViewPrivate()
dragEnabled(false),
dragDropMode(QAbstractItemView::NoDragDrop),
overwrite(false),
+ dropEventMoved(false),
dropIndicatorPosition(QAbstractItemView::OnItem),
defaultDropAction(Qt::IgnoreAction),
#endif
@@ -132,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);
@@ -159,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()));
}
@@ -202,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);
@@ -220,7 +191,11 @@ void QAbstractItemViewPrivate::_q_scrollerStateChanged()
// restore the old selection if we really start scrolling
if (q->selectionModel()) {
q->selectionModel()->select(oldSelection, QItemSelectionModel::ClearAndSelect);
+ // block autoScroll logic while we are already handling scrolling
+ const bool wasAutoScroll = autoScroll;
+ autoScroll = false;
q->selectionModel()->setCurrentIndex(oldCurrent, QItemSelectionModel::NoUpdate);
+ autoScroll = wasAutoScroll;
}
Q_FALLTHROUGH();
@@ -234,6 +209,73 @@ void QAbstractItemViewPrivate::_q_scrollerStateChanged()
#endif // QT_NO_GESTURES
+void QAbstractItemViewPrivate::delegateSizeHintChanged(const QModelIndex &index)
+{
+ Q_Q(QAbstractItemView);
+ if (model) {
+ if (!model->checkIndex(index))
+ qWarning("Delegate size hint changed for a model index that does not belong to this view");
+ }
+ 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
@@ -268,7 +310,7 @@ void QAbstractItemViewPrivate::_q_scrollerStateChanged()
\li Changes the current item and selects it. The previously
selected item(s) is not deselected.
\row
- \li Ctr+Space
+ \li Ctrl+Space
\li Toggles selection of the current item.
\row
\li Tab/Backtab
@@ -334,7 +376,7 @@ void QAbstractItemViewPrivate::_q_scrollerStateChanged()
\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
*/
/*!
@@ -647,6 +689,7 @@ QAbstractItemView::~QAbstractItemView()
d->autoScrollTimer.stop();
d->delayedLayout.stop();
d->fetchMoreTimer.stop();
+ d->disconnectAll();
}
/*!
@@ -675,77 +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,QVector<int>)),
- this, SLOT(dataChanged(QModelIndex,QModelIndex,QVector<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());
- // These asserts do basic sanity checking of the model
- Q_ASSERT_X(d->model->index(0,0) == d->model->index(0,0),
- "QAbstractItemView::setModel",
- "A model should return the exact same index "
- "(including its internal id/pointer) when asked for it twice in a row.");
- Q_ASSERT_X(!d->model->index(0,0).parent().isValid(),
- "QAbstractItemView::setModel",
- "The parent of a top level index should be invalid");
-
if (d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- connect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- connect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)),
- this, SLOT(dataChanged(QModelIndex,QModelIndex,QVector<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
@@ -795,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);
@@ -848,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(doItemsLayout()));
- }
+ 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(doItemsLayout()), Qt::QueuedConnection);
- }
+ if (d->delegateRefCount(delegate) == 0)
+ d->connectDelegate(delegate);
}
d->itemDelegate = delegate;
viewport()->update();
@@ -885,10 +889,26 @@ QAbstractItemDelegate *QAbstractItemView::itemDelegate() const
*/
QVariant QAbstractItemView::inputMethodQuery(Qt::InputMethodQuery query) const
{
+ Q_D(const QAbstractItemView);
const QModelIndex current = currentIndex();
- if (!current.isValid() || query != Qt::ImCursorRectangle)
- return QAbstractScrollArea::inputMethodQuery(query);
- return visualRect(current);
+ QVariant result;
+ if (current.isValid()) {
+ if (QWidget *currentEditor;
+ d->waitForIMCommit && (currentEditor = d->editorForIndex(current).widget)) {
+ // An editor is open but the initial preedit is still ongoing. Delegate
+ // queries to the editor and map coordinates from editor to this view.
+ result = currentEditor->inputMethodQuery(query);
+ if (result.typeId() == QMetaType::QRect) {
+ const QRect editorRect = result.value<QRect>();
+ result = QRect(currentEditor->mapTo(this, editorRect.topLeft()), editorRect.size());
+ }
+ } else if (query == Qt::ImCursorRectangle) {
+ result = visualRect(current);
+ }
+ }
+ if (!result.isValid())
+ result = QAbstractScrollArea::inputMethodQuery(query);
+ return result;
}
/*!
@@ -916,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(doItemsLayout()));
- }
+ 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(doItemsLayout()), Qt::QueuedConnection);
- }
+ if (d->delegateRefCount(delegate) == 0)
+ d->connectDelegate(delegate);
d->rowDelegates.insert(row, delegate);
}
viewport()->update();
@@ -976,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(doItemsLayout()));
- }
+ 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(doItemsLayout()), Qt::QueuedConnection);
- }
+ if (d->delegateRefCount(delegate) == 0)
+ d->connectDelegate(delegate);
d->columnDelegates.insert(column, delegate);
}
viewport()->update();
@@ -1013,10 +1017,21 @@ QAbstractItemDelegate *QAbstractItemView::itemDelegateForColumn(int column) cons
}
/*!
+ \fn QAbstractItemDelegate *QAbstractItemView::itemDelegate(const QModelIndex &index) const
+ \deprecated Use itemDelegateForIndex() instead.
+ Returns the item delegate used by this view and model for
+ the given \a index.
+*/
+
+/*!
+ \since 6.0
+
Returns the item delegate used by this view and model for
the given \a index.
+
+ \sa setItemDelegate(), setItemDelegateForRow(), setItemDelegateForColumn()
*/
-QAbstractItemDelegate *QAbstractItemView::itemDelegate(const QModelIndex &index) const
+QAbstractItemDelegate *QAbstractItemView::itemDelegateForIndex(const QModelIndex &index) const
{
Q_D(const QAbstractItemView);
return d->delegateForIndex(index);
@@ -1117,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()));
}
@@ -1129,7 +1148,7 @@ void QAbstractItemView::reset()
setRootIndex(QModelIndex());
if (d->selectionModel)
d->selectionModel->reset();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
QAccessibleTableModelChangeEvent accessibleEvent(this, QAccessibleTableModelChangeEvent::ModelReset);
QAccessible::updateAccessibility(&accessibleEvent);
@@ -1151,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();
}
@@ -1176,12 +1201,21 @@ QModelIndex QAbstractItemView::rootIndex() const
void QAbstractItemView::selectAll()
{
Q_D(QAbstractItemView);
- SelectionMode mode = d->selectionMode;
- if (mode == MultiSelection || mode == ExtendedSelection)
+ const SelectionMode mode = d->selectionMode;
+ switch (mode) {
+ case MultiSelection:
+ case ExtendedSelection:
d->selectAll(QItemSelectionModel::ClearAndSelect
- |d->selectionBehaviorFlags());
- else if (mode != SingleSelection)
- d->selectAll(selectionCommand(d->model->index(0, 0, d->root)));
+ | d->selectionBehaviorFlags());
+ break;
+ case NoSelection:
+ case ContiguousSelection:
+ if (d->model->hasChildren(d->root))
+ d->selectAll(selectionCommand(d->model->index(0, 0, d->root)));
+ break;
+ case SingleSelection:
+ break;
+ }
}
/*!
@@ -1534,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.
@@ -1627,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())
@@ -1698,9 +1732,15 @@ 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)->pos()));
+ d->setHoverIndex(indexAt(static_cast<QHoverEvent*>(event)->position().toPoint()));
break;
case QEvent::HoverLeave:
d->setHoverIndex(QModelIndex());
@@ -1725,11 +1765,12 @@ bool QAbstractItemView::viewportEvent(QEvent *event)
case QEvent::WhatsThis: {
QHelpEvent *he = static_cast<QHelpEvent*>(event);
const QModelIndex index = indexAt(he->pos());
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
option.rect = visualRect(index);
option.state |= (index == currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
- QAbstractItemDelegate *delegate = d->delegateForIndex(index);
+ QAbstractItemDelegate *delegate = itemDelegateForIndex(index);
if (!delegate)
return false;
return delegate->helpEvent(he, this, option, index);
@@ -1744,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;
@@ -1762,12 +1806,15 @@ bool QAbstractItemView::viewportEvent(QEvent *event)
void QAbstractItemView::mousePressEvent(QMouseEvent *event)
{
Q_D(QAbstractItemView);
+ d->releaseFromDoubleClick = false;
d->delayedAutoScroll.stop(); //any interaction with the view cancel the auto scrolling
- QPoint pos = event->pos();
+ QPoint pos = event->position().toPoint();
QPersistentModelIndex index = indexAt(pos);
- if (!d->selectionModel
- || (d->state == EditingState && d->hasEditor(index)))
+ // this is the mouse press event that closed the last editor (via focus event)
+ d->pressClosedEditor = d->pressClosedEditorWatcher.isActive() && d->lastEditedIndex == index;
+
+ if (!d->selectionModel || (d->state == EditingState && d->hasEditor(index)))
return;
d->pressedAlreadySelected = d->selectionModel->isSelected(index);
@@ -1776,8 +1823,16 @@ void QAbstractItemView::mousePressEvent(QMouseEvent *event)
QItemSelectionModel::SelectionFlags command = selectionCommand(index, event);
d->noSelectionOnMousePress = command == QItemSelectionModel::NoUpdate || !index.isValid();
QPoint offset = d->offset();
- d->pressedPosition = pos + offset;
- if ((command & QItemSelectionModel::Current) == 0) {
+ 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;
d->currentSelectionStartIndex = index;
}
else if (!d->currentSelectionStartIndex.isValid())
@@ -1799,7 +1854,7 @@ void QAbstractItemView::mousePressEvent(QMouseEvent *event)
command |= d->ctrlDragSelectionFlag;
}
- if ((command & QItemSelectionModel::Current) == 0) {
+ if (!(command & QItemSelectionModel::Current)) {
setSelection(QRect(pos, QSize(1, 1)), command);
} else {
QRect rect(visualRect(d->currentSelectionStartIndex).center(), pos);
@@ -1828,21 +1883,16 @@ void QAbstractItemView::mousePressEvent(QMouseEvent *event)
void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
{
Q_D(QAbstractItemView);
- QPoint topLeft;
- QPoint bottomRight = event->pos();
+ QPoint bottomRight = event->position().toPoint();
+
+ d->draggedPosition = bottomRight + d->offset();
if (state() == ExpandingState || state() == CollapsingState)
return;
#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)
@@ -1853,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);
@@ -1867,6 +1915,7 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
&& (event->buttons() != Qt::NoButton)
&& !d->selectedDraggableIndexes().isEmpty()) {
setState(DraggingState);
+ d->maybeStartDrag(bottomRight);
return;
}
#endif
@@ -1884,10 +1933,10 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
setSelection(selectionRect, command);
// set at the end because it might scroll the view
- if (index.isValid()
- && (index != d->selectionModel->currentIndex())
- && d->isIndexEnabled(index))
+ if (index.isValid() && (index != d->selectionModel->currentIndex()) && d->isIndexEnabled(index))
d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
+ else if (d->shouldAutoScroll(event->pos()) && !d->autoScrollTimer.isActive())
+ startAutoScroll();
}
}
@@ -1901,8 +1950,10 @@ void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event)
{
Q_D(QAbstractItemView);
+ const bool releaseFromDoubleClick = d->releaseFromDoubleClick;
+ d->releaseFromDoubleClick = false;
- QPoint pos = event->pos();
+ QPoint pos = event->position().toPoint();
QPersistentModelIndex index = indexAt(pos);
if (state() == EditingState) {
@@ -1913,18 +1964,22 @@ void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event)
return;
}
- bool click = (index == d->pressedIndex && index.isValid());
- bool selectedClicked = click && (event->button() == Qt::LeftButton) && d->pressedAlreadySelected;
+ bool click = (index == d->pressedIndex && index.isValid() && !releaseFromDoubleClick);
+ bool selectedClicked = click && d->pressedAlreadySelected
+ && (event->button() == Qt::LeftButton)
+ && (event->modifiers() == Qt::NoModifier);
EditTrigger trigger = (selectedClicked ? SelectedClicked : NoEditTriggers);
- const bool edited = click ? edit(index, trigger, event) : false;
+ const bool edited = click && !d->pressClosedEditor ? edit(index, trigger, event) : false;
d->ctrlDragSelectionFlag = QItemSelectionModel::NoUpdate;
if (d->selectionModel && d->noSelectionOnMousePress) {
d->noSelectionOnMousePress = false;
- d->selectionModel->select(index, selectionCommand(index, event));
+ if (!d->pressClosedEditor)
+ d->selectionModel->select(index, selectionCommand(index, event));
}
+ d->pressClosedEditor = false;
setState(NoState);
if (click) {
@@ -1932,7 +1987,8 @@ void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event)
emit clicked(index);
if (edited)
return;
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
if (d->pressedAlreadySelected)
option.state |= QStyle::State_Selected;
if ((d->model->flags(index) & Qt::ItemIsEnabled)
@@ -1950,13 +2006,14 @@ void QAbstractItemView::mouseDoubleClickEvent(QMouseEvent *event)
{
Q_D(QAbstractItemView);
- QModelIndex index = indexAt(event->pos());
+ QModelIndex index = indexAt(event->position().toPoint());
if (!index.isValid()
|| !d->isIndexEnabled(index)
|| (d->pressedIndex != index)) {
QMouseEvent me(QEvent::MouseButtonPress,
- event->localPos(), event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers(), event->source());
+ event->position(), event->scenePosition(), event->globalPosition(),
+ event->button(), event->buttons(), event->modifiers(),
+ event->source(), event->pointingDevice());
mousePressEvent(&me);
return;
}
@@ -1966,7 +2023,7 @@ void QAbstractItemView::mouseDoubleClickEvent(QMouseEvent *event)
if ((event->button() == Qt::LeftButton) && !edit(persistent, DoubleClicked, event)
&& !style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, nullptr, this))
emit activated(persistent);
- d->pressedIndex = QModelIndex();
+ d->releaseFromDoubleClick = true;
}
#if QT_CONFIG(draganddrop)
@@ -2003,6 +2060,7 @@ void QAbstractItemView::dragEnterEvent(QDragEnterEvent *event)
void QAbstractItemView::dragMoveEvent(QDragMoveEvent *event)
{
Q_D(QAbstractItemView);
+ d->draggedPosition = event->position().toPoint() + d->offset();
if (dragDropMode() == InternalMove
&& (event->source() != this || !(event->possibleActions() & Qt::MoveAction)))
return;
@@ -2010,14 +2068,14 @@ void QAbstractItemView::dragMoveEvent(QDragMoveEvent *event)
// ignore by default
event->ignore();
- QModelIndex index = indexAt(event->pos());
+ QModelIndex index = indexAt(event->position().toPoint());
d->hover = index;
if (!d->droppingOnItself(event, index)
&& d->canDrop(event)) {
if (index.isValid() && d->showDropIndicator) {
QRect rect = visualRect(index);
- d->dropIndicatorPosition = d->position(event->pos(), rect, index);
+ d->dropIndicatorPosition = d->position(event->position().toPoint(), rect, index);
switch (d->dropIndicatorPosition) {
case AboveItem:
if (d->isIndexDropEnabled(index.parent())) {
@@ -2060,7 +2118,7 @@ void QAbstractItemView::dragMoveEvent(QDragMoveEvent *event)
d->viewport->update();
} // can drop
- if (d->shouldAutoScroll(event->pos()))
+ if (d->shouldAutoScroll(event->position().toPoint()))
startAutoScroll();
}
@@ -2157,9 +2215,9 @@ bool QAbstractItemViewPrivate::dropOn(QDropEvent *event, int *dropRow, int *drop
QModelIndex index;
// rootIndex() (i.e. the viewport) might be a valid index
- if (viewport->rect().contains(event->pos())) {
- index = q->indexAt(event->pos());
- if (!index.isValid() || !q->visualRect(index).contains(event->pos()))
+ if (viewport->rect().contains(event->position().toPoint())) {
+ index = q->indexAt(event->position().toPoint());
+ if (!index.isValid() || !q->visualRect(index).contains(event->position().toPoint()))
index = root;
}
@@ -2168,7 +2226,7 @@ bool QAbstractItemViewPrivate::dropOn(QDropEvent *event, int *dropRow, int *drop
int row = -1;
int col = -1;
if (index != root) {
- dropIndicatorPosition = position(event->pos(), q->visualRect(index), index);
+ dropIndicatorPosition = position(event->position().toPoint(), q->visualRect(index), index);
switch (dropIndicatorPosition) {
case QAbstractItemView::AboveItem:
row = index.row();
@@ -2336,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.type() == QVariant::String)
- 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
@@ -2464,7 +2523,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
}
#endif
break;
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
case Qt::Key_Enter:
case Qt::Key_Return:
// Propagate the enter if you couldn't edit the item and there are no
@@ -2479,7 +2538,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
break;
case Qt::Key_Enter:
case Qt::Key_Return:
- // ### we can't open the editor on enter, becuse
+ // ### we can't open the editor on enter, because
// some widgets will forward the enter event back
// to the viewport, starting an endless loop
if (state() != EditingState || hasFocus()) {
@@ -2496,7 +2555,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
break;
}
#endif
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
if (event->key() == Qt::Key_O && event->modifiers() & Qt::ControlModifier && currentIndex().isValid()) {
emit activated(currentIndex());
break;
@@ -2562,6 +2621,8 @@ void QAbstractItemView::timerEvent(QTimerEvent *event)
//we only get here if there was no double click
if (d->pressedIndex.isValid() && d->pressedIndex == currentIndex())
scrollTo(d->pressedIndex);
+ } else if (event->timerId() == d->pressClosedEditorWatcher.timerId()) {
+ d->pressClosedEditorWatcher.stop();
}
}
@@ -2570,14 +2631,53 @@ void QAbstractItemView::timerEvent(QTimerEvent *event)
*/
void QAbstractItemView::inputMethodEvent(QInputMethodEvent *event)
{
- if (event->commitString().isEmpty() && event->preeditString().isEmpty()) {
+ Q_D(QAbstractItemView);
+ // When QAbstractItemView::AnyKeyPressed is used, a new IM composition might
+ // start before the editor widget acquires focus. Changing focus would interrupt
+ // the composition, so we keep focus on the view until that first composition
+ // is complete, and pass QInputMethoEvents on to the editor widget so that the
+ // user gets the expected feedback. See also inputMethodQuery, which redirects
+ // calls to the editor widget during that period.
+ bool forwardEventToEditor = false;
+ const bool commit = !event->commitString().isEmpty();
+ const bool preediting = !event->preeditString().isEmpty();
+ if (QWidget *currentEditor = d->editorForIndex(currentIndex()).widget) {
+ if (d->waitForIMCommit) {
+ if (commit || !preediting) {
+ // commit or cancel
+ d->waitForIMCommit = false;
+ QApplication::sendEvent(currentEditor, event);
+ if (!commit) {
+ QAbstractItemDelegate *delegate = itemDelegateForIndex(currentIndex());
+ if (delegate)
+ delegate->setEditorData(currentEditor, currentIndex());
+ d->selectAllInEditor(currentEditor);
+ }
+ if (currentEditor->focusPolicy() != Qt::NoFocus)
+ currentEditor->setFocus();
+ } else {
+ // more pre-editing
+ QApplication::sendEvent(currentEditor, event);
+ }
+ return;
+ }
+ } else if (preediting) {
+ // don't set focus when the editor opens
+ d->waitForIMCommit = true;
+ // but pass preedit on to editor
+ forwardEventToEditor = true;
+ } else if (!commit) {
event->ignore();
return;
}
if (!edit(currentIndex(), AnyKeyPressed, event)) {
- if (!event->commitString().isEmpty())
+ d->waitForIMCommit = false;
+ if (commit)
keyboardSearch(event->commitString());
event->ignore();
+ } else if (QWidget *currentEditor; forwardEventToEditor
+ && (currentEditor = d->editorForIndex(currentIndex()).widget)) {
+ QApplication::sendEvent(currentEditor, event);
}
}
@@ -2628,8 +2728,7 @@ QModelIndexList QAbstractItemView::selectedIndexes() const
auto isHidden = [this](const QModelIndex &idx) {
return isIndexHidden(idx);
};
- const auto end = indexes.end();
- indexes.erase(std::remove_if(indexes.begin(), end, isHidden), end);
+ indexes.removeIf(isHidden);
}
return indexes;
}
@@ -2657,7 +2756,10 @@ bool QAbstractItemView::edit(const QModelIndex &index, EditTrigger trigger, QEve
if (QWidget *w = (d->persistent.isEmpty() ? static_cast<QWidget*>(nullptr) : d->editorForIndex(index).widget.data())) {
if (w->focusPolicy() == Qt::NoFocus)
return false;
- w->setFocus();
+ if (!d->waitForIMCommit)
+ w->setFocus();
+ else
+ updateMicroFocus();
return true;
}
@@ -2668,16 +2770,23 @@ bool QAbstractItemView::edit(const QModelIndex &index, EditTrigger trigger, QEve
d->delayedEditing.stop();
}
+ // in case e.g. setData() triggers a reset()
+ QPersistentModelIndex safeIndex(index);
+
if (d->sendDelegateEvent(index, event)) {
- update(index);
+ update(safeIndex);
return true;
}
+ if (!safeIndex.isValid()) {
+ return false;
+ }
+
// save the previous trigger before updating
EditTriggers lastTrigger = d->lastTrigger;
d->lastTrigger = trigger;
- if (!d->shouldEdit(trigger, d->model->buddy(index)))
+ if (!d->shouldEdit(trigger, d->model->buddy(safeIndex)))
return false;
if (d->delayedEditing.isActive())
@@ -2692,7 +2801,7 @@ bool QAbstractItemView::edit(const QModelIndex &index, EditTrigger trigger, QEve
if (trigger == SelectedClicked)
d->delayedEditing.start(QApplication::doubleClickInterval(), this);
else
- d->openEditor(index, d->shouldForwardEvent(trigger, event) ? event : nullptr);
+ d->openEditor(safeIndex, d->shouldForwardEvent(trigger, event) ? event : nullptr);
return true;
}
@@ -2714,14 +2823,15 @@ void QAbstractItemView::updateEditorData()
void QAbstractItemView::updateEditorGeometries()
{
Q_D(QAbstractItemView);
- if(d->editorIndexHash.isEmpty())
+ if (d->editorIndexHash.isEmpty())
return;
if (d->delayedPendingLayout) {
// doItemsLayout() will end up calling this function again
d->executePostedLayout();
return;
}
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
QEditorIndexHash::iterator it = d->editorIndexHash.begin();
QWidgetList editorsToRelease;
QWidgetList editorsToHide;
@@ -2732,7 +2842,7 @@ void QAbstractItemView::updateEditorGeometries()
option.rect = visualRect(index);
if (option.rect.isValid()) {
editor->show();
- QAbstractItemDelegate *delegate = d->delegateForIndex(index);
+ QAbstractItemDelegate *delegate = itemDelegateForIndex(index);
if (delegate)
delegate->updateEditorGeometry(editor, option, index);
} else {
@@ -2748,10 +2858,10 @@ void QAbstractItemView::updateEditorGeometries()
//we hide and release the editor outside of the loop because it might change the focus and try
//to change the editors hashes.
- for (int i = 0; i < editorsToHide.count(); ++i) {
+ for (int i = 0; i < editorsToHide.size(); ++i) {
editorsToHide.at(i)->hide();
}
- for (int i = 0; i < editorsToRelease.count(); ++i) {
+ for (int i = 0; i < editorsToRelease.size(); ++i) {
d->releaseEditor(editorsToRelease.at(i));
}
}
@@ -2826,33 +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);
- if (!index.isValid())
- return; // the editor was not registered
-
- if (!isPersistent) {
- setState(NoState);
- QModelIndex index = d->indexForEditor(editor);
- editor->removeEventFilter(d->delegateForIndex(index));
- d->removeEditor(editor);
- }
- if (hadFocus) {
- if (focusPolicy() != Qt::NoFocus)
- setFocus(); // this will send a focusLost event to the editor
- else
- editor->clearFocus();
+ const bool isPersistent = d->persistent.contains(editor);
+ const QModelIndex index = d->indexForEditor(editor);
+ if (!index.isValid()) {
+ 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
@@ -2902,10 +3029,12 @@ void QAbstractItemView::commitData(QWidget *editor)
if (!editor || !d->itemDelegate || d->currentlyCommittingEditor)
return;
QModelIndex index = d->indexForEditor(editor);
- if (!index.isValid())
+ if (!index.isValid()) {
+ qWarning("QAbstractItemView::commitData called with an editor that does not belong to this view");
return;
+ }
d->currentlyCommittingEditor = editor;
- QAbstractItemDelegate *delegate = d->delegateForIndex(index);
+ QAbstractItemDelegate *delegate = itemDelegateForIndex(index);
editor->removeEventFilter(delegate);
delegate->setModelData(editor, d->model, index);
editor->installEventFilter(delegate);
@@ -2927,65 +3056,7 @@ void QAbstractItemView::editorDestroyed(QObject *editor)
setState(NoState);
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \obsolete
- Sets the horizontal scroll bar's steps per item to \a steps.
- This is the number of steps used by the horizontal scroll bar to
- represent the width of an item.
-
- Note that if the view has a horizontal header, the item steps
- will be ignored and the header section size will be used instead.
-
- \sa horizontalStepsPerItem(), setVerticalStepsPerItem()
-*/
-void QAbstractItemView::setHorizontalStepsPerItem(int steps)
-{
- Q_UNUSED(steps)
- // do nothing
-}
-
-/*!
- \obsolete
- Returns the horizontal scroll bar's steps per item.
-
- \sa setHorizontalStepsPerItem(), verticalStepsPerItem()
-*/
-int QAbstractItemView::horizontalStepsPerItem() const
-{
- return 1;
-}
-
-/*!
- \obsolete
- Sets the vertical scroll bar's steps per item to \a steps.
-
- This is the number of steps used by the vertical scroll bar to
- represent the height of an item.
-
- Note that if the view has a vertical header, the item steps
- will be ignored and the header section size will be used instead.
-
- \sa verticalStepsPerItem(), setHorizontalStepsPerItem()
-*/
-void QAbstractItemView::setVerticalStepsPerItem(int steps)
-{
- Q_UNUSED(steps)
- // do nothing
-}
-
-/*!
- \obsolete
- Returns the vertical scroll bar's steps per item.
-
- \sa setVerticalStepsPerItem(), horizontalStepsPerItem()
-*/
-int QAbstractItemView::verticalStepsPerItem() const
-{
- return 1;
-}
-#endif
/*!
Moves to and selects the item best matching the string \a search.
@@ -3020,9 +3091,9 @@ void QAbstractItemView::keyboardSearch(const QString &search)
// special case for searches with same key like 'aaaaa'
bool sameKey = false;
- if (d->keyboardInput.length() > 1) {
- int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.length() - 1));
- sameKey = (c == d->keyboardInput.length());
+ if (d->keyboardInput.size() > 1) {
+ int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.size() - 1));
+ sameKey = (c == d->keyboardInput.size());
if (sameKey)
skipRow = true;
}
@@ -3076,8 +3147,10 @@ QSize QAbstractItemView::sizeHintForIndex(const QModelIndex &index) const
Q_D(const QAbstractItemView);
if (!d->isIndexValid(index))
return QSize();
- const auto delegate = d->delegateForIndex(index);
- return delegate ? delegate->sizeHint(d->viewOptionsV1(), index) : QSize();
+ const auto delegate = itemDelegateForIndex(index);
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
+ return delegate ? delegate->sizeHint(option, index) : QSize();
}
/*!
@@ -3105,14 +3178,15 @@ int QAbstractItemView::sizeHintForRow(int row) const
ensurePolished();
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
int height = 0;
int colCount = d->model->columnCount(d->root);
for (int c = 0; c < colCount; ++c) {
const QModelIndex index = d->model->index(row, c, d->root);
if (QWidget *editor = d->editorForIndex(index).widget.data())
height = qMax(height, editor->height());
- if (const QAbstractItemDelegate *delegate = d->delegateForIndex(index))
+ if (const QAbstractItemDelegate *delegate = itemDelegateForIndex(index))
height = qMax(height, delegate->sizeHint(option, index).height());
}
return height;
@@ -3135,14 +3209,15 @@ int QAbstractItemView::sizeHintForColumn(int column) const
ensurePolished();
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
int width = 0;
int rows = d->model->rowCount(d->root);
for (int r = 0; r < rows; ++r) {
const QModelIndex index = d->model->index(r, column, d->root);
if (QWidget *editor = d->editorForIndex(index).widget.data())
width = qMax(width, editor->sizeHint().width());
- if (const QAbstractItemDelegate *delegate = d->delegateForIndex(index))
+ if (const QAbstractItemDelegate *delegate = itemDelegateForIndex(index))
width = qMax(width, delegate->sizeHint(option, index).width());
}
return width;
@@ -3157,7 +3232,8 @@ int QAbstractItemView::sizeHintForColumn(int column) const
void QAbstractItemView::openPersistentEditor(const QModelIndex &index)
{
Q_D(QAbstractItemView);
- QStyleOptionViewItem options = d->viewOptionsV1();
+ QStyleOptionViewItem options;
+ initViewItemOption(&options);
options.rect = visualRect(index);
options.state |= (index == currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
@@ -3244,8 +3320,10 @@ void QAbstractItemView::setIndexWidget(const QModelIndex &index, QWidget *widget
widget->installEventFilter(this);
widget->show();
dataChanged(index, index); // update the geometry
- if (!d->delayedPendingLayout)
+ if (!d->delayedPendingLayout) {
widget->setGeometry(visualRect(index));
+ d->doDelayedItemsLayout(); // relayout due to updated geometry
+ }
}
}
@@ -3303,8 +3381,8 @@ void QAbstractItemView::update(const QModelIndex &index)
{
Q_D(QAbstractItemView);
if (index.isValid()) {
- const QRect rect = visualRect(index);
- //this test is important for peformance reason
+ 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
if (d->viewport->rect().intersects(rect))
@@ -3322,7 +3400,8 @@ void QAbstractItemView::update(const QModelIndex &index)
\note: Qt::ToolTipRole is not honored by dataChanged() in the views provided by Qt.
*/
-void QAbstractItemView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
+void QAbstractItemView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &roles)
{
Q_UNUSED(roles);
// Single item changed
@@ -3331,7 +3410,7 @@ void QAbstractItemView::dataChanged(const QModelIndex &topLeft, const QModelInde
const QEditorInfo &editorInfo = d->editorForIndex(topLeft);
//we don't update the edit data if it is static
if (!editorInfo.isStatic && editorInfo.widget) {
- QAbstractItemDelegate *delegate = d->delegateForIndex(topLeft);
+ QAbstractItemDelegate *delegate = itemDelegateForIndex(topLeft);
if (delegate) {
delegate->setEditorData(editorInfo.widget.data(), topLeft);
}
@@ -3342,11 +3421,22 @@ void QAbstractItemView::dataChanged(const QModelIndex &topLeft, const QModelInde
}
} else {
d->updateEditorData(topLeft, bottomRight);
- if (isVisible() && !d->delayedPendingLayout)
- d->viewport->update();
+ if (isVisible() && !d->delayedPendingLayout) {
+ if (!topLeft.isValid() ||
+ topLeft.parent() != bottomRight.parent() ||
+ topLeft.row() > bottomRight.row() ||
+ topLeft.column() > bottomRight.column()) {
+ // invalid parameter - call update() to redraw all
+ d->viewport->update();
+ } else {
+ const QRect updateRect = d->intersectedRect(d->viewport->rect(), topLeft, bottomRight);
+ if (!updateRect.isEmpty())
+ d->viewport->update(updateRect);
+ }
+ }
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
QAccessibleTableModelChangeEvent accessibleEvent(this, QAccessibleTableModelChangeEvent::DataChanged);
accessibleEvent.setFirstRow(topLeft.row());
@@ -3404,24 +3494,59 @@ void QAbstractItemView::rowsAboutToBeRemoved(const QModelIndex &parent, int star
} else {
int row = end + 1;
QModelIndex next;
- do { // find the next visible and enabled item
+ const int rowCount = d->model->rowCount(parent);
+ bool found = false;
+ // find the next visible and enabled item
+ while (row < rowCount && !found) {
next = d->model->index(row++, current.column(), current.parent());
- } while (next.isValid() && (isIndexHidden(next) || !d->isIndexEnabled(next)));
- if (row > d->model->rowCount(parent)) {
+#ifdef QT_DEBUG
+ if (!next.isValid()) {
+ qWarning("Model unexpectedly returned an invalid index");
+ break;
+ }
+#endif
+ if (!isIndexHidden(next) && d->isIndexEnabled(next)) {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found) {
row = start - 1;
- do { // find the previous visible and enabled item
+ // find the previous visible and enabled item
+ while (row >= 0) {
next = d->model->index(row--, current.column(), current.parent());
- } while (next.isValid() && (isIndexHidden(next) || !d->isIndexEnabled(next)));
+#ifdef QT_DEBUG
+ if (!next.isValid()) {
+ qWarning("Model unexpectedly returned an invalid index");
+ break;
+ }
+#endif
+ if (!isIndexHidden(next) && d->isIndexEnabled(next))
+ break;
+ }
}
+
setCurrentIndex(next);
}
}
// 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);
@@ -3440,17 +3565,17 @@ 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)
- Q_UNUSED(end)
+ Q_UNUSED(index);
+ Q_UNUSED(start);
+ Q_UNUSED(end);
Q_Q(QAbstractItemView);
if (q->isVisible())
q->updateEditorGeometries();
q->setState(QAbstractItemView::NoState);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::RowsRemoved);
accessibleEvent.setFirstRow(start);
@@ -3468,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);
@@ -3490,9 +3615,19 @@ void QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &par
} else {
int column = end;
QModelIndex next;
- do { // find the next visible and enabled item
+ const int columnCount = model->columnCount(current.parent());
+ // find the next visible and enabled item
+ while (column < columnCount) {
next = model->index(current.row(), column++, current.parent());
- } while (next.isValid() && (q->isIndexHidden(next) || !isIndexEnabled(next)));
+#ifdef QT_DEBUG
+ if (!next.isValid()) {
+ qWarning("Model unexpectedly returned an invalid index");
+ break;
+ }
+#endif
+ if (!q->isIndexHidden(next) && isIndexEnabled(next))
+ break;
+ }
q->setCurrentIndex(next);
}
}
@@ -3521,17 +3656,17 @@ 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)
- Q_UNUSED(end)
+ Q_UNUSED(index);
+ Q_UNUSED(start);
+ Q_UNUSED(end);
Q_Q(QAbstractItemView);
if (q->isVisible())
q->updateEditorGeometries();
q->setState(QAbstractItemView::NoState);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::ColumnsRemoved);
accessibleEvent.setFirstColumn(start);
@@ -3548,13 +3683,13 @@ 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)
- Q_UNUSED(end)
+ Q_UNUSED(index);
+ Q_UNUSED(start);
+ Q_UNUSED(end);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
Q_Q(QAbstractItemView);
if (QAccessible::isActive()) {
QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::RowsInserted);
@@ -3571,16 +3706,16 @@ 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)
- Q_UNUSED(end)
+ Q_UNUSED(index);
+ Q_UNUSED(start);
+ Q_UNUSED(end);
Q_Q(QAbstractItemView);
if (q->isVisible())
q->updateEditorGeometries();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::ColumnsInserted);
accessibleEvent.setFirstColumn(start);
@@ -3594,7 +3729,7 @@ void QAbstractItemViewPrivate::_q_columnsInserted(const QModelIndex &index, int
/*!
\internal
*/
-void QAbstractItemViewPrivate::_q_modelDestroyed()
+void QAbstractItemViewPrivate::modelDestroyed()
{
model = QAbstractItemModelPrivate::staticEmptyModel();
doDelayedReset();
@@ -3605,10 +3740,10 @@ void QAbstractItemViewPrivate::_q_modelDestroyed()
This slot is called when the layout is changed.
*/
-void QAbstractItemViewPrivate::_q_layoutChanged()
+void QAbstractItemViewPrivate::layoutChanged()
{
doDelayedItemsLayout();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
Q_Q(QAbstractItemView);
if (QAccessible::isActive()) {
QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::ModelReset);
@@ -3617,14 +3752,27 @@ 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)
+{
+ layoutChanged();
+}
+
+void QAbstractItemViewPrivate::columnsMoved(const QModelIndex &, int, int, const QModelIndex &, int)
{
- _q_layoutChanged();
+ layoutChanged();
}
-void QAbstractItemViewPrivate::_q_columnsMoved(const QModelIndex &, int, int, const QModelIndex &, int)
+QRect QAbstractItemViewPrivate::intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const
{
- _q_layoutChanged();
+ Q_Q(const QAbstractItemView);
+
+ const auto parentIdx = topLeft.parent();
+ QRect updateRect;
+ for (int r = topLeft.row(); r <= bottomRight.row(); ++r) {
+ for (int c = topLeft.column(); c <= bottomRight.column(); ++c)
+ updateRect |= q->visualRect(model->index(r, c, parentIdx));
+ }
+ return rect.intersected(updateRect);
}
/*!
@@ -3694,7 +3842,7 @@ void QAbstractItemView::startDrag(Qt::DropActions supportedActions)
{
Q_D(QAbstractItemView);
QModelIndexList indexes = d->selectedDraggableIndexes();
- if (indexes.count() > 0) {
+ if (indexes.size() > 0) {
QMimeData *data = d->model->mimeData(indexes);
if (!data)
return;
@@ -3706,12 +3854,18 @@ void QAbstractItemView::startDrag(Qt::DropActions supportedActions)
drag->setMimeData(data);
drag->setHotSpot(d->pressedPosition - rect.topLeft());
Qt::DropAction defaultDropAction = Qt::IgnoreAction;
+ if (dragDropMode() == InternalMove)
+ supportedActions &= ~Qt::CopyAction;
if (d->defaultDropAction != Qt::IgnoreAction && (supportedActions & d->defaultDropAction))
defaultDropAction = d->defaultDropAction;
else if (supportedActions & Qt::CopyAction && dragDropMode() != QAbstractItemView::InternalMove)
defaultDropAction = Qt::CopyAction;
- if (drag->exec(supportedActions, defaultDropAction) == Qt::MoveAction)
- d->clearOrRemove();
+ d->dropEventMoved = false;
+ if (drag->exec(supportedActions, defaultDropAction) == Qt::MoveAction && !d->dropEventMoved) {
+ if (dragDropMode() != InternalMove || drag->target() == viewport())
+ d->clearOrRemove();
+ }
+ d->dropEventMoved = false;
// Reset the drop indicator
d->dropIndicatorRect = QRect();
d->dropIndicatorPosition = OnItem;
@@ -3720,47 +3874,45 @@ void QAbstractItemView::startDrag(Qt::DropActions supportedActions)
#endif // QT_CONFIG(draganddrop)
/*!
- Returns a QStyleOptionViewItem structure populated with the view's
- palette, font, state, alignments etc.
+ \since 6.0
+
+ Initialize the \a option structure with the view's palette, font, state,
+ alignments etc.
+
+ \note Implementations of this methods should check the \l{QStyleOption::}{version}
+ of the structure received, populate all members the implementation is familiar with,
+ and set the version member to the one supported by the implementation before returning.
*/
-QStyleOptionViewItem QAbstractItemView::viewOptions() const
+void QAbstractItemView::initViewItemOption(QStyleOptionViewItem *option) const
{
Q_D(const QAbstractItemView);
- QStyleOptionViewItem option;
- option.init(this);
- option.state &= ~QStyle::State_MouseOver;
- option.font = font();
+ option->initFrom(this);
+ option->state &= ~QStyle::State_MouseOver;
+ option->font = font();
// On mac the focus appearance follows window activation
// not widget activation
if (!hasFocus())
- option.state &= ~QStyle::State_Active;
+ option->state &= ~QStyle::State_Active;
- option.state &= ~QStyle::State_HasFocus;
+ option->state &= ~QStyle::State_HasFocus;
if (d->iconSize.isValid()) {
- option.decorationSize = d->iconSize;
+ option->decorationSize = d->iconSize;
} else {
int pm = style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, this);
- option.decorationSize = QSize(pm, pm);
+ option->decorationSize = QSize(pm, pm);
}
- option.decorationPosition = QStyleOptionViewItem::Left;
- option.decorationAlignment = Qt::AlignCenter;
- option.displayAlignment = Qt::AlignLeft|Qt::AlignVCenter;
- option.textElideMode = d->textElideMode;
- option.rect = QRect();
- option.showDecorationSelected = style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, nullptr, this);
+ option->decorationPosition = QStyleOptionViewItem::Left;
+ option->decorationAlignment = Qt::AlignCenter;
+ option->displayAlignment = Qt::AlignLeft|Qt::AlignVCenter;
+ option->textElideMode = d->textElideMode;
+ option->rect = QRect();
+ option->showDecorationSelected = style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, nullptr, this);
if (d->wrapItemText)
- option.features = QStyleOptionViewItem::WrapText;
- option.locale = locale();
- option.locale.setNumberOptions(QLocale::OmitGroupSeparator);
- option.widget = this;
- return option;
-}
-
-QStyleOptionViewItem QAbstractItemViewPrivate::viewOptionsV1() const
-{
- Q_Q(const QAbstractItemView);
- return q->viewOptions();
+ option->features = QStyleOptionViewItem::WrapText;
+ option->locale = locale();
+ option->locale.setNumberOptions(QLocale::OmitGroupSeparator);
+ option->widget = this;
}
/*!
@@ -3901,17 +4053,17 @@ void QAbstractItemView::doAutoScroll()
}
}
- int verticalStep = verticalScroll->pageStep();
- int horizontalStep = horizontalScroll->pageStep();
+ const int verticalStep = verticalScroll->pageStep();
+ const int horizontalStep = horizontalScroll->pageStep();
if (d->autoScrollCount < qMax(verticalStep, horizontalStep))
++d->autoScrollCount;
- int margin = d->autoScrollMargin;
- int verticalValue = verticalScroll->value();
- int horizontalValue = horizontalScroll->value();
+ const int margin = d->autoScrollMargin;
+ const int verticalValue = verticalScroll->value();
+ const int horizontalValue = horizontalScroll->value();
- QPoint pos = d->viewport->mapFromGlobal(QCursor::pos());
- QRect area = QWidgetPrivate::get(d->viewport)->clipRect();
+ const QPoint pos = d->draggedPosition - d->offset();
+ const QRect area = QWidgetPrivate::get(d->viewport)->clipRect();
// do the scrolling if we are in the scroll margins
if (pos.y() - area.top() < margin)
@@ -3923,8 +4075,8 @@ void QAbstractItemView::doAutoScroll()
else if (area.right() - pos.x() < margin)
horizontalScroll->setValue(horizontalValue + d->autoScrollCount);
// if nothing changed, stop scrolling
- bool verticalUnchanged = (verticalValue == verticalScroll->value());
- bool horizontalUnchanged = (horizontalValue == horizontalScroll->value());
+ const bool verticalUnchanged = (verticalValue == verticalScroll->value());
+ const bool horizontalUnchanged = (horizontalValue == horizontalScroll->value());
if (verticalUnchanged && horizontalUnchanged) {
stopAutoScroll();
} else {
@@ -3932,14 +4084,39 @@ void QAbstractItemView::doAutoScroll()
d->dropIndicatorRect = QRect();
d->dropIndicatorPosition = QAbstractItemView::OnViewport;
#endif
+ switch (state()) {
+ case QAbstractItemView::DragSelectingState: {
+ // mouseMoveEvent updates the drag-selection rectangle, so fake an event. This also
+ // updates draggedPosition taking the now scrolled viewport into account.
+ const QPoint globalPos = d->viewport->mapToGlobal(pos);
+ const QPoint windowPos = window()->mapFromGlobal(globalPos);
+ QMouseEvent mm(QEvent::MouseMove, pos, windowPos, globalPos,
+ Qt::NoButton, Qt::LeftButton, d->pressedModifiers,
+ Qt::MouseEventSynthesizedByQt);
+ QApplication::sendEvent(viewport(), &mm);
+ break;
+ }
+ case QAbstractItemView::DraggingState: {
+ // we can't simulate mouse (it would throw off the drag'n'drop state logic) or drag
+ // (we don't have the mime data or the actions) move events during drag'n'drop, so
+ // update our dragged position manually after the scroll. "pos" is the old
+ // draggedPosition - d->offset(), and d->offset() is now updated after scrolling, so
+ // pos + d->offset() gives us the new position.
+ d->draggedPosition = pos + d->offset();
+ break;
+ }
+ default:
+ break;
+ }
d->viewport->update();
}
}
/*!
- Returns the SelectionFlags to be used when updating a selection with
- to include the \a index specified. The \a event is a user input event,
- such as a mouse or keyboard event.
+ Returns the SelectionFlags to be used when updating a selection model
+ for the specified \a index. The result depends on the current
+ selectionMode(), and on the user input event \a event, which can be
+ \nullptr.
Reimplement this function to define your own selection behavior.
@@ -3949,31 +4126,35 @@ QItemSelectionModel::SelectionFlags QAbstractItemView::selectionCommand(const QM
const QEvent *event) const
{
Q_D(const QAbstractItemView);
- Qt::KeyboardModifiers keyModifiers = Qt::NoModifier;
- if (event) {
- switch (event->type()) {
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseMove:
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- keyModifiers = (static_cast<const QInputEvent*>(event))->modifiers();
- break;
- default:
- keyModifiers = QGuiApplication::keyboardModifiers();
- }
- }
+ Qt::KeyboardModifiers keyModifiers = event && event->isInputEvent()
+ ? static_cast<const QInputEvent*>(event)->modifiers()
+ : Qt::NoModifier;
switch (d->selectionMode) {
case NoSelection: // Never update selection model
return QItemSelectionModel::NoUpdate;
case SingleSelection: // ClearAndSelect on valid index otherwise NoUpdate
- if (event && event->type() == QEvent::MouseButtonRelease)
- return QItemSelectionModel::NoUpdate;
- if ((keyModifiers & Qt::ControlModifier) && d->selectionModel->isSelected(index) && event->type() != QEvent::MouseMove)
- return QItemSelectionModel::Deselect | d->selectionBehaviorFlags();
- else
- return QItemSelectionModel::ClearAndSelect | d->selectionBehaviorFlags();
+ if (event) {
+ switch (event->type()) {
+ case QEvent::MouseButtonPress:
+ // press with any modifiers on a selected item does nothing
+ if (d->pressedAlreadySelected)
+ return QItemSelectionModel::NoUpdate;
+ break;
+ 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();
+ break;
+ default:
+ break;
+ }
+ }
+ return QItemSelectionModel::ClearAndSelect | d->selectionBehaviorFlags();
case MultiSelection:
return d->multiSelectionCommand(index, event);
case ExtendedSelection:
@@ -3987,7 +4168,7 @@ QItemSelectionModel::SelectionFlags QAbstractItemView::selectionCommand(const QM
QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::multiSelectionCommand(
const QModelIndex &index, const QEvent *event) const
{
- Q_UNUSED(index)
+ Q_UNUSED(index);
if (event) {
switch (event->type()) {
@@ -3997,16 +4178,31 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::multiSelectionComm
return QItemSelectionModel::Toggle|selectionBehaviorFlags();
break;
case QEvent::MouseButtonPress:
- if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton)
- return QItemSelectionModel::Toggle|selectionBehaviorFlags(); // toggle
+ if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton) {
+ // since the press might start a drag, deselect only on release
+ 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 (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton) {
+ if (pressedAlreadySelected
+#if QT_CONFIG(draganddrop)
+ && dragEnabled && isIndexDragEnabled(index)
+#endif
+ && index == pressedIndex)
+ return QItemSelectionModel::Toggle|selectionBehaviorFlags();
return QItemSelectionModel::NoUpdate|selectionBehaviorFlags(); // finalize
+ }
break;
case QEvent::MouseMove:
if (static_cast<const QMouseEvent*>(event)->buttons() & Qt::LeftButton)
return QItemSelectionModel::ToggleCurrent|selectionBehaviorFlags(); // toggle drag select
+ break;
default:
break;
}
@@ -4019,18 +4215,18 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::multiSelectionComm
QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionCommand(
const QModelIndex &index, const QEvent *event) const
{
- Qt::KeyboardModifiers modifiers = QGuiApplication::keyboardModifiers();
+ Qt::KeyboardModifiers modifiers = event && event->isInputEvent()
+ ? static_cast<const QInputEvent*>(event)->modifiers()
+ : QGuiApplication::keyboardModifiers();
if (event) {
switch (event->type()) {
case QEvent::MouseMove: {
// Toggle on MouseMove
- modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
if (modifiers & Qt::ControlModifier)
return QItemSelectionModel::ToggleCurrent|selectionBehaviorFlags();
break;
}
case QEvent::MouseButtonPress: {
- modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
const Qt::MouseButton button = static_cast<const QMouseEvent*>(event)->button();
const bool rightButtonPressed = button & Qt::RightButton;
const bool shiftKeyPressed = modifiers & Qt::ShiftModifier;
@@ -4044,11 +4240,18 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionC
return QItemSelectionModel::Clear;
if (!index.isValid())
return QItemSelectionModel::NoUpdate;
+ // since the press might start a drag, deselect only on release
+ if (controlKeyPressed && !rightButtonPressed && pressedAlreadySelected
+#if QT_CONFIG(draganddrop)
+ && dragEnabled && isIndexDragEnabled(index)
+#endif
+ ) {
+ return QItemSelectionModel::NoUpdate;
+ }
break;
}
case QEvent::MouseButtonRelease: {
// ClearAndSelect on MouseButtonRelease if MouseButtonPress on selected item or empty area
- modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
const Qt::MouseButton button = static_cast<const QMouseEvent*>(event)->button();
const bool rightButtonPressed = button & Qt::RightButton;
const bool shiftKeyPressed = modifiers & Qt::ShiftModifier;
@@ -4057,11 +4260,17 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionC
|| !index.isValid()) && state != QAbstractItemView::DragSelectingState
&& !shiftKeyPressed && !controlKeyPressed && (!rightButtonPressed || !index.isValid()))
return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
+ if (index == pressedIndex && controlKeyPressed && !rightButtonPressed
+#if QT_CONFIG(draganddrop)
+ && dragEnabled && isIndexDragEnabled(index)
+#endif
+ ) {
+ break;
+ }
return QItemSelectionModel::NoUpdate;
}
case QEvent::KeyPress: {
// NoUpdate on Key movement and Ctrl
- modifiers = static_cast<const QKeyEvent*>(event)->modifiers();
switch (static_cast<const QKeyEvent*>(event)->key()) {
case Qt::Key_Backtab:
modifiers = modifiers & ~Qt::ShiftModifier; // special case for backtab
@@ -4092,6 +4301,7 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionC
default:
break;
}
+ break;
}
default:
break;
@@ -4226,39 +4436,48 @@ void QAbstractItemViewPrivate::updateGeometry()
q->updateGeometry();
}
+/*
+ Handles selection of content for some editors containing QLineEdit.
+
+ ### Qt 7 This should be done by a virtual method in QAbstractItemDelegate.
+*/
+void QAbstractItemViewPrivate::selectAllInEditor(QWidget *editor)
+{
+ while (QWidget *fp = editor->focusProxy())
+ editor = fp;
+
+#if QT_CONFIG(lineedit)
+ if (QLineEdit *le = qobject_cast<QLineEdit*>(editor))
+ le->selectAll();
+#endif
+#if QT_CONFIG(spinbox)
+ if (QSpinBox *sb = qobject_cast<QSpinBox*>(editor))
+ sb->selectAll();
+ else if (QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox*>(editor))
+ dsb->selectAll();
+#endif
+}
+
QWidget *QAbstractItemViewPrivate::editor(const QModelIndex &index,
const QStyleOptionViewItem &options)
{
Q_Q(QAbstractItemView);
QWidget *w = editorForIndex(index).widget.data();
if (!w) {
- QAbstractItemDelegate *delegate = delegateForIndex(index);
+ QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
if (!delegate)
return nullptr;
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);
if (w->parent() == viewport)
QWidget::setTabOrder(q, w);
- // Special cases for some editors containing QLineEdit
- QWidget *focusWidget = w;
- while (QWidget *fp = focusWidget->focusProxy())
- focusWidget = fp;
-#if QT_CONFIG(lineedit)
- if (QLineEdit *le = qobject_cast<QLineEdit*>(focusWidget))
- le->selectAll();
-#endif
-#if QT_CONFIG(spinbox)
- if (QSpinBox *sb = qobject_cast<QSpinBox*>(focusWidget))
- sb->selectAll();
- else if (QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox*>(focusWidget))
- dsb->selectAll();
-#endif
+ selectAllInEditor(w);
}
}
@@ -4267,6 +4486,7 @@ QWidget *QAbstractItemViewPrivate::editor(const QModelIndex &index,
void QAbstractItemViewPrivate::updateEditorData(const QModelIndex &tl, const QModelIndex &br)
{
+ Q_Q(QAbstractItemView);
// we are counting on having relatively few editors
const bool checkIndexes = tl.isValid() && br.isValid();
const QModelIndex parent = tl.parent();
@@ -4285,7 +4505,7 @@ void QAbstractItemViewPrivate::updateEditorData(const QModelIndex &tl, const QMo
|| index.parent() != parent)))
continue;
- QAbstractItemDelegate *delegate = delegateForIndex(index);
+ QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
if (delegate) {
delegate->setEditorData(editor, index);
}
@@ -4297,7 +4517,7 @@ void QAbstractItemViewPrivate::updateEditorData(const QModelIndex &tl, const QMo
In DND if something has been moved then this is called.
Typically this means you should "remove" the selected item or row,
- but the behavior is view dependant (table just clears the selected indexes for example).
+ but the behavior is view-dependent (table just clears the selected indexes for example).
Either remove the selected rows or clear them
*/
@@ -4387,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());
@@ -4404,10 +4627,11 @@ bool QAbstractItemViewPrivate::sendDelegateEvent(const QModelIndex &index, QEven
{
Q_Q(const QAbstractItemView);
QModelIndex buddy = model->buddy(index);
- QStyleOptionViewItem options = viewOptionsV1();
+ QStyleOptionViewItem options;
+ q->initViewItemOption(&options);
options.rect = q->visualRect(buddy);
options.state |= (buddy == q->currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
- QAbstractItemDelegate *delegate = delegateForIndex(index);
+ QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
return (event && delegate && delegate->editorEvent(event, model, options, buddy));
}
@@ -4416,7 +4640,8 @@ bool QAbstractItemViewPrivate::openEditor(const QModelIndex &index, QEvent *even
Q_Q(QAbstractItemView);
QModelIndex buddy = model->buddy(index);
- QStyleOptionViewItem options = viewOptionsV1();
+ QStyleOptionViewItem options;
+ q->initViewItemOption(&options);
options.rect = q->visualRect(buddy);
options.state |= (buddy == q->currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
@@ -4426,7 +4651,10 @@ bool QAbstractItemViewPrivate::openEditor(const QModelIndex &index, QEvent *even
q->setState(QAbstractItemView::EditingState);
w->show();
- w->setFocus();
+ if (!waitForIMCommit)
+ w->setFocus();
+ else
+ q->updateMicroFocus();
if (event)
QCoreApplication::sendEvent(w->focusProxy() ? w->focusProxy() : w, event);
@@ -4462,6 +4690,7 @@ QItemViewPaintPairs QAbstractItemViewPrivate::draggablePaintPairs(const QModelIn
QPixmap QAbstractItemViewPrivate::renderToPixmap(const QModelIndexList &indexes, QRect *r) const
{
+ Q_Q(const QAbstractItemView);
Q_ASSERT(r);
QItemViewPaintPairs paintPairs = draggablePaintPairs(indexes, r);
if (paintPairs.isEmpty())
@@ -4475,13 +4704,14 @@ QPixmap QAbstractItemViewPrivate::renderToPixmap(const QModelIndexList &indexes,
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
- QStyleOptionViewItem option = viewOptionsV1();
+ QStyleOptionViewItem option;
+ q->initViewItemOption(&option);
option.state |= QStyle::State_Selected;
- for (int j = 0; j < paintPairs.count(); ++j) {
+ for (int j = 0; j < paintPairs.size(); ++j) {
option.rect = paintPairs.at(j).rect.translated(-r->topLeft());
const QModelIndex &current = paintPairs.at(j).index;
adjustViewOptionsForIndex(&option, current);
- delegateForIndex(current)->paint(&painter, option, current);
+ q->itemDelegateForIndex(current)->paint(&painter, option, current);
}
return pixmap;
}
@@ -4490,6 +4720,8 @@ void QAbstractItemViewPrivate::selectAll(QItemSelectionModel::SelectionFlags com
{
if (!selectionModel)
return;
+ if (!model->hasChildren(root))
+ return;
QItemSelection selection;
QModelIndex tl = model->index(0, 0, root);
@@ -4500,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);
@@ -4507,12 +4740,25 @@ QModelIndexList QAbstractItemViewPrivate::selectedDraggableIndexes() const
auto isNotDragEnabled = [this](const QModelIndex &index) {
return !isIndexDragEnabled(index);
};
- indexes.erase(std::remove_if(indexes.begin(), indexes.end(),
- isNotDragEnabled),
- indexes.end());
+ indexes.removeIf(isNotDragEnabled);
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 be8fa07c94..837419100a 100644
--- a/src/widgets/itemviews/qabstractitemview.h
+++ b/src/widgets/itemviews/qabstractitemview.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTITEMVIEW_H
#define QABSTRACTITEMVIEW_H
@@ -74,11 +38,14 @@ class Q_WIDGETS_EXPORT QAbstractItemView : public QAbstractScrollArea
#endif
Q_PROPERTY(bool alternatingRowColors READ alternatingRowColors WRITE setAlternatingRowColors)
Q_PROPERTY(SelectionMode selectionMode READ selectionMode WRITE setSelectionMode)
- Q_PROPERTY(SelectionBehavior selectionBehavior READ selectionBehavior WRITE setSelectionBehavior)
+ Q_PROPERTY(SelectionBehavior selectionBehavior READ selectionBehavior
+ WRITE setSelectionBehavior)
Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize NOTIFY iconSizeChanged)
Q_PROPERTY(Qt::TextElideMode textElideMode READ textElideMode WRITE setTextElideMode)
- Q_PROPERTY(ScrollMode verticalScrollMode READ verticalScrollMode WRITE setVerticalScrollMode RESET resetVerticalScrollMode)
- Q_PROPERTY(ScrollMode horizontalScrollMode READ horizontalScrollMode WRITE setHorizontalScrollMode RESET resetHorizontalScrollMode)
+ Q_PROPERTY(ScrollMode verticalScrollMode READ verticalScrollMode WRITE setVerticalScrollMode
+ RESET resetVerticalScrollMode)
+ Q_PROPERTY(ScrollMode horizontalScrollMode READ horizontalScrollMode
+ WRITE setHorizontalScrollMode RESET resetHorizontalScrollMode)
public:
enum SelectionMode {
@@ -223,7 +190,12 @@ public:
void setItemDelegateForColumn(int column, QAbstractItemDelegate *delegate);
QAbstractItemDelegate *itemDelegateForColumn(int column) const;
- QAbstractItemDelegate *itemDelegate(const QModelIndex &index) const;
+#if QT_DEPRECATED_SINCE(6, 0)
+ QT_DEPRECATED_VERSION_X_6_0("Use itemDelegateForIndex instead")
+ QAbstractItemDelegate *itemDelegate(const QModelIndex &index) const
+ { return itemDelegateForIndex(index); }
+#endif
+ virtual QAbstractItemDelegate *itemDelegateForIndex(const QModelIndex &index) const;
virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const override;
@@ -242,7 +214,8 @@ public Q_SLOTS:
void update(const QModelIndex &index);
protected Q_SLOTS:
- virtual void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>());
+ virtual void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &roles = QList<int>());
virtual void rowsInserted(const QModelIndex &parent, int start, int end);
virtual void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
virtual void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
@@ -272,13 +245,6 @@ Q_SIGNALS:
protected:
QAbstractItemView(QAbstractItemViewPrivate &, QWidget *parent = nullptr);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED void setHorizontalStepsPerItem(int steps);
- QT_DEPRECATED int horizontalStepsPerItem() const;
- QT_DEPRECATED void setVerticalStepsPerItem(int steps);
- QT_DEPRECATED int verticalStepsPerItem() const;
-#endif
-
enum CursorAction { MoveUp, MoveDown, MoveLeft, MoveRight,
MoveHome, MoveEnd, MovePageUp, MovePageDown,
MoveNext, MovePrevious };
@@ -303,7 +269,7 @@ protected:
virtual void startDrag(Qt::DropActions supportedActions);
#endif
- virtual QStyleOptionViewItem viewOptions() const;
+ virtual void initViewItemOption(QStyleOptionViewItem *option) const;
enum State {
NoState,
@@ -360,19 +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
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 fe1c00248f..433429f48b 100644
--- a/src/widgets/itemviews/qabstractitemview_p.h
+++ b/src/widgets/itemviews/qabstractitemview_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTITEMVIEW_P_H
#define QABSTRACTITEMVIEW_P_H
@@ -52,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);
@@ -87,7 +56,7 @@ struct QItemViewPaintPair {
template <>
class QTypeInfo<QItemViewPaintPair> : public QTypeInfoMerger<QItemViewPaintPair, QRect, QModelIndex> {};
-typedef QVector<QItemViewPaintPair> QItemViewPaintPairs;
+typedef QList<QItemViewPaintPair> QItemViewPaintPairs;
class Q_AUTOTEST_EXPORT QAbstractItemViewPrivate : public QAbstractScrollAreaPrivate
{
@@ -99,18 +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);
-
- void _q_headerDataChanged() { doDelayedItemsLayout(); }
- void _q_scrollerStateChanged();
+ 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 headerDataChanged() { doDelayedItemsLayout(); }
+ void scrollerStateChanged();
+ void delegateSizeHintChanged(const QModelIndex &index);
void fetchMore();
@@ -139,6 +110,7 @@ public:
bool sendDelegateEvent(const QModelIndex &index, QEvent *event) const;
bool openEditor(const QModelIndex &index, QEvent *event);
void updateEditorData(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+ void selectAllInEditor(QWidget *w);
QItemSelectionModel::SelectionFlags multiSelectionCommand(const QModelIndex &index,
const QEvent *event) const;
@@ -197,7 +169,7 @@ public:
#endif
) {
QStyleOption opt;
- opt.init(q_func());
+ opt.initFrom(q_func());
opt.rect = dropIndicatorRect;
q_func()->style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemDrop, &opt, painter, q_func());
}
@@ -210,11 +182,12 @@ public:
inline void releaseEditor(QWidget *editor, const QModelIndex &index = QModelIndex()) const {
if (editor) {
- QObject::disconnect(editor, SIGNAL(destroyed(QObject*)),
- q_func(), SLOT(editorDestroyed(QObject*)));
+ Q_Q(const QAbstractItemView);
+ QObject::disconnect(editor, &QWidget::destroyed,
+ q, &QAbstractItemView::editorDestroyed);
editor->removeEventFilter(itemDelegate);
editor->hide();
- QAbstractItemDelegate *delegate = delegateForIndex(index);
+ QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
if (delegate)
delegate->destroyEditor(editor, index);
@@ -275,20 +248,6 @@ public:
return state == QAbstractItemView::AnimatingState;
}
- inline QAbstractItemDelegate *delegateForIndex(const QModelIndex &index) const {
- QMap<int, QPointer<QAbstractItemDelegate> >::ConstIterator it;
-
- it = rowDelegates.find(index.row());
- if (it != rowDelegates.end())
- return it.value();
-
- it = columnDelegates.find(index.column());
- if (it != columnDelegates.end())
- return it.value();
-
- return itemDelegate;
- }
-
inline bool isIndexValid(const QModelIndex &index) const {
return (index.row() >= 0) && (index.column() >= 0) && (index.model() == model);
}
@@ -298,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
@@ -350,15 +311,16 @@ public:
return static_cast<QAbstractItemModelPrivate *>(model->d_ptr.data())->persistent.indexes.contains(index);
}
+#if QT_CONFIG(draganddrop)
QModelIndexList selectedDraggableIndexes() const;
-
- QStyleOptionViewItem viewOptionsV1() 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());
}
@@ -378,13 +340,19 @@ public:
QIndexEditorHash indexEditorHash;
QSet<QWidget*> persistent;
QWidget *currentlyCommittingEditor;
+ QBasicTimer pressClosedEditorWatcher;
+ QPersistentModelIndex lastEditedIndex;
+ bool pressClosedEditor;
+ bool waitForIMCommit;
QPersistentModelIndex enteredIndex;
QPersistentModelIndex pressedIndex;
QPersistentModelIndex currentSelectionStartIndex;
Qt::KeyboardModifiers pressedModifiers;
QPoint pressedPosition;
+ QPoint draggedPosition;
bool pressedAlreadySelected;
+ bool releaseFromDoubleClick;
//forces the next mouseMoveEvent to send the viewportEntered signal
//if the mouse is over the viewport and not over an item
@@ -406,6 +374,7 @@ public:
bool dragEnabled;
QAbstractItemView::DragDropMode dragDropMode;
bool overwrite;
+ bool dropEventMoved;
QAbstractItemView::DropIndicatorPosition dropIndicatorPosition;
Qt::DropAction defaultDropAction;
#endif
@@ -452,17 +421,42 @@ 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;
+
+ it = rowDelegates.find(index.row());
+ if (it != rowDelegates.end())
+ return it.value();
+
+ it = columnDelegates.find(index.column());
+ if (it != columnDelegates.end())
+ return it.value();
+
+ return itemDelegate;
+ }
+
mutable QBasicTimer delayedLayout;
mutable QBasicTimer fetchMoreTimer;
};
QT_BEGIN_INCLUDE_NAMESPACE
-#include <qvector.h>
+#include <qlist.h>
QT_END_INCLUDE_NAMESPACE
-template <typename T>
-inline int qBinarySearch(const QVector<T> &vec, const T &item, int start, int end)
+template<typename T>
+inline int qBinarySearch(const QList<T> &vec, const T &item, int start, int end)
{
int i = (start + end + 1) >> 1;
while (end - start > 0) {
diff --git a/src/widgets/itemviews/qbsptree.cpp b/src/widgets/itemviews/qbsptree.cpp
index 0e896317d0..d75144b1a8 100644
--- a/src/widgets/itemviews/qbsptree.cpp
+++ b/src/widgets/itemviews/qbsptree.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qbsptree_p.h"
@@ -56,8 +20,8 @@ void QBspTree::create(int n, int d)
}
depth = qMax(depth, uint(1));
- nodes.resize((1 << depth) - 1); // resize to number of nodes
- leaves.resize(1 << depth); // resize to number of leaves
+ nodes.resize((1ll << depth) - 1); // resize to number of nodes
+ leaves.resize(1ll << depth); // resize to number of leaves
}
void QBspTree::destroy()
@@ -76,9 +40,9 @@ void QBspTree::climbTree(const QRect &rect, callback *function, QBspTreeData dat
void QBspTree::climbTree(const QRect &area, callback *function, QBspTreeData data, int index)
{
- if (index >= nodes.count()) { // the index points to a leaf
+ if (index >= nodes.size()) { // the index points to a leaf
Q_ASSERT(!nodes.isEmpty());
- function(leaf(index - nodes.count()), area, visited, data);
+ function(leaf(index - nodes.size()), area, visited, data);
return;
}
@@ -128,12 +92,12 @@ void QBspTree::init(const QRect &area, int depth, NodeType type, int index)
}
}
-void QBspTree::insert(QVector<int> &leaf, const QRect &, uint, QBspTreeData data)
+void QBspTree::insert(QList<int> &leaf, const QRect &, uint, QBspTreeData data)
{
leaf.append(data.i);
}
-void QBspTree::remove(QVector<int> &leaf, const QRect &, uint, QBspTreeData data)
+void QBspTree::remove(QList<int> &leaf, const QRect &, uint, QBspTreeData data)
{
int i = leaf.indexOf(data.i);
if (i != -1)
diff --git a/src/widgets/itemviews/qbsptree_p.h b/src/widgets/itemviews/qbsptree_p.h
index 5fd7a5c45f..1f00616e87 100644
--- a/src/widgets/itemviews/qbsptree_p.h
+++ b/src/widgets/itemviews/qbsptree_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QBSPTREE_P_H
#define QBSPTREE_P_H
@@ -52,7 +16,7 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
-#include <qvector.h>
+#include <qlist.h>
#include <qrect.h>
QT_BEGIN_NAMESPACE
@@ -80,7 +44,7 @@ public:
};
};
typedef QBspTree::Data QBspTreeData;
- typedef void callback(QVector<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
+ typedef void callback(QList<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
QBspTree();
@@ -91,8 +55,8 @@ public:
void climbTree(const QRect &rect, callback *function, QBspTreeData data);
- inline int leafCount() const { return leaves.count(); }
- inline QVector<int> &leaf(int i) { return leaves[i]; }
+ inline int leafCount() const { return leaves.size(); }
+ inline QList<int> &leaf(int i) { return leaves[i]; }
inline void insertLeaf(const QRect &r, int i) { climbTree(r, &insert, i, 0); }
inline void removeLeaf(const QRect &r, int i) { climbTree(r, &remove, i, 0); }
@@ -103,14 +67,14 @@ protected:
inline int parentIndex(int i) const { return (i & 1) ? ((i - 1) / 2) : ((i - 2) / 2); }
inline int firstChildIndex(int i) const { return ((i * 2) + 1); }
- static void insert(QVector<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
- static void remove(QVector<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
+ static void insert(QList<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
+ static void remove(QList<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
private:
uint depth;
mutable uint visited;
- QVector<Node> nodes;
- mutable QVector< QVector<int> > leaves; // the leaves are just indices into the items
+ QList<Node> nodes;
+ mutable QList<QList<int>> leaves; // the leaves are just indices into the items
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qcolumnview.cpp b/src/widgets/itemviews/qcolumnview.cpp
index 4d0161025c..04bc8f5f88 100644
--- a/src/widgets/itemviews/qcolumnview.cpp
+++ b/src/widgets/itemviews/qcolumnview.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 <qglobal.h>
#include "qcolumnview.h"
@@ -104,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);
@@ -113,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();
}
/*!
@@ -134,12 +115,15 @@ void QColumnView::setResizeGripsVisible(bool visible)
if (d->showResizeGrips == visible)
return;
d->showResizeGrips = visible;
- for (int i = 0; i < d->columns.count(); ++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);
@@ -176,7 +160,7 @@ void QColumnView::setRootIndex(const QModelIndex &index)
return;
d->closeColumns();
- Q_ASSERT(d->columns.count() == 0);
+ Q_ASSERT(d->columns.size() == 0);
QAbstractItemView *view = d->createColumn(index, true);
if (view->selectionModel())
@@ -242,7 +226,7 @@ void QColumnView::scrollContentsBy(int dx, int dy)
return;
dx = isRightToLeft() ? -dx : dx;
- for (int i = 0; i < d->columns.count(); ++i)
+ for (int i = 0; i < d->columns.size(); ++i)
d->columns.at(i)->move(d->columns.at(i)->x() + dx, 0);
d->offset += dx;
QAbstractItemView::scrollContentsBy(dx, dy);
@@ -303,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;
}
@@ -456,7 +440,7 @@ int QColumnView::verticalOffset() const
*/
QRegion QColumnView::visualRegionForSelection(const QItemSelection &selection) const
{
- int ranges = selection.count();
+ int ranges = selection.size();
if (ranges == 0)
return QRect();
@@ -522,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);
@@ -566,7 +550,7 @@ void QColumnViewPrivate::closeColumns(const QModelIndex &parent, bool build)
bool clearAll = !parent.isValid();
bool passThroughRoot = false;
- QVector<QModelIndex> dirsToAppend;
+ QList<QModelIndex> dirsToAppend;
// Find the last column that matches the parent's tree
int currentColumn = -1;
@@ -614,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()) {
@@ -634,12 +620,22 @@ 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();
QAbstractItemView *columnClicked = nullptr;
- for (int column = 0; column < columns.count(); ++column) {
+ for (int column = 0; column < columns.size(); ++column) {
if (columns.at(column)->rootIndex() == parent) {
columnClicked = columns[column];
break;
@@ -667,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));
@@ -678,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);
@@ -697,19 +692,22 @@ 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.count() > columns.count()) {
- view->setGeometry(0, 0, columnSizes.at(columns.count()), viewport->height());
+ if (columnSizes.size() > columns.size()) {
+ view->setGeometry(0, 0, columnSizes.at(columns.size()), viewport->height());
} else {
int initialWidth = view->sizeHint().width();
if (q->isRightToLeft())
view->setGeometry(viewport->width() - initialWidth, 0, initialWidth, viewport->height());
else
view->setGeometry(0, 0, initialWidth, viewport->height());
- columnSizes.resize(qMax(columnSizes.count(), columns.count() + 1));
- columnSizes[columns.count()] = initialWidth;
+ columnSizes.resize(qMax(columnSizes.size(), columns.size() + 1));
+ columnSizes[columns.size()] = initialWidth;
}
if (!columns.isEmpty() && columns.constLast()->isHidden())
columns.constLast()->setVisible(true);
@@ -862,8 +860,8 @@ void QColumnView::setColumnWidths(const QList<int> &list)
{
Q_D(QColumnView);
int i = 0;
- const int listCount = list.count();
- const int count = qMin(listCount, d->columns.count());
+ const int listCount = list.size();
+ const int count = qMin(listCount, d->columns.size());
for (; i < count; ++i) {
d->columns.at(i)->resize(list.at(i), d->columns.at(i)->height());
d->columnSizes[i] = list.at(i);
@@ -883,7 +881,7 @@ QList<int> QColumnView::columnWidths() const
{
Q_D(const QColumnView);
QList<int> list;
- const int columnCount = d->columns.count();
+ const int columnCount = d->columns.size();
list.reserve(columnCount);
for (int i = 0; i < columnCount; ++i)
list.append(d->columnSizes.at(i));
@@ -951,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())
@@ -1020,9 +1018,9 @@ void QColumnView::selectAll()
QModelIndexList indexList = selectionModel()->selectedIndexes();
QModelIndex parent = rootIndex();
QItemSelection selection;
- if (indexList.count() >= 1)
+ if (indexList.size() >= 1)
parent = indexList.at(0).parent();
- if (indexList.count() == 1) {
+ if (indexList.size() == 1) {
parent = indexList.at(0);
if (!model()->hasChildren(parent))
parent = parent.parent();
@@ -1058,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);
}
@@ -1075,7 +1073,7 @@ void QColumnViewPrivate::checkColumnCreation(const QModelIndex &parent)
if (parent == q_func()->currentIndex() && model->hasChildren(parent)) {
//the parent has children and is the current
//let's try to find out if there is already a mapping that is good
- for (int i = 0; i < columns.count(); ++i) {
+ for (int i = 0; i < columns.size(); ++i) {
QAbstractItemView *view = columns.at(i);
if (view->rootIndex() == parent) {
if (view == previewColumn) {
@@ -1126,14 +1124,12 @@ void QColumnViewPrivate::doLayout()
Draws a delegate with a > if an object has children.
- \sa {Model/View Programming}, QItemDelegate
+ \sa {Model/View Programming}, QStyledItemDelegate
*/
void QColumnViewDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
- drawBackground(painter, option, index );
-
bool reverse = (option.direction == Qt::RightToLeft);
int width = ((option.rect.height() * 2) / 3);
// Modify the options to give us room to add an arrow
@@ -1148,7 +1144,7 @@ void QColumnViewDelegate::paint(QPainter *painter,
opt.state |= QStyle::State_Selected;
}
- QItemDelegate::paint(painter, opt, index);
+ QStyledItemDelegate::paint(painter, opt, index);
if (reverse)
opt.rect = QRect(option.rect.x(), option.rect.y(), width, option.rect.height());
diff --git a/src/widgets/itemviews/qcolumnview.h b/src/widgets/itemviews/qcolumnview.h
index 5c62f9c9af..c0c1398692 100644
--- a/src/widgets/itemviews/qcolumnview.h
+++ b/src/widgets/itemviews/qcolumnview.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOLUMNVIEW_H
#define QCOLUMNVIEW_H
@@ -103,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 c60579255e..f9b2f3baa4 100644
--- a/src/widgets/itemviews/qcolumnview_p.h
+++ b/src/widgets/itemviews/qcolumnview_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QCOLUMNVIEW_P_H
#define QCOLUMNVIEW_P_H
@@ -62,11 +26,13 @@
#endif
#include <QtWidgets/qabstractitemdelegate.h>
#include <QtWidgets/qabstractitemview.h>
-#include <QtWidgets/qitemdelegate.h>
+#include <QtWidgets/qstyleditemdelegate.h>
#include <qlistview.h>
#include <qevent.h>
#include <qscrollbar.h>
+#include <vector>
+
QT_REQUIRE_CONFIG(columnview);
QT_BEGIN_NAMESPACE
@@ -152,28 +118,35 @@ 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;
- QVector<int> columnSizes; // used during init and corner moving
+ QList<int> columnSizes; // used during init and corner moving
bool showResizeGrips;
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;
};
@@ -181,12 +154,11 @@ public:
/*!
* This is a delegate that will paint the triangle
*/
-// ### Qt6: QStyledItemDelegate
-class QColumnViewDelegate : public QItemDelegate
+class QColumnViewDelegate : public QStyledItemDelegate
{
public:
- explicit QColumnViewDelegate(QObject *parent = nullptr) : QItemDelegate(parent) {}
+ explicit QColumnViewDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}
~QColumnViewDelegate() {}
void paint(QPainter *painter,
diff --git a/src/widgets/itemviews/qcolumnviewgrip.cpp b/src/widgets/itemviews/qcolumnviewgrip.cpp
index 00cd7df20a..22becae872 100644
--- a/src/widgets/itemviews/qcolumnviewgrip.cpp
+++ b/src/widgets/itemviews/qcolumnviewgrip.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qcolumnviewgrip_p.h"
#include <qstyleoption.h>
@@ -149,7 +113,7 @@ void QColumnViewGrip::mouseDoubleClickEvent(QMouseEvent *event)
void QColumnViewGrip::mousePressEvent(QMouseEvent *event)
{
Q_D(QColumnViewGrip);
- d->originalXLocation = event->globalX();
+ d->originalXLocation = event->globalPosition().toPoint().x();
event->accept();
}
@@ -160,7 +124,7 @@ void QColumnViewGrip::mousePressEvent(QMouseEvent *event)
void QColumnViewGrip::mouseMoveEvent(QMouseEvent *event)
{
Q_D(QColumnViewGrip);
- int offset = event->globalX() - d->originalXLocation;
+ int offset = event->globalPosition().toPoint().x() - d->originalXLocation;
d->originalXLocation = moveGrip(offset) + d->originalXLocation;
event->accept();
}
diff --git a/src/widgets/itemviews/qcolumnviewgrip_p.h b/src/widgets/itemviews/qcolumnviewgrip_p.h
index 13e4c764e8..30e8ce0f79 100644
--- a/src/widgets/itemviews/qcolumnviewgrip_p.h
+++ b/src/widgets/itemviews/qcolumnviewgrip_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOLUMNVIEWGRIP_P_H
#define QCOLUMNVIEWGRIP_P_H
diff --git a/src/widgets/itemviews/qdatawidgetmapper.cpp b/src/widgets/itemviews/qdatawidgetmapper.cpp
index 24039c42f6..3b7e97eed9 100644
--- a/src/widgets/itemviews/qdatawidgetmapper.cpp
+++ b/src/widgets/itemviews/qdatawidgetmapper.cpp
@@ -1,51 +1,18 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "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
@@ -102,10 +69,22 @@ public:
void populate();
// private slots
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<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
{
@@ -121,8 +100,10 @@ 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_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QDataWidgetMapperPrivate::WidgetMapper, Q_RELOCATABLE_TYPE);
int QDataWidgetMapperPrivate::findWidget(QWidget *w) const
{
@@ -176,7 +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 QVector<int> &)
+void QDataWidgetMapperPrivate::dataChanged(const QModelIndex &topLeft,
+ const QModelIndex &bottomRight, const QList<int> &)
{
if (topLeft.parent() != rootIndex)
return; // not in our hierarchy
@@ -187,7 +169,7 @@ void QDataWidgetMapperPrivate::_q_dataChanged(const QModelIndex &topLeft, const
}
}
-void QDataWidgetMapperPrivate::_q_commitData(QWidget *w)
+void QDataWidgetMapperPrivate::commitData(QWidget *w)
{
if (submitPolicy == QDataWidgetMapper::ManualSubmit)
return;
@@ -199,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)
@@ -222,7 +204,7 @@ void QDataWidgetMapperPrivate::_q_closeEditor(QWidget *w, QAbstractItemDelegate:
}
}
-void QDataWidgetMapperPrivate::_q_modelDestroyed()
+void QDataWidgetMapperPrivate::modelDestroyed()
{
Q_Q(QDataWidgetMapper);
@@ -253,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:
@@ -324,8 +306,7 @@ void QDataWidgetMapperPrivate::_q_modelDestroyed()
QDataWidgetMapper::QDataWidgetMapper(QObject *parent)
: QObject(*new QDataWidgetMapperPrivate, parent)
{
- // ### Qt6: QStyledItemDelegate
- setItemDelegate(new QItemDelegate(this));
+ setItemDelegate(new QStyledItemDelegate(this));
}
/*!
@@ -333,6 +314,9 @@ QDataWidgetMapper::QDataWidgetMapper(QObject *parent)
*/
QDataWidgetMapper::~QDataWidgetMapper()
{
+ Q_D(QDataWidgetMapper);
+ d->disconnectModel();
+ d->disconnectDelegate();
}
/*!
@@ -348,21 +332,19 @@ void QDataWidgetMapper::setModel(QAbstractItemModel *model)
if (d->model == model)
return;
- if (d->model) {
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)), this,
- SLOT(_q_dataChanged(QModelIndex,QModelIndex,QVector<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,QVector<int>)),
- SLOT(_q_dataChanged(QModelIndex,QModelIndex,QVector<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)
+ };
}
/*!
@@ -383,6 +365,9 @@ QAbstractItemModel *QDataWidgetMapper::model() const
data from the model into the widget and from the widget to the model,
using QAbstractItemDelegate::setEditorData() and QAbstractItemDelegate::setModelData().
+ Any existing delegate will be removed, but not deleted. QDataWidgetMapper
+ does not take ownership of \a delegate.
+
The delegate also decides when to apply data and when to change the editor,
using QAbstractItemDelegate::commitData() and QAbstractItemDelegate::closeEditor().
@@ -395,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 2d75b63a5e..6c7beff7fc 100644
--- a/src/widgets/itemviews/qdatawidgetmapper.h
+++ b/src/widgets/itemviews/qdatawidgetmapper.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDATAWIDGETMAPPER_H
#define QDATAWIDGETMAPPER_H
@@ -108,10 +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 QVector<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/qdirmodel.cpp b/src/widgets/itemviews/qdirmodel.cpp
deleted file mode 100644
index 0d387d7def..0000000000
--- a/src/widgets/itemviews/qdirmodel.cpp
+++ /dev/null
@@ -1,1378 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdirmodel.h"
-
-#if QT_DEPRECATED_SINCE(5, 15)
-
-#include <qfile.h>
-#include <qfilesystemmodel.h>
-#include <qurl.h>
-#include <qmimedata.h>
-#include <qpair.h>
-#include <qvector.h>
-#include <qobject.h>
-#include <qdatetime.h>
-#include <qlocale.h>
-#include <qstyle.h>
-#include <qapplication.h>
-#include <private/qabstractitemmodel_p.h>
-#include <private/qfilesystementry_p.h>
-#include <qdebug.h>
-
-#include <stack>
-#include <vector>
-
-/*!
- \enum QDirModel::Roles
- \value FileIconRole
- \value FilePathRole
- \value FileNameRole
-*/
-
-QT_BEGIN_NAMESPACE
-
-class QDirModelPrivate : public QAbstractItemModelPrivate
-{
- Q_DECLARE_PUBLIC(QDirModel)
-
-public:
- struct QDirNode
- {
- QDirNode() : parent(nullptr), populated(false), stat(false) {}
- QDirNode *parent;
- QFileInfo info;
- QIcon icon; // cache the icon
- mutable QVector<QDirNode> children;
- mutable bool populated; // have we read the children
- mutable bool stat;
- };
-
- QDirModelPrivate()
- : resolveSymlinks(true),
- readOnly(true),
- lazyChildCount(false),
- allowAppendChild(true),
- iconProvider(&defaultProvider),
- shouldStat(true) // ### This is set to false by QFileDialog
- { }
-
- void init();
- QDirNode *node(int row, QDirNode *parent) const;
- QVector<QDirNode> children(QDirNode *parent, bool stat) const;
-
- void _q_refresh();
-
- void savePersistentIndexes();
- void restorePersistentIndexes();
-
- QFileInfoList entryInfoList(const QString &path) const;
- QStringList entryList(const QString &path) const;
-
- QString name(const QModelIndex &index) const;
- QString size(const QModelIndex &index) const;
- QString type(const QModelIndex &index) const;
- QString time(const QModelIndex &index) const;
-
- void appendChild(QDirModelPrivate::QDirNode *parent, const QString &path) const;
- static QFileInfo resolvedInfo(QFileInfo info);
-
- inline QDirNode *node(const QModelIndex &index) const;
- inline void populate(QDirNode *parent) const;
- inline void clear(QDirNode *parent) const;
-
- void invalidate();
-
- mutable QDirNode root;
- bool resolveSymlinks;
- bool readOnly;
- bool lazyChildCount;
- bool allowAppendChild;
-
- QDir::Filters filters;
- QDir::SortFlags sort;
- QStringList nameFilters;
-
- QFileIconProvider *iconProvider;
- QFileIconProvider defaultProvider;
-
- struct SavedPersistent {
- QString path;
- int column;
- QPersistentModelIndexData *data;
- QPersistentModelIndex index;
- };
- QVector<SavedPersistent> savedPersistent;
- QPersistentModelIndex toBeRefreshed;
-
- bool shouldStat; // use the "carefull not to stat directories" mode
-};
-Q_DECLARE_TYPEINFO(QDirModelPrivate::SavedPersistent, Q_MOVABLE_TYPE);
-
-void qt_setDirModelShouldNotStat(QDirModelPrivate *modelPrivate)
-{
- modelPrivate->shouldStat = false;
-}
-
-QDirModelPrivate::QDirNode *QDirModelPrivate::node(const QModelIndex &index) const
-{
- QDirModelPrivate::QDirNode *n =
- static_cast<QDirModelPrivate::QDirNode*>(index.internalPointer());
- Q_ASSERT(n);
- return n;
-}
-
-void QDirModelPrivate::populate(QDirNode *parent) const
-{
- Q_ASSERT(parent);
- parent->children = children(parent, parent->stat);
- parent->populated = true;
-}
-
-void QDirModelPrivate::clear(QDirNode *parent) const
-{
- Q_ASSERT(parent);
- parent->children.clear();
- parent->populated = false;
-}
-
-void QDirModelPrivate::invalidate()
-{
- std::stack<const QDirNode*, std::vector<const QDirNode*> > nodes;
- nodes.push(&root);
- while (!nodes.empty()) {
- const QDirNode *current = nodes.top();
- nodes.pop();
- current->stat = false;
- const QVector<QDirNode> &children = current->children;
- for (const auto &child : children)
- nodes.push(&child);
- }
-}
-
-/*!
- \class QDirModel
- \obsolete
- \brief The QDirModel class provides a data model for the local filesystem.
-
- \ingroup model-view
- \inmodule QtWidgets
-
- The usage of QDirModel is not recommended anymore. The
- QFileSystemModel class is a more performant alternative.
-
- This class provides access to the local filesystem, providing functions
- for renaming and removing files and directories, and for creating new
- directories. In the simplest case, it can be used with a suitable display
- widget as part of a browser or filer.
-
- QDirModel keeps a cache with file information. The cache needs to be
- updated with refresh().
-
- QDirModel can be accessed using the standard interface provided by
- QAbstractItemModel, but it also provides some convenience functions
- that are specific to a directory model. The fileInfo() and isDir()
- functions provide information about the underlying files and directories
- related to items in the model.
-
- Directories can be created and removed using mkdir(), rmdir(), and the
- model will be automatically updated to take the changes into account.
-
- \note QDirModel requires an instance of \l QApplication.
-
- \sa nameFilters(), setFilter(), filter(), QListView, QTreeView, QFileSystemModel,
- {Dir View Example}, {Model Classes}
-*/
-
-/*!
- Constructs a new directory model with the given \a parent.
- Only those files matching the \a nameFilters and the
- \a filters are included in the model. The sort order is given by the
- \a sort flags.
-*/
-
-QDirModel::QDirModel(const QStringList &nameFilters,
- QDir::Filters filters,
- QDir::SortFlags sort,
- QObject *parent)
- : QAbstractItemModel(*new QDirModelPrivate, parent)
-{
- Q_D(QDirModel);
- // we always start with QDir::drives()
- d->nameFilters = nameFilters.isEmpty() ? QStringList(QLatin1String("*")) : nameFilters;
- d->filters = filters;
- d->sort = sort;
- d->root.parent = nullptr;
- d->root.info = QFileInfo();
- d->clear(&d->root);
-}
-
-/*!
- Constructs a directory model with the given \a parent.
-*/
-
-QDirModel::QDirModel(QObject *parent)
- : QAbstractItemModel(*new QDirModelPrivate, parent)
-{
- Q_D(QDirModel);
- d->init();
-}
-
-/*!
- \internal
-*/
-QDirModel::QDirModel(QDirModelPrivate &dd, QObject *parent)
- : QAbstractItemModel(dd, parent)
-{
- Q_D(QDirModel);
- d->init();
-}
-
-/*!
- Destroys this directory model.
-*/
-
-QDirModel::~QDirModel()
-{
-
-}
-
-/*!
- Returns the model item index for the item in the \a parent with the
- given \a row and \a column.
-
-*/
-
-QModelIndex QDirModel::index(int row, int column, const QModelIndex &parent) const
-{
- Q_D(const QDirModel);
- // note that rowCount does lazy population
- if (column < 0 || column >= columnCount(parent) || row < 0 || parent.column() > 0)
- return QModelIndex();
- // make sure the list of children is up to date
- QDirModelPrivate::QDirNode *p = (d->indexValid(parent) ? d->node(parent) : &d->root);
- Q_ASSERT(p);
- if (!p->populated)
- d->populate(p); // populate without stat'ing
- if (row >= p->children.count())
- return QModelIndex();
- // now get the internal pointer for the index
- QDirModelPrivate::QDirNode *n = d->node(row, d->indexValid(parent) ? p : nullptr);
- Q_ASSERT(n);
-
- return createIndex(row, column, n);
-}
-
-/*!
- Return the parent of the given \a child model item.
-*/
-
-QModelIndex QDirModel::parent(const QModelIndex &child) const
-{
- Q_D(const QDirModel);
-
- if (!d->indexValid(child))
- return QModelIndex();
- QDirModelPrivate::QDirNode *node = d->node(child);
- QDirModelPrivate::QDirNode *par = (node ? node->parent : nullptr);
- if (par == nullptr) // parent is the root node
- return QModelIndex();
-
- // get the parent's row
- const QVector<QDirModelPrivate::QDirNode> children =
- par->parent ? par->parent->children : d->root.children;
- Q_ASSERT(children.count() > 0);
- int row = (par - &(children.at(0)));
- Q_ASSERT(row >= 0);
-
- return createIndex(row, 0, par);
-}
-
-/*!
- Returns the number of rows in the \a parent model item.
-
-*/
-
-int QDirModel::rowCount(const QModelIndex &parent) const
-{
- Q_D(const QDirModel);
- if (parent.column() > 0)
- return 0;
-
- if (!parent.isValid()) {
- if (!d->root.populated) // lazy population
- d->populate(&d->root);
- return d->root.children.count();
- }
- if (parent.model() != this)
- return 0;
- QDirModelPrivate::QDirNode *p = d->node(parent);
- if (p->info.isDir() && !p->populated) // lazy population
- d->populate(p);
- return p->children.count();
-}
-
-/*!
- Returns the number of columns in the \a parent model item.
-
-*/
-
-int QDirModel::columnCount(const QModelIndex &parent) const
-{
- if (parent.column() > 0)
- return 0;
- return 4;
-}
-
-/*!
- Returns the data for the model item \a index with the given \a role.
-*/
-QVariant QDirModel::data(const QModelIndex &index, int role) const
-{
- Q_D(const QDirModel);
- if (!d->indexValid(index))
- return QVariant();
-
- if (role == Qt::DisplayRole || role == Qt::EditRole) {
- switch (index.column()) {
- case 0: return d->name(index);
- case 1: return d->size(index);
- case 2: return d->type(index);
- case 3: return d->time(index);
- default:
- qWarning("data: invalid display value column %d", index.column());
- return QVariant();
- }
- }
-
- if (index.column() == 0) {
- if (role == FileIconRole)
- return fileIcon(index);
- if (role == FilePathRole)
- return filePath(index);
- if (role == FileNameRole)
- return fileName(index);
- }
-
- if (index.column() == 1 && Qt::TextAlignmentRole == role) {
- return Qt::AlignRight;
- }
- return QVariant();
-}
-
-/*!
- Sets the data for the model item \a index with the given \a role to
- the data referenced by the \a value. Returns \c true if successful;
- otherwise returns \c false.
-
- \sa Qt::ItemDataRole
-*/
-
-bool QDirModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- Q_D(QDirModel);
- if (!d->indexValid(index) || index.column() != 0
- || (flags(index) & Qt::ItemIsEditable) == 0 || role != Qt::EditRole)
- return false;
-
- QDirModelPrivate::QDirNode *node = d->node(index);
- QDir dir = node->info.dir();
- QString name = value.toString();
- if (dir.rename(node->info.fileName(), name)) {
- node->info = QFileInfo(dir, name);
- QModelIndex sibling = index.sibling(index.row(), 3);
- emit dataChanged(index, sibling);
-
- d->toBeRefreshed = index.parent();
- QMetaObject::invokeMethod(this, "_q_refresh", Qt::QueuedConnection);
-
- return true;
- }
-
- return false;
-}
-
-/*!
- Returns the data stored under the given \a role for the specified \a section
- of the header with the given \a orientation.
-*/
-
-QVariant QDirModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (orientation == Qt::Horizontal) {
- if (role != Qt::DisplayRole)
- return QVariant();
- switch (section) {
- case 0: return tr("Name");
- case 1: return tr("Size");
- case 2: return
-#ifdef Q_OS_MAC
- tr("Kind", "Match OS X Finder");
-#else
- tr("Type", "All other platforms");
-#endif
- // Windows - Type
- // OS X - Kind
- // Konqueror - File Type
- // Nautilus - Type
- case 3: return tr("Date Modified");
- default: return QVariant();
- }
- }
- return QAbstractItemModel::headerData(section, orientation, role);
-}
-
-/*!
- Returns \c true if the \a parent model item has children; otherwise
- returns \c false.
-*/
-
-bool QDirModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QDirModel);
- if (parent.column() > 0)
- return false;
-
- if (!parent.isValid()) // the invalid index is the "My Computer" item
- return true; // the drives
- QDirModelPrivate::QDirNode *p = d->node(parent);
- Q_ASSERT(p);
-
- if (d->lazyChildCount) // optimization that only checks for children if the node has been populated
- return p->info.isDir();
- return p->info.isDir() && rowCount(parent) > 0;
-}
-
-/*!
- Returns the item flags for the given \a index in the model.
-
- \sa Qt::ItemFlags
-*/
-Qt::ItemFlags QDirModel::flags(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (!d->indexValid(index))
- return flags;
- flags |= Qt::ItemIsDragEnabled;
- if (d->readOnly)
- return flags;
- QDirModelPrivate::QDirNode *node = d->node(index);
- if ((index.column() == 0) && node->info.isWritable()) {
- flags |= Qt::ItemIsEditable;
- if (fileInfo(index).isDir()) // is directory and is editable
- flags |= Qt::ItemIsDropEnabled;
- }
- return flags;
-}
-
-/*!
- Sort the model items in the \a column using the \a order given.
- The order is a value defined in \l Qt::SortOrder.
-*/
-
-void QDirModel::sort(int column, Qt::SortOrder order)
-{
- QDir::SortFlags sort = QDir::DirsFirst | QDir::IgnoreCase;
- if (order == Qt::DescendingOrder)
- sort |= QDir::Reversed;
-
- switch (column) {
- case 0:
- sort |= QDir::Name;
- break;
- case 1:
- sort |= QDir::Size;
- break;
- case 2:
- sort |= QDir::Type;
- break;
- case 3:
- sort |= QDir::Time;
- break;
- default:
- break;
- }
-
- setSorting(sort);
-}
-
-/*!
- Returns a list of MIME types that can be used to describe a list of items
- in the model.
-*/
-
-QStringList QDirModel::mimeTypes() const
-{
- return QStringList(QLatin1String("text/uri-list"));
-}
-
-/*!
- Returns an object that contains a serialized description of the specified
- \a indexes. The format used to describe the items corresponding to the
- indexes is obtained from the mimeTypes() function.
-
- If the list of indexes is empty, 0 is returned rather than a serialized
- empty list.
-*/
-
-QMimeData *QDirModel::mimeData(const QModelIndexList &indexes) const
-{
- QList<QUrl> urls;
- QList<QModelIndex>::const_iterator it = indexes.begin();
- for (; it != indexes.end(); ++it)
- if ((*it).column() == 0)
- urls << QUrl::fromLocalFile(filePath(*it));
- QMimeData *data = new QMimeData();
- data->setUrls(urls);
- return data;
-}
-
-/*!
- Handles the \a data supplied by a drag and drop operation that ended with
- the given \a action over the row in the model specified by the \a row and
- \a column and by the \a parent index.
-
- Returns \c true if the drop was successful, and false otherwise.
-
- \sa supportedDropActions()
-*/
-
-bool QDirModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int /* row */, int /* column */, const QModelIndex &parent)
-{
- Q_D(QDirModel);
- if (!d->indexValid(parent) || isReadOnly())
- return false;
-
- bool success = true;
- QString to = filePath(parent) + QDir::separator();
- QModelIndex _parent = parent;
-
- QList<QUrl> urls = data->urls();
- QList<QUrl>::const_iterator it = urls.constBegin();
-
- switch (action) {
- case Qt::CopyAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::copy(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- case Qt::LinkAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::link(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- case Qt::MoveAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- if (QFile::copy(path, to + QFileInfo(path).fileName())
- && QFile::remove(path)) {
- QModelIndex idx=index(QFileInfo(path).path());
- if (idx.isValid()) {
- refresh(idx);
- //the previous call to refresh may invalidate the _parent. so recreate a new QModelIndex
- _parent = index(to);
- }
- } else {
- success = false;
- }
- }
- break;
- default:
- return false;
- }
-
- if (success)
- refresh(_parent);
-
- return success;
-}
-
-/*!
- Returns the drop actions supported by this model.
-
- \sa Qt::DropActions
-*/
-
-Qt::DropActions QDirModel::supportedDropActions() const
-{
- return Qt::CopyAction | Qt::MoveAction; // FIXME: LinkAction is not supported yet
-}
-
-/*!
- Sets the \a provider of file icons for the directory model.
-
-*/
-
-void QDirModel::setIconProvider(QFileIconProvider *provider)
-{
- Q_D(QDirModel);
- d->iconProvider = provider;
-}
-
-/*!
- Returns the file icon provider for this directory model.
-*/
-
-QFileIconProvider *QDirModel::iconProvider() const
-{
- Q_D(const QDirModel);
- return d->iconProvider;
-}
-
-/*!
- Sets the name \a filters for the directory model.
-*/
-
-void QDirModel::setNameFilters(const QStringList &filters)
-{
- Q_D(QDirModel);
- d->nameFilters = filters;
- emit layoutAboutToBeChanged();
- if (d->shouldStat)
- refresh(QModelIndex());
- else
- d->invalidate();
- emit layoutChanged();
-}
-
-/*!
- Returns a list of filters applied to the names in the model.
-*/
-
-QStringList QDirModel::nameFilters() const
-{
- Q_D(const QDirModel);
- return d->nameFilters;
-}
-
-/*!
- Sets the directory model's filter to that specified by \a filters.
-
- Note that the filter you set should always include the QDir::AllDirs enum value,
- otherwise QDirModel won't be able to read the directory structure.
-
- \sa QDir::Filters
-*/
-
-void QDirModel::setFilter(QDir::Filters filters)
-{
- Q_D(QDirModel);
- d->filters = filters;
- emit layoutAboutToBeChanged();
- if (d->shouldStat)
- refresh(QModelIndex());
- else
- d->invalidate();
- emit layoutChanged();
-}
-
-/*!
- Returns the filter specification for the directory model.
-
- \sa QDir::Filters
-*/
-
-QDir::Filters QDirModel::filter() const
-{
- Q_D(const QDirModel);
- return d->filters;
-}
-
-/*!
- Sets the directory model's sorting order to that specified by \a sort.
-
- \sa QDir::SortFlags
-*/
-
-void QDirModel::setSorting(QDir::SortFlags sort)
-{
- Q_D(QDirModel);
- d->sort = sort;
- emit layoutAboutToBeChanged();
- if (d->shouldStat)
- refresh(QModelIndex());
- else
- d->invalidate();
- emit layoutChanged();
-}
-
-/*!
- Returns the sorting method used for the directory model.
-
- \sa QDir::SortFlags
-*/
-
-QDir::SortFlags QDirModel::sorting() const
-{
- Q_D(const QDirModel);
- return d->sort;
-}
-
-/*!
- \property QDirModel::resolveSymlinks
- \brief Whether the directory model should resolve symbolic links
-
- This is only relevant on operating systems that support symbolic
- links.
-*/
-void QDirModel::setResolveSymlinks(bool enable)
-{
- Q_D(QDirModel);
- d->resolveSymlinks = enable;
-}
-
-bool QDirModel::resolveSymlinks() const
-{
- Q_D(const QDirModel);
- return d->resolveSymlinks;
-}
-
-/*!
- \property QDirModel::readOnly
- \brief Whether the directory model allows writing to the file system
-
- If this property is set to false, the directory model will allow renaming, copying
- and deleting of files and directories.
-
- This property is \c true by default
-*/
-
-void QDirModel::setReadOnly(bool enable)
-{
- Q_D(QDirModel);
- d->readOnly = enable;
-}
-
-bool QDirModel::isReadOnly() const
-{
- Q_D(const QDirModel);
- return d->readOnly;
-}
-
-/*!
- \property QDirModel::lazyChildCount
- \brief Whether the directory model optimizes the hasChildren function
- to only check if the item is a directory.
-
- If this property is set to false, the directory model will make sure that a directory
- actually containes any files before reporting that it has children.
- Otherwise the directory model will report that an item has children if the item
- is a directory.
-
- This property is \c false by default
-*/
-
-void QDirModel::setLazyChildCount(bool enable)
-{
- Q_D(QDirModel);
- d->lazyChildCount = enable;
-}
-
-bool QDirModel::lazyChildCount() const
-{
- Q_D(const QDirModel);
- return d->lazyChildCount;
-}
-
-/*!
- QDirModel caches file information. This function updates the
- cache. The \a parent parameter is the directory from which the
- model is updated; the default value will update the model from
- root directory of the file system (the entire model).
-*/
-
-void QDirModel::refresh(const QModelIndex &parent)
-{
- Q_D(QDirModel);
-
- QDirModelPrivate::QDirNode *n = d->indexValid(parent) ? d->node(parent) : &(d->root);
-
- int rows = n->children.count();
- if (rows == 0) {
- emit layoutAboutToBeChanged();
- n->stat = true; // make sure that next time we read all the info
- n->populated = false;
- emit layoutChanged();
- return;
- }
-
- emit layoutAboutToBeChanged();
- d->savePersistentIndexes();
- d->rowsAboutToBeRemoved(parent, 0, rows - 1);
- n->stat = true; // make sure that next time we read all the info
- d->clear(n);
- d->rowsRemoved(parent, 0, rows - 1);
- d->restorePersistentIndexes();
- emit layoutChanged();
-}
-
-/*!
- \overload
-
- Returns the model item index for the given \a path.
-*/
-
-QModelIndex QDirModel::index(const QString &path, int column) const
-{
- Q_D(const QDirModel);
-
- if (path.isEmpty() || path == QCoreApplication::translate("QFileDialog", "My Computer"))
- return QModelIndex();
-
- QString absolutePath = QDir(path).absolutePath();
-#if defined(Q_OS_WIN)
- absolutePath = absolutePath.toLower();
- // On Windows, "filename......." and "filename" are equivalent
- if (absolutePath.endsWith(QLatin1Char('.'))) {
- int i;
- for (i = absolutePath.count() - 1; i >= 0; --i) {
- if (absolutePath.at(i) != QLatin1Char('.'))
- break;
- }
- absolutePath = absolutePath.left(i+1);
- }
-#endif
-
- QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts);
- if ((pathElements.isEmpty() || !QFileInfo::exists(path))
-#if !defined(Q_OS_WIN)
- && path != QLatin1String("/")
-#endif
- )
- return QModelIndex();
-
- QModelIndex idx; // start with "My Computer"
- if (!d->root.populated) // make sure the root is populated
- d->populate(&d->root);
-
-#if defined(Q_OS_WIN)
- if (absolutePath.startsWith(QLatin1String("//"))) { // UNC path
- QString host = pathElements.constFirst();
- int r = 0;
- for (; r < d->root.children.count(); ++r)
- if (d->root.children.at(r).info.fileName() == host)
- break;
- bool childAppended = false;
- if (r >= d->root.children.count() && d->allowAppendChild) {
- d->appendChild(&d->root, QLatin1String("//") + host);
- childAppended = true;
- }
- idx = index(r, 0, QModelIndex());
- pathElements.pop_front();
- if (childAppended)
- emit const_cast<QDirModel*>(this)->layoutChanged();
- } else
-#endif
-#if defined(Q_OS_WIN)
- if (pathElements.at(0).endsWith(QLatin1Char(':'))) {
- pathElements[0] += QLatin1Char('/');
- }
-#else
- // add the "/" item, since it is a valid path element on unix
- pathElements.prepend(QLatin1String("/"));
-#endif
-
- for (int i = 0; i < pathElements.count(); ++i) {
- Q_ASSERT(!pathElements.at(i).isEmpty());
- QString element = pathElements.at(i);
- QDirModelPrivate::QDirNode *parent = (idx.isValid() ? d->node(idx) : &d->root);
-
- Q_ASSERT(parent);
- if (!parent->populated)
- d->populate(parent);
-
- // search for the element in the child nodes first
- int row = -1;
- for (int j = parent->children.count() - 1; j >= 0; --j) {
- const QFileInfo& fi = parent->children.at(j).info;
- QString childFileName;
- childFileName = idx.isValid() ? fi.fileName() : fi.absoluteFilePath();
-#if defined(Q_OS_WIN)
- childFileName = childFileName.toLower();
-#endif
- if (childFileName == element) {
- if (i == pathElements.count() - 1)
- parent->children[j].stat = true;
- row = j;
- break;
- }
- }
-
- // we couldn't find the path element, we create a new node since we _know_ that the path is valid
- if (row == -1) {
- QString newPath = parent->info.absoluteFilePath() + QLatin1Char('/') + element;
- if (!d->allowAppendChild || !QFileInfo(newPath).isDir())
- return QModelIndex();
- d->appendChild(parent, newPath);
- row = parent->children.count() - 1;
- if (i == pathElements.count() - 1) // always stat children of the last element
- parent->children[row].stat = true;
- emit const_cast<QDirModel*>(this)->layoutChanged();
- }
-
- Q_ASSERT(row >= 0);
- idx = createIndex(row, 0, static_cast<void*>(&parent->children[row]));
- Q_ASSERT(idx.isValid());
- }
-
- if (column != 0)
- return idx.sibling(idx.row(), column);
- return idx;
-}
-
-/*!
- Returns \c true if the model item \a index represents a directory;
- otherwise returns \c false.
-*/
-
-bool QDirModel::isDir(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- Q_ASSERT(d->indexValid(index));
- QDirModelPrivate::QDirNode *node = d->node(index);
- return node->info.isDir();
-}
-
-/*!
- Create a directory with the \a name in the \a parent model item.
-*/
-
-QModelIndex QDirModel::mkdir(const QModelIndex &parent, const QString &name)
-{
- Q_D(QDirModel);
- if (!d->indexValid(parent) || isReadOnly())
- return QModelIndex();
-
- QDirModelPrivate::QDirNode *p = d->node(parent);
- QString path = p->info.absoluteFilePath();
- // For the indexOf() method to work, the new directory has to be a direct child of
- // the parent directory.
-
- QDir newDir(name);
- QDir dir(path);
- if (newDir.isRelative())
- newDir = QDir(path + QLatin1Char('/') + name);
- QString childName = newDir.dirName(); // Get the singular name of the directory
- newDir.cdUp();
-
- if (newDir.absolutePath() != dir.absolutePath() || !dir.mkdir(name))
- return QModelIndex(); // nothing happened
-
- refresh(parent);
-
- QStringList entryList = d->entryList(path);
- int r = entryList.indexOf(childName);
- QModelIndex i = index(r, 0, parent); // return an invalid index
-
- return i;
-}
-
-/*!
- Removes the directory corresponding to the model item \a index in the
- directory model and \b{deletes the corresponding directory from the
- file system}, returning true if successful. If the directory cannot be
- removed, false is returned.
-
- \warning This function deletes directories from the file system; it does
- \b{not} move them to a location where they can be recovered.
-
- \sa remove()
-*/
-
-bool QDirModel::rmdir(const QModelIndex &index)
-{
- Q_D(QDirModel);
- if (!d->indexValid(index) || isReadOnly())
- return false;
-
- QDirModelPrivate::QDirNode *n = d_func()->node(index);
- if (Q_UNLIKELY(!n->info.isDir())) {
- qWarning("rmdir: the node is not a directory");
- return false;
- }
-
- QModelIndex par = parent(index);
- QDirModelPrivate::QDirNode *p = d_func()->node(par);
- QDir dir = p->info.dir(); // parent dir
- QString path = n->info.absoluteFilePath();
- if (!dir.rmdir(path))
- return false;
-
- refresh(par);
-
- return true;
-}
-
-/*!
- Removes the model item \a index from the directory model and \b{deletes the
- corresponding file from the file system}, returning true if successful. If the
- item cannot be removed, false is returned.
-
- \warning This function deletes files from the file system; it does \b{not}
- move them to a location where they can be recovered.
-
- \sa rmdir()
-*/
-
-bool QDirModel::remove(const QModelIndex &index)
-{
- Q_D(QDirModel);
- if (!d->indexValid(index) || isReadOnly())
- return false;
-
- QDirModelPrivate::QDirNode *n = d_func()->node(index);
- if (n->info.isDir())
- return false;
-
- QModelIndex par = parent(index);
- QDirModelPrivate::QDirNode *p = d_func()->node(par);
- QDir dir = p->info.dir(); // parent dir
- QString path = n->info.absoluteFilePath();
- if (!dir.remove(path))
- return false;
-
- refresh(par);
-
- return true;
-}
-
-/*!
- Returns the path of the item stored in the model under the
- \a index given.
-
-*/
-
-QString QDirModel::filePath(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- if (d->indexValid(index)) {
- QFileInfo fi = fileInfo(index);
- if (d->resolveSymlinks && fi.isSymLink())
- fi = QDirModelPrivate::resolvedInfo(fi);
- return QDir::cleanPath(fi.absoluteFilePath());
- }
- return QString(); // root path
-}
-
-/*!
- Returns the name of the item stored in the model under the
- \a index given.
-
-*/
-
-QString QDirModel::fileName(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- if (!d->indexValid(index))
- return QString();
- QFileInfo info = fileInfo(index);
- const QString &path = info.absoluteFilePath();
- if (QFileSystemEntry::isRootPath(path))
- return path;
- if (d->resolveSymlinks && info.isSymLink())
- info = QDirModelPrivate::resolvedInfo(info);
- return info.fileName();
-}
-
-/*!
- Returns the icons for the item stored in the model under the given
- \a index.
-*/
-
-QIcon QDirModel::fileIcon(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- if (!d->indexValid(index))
- return d->iconProvider->icon(QFileIconProvider::Computer);
- QDirModelPrivate::QDirNode *node = d->node(index);
- if (node->icon.isNull())
- node->icon = d->iconProvider->icon(node->info);
- return node->icon;
-}
-
-/*!
- Returns the file information for the specified model \a index.
-
- \b{Note:} If the model index represents a symbolic link in the
- underlying filing system, the file information returned will contain
- information about the symbolic link itself, regardless of whether
- resolveSymlinks is enabled or not.
-
- \sa QFileInfo::symLinkTarget()
-*/
-
-QFileInfo QDirModel::fileInfo(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- Q_ASSERT(d->indexValid(index));
-
- QDirModelPrivate::QDirNode *node = d->node(index);
- return node->info;
-}
-
-/*
- The root node is never seen outside the model.
-*/
-
-void QDirModelPrivate::init()
-{
- filters = QDir::AllEntries | QDir::NoDotAndDotDot;
- sort = QDir::Name;
- nameFilters << QLatin1String("*");
- root.parent = nullptr;
- root.info = QFileInfo();
- clear(&root);
- roleNames.insert(QDirModel::FileIconRole, QByteArrayLiteral("fileIcon")); // == Qt::decoration
- roleNames.insert(QDirModel::FilePathRole, QByteArrayLiteral("filePath"));
- roleNames.insert(QDirModel::FileNameRole, QByteArrayLiteral("fileName"));
-}
-
-QDirModelPrivate::QDirNode *QDirModelPrivate::node(int row, QDirNode *parent) const
-{
- if (row < 0)
- return nullptr;
-
- bool isDir = !parent || parent->info.isDir();
- QDirNode *p = (parent ? parent : &root);
- if (isDir && !p->populated)
- populate(p); // will also resolve symlinks
-
- if (Q_UNLIKELY(row >= p->children.count())) {
- qWarning("node: the row does not exist");
- return nullptr;
- }
-
- return const_cast<QDirNode*>(&p->children.at(row));
-}
-
-QVector<QDirModelPrivate::QDirNode> QDirModelPrivate::children(QDirNode *parent, bool stat) const
-{
- Q_ASSERT(parent);
- QFileInfoList infoList;
- if (parent == &root) {
- parent = nullptr;
- infoList = QDir::drives();
- } else if (parent->info.isDir()) {
- //resolve directory links only if requested.
- if (parent->info.isSymLink() && resolveSymlinks) {
- QString link = parent->info.symLinkTarget();
- if (link.size() > 1 && link.at(link.size() - 1) == QDir::separator())
- link.chop(1);
- if (stat)
- infoList = entryInfoList(link);
- else
- infoList = QDir(link).entryInfoList(nameFilters, QDir::AllEntries | QDir::System);
- } else {
- if (stat)
- infoList = entryInfoList(parent->info.absoluteFilePath());
- else
- infoList = QDir(parent->info.absoluteFilePath()).entryInfoList(nameFilters, QDir::AllEntries | QDir::System);
- }
- }
-
- QVector<QDirNode> nodes(infoList.count());
- for (int i = 0; i < infoList.count(); ++i) {
- QDirNode &node = nodes[i];
- node.parent = parent;
- node.info = infoList.at(i);
- node.populated = false;
- node.stat = shouldStat;
- }
-
- return nodes;
-}
-
-void QDirModelPrivate::_q_refresh()
-{
- Q_Q(QDirModel);
- q->refresh(toBeRefreshed);
- toBeRefreshed = QModelIndex();
-}
-
-void QDirModelPrivate::savePersistentIndexes()
-{
- Q_Q(QDirModel);
- savedPersistent.clear();
- savedPersistent.reserve(persistent.indexes.size());
- foreach (QPersistentModelIndexData *data, persistent.indexes) {
- QModelIndex index = data->index;
- SavedPersistent saved = {
- q->filePath(index),
- index.column(),
- data,
- index,
- };
- savedPersistent.push_back(std::move(saved));
- }
-}
-
-void QDirModelPrivate::restorePersistentIndexes()
-{
- Q_Q(QDirModel);
- bool allow = allowAppendChild;
- allowAppendChild = false;
- for (const SavedPersistent &sp : qAsConst(savedPersistent)) {
- QPersistentModelIndexData *data = sp.data;
- QModelIndex idx = q->index(sp.path, sp.column);
- if (idx != data->index || data->index.model() == nullptr) {
- //data->model may be equal to 0 if the model is getting destroyed
- persistent.indexes.remove(data->index);
- data->index = idx;
- if (idx.isValid())
- persistent.indexes.insert(idx, data);
- }
- }
- savedPersistent.clear();
- allowAppendChild = allow;
-}
-
-QFileInfoList QDirModelPrivate::entryInfoList(const QString &path) const
-{
- const QDir dir(path);
- return dir.entryInfoList(nameFilters, filters, sort);
-}
-
-QStringList QDirModelPrivate::entryList(const QString &path) const
-{
- const QDir dir(path);
- return dir.entryList(nameFilters, filters, sort);
-}
-
-QString QDirModelPrivate::name(const QModelIndex &index) const
-{
- const QDirNode *n = node(index);
- const QFileInfo info = n->info;
- QString name = info.absoluteFilePath();
- if (QFileSystemEntry::isRootPath(name)) {
-#if defined(Q_OS_WIN)
- if (name.startsWith(QLatin1Char('/'))) // UNC host
- return info.fileName();
- if (name.endsWith(QLatin1Char('/')))
- name.chop(1);
-#endif
- return name;
- }
- return info.fileName();
-}
-
-QString QDirModelPrivate::size(const QModelIndex &index) const
-{
- const QDirNode *n = node(index);
- if (n->info.isDir()) {
-#ifdef Q_OS_MAC
- return QLatin1String("--");
-#else
- return QLatin1String("");
-#endif
- // Windows - ""
- // OS X - "--"
- // Konqueror - "4 KB"
- // Nautilus - "9 items" (the number of children)
- }
-
- return QLocale::system().formattedDataSize(n->info.size());
-}
-
-QString QDirModelPrivate::type(const QModelIndex &index) const
-{
- return iconProvider->type(node(index)->info);
-}
-
-QString QDirModelPrivate::time(const QModelIndex &index) const
-{
-#if QT_CONFIG(datestring)
- return node(index)->info.lastModified().toString(Qt::LocalDate);
-#else
- Q_UNUSED(index);
- return QString();
-#endif
-}
-
-void QDirModelPrivate::appendChild(QDirModelPrivate::QDirNode *parent, const QString &path) const
-{
- QDirModelPrivate::QDirNode node;
- node.populated = false;
- node.stat = shouldStat;
- node.parent = (parent == &root ? nullptr : parent);
- node.info = QFileInfo(path);
- node.info.setCaching(true);
-
- // The following append(node) may reallocate the vector, thus
- // we need to update the pointers to the childnodes parent.
- QDirModelPrivate *that = const_cast<QDirModelPrivate *>(this);
- that->savePersistentIndexes();
- parent->children.append(node);
- for (int i = 0; i < parent->children.count(); ++i) {
- QDirNode *childNode = &parent->children[i];
- for (int j = 0; j < childNode->children.count(); ++j)
- childNode->children[j].parent = childNode;
- }
- that->restorePersistentIndexes();
-}
-
-QFileInfo QDirModelPrivate::resolvedInfo(QFileInfo info)
-{
-#ifdef Q_OS_WIN
- // On windows, we cannot create a shortcut to a shortcut.
- return QFileInfo(info.symLinkTarget());
-#else
- QStringList paths;
- do {
- QFileInfo link(info.symLinkTarget());
- if (link.isRelative())
- info.setFile(info.absolutePath(), link.filePath());
- else
- info = link;
- if (paths.contains(info.absoluteFilePath()))
- return QFileInfo();
- paths.append(info.absoluteFilePath());
- } while (info.isSymLink());
- return info;
-#endif
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qdirmodel.cpp"
-
-#endif // QT_DEPRECATED_SINCE(5, 15)
diff --git a/src/widgets/itemviews/qdirmodel.h b/src/widgets/itemviews/qdirmodel.h
deleted file mode 100644
index 665a622dbe..0000000000
--- a/src/widgets/itemviews/qdirmodel.h
+++ /dev/null
@@ -1,152 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDIRMODEL_H
-#define QDIRMODEL_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qdir.h>
-#include <QtWidgets/qfileiconprovider.h>
-
-#if QT_DEPRECATED_SINCE(5, 15)
-
-QT_REQUIRE_CONFIG(dirmodel);
-
-QT_BEGIN_NAMESPACE
-
-class QDirModelPrivate;
-
-class Q_WIDGETS_EXPORT QDirModel : public QAbstractItemModel
-{
- Q_OBJECT
- Q_PROPERTY(bool resolveSymlinks READ resolveSymlinks WRITE setResolveSymlinks)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
- Q_PROPERTY(bool lazyChildCount READ lazyChildCount WRITE setLazyChildCount)
-
-public:
- enum Roles {
- FileIconRole = Qt::DecorationRole,
- FilePathRole = Qt::UserRole + 1,
- FileNameRole
- };
-
- QT_DEPRECATED_VERSION_X_5_15("Use QFileSystemModel") QDirModel(const QStringList &nameFilters,
- QDir::Filters filters, QDir::SortFlags sort,
- QObject *parent = nullptr);
- QT_DEPRECATED_VERSION_X_5_15("Use QFileSystemModel") explicit QDirModel(QObject *parent = nullptr);
- ~QDirModel();
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
- QModelIndex parent(const QModelIndex &child) const override;
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const override;
- int columnCount(const QModelIndex &parent = QModelIndex()) const override;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
-
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
-
- bool hasChildren(const QModelIndex &index = QModelIndex()) const override;
- Qt::ItemFlags flags(const QModelIndex &index) const override;
-
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override;
-
- QStringList mimeTypes() const override;
- QMimeData *mimeData(const QModelIndexList &indexes) const override;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent) override;
- Qt::DropActions supportedDropActions() const override;
-
- // QDirModel specific API
-
- void setIconProvider(QFileIconProvider *provider);
- QFileIconProvider *iconProvider() const;
-
- void setNameFilters(const QStringList &filters);
- QStringList nameFilters() const;
-
- void setFilter(QDir::Filters filters);
- QDir::Filters filter() const;
-
- void setSorting(QDir::SortFlags sort);
- QDir::SortFlags sorting() const;
-
- void setResolveSymlinks(bool enable);
- bool resolveSymlinks() const;
-
- void setReadOnly(bool enable);
- bool isReadOnly() const;
-
- void setLazyChildCount(bool enable);
- bool lazyChildCount() const;
-
- QModelIndex index(const QString &path, int column = 0) const;
-
- bool isDir(const QModelIndex &index) const;
- QModelIndex mkdir(const QModelIndex &parent, const QString &name);
- bool rmdir(const QModelIndex &index);
- bool remove(const QModelIndex &index);
-
- QString filePath(const QModelIndex &index) const;
- QString fileName(const QModelIndex &index) const;
- QIcon fileIcon(const QModelIndex &index) const;
- QFileInfo fileInfo(const QModelIndex &index) const;
-
- using QObject::parent;
-
-public Q_SLOTS:
- void refresh(const QModelIndex &parent = QModelIndex());
-
-protected:
- QDirModel(QDirModelPrivate &, QObject *parent = nullptr);
- friend class QFileDialogPrivate;
-
-private:
- Q_DECLARE_PRIVATE(QDirModel)
- Q_DISABLE_COPY(QDirModel)
- Q_PRIVATE_SLOT(d_func(), void _q_refresh())
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_DEPRECATED_SINCE(5, 15)
-
-#endif // QDIRMODEL_H
diff --git a/src/widgets/itemviews/qfileiconprovider.cpp b/src/widgets/itemviews/qfileiconprovider.cpp
index 65ae6b9505..003fef4224 100644
--- a/src/widgets/itemviews/qfileiconprovider.cpp
+++ b/src/widgets/itemviews/qfileiconprovider.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qfileiconprovider.h"
#include "qfileiconprovider_p.h"
@@ -53,10 +17,8 @@
#if defined(Q_OS_WIN)
# include <qt_windows.h>
-# ifndef Q_OS_WINRT
-# include <commctrl.h>
-# include <objbase.h>
-# endif
+# include <commctrl.h>
+# include <objbase.h>
#endif
QT_BEGIN_NAMESPACE
@@ -66,32 +28,11 @@ QT_BEGIN_NAMESPACE
\inmodule QtWidgets
- \brief The QFileIconProvider class provides file icons for the QDirModel and the QFileSystemModel classes.
+ \brief The QFileIconProvider class provides file icons for the QFileSystemModel class.
*/
-/*!
- \enum QFileIconProvider::IconType
- \value Computer
- \value Desktop
- \value Trashcan
- \value Network
- \value Drive
- \value Folder
- \value File
-*/
-
-
-/*!
- \enum QFileIconProvider::Option
- \since 5.2
-
- \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.
-*/
-
-QFileIconProviderPrivate::QFileIconProviderPrivate(QFileIconProvider *q) :
- q_ptr(q), homePath(QDir::home().absolutePath())
+QFileIconProviderPrivate::QFileIconProviderPrivate(QFileIconProvider *q)
+ : QAbstractFileIconProviderPrivate(q), homePath(QDir::home().absolutePath())
{
}
@@ -157,46 +98,18 @@ QIcon QFileIconProviderPrivate::getIcon(QStyle::StandardPixmap name) const
*/
QFileIconProvider::QFileIconProvider()
- : d_ptr(new QFileIconProviderPrivate(this))
+ : QAbstractFileIconProvider(*new QFileIconProviderPrivate(this))
{
}
/*!
Destroys the file icon provider.
-
-*/
-
-QFileIconProvider::~QFileIconProvider()
-{
-}
-
-/*!
- \since 5.2
- Sets \a options that affect the icon provider.
- \sa options()
*/
-void QFileIconProvider::setOptions(QFileIconProvider::Options options)
-{
- Q_D(QFileIconProvider);
- d->options = options;
-}
+QFileIconProvider::~QFileIconProvider() = default;
/*!
- \since 5.2
- Returns all the options that affect the icon provider.
- By default, all options are disabled.
- \sa setOptions()
-*/
-
-QFileIconProvider::Options QFileIconProvider::options() const
-{
- Q_D(const QFileIconProvider);
- return d->options;
-}
-
-/*!
- Returns an icon set for the given \a type.
+ \reimp
*/
QIcon QFileIconProvider::icon(IconType type) const
@@ -223,21 +136,13 @@ QIcon QFileIconProvider::icon(IconType type) const
return QIcon();
}
-static inline QPlatformTheme::IconOptions toThemeIconOptions(QFileIconProvider::Options options)
-{
- QPlatformTheme::IconOptions result;
- if (options & QFileIconProvider::DontUseCustomDirectoryIcons)
- result |= QPlatformTheme::DontUseCustomDirectoryIcons;
- return result;
-}
-
QIcon QFileIconProviderPrivate::getIcon(const QFileInfo &fi) const
{
- return QGuiApplicationPrivate::platformTheme()->fileIcon(fi, toThemeIconOptions(options));
+ return getPlatformThemeIcon(fi);
}
/*!
- Returns an icon for the file described by \a info.
+ \reimp
*/
QIcon QFileIconProvider::icon(const QFileInfo &info) const
@@ -250,7 +155,7 @@ QIcon QFileIconProvider::icon(const QFileInfo &info) const
const QString &path = info.absoluteFilePath();
if (path.isEmpty() || QFileSystemEntry::isRootPath(path))
-#if defined (Q_OS_WIN) && !defined(Q_OS_WINRT)
+#if defined (Q_OS_WIN)
{
UINT type = GetDriveType(reinterpret_cast<const wchar_t *>(path.utf16()));
@@ -294,45 +199,4 @@ QIcon QFileIconProvider::icon(const QFileInfo &info) const
return QIcon();
}
-/*!
- Returns the type of the file described by \a info.
-*/
-
-QString QFileIconProvider::type(const QFileInfo &info) const
-{
- if (QFileSystemEntry::isRootPath(info.absoluteFilePath()))
- return QApplication::translate("QFileDialog", "Drive");
- if (info.isFile()) {
- if (!info.suffix().isEmpty()) {
- //: %1 is a file name suffix, for example txt
- return QApplication::translate("QFileDialog", "%1 File").arg(info.suffix());
- }
- return QApplication::translate("QFileDialog", "File");
- }
-
- if (info.isDir())
-#ifdef Q_OS_WIN
- return QApplication::translate("QFileDialog", "File Folder", "Match Windows Explorer");
-#else
- return QApplication::translate("QFileDialog", "Folder", "All other platforms");
-#endif
- // Windows - "File Folder"
- // OS X - "Folder"
- // Konqueror - "Folder"
- // Nautilus - "folder"
-
- if (info.isSymLink())
-#ifdef Q_OS_MAC
- return QApplication::translate("QFileDialog", "Alias", "OS X Finder");
-#else
- return QApplication::translate("QFileDialog", "Shortcut", "All other platforms");
-#endif
- // OS X - "Alias"
- // Windows - "Shortcut"
- // Konqueror - "Folder" or "TXT File" i.e. what it is pointing to
- // Nautilus - "link to folder" or "link to object file", same as Konqueror
-
- return QApplication::translate("QFileDialog", "Unknown");
-}
-
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qfileiconprovider.h b/src/widgets/itemviews/qfileiconprovider.h
index 732ca1ac8e..3cc481b756 100644
--- a/src/widgets/itemviews/qfileiconprovider.h
+++ b/src/widgets/itemviews/qfileiconprovider.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFILEICONPROVIDER_H
#define QFILEICONPROVIDER_H
@@ -44,39 +8,27 @@
#include <QtCore/qfileinfo.h>
#include <QtCore/qscopedpointer.h>
#include <QtGui/qicon.h>
+#include <QtGui/qabstractfileiconprovider.h>
QT_BEGIN_NAMESPACE
class QFileIconProviderPrivate;
-class Q_WIDGETS_EXPORT QFileIconProvider
+class Q_WIDGETS_EXPORT QFileIconProvider : public QAbstractFileIconProvider
{
public:
QFileIconProvider();
- virtual ~QFileIconProvider();
- enum IconType { Computer, Desktop, Trashcan, Network, Drive, Folder, File };
+ ~QFileIconProvider();
- enum Option {
- DontUseCustomDirectoryIcons = 0x00000001
- };
- Q_DECLARE_FLAGS(Options, Option)
-
- virtual QIcon icon(IconType type) const;
- virtual QIcon icon(const QFileInfo &info) const;
- virtual QString type(const QFileInfo &info) const;
-
- void setOptions(Options options);
- Options options() const;
+ QIcon icon(IconType type) const override;
+ QIcon icon(const QFileInfo &info) const override;
private:
Q_DECLARE_PRIVATE(QFileIconProvider)
- QScopedPointer<QFileIconProviderPrivate> d_ptr;
Q_DISABLE_COPY(QFileIconProvider)
};
-Q_DECLARE_OPERATORS_FOR_FLAGS(QFileIconProvider::Options)
-
QT_END_NAMESPACE
#endif // QFILEICONPROVIDER_H
diff --git a/src/widgets/itemviews/qfileiconprovider_p.h b/src/widgets/itemviews/qfileiconprovider_p.h
index 4726b15816..e94980066f 100644
--- a/src/widgets/itemviews/qfileiconprovider_p.h
+++ b/src/widgets/itemviews/qfileiconprovider_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFILEICONPROVIDER_P_H
#define QFILEICONPROVIDER_P_H
@@ -54,6 +18,7 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "qfileiconprovider.h"
+#include <private/qabstractfileiconprovider_p.h>
#include <QtCore/qstring.h>
#include <QtGui/qicon.h>
#include <QtWidgets/qstyle.h>
@@ -62,7 +27,7 @@ QT_BEGIN_NAMESPACE
class QFileInfo;
-class QFileIconProviderPrivate
+class QFileIconProviderPrivate : public QAbstractFileIconProviderPrivate
{
Q_DECLARE_PUBLIC(QFileIconProvider)
@@ -71,9 +36,7 @@ public:
QIcon getIcon(QStyle::StandardPixmap name) const;
QIcon getIcon(const QFileInfo &fi) const;
- QFileIconProvider *q_ptr;
const QString homePath;
- QFileIconProvider::Options options;
private:
mutable QIcon file;
diff --git a/src/widgets/itemviews/qheaderview.cpp b/src/widgets/itemviews/qheaderview.cpp
index 790f305463..9ce09dbacc 100644
--- a/src/widgets/itemviews/qheaderview.cpp
+++ b/src/widgets/itemviews/qheaderview.cpp
@@ -1,63 +1,30 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qheaderview.h"
+#include <qabstractitemdelegate.h>
+#include <qapplication.h>
#include <qbitarray.h>
#include <qbrush.h>
#include <qdebug.h>
#include <qevent.h>
+#include <qlist.h>
#include <qpainter.h>
#include <qscrollbar.h>
-#include <qtooltip.h>
-#if QT_CONFIG(whatsthis)
-#include <qwhatsthis.h>
-#endif
#include <qstyle.h>
#include <qstyleoption.h>
-#include <qvector.h>
-#include <qapplication.h>
+#if QT_CONFIG(tooltip)
+#include <qtooltip.h>
+#endif
#include <qvarlengtharray.h>
-#include <qabstractitemdelegate.h>
#include <qvariant.h>
+#if QT_CONFIG(whatsthis)
+#include <qwhatsthis.h>
+#endif
#include <private/qheaderview_p.h>
#include <private/qabstractitemmodel_p.h>
+#include <private/qabstractitemdelegate_p.h>
#ifndef QT_NO_DATASTREAM
#include <qdatastream.h>
@@ -328,6 +295,8 @@ QHeaderView::QHeaderView(QHeaderViewPrivate &dd,
QHeaderView::~QHeaderView()
{
+ Q_D(QHeaderView);
+ d->disconnectModel();
}
/*!
@@ -355,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;
@@ -451,7 +387,7 @@ Qt::Orientation QHeaderView::orientation() const
int QHeaderView::offset() const
{
Q_D(const QHeaderView);
- return d->offset;
+ return d->headerOffset;
}
/*!
@@ -465,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
@@ -624,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;
@@ -714,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;
@@ -1013,7 +949,7 @@ bool QHeaderView::isSectionHidden(int logicalIndex) const
int QHeaderView::hiddenSectionCount() const
{
Q_D(const QHeaderView);
- return d->hiddenSectionSize.count();
+ return d->hiddenSectionSize.size();
}
/*!
@@ -1094,7 +1030,7 @@ int QHeaderView::visualIndex(int logicalIndex) const
if (d->visualIndices.isEmpty()) { // nothing has been moved, so we have no mapping
if (logicalIndex < d->sectionCount())
return logicalIndex;
- } else if (logicalIndex < d->visualIndices.count()) {
+ } else if (logicalIndex < d->visualIndices.size()) {
int visual = d->visualIndices.at(logicalIndex);
Q_ASSERT(visual < d->sectionCount());
return visual;
@@ -1120,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);
@@ -1140,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);
@@ -1170,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.
@@ -1189,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);
@@ -1204,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);
@@ -1465,6 +1396,41 @@ Qt::SortOrder QHeaderView::sortIndicatorOrder() const
}
/*!
+ \property QHeaderView::sortIndicatorClearable
+ \brief Whether the sort indicator can be cleared by clicking on a section multiple times
+ \since 6.1
+
+ This property controls whether the user is able to remove the
+ sorting indicator on a given section by clicking on the section
+ multiple times. Normally, clicking on a section will simply change
+ the sorting order for that section. By setting this property to
+ true, the sorting indicator will be cleared after alternating to
+ ascending and descending; this will typically restore the original
+ sorting of a model.
+
+ Setting this property to true has no effect unless
+ sectionsClickable() is also true (which is the default for certain
+ views, for instance QTableView, or is automatically set when making
+ a view sortable, for instance by calling
+ QTreeView::setSortingEnabled).
+*/
+
+void QHeaderView::setSortIndicatorClearable(bool clearable)
+{
+ Q_D(QHeaderView);
+ if (d->sortIndicatorClearable == clearable)
+ return;
+ d->sortIndicatorClearable = clearable;
+ emit sortIndicatorClearableChanged(clearable);
+}
+
+bool QHeaderView::isSortIndicatorClearable() const
+{
+ Q_D(const QHeaderView);
+ return d->sortIndicatorClearable;
+}
+
+/*!
\property QHeaderView::stretchLastSection
\brief whether the last visible section in the header takes up all the
available space
@@ -1570,8 +1536,7 @@ void QHeaderView::resetDefaultSectionSize()
\brief the minimum size of the header sections.
The minimum section size is the smallest section size allowed. If the
- minimum section size is set to -1, QHeaderView will use the maximum of
- the \l{QApplication::globalStrut()}{global strut} or the
+ minimum section size is set to -1, QHeaderView will use the
\l{fontMetrics()}{font metrics} size.
This property is honored by all \l{ResizeMode}{resize modes}.
@@ -1582,11 +1547,10 @@ int QHeaderView::minimumSectionSize() const
{
Q_D(const QHeaderView);
if (d->minimumSectionSize == -1) {
- QSize strut = QApplication::globalStrut();
int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, nullptr, this);
if (d->orientation == Qt::Horizontal)
- return qMax(strut.width(), (fontMetrics().maxWidth() + margin));
- return qMax(strut.height(), (fontMetrics().height() + margin));
+ return fontMetrics().maxWidth() + margin;
+ return fontMetrics().height() + margin;
}
return d->minimumSectionSize;
}
@@ -1742,6 +1706,7 @@ QByteArray QHeaderView::saveState() const
Q_D(const QHeaderView);
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
+ stream.setVersion(QDataStream::Qt_5_0);
stream << QHeaderViewPrivate::VersionMarker;
stream << 0; // current version is 0
d->write(stream);
@@ -1761,21 +1726,27 @@ bool QHeaderView::restoreState(const QByteArray &state)
Q_D(QHeaderView);
if (state.isEmpty())
return false;
- QByteArray data = state;
- QDataStream stream(&data, QIODevice::ReadOnly);
- int marker;
- int ver;
- stream >> marker;
- stream >> ver;
- if (stream.status() != QDataStream::Ok
+
+ for (const auto dataStreamVersion : {QDataStream::Qt_5_0, QDataStream::Qt_6_0}) {
+
+ QByteArray data = state;
+ QDataStream stream(&data, QIODevice::ReadOnly);
+ stream.setVersion(dataStreamVersion);
+ int marker;
+ int ver;
+ stream >> marker;
+ stream >> ver;
+ if (stream.status() != QDataStream::Ok
|| marker != QHeaderViewPrivate::VersionMarker
- || ver != 0) // current version is 0
- return false;
+ || ver != 0) { // current version is 0
+ return false;
+ }
- if (d->read(stream)) {
- emit sortIndicatorChanged(d->sortIndicatorSection, d->sortIndicatorOrder );
- d->viewport->update();
- return true;
+ if (d->read(stream)) {
+ emit sortIndicatorChanged(d->sortIndicatorSection, d->sortIndicatorOrder );
+ d->viewport->update();
+ return true;
+ }
}
return false;
}
@@ -1873,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();
@@ -1904,10 +1876,10 @@ void QHeaderView::sectionsInserted(const QModelIndex &parent,
QHeaderViewPrivate::SectionItem section(d->defaultSectionSize, d->globalResizeMode);
d->sectionStartposRecalc = true;
- if (d->sectionItems.isEmpty() || insertAt >= d->sectionItems.count()) {
+ if (d->sectionItems.isEmpty() || insertAt >= d->sectionItems.size()) {
int insertLength = d->defaultSectionSize * insertCount;
d->length += insertLength;
- d->sectionItems.insert(d->sectionItems.count(), insertCount, section); // append
+ d->sectionItems.insert(d->sectionItems.size(), insertCount, section); // append
} else {
// separate them out into their own sections
int insertLength = d->defaultSectionSize * insertCount;
@@ -1930,8 +1902,8 @@ void QHeaderView::sectionsInserted(const QModelIndex &parent,
// update mapping
if (!d->visualIndices.isEmpty() && !d->logicalIndices.isEmpty()) {
- Q_ASSERT(d->visualIndices.count() == d->logicalIndices.count());
- int mappingCount = d->visualIndices.count();
+ Q_ASSERT(d->visualIndices.size() == d->logicalIndices.size());
+ int mappingCount = d->visualIndices.size();
for (int i = 0; i < mappingCount; ++i) {
if (d->visualIndices.at(i) >= logicalFirst)
d->visualIndices[i] += insertCount;
@@ -1997,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)
@@ -2021,7 +1993,7 @@ void QHeaderViewPrivate::_q_sectionsRemoved(const QModelIndex &parent,
if (logicalFirst == logicalLast) { // Remove just one index.
int l = logicalFirst;
int visual = visualIndices.at(l);
- Q_ASSERT(sectionCount() == logicalIndices.count());
+ Q_ASSERT(sectionCount() == logicalIndices.size());
for (int v = 0; v < sectionCount(); ++v) {
if (v > visual) {
int logical = logicalIndices.at(v);
@@ -2036,17 +2008,17 @@ void QHeaderViewPrivate::_q_sectionsRemoved(const QModelIndex &parent,
removeSectionsFromSectionItems(visual, visual);
} else {
sectionStartposRecalc = true; // We will need to recalc positions after removing items
- for (int u = 0; u < sectionItems.count(); ++u) // Store section info
+ for (int u = 0; u < sectionItems.size(); ++u) // Store section info
sectionItems.at(u).tmpLogIdx = logicalIndices.at(u);
- for (int v = sectionItems.count() - 1; v >= 0; --v) { // Remove the sections
+ for (int v = sectionItems.size() - 1; v >= 0; --v) { // Remove the sections
if (logicalFirst <= sectionItems.at(v).tmpLogIdx && sectionItems.at(v).tmpLogIdx <= logicalLast)
removeSectionsFromSectionItems(v, v);
}
- visualIndices.resize(sectionItems.count());
- logicalIndices.resize(sectionItems.count());
+ visualIndices.resize(sectionItems.size());
+ logicalIndices.resize(sectionItems.size());
int* visual_data = visualIndices.data();
int* logical_data = logicalIndices.data();
- for (int w = 0; w < sectionItems.count(); ++w) { // Restore visual and logical indexes
+ for (int w = 0; w < sectionItems.size(); ++w) { // Restore visual and logical indexes
int logindex = sectionItems.at(w).tmpLogIdx;
if (logindex > logicalFirst)
logindex -= changeCount;
@@ -2083,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))
@@ -2119,9 +2095,9 @@ void QHeaderViewPrivate::_q_sectionsAboutToBeChanged(const QList<QPersistentMode
return;
layoutChangePersistentSections.clear();
- layoutChangePersistentSections.reserve(std::min(10, sectionItems.count()));
+ layoutChangePersistentSections.reserve(std::min(10, int(sectionItems.size())));
// after layoutChanged another section can be last stretched section
- if (stretchLastSection && lastSectionLogicalIdx >= 0 && lastSectionLogicalIdx < sectionItems.count()) {
+ if (stretchLastSection && lastSectionLogicalIdx >= 0 && lastSectionLogicalIdx < sectionItems.size()) {
const int visual = visualIndex(lastSectionLogicalIdx);
if (visual >= 0 && visual < sectionItems.size()) {
auto &itemRef = sectionItems[visual];
@@ -2149,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))
@@ -2180,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
@@ -2216,7 +2192,7 @@ void QHeaderViewPrivate::_q_sectionsChanged(const QList<QPersistentModelIndex> &
: index.row());
// the new visualIndices are already adjusted / reset by initializeSections()
const int newVisualIndex = visualIndex(newLogicalIndex);
- if (newVisualIndex < sectionItems.count()) {
+ if (newVisualIndex < sectionItems.size()) {
auto &newSection = sectionItems[newVisualIndex];
newSection = item.section;
@@ -2281,7 +2257,7 @@ void QHeaderView::initializeSections(int start, int end)
int newCount = end + 1;
d->removeSectionsFromSectionItems(newCount, d->sectionCount() - 1);
if (!d->hiddenSectionSize.isEmpty()) {
- if (oldCount - newCount > d->hiddenSectionSize.count()) {
+ if (oldCount - newCount > d->hiddenSectionSize.size()) {
for (int i = end + 1; i < d->sectionCount(); ++i)
d->hiddenSectionSize.remove(i);
} else {
@@ -2327,7 +2303,7 @@ void QHeaderView::initializeSections(int start, int end)
d->contentsSections = newSectionCount;
if (newSectionCount > oldCount)
- d->createSectionItems(start, end, (end - start + 1) * d->defaultSectionSize, d->globalResizeMode);
+ d->createSectionItems(start, end, d->defaultSectionSize, d->globalResizeMode);
//Q_ASSERT(d->headerLength() == d->length);
if (d->sectionCount() != oldCount)
@@ -2371,7 +2347,7 @@ bool QHeaderView::event(QEvent *e)
switch (e->type()) {
case QEvent::HoverEnter: {
QHoverEvent *he = static_cast<QHoverEvent*>(e);
- d->hover = logicalIndexAt(he->pos());
+ d->hover = logicalIndexAt(he->position().toPoint());
if (d->hover != -1)
updateSection(d->hover);
break; }
@@ -2384,7 +2360,7 @@ bool QHeaderView::event(QEvent *e)
case QEvent::HoverMove: {
QHoverEvent *he = static_cast<QHoverEvent*>(e);
int oldHover = d->hover;
- d->hover = logicalIndexAt(he->pos());
+ d->hover = logicalIndexAt(he->position().toPoint());
if (d->hover != oldHover) {
if (oldHover != -1)
updateSection(oldHover);
@@ -2478,7 +2454,7 @@ void QHeaderView::paintEvent(QPaintEvent *e)
}
QStyleOption opt;
- opt.init(this);
+ opt.initFrom(this);
// Paint the area beyond where there are indexes
if (d->reverse()) {
opt.state |= QStyle::State_Horizontal;
@@ -2506,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;
}
@@ -2524,11 +2500,11 @@ void QHeaderView::mousePressEvent(QMouseEvent *e)
Q_D(QHeaderView);
if (d->state != QHeaderViewPrivate::NoState || e->button() != Qt::LeftButton)
return;
- int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
+ int pos = d->orientation == Qt::Horizontal ? e->position().toPoint().x() : e->position().toPoint().y();
int handle = d->sectionHandleAt(pos);
d->originalSize = -1; // clear the stored original size
if (handle == -1) {
- d->pressed = logicalIndexAt(pos);
+ d->firstPressed = d->pressed = logicalIndexAt(pos);
if (d->clickableSections)
emit sectionPressed(d->pressed);
@@ -2537,7 +2513,8 @@ void QHeaderView::mousePressEvent(QMouseEvent *e)
acceptMoveSection = false; // Do not allow moving the tree nod
if (acceptMoveSection) {
- d->section = d->target = d->pressed;
+ d->target = -1;
+ d->section = d->pressed;
if (d->section == -1)
return;
d->state = QHeaderViewPrivate::MoveSection;
@@ -2566,7 +2543,7 @@ void QHeaderView::mousePressEvent(QMouseEvent *e)
void QHeaderView::mouseMoveEvent(QMouseEvent *e)
{
Q_D(QHeaderView);
- int pos = d->orientation == Qt::Horizontal ? e->x() : e->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) {
@@ -2576,7 +2553,7 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
// just before the mouseReleaseEvent and resets the state. This prevents
// column dragging from working. So this code is disabled under Cocoa.
d->state = QHeaderViewPrivate::NoState;
- d->pressed = -1;
+ d->firstPressed = d->pressed = -1;
}
switch (d->state) {
case QHeaderViewPrivate::ResizeSection: {
@@ -2594,8 +2571,10 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
return;
}
case QHeaderViewPrivate::MoveSection: {
- if (d->shouldAutoScroll(e->pos()))
+ 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()
@@ -2607,27 +2586,31 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
if (visual == 0 && logicalIndex(0) == 0 && !d->allowUserMoveOfSection0)
return;
- 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;
if (visual < moving) {
- if (pos < posThreshold)
+ if (checkPos < posThreshold)
d->target = d->logicalIndex(visual);
else
d->target = d->logicalIndex(visual + 1);
} else if (visual > moving) {
- if (pos > posThreshold)
+ if (checkPos > posThreshold)
d->target = d->logicalIndex(visual);
else
d->target = d->logicalIndex(visual - 1);
} else {
d->target = d->section;
}
+ if (oldTarget != d->target || oldTarget == -1)
+ d->updateSectionsBeforeAfter(d->target);
d->updateSectionIndicator(d->section, pos);
}
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)
@@ -2678,7 +2661,7 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
void QHeaderView::mouseReleaseEvent(QMouseEvent *e)
{
Q_D(QHeaderView);
- int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
+ int pos = d->orientation == Qt::Horizontal ? e->position().toPoint().x() : e->position().toPoint().y();
switch (d->state) {
case QHeaderViewPrivate::MoveSection:
if (true
@@ -2693,6 +2676,8 @@ void QHeaderView::mouseReleaseEvent(QMouseEvent *e)
moveSection(from, to);
d->section = d->target = -1;
d->updateSectionIndicator(d->section, pos);
+ if (from == to)
+ d->updateSectionsBeforeAfter(from);
break;
} // not moving
Q_FALLTHROUGH();
@@ -2705,9 +2690,27 @@ void QHeaderView::mouseReleaseEvent(QMouseEvent *e)
case QHeaderViewPrivate::NoState:
if (d->clickableSections) {
int section = logicalIndexAt(pos);
- if (section != -1 && section == d->pressed) {
- d->flipSortIndicator(section);
- emit sectionClicked(section);
+ if (section != -1 && section == d->firstPressed) {
+ QRect firstPressedSectionRect;
+ switch (d->orientation) {
+ case Qt::Horizontal:
+ firstPressedSectionRect.setRect(sectionViewportPosition(d->firstPressed),
+ 0,
+ sectionSize(d->firstPressed),
+ d->viewport->height());
+ break;
+ case Qt::Vertical:
+ firstPressedSectionRect.setRect(0,
+ sectionViewportPosition(d->firstPressed),
+ d->viewport->width(),
+ sectionSize(d->firstPressed));
+ break;
+ };
+
+ if (firstPressedSectionRect.contains(e->position().toPoint())) {
+ d->flipSortIndicator(section);
+ emit sectionClicked(section);
+ }
}
if (d->pressed != -1)
updateSection(d->pressed);
@@ -2721,7 +2724,7 @@ void QHeaderView::mouseReleaseEvent(QMouseEvent *e)
break;
}
d->state = QHeaderViewPrivate::NoState;
- d->pressed = -1;
+ d->firstPressed = d->pressed = -1;
}
/*!
@@ -2731,7 +2734,7 @@ void QHeaderView::mouseReleaseEvent(QMouseEvent *e)
void QHeaderView::mouseDoubleClickEvent(QMouseEvent *e)
{
Q_D(QHeaderView);
- int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
+ int pos = d->orientation == Qt::Horizontal ? e->position().toPoint().x() : e->position().toPoint().y();
int handle = d->sectionHandleAt(pos);
if (handle > -1 && sectionResizeMode(handle) == Interactive) {
emit sectionHandleDoubleClicked(handle);
@@ -2746,7 +2749,7 @@ void QHeaderView::mouseDoubleClickEvent(QMouseEvent *e)
}
#endif
} else {
- emit sectionDoubleClicked(logicalIndexAt(e->pos()));
+ emit sectionDoubleClicked(logicalIndexAt(e->position().toPoint()));
}
}
@@ -2758,7 +2761,7 @@ bool QHeaderView::viewportEvent(QEvent *e)
{
Q_D(QHeaderView);
switch (e->type()) {
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::ToolTip: {
QHelpEvent *he = static_cast<QHelpEvent*>(e);
int logical = logicalIndexAt(he->pos());
@@ -2833,23 +2836,26 @@ bool QHeaderView::viewportEvent(QEvent *e)
}
/*!
- Paints the section specified by the given \a logicalIndex, using the given
- \a painter and \a rect.
+ \fn void QHeaderView::initStyleOptionForIndex(QStyleOptionHeader *option, int logicalIndex) const
+ \since 6.0
- Normally, you do not have to call this function.
+ Initializes the style \a option from the specified \a logicalIndex.
+ This function is called by the default implementation of paintSection after
+ initStyleOption has been called.
+
+ \sa paintSection(), initStyleOption()
*/
-void QHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
+void QHeaderView::initStyleOptionForIndex(QStyleOptionHeader *option, int logicalIndex) const
{
Q_D(const QHeaderView);
- if (!rect.isValid())
+
+ if (!option)
return;
- // get the state of the section
- QStyleOptionHeader opt;
- initStyleOption(&opt);
+ QStyleOptionHeader &opt = *option;
+ QStyleOptionHeaderV2 *optV2 = qstyleoption_cast<QStyleOptionHeaderV2*>(option);
+
QStyle::State state = QStyle::State_None;
- if (isEnabled())
- state |= QStyle::State_Enabled;
if (window()->isActiveWindow())
state |= QStyle::State_Active;
if (d->clickableSections) {
@@ -2863,7 +2869,6 @@ void QHeaderView::paintSection(QPainter *painter, const QRect &rect, int logical
if (d->isSectionSelected(logicalIndex))
state |= QStyle::State_Sunken;
}
-
}
if (isSortIndicatorShown() && sortIndicatorSection() == logicalIndex)
opt.sortIndicator = (sortIndicatorOrder() == Qt::AscendingOrder)
@@ -2872,50 +2877,39 @@ void QHeaderView::paintSection(QPainter *painter, const QRect &rect, int logical
// setup the style options structure
QVariant textAlignment = d->model->headerData(logicalIndex, d->orientation,
Qt::TextAlignmentRole);
- opt.rect = rect;
opt.section = logicalIndex;
opt.state |= state;
- opt.textAlignment = Qt::Alignment(textAlignment.isValid()
- ? Qt::Alignment(textAlignment.toInt())
- : d->defaultAlignment);
+ opt.textAlignment = textAlignment.isValid()
+ ? QtPrivate::legacyFlagValueFromModelData<Qt::Alignment>(textAlignment)
+ : d->defaultAlignment;
opt.iconAlignment = Qt::AlignVCenter;
opt.text = d->model->headerData(logicalIndex, d->orientation,
Qt::DisplayRole).toString();
- int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, nullptr, this);
-
- const Qt::Alignment headerArrowAlignment = static_cast<Qt::Alignment>(style()->styleHint(QStyle::SH_Header_ArrowAlignment, nullptr, this));
- const bool isHeaderArrowOnTheSide = headerArrowAlignment & Qt::AlignVCenter;
- if (isSortIndicatorShown() && sortIndicatorSection() == logicalIndex && isHeaderArrowOnTheSide)
- margin += style()->pixelMetric(QStyle::PM_HeaderMarkSize, nullptr, this);
-
const QVariant variant = d->model->headerData(logicalIndex, d->orientation,
Qt::DecorationRole);
opt.icon = qvariant_cast<QIcon>(variant);
if (opt.icon.isNull())
opt.icon = qvariant_cast<QPixmap>(variant);
- if (!opt.icon.isNull()) // see CT_HeaderSection
- margin += style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, this) +
- style()->pixelMetric(QStyle::PM_HeaderMargin, nullptr, this);
- if (d->textElideMode != Qt::ElideNone) {
- const QRect textRect = style()->subElementRect(QStyle::SE_HeaderLabel, &opt, this);
- opt.text = opt.fontMetrics.elidedText(opt.text, d->textElideMode, textRect.width() - margin);
- }
+ QVariant var = d->model->headerData(logicalIndex, d->orientation,
+ Qt::FontRole);
+ if (var.isValid() && var.canConvert<QFont>())
+ opt.fontMetrics = QFontMetrics(qvariant_cast<QFont>(var));
+ if (optV2)
+ optV2->textElideMode = d->textElideMode;
QVariant foregroundBrush = d->model->headerData(logicalIndex, d->orientation,
Qt::ForegroundRole);
if (foregroundBrush.canConvert<QBrush>())
opt.palette.setBrush(QPalette::ButtonText, qvariant_cast<QBrush>(foregroundBrush));
- QPointF oldBO = painter->brushOrigin();
QVariant backgroundBrush = d->model->headerData(logicalIndex, d->orientation,
Qt::BackgroundRole);
if (backgroundBrush.canConvert<QBrush>()) {
opt.palette.setBrush(QPalette::Button, qvariant_cast<QBrush>(backgroundBrush));
opt.palette.setBrush(QPalette::Window, qvariant_cast<QBrush>(backgroundBrush));
- painter->setBrushOrigin(opt.rect.topLeft());
}
// the section position
@@ -2943,9 +2937,44 @@ void QHeaderView::paintSection(QPainter *painter, const QRect &rect, int logical
opt.selectedPosition = QStyleOptionHeader::NextIsSelected;
else
opt.selectedPosition = QStyleOptionHeader::NotAdjacent;
- // draw the section
- style()->drawControl(QStyle::CE_Header, &opt, painter, this);
+ if (optV2)
+ optV2->isSectionDragTarget = d->target == logicalIndex;
+}
+
+/*!
+ Paints the section specified by the given \a logicalIndex, using the given
+ \a painter and \a rect.
+
+ Normally, you do not have to call this function.
+*/
+
+void QHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
+{
+ if (!rect.isValid())
+ return;
+
+ QStyleOptionHeaderV2 opt;
+ QPointF oldBO = painter->brushOrigin();
+
+ initStyleOption(&opt);
+ QBrush oBrushButton = opt.palette.brush(QPalette::Button);
+ QBrush oBrushWindow = opt.palette.brush(QPalette::Window);
+
+ initStyleOptionForIndex(&opt, logicalIndex);
+ // We set rect here. If it needs to be changed it can be changed by overriding this function
+ opt.rect = rect;
+
+ QBrush nBrushButton = opt.palette.brush(QPalette::Button);
+ QBrush nBrushWindow = opt.palette.brush(QPalette::Window);
+
+ // If relevant brushes are not the same as from the regular widgets we set the brush origin
+ if (oBrushButton != nBrushButton || oBrushWindow != nBrushWindow) {
+ painter->setBrushOrigin(opt.rect.topLeft());
+ }
+
+ // draw the section.
+ style()->drawControl(QStyle::CE_Header, &opt, painter, this);
painter->setBrushOrigin(oldBO);
}
@@ -2969,7 +2998,7 @@ QSize QHeaderView::sectionSizeFromContents(int logicalIndex) const
return qvariant_cast<QSize>(variant);
// otherwise use the contents
- QStyleOptionHeader opt;
+ QStyleOptionHeaderV2 opt;
initStyleOption(&opt);
opt.section = logicalIndex;
QVariant var = d->model->headerData(logicalIndex, d->orientation,
@@ -3003,7 +3032,7 @@ int QHeaderView::horizontalOffset() const
{
Q_D(const QHeaderView);
if (d->orientation == Qt::Horizontal)
- return d->offset;
+ return d->headerOffset;
return 0;
}
@@ -3018,7 +3047,7 @@ int QHeaderView::verticalOffset() const
{
Q_D(const QHeaderView);
if (d->orientation == Qt::Vertical)
- return d->offset;
+ return d->headerOffset;
return 0;
}
@@ -3050,7 +3079,8 @@ void QHeaderView::scrollContentsBy(int dx, int dy)
\reimp
\internal
*/
-void QHeaderView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
+void QHeaderView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &roles)
{
Q_D(QHeaderView);
if (!roles.isEmpty()) {
@@ -3318,7 +3348,7 @@ void QHeaderViewPrivate::setupSectionIndicator(int section, int position)
sectionIndicator->resize(w, h);
#endif
- const qreal pixmapDevicePixelRatio = q->devicePixelRatioF();
+ const qreal pixmapDevicePixelRatio = q->devicePixelRatio();
QPixmap pm(QSize(w, h) * pixmapDevicePixelRatio);
pm.setDevicePixelRatio(pixmapDevicePixelRatio);
pm.fill(QColor(0, 0, 0, 45));
@@ -3369,7 +3399,7 @@ void QHeaderViewPrivate::updateSectionIndicator(int section, int position)
useful for subclasses when they need a QStyleOptionHeader, but do not want
to fill in all the information themselves.
- \sa QStyleOption::initFrom()
+ \sa QStyleOption::initFrom(), initStyleOptionForIndex()
*/
void QHeaderView::initStyleOption(QStyleOptionHeader *option) const
{
@@ -3384,10 +3414,17 @@ void QHeaderView::initStyleOption(QStyleOptionHeader *option) const
option->section = 0;
}
+void QHeaderView::initStyleOption(QStyleOptionFrame *option) const
+{
+ // The QFrame version is only here to avoid compiler warnings.
+ // If invoked we just pass it on to the base class.
+ QFrame::initStyleOption(option);
+}
+
bool QHeaderViewPrivate::isSectionSelected(int section) const
{
int i = section * 2;
- if (i < 0 || i >= sectionSelected.count())
+ if (i < 0 || i >= sectionSelected.size())
return false;
if (sectionSelected.testBit(i)) // if the value was cached
return sectionSelected.testBit(i + 1);
@@ -3590,8 +3627,7 @@ void QHeaderViewPrivate::resizeSections(QHeaderView::ResizeMode globalMode, bool
//Q_ASSERT(newSectionLength > 0);
if ((previousSectionResizeMode != newSectionResizeMode
|| previousSectionLength != newSectionLength) && i > 0) {
- int spanLength = (i - spanStartSection) * previousSectionLength;
- createSectionItems(spanStartSection, i - 1, spanLength, previousSectionResizeMode);
+ createSectionItems(spanStartSection, i - 1, previousSectionLength, previousSectionResizeMode);
//Q_ASSERT(headerLength() == length);
spanStartSection = i;
}
@@ -3604,17 +3640,15 @@ void QHeaderViewPrivate::resizeSections(QHeaderView::ResizeMode globalMode, bool
}
createSectionItems(spanStartSection, sectionCount() - 1,
- (sectionCount() - spanStartSection) * previousSectionLength,
- previousSectionResizeMode);
+ previousSectionLength, previousSectionResizeMode);
//Q_ASSERT(headerLength() == length);
resizeRecursionBlock = false;
viewport->update();
}
-void QHeaderViewPrivate::createSectionItems(int start, int end, int size, QHeaderView::ResizeMode mode)
+void QHeaderViewPrivate::createSectionItems(int start, int end, int sizePerSection, QHeaderView::ResizeMode mode)
{
- int sizePerSection = size / (end - start + 1);
- if (end >= sectionItems.count()) {
+ if (end >= sectionItems.size()) {
sectionItems.resize(end + 1);
sectionStartposRecalc = true;
}
@@ -3630,7 +3664,7 @@ void QHeaderViewPrivate::createSectionItems(int start, int end, int size, QHeade
void QHeaderViewPrivate::removeSectionsFromSectionItems(int start, int end)
{
// remove sections
- sectionStartposRecalc |= (end != sectionItems.count() - 1);
+ sectionStartposRecalc |= (end != sectionItems.size() - 1);
int removedlength = 0;
for (int u = start; u <= end; ++u)
removedlength += sectionItems.at(u).size;
@@ -3652,22 +3686,47 @@ void QHeaderViewPrivate::clear()
}
}
+static Qt::SortOrder flipOrder(Qt::SortOrder order)
+{
+ switch (order) {
+ case Qt::AscendingOrder:
+ return Qt::DescendingOrder;
+ case Qt::DescendingOrder:
+ return Qt::AscendingOrder;
+ };
+ Q_UNREACHABLE_RETURN(Qt::AscendingOrder);
+};
+
void QHeaderViewPrivate::flipSortIndicator(int section)
{
Q_Q(QHeaderView);
Qt::SortOrder sortOrder;
if (sortIndicatorSection == section) {
- sortOrder = (sortIndicatorOrder == Qt::DescendingOrder) ? Qt::AscendingOrder : Qt::DescendingOrder;
+ if (sortIndicatorClearable) {
+ const Qt::SortOrder defaultSortOrder = defaultSortOrderForSection(section);
+ if (sortIndicatorOrder == defaultSortOrder) {
+ sortOrder = flipOrder(sortIndicatorOrder);
+ } else {
+ section = -1;
+ sortOrder = Qt::AscendingOrder;
+ }
+ } else {
+ sortOrder = flipOrder(sortIndicatorOrder);
+ }
} else {
- const QVariant value = model->headerData(section, orientation, Qt::InitialSortOrderRole);
- if (value.canConvert(QVariant::Int))
- sortOrder = static_cast<Qt::SortOrder>(value.toInt());
- else
- sortOrder = Qt::AscendingOrder;
+ sortOrder = defaultSortOrderForSection(section);
}
q->setSortIndicator(section, sortOrder);
}
+Qt::SortOrder QHeaderViewPrivate::defaultSortOrderForSection(int section) const
+{
+ const QVariant value = model->headerData(section, orientation, Qt::InitialSortOrderRole);
+ if (value.canConvert<int>())
+ return static_cast<Qt::SortOrder>(value.toInt());
+ return Qt::AscendingOrder;
+}
+
void QHeaderViewPrivate::cascadingResize(int visual, int newSize)
{
Q_Q(QHeaderView);
@@ -3712,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;
}
@@ -3735,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;
@@ -3792,7 +3847,7 @@ void QHeaderViewPrivate::setDefaultSectionSize(int size)
customDefaultSectionSize = true;
if (state == QHeaderViewPrivate::ResizeSection)
preventCursorChangeInSetOffset = true;
- for (int i = 0; i < sectionItems.count(); ++i) {
+ for (int i = 0; i < sectionItems.size(); ++i) {
QHeaderViewPrivate::SectionItem &section = sectionItems[i];
if (hiddenSectionSize.isEmpty() || !isVisualIndexHidden(i)) { // resize on not hidden.
const int newSize = size;
@@ -3861,7 +3916,7 @@ int QHeaderViewPrivate::headerVisualIndexAt(int position) const
if (sectionStartposRecalc)
recalcSectionStartPos();
int startidx = 0;
- int endidx = sectionItems.count() - 1;
+ int endidx = sectionItems.size() - 1;
while (startidx <= endidx) {
int middle = (endidx + startidx) / 2;
if (sectionItems.at(middle).calculated_startpos > position) {
@@ -3884,7 +3939,7 @@ void QHeaderViewPrivate::setHeaderSectionResizeMode(int visual, QHeaderView::Res
QHeaderView::ResizeMode QHeaderViewPrivate::headerSectionResizeMode(int visual) const
{
- if (visual < 0 || visual >= sectionItems.count())
+ if (visual < 0 || visual >= sectionItems.size())
return globalResizeMode;
return static_cast<QHeaderView::ResizeMode>(sectionItems.at(visual).resizeMode);
}
@@ -3892,7 +3947,7 @@ QHeaderView::ResizeMode QHeaderViewPrivate::headerSectionResizeMode(int visual)
void QHeaderViewPrivate::setGlobalHeaderResizeMode(QHeaderView::ResizeMode mode)
{
globalResizeMode = mode;
- for (int i = 0; i < sectionItems.count(); ++i)
+ for (int i = 0; i < sectionItems.size(); ++i)
sectionItems[i].resizeMode = mode;
}
@@ -3911,7 +3966,7 @@ int QHeaderViewPrivate::adjustedVisualIndex(int visualIndex) const
if (!hiddenSectionSize.isEmpty()) {
int adjustedVisualIndex = visualIndex;
int currentVisualIndex = 0;
- for (int i = 0; i < sectionItems.count(); ++i) {
+ for (int i = 0; i < sectionItems.size(); ++i) {
if (isVisualIndexHidden(i))
++adjustedVisualIndex;
else
@@ -3937,6 +3992,25 @@ void QHeaderViewPrivate::setScrollOffset(const QScrollBar *scrollBar, QAbstractI
}
}
+void QHeaderViewPrivate::updateSectionsBeforeAfter(int logical)
+{
+ Q_Q(QHeaderView);
+ const int visual = visualIndex(logical);
+ int from = logicalIndex(visual > 1 ? visual - 1 : 0);
+ int to = logicalIndex(visual + 1 >= sectionCount() ? visual : visual + 1);
+ QRect updateRect;
+ if (orientation == Qt::Horizontal) {
+ if (reverse())
+ std::swap(from, to);
+ updateRect = QRect(QPoint(q->sectionViewportPosition(from), 0),
+ QPoint(q->sectionViewportPosition(to) + headerSectionSize(to), viewport->height()));
+ } else {
+ updateRect = QRect(QPoint(0, q->sectionViewportPosition(from)),
+ QPoint(viewport->width(), q->sectionViewportPosition(to) + headerSectionSize(to)));
+ }
+ viewport->update(updateRect);
+}
+
#ifndef QT_NO_DATASTREAM
void QHeaderViewPrivate::write(QDataStream &out) const
{
@@ -3970,6 +4044,7 @@ void QHeaderViewPrivate::write(QDataStream &out) const
out << resizeContentsPrecision;
out << customDefaultSectionSize;
out << lastSectionSize;
+ out << int(sortIndicatorClearable);
}
bool QHeaderViewPrivate::read(QDataStream &in)
@@ -3979,8 +4054,8 @@ bool QHeaderViewPrivate::read(QDataStream &in)
int sortIndicatorSectionIn;
bool sortIndicatorShownIn;
int lengthIn;
- QVector<int> visualIndicesIn;
- QVector<int> logicalIndicesIn;
+ QList<int> visualIndicesIn;
+ QList<int> logicalIndicesIn;
QHash<int, int> hiddenSectionSizeIn;
bool movableSectionsIn;
bool clickableSectionsIn;
@@ -3991,7 +4066,7 @@ bool QHeaderViewPrivate::read(QDataStream &in)
int contentsSectionsIn;
int defaultSectionSizeIn;
int minimumSectionSizeIn;
- QVector<SectionItem> sectionItemsIn;
+ QList<SectionItem> sectionItemsIn;
in >> orient;
in >> order;
@@ -4027,12 +4102,21 @@ bool QHeaderViewPrivate::read(QDataStream &in)
in >> global;
+ // Check parameter consistency
+ // Global orientation out of bounds?
+ if (global < 0 || global > QHeaderView::ResizeToContents)
+ return false;
+
+ // Alignment out of bounds?
+ if (align < 0 || align > Qt::AlignVertical_Mask)
+ return false;
+
in >> sectionItemsIn;
// In Qt4 we had a vector of spans where one span could hold information on more sections.
// Now we have an itemvector where one items contains information about one section
// For backward compatibility with Qt4 we do the following
- QVector<SectionItem> newSectionItems;
- for (int u = 0; u < sectionItemsIn.count(); ++u) {
+ QList<SectionItem> newSectionItems;
+ for (int u = 0; u < sectionItemsIn.size(); ++u) {
int count = sectionItemsIn.at(u).tmpDataStreamSectionCount;
if (count > 1)
sectionItemsIn[u].size /= count;
@@ -4041,25 +4125,25 @@ bool QHeaderViewPrivate::read(QDataStream &in)
}
int sectionItemsLengthTotal = 0;
- for (const SectionItem &section : qAsConst(newSectionItems))
+ for (const SectionItem &section : std::as_const(newSectionItems))
sectionItemsLengthTotal += section.size;
if (sectionItemsLengthTotal != lengthIn)
return false;
const int currentCount = (orient == Qt::Horizontal ? model->columnCount(root) : model->rowCount(root));
- if (newSectionItems.count() < currentCount) {
+ if (newSectionItems.size() < currentCount) {
// we have sections not in the saved state, give them default settings
if (!visualIndicesIn.isEmpty() && !logicalIndicesIn.isEmpty()) {
- for (int i = newSectionItems.count(); i < currentCount; ++i) {
+ for (int i = newSectionItems.size(); i < currentCount; ++i) {
visualIndicesIn.append(i);
logicalIndicesIn.append(i);
}
}
- const int insertCount = currentCount - newSectionItems.count();
+ const int insertCount = currentCount - newSectionItems.size();
const int insertLength = defaultSectionSizeIn * insertCount;
lengthIn += insertLength;
SectionItem section(defaultSectionSizeIn, globalResizeMode);
- newSectionItems.insert(newSectionItems.count(), insertCount, section); // append
+ newSectionItems.insert(newSectionItems.size(), insertCount, section); // append
}
orientation = static_cast<Qt::Orientation>(orient);
@@ -4113,6 +4197,11 @@ bool QHeaderViewPrivate::read(QDataStream &in)
doDelayedResizeSections();
}
+ int inSortIndicatorClearable;
+ in >> inSortIndicatorClearable;
+ if (in.status() == QDataStream::Ok) // we haven't read past end
+ sortIndicatorClearable = inSortIndicatorClearable;
+
return true;
}
diff --git a/src/widgets/itemviews/qheaderview.h b/src/widgets/itemviews/qheaderview.h
index 7e950add1f..bd0050df5e 100644
--- a/src/widgets/itemviews/qheaderview.h
+++ b/src/widgets/itemviews/qheaderview.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QHEADERVIEW_H
#define QHEADERVIEW_H
@@ -55,13 +19,19 @@ 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 WRITE setCascadingSectionResizes)
- Q_PROPERTY(int defaultSectionSize READ defaultSectionSize WRITE setDefaultSectionSize RESET resetDefaultSectionSize)
+ Q_PROPERTY(bool cascadingSectionResizes READ cascadingSectionResizes
+ WRITE setCascadingSectionResizes)
+ Q_PROPERTY(int defaultSectionSize READ defaultSectionSize WRITE setDefaultSectionSize
+ RESET resetDefaultSectionSize)
Q_PROPERTY(int minimumSectionSize READ minimumSectionSize WRITE setMinimumSectionSize)
Q_PROPERTY(int maximumSectionSize READ maximumSectionSize WRITE setMaximumSectionSize)
Q_PROPERTY(Qt::Alignment defaultAlignment READ defaultAlignment WRITE setDefaultAlignment)
+ Q_PROPERTY(bool sortIndicatorClearable READ isSortIndicatorClearable
+ WRITE setSortIndicatorClearable NOTIFY sortIndicatorClearableChanged)
public:
@@ -115,19 +85,11 @@ public:
void setSectionsMovable(bool movable);
bool sectionsMovable() const;
-#if QT_DEPRECATED_SINCE(5, 0)
- inline QT_DEPRECATED void setMovable(bool movable) { setSectionsMovable(movable); }
- inline QT_DEPRECATED bool isMovable() const { return sectionsMovable(); }
-#endif
void setFirstSectionMovable(bool movable);
bool isFirstSectionMovable() const;
void setSectionsClickable(bool clickable);
bool sectionsClickable() const;
-#if QT_DEPRECATED_SINCE(5, 0)
- inline QT_DEPRECATED void setClickable(bool clickable) { setSectionsClickable(clickable); }
- inline QT_DEPRECATED bool isClickable() const { return sectionsClickable(); }
-#endif
void setHighlightSections(bool highlight);
bool highlightSections() const;
@@ -139,15 +101,6 @@ public:
void setResizeContentsPrecision(int precision);
int resizeContentsPrecision() const;
-#if QT_DEPRECATED_SINCE(5, 0)
- inline QT_DEPRECATED void setResizeMode(ResizeMode mode)
- { setSectionResizeMode(mode); }
- inline QT_DEPRECATED void setResizeMode(int logicalindex, ResizeMode mode)
- { setSectionResizeMode(logicalindex, mode); }
- inline QT_DEPRECATED ResizeMode resizeMode(int logicalindex) const
- { return sectionResizeMode(logicalindex); }
-#endif
-
int stretchSectionCount() const;
void setSortIndicatorShown(bool show);
@@ -157,6 +110,9 @@ public:
int sortIndicatorSection() const;
Qt::SortOrder sortIndicatorOrder() const;
+ void setSortIndicatorClearable(bool clearable);
+ bool isSortIndicatorClearable() const;
+
bool stretchLastSection() const;
void setStretchLastSection(bool stretch);
@@ -203,6 +159,7 @@ Q_SIGNALS:
void sectionHandleDoubleClicked(int logicalIndex);
void geometriesChanged();
void sortIndicatorChanged(int logicalIndex, Qt::SortOrder order);
+ void sortIndicatorClearableChanged(bool clearable);
protected Q_SLOTS:
void updateSection(int logicalIndex);
@@ -234,7 +191,8 @@ protected:
void updateGeometries() override;
void scrollContentsBy(int dx, int dy) override;
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>()) override;
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &roles = QList<int>()) override;
void rowsInserted(const QModelIndex &parent, int start, int end) override;
QRect visualRect(const QModelIndex &index) const override;
@@ -246,20 +204,15 @@ protected:
QModelIndex moveCursor(CursorAction, Qt::KeyboardModifiers) override;
void setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags flags) override;
QRegion visualRegionForSelection(const QItemSelection &selection) const override;
- void initStyleOption(QStyleOptionHeader *option) const;
+ virtual void initStyleOptionForIndex(QStyleOptionHeader *option, int logicalIndex) const;
+ virtual void initStyleOption(QStyleOptionHeader *option) const;
friend class QTableView;
friend class QTreeView;
private:
- // ### 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))
+ void initStyleOption(QStyleOptionFrame *option) const override;
+
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 766adef36d..8b214e1d03 100644
--- a/src/widgets/itemviews/qheaderview_p.h
+++ b/src/widgets/itemviews/qheaderview_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QHEADERVIEW_P_H
#define QHEADERVIEW_P_H
@@ -52,6 +16,7 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "qheaderview.h"
#include "private/qabstractitemview_p.h"
#include "QtCore/qbitarray.h"
@@ -60,6 +25,8 @@
#include "QtWidgets/qlabel.h"
#endif
+#include <array>
+
QT_REQUIRE_CONFIG(itemviews);
QT_BEGIN_NAMESPACE
@@ -73,15 +40,17 @@ public:
QHeaderViewPrivate()
: state(NoState),
- offset(0),
+ headerOffset(0),
sortIndicatorOrder(Qt::DescendingOrder),
sortIndicatorSection(0),
sortIndicatorShown(false),
+ sortIndicatorClearable(false),
lastPos(-1),
firstPos(-1),
originalSize(-1),
section(-1),
target(-1),
+ firstPressed(-1),
pressed(-1),
hover(-1),
length(0),
@@ -119,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;
@@ -154,12 +127,12 @@ public:
inline void prepareSectionSelected() {
if (!selectionModel || !selectionModel->hasSelection())
sectionSelected.clear();
- else if (sectionSelected.count() != sectionCount() * 2)
+ else if (sectionSelected.size() != sectionCount() * 2)
sectionSelected.fill(false, sectionCount() * 2);
else sectionSelected.fill(false);
}
- inline int sectionCount() const {return sectionItems.count();}
+ inline int sectionCount() const {return sectionItems.size();}
inline bool reverse() const {
return orientation == Qt::Horizontal && q_func()->isRightToLeft();
@@ -200,8 +173,8 @@ public:
}
inline void initializeIndexMapping() const {
- if (visualIndices.count() != sectionCount()
- || logicalIndices.count() != sectionCount()) {
+ if (visualIndices.size() != sectionCount()
+ || logicalIndices.size() != sectionCount()) {
visualIndices.resize(sectionCount());
logicalIndices.resize(sectionCount());
for (int s = 0; s < sectionCount(); ++s) {
@@ -212,7 +185,7 @@ public:
}
inline void clearCascadingSections() {
- firstCascadingSection = sectionItems.count();
+ firstCascadingSection = sectionItems.size();
lastCascadingSection = 0;
cascadingSectionSize.clear();
}
@@ -246,20 +219,28 @@ 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;
void cascadingResize(int visual, int newSize);
enum State { NoState, ResizeSection, MoveSection, SelectSections, NoClear } state;
- int offset;
+ int headerOffset;
Qt::Orientation orientation;
Qt::SortOrder sortIndicatorOrder;
int sortIndicatorSection;
bool sortIndicatorShown;
+ bool sortIndicatorClearable;
- mutable QVector<int> visualIndices; // visualIndex = visualIndices.at(logicalIndex)
- mutable QVector<int> logicalIndices; // logicalIndex = row or column in the model
+ mutable QList<int> visualIndices; // visualIndex = visualIndices.at(logicalIndex)
+ mutable QList<int> logicalIndices; // logicalIndex = row or column in the model
mutable QBitArray sectionSelected; // from logical index to bit
mutable QHash<int, int> hiddenSectionSize; // from logical index to section size
mutable QHash<int, int> cascadingSectionSize; // from visual index to section size
@@ -274,6 +255,7 @@ public:
int originalSize;
int section; // used for resizing and moving sections
int target;
+ int firstPressed;
int pressed;
int hover;
@@ -329,14 +311,15 @@ public:
#endif
};
- QVector<SectionItem> sectionItems;
+ QList<SectionItem> sectionItems;
struct LayoutChangeItem {
QPersistentModelIndex index;
SectionItem section;
};
- QVector<LayoutChangeItem> layoutChangePersistentSections;
+ QList<LayoutChangeItem> layoutChangePersistentSections;
+ std::array<QMetaObject::Connection, 8> modelConnections;
- void createSectionItems(int start, int end, int size, QHeaderView::ResizeMode mode);
+ void createSectionItems(int start, int end, int sectionSize, QHeaderView::ResizeMode mode);
void removeSectionsFromSectionItems(int start, int end);
void resizeSectionItem(int visualIndex, int oldSize, int newSize);
void setDefaultSectionSize(int size);
@@ -363,7 +346,7 @@ public:
void setHiddenSectionsFromBitVector(const QBitArray &sectionHidden) {
SectionItem *sectionData = sectionItems.data();
- for (int i = 0; i < sectionHidden.count(); ++i)
+ for (int i = 0; i < sectionHidden.size(); ++i)
sectionData[i].isHidden = sectionHidden.at(i);
}
@@ -380,6 +363,7 @@ public:
int viewSectionSizeHint(int logical) const;
int adjustedVisualIndex(int visualIndex) const;
void setScrollOffset(const QScrollBar *scrollBar, QAbstractItemView::ScrollMode scrollMode);
+ void updateSectionsBeforeAfter(int logical);
#ifndef QT_NO_DATASTREAM
void write(QDataStream &out) const;
@@ -388,7 +372,7 @@ public:
};
Q_DECLARE_TYPEINFO(QHeaderViewPrivate::SectionItem, Q_PRIMITIVE_TYPE);
-Q_DECLARE_TYPEINFO(QHeaderViewPrivate::LayoutChangeItem, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QHeaderViewPrivate::LayoutChangeItem, Q_RELOCATABLE_TYPE);
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qitemdelegate.cpp b/src/widgets/itemviews/qitemdelegate.cpp
index daea907963..e4a90278b4 100644
--- a/src/widgets/itemviews/qitemdelegate.cpp
+++ b/src/widgets/itemviews/qitemdelegate.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qitemdelegate.h"
@@ -58,6 +22,7 @@
#include <qmetaobject.h>
#include <qtextlayout.h>
#include <private/qabstractitemdelegate_p.h>
+#include <private/qabstractitemmodel_p.h>
#include <private/qtextengine_p.h>
#include <qdebug.h>
#include <qlocale.h>
@@ -94,7 +59,7 @@ public:
inline static QString replaceNewLine(QString text)
{
- text.replace(QLatin1Char('\n'), QChar::LineSeparator);
+ text.replace(u'\n', QChar::LineSeparator);
return text;
}
@@ -267,7 +232,6 @@ QSizeF QItemDelegatePrivate::doTextLayout(int lineWidth) const
\row \li \l Qt::AccessibleTextRole \li QString
\endomit
\row \li \l Qt::BackgroundRole \li QBrush (\since 4.2)
- \row \li \l Qt::BackgroundColorRole \li QColor (obsolete; use Qt::BackgroundRole instead)
\row \li \l Qt::CheckStateRole \li Qt::CheckState
\row \li \l Qt::DecorationRole \li QIcon, QPixmap and QColor
\row \li \l Qt::DisplayRole \li QString and types with a string representation
@@ -279,7 +243,6 @@ QSizeF QItemDelegatePrivate::doTextLayout(int lineWidth) const
\endomit
\row \li \l Qt::TextAlignmentRole \li Qt::Alignment
\row \li \l Qt::ForegroundRole \li QBrush (\since 4.2)
- \row \li \l Qt::TextColorRole \li QColor (obsolete; use Qt::ForegroundRole instead)
\omit
\row \li \l Qt::ToolTipRole
\row \li \l Qt::WhatsThisRole
@@ -303,8 +266,8 @@ QSizeF QItemDelegatePrivate::doTextLayout(int lineWidth) const
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}.
+ setModelData(), and updateEditorGeometry(). This process is described
+ in the \l{A simple delegate}{Model/View Programming overview documentation}.
\section1 QStyledItemDelegate vs. QItemDelegate
@@ -318,9 +281,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
*/
/*!
@@ -380,8 +341,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,
@@ -414,7 +377,7 @@ void QItemDelegate::paint(QPainter *painter,
if (value.isValid()) {
// ### we need the pixmap to call the virtual function
pixmap = decoration(opt, value);
- if (value.type() == QVariant::Icon) {
+ if (value.userType() == QMetaType::QIcon) {
d->tmp.icon = qvariant_cast<QIcon>(value);
d->tmp.mode = d->iconMode(option.state);
d->tmp.state = d->iconState(option.state);
@@ -434,7 +397,7 @@ void QItemDelegate::paint(QPainter *painter,
Qt::CheckState checkState = Qt::Unchecked;
value = index.data(Qt::CheckStateRole);
if (value.isValid()) {
- checkState = static_cast<Qt::CheckState>(value.toInt());
+ checkState = QtPrivate::legacyEnumValueFromModelData<Qt::CheckState>(value);
checkRect = doCheck(opt, opt.rect, value);
}
@@ -524,19 +487,14 @@ QWidget *QItemDelegate::createEditor(QWidget *parent,
void QItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(editor);
- Q_UNUSED(index);
-#else
QVariant v = index.data(Qt::EditRole);
QByteArray n = editor->metaObject()->userProperty().name();
if (!n.isEmpty()) {
if (!v.isValid())
- v = QVariant(editor->property(n).userType(), (const void *)nullptr);
+ v = QVariant(editor->property(n).metaType());
editor->setProperty(n, v);
}
-#endif
}
/*!
@@ -554,11 +512,6 @@ void QItemDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(model);
- Q_UNUSED(editor);
- Q_UNUSED(index);
-#else
Q_D(const QItemDelegate);
Q_ASSERT(model);
Q_ASSERT(editor);
@@ -568,7 +521,6 @@ void QItemDelegate::setModelData(QWidget *editor,
model->data(index, Qt::EditRole).userType());
if (!n.isEmpty())
model->setData(index, editor->property(n), Qt::EditRole);
-#endif
}
/*!
@@ -697,10 +649,12 @@ void QItemDelegate::drawDisplay(QPainter *painter, const QStyleOptionViewItem &o
|| textRect.height() < textLayoutSize.height())) {
painter->save();
painter->setClipRect(layoutRect);
- d->textLayout.draw(painter, layoutRect.topLeft(), QVector<QTextLayout::FormatRange>(), layoutRect);
+ d->textLayout.draw(painter, layoutRect.topLeft(), QList<QTextLayout::FormatRange>(),
+ layoutRect);
painter->restore();
} else {
- d->textLayout.draw(painter, layoutRect.topLeft(), QVector<QTextLayout::FormatRange>(), layoutRect);
+ d->textLayout.draw(painter, layoutRect.topLeft(), QList<QTextLayout::FormatRange>(),
+ layoutRect);
}
}
@@ -969,12 +923,12 @@ void QItemDelegate::doLayout(const QStyleOptionViewItem &option,
QPixmap QItemDelegate::decoration(const QStyleOptionViewItem &option, const QVariant &variant) const
{
Q_D(const QItemDelegate);
- switch (variant.type()) {
- case QVariant::Icon: {
+ switch (variant.userType()) {
+ case QMetaType::QIcon: {
QIcon::Mode mode = d->iconMode(option.state);
QIcon::State state = d->iconState(option.state);
return qvariant_cast<QIcon>(variant).pixmap(option.decorationSize, mode, state); }
- case QVariant::Color: {
+ case QMetaType::QColor: {
static QPixmap pixmap(option.decorationSize);
pixmap.fill(qvariant_cast<QColor>(variant));
return pixmap; }
@@ -1001,20 +955,6 @@ static QString qPixmapSerial(quint64 i, bool enabled)
return QString((const QChar *)ptr, int(&arr[sizeof(arr) / sizeof(ushort)] - ptr));
}
-#if QT_DEPRECATED_SINCE(5, 13)
-QPixmap *QItemDelegate::selected(const QPixmap &pixmap, const QPalette &palette, bool enabled) const
-{
- const QString key = qPixmapSerial(pixmap.cacheKey(), enabled);
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- QPixmap *pm = QPixmapCache::find(key);
- if (pm)
- return pm;
- selectedPixmap(pixmap, palette, enabled);
- return QPixmapCache::find(key);
-QT_WARNING_POP
-}
-#endif
/*!
\internal
@@ -1031,7 +971,7 @@ QPixmap QItemDelegate::selectedPixmap(const QPixmap &pixmap, const QPalette &pal
QColor color = palette.color(enabled ? QPalette::Normal : QPalette::Disabled,
QPalette::Highlight);
- color.setAlphaF((qreal)0.3);
+ color.setAlphaF(0.3f);
QPainter painter(&img);
painter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
@@ -1060,24 +1000,24 @@ QRect QItemDelegate::rect(const QStyleOptionViewItem &option,
if (role == Qt::CheckStateRole)
return doCheck(option, option.rect, value);
if (value.isValid() && !value.isNull()) {
- switch (value.type()) {
- case QVariant::Invalid:
+ switch (value.userType()) {
+ case QMetaType::UnknownType:
break;
- case QVariant::Pixmap: {
+ case QMetaType::QPixmap: {
const QPixmap &pixmap = qvariant_cast<QPixmap>(value);
- return QRect(QPoint(0, 0), pixmap.size() / pixmap.devicePixelRatio() ); }
- case QVariant::Image: {
+ return QRect(QPoint(0, 0), pixmap.deviceIndependentSize().toSize()); }
+ case QMetaType::QImage: {
const QImage &image = qvariant_cast<QImage>(value);
- return QRect(QPoint(0, 0), image.size() / image.devicePixelRatio() ); }
- case QVariant::Icon: {
+ return QRect(QPoint(0, 0), image.deviceIndependentSize().toSize()); }
+ case QMetaType::QIcon: {
QIcon::Mode mode = d->iconMode(option.state);
QIcon::State state = d->iconState(option.state);
QIcon icon = qvariant_cast<QIcon>(value);
QSize size = icon.actualSize(option.decorationSize, mode, state);
return QRect(QPoint(0, 0), size); }
- case QVariant::Color:
+ case QMetaType::QColor:
return QRect(QPoint(0, 0), option.decorationSize);
- case QVariant::String:
+ case QMetaType::QString:
default: {
const QString text = d->valueToText(value, option);
value = index.data(Qt::FontRole);
@@ -1122,7 +1062,7 @@ QRect QItemDelegate::textRectangle(QPainter * /*painter*/, const QRect &rect,
QSizeF fpSize = d->doTextLayout(rect.width());
const QSize size = QSize(qCeil(fpSize.width()), qCeil(fpSize.height()));
// ###: textRectangle should take style option as argument
- const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
+ const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin, nullptr) + 1;
return QRect(0, 0, size.width() + 2 * textMargin, size.height());
}
@@ -1191,7 +1131,7 @@ bool QItemDelegate::editorEvent(QEvent *event,
QRect emptyRect;
doLayout(option, &checkRect, &emptyRect, &emptyRect, false);
QMouseEvent *me = static_cast<QMouseEvent*>(event);
- if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
+ if (me->button() != Qt::LeftButton || !checkRect.contains(me->position().toPoint()))
return false;
// eat the double click events inside the check rect
@@ -1207,7 +1147,7 @@ bool QItemDelegate::editorEvent(QEvent *event,
return false;
}
- Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
+ Qt::CheckState state = QtPrivate::legacyEnumValueFromModelData<Qt::CheckState>(value);
if (flags & Qt::ItemIsUserTristate)
state = ((Qt::CheckState)((state + 1) % 3));
else
@@ -1234,7 +1174,7 @@ QStyleOptionViewItem QItemDelegate::setOptions(const QModelIndex &index,
// set text alignment
value = index.data(Qt::TextAlignmentRole);
if (value.isValid())
- opt.displayAlignment = Qt::Alignment(value.toInt());
+ opt.displayAlignment = QtPrivate::legacyFlagValueFromModelData<Qt::Alignment>(value);
// set foreground brush
value = index.data(Qt::ForegroundRole);
diff --git a/src/widgets/itemviews/qitemdelegate.h b/src/widgets/itemviews/qitemdelegate.h
index e504615fb2..5ad32e663e 100644
--- a/src/widgets/itemviews/qitemdelegate.h
+++ b/src/widgets/itemviews/qitemdelegate.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QITEMDELEGATE_H
#define QITEMDELEGATE_H
@@ -114,10 +78,6 @@ protected:
QPixmap decoration(const QStyleOptionViewItem &option, const QVariant &variant) const;
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use selectedPixmap() instead")
- QPixmap *selected(const QPixmap &pixmap, const QPalette &palette, bool enabled) const;
-#endif
static QPixmap selectedPixmap(const QPixmap &pixmap, const QPalette &palette, bool enabled);
QRect doCheck(const QStyleOptionViewItem &option, const QRect &bounding,
diff --git a/src/widgets/itemviews/qitemeditorfactory.cpp b/src/widgets/itemviews/qitemeditorfactory.cpp
index f874597d59..609df364cf 100644
--- a/src/widgets/itemviews/qitemeditorfactory.cpp
+++ b/src/widgets/itemviews/qitemeditorfactory.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qitemeditorfactory.h"
@@ -241,21 +205,21 @@ QWidget *QDefaultItemEditorFactory::createEditor(int userType, QWidget *parent)
{
switch (userType) {
#if QT_CONFIG(combobox)
- case QVariant::Bool: {
+ case QMetaType::Bool: {
QBooleanComboBox *cb = new QBooleanComboBox(parent);
cb->setFrame(false);
cb->setSizePolicy(QSizePolicy::Ignored, cb->sizePolicy().verticalPolicy());
return cb; }
#endif
#if QT_CONFIG(spinbox)
- case QVariant::UInt: {
+ case QMetaType::UInt: {
QSpinBox *sb = new QUIntSpinBox(parent);
sb->setFrame(false);
sb->setMinimum(0);
sb->setMaximum(INT_MAX);
sb->setSizePolicy(QSizePolicy::Ignored, sb->sizePolicy().verticalPolicy());
return sb; }
- case QVariant::Int: {
+ case QMetaType::Int: {
QSpinBox *sb = new QSpinBox(parent);
sb->setFrame(false);
sb->setMinimum(INT_MIN);
@@ -264,25 +228,25 @@ QWidget *QDefaultItemEditorFactory::createEditor(int userType, QWidget *parent)
return sb; }
#endif
#if QT_CONFIG(datetimeedit)
- case QVariant::Date: {
+ case QMetaType::QDate: {
QDateTimeEdit *ed = new QDateEdit(parent);
ed->setFrame(false);
return ed; }
- case QVariant::Time: {
+ case QMetaType::QTime: {
QDateTimeEdit *ed = new QTimeEdit(parent);
ed->setFrame(false);
return ed; }
- case QVariant::DateTime: {
+ case QMetaType::QDateTime: {
QDateTimeEdit *ed = new QDateTimeEdit(parent);
ed->setFrame(false);
return ed; }
#endif
#if QT_CONFIG(label)
- case QVariant::Pixmap:
+ case QMetaType::QPixmap:
return new QLabel(parent);
#endif
#if QT_CONFIG(spinbox)
- case QVariant::Double: {
+ case QMetaType::Double: {
QDoubleSpinBox *sb = new QDoubleSpinBox(parent);
sb->setFrame(false);
sb->setMinimum(-DBL_MAX);
@@ -291,7 +255,7 @@ QWidget *QDefaultItemEditorFactory::createEditor(int userType, QWidget *parent)
return sb; }
#endif
#if QT_CONFIG(lineedit)
- case QVariant::String:
+ case QMetaType::QString:
default: {
// the default editor is a lineedit
QExpandingLineEdit *le = new QExpandingLineEdit(parent);
@@ -311,24 +275,24 @@ QByteArray QDefaultItemEditorFactory::valuePropertyName(int userType) const
{
switch (userType) {
#if QT_CONFIG(combobox)
- case QVariant::Bool:
+ case QMetaType::Bool:
return "currentIndex";
#endif
#if QT_CONFIG(spinbox)
- case QVariant::UInt:
- case QVariant::Int:
- case QVariant::Double:
+ case QMetaType::UInt:
+ case QMetaType::Int:
+ case QMetaType::Double:
return "value";
#endif
#if QT_CONFIG(datetimeedit)
- case QVariant::Date:
+ case QMetaType::QDate:
return "date";
- case QVariant::Time:
+ case QMetaType::QTime:
return "time";
- case QVariant::DateTime:
+ case QMetaType::QDateTime:
return "dateTime";
#endif
- case QVariant::String:
+ case QMetaType::QString:
default:
// the default editor is a lineedit
return "text";
@@ -432,7 +396,7 @@ QItemEditorCreatorBase::~QItemEditorCreatorBase()
the creator is registered for. For example, a creator which constructs
QCheckBox widgets to edit boolean values would return the
\l{QCheckBox::checkable}{checkable} property name from this function,
- and must be registered in the item editor factory for the QVariant::Bool
+ and must be registered in the item editor factory for the QMetaType::Bool
type.
Note: Since Qt 4.2 the item delegates query the user property of widgets,
@@ -513,7 +477,7 @@ QItemEditorCreatorBase::~QItemEditorCreatorBase()
Setting the \c editorFactory created above in an item delegate via
QStyledItemDelegate::setItemEditorFactory() makes sure that all values of type
- QVariant::DateTime will be edited in \c{MyFancyDateTimeEdit}.
+ QMetaType::QDateTime will be edited in \c{MyFancyDateTimeEdit}.
The editor must provide a user property that will contain the
editing data. The property is used by \l{QStyledItemDelegate}s to set
@@ -577,8 +541,7 @@ void QExpandingLineEdit::updateMinimumWidth()
QStyleOptionFrame opt;
initStyleOption(&opt);
- int minWidth = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(width, 0).
- expandedTo(QApplication::globalStrut()), this).width();
+ int minWidth = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(width, 0), this).width();
setMinimumWidth(minWidth);
}
@@ -592,7 +555,7 @@ void QExpandingLineEdit::resizeToContents()
int hintWidth = minimumWidth() + fontMetrics().horizontalAdvance(displayText());
int parentWidth = parent->width();
int maxWidth = isRightToLeft() ? position.x() + oldWidth : parentWidth - position.x();
- int newWidth = qBound(originalWidth, hintWidth, maxWidth);
+ int newWidth = qBound(qMin(originalWidth, maxWidth), hintWidth, maxWidth);
if (widgetOwnsGeometry)
setMaximumWidth(newWidth);
if (isRightToLeft())
diff --git a/src/widgets/itemviews/qitemeditorfactory.h b/src/widgets/itemviews/qitemeditorfactory.h
index 118f6e45e8..2c8ed301cd 100644
--- a/src/widgets/itemviews/qitemeditorfactory.h
+++ b/src/widgets/itemviews/qitemeditorfactory.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QITEMEDITORFACTORY_H
#define QITEMEDITORFACTORY_H
diff --git a/src/widgets/itemviews/qitemeditorfactory_p.h b/src/widgets/itemviews/qitemeditorfactory_p.h
index e78f42b729..4f4252a7c4 100644
--- a/src/widgets/itemviews/qitemeditorfactory_p.h
+++ b/src/widgets/itemviews/qitemeditorfactory_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QITEMEDITORFACTORY_P_H
#define QITEMEDITORFACTORY_P_H
diff --git a/src/widgets/itemviews/qlistview.cpp b/src/widgets/itemviews/qlistview.cpp
index ec01922746..a7f1931947 100644
--- a/src/widgets/itemviews/qlistview.cpp
+++ b/src/widgets/itemviews/qlistview.cpp
@@ -1,66 +1,30 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2013 Samuel Gaist <samuel.gaist@deltech.ch>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2013 Samuel Gaist <samuel.gaist@deltech.ch>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qlistview.h"
#include <qabstractitemdelegate.h>
+#if QT_CONFIG(accessibility)
+#include <qaccessible.h>
+#endif
#include <qapplication.h>
-#include <qpainter.h>
+#include <qstylepainter.h>
#include <qbitmap.h>
+#include <qdebug.h>
#if QT_CONFIG(draganddrop)
#include <qdrag.h>
#endif
-#include <qvector.h>
-#include <qstyle.h>
#include <qevent.h>
-#include <qscrollbar.h>
+#include <qlist.h>
#if QT_CONFIG(rubberband)
#include <qrubberband.h>
#endif
+#include <qscrollbar.h>
+#include <qstyle.h>
#include <private/qapplication_p.h>
#include <private/qlistview_p.h>
#include <private/qscrollbar_p.h>
-#include <qdebug.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include <qaccessible.h>
-#endif
#include <algorithm>
@@ -124,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
*/
/*!
@@ -214,8 +178,8 @@ QListView::~QListView()
grid, or cannot be moved at all.
This property determines how the user can move the items in the
- view. \l Static means that the items can't be moved the user. \l
- Free means that the user can drag and drop the items to any
+ view. \l Static means that the items can't be moved by the user.
+ \l Free means that the user can drag and drop the items to any
position in the view. \l Snap means that the user can drag and
drop the items, but only to the positions in a notional grid
signified by the gridSize property.
@@ -388,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.
@@ -572,6 +536,8 @@ void QListView::scrollTo(const QModelIndex &index, ScrollHint hint)
return;
const QRect rect = visualRect(index);
+ if (!rect.isValid())
+ return;
if (hint == EnsureVisible && d->viewport->rect().contains(rect)) {
d->viewport->update(rect);
return;
@@ -655,7 +621,8 @@ QItemViewPaintPairs QListViewPrivate::draggablePaintPairs(const QModelIndexList
QRect &rect = *r;
const QRect viewportRect = viewport->rect();
QItemViewPaintPairs ret;
- QVector<QModelIndex> visibleIndexes = intersectingSet(viewportRect.translated(q->horizontalOffset(), q->verticalOffset()));
+ QList<QModelIndex> visibleIndexes =
+ intersectingSet(viewportRect.translated(q->horizontalOffset(), q->verticalOffset()));
std::sort(visibleIndexes.begin(), visibleIndexes.end());
for (const auto &index : indexes) {
if (std::binary_search(visibleIndexes.cbegin(), visibleIndexes.cend(), index)) {
@@ -682,12 +649,12 @@ void QListView::reset()
}
/*!
- \internal
+ \reimp
*/
void QListView::setRootIndex(const QModelIndex &index)
{
Q_D(QListView);
- d->column = qBound(0, d->column, d->model->columnCount(index) - 1);
+ d->column = qMax(0, qMin(d->column, d->model->columnCount(index) - 1));
QAbstractItemView::setRootIndex(index);
// sometimes we get an update before reset() is called
d->clear();
@@ -695,7 +662,7 @@ void QListView::setRootIndex(const QModelIndex &index)
}
/*!
- \internal
+ \reimp
Scroll the view contents by \a dx and \a dy.
*/
@@ -731,7 +698,8 @@ QSize QListView::contentsSize() const
/*!
\reimp
*/
-void QListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
+void QListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &roles)
{
d_func()->commonListView->dataChanged(topLeft, bottomRight);
QAbstractItemView::dataChanged(topLeft, bottomRight, roles);
@@ -785,9 +753,12 @@ void QListView::mouseMoveEvent(QMouseEvent *e)
&& d->showElasticBand
&& d->selectionMode != SingleSelection
&& d->selectionMode != NoSelection) {
- QRect rect(d->pressedPosition, e->pos() + QPoint(horizontalOffset(), verticalOffset()));
+ 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;
}
}
@@ -801,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();
}
}
@@ -909,10 +882,68 @@ void QListView::dragLeaveEvent(QDragLeaveEvent *e)
/*!
\reimp
*/
-void QListView::dropEvent(QDropEvent *e)
+void QListView::dropEvent(QDropEvent *event)
{
- if (!d_func()->commonListView->filterDropEvent(e))
- QAbstractItemView::dropEvent(e);
+ Q_D(QListView);
+
+ if (event->source() == this && (event->dropAction() == Qt::MoveAction ||
+ dragDropMode() == QAbstractItemView::InternalMove)) {
+ QModelIndex topIndex;
+ bool topIndexDropped = false;
+ int col = -1;
+ int row = -1;
+ // check whether a subclass has already accepted the event, ie. moved the data
+ if (!event->isAccepted() && d->dropOn(event, &row, &col, &topIndex)) {
+ const QList<QModelIndex> selIndexes = selectedIndexes();
+ QList<QPersistentModelIndex> persIndexes;
+ persIndexes.reserve(selIndexes.size());
+
+ for (const auto &index : selIndexes) {
+ persIndexes.append(index);
+ if (index == topIndex) {
+ topIndexDropped = true;
+ break;
+ }
+ }
+
+ if (!topIndexDropped && !topIndex.isValid()) {
+ std::sort(persIndexes.begin(), persIndexes.end()); // The dropped items will remain in the same visual order.
+
+ QPersistentModelIndex dropRow = model()->index(row, col, topIndex);
+
+ int r = row == -1 ? model()->rowCount() : (dropRow.row() >= 0 ? dropRow.row() : row);
+ bool dataMoved = false;
+ for (int i = 0; i < persIndexes.size(); ++i) {
+ const QPersistentModelIndex &pIndex = persIndexes.at(i);
+ // 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
+ break;
+ } else {
+ // move onto itself is blocked, don't delete anything
+ dataMoved = true;
+ }
+ r = pIndex.row() + 1; // Dropped items are inserted contiguously and in the right order.
+ }
+ if (dataMoved)
+ event->accept();
+ }
+ }
+
+ // either we or a subclass accepted the move event, so assume that the data was
+ // moved and that QAbstractItemView shouldn't remove the source when QDrag::exec returns
+ if (event->isAccepted())
+ d->dropEventMoved = true;
+ }
+
+ if (!d->commonListView->filterDropEvent(event) || !d->dropEventMoved) {
+ // icon view didn't move the data, and moveRows not implemented, so fall back to default
+ if (!d->dropEventMoved)
+ event->ignore();
+ QAbstractItemView::dropEvent(event);
+ }
}
/*!
@@ -929,29 +960,27 @@ void QListView::startDrag(Qt::DropActions supportedActions)
/*!
\reimp
*/
-QStyleOptionViewItem QListView::viewOptions() const
+void QListView::initViewItemOption(QStyleOptionViewItem *option) const
{
Q_D(const QListView);
- QStyleOptionViewItem option = QAbstractItemView::viewOptions();
+ QAbstractItemView::initViewItemOption(option);
if (!d->iconSize.isValid()) { // otherwise it was already set in abstractitemview
int pm = (d->viewMode == QListView::ListMode
? style()->pixelMetric(QStyle::PM_ListViewIconSize, nullptr, this)
: style()->pixelMetric(QStyle::PM_IconViewIconSize, nullptr, this));
- option.decorationSize = QSize(pm, pm);
+ option->decorationSize = QSize(pm, pm);
}
if (d->viewMode == QListView::IconMode) {
- option.showDecorationSelected = false;
- option.decorationPosition = QStyleOptionViewItem::Top;
- option.displayAlignment = Qt::AlignCenter;
+ option->showDecorationSelected = false;
+ option->decorationPosition = QStyleOptionViewItem::Top;
+ option->displayAlignment = Qt::AlignCenter;
} else {
- option.decorationPosition = QStyleOptionViewItem::Left;
+ option->decorationPosition = QStyleOptionViewItem::Left;
}
if (d->gridSize().isValid()) {
- option.rect.setSize(d->gridSize());
+ option->rect.setSize(d->gridSize());
}
-
- return option;
}
@@ -963,10 +992,12 @@ void QListView::paintEvent(QPaintEvent *e)
Q_D(QListView);
if (!d->itemDelegate)
return;
- QStyleOptionViewItem option = d->viewOptionsV1();
- QPainter painter(d->viewport);
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
+ QStylePainter painter(d->viewport);
- const QVector<QModelIndex> toBeRendered = d->intersectingSet(e->rect().translated(horizontalOffset(), verticalOffset()), false);
+ const QList<QModelIndex> toBeRendered =
+ d->intersectingSet(e->rect().translated(horizontalOffset(), verticalOffset()), false);
const QModelIndex current = currentIndex();
const QModelIndex hover = d->hover;
@@ -985,8 +1016,8 @@ void QListView::paintEvent(QPaintEvent *e)
? qMax(viewport()->size().width(), d->contentsSize().width()) - 2 * d->spacing()
: qMax(viewport()->size().height(), d->contentsSize().height()) - 2 * d->spacing();
- QVector<QModelIndex>::const_iterator end = toBeRendered.constEnd();
- for (QVector<QModelIndex>::const_iterator it = toBeRendered.constBegin(); it != end; ++it) {
+ QList<QModelIndex>::const_iterator end = toBeRendered.constEnd();
+ for (QList<QModelIndex>::const_iterator it = toBeRendered.constBegin(); it != end; ++it) {
Q_ASSERT((*it).isValid());
option.rect = visualRect(*it);
@@ -1034,14 +1065,14 @@ void QListView::paintEvent(QPaintEvent *e)
// is provided by the delegate
QStyle::State oldState = option.state;
option.state &= ~QStyle::State_Selected;
- style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &option, &painter, this);
+ painter.drawPrimitive(QStyle::PE_PanelItemViewRow, option);
option.state = oldState;
alternateBase = !alternateBase;
previousRow = row;
}
- d->delegateForIndex(*it)->paint(&painter, option, *it);
+ itemDelegateForIndex(*it)->paint(&painter, option, *it);
}
#if QT_CONFIG(draganddrop)
@@ -1058,7 +1089,7 @@ void QListView::paintEvent(QPaintEvent *e)
opt.rect = d->mapToViewport(d->elasticBand, false).intersected(
d->viewport->rect().adjusted(-16, -16, 16, 16));
painter.save();
- style()->drawControl(QStyle::CE_RubberBand, &opt, &painter);
+ painter.drawControl(QStyle::CE_RubberBand, opt);
painter.restore();
}
#endif
@@ -1071,8 +1102,8 @@ QModelIndex QListView::indexAt(const QPoint &p) const
{
Q_D(const QListView);
QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1);
- const QVector<QModelIndex> intersectVector = d->intersectingSet(rect);
- QModelIndex index = intersectVector.count() > 0
+ const QList<QModelIndex> intersectVector = d->intersectingSet(rect);
+ QModelIndex index = intersectVector.size() > 0
? intersectVector.last() : QModelIndex();
if (index.isValid() && visualRect(index).contains(p))
return index;
@@ -1150,7 +1181,7 @@ QModelIndex QListView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
if (d->gridSize().isValid()) rect.setSize(d->gridSize());
QSize contents = d->contentsSize();
- QVector<QModelIndex> intersectVector;
+ QList<QModelIndex> intersectVector;
switch (cursorAction) {
case MoveLeft:
@@ -1175,13 +1206,28 @@ QModelIndex QListView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
d->removeCurrentAndDisabled(&intersectVector, current);
}
return d->closestIndex(initialRect, intersectVector);
- case MovePageUp:
- // move current by (visibileRowCount - 1) items.
- // rect.translate(0, -rect.height()); will happen in the switch fallthrough for MoveUp.
- rect.moveTop(rect.top() - d->viewport->height() + 2 * rect.height());
- if (rect.top() < rect.height())
- rect.moveTop(rect.height());
- Q_FALLTHROUGH();
+ case MovePageUp: {
+ if (rect.height() >= d->viewport->height())
+ return moveCursor(QAbstractItemView::MoveUp, modifiers);
+
+ rect.moveTop(rect.top() - d->viewport->height() + 1);
+ if (rect.top() < rect.height()) {
+ rect.setTop(0);
+ rect.setBottom(1);
+ }
+ QModelIndex findindex = current;
+ while (intersectVector.isEmpty()
+ || rectForIndex(findindex).top() <= (rectForIndex(current).bottom() - d->viewport->rect().height())
+ || rect.top() <= 0) {
+ rect.translate(0, 1);
+ if (rect.bottom() <= 0) {
+ return current;
+ }
+ intersectVector = d->intersectingSet(rect);
+ findindex = d->closestIndex(initialRect, intersectVector);
+ }
+ return findindex;
+ }
case MovePrevious:
case MoveUp:
while (intersectVector.isEmpty()) {
@@ -1204,13 +1250,29 @@ QModelIndex QListView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
d->removeCurrentAndDisabled(&intersectVector, current);
}
return d->closestIndex(initialRect, intersectVector);
- case MovePageDown:
- // move current by (visibileRowCount - 1) items.
- // rect.translate(0, rect.height()); will happen in the switch fallthrough for MoveDown.
- rect.moveTop(rect.top() + d->viewport->height() - 2 * rect.height());
- if (rect.bottom() > contents.height() - rect.height())
- rect.moveBottom(contents.height() - rect.height());
- Q_FALLTHROUGH();
+ case MovePageDown: {
+ if (rect.height() >= d->viewport->height())
+ return moveCursor(QAbstractItemView::MoveDown, modifiers);
+
+ rect.moveTop(rect.top() + d->viewport->height() - 1);
+ if (rect.bottom() > contents.height() - rect.height()) {
+ rect.setTop(contents.height() - 1);
+ rect.setBottom(contents.height());
+ }
+ QModelIndex index = current;
+ // index's bottom() - current's top() always <= (d->viewport->rect().height()
+ while (intersectVector.isEmpty()
+ || rectForIndex(index).bottom() >= (d->viewport->rect().height() + rectForIndex(current).top())
+ || rect.bottom() > contents.height()) {
+ rect.translate(0, -1);
+ if (rect.top() >= contents.height()) {
+ return current;
+ }
+ intersectVector = d->intersectingSet(rect);
+ index = d->closestIndex(initialRect, intersectVector);
+ }
+ return index;
+ }
case MoveNext:
case MoveDown:
while (intersectVector.isEmpty()) {
@@ -1283,7 +1345,7 @@ void QListView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFl
if (!d->selectionModel)
return;
- // if we are wrapping, we can only selecte inside the contents rectangle
+ // if we are wrapping, we can only select inside the contents rectangle
int w = qMax(d->contentsSize().width(), d->viewport->width());
int h = qMax(d->contentsSize().height(), d->viewport->height());
if (d->wrap && !QRect(0, 0, w, h).intersects(rect))
@@ -1292,7 +1354,8 @@ void QListView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFl
QItemSelection selection;
if (rect.width() == 1 && rect.height() == 1) {
- const QVector<QModelIndex> intersectVector = d->intersectingSet(rect.translated(horizontalOffset(), verticalOffset()));
+ const QList<QModelIndex> intersectVector =
+ d->intersectingSet(rect.translated(horizontalOffset(), verticalOffset()));
QModelIndex tl;
if (!intersectVector.isEmpty())
tl = intersectVector.last(); // special case for mouse press; only select the top item
@@ -1305,7 +1368,7 @@ void QListView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFl
QModelIndex tl, br;
// get the first item
const QRect topLeft(rect.left() + horizontalOffset(), rect.top() + verticalOffset(), 1, 1);
- QVector<QModelIndex> intersectVector = d->intersectingSet(topLeft);
+ QList<QModelIndex> intersectVector = d->intersectingSet(topLeft);
if (!intersectVector.isEmpty())
tl = intersectVector.last();
// get the last item
@@ -1330,7 +1393,7 @@ void QListView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFl
top = bottom;
bottom = tmp;
}
- // if the rect are on differnet lines, expand
+ // if the rect are on different lines, expand
if (top.top() != bottom.top()) {
// top rectangle
if (isRightToLeft())
@@ -1469,8 +1532,7 @@ QModelIndexList QListView::selectedIndexes() const
auto ignorable = [this, d](const QModelIndex &index) {
return index.column() != d->column || index.parent() != d->root || isIndexHidden(index);
};
- viewSelected.erase(std::remove_if(viewSelected.begin(), viewSelected.end(), ignorable),
- viewSelected.end());
+ viewSelected.removeIf(ignorable);
return viewSelected;
}
@@ -1489,12 +1551,14 @@ void QListView::doItemsLayout()
setState(ExpandingState);
if (d->model->columnCount(d->root) > 0) { // no columns means no contents
d->resetBatchStartRow();
- if (layoutMode() == SinglePass)
+ if (layoutMode() == SinglePass) {
d->doItemsLayout(d->model->rowCount(d->root)); // layout everything
- else if (!d->batchLayoutTimer.isActive()) {
+ } else if (!d->batchLayoutTimer.isActive()) {
if (!d->doItemsLayout(d->batchSize)) // layout is done
d->batchLayoutTimer.start(0, this); // do a new batch as fast as possible
}
+ } else { // clear the QBspTree generated by the last layout
+ d->clear();
}
QAbstractItemView::doItemsLayout();
setState(oldState); // restoring the oldState
@@ -1511,7 +1575,8 @@ void QListView::updateGeometries()
verticalScrollBar()->setRange(0, 0);
} else {
QModelIndex index = d->model->index(0, d->column, d->root);
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
QSize step = d->itemSize(option, index);
d->commonListView->updateHorizontalScrollBar(step);
d->commonListView->updateVerticalScrollBar(step);
@@ -1562,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
@@ -1728,13 +1799,17 @@ void QListViewPrivate::prepareItemsLayout()
layoutBounds = QRect(QPoint(), q->maximumViewportSize());
int frameAroundContents = 0;
- if (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents))
- frameAroundContents = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2;
+ if (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents)) {
+ QStyleOption option;
+ option.initFrom(q);
+ frameAroundContents = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &option, q) * 2;
+ }
// maximumViewportSize() already takes scrollbar into account if policy is
// Qt::ScrollBarAlwaysOn but scrollbar extent must be deduced if policy
// is Qt::ScrollBarAsNeeded
- int verticalMargin = vbarpolicy==Qt::ScrollBarAsNeeded
+ int verticalMargin = (vbarpolicy == Qt::ScrollBarAsNeeded) && (flow == QListView::LeftToRight || vbar->isVisible())
+ && !q->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, nullptr, vbar)
? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, nullptr, vbar) + frameAroundContents
: 0;
int horizontalMargin = hbarpolicy==Qt::ScrollBarAsNeeded
@@ -1799,12 +1874,12 @@ QRect QListViewPrivate::mapToViewport(const QRect &rect, bool extend) const
}
QModelIndex QListViewPrivate::closestIndex(const QRect &target,
- const QVector<QModelIndex> &candidates) const
+ const QList<QModelIndex> &candidates) const
{
int distance = 0;
int shortest = INT_MAX;
QModelIndex closest;
- QVector<QModelIndex>::const_iterator it = candidates.begin();
+ QList<QModelIndex>::const_iterator it = candidates.begin();
for (; it != candidates.end(); ++it) {
if (!(*it).isValid())
@@ -1836,14 +1911,15 @@ QModelIndex QListViewPrivate::closestIndex(const QRect &target,
QSize QListViewPrivate::itemSize(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
+ Q_Q(const QListView);
if (!uniformItemSizes) {
- const QAbstractItemDelegate *delegate = delegateForIndex(index);
+ const QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
return delegate ? delegate->sizeHint(option, index) : QSize();
}
- if (!cachedItemSize.isValid()) { // the last item is probaly the largest, so we use its size
+ if (!cachedItemSize.isValid()) { // the last item is probably the largest, so we use its size
int row = model->rowCount(root) - 1;
QModelIndex sample = model->index(row, column, root);
- const QAbstractItemDelegate *delegate = delegateForIndex(sample);
+ const QAbstractItemDelegate *delegate = q->itemDelegateForIndex(sample);
cachedItemSize = delegate ? delegate->sizeHint(option, sample) : QSize();
}
return cachedItemSize;
@@ -1853,8 +1929,8 @@ QItemSelection QListViewPrivate::selection(const QRect &rect) const
{
QItemSelection selection;
QModelIndex tl, br;
- const QVector<QModelIndex> intersectVector = intersectingSet(rect);
- QVector<QModelIndex>::const_iterator it = intersectVector.begin();
+ const QList<QModelIndex> intersectVector = intersectingSet(rect);
+ QList<QModelIndex>::const_iterator it = intersectVector.begin();
for (; it != intersectVector.end(); ++it) {
if (!tl.isValid() && !br.isValid()) {
tl = br = *it;
@@ -1896,14 +1972,13 @@ bool QListViewPrivate::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QMo
}
#endif
-void QListViewPrivate::removeCurrentAndDisabled(QVector<QModelIndex> *indexes, const QModelIndex &current) const
+void QListViewPrivate::removeCurrentAndDisabled(QList<QModelIndex> *indexes,
+ const QModelIndex &current) const
{
auto isCurrentOrDisabled = [this, current](const QModelIndex &index) {
return !isIndexEnabled(index) || index == current;
};
- indexes->erase(std::remove_if(indexes->begin(), indexes->end(),
- isCurrentOrDisabled),
- indexes->end());
+ indexes->removeIf(isCurrentOrDisabled);
}
/*
@@ -2092,11 +2167,11 @@ void QListModeViewBase::dragMoveEvent(QDragMoveEvent *event)
event->ignore();
// can't use indexAt, doesn't account for spacing.
- QPoint p = event->pos();
+ QPoint p = event->position().toPoint();
QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1);
rect.adjust(-dd->spacing(), -dd->spacing(), dd->spacing(), dd->spacing());
- const QVector<QModelIndex> intersectVector = dd->intersectingSet(rect);
- QModelIndex index = intersectVector.count() > 0
+ const QList<QModelIndex> intersectVector = dd->intersectingSet(rect);
+ QModelIndex index = intersectVector.size() > 0
? intersectVector.last() : QModelIndex();
dd->hover = index;
if (!dd->droppingOnItself(event, index)
@@ -2104,7 +2179,7 @@ void QListModeViewBase::dragMoveEvent(QDragMoveEvent *event)
if (index.isValid() && dd->showDropIndicator) {
QRect rect = qq->visualRect(index);
- dd->dropIndicatorPosition = position(event->pos(), rect, index);
+ dd->dropIndicatorPosition = position(event->position().toPoint(), rect, index);
// if spacing, should try to draw between items, not just next to item.
switch (dd->dropIndicatorPosition) {
case QAbstractItemView::AboveItem:
@@ -2148,7 +2223,7 @@ void QListModeViewBase::dragMoveEvent(QDragMoveEvent *event)
dd->viewport->update();
} // can drop
- if (dd->shouldAutoScroll(event->pos()))
+ if (dd->shouldAutoScroll(event->position().toPoint()))
qq->startAutoScroll();
}
@@ -2169,13 +2244,13 @@ bool QListModeViewBase::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QM
return false;
QModelIndex index;
- if (dd->viewport->rect().contains(event->pos())) {
+ if (dd->viewport->rect().contains(event->position().toPoint())) {
// can't use indexAt, doesn't account for spacing.
- QPoint p = event->pos();
+ QPoint p = event->position().toPoint();
QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1);
rect.adjust(-dd->spacing(), -dd->spacing(), dd->spacing(), dd->spacing());
- const QVector<QModelIndex> intersectVector = dd->intersectingSet(rect);
- index = intersectVector.count() > 0
+ const QList<QModelIndex> intersectVector = dd->intersectingSet(rect);
+ index = intersectVector.size() > 0
? intersectVector.last() : QModelIndex();
if (!index.isValid())
index = dd->root;
@@ -2186,7 +2261,7 @@ bool QListModeViewBase::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QM
int row = -1;
int col = -1;
if (index != dd->root) {
- dd->dropIndicatorPosition = position(event->pos(), qq->visualRect(index), index);
+ dd->dropIndicatorPosition = position(event->position().toPoint(), qq->visualRect(index), index);
switch (dd->dropIndicatorPosition) {
case QAbstractItemView::AboveItem:
row = index.row();
@@ -2221,7 +2296,7 @@ void QListModeViewBase::updateVerticalScrollBar(const QSize &step)
if (verticalScrollMode() == QAbstractItemView::ScrollPerItem
&& ((flow() == QListView::TopToBottom && !isWrapping())
|| (flow() == QListView::LeftToRight && isWrapping()))) {
- const int steps = (flow() == QListView::TopToBottom ? scrollValueMap : segmentPositions).count() - 1;
+ const int steps = (flow() == QListView::TopToBottom ? scrollValueMap : segmentPositions).size() - 1;
if (steps > 0) {
const int pageSteps = perItemScrollingPageSteps(viewport()->height(), contentsSize.height(), isWrapping());
verticalScrollBar()->setSingleStep(1);
@@ -2242,7 +2317,7 @@ void QListModeViewBase::updateHorizontalScrollBar(const QSize &step)
if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem
&& ((flow() == QListView::TopToBottom && isWrapping())
|| (flow() == QListView::LeftToRight && !isWrapping()))) {
- int steps = (flow() == QListView::TopToBottom ? segmentPositions : scrollValueMap).count() - 1;
+ int steps = (flow() == QListView::TopToBottom ? segmentPositions : scrollValueMap).size() - 1;
if (steps > 0) {
const int pageSteps = perItemScrollingPageSteps(viewport()->width(), contentsSize.width(), isWrapping());
horizontalScrollBar()->setSingleStep(1);
@@ -2266,10 +2341,10 @@ int QListModeViewBase::verticalScrollToValue(int index, QListView::ScrollHint hi
} else {
int scrollBarValue = verticalScrollBar()->value();
int numHidden = 0;
- for (const auto &idx : qAsConst(dd->hiddenRows))
+ for (const auto &idx : std::as_const(dd->hiddenRows))
if (idx.row() <= scrollBarValue)
++numHidden;
- value = qBound(0, scrollValueMap.at(verticalScrollBar()->value()) - numHidden, flowPositions.count() - 1);
+ value = qBound(0, scrollValueMap.at(verticalScrollBar()->value()) - numHidden, flowPositions.size() - 1);
}
if (above)
hint = QListView::PositionAtTop;
@@ -2289,7 +2364,7 @@ int QListModeViewBase::horizontalOffset() const
if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) {
if (isWrapping()) {
if (flow() == QListView::TopToBottom && !segmentPositions.isEmpty()) {
- const int max = segmentPositions.count() - 1;
+ const int max = segmentPositions.size() - 1;
int currentValue = qBound(0, horizontalScrollBar()->value(), max);
int position = segmentPositions.at(currentValue);
int maximumValue = qBound(0, horizontalScrollBar()->maximum(), max);
@@ -2311,13 +2386,13 @@ int QListModeViewBase::verticalOffset() const
if (isWrapping()) {
if (flow() == QListView::LeftToRight && !segmentPositions.isEmpty()) {
int value = verticalScrollBar()->value();
- if (value >= segmentPositions.count())
+ if (value >= segmentPositions.size())
return 0;
return segmentPositions.at(value) - spacing();
}
} else if (flow() == QListView::TopToBottom && !flowPositions.isEmpty()) {
int value = verticalScrollBar()->value();
- if (value > scrollValueMap.count())
+ if (value > scrollValueMap.size())
return 0;
return flowPositions.at(scrollValueMap.at(value)) - spacing();
}
@@ -2335,7 +2410,7 @@ int QListModeViewBase::horizontalScrollToValue(int index, QListView::ScrollHint
if (scrollValueMap.isEmpty())
value = 0;
else
- value = qBound(0, scrollValueMap.at(horizontalScrollBar()->value()), flowPositions.count() - 1);
+ value = qBound(0, scrollValueMap.at(horizontalScrollBar()->value()), flowPositions.size() - 1);
if (leftOf)
hint = QListView::PositionAtTop;
else if (rightOf)
@@ -2357,7 +2432,7 @@ void QListModeViewBase::scrollContentsBy(int dx, int dy, bool scrollElasticBand)
if (isWrapping()) {
if (segmentPositions.isEmpty())
return;
- const int max = segmentPositions.count() - 1;
+ const int max = segmentPositions.size() - 1;
if (horizontal && flow() == QListView::TopToBottom && dx != 0) {
int currentValue = qBound(0, horizontalValue, max);
int previousValue = qBound(0, currentValue + dx, max);
@@ -2374,7 +2449,7 @@ void QListModeViewBase::scrollContentsBy(int dx, int dy, bool scrollElasticBand)
} else {
if (flowPositions.isEmpty())
return;
- const int max = scrollValueMap.count() - 1;
+ const int max = scrollValueMap.size() - 1;
if (vertical && flow() == QListView::TopToBottom && dy != 0) {
int currentValue = qBound(0, verticalValue, max);
int previousValue = qBound(0, currentValue + dy, max);
@@ -2402,14 +2477,15 @@ QListViewItem QListModeViewBase::indexToListViewItem(const QModelIndex &index) c
{
if (flowPositions.isEmpty()
|| segmentPositions.isEmpty()
- || index.row() >= flowPositions.count() - 1)
+ || index.row() >= flowPositions.size() - 1)
return QListViewItem();
const int segment = qBinarySearch<int>(segmentStartRows, index.row(),
- 0, segmentStartRows.count() - 1);
+ 0, segmentStartRows.size() - 1);
- QStyleOptionViewItem options = viewOptions();
+ QStyleOptionViewItem options;
+ initViewItemOption(&options);
options.rect.setSize(contentsSize);
QSize size = (uniformItemSizes() && cachedItemSize().isValid())
? cachedItemSize() : itemSize(options, index);
@@ -2423,7 +2499,7 @@ QListViewItem QListModeViewBase::indexToListViewItem(const QModelIndex &index) c
pos.setY(flowPositions.at(index.row()));
pos.setX(segmentPositions.at(segment));
if (isWrapping()) { // make the items as wide as the segment
- int right = (segment + 1 >= segmentPositions.count()
+ int right = (segment + 1 >= segmentPositions.size()
? contentsSize.width()
: segmentPositions.at(segment + 1));
cellSize.setWidth(right - pos.x());
@@ -2485,7 +2561,8 @@ void QListModeViewBase::doStaticLayout(const QListViewLayoutInfo &info)
{
const bool useItemSize = !info.grid.isValid();
const QPoint topLeft = initStaticLayout(info);
- QStyleOptionViewItem option = viewOptions();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
option.rect = info.bounds;
option.rect.adjust(info.spacing, info.spacing, -info.spacing, -info.spacing);
@@ -2546,7 +2623,7 @@ void QListModeViewBase::doStaticLayout(const QListViewLayoutInfo &info)
deltaSegPosition = 0;
}
// save the flow position of this item
- scrollValueMap.append(flowPositions.count());
+ scrollValueMap.append(flowPositions.size());
flowPositions.append(flowPosition);
// prepare for the next item
deltaSegPosition = qMax(deltaSegHint, deltaSegPosition);
@@ -2562,21 +2639,21 @@ void QListModeViewBase::doStaticLayout(const QListViewLayoutInfo &info)
// set the contents size
QRect rect = info.bounds;
if (info.flow == QListView::LeftToRight) {
- rect.setRight(segmentPositions.count() == 1 ? flowPosition : info.bounds.right());
+ rect.setRight(segmentPositions.size() == 1 ? flowPosition : info.bounds.right());
rect.setBottom(segPosition + deltaSegPosition);
} else { // TopToBottom
rect.setRight(segPosition + deltaSegPosition);
- rect.setBottom(segmentPositions.count() == 1 ? flowPosition : info.bounds.bottom());
+ rect.setBottom(segmentPositions.size() == 1 ? flowPosition : info.bounds.bottom());
}
contentsSize = QSize(rect.right(), rect.bottom());
// if it is the last batch, save the end of the segments
if (info.last == info.max) {
segmentExtents.append(flowPosition);
- scrollValueMap.append(flowPositions.count());
+ scrollValueMap.append(flowPositions.size());
flowPositions.append(flowPosition);
segmentPositions.append(info.wrap ? segPosition + deltaSegPosition : INT_MAX);
}
- // if the new items are visble, update the viewport
+ // if the new items are visible, update the viewport
QRect changedRect(topLeft, rect.bottomRight());
if (clipRect().intersects(changedRect))
viewport()->update();
@@ -2587,9 +2664,9 @@ void QListModeViewBase::doStaticLayout(const QListViewLayoutInfo &info)
Finds the set of items intersecting with \a area.
In this function, itemsize is counted from topleft to the start of the next item.
*/
-QVector<QModelIndex> QListModeViewBase::intersectingSet(const QRect &area) const
+QList<QModelIndex> QListModeViewBase::intersectingSet(const QRect &area) const
{
- QVector<QModelIndex> ret;
+ QList<QModelIndex> ret;
int segStartPosition;
int segEndPosition;
int flowStartPosition;
@@ -2605,10 +2682,10 @@ QVector<QModelIndex> QListModeViewBase::intersectingSet(const QRect &area) const
flowStartPosition = area.top();
flowEndPosition = area.bottom();
}
- if (segmentPositions.count() < 2 || flowPositions.isEmpty())
+ if (segmentPositions.size() < 2 || flowPositions.isEmpty())
return ret;
// the last segment position is actually the edge of the last segment
- const int segLast = segmentPositions.count() - 2;
+ const int segLast = segmentPositions.size() - 2;
int seg = qBinarySearch<int>(segmentPositions, segStartPosition, 0, segLast + 1);
for (; seg <= segLast && segmentPositions.at(seg) <= segEndPosition; ++seg) {
int first = segmentStartRows.at(seg);
@@ -2666,7 +2743,7 @@ QRect QListModeViewBase::mapToViewport(const QRect &rect) const
int QListModeViewBase::perItemScrollingPageSteps(int length, int bounds, bool wrap) const
{
- QVector<int> positions;
+ QList<int> positions;
if (wrap)
positions = segmentPositions;
else if (!flowPositions.isEmpty()) {
@@ -2675,15 +2752,15 @@ int QListModeViewBase::perItemScrollingPageSteps(int length, int bounds, bool wr
positions.append(flowPositions.at(itemShown));
}
if (positions.isEmpty() || bounds <= length)
- return positions.count();
+ return positions.size();
if (uniformItemSizes()) {
- for (int i = 1; i < positions.count(); ++i)
+ for (int i = 1; i < positions.size(); ++i)
if (positions.at(i) > 0)
return length / positions.at(i);
return 0; // all items had height 0
}
int pageSteps = 0;
- int steps = positions.count() - 1;
+ int steps = positions.size() - 1;
int max = qMax(length, bounds);
int min = qMin(length, bounds);
int pos = min - (max - positions.constLast());
@@ -2707,7 +2784,7 @@ int QListModeViewBase::perItemScrollToValue(int index, int scrollValue, int view
return scrollValue;
itemExtent += spacing();
- QVector<int> hiddenRows = dd->hiddenRowIds();
+ QList<int> hiddenRows = dd->hiddenRowIds();
std::sort(hiddenRows.begin(), hiddenRows.end());
int hiddenRowsBefore = 0;
for (int i = 0; i < hiddenRows.size() - 1; ++i)
@@ -2745,7 +2822,7 @@ int QListModeViewBase::perItemScrollToValue(int index, int scrollValue, int view
// ### wrapped scrolling in the flow direction
return flowPositions.at(index + hiddenRowsBefore); // ### always pixel based for now
} else if (!segmentStartRows.isEmpty()) { // we are scrolling in the "segment" direction
- int segment = qBinarySearch<int>(segmentStartRows, index, 0, segmentStartRows.count() - 1);
+ int segment = qBinarySearch<int>(segmentStartRows, index, 0, segmentStartRows.size() - 1);
int leftSegment = segment;
const int rightSegment = leftSegment;
const int bottomCoordinate = segmentPositions.at(segment);
@@ -2788,7 +2865,7 @@ void QListModeViewBase::clear()
void QIconModeViewBase::setPositionForIndex(const QPoint &position, const QModelIndex &index)
{
- if (index.row() >= items.count())
+ if (index.row() >= items.size())
return;
const QSize oldContents = contentsSize;
qq->update(index); // update old position
@@ -2801,7 +2878,7 @@ void QIconModeViewBase::setPositionForIndex(const QPoint &position, const QModel
void QIconModeViewBase::appendHiddenRow(int row)
{
- if (row >= 0 && row < items.count()) //remove item
+ if (row >= 0 && row < items.size()) //remove item
tree.removeLeaf(items.at(row).rect(), row);
QCommonListViewBase::appendHiddenRow(row);
}
@@ -2809,7 +2886,7 @@ void QIconModeViewBase::appendHiddenRow(int row)
void QIconModeViewBase::removeHiddenRow(int row)
{
QCommonListViewBase::removeHiddenRow(row);
- if (row >= 0 && row < items.count()) //insert item
+ if (row >= 0 && row < items.size()) //insert item
tree.insertLeaf(items.at(row).rect(), row);
}
@@ -2820,7 +2897,7 @@ bool QIconModeViewBase::filterStartDrag(Qt::DropActions supportedActions)
// plus adding viewitems to the draggedItems list.
// We need these items to draw the drag items
QModelIndexList indexes = dd->selectionModel->selectedIndexes();
- if (indexes.count() > 0 ) {
+ if (indexes.size() > 0 ) {
if (viewport()->acceptDrops()) {
QModelIndexList::ConstIterator it = indexes.constBegin();
for (; it != indexes.constEnd(); ++it)
@@ -2836,12 +2913,15 @@ bool QIconModeViewBase::filterStartDrag(Qt::DropActions supportedActions)
drag->setMimeData(dd->model->mimeData(indexes));
drag->setPixmap(pixmap);
drag->setHotSpot(dd->pressedPosition - rect.topLeft());
+ dd->dropEventMoved = false;
Qt::DropAction action = drag->exec(supportedActions, dd->defaultDropAction);
draggedItems.clear();
- // for internal moves the action was set to Qt::CopyAction in
- // filterDropEvent() to avoid the deletion here
- if (action == Qt::MoveAction)
- dd->clearOrRemove();
+ // delete item, unless it has already been moved internally (see filterDropEvent)
+ if (action == Qt::MoveAction && !dd->dropEventMoved) {
+ if (dd->dragDropMode != QAbstractItemView::InternalMove || drag->target() == qq->viewport())
+ dd->clearOrRemove();
+ }
+ dd->dropEventMoved = false;
}
return true;
}
@@ -2853,10 +2933,10 @@ bool QIconModeViewBase::filterDropEvent(QDropEvent *e)
const QSize contents = contentsSize;
QPoint offset(horizontalOffset(), verticalOffset());
- QPoint end = e->pos() + offset;
+ QPoint end = e->position().toPoint() + offset;
if (qq->acceptDrops()) {
const Qt::ItemFlags dropableFlags = Qt::ItemIsDropEnabled|Qt::ItemIsEnabled;
- const QVector<QModelIndex> &dropIndices = intersectingSet(QRect(end, QSize(1, 1)));
+ const QList<QModelIndex> &dropIndices = intersectingSet(QRect(end, QSize(1, 1)));
for (const QModelIndex &index : dropIndices)
if ((index.flags() & dropableFlags) == dropableFlags)
return false;
@@ -2877,9 +2957,9 @@ bool QIconModeViewBase::filterDropEvent(QDropEvent *e)
draggedItems.clear();
dd->emitIndexesMoved(indexes);
// do not delete item on internal move, see filterStartDrag()
- e->setDropAction(Qt::CopyAction);
+ dd->dropEventMoved = true;
e->accept(); // we have handled the event
- // if the size has not grown, we need to check if it has shrinked
+ // if the size has not grown, we need to check if it has shrunk
if (contentsSize != contents) {
if ((contentsSize.width() <= contents.width()
|| contentsSize.height() <= contents.height())) {
@@ -2914,17 +2994,17 @@ bool QIconModeViewBase::filterDragMoveEvent(QDragMoveEvent *e)
QRect itemsRect = this->itemsRect(draggedItems);
viewport()->update(itemsRect.translated(draggedItemsDelta()));
// update position
- draggedItemsPos = e->pos();
+ draggedItemsPos = e->position().toPoint();
// get new items rect
viewport()->update(itemsRect.translated(draggedItemsDelta()));
// set the item under the cursor to current
QModelIndex index;
if (movement() == QListView::Snap) {
- QRect rect(snapToGrid(e->pos() + offset()), gridSize());
- const QVector<QModelIndex> intersectVector = intersectingSet(rect);
- index = intersectVector.count() > 0 ? intersectVector.last() : QModelIndex();
+ QRect rect(snapToGrid(e->position().toPoint() + offset()), gridSize());
+ const QList<QModelIndex> intersectVector = intersectingSet(rect);
+ index = intersectVector.size() > 0 ? intersectVector.last() : QModelIndex();
} else {
- index = qq->indexAt(e->pos());
+ index = qq->indexAt(e->position().toPoint());
}
// check if we allow drops here
if (draggedItems.contains(index))
@@ -2935,7 +3015,7 @@ bool QIconModeViewBase::filterDragMoveEvent(QDragMoveEvent *e)
e->accept(); // allow dropping in empty areas
// the event was treated. do autoscrolling
- if (dd->shouldAutoScroll(e->pos()))
+ if (dd->shouldAutoScroll(e->position().toPoint()))
dd->startAutoScroll();
return true;
}
@@ -2959,8 +3039,9 @@ void QIconModeViewBase::scrollContentsBy(int dx, int dy, bool scrollElasticBand)
void QIconModeViewBase::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
if (column() >= topLeft.column() && column() <= bottomRight.column()) {
- const QStyleOptionViewItem option = viewOptions();
- const int bottom = qMin(items.count(), bottomRight.row() + 1);
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
+ const int bottom = qMin(items.size(), bottomRight.row() + 1);
const bool useItemSize = !dd->grid.isValid();
for (int row = topLeft.row(); row < bottom; ++row)
{
@@ -2977,10 +3058,11 @@ void QIconModeViewBase::dataChanged(const QModelIndex &topLeft, const QModelInde
bool QIconModeViewBase::doBatchedItemLayout(const QListViewLayoutInfo &info, int max)
{
- if (info.last >= items.count()) {
+ if (info.last >= items.size()) {
//first we create the items
- QStyleOptionViewItem option = viewOptions();
- for (int row = items.count(); row <= info.last; ++row) {
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
+ for (int row = items.size(); row <= info.last; ++row) {
QSize size = itemSize(option, modelIndex(row));
QListViewItem item(QRect(0, 0, size.width(), size.height()), row); // default pos
items.append(item);
@@ -2992,7 +3074,7 @@ bool QIconModeViewBase::doBatchedItemLayout(const QListViewLayoutInfo &info, int
QListViewItem QIconModeViewBase::indexToListViewItem(const QModelIndex &index) const
{
- if (index.isValid() && index.row() < items.count())
+ if (index.isValid() && index.row() < items.size())
return items.at(index.row());
return QListViewItem();
}
@@ -3070,11 +3152,12 @@ void QIconModeViewBase::doDynamicLayout(const QListViewLayoutInfo &info)
segPosition = topLeft.x();
}
- if (moved.count() != items.count())
- moved.resize(items.count());
+ if (moved.size() != items.size())
+ moved.resize(items.size());
QRect rect(QPoint(), topLeft);
QListViewItem *item = nullptr;
+ Q_ASSERT(info.first <= info.last);
for (int row = info.first; row <= info.last; ++row) {
item = &items[row];
if (isHidden(row)) {
@@ -3145,6 +3228,7 @@ void QIconModeViewBase::doDynamicLayout(const QListViewLayoutInfo &info)
flowPosition += deltaFlowPosition; // current position + item width + gap
}
}
+ Q_ASSERT(item);
batchSavedDeltaSeg = deltaSegPosition;
batchStartRow = info.last + 1;
bool done = (info.last >= rowCount() - 1);
@@ -3167,32 +3251,28 @@ void QIconModeViewBase::doDynamicLayout(const QListViewLayoutInfo &info)
// insert items in tree
for (int row = insertFrom; row <= info.last; ++row)
tree.insertLeaf(items.at(row).rect(), row);
- // if the new items are visble, update the viewport
+ // if the new items are visible, update the viewport
QRect changedRect(topLeft, rect.bottomRight());
if (clipRect().intersects(changedRect))
viewport()->update();
}
-QVector<QModelIndex> QIconModeViewBase::intersectingSet(const QRect &area) const
+QList<QModelIndex> QIconModeViewBase::intersectingSet(const QRect &area) const
{
QIconModeViewBase *that = const_cast<QIconModeViewBase*>(this);
QBspTree::Data data(static_cast<void*>(that));
- QVector<QModelIndex> res;
+ QList<QModelIndex> res;
that->interSectingVector = &res;
that->tree.climbTree(area, &QIconModeViewBase::addLeaf, data);
that->interSectingVector = nullptr;
return res;
}
-QRect QIconModeViewBase::itemsRect(const QVector<QModelIndex> &indexes) const
+QRect QIconModeViewBase::itemsRect(const QList<QModelIndex> &indexes) const
{
- QVector<QModelIndex>::const_iterator it = indexes.begin();
- QListViewItem item = indexToListViewItem(*it);
- QRect rect(item.x, item.y, item.w, item.h);
- for (; it != indexes.end(); ++it) {
- item = indexToListViewItem(*it);
- rect |= viewItemRect(item);
- }
+ QRect rect;
+ for (const auto &index : indexes)
+ rect |= viewItemRect(indexToListViewItem(index));
return rect;
}
@@ -3201,15 +3281,15 @@ int QIconModeViewBase::itemIndex(const QListViewItem &item) const
if (!item.isValid())
return -1;
int i = item.indexHint;
- if (i < items.count()) {
+ if (i < items.size()) {
if (items.at(i) == item)
return i;
} else {
- i = items.count() - 1;
+ i = items.size() - 1;
}
int j = i;
- int c = items.count();
+ int c = items.size();
bool a = true;
bool b = true;
@@ -3232,14 +3312,14 @@ int QIconModeViewBase::itemIndex(const QListViewItem &item) const
return -1;
}
-void QIconModeViewBase::addLeaf(QVector<int> &leaf, const QRect &area,
- uint visited, QBspTree::Data data)
+void QIconModeViewBase::addLeaf(QList<int> &leaf, const QRect &area, uint visited,
+ QBspTree::Data data)
{
QListViewItem *vi;
QIconModeViewBase *_this = static_cast<QIconModeViewBase *>(data.ptr);
- for (int i = 0; i < leaf.count(); ++i) {
+ for (int i = 0; i < leaf.size(); ++i) {
int idx = leaf.at(i);
- if (idx < 0 || idx >= _this->items.count())
+ if (idx < 0 || idx >= _this->items.size())
continue;
vi = &_this->items[idx];
Q_ASSERT(vi);
@@ -3267,8 +3347,8 @@ void QIconModeViewBase::moveItem(int index, const QPoint &dest)
contentsSize = (QRect(QPoint(0, 0), contentsSize)|QRect(dest, rect.size())).size();
// mark the item as moved
- if (moved.count() != items.count())
- moved.resize(items.count());
+ if (moved.size() != items.size())
+ moved.resize(items.size());
moved.setBit(index, true);
}
@@ -3320,7 +3400,7 @@ void QIconModeViewBase::clear()
void QIconModeViewBase::updateContentsSize()
{
QRect bounding;
- for (int i = 0; i < items.count(); ++i)
+ for (int i = 0; i < items.size(); ++i)
bounding |= items.at(i).rect();
contentsSize = bounding.size();
}
@@ -3330,9 +3410,10 @@ void QIconModeViewBase::updateContentsSize()
*/
void QListView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
-#ifndef QT_NO_ACCESSIBILITY
+ 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);
@@ -3340,7 +3421,6 @@ void QListView::currentChanged(const QModelIndex &current, const QModelIndex &pr
}
}
#endif
- QAbstractItemView::currentChanged(current, previous);
}
/*!
@@ -3349,7 +3429,7 @@ void QListView::currentChanged(const QModelIndex &current, const QModelIndex &pr
void QListView::selectionChanged(const QItemSelection &selected,
const QItemSelection &deselected)
{
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
// ### does not work properly for selection ranges.
QModelIndex sel = selected.indexes().value(0);
@@ -3377,7 +3457,7 @@ int QListView::visualIndex(const QModelIndex &index) const
d->executePostedLayout();
QListViewItem itm = d->indexToListViewItem(index);
int visualIndex = d->commonListView->itemIndex(itm);
- for (const auto &idx : qAsConst(d->hiddenRows)) {
+ for (const auto &idx : std::as_const(d->hiddenRows)) {
if (idx.row() <= index.row())
--visualIndex;
}
@@ -3391,7 +3471,47 @@ int QListView::visualIndex(const QModelIndex &index) const
*/
QSize QListView::viewportSizeHint() const
{
- return QAbstractItemView::viewportSizeHint();
+ Q_D(const QListView);
+ // We don't have a nice simple size hint for invalid or wrapping list views.
+ if (!d->model)
+ return QAbstractItemView::viewportSizeHint();
+ const int rc = d->model->rowCount();
+ if (rc == 0 || isWrapping())
+ return QAbstractItemView::viewportSizeHint();
+
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
+
+ if (uniformItemSizes()) {
+ QSize sz = d->cachedItemSize;
+ if (!sz.isValid()) {
+ QModelIndex idx = d->model->index(0, d->column, d->root);
+ sz = d->itemSize(option, idx);
+ }
+ sz.setHeight(rc * sz.height());
+ return sz;
+ }
+
+ // Using AdjustToContents with a high number of rows will normally not make sense, so we limit
+ // this to default 1000 (that is btw the default for QHeaderView::resizeContentsPrecision())
+ // (By setting the property _q_resizeContentPrecision the user can however override this).
+ int maximumRows = 1000;
+ const QVariant userOverrideValue = property("_q_resizeContentPrecision");
+ if (userOverrideValue.isValid() && userOverrideValue.toInt() > 0) {
+ maximumRows = userOverrideValue.toInt();
+ }
+ const int rowCount = qMin(rc, maximumRows);
+
+ int h = 0;
+ int w = 0;
+
+ for (int row = 0; row < rowCount; ++row) {
+ QModelIndex idx = d->model->index(row, d->column, d->root);
+ QSize itemSize = d->itemSize(option, idx);
+ h += itemSize.height();
+ w = qMax(w, itemSize.width());
+ }
+ return QSize(w, h);
}
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qlistview.h b/src/widgets/itemviews/qlistview.h
index 8a5d5e02ae..31b02d660e 100644
--- a/src/widgets/itemviews/qlistview.h
+++ b/src/widgets/itemviews/qlistview.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLISTVIEW_H
#define QLISTVIEW_H
@@ -150,7 +114,8 @@ protected:
void resizeContents(int width, int height);
QSize contentsSize() const;
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>()) override;
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &roles = QList<int>()) override;
void rowsInserted(const QModelIndex &parent, int start, int end) override;
void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) override;
@@ -169,7 +134,7 @@ protected:
void startDrag(Qt::DropActions supportedActions) override;
#endif // QT_CONFIG(draganddrop)
- QStyleOptionViewItem viewOptions() const override;
+ void initViewItemOption(QStyleOptionViewItem *option) const override;
void paintEvent(QPaintEvent *e) override;
int horizontalOffset() const override;
@@ -193,6 +158,7 @@ protected:
private:
int visualIndex(const QModelIndex &index) const;
+ friend class QCommonListViewBase;
Q_DECLARE_PRIVATE(QListView)
Q_DISABLE_COPY(QListView)
diff --git a/src/widgets/itemviews/qlistview_p.h b/src/widgets/itemviews/qlistview_p.h
index 86331bb862..40dabf5656 100644
--- a/src/widgets/itemviews/qlistview_p.h
+++ b/src/widgets/itemviews/qlistview_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLISTVIEW_P_H
#define QLISTVIEW_P_H
@@ -52,6 +16,7 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "qlistview.h"
#include "private/qabstractitemview_p.h"
#include "qbitarray.h"
#include "qbsptree_p.h"
@@ -68,28 +33,28 @@ class QListViewItem
friend class QListModeViewBase;
friend class QIconModeViewBase;
public:
- Q_DECL_CONSTEXPR QListViewItem()
+ constexpr QListViewItem()
: x(-1), y(-1), w(0), h(0), indexHint(-1), visited(0xffff) {}
- Q_DECL_CONSTEXPR QListViewItem(QRect r, int i)
+ constexpr QListViewItem(QRect r, int i)
: x(r.x()), y(r.y()), w(qMin(r.width(), SHRT_MAX)), h(qMin(r.height(), SHRT_MAX)),
indexHint(i), visited(0xffff) {}
- Q_DECL_CONSTEXPR bool operator==(const QListViewItem &other) const {
+ constexpr bool operator==(const QListViewItem &other) const {
return (x == other.x && y == other.y && w == other.w && h == other.h &&
indexHint == other.indexHint); }
- Q_DECL_CONSTEXPR bool operator!=(const QListViewItem &other) const
+ constexpr bool operator!=(const QListViewItem &other) const
{ return !(*this == other); }
- Q_DECL_CONSTEXPR bool isValid() const
+ constexpr bool isValid() const
{ return rect().isValid() && (indexHint > -1); }
- Q_DECL_RELAXED_CONSTEXPR void invalidate()
+ constexpr void invalidate()
{ x = -1; y = -1; w = 0; h = 0; }
- Q_DECL_RELAXED_CONSTEXPR void resize(QSize size)
+ constexpr void resize(QSize size)
{ w = qMin(size.width(), SHRT_MAX); h = qMin(size.height(), SHRT_MAX); }
- Q_DECL_RELAXED_CONSTEXPR void move(QPoint position)
+ constexpr void move(QPoint position)
{ x = position.x(); y = position.y(); }
- Q_DECL_CONSTEXPR int width() const { return w; }
- Q_DECL_CONSTEXPR int height() const { return h; }
+ constexpr int width() const { return w; }
+ constexpr int height() const { return h; }
private:
- Q_DECL_CONSTEXPR QRect rect() const
+ constexpr QRect rect() const
{ return QRect(x, y, w, h); }
int x, y;
short w, h;
@@ -126,7 +91,7 @@ public:
virtual bool doBatchedItemLayout(const QListViewLayoutInfo &info, int max) = 0;
virtual void clear() = 0;
virtual void setRowCount(int) = 0;
- virtual QVector<QModelIndex> intersectingSet(const QRect &area) const = 0;
+ virtual QList<QModelIndex> intersectingSet(const QRect &area) const = 0;
virtual void dataChanged(const QModelIndex &, const QModelIndex &) = 0;
virtual int horizontalScrollToValue(int index, QListView::ScrollHint hint,
@@ -172,7 +137,7 @@ public:
inline QModelIndex modelIndex(int row) const;
inline int rowCount() const;
- inline QStyleOptionViewItem viewOptions() const;
+ inline void initViewItemOption(QStyleOptionViewItem *option) const;
inline QWidget *viewport() const;
inline QRect clipRect() const;
@@ -198,11 +163,11 @@ class QListModeViewBase : public QCommonListViewBase
public:
QListModeViewBase(QListView *q, QListViewPrivate *d);
- QVector<int> flowPositions;
- QVector<int> segmentPositions;
- QVector<int> segmentStartRows;
- QVector<int> segmentExtents;
- QVector<int> scrollValueMap;
+ QList<int> flowPositions;
+ QList<int> segmentPositions;
+ QList<int> segmentStartRows;
+ QList<int> segmentExtents;
+ QList<int> scrollValueMap;
// used when laying out in batches
int batchSavedPosition;
@@ -213,7 +178,7 @@ public:
bool doBatchedItemLayout(const QListViewLayoutInfo &info, int max) override;
void clear() override;
void setRowCount(int rowCount) override { flowPositions.resize(rowCount); }
- QVector<QModelIndex> intersectingSet(const QRect &area) const override;
+ QList<QModelIndex> intersectingSet(const QRect &area) const override;
void dataChanged(const QModelIndex &, const QModelIndex &) override;
int horizontalScrollToValue(int index, QListView::ScrollHint hint,
@@ -251,14 +216,14 @@ public:
QIconModeViewBase(QListView *q, QListViewPrivate *d) : QCommonListViewBase(q, d), interSectingVector(nullptr) {}
QBspTree tree;
- QVector<QListViewItem> items;
+ QList<QListViewItem> items;
QBitArray moved;
- QVector<QModelIndex> draggedItems; // indices to the tree.itemVector
+ QList<QModelIndex> draggedItems; // indices to the tree.itemVector
mutable QPoint draggedItemsPos;
// used when laying out in batches
- QVector<QModelIndex> *interSectingVector; //used from within intersectingSet
+ QList<QModelIndex> *interSectingVector; // used from within intersectingSet
//reimplementations
int itemIndex(const QListViewItem &item) const override;
@@ -266,7 +231,7 @@ public:
bool doBatchedItemLayout(const QListViewLayoutInfo &info, int max) override;
void clear() override;
void setRowCount(int rowCount) override;
- QVector<QModelIndex> intersectingSet(const QRect &area) const override;
+ QList<QModelIndex> intersectingSet(const QRect &area) const override;
void scrollContentsBy(int dx, int dy, bool scrollElasticBand) override;
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) override;
@@ -285,14 +250,13 @@ private:
void initBspTree(const QSize &contents);
QPoint initDynamicLayout(const QListViewLayoutInfo &info);
void doDynamicLayout(const QListViewLayoutInfo &info);
- static void addLeaf(QVector<int> &leaf, const QRect &area,
- uint visited, QBspTree::Data data);
- QRect itemsRect(const QVector<QModelIndex> &indexes) const;
+ static void addLeaf(QList<int> &leaf, const QRect &area, uint visited, QBspTree::Data data);
+ QRect itemsRect(const QList<QModelIndex> &indexes) const;
QRect draggedItemsRect() const;
QPoint snapToGrid(const QPoint &pos) const;
void updateContentsSize();
QPoint draggedItemsDelta() const;
- void drawItems(QPainter *painter, const QVector<QModelIndex> &indexes) const;
+ void drawItems(QPainter *painter, const QList<QModelIndex> &indexes) const;
void moveItem(int index, const QPoint &dest);
};
@@ -309,7 +273,8 @@ public:
bool doItemsLayout(int num);
- inline QVector<QModelIndex> intersectingSet(const QRect &area, bool doLayout = true) const {
+ inline QList<QModelIndex> intersectingSet(const QRect &area, bool doLayout = true) const
+ {
if (doLayout) executePostedLayout();
QRect a = (q_func()->isRightToLeft() ? flipX(area.normalized()) : area.normalized());
return commonListView->intersectingSet(a);
@@ -363,7 +328,7 @@ public:
QRect mapToViewport(const QRect &rect, bool extend = true) const;
- QModelIndex closestIndex(const QRect &target, const QVector<QModelIndex> &candidates) const;
+ QModelIndex closestIndex(const QRect &target, const QList<QModelIndex> &candidates) const;
QSize itemSize(const QStyleOptionViewItem &option, const QModelIndex &index) const;
bool selectionAllowed(const QModelIndex &index) const override
@@ -395,8 +360,9 @@ public:
return isPersistent(idx) && hiddenRows.contains(idx);
}
// helper to avoid checking for isPersistent and creating persistent indexes as above in isHidden
- QVector<int> hiddenRowIds() const {
- QVector<int> rowIds;
+ QList<int> hiddenRowIds() const
+ {
+ QList<int> rowIds;
rowIds.reserve(hiddenRows.size());
for (const auto &idx : hiddenRows)
rowIds += idx.row();
@@ -404,7 +370,7 @@ public:
}
inline bool isHiddenOrDisabled(int row) const { return isHidden(row) || !isIndexEnabled(modelIndex(row)); }
- void removeCurrentAndDisabled(QVector<QModelIndex> *indexes, const QModelIndex &current) const;
+ void removeCurrentAndDisabled(QList<QModelIndex> *indexes, const QModelIndex &current) const;
void scrollElasticBandBy(int dx, int dy);
@@ -482,7 +448,7 @@ inline QModelIndex QCommonListViewBase::modelIndex(int row) const
{ return dd->model->index(row, dd->column, dd->root); }
inline int QCommonListViewBase::rowCount() const { return dd->model->rowCount(dd->root); }
-inline QStyleOptionViewItem QCommonListViewBase::viewOptions() const { return dd->viewOptionsV1(); }
+inline void QCommonListViewBase::initViewItemOption(QStyleOptionViewItem *option) const { qq->initViewItemOption(option); }
inline QWidget *QCommonListViewBase::viewport() const { return dd->viewport; }
inline QRect QCommonListViewBase::clipRect() const { return dd->clipRect(); }
@@ -492,10 +458,10 @@ inline QSize QCommonListViewBase::itemSize(const QStyleOptionViewItem &opt, cons
{ return dd->itemSize(opt, idx); }
inline QAbstractItemDelegate *QCommonListViewBase::delegate(const QModelIndex &idx) const
- { return dd->delegateForIndex(idx); }
+ { return qq->itemDelegateForIndex(idx); }
inline bool QCommonListViewBase::isHidden(int row) const { return dd->isHidden(row); }
-inline int QCommonListViewBase::hiddenCount() const { return dd->hiddenRows.count(); }
+inline int QCommonListViewBase::hiddenCount() const { return dd->hiddenRows.size(); }
inline bool QCommonListViewBase::isRightToLeft() const { return qq->isRightToLeft(); }
diff --git a/src/widgets/itemviews/qlistwidget.cpp b/src/widgets/itemviews/qlistwidget.cpp
index 4aca923151..a91902813a 100644
--- a/src/widgets/itemviews/qlistwidget.cpp
+++ b/src/widgets/itemviews/qlistwidget.cpp
@@ -1,45 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qlistwidget.h"
-#include <qitemdelegate.h>
#include <private/qlistview_p.h>
#include <private/qwidgetitemdata_p.h>
#include <private/qlistwidget_p.h>
@@ -72,7 +35,7 @@ QListModel::~QListModel()
void QListModel::clear()
{
beginResetModel();
- for (int i = 0; i < items.count(); ++i) {
+ for (int i = 0; i < items.size(); ++i) {
if (items.at(i)) {
items.at(i)->d->theid = -1;
items.at(i)->view = nullptr;
@@ -116,8 +79,8 @@ void QListModel::insert(int row, QListWidgetItem *item)
} else {
if (row < 0)
row = 0;
- else if (row > items.count())
- row = items.count();
+ else if (row > items.size())
+ row = items.size();
}
beginInsertRows(QModelIndex(), row, row);
items.insert(row, item);
@@ -127,7 +90,7 @@ void QListModel::insert(int row, QListWidgetItem *item)
void QListModel::insert(int row, const QStringList &labels)
{
- const int count = labels.count();
+ const int count = labels.size();
if (count <= 0)
return;
QListWidget *view = qobject_cast<QListWidget*>(QObject::parent());
@@ -140,8 +103,8 @@ void QListModel::insert(int row, const QStringList &labels)
} else {
if (row < 0)
row = 0;
- else if (row > items.count())
- row = items.count();
+ else if (row > items.size())
+ row = items.size();
beginInsertRows(QModelIndex(), row, row + count - 1);
for (int i = 0; i < count; ++i) {
QListWidgetItem *item = new QListWidgetItem(labels.at(i));
@@ -155,7 +118,7 @@ void QListModel::insert(int row, const QStringList &labels)
QListWidgetItem *QListModel::take(int row)
{
- if (row < 0 || row >= items.count())
+ if (row < 0 || row >= items.size())
return nullptr;
beginRemoveRows(QModelIndex(), row, row);
@@ -169,8 +132,8 @@ QListWidgetItem *QListModel::take(int row)
void QListModel::move(int srcRow, int dstRow)
{
if (srcRow == dstRow
- || srcRow < 0 || srcRow >= items.count()
- || dstRow < 0 || dstRow > items.count())
+ || srcRow < 0 || srcRow >= items.size()
+ || dstRow < 0 || dstRow > items.size())
return;
if (!beginMoveRows(QModelIndex(), srcRow, srcRow, QModelIndex(), dstRow))
@@ -183,7 +146,7 @@ void QListModel::move(int srcRow, int dstRow)
int QListModel::rowCount(const QModelIndex &parent) const
{
- return parent.isValid() ? 0 : items.count();
+ return parent.isValid() ? 0 : items.size();
}
QModelIndex QListModel::index(const QListWidgetItem *item_) const
@@ -194,7 +157,7 @@ QModelIndex QListModel::index(const QListWidgetItem *item_) const
return QModelIndex();
int row;
const int theid = item->d->theid;
- if (theid >= 0 && theid < items.count() && items.at(theid) == item) {
+ if (theid >= 0 && theid < items.size() && items.at(theid) == item) {
row = theid;
} else { // we need to search for the item
row = items.lastIndexOf(item); // lastIndexOf is an optimization in favor of indexOf
@@ -214,20 +177,19 @@ QModelIndex QListModel::index(int row, int column, const QModelIndex &parent) co
QVariant QListModel::data(const QModelIndex &index, int role) const
{
- if (!index.isValid() || index.row() >= items.count())
+ if (!index.isValid() || index.row() >= items.size())
return QVariant();
return items.at(index.row())->data(role);
}
bool QListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
- if (!index.isValid() || index.row() >= items.count())
+ if (!index.isValid() || index.row() >= items.size())
return false;
items.at(index.row())->setData(role, value);
return true;
}
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool QListModel::clearItemData(const QModelIndex &index)
{
if (!checkIndex(index, CheckIndexOption::IndexIsValid))
@@ -238,18 +200,17 @@ bool QListModel::clearItemData(const QModelIndex &index)
if (std::all_of(beginIter, endIter, [](const QWidgetItemData& data) -> bool { return !data.value.isValid(); }))
return true; //it's already cleared
item->d->values.clear();
- emit dataChanged(index, index, QVector<int>{});
+ emit dataChanged(index, index, QList<int> {});
return true;
}
-#endif
QMap<int, QVariant> QListModel::itemData(const QModelIndex &index) const
{
QMap<int, QVariant> roles;
- if (!index.isValid() || index.row() >= items.count())
+ if (!index.isValid() || index.row() >= items.size())
return roles;
QListWidgetItem *itm = items.at(index.row());
- for (int i = 0; i < itm->d->values.count(); ++i) {
+ for (int i = 0; i < itm->d->values.size(); ++i) {
roles.insert(itm->d->values.at(i).role,
itm->d->values.at(i).value);
}
@@ -326,7 +287,7 @@ bool QListModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int co
Qt::ItemFlags QListModel::flags(const QModelIndex &index) const
{
- if (!index.isValid() || index.row() >= items.count() || index.model() != this)
+ if (!index.isValid() || index.row() >= items.size() || index.model() != this)
return Qt::ItemIsDropEnabled; // we allow drops outside the items
return items.at(index.row())->flags();
}
@@ -338,18 +299,18 @@ void QListModel::sort(int column, Qt::SortOrder order)
emit layoutAboutToBeChanged({}, QAbstractItemModel::VerticalSortHint);
- QVector < QPair<QListWidgetItem*,int> > sorting(items.count());
- for (int i = 0; i < items.count(); ++i) {
+ QList<QPair<QListWidgetItem *, int>> sorting(items.size());
+ for (int i = 0; i < items.size(); ++i) {
QListWidgetItem *item = items.at(i);
sorting[i].first = item;
sorting[i].second = i;
}
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.count();
+ const int sortingCount = sorting.size();
fromIndexes.reserve(sortingCount);
toIndexes.reserve(sortingCount);
for (int r = 0; r < sortingCount; ++r) {
@@ -366,72 +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;
- int count = end - start + 1;
- QVector < 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) {
- 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.count(); ++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) {
- emit layoutAboutToBeChanged();
- items = tmp;
- changePersistentIndexList(oldPersistentIndexes, newPersistentIndexes);
- emit layoutChanged();
- }
+ /** 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,
@@ -456,7 +379,7 @@ QList<QListWidgetItem*>::iterator QListModel::sortedInsertionIterator(
return std::lower_bound(begin, end, item, QListModelGreaterThan());
}
-void QListModel::itemChanged(QListWidgetItem *item, const QVector<int> &roles)
+void QListModel::itemChanged(QListWidgetItem *item, const QList<int> &roles)
{
const QModelIndex idx = index(item);
emit dataChanged(idx, idx, roles);
@@ -465,7 +388,9 @@ void QListModel::itemChanged(QListWidgetItem *item, const QVector<int> &roles)
QStringList QListModel::mimeTypes() const
{
const QListWidget *view = qobject_cast<const QListWidget*>(QObject::parent());
- return view->mimeTypes();
+ if (view)
+ return view->mimeTypes();
+ return {};
}
QMimeData *QListModel::internalMimeData() const
@@ -476,7 +401,7 @@ QMimeData *QListModel::internalMimeData() const
QMimeData *QListModel::mimeData(const QModelIndexList &indexes) const
{
QList<QListWidgetItem*> itemlist;
- const int indexesCount = indexes.count();
+ const int indexesCount = indexes.size();
itemlist.reserve(indexesCount);
for (int i = 0; i < indexesCount; ++i)
itemlist << at(indexes.at(i).row());
@@ -497,7 +422,7 @@ bool QListModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
if (index.isValid())
row = index.row();
else if (row == -1)
- row = items.count();
+ row = items.size();
return view->dropMimeData(row, data, action);
}
@@ -734,7 +659,7 @@ void QListWidgetItem::setData(int role, const QVariant &value)
{
bool found = false;
role = (role == Qt::EditRole ? Qt::DisplayRole : role);
- for (int i = 0; i < d->values.count(); ++i) {
+ for (int i = 0; i < d->values.size(); ++i) {
if (d->values.at(i).role == role) {
if (d->values.at(i).value == value)
return;
@@ -746,9 +671,9 @@ void QListWidgetItem::setData(int role, const QVariant &value)
if (!found)
d->values.append(QWidgetItemData(role, value));
if (QListModel *model = listModel()) {
- const QVector<int> roles((role == Qt::DisplayRole) ?
- QVector<int>({Qt::DisplayRole, Qt::EditRole}) :
- QVector<int>({role}));
+ const QList<int> roles((role == Qt::DisplayRole)
+ ? QList<int>({ Qt::DisplayRole, Qt::EditRole })
+ : QList<int>({ role }));
model->itemChanged(this, roles);
}
}
@@ -762,7 +687,7 @@ void QListWidgetItem::setData(int role, const QVariant &value)
QVariant QListWidgetItem::data(int role) const
{
role = (role == Qt::EditRole ? Qt::DisplayRole : role);
- for (int i = 0; i < d->values.count(); ++i)
+ for (int i = 0; i < d->values.size(); ++i)
if (d->values.at(i).role == role)
return d->values.at(i).value;
return QVariant();
@@ -930,21 +855,25 @@ QDataStream &operator>>(QDataStream &in, QListWidgetItem &item)
*/
/*!
+ \if defined(qt7)
+
+ \fn Qt::Alignment QListWidgetItem::textAlignment() const
+
+ Returns the text alignment for the list item.
+
+ \else
+
\fn int QListWidgetItem::textAlignment() const
Returns the text alignment for the list item.
- \sa Qt::AlignmentFlag
-*/
+ \note This function returns an int for historical reasons. It will
+ be corrected to return Qt::Alignment in Qt 7.
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \fn QColor QListWidgetItem::backgroundColor() const
- \obsolete
+ \sa Qt::Alignment
- This function is deprecated. Use background() instead.
+ \endif
*/
-#endif
/*!
\fn QBrush QListWidgetItem::background() const
@@ -955,17 +884,6 @@ QDataStream &operator>>(QDataStream &in, QListWidgetItem &item)
\sa setBackground(), foreground()
*/
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \fn QColor QListWidgetItem::textColor() const
- \obsolete
-
- Returns the color used to display the list item's text.
-
- This function is deprecated. Use foreground() instead.
-*/
-#endif
-
/*!
\fn QBrush QListWidgetItem::foreground() const
\since 4.2
@@ -1108,18 +1026,26 @@ void QListWidgetItem::setFlags(Qt::ItemFlags aflags)
*/
/*!
+ \obsolete [6.4] Use the overload that takes a Qt::Alignment argument.
+
\fn void QListWidgetItem::setTextAlignment(int alignment)
Sets the list item's text alignment to \a alignment.
- \sa Qt::AlignmentFlag
+ \sa Qt::Alignment
*/
/*!
- \fn void QListWidgetItem::setBackgroundColor(const QColor &color)
- \obsolete
+ \since 6.4
+
+ \fn void QListWidgetItem::setTextAlignment(Qt::Alignment alignment)
- This function is deprecated. Use setBackground() instead.
+ Sets the list item's text alignment to \a alignment.
+*/
+
+/*!
+ \fn void QListWidgetItem::setTextAlignment(Qt::AlignmentFlag alignment)
+ \internal
*/
/*!
@@ -1133,15 +1059,6 @@ void QListWidgetItem::setFlags(Qt::ItemFlags aflags)
\sa background(), setForeground()
*/
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \fn void QListWidgetItem::setTextColor(const QColor &color)
- \obsolete
-
- This function is deprecated. Use setForeground() instead.
-*/
-#endif
-
/*!
\fn void QListWidgetItem::setForeground(const QBrush &brush)
\since 4.2
@@ -1166,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);
@@ -1234,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,
@@ -1447,6 +1378,8 @@ QListWidget::QListWidget(QWidget *parent)
QListWidget::~QListWidget()
{
+ Q_D(QListWidget);
+ d->clearConnections();
}
/*!
@@ -1457,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)
+ };
}
}
@@ -1791,34 +1722,6 @@ void QListWidget::setItemWidget(QListWidgetItem *item, QWidget *widget)
QAbstractItemView::setIndexWidget(index, widget);
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- Returns \c true if \a item is selected; otherwise returns \c false.
-
- \obsolete
-
- This function is deprecated. Use QListWidgetItem::isSelected() instead.
-*/
-bool QListWidget::isItemSelected(const QListWidgetItem *item) const
-{
- return ((item && item->listWidget() == this) ? item->isSelected() : false);
-}
-
-/*!
- Selects or deselects the given \a item depending on whether \a select is
- true of false.
-
- \obsolete
-
- This function is deprecated. Use QListWidgetItem::setSelected() instead.
-*/
-void QListWidget::setItemSelected(const QListWidgetItem *item, bool select)
-{
- if (item && item->listWidget() == this)
- const_cast<QListWidgetItem*>(item)->setSelected(select);
-}
-#endif
-
/*!
Returns a list of all selected items in the list widget.
*/
@@ -1828,7 +1731,7 @@ QList<QListWidgetItem*> QListWidget::selectedItems() const
Q_D(const QListWidget);
QModelIndexList indexes = selectionModel()->selectedIndexes();
QList<QListWidgetItem*> items;
- const int numIndexes = indexes.count();
+ const int numIndexes = indexes.size();
items.reserve(numIndexes);
for (int i = 0; i < numIndexes; ++i)
items.append(d->listModel()->at(indexes.at(i).row()));
@@ -1853,32 +1756,6 @@ QList<QListWidgetItem*> QListWidget::findItems(const QString &text, Qt::MatchFla
return items;
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- Returns \c true if the \a item is explicitly hidden; otherwise returns \c false.
-
- \obsolete
-
- This function is deprecated. Use QListWidgetItem::isHidden() instead.
-*/
-bool QListWidget::isItemHidden(const QListWidgetItem *item) const
-{
- return isRowHidden(row(item));
-}
-
-/*!
- If \a hide is true, the \a item will be hidden; otherwise it will be shown.
-
- \obsolete
-
- This function is deprecated. Use QListWidgetItem::setHidden() instead.
-*/
-void QListWidget::setItemHidden(const QListWidgetItem *item, bool hide)
-{
- setRowHidden(row(item), hide);
-}
-#endif
-
/*!
Scrolls the view if necessary to ensure that the \a item is visible.
@@ -1923,11 +1800,7 @@ QStringList QListWidget::mimeTypes() const
If the list of items is empty, \nullptr is returned instead of a
serialized empty list.
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
QMimeData *QListWidget::mimeData(const QList<QListWidgetItem *> &items) const
-#else
-QMimeData *QListWidget::mimeData(const QList<QListWidgetItem*> items) const
-#endif
{
Q_D(const QListWidget);
@@ -1935,7 +1808,7 @@ QMimeData *QListWidget::mimeData(const QList<QListWidgetItem*> items) const
// if non empty, it's called from the model's own mimeData
if (cachedIndexes.isEmpty()) {
- cachedIndexes.reserve(items.count());
+ cachedIndexes.reserve(items.size());
for (QListWidgetItem *item : items)
cachedIndexes << indexFromItem(item);
@@ -1971,45 +1844,8 @@ bool QListWidget::dropMimeData(int index, const QMimeData *data, Qt::DropAction
}
/*! \reimp */
-void QListWidget::dropEvent(QDropEvent *event) {
- Q_D(QListWidget);
- if (event->source() == this && d->movement != Static) {
- QListView::dropEvent(event);
- return;
- }
-
- if (event->source() == this && (event->dropAction() == Qt::MoveAction ||
- dragDropMode() == QAbstractItemView::InternalMove)) {
- QModelIndex topIndex;
- int col = -1;
- int row = -1;
- if (d->dropOn(event, &row, &col, &topIndex)) {
- QList<QModelIndex> selIndexes = selectedIndexes();
- QList<QPersistentModelIndex> persIndexes;
- const int selIndexesCount = selIndexes.count();
- persIndexes.reserve(selIndexesCount);
- for (int i = 0; i < selIndexesCount; i++)
- persIndexes.append(selIndexes.at(i));
-
- if (persIndexes.contains(topIndex))
- return;
- std::sort(persIndexes.begin(), persIndexes.end()); // The dropped items will remain in the same visual order.
-
- QPersistentModelIndex dropRow = model()->index(row, col, topIndex);
-
- int r = row == -1 ? count() : (dropRow.row() >= 0 ? dropRow.row() : row);
- for (int i = 0; i < persIndexes.count(); ++i) {
- const QPersistentModelIndex &pIndex = persIndexes.at(i);
- d->listModel()->move(pIndex.row(), r);
- r = pIndex.row() + 1; // Dropped items are inserted contiguously and in the right order.
- }
-
- event->accept();
- // Don't want QAbstractItemView to delete it because it was "moved" we already did it
- event->setDropAction(Qt::CopyAction);
- }
- }
-
+void QListWidget::dropEvent(QDropEvent *event)
+{
QListView::dropEvent(event);
}
@@ -2050,18 +1886,6 @@ QModelIndex QListWidget::indexFromItem(const QListWidgetItem *item) const
return d->listModel()->index(item);
}
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-/*!
- \internal
- \obsolete
- \overload
-*/
-QModelIndex QListWidget::indexFromItem(QListWidgetItem *item) const
-{
- return indexFromItem(const_cast<const QListWidgetItem *>(item));
-}
-#endif
-
/*!
Returns a pointer to the QListWidgetItem associated with the given \a index.
*/
diff --git a/src/widgets/itemviews/qlistwidget.h b/src/widgets/itemviews/qlistwidget.h
index 1319d658ab..c6ba714c43 100644
--- a/src/widgets/itemviews/qlistwidget.h
+++ b/src/widgets/itemviews/qlistwidget.h
@@ -1,50 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLISTWIDGET_H
#define QLISTWIDGET_H
-#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qlistview.h>
-#include <QtCore/qvariant.h>
-#include <QtCore/qvector.h>
+#include <QtWidgets/qtwidgetsglobal.h>
+#include <QtCore/qlist.h>
#include <QtCore/qitemselectionmodel.h>
+#include <QtCore/qvariant.h>
QT_REQUIRE_CONFIG(listwidget);
@@ -93,7 +57,7 @@ public:
{ return data(Qt::StatusTipRole).toString(); }
inline void setStatusTip(const QString &statusTip);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
inline QString toolTip() const
{ return data(Qt::ToolTipRole).toString(); }
inline void setToolTip(const QString &toolTip);
@@ -109,42 +73,35 @@ public:
{ return qvariant_cast<QFont>(data(Qt::FontRole)); }
inline void setFont(const QFont &font);
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
inline int textAlignment() const
{ return data(Qt::TextAlignmentRole).toInt(); }
+#else
+ inline Qt::Alignment textAlignment() const
+ { return qvariant_cast<Qt::Alignment>(data(Qt::TextAlignmentRole)); }
+#endif
+#if QT_DEPRECATED_SINCE(6, 4)
+ QT_DEPRECATED_VERSION_X_6_4("Use the overload taking Qt::Alignment")
inline void setTextAlignment(int alignment)
{ setData(Qt::TextAlignmentRole, alignment); }
-
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QListWidgetItem::background() instead")
- inline QColor backgroundColor() const
- { return qvariant_cast<QColor>(data(Qt::BackgroundRole)); }
+ inline void setTextAlignment(Qt::AlignmentFlag alignment)
+ { setData(Qt::TextAlignmentRole, QVariant::fromValue(Qt::Alignment(alignment))); }
#endif
- // no QT_DEPRECATED_SINCE because it is a virtual function
- QT_DEPRECATED_X ("Use QListWidgetItem::setBackground() instead")
- virtual void setBackgroundColor(const QColor &color)
- { setData(Qt::BackgroundRole, color); }
+ inline void setTextAlignment(Qt::Alignment alignment)
+ { setData(Qt::TextAlignmentRole, QVariant::fromValue(alignment)); }
inline QBrush background() const
{ return qvariant_cast<QBrush>(data(Qt::BackgroundRole)); }
inline void setBackground(const QBrush &brush)
{ setData(Qt::BackgroundRole, brush.style() != Qt::NoBrush ? QVariant(brush) : QVariant()); }
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QListWidgetItem::foreground() instead")
- inline QColor textColor() const
- { return qvariant_cast<QColor>(data(Qt::ForegroundRole)); }
- QT_DEPRECATED_X ("Use QListWidgetItem::setForeground() instead")
- inline void setTextColor(const QColor &color)
- { setData(Qt::ForegroundRole, color); }
-#endif
-
inline QBrush foreground() const
{ return qvariant_cast<QBrush>(data(Qt::ForegroundRole)); }
inline void setForeground(const QBrush &brush)
{ setData(Qt::ForegroundRole, brush.style() != Qt::NoBrush ? QVariant(brush) : QVariant()); }
inline Qt::CheckState checkState() const
- { return static_cast<Qt::CheckState>(data(Qt::CheckStateRole).toInt()); }
+ { return qvariant_cast<Qt::CheckState>(data(Qt::CheckStateRole)); }
inline void setCheckState(Qt::CheckState state)
{ setData(Qt::CheckStateRole, static_cast<int>(state)); }
@@ -169,7 +126,6 @@ public:
private:
QListModel *listModel() const;
int rtti;
- QVector<void *> dummy;
QListWidget *view;
QListWidgetItemPrivate *d;
Qt::ItemFlags itemFlags;
@@ -184,7 +140,7 @@ inline void QListWidgetItem::setIcon(const QIcon &aicon)
inline void QListWidgetItem::setStatusTip(const QString &astatusTip)
{ setData(Qt::StatusTipRole, astatusTip); }
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
inline void QListWidgetItem::setToolTip(const QString &atoolTip)
{ setData(Qt::ToolTipRole, atoolTip); }
#endif
@@ -208,7 +164,8 @@ class Q_WIDGETS_EXPORT QListWidget : public QListView
{
Q_OBJECT
Q_PROPERTY(int count READ count)
- Q_PROPERTY(int currentRow READ currentRow WRITE setCurrentRow NOTIFY currentRowChanged USER true)
+ Q_PROPERTY(int currentRow READ currentRow WRITE setCurrentRow NOTIFY currentRowChanged
+ USER true)
Q_PROPERTY(bool sortingEnabled READ isSortingEnabled WRITE setSortingEnabled)
friend class QListWidgetItem;
@@ -256,24 +213,15 @@ public:
void setItemWidget(QListWidgetItem *item, QWidget *widget);
inline void removeItemWidget(QListWidgetItem *item);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QListWidgetItem::isSelected() instead")
- bool isItemSelected(const QListWidgetItem *item) const;
- QT_DEPRECATED_X ("Use QListWidgetItem::setSelected() instead")
- void setItemSelected(const QListWidgetItem *item, bool select);
-#endif
QList<QListWidgetItem*> selectedItems() const;
QList<QListWidgetItem*> findItems(const QString &text, Qt::MatchFlags flags) const;
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QListWidgetItem::isHidden() instead")
- bool isItemHidden(const QListWidgetItem *item) const;
- QT_DEPRECATED_X ("Use QListWidgetItem::setHidden() instead")
- void setItemHidden(const QListWidgetItem *item, bool hide);
-#endif
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ QList<QListWidgetItem*> items(const QMimeData *data) const;
+
+ QModelIndex indexFromItem(const QListWidgetItem *item) const;
+ QListWidgetItem *itemFromIndex(const QModelIndex &index) const;
+
protected:
-#endif
#if QT_CONFIG(draganddrop)
void dropEvent(QDropEvent *event) override;
#endif
@@ -287,7 +235,6 @@ Q_SIGNALS:
void itemDoubleClicked(QListWidgetItem *item);
void itemActivated(QListWidgetItem *item);
void itemEntered(QListWidgetItem *item);
- // ### Qt 6: add changed roles
void itemChanged(QListWidgetItem *item);
void currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous);
@@ -299,45 +246,18 @@ Q_SIGNALS:
protected:
bool event(QEvent *e) override;
virtual QStringList mimeTypes() const;
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
virtual QMimeData *mimeData(const QList<QListWidgetItem *> &items) const;
-#else
- virtual QMimeData *mimeData(const QList<QListWidgetItem*> items) const;
-#endif
#if QT_CONFIG(draganddrop)
virtual bool dropMimeData(int index, const QMimeData *data, Qt::DropAction action);
virtual Qt::DropActions supportedDropActions() const;
#endif
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
-public:
-#else
-protected:
-#endif
- QList<QListWidgetItem*> items(const QMimeData *data) const;
-
- QModelIndex indexFromItem(const QListWidgetItem *item) const;
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
- QModelIndex indexFromItem(QListWidgetItem *item) const; // ### Qt 6: remove
-#endif
- QListWidgetItem *itemFromIndex(const QModelIndex &index) const;
-
private:
void setModel(QAbstractItemModel *model) override;
Qt::SortOrder sortOrder() const;
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 65a7124322..1007542ddc 100644
--- a/src/widgets/itemviews/qlistwidget_p.h
+++ b/src/widgets/itemviews/qlistwidget_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLISTWIDGET_P_H
#define QLISTWIDGET_P_H
@@ -54,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
@@ -100,9 +65,7 @@ public:
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role) override;
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool clearItemData(const QModelIndex &index) override;
-#endif
QMap<int, QVariant> itemData(const QModelIndex &index) const override;
@@ -123,7 +86,7 @@ public:
const QList<QListWidgetItem*>::iterator &end,
Qt::SortOrder order, QListWidgetItem *item);
- void itemChanged(QListWidgetItem *item, const QVector<int> &roles = QVector<int>());
+ void itemChanged(QListWidgetItem *item, const QList<int> &roles = QList<int>());
// dnd
QStringList mimeTypes() const override;
@@ -151,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
@@ -169,7 +136,7 @@ class QListWidgetItemPrivate
public:
QListWidgetItemPrivate(QListWidgetItem *item) : q(item), theid(-1) {}
QListWidgetItem *q;
- QVector<QWidgetItemData> values;
+ QList<QWidgetItemData> values;
int theid;
};
diff --git a/src/widgets/itemviews/qstyleditemdelegate.cpp b/src/widgets/itemviews/qstyleditemdelegate.cpp
index f42af2ea00..0587e8d0be 100644
--- a/src/widgets/itemviews/qstyleditemdelegate.cpp
+++ b/src/widgets/itemviews/qstyleditemdelegate.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstyleditemdelegate.h"
@@ -66,6 +30,7 @@
#include <qmetaobject.h>
#include <qtextlayout.h>
#include <private/qabstractitemdelegate_p.h>
+#include <private/qabstractitemmodel_p.h>
#include <private/qtextengine_p.h>
#include <private/qlayoutengine_p.h>
#include <qdebug.h>
@@ -74,6 +39,7 @@
#include <qtableview.h>
#endif
+#include <array>
#include <limits.h>
QT_BEGIN_NAMESPACE
@@ -96,6 +62,16 @@ public:
}
QItemEditorFactory *factory;
+
+ mutable std::array<QModelRoleData, 7> modelRoleData = {
+ QModelRoleData(Qt::FontRole),
+ QModelRoleData(Qt::TextAlignmentRole),
+ QModelRoleData(Qt::ForegroundRole),
+ QModelRoleData(Qt::CheckStateRole),
+ QModelRoleData(Qt::DecorationRole),
+ QModelRoleData(Qt::DisplayRole),
+ QModelRoleData(Qt::BackgroundRole)
+ };
};
/*!
@@ -139,8 +115,7 @@ public:
\row \li \l Qt::AccessibleDescriptionRole \li QString
\row \li \l Qt::AccessibleTextRole \li QString
\endomit
- \row \li \l Qt::BackgroundRole \li QBrush (\since 4.2)
- \row \li \l Qt::BackgroundColorRole \li QColor (obsolete; use Qt::BackgroundRole instead)
+ \row \li \l Qt::BackgroundRole \li QBrush \since 4.2
\row \li \l Qt::CheckStateRole \li Qt::CheckState
\row \li \l Qt::DecorationRole \li QIcon, QPixmap, QImage and QColor
\row \li \l Qt::DisplayRole \li QString and types with a string representation
@@ -151,8 +126,7 @@ public:
\row \li \l Qt::StatusTipRole \li
\endomit
\row \li \l Qt::TextAlignmentRole \li Qt::Alignment
- \row \li \l Qt::ForegroundRole \li QBrush (\since 4.2)
- \row \li \l Qt::TextColorRole \li QColor (obsolete; use Qt::ForegroundRole instead)
+ \row \li \l Qt::ForegroundRole \li QBrush \since 4.2
\omit
\row \li \l Qt::ToolTipRole
\row \li \l Qt::WhatsThisRole
@@ -230,8 +204,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}, {Color Editor Factory Example}
*/
@@ -278,33 +251,43 @@ QString QStyledItemDelegate::displayText(const QVariant &value, const QLocale& l
void QStyledItemDelegate::initStyleOption(QStyleOptionViewItem *option,
const QModelIndex &index) const
{
- QVariant value = index.data(Qt::FontRole);
- if (value.isValid() && !value.isNull()) {
- option->font = qvariant_cast<QFont>(value).resolve(option->font);
+ option->index = index;
+
+ Q_D(const QStyledItemDelegate);
+ QModelRoleDataSpan modelRoleDataSpan = d->modelRoleData;
+ index.multiData(modelRoleDataSpan);
+
+ const QVariant *value;
+ value = modelRoleDataSpan.dataForRole(Qt::FontRole);
+ if (value->isValid() && !value->isNull()) {
+ option->font = qvariant_cast<QFont>(*value).resolve(option->font);
option->fontMetrics = QFontMetrics(option->font);
}
- value = index.data(Qt::TextAlignmentRole);
- if (value.isValid() && !value.isNull())
- option->displayAlignment = Qt::Alignment(value.toInt());
+ value = modelRoleDataSpan.dataForRole(Qt::TextAlignmentRole);
+ if (value->isValid() && !value->isNull())
+ option->displayAlignment = QtPrivate::legacyFlagValueFromModelData<Qt::Alignment>(*value);
- value = index.data(Qt::ForegroundRole);
- if (value.canConvert<QBrush>())
- option->palette.setBrush(QPalette::Text, qvariant_cast<QBrush>(value));
+ value = modelRoleDataSpan.dataForRole(Qt::ForegroundRole);
+ if (value->canConvert<QBrush>())
+ option->palette.setBrush(QPalette::Text, qvariant_cast<QBrush>(*value));
- option->index = index;
- value = index.data(Qt::CheckStateRole);
- if (value.isValid() && !value.isNull()) {
+ value = modelRoleDataSpan.dataForRole(Qt::CheckStateRole);
+ if (value->isValid() && !value->isNull()) {
option->features |= QStyleOptionViewItem::HasCheckIndicator;
- option->checkState = static_cast<Qt::CheckState>(value.toInt());
+ option->checkState = QtPrivate::legacyEnumValueFromModelData<Qt::CheckState>(*value);
}
- value = index.data(Qt::DecorationRole);
- if (value.isValid() && !value.isNull()) {
+ value = modelRoleDataSpan.dataForRole(Qt::DecorationRole);
+ if (value->isValid() && !value->isNull()) {
option->features |= QStyleOptionViewItem::HasDecoration;
- switch (value.type()) {
- case QVariant::Icon: {
- option->icon = qvariant_cast<QIcon>(value);
+ 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;
@@ -319,22 +302,22 @@ void QStyledItemDelegate::initStyleOption(QStyleOptionViewItem *option,
qMin(option->decorationSize.height(), actualSize.height()));
break;
}
- case QVariant::Color: {
+ case QMetaType::QColor: {
QPixmap pixmap(option->decorationSize);
- pixmap.fill(qvariant_cast<QColor>(value));
+ pixmap.fill(qvariant_cast<QColor>(*value));
option->icon = QIcon(pixmap);
break;
}
- case QVariant::Image: {
- QImage image = qvariant_cast<QImage>(value);
+ case QMetaType::QImage: {
+ QImage image = qvariant_cast<QImage>(*value);
option->icon = QIcon(QPixmap::fromImage(image));
- option->decorationSize = image.size() / image.devicePixelRatio();
+ option->decorationSize = image.deviceIndependentSize().toSize();
break;
}
- case QVariant::Pixmap: {
- QPixmap pixmap = qvariant_cast<QPixmap>(value);
+ case QMetaType::QPixmap: {
+ QPixmap pixmap = qvariant_cast<QPixmap>(*value);
option->icon = QIcon(pixmap);
- option->decorationSize = pixmap.size() / pixmap.devicePixelRatio();
+ option->decorationSize = pixmap.deviceIndependentSize().toSize();
break;
}
default:
@@ -342,13 +325,14 @@ void QStyledItemDelegate::initStyleOption(QStyleOptionViewItem *option,
}
}
- value = index.data(Qt::DisplayRole);
- if (value.isValid() && !value.isNull()) {
+ value = modelRoleDataSpan.dataForRole(Qt::DisplayRole);
+ if (value->isValid() && !value->isNull()) {
option->features |= QStyleOptionViewItem::HasDisplay;
- option->text = displayText(value, option->locale);
+ option->text = displayText(*value, option->locale);
}
- option->backgroundBrush = qvariant_cast<QBrush>(index.data(Qt::BackgroundRole));
+ value = modelRoleDataSpan.dataForRole(Qt::BackgroundRole);
+ option->backgroundBrush = qvariant_cast<QBrush>(*value);
// disable style animations for checkboxes etc. within itemviews (QTBUG-30146)
option->styleObject = nullptr;
@@ -421,9 +405,10 @@ QSize QStyledItemDelegate::sizeHint(const QStyleOptionViewItem &option,
\sa QAbstractItemDelegate::createEditor()
*/
QWidget *QStyledItemDelegate::createEditor(QWidget *parent,
- const QStyleOptionViewItem &,
+ const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
+ Q_UNUSED(option);
Q_D(const QStyledItemDelegate);
if (!index.isValid())
return nullptr;
@@ -441,19 +426,14 @@ QWidget *QStyledItemDelegate::createEditor(QWidget *parent,
*/
void QStyledItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(editor);
- Q_UNUSED(index);
-#else
QVariant v = index.data(Qt::EditRole);
QByteArray n = editor->metaObject()->userProperty().name();
if (!n.isEmpty()) {
if (!v.isValid())
- v = QVariant(editor->property(n).userType(), (const void *)nullptr);
+ v = QVariant(editor->property(n).metaType());
editor->setProperty(n, v);
}
-#endif
}
/*!
@@ -470,11 +450,6 @@ void QStyledItemDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(model);
- Q_UNUSED(editor);
- Q_UNUSED(index);
-#else
Q_D(const QStyledItemDelegate);
Q_ASSERT(model);
Q_ASSERT(editor);
@@ -484,7 +459,6 @@ void QStyledItemDelegate::setModelData(QWidget *editor,
model->data(index, Qt::EditRole).userType());
if (!n.isEmpty())
model->setData(index, editor->property(n), Qt::EditRole);
-#endif
}
/*!
@@ -502,15 +476,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);
@@ -558,8 +524,9 @@ void QStyledItemDelegate::setItemEditorFactory(QItemEditorFactory *factory)
\li \uicontrol Esc
\endlist
- If the \a editor's type is QTextEdit or QPlainTextEdit then \uicontrol Enter and
- \uicontrol Return keys are \e not handled.
+ If the \a editor's type is QTextEdit or QPlainTextEdit then \uicontrol Tab,
+ \uicontrol Backtab, \uicontrol Enter and \uicontrol Return keys are \e not
+ handled.
In the case of \uicontrol Tab, \uicontrol Backtab, \uicontrol Enter and \uicontrol Return
key press events, the \a editor's data is committed to the model
@@ -612,7 +579,7 @@ bool QStyledItemDelegate::editorEvent(QEvent *event,
initStyleOption(&viewOpt, index);
QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, widget);
QMouseEvent *me = static_cast<QMouseEvent*>(event);
- if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
+ if (me->button() != Qt::LeftButton || !checkRect.contains(me->position().toPoint()))
return false;
if ((event->type() == QEvent::MouseButtonPress)
@@ -627,7 +594,7 @@ bool QStyledItemDelegate::editorEvent(QEvent *event,
return false;
}
- Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
+ Qt::CheckState state = QtPrivate::legacyEnumValueFromModelData<Qt::CheckState>(value);
if (flags & Qt::ItemIsUserTristate)
state = ((Qt::CheckState)((state + 1) % 3));
else
diff --git a/src/widgets/itemviews/qstyleditemdelegate.h b/src/widgets/itemviews/qstyleditemdelegate.h
index 2df2450f07..23f059355d 100644
--- a/src/widgets/itemviews/qstyleditemdelegate.h
+++ b/src/widgets/itemviews/qstyleditemdelegate.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTYLEDITEMDELEGATE_H
#define QSTYLEDITEMDELEGATE_H
diff --git a/src/widgets/itemviews/qtableview.cpp b/src/widgets/itemviews/qtableview.cpp
index 81fceba8dc..5726348bc5 100644
--- a/src/widgets/itemviews/qtableview.cpp
+++ b/src/widgets/itemviews/qtableview.cpp
@@ -1,46 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtableview.h"
#include <qheaderview.h>
-#include <qitemdelegate.h>
+#include <qabstractitemdelegate.h>
#include <qapplication.h>
#include <qpainter.h>
#include <qstyle.h>
@@ -55,7 +19,7 @@
#include <private/qtableview_p.h>
#include <private/qheaderview_p.h>
#include <private/qscrollbar_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include <qaccessible.h>
#endif
@@ -79,7 +43,7 @@ void QSpanCollection::addSpan(QSpanCollection::Span *span)
const SubIndex previousList = it_y.value();
for (Span *s : previousList) {
//If a subspans intersect the row, we need to split it into subspans
- if(s->bottom() >= span->top())
+ if (s->bottom() >= span->top())
sub_index.insert(-s->left(), s);
}
}
@@ -90,7 +54,7 @@ void QSpanCollection::addSpan(QSpanCollection::Span *span)
//insert the span as supspan in all the lists that intesects the span
while(-it_y.key() <= span->bottom()) {
(*it_y).insert(-span->left(), span);
- if(it_y == index.begin())
+ if (it_y == index.begin())
break;
--it_y;
}
@@ -112,7 +76,7 @@ void QSpanCollection::updateSpan(QSpanCollection::Span *span, int old_height)
Q_ASSERT(it_y != index.end()); //it_y must exist since the span is in the list
while (-it_y.key() <= span->bottom()) {
(*it_y).insert(-span->left(), span);
- if(it_y == index.begin())
+ if (it_y == index.begin())
break;
--it_y;
}
@@ -123,12 +87,13 @@ void QSpanCollection::updateSpan(QSpanCollection::Span *span, int old_height)
while (-it_y.key() <= span->top() + old_height -1) {
if (-it_y.key() > span->bottom()) {
int removed = (*it_y).remove(-span->left());
- Q_ASSERT(removed == 1); Q_UNUSED(removed);
+ Q_ASSERT(removed == 1);
+ Q_UNUSED(removed);
if (it_y->isEmpty()) {
it_y = index.erase(it_y);
}
}
- if(it_y == index.begin())
+ if (it_y == index.begin())
break;
--it_y;
}
@@ -176,7 +141,7 @@ QSet<QSpanCollection::Span *> QSpanCollection::spansInRect(int x, int y, int w,
{
QSet<Span *> list;
Index::const_iterator it_y = index.lowerBound(-y);
- if(it_y == index.end())
+ if (it_y == index.end())
--it_y;
while(-it_y.key() <= y + h) {
SubIndex::const_iterator it_x = (*it_y).lowerBound(-x);
@@ -190,7 +155,7 @@ QSet<QSpanCollection::Span *> QSpanCollection::spansInRect(int x, int y, int w,
break;
--it_x;
}
- if(it_y == index.begin())
+ if (it_y == index.begin())
break;
--it_y;
}
@@ -205,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
@@ -235,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(); ) {
@@ -282,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) {
@@ -387,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);
@@ -455,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);
}
@@ -514,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);
@@ -534,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);
}
@@ -589,7 +555,7 @@ public:
QTableCornerButton(QWidget *parent) : QAbstractButton(parent) {}
void paintEvent(QPaintEvent*) override {
QStyleOptionHeader opt;
- opt.init(this);
+ opt.initFrom(this);
QStyle::State state = QStyle::State_None;
if (isEnabled())
state |= QStyle::State_Enabled;
@@ -627,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
}
@@ -669,6 +653,52 @@ void QTableViewPrivate::trimHiddenSelections(QItemSelectionRange *range) const
*range = QItemSelectionRange(topLeft, bottomRight);
}
+QRect QTableViewPrivate::intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const
+{
+ Q_Q(const QTableView);
+
+ using minMaxPair = std::pair<int, int>;
+ const auto calcMinMax = [q](QHeaderView *hdr, int startIdx, int endIdx, minMaxPair bounds) -> minMaxPair
+ {
+ minMaxPair ret(std::numeric_limits<int>::max(), std::numeric_limits<int>::min());
+ if (hdr->sectionsMoved()) {
+ for (int i = startIdx; i <= endIdx; ++i) {
+ const int start = hdr->sectionViewportPosition(i);
+ const int end = start + hdr->sectionSize(i);
+ ret.first = std::min(start, ret.first);
+ ret.second = std::max(end, ret.second);
+ if (ret.first <= bounds.first && ret.second >= bounds.second)
+ break;
+ }
+ } else {
+ if (q->isRightToLeft() && q->horizontalHeader() == hdr)
+ std::swap(startIdx, endIdx);
+ ret.first = hdr->sectionViewportPosition(startIdx);
+ ret.second = hdr->sectionViewportPosition(endIdx) +
+ hdr->sectionSize(endIdx);
+ }
+ return ret;
+ };
+
+ const auto yVals = calcMinMax(verticalHeader, topLeft.row(), bottomRight.row(),
+ minMaxPair(rect.top(), rect.bottom()));
+ if (yVals.first == yVals.second) // all affected rows are hidden
+ return QRect();
+
+ // short circuit: check if no row is inside rect
+ const QRect colRect(QPoint(rect.left(), yVals.first),
+ QPoint(rect.right(), yVals.second));
+ const QRect intersected = rect.intersected(colRect);
+ if (intersected.isNull())
+ return QRect();
+
+ const auto xVals = calcMinMax(horizontalHeader, topLeft.column(), bottomRight.column(),
+ minMaxPair(rect.left(), rect.right()));
+ const QRect updateRect(QPoint(xVals.first, yVals.first),
+ QPoint(xVals.second, yVals.second));
+ return rect.intersected(updateRect);
+}
+
/*!
\internal
Sets the span for the cell at (\a row, \a column).
@@ -871,13 +901,32 @@ void QTableViewPrivate::drawAndClipSpans(const QRegion &area, QPainter *painter,
visibleSpans = spans.spansInRect(logicalColumn(firstVisualColumn), logicalRow(firstVisualRow),
lastVisualColumn - firstVisualColumn + 1, lastVisualRow - firstVisualRow + 1);
} else {
- for(int x = firstVisualColumn; x <= lastVisualColumn; x++)
- for(int y = firstVisualRow; y <= lastVisualRow; y++)
- visibleSpans.insert(spans.spanAt(x,y));
- visibleSpans.remove(nullptr);
- }
-
- for (QSpanCollection::Span *span : qAsConst(visibleSpans)) {
+ // Any cell outside the viewport, on the top or left, can still end up visible inside the
+ // viewport if is has a span. Calculating if a spanned cell overlaps with the viewport is
+ // "easy" enough when the columns (or rows) in the view are aligned with the columns
+ // in the model; In that case you know that if a column is outside the viewport on the
+ // right, it cannot affect the drawing of the cells inside the viewport, even with a span.
+ // And under that assumption, the spansInRect() function can be used (which is optimized
+ // to only iterate the spans that are close to the viewport).
+ // But when the view has rearranged the columns (or rows), this is no longer true. In that
+ // case, even if a column, according to the model, is outside the viewport on the right, it
+ // can still overlap with the viewport. This can happen if it was moved to the left of the
+ // viewport and one of its cells has a span. In that case we need to take the theoretically
+ // slower route and iterate through all the spans, and check if any of them overlaps with
+ // the viewport.
+ const auto spanList = spans.spans;
+ for (QSpanCollection::Span *span : spanList) {
+ const int spanVisualLeft = visualColumn(span->left());
+ const int spanVisualTop = visualRow(span->top());
+ const int spanVisualRight = spanVisualLeft + span->width() - 1;
+ const int spanVisualBottom = spanVisualTop + span->height() - 1;
+ if ((spanVisualLeft <= lastVisualColumn && spanVisualRight >= firstVisualColumn)
+ && (spanVisualTop <= lastVisualRow && spanVisualBottom >= firstVisualRow))
+ visibleSpans.insert(span);
+ }
+ }
+
+ for (QSpanCollection::Span *span : std::as_const(visibleSpans)) {
int row = span->top();
int col = span->left();
QModelIndex index = model->index(row, col, root);
@@ -926,9 +975,9 @@ 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)
+ Q_UNUSED(parent);
spans.updateInsertedRows(start, end);
}
@@ -936,9 +985,9 @@ 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)
+ Q_UNUSED(parent);
spans.updateInsertedColumns(start, end);
}
@@ -946,9 +995,9 @@ 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)
+ Q_UNUSED(parent);
spans.updateRemovedRows(start, end);
}
@@ -956,9 +1005,9 @@ 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)
+ Q_UNUSED(parent);
spans.updateRemovedColumns(start, end);
}
@@ -966,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);
}
@@ -1003,7 +1052,7 @@ void QTableViewPrivate::drawCell(QPainter *painter, const QStyleOptionViewItem &
q->style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, q);
- q->itemDelegate(index)->paint(painter, opt, index);
+ q->itemDelegateForIndex(index)->paint(painter, opt, index);
}
/*!
@@ -1013,6 +1062,7 @@ void QTableViewPrivate::drawCell(QPainter *painter, const QStyleOptionViewItem &
int QTableViewPrivate::widthHintForIndex(const QModelIndex &index, int hint, const QStyleOptionViewItem &option) const
{
Q_Q(const QTableView);
+ const int oldHint = hint;
QWidget *editor = editorForIndex(index).widget.data();
if (editor && persistent.contains(editor)) {
hint = qMax(hint, editor->sizeHint().width());
@@ -1020,7 +1070,18 @@ int QTableViewPrivate::widthHintForIndex(const QModelIndex &index, int hint, con
int max = editor->maximumSize().width();
hint = qBound(min, hint, max);
}
- hint = qMax(hint, q->itemDelegate(index)->sizeHint(option, index).width());
+ hint = qMax(hint, q->itemDelegateForIndex(index)->sizeHint(option, index).width());
+
+ if (hasSpans()) {
+ auto span = spans.spanAt(index.column(), index.row());
+ if (span && span->m_left == index.column() && span->m_top == index.row()) {
+ // spans are screwed up when sections are moved
+ const auto left = logicalColumn(span->m_left);
+ for (int i = 1; i <= span->width(); ++i)
+ hint -= q->columnWidth(visualColumn(left + i));
+ }
+ hint = std::max(hint, oldHint);
+ }
return hint;
}
@@ -1042,7 +1103,7 @@ int QTableViewPrivate::heightHintForIndex(const QModelIndex &index, int hint, QS
if (wrapItemText) {// for wrapping boundaries
option.rect.setY(q->rowViewportPosition(index.row()));
int height = q->rowHeight(index.row());
- // if the option.height == 0 then q->itemDelegate(index)->sizeHint(option, index) will be wrong.
+ // if the option.height == 0 then q->itemDelegateForIndex(index)->sizeHint(option, index) will be wrong.
// The option.height == 0 is used to conclude that the text is not wrapped, and hence it will
// (exactly like widthHintForIndex) return a QSize with a long width (that we don't use) -
// and the height of the text if it was/is on one line.
@@ -1053,11 +1114,16 @@ int QTableViewPrivate::heightHintForIndex(const QModelIndex &index, int hint, QS
option.rect.setHeight(height);
option.rect.setX(q->columnViewportPosition(index.column()));
option.rect.setWidth(q->columnWidth(index.column()));
+ if (hasSpans()) {
+ auto span = spans.spanAt(index.column(), index.row());
+ if (span && span->m_left == index.column() && span->m_top == index.row())
+ option.rect.setWidth(std::max(option.rect.width(), visualSpanRect(*span).width()));
+ }
// 1px less space when grid is shown (see drawCell)
if (showGrid)
option.rect.setWidth(option.rect.width() - 1);
}
- hint = qMax(hint, q->itemDelegate(index)->sizeHint(option, index).height());
+ hint = qMax(hint, q->itemDelegateForIndex(index)->sizeHint(option, index).height());
return hint;
}
@@ -1101,6 +1167,8 @@ int QTableViewPrivate::heightHintForIndex(const QModelIndex &index, int hint, QS
table can be found by using rowHeight(); similarly, the width of
columns can be found using columnWidth(). Since both of these are plain
widgets, you can hide either of them using their hide() functions.
+ Each header is configured with its \l{QHeaderView::}{highlightSections}
+ and \l{QHeaderView::}{sectionsClickable} properties set to \c true.
Rows and columns can be hidden and shown with hideRow(), hideColumn(),
showRow(), and showColumn(). They can be selected with selectRow()
@@ -1139,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}
*/
/*!
@@ -1170,6 +1238,8 @@ QTableView::QTableView(QTableViewPrivate &dd, QWidget *parent)
*/
QTableView::~QTableView()
{
+ Q_D(QTableView);
+ d->clearConnections();
}
/*!
@@ -1193,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);
@@ -1256,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);
@@ -1266,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);
}
}
@@ -1304,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;
@@ -1315,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);
}
@@ -1342,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;
@@ -1353,21 +1422,26 @@ 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); })
+ };
}
/*!
- \internal
+ \reimp
Scroll the contents of the table view by (\a dx, \a dy).
*/
@@ -1412,11 +1486,10 @@ void QTableView::scrollContentsBy(int dx, int dy)
/*!
\reimp
*/
-QStyleOptionViewItem QTableView::viewOptions() const
+void QTableView::initViewItemOption(QStyleOptionViewItem *option) const
{
- QStyleOptionViewItem option = QAbstractItemView::viewOptions();
- option.showDecorationSelected = true;
- return option;
+ QAbstractItemView::initViewItemOption(option);
+ option->showDecorationSelected = true;
}
/*!
@@ -1426,13 +1499,14 @@ void QTableView::paintEvent(QPaintEvent *event)
{
Q_D(QTableView);
// setup temp variables for the painting
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
const QPoint offset = d->scrollDelayOffset;
const bool showGrid = d->showGrid;
const int gridSize = showGrid ? 1 : 0;
const int gridHint = style()->styleHint(QStyle::SH_Table_GridLineColor, &option, this);
const QColor gridColor = QColor::fromRgba(static_cast<QRgb>(gridHint));
- const QPen gridPen = QPen(gridColor, 0, d->gridStyle);
+ const QPen gridPen = QPen(gridColor, 1, d->gridStyle);
const QHeaderView *verticalHeader = d->verticalHeader;
const QHeaderView *horizontalHeader = d->horizontalHeader;
const bool alternate = d->alternatingColors;
@@ -1566,7 +1640,8 @@ void QTableView::paintEvent(QPaintEvent *event)
int rowY = rowViewportPosition(row);
rowY += offset.y();
int rowh = rowHeight(row) - gridSize;
- painter.drawLine(dirtyArea.left(), rowY + rowh, dirtyArea.right(), rowY + rowh);
+ QLineF line(dirtyArea.left(), rowY + rowh, dirtyArea.right(), rowY + rowh);
+ painter.drawLine(line.translated(0.5, 0.5));
}
// Paint each column
@@ -1578,7 +1653,30 @@ void QTableView::paintEvent(QPaintEvent *event)
colp += offset.x();
if (!rightToLeft)
colp += columnWidth(col) - gridSize;
- painter.drawLine(colp, dirtyArea.top(), colp, dirtyArea.bottom());
+ QLineF line(colp, dirtyArea.top(), colp, dirtyArea.bottom());
+ painter.drawLine(line.translated(0.5, 0.5));
+ }
+ const bool drawWhenHidden = style()->styleHint(QStyle::SH_Table_AlwaysDrawLeftTopGridLines,
+ &option, this);
+ if (drawWhenHidden && horizontalHeader->isHidden()) {
+ const int row = verticalHeader->logicalIndex(top);
+ if (!verticalHeader->isSectionHidden(row)) {
+ const int rowY = rowViewportPosition(row) + offset.y();
+ if (rowY == dirtyArea.top())
+ painter.drawLine(dirtyArea.left(), rowY, dirtyArea.right(), rowY);
+ }
+ }
+ if (drawWhenHidden && verticalHeader->isHidden()) {
+ const int col = horizontalHeader->logicalIndex(left);
+ if (!horizontalHeader->isSectionHidden(col)) {
+ int colX = columnViewportPosition(col) + offset.x();
+ if (!isLeftToRight())
+ colX += columnWidth(left) - 1;
+ if (isLeftToRight() && colX == dirtyArea.left())
+ painter.drawLine(colX, dirtyArea.top(), colX, dirtyArea.bottom());
+ if (!isLeftToRight() && colX == dirtyArea.right())
+ painter.drawLine(colX, dirtyArea.top(), colX, dirtyArea.bottom());
+ }
}
painter.setPen(old);
}
@@ -1918,6 +2016,9 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
if (d->hasSpans()) {
bool expanded;
+ // when the current selection does not intersect with any spans of merged cells,
+ // the range of selected cells must be the same as if there were no merged cells
+ bool intersectsSpan = false;
int top = qMin(d->visualRow(tl.row()), d->visualRow(br.row()));
int left = qMin(d->visualColumn(tl.column()), d->visualColumn(br.column()));
int bottom = qMax(d->visualRow(tl.row()), d->visualRow(br.row()));
@@ -1932,6 +2033,7 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
int r = d->visualColumn(d->columnSpanEndLogical(span.left(), span.width()));
if ((t > bottom) || (l > right) || (top > b) || (left > r))
continue; // no intersect
+ intersectsSpan = true;
if (t < top) {
top = t;
expanded = true;
@@ -1952,14 +2054,20 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
break;
}
} while (expanded);
- selection.reserve((right - left + 1) * (bottom - top + 1));
- for (int horizontal = left; horizontal <= right; ++horizontal) {
- int column = d->logicalColumn(horizontal);
- for (int vertical = top; vertical <= bottom; ++vertical) {
- int row = d->logicalRow(vertical);
- QModelIndex index = d->model->index(row, column, d->root);
- selection.append(QItemSelectionRange(index));
+ if (intersectsSpan) {
+ selection.reserve((right - left + 1) * (bottom - top + 1));
+ for (int horizontal = left; horizontal <= right; ++horizontal) {
+ int column = d->logicalColumn(horizontal);
+ for (int vertical = top; vertical <= bottom; ++vertical) {
+ int row = d->logicalRow(vertical);
+ QModelIndex index = d->model->index(row, column, d->root);
+ selection.append(QItemSelectionRange(index));
+ }
}
+ } else {
+ QItemSelectionRange range(tl, br);
+ if (!range.isEmpty())
+ selection.append(range);
}
} else if (verticalMoved && horizontalMoved) {
int top = d->visualRow(tl.row());
@@ -2005,7 +2113,7 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
}
/*!
- \internal
+ \reimp
Returns the rectangle from the viewport of the items in the given
\a selection.
@@ -2114,7 +2222,7 @@ QModelIndexList QTableView::selectedIndexes() const
QModelIndexList modelSelected;
if (d->selectionModel)
modelSelected = d->selectionModel->selectedIndexes();
- for (int i = 0; i < modelSelected.count(); ++i) {
+ for (int i = 0; i < modelSelected.size(); ++i) {
QModelIndex index = modelSelected.at(i);
if (!isIndexHidden(index) && index.parent() == d->root)
viewSelected.append(index);
@@ -2305,7 +2413,8 @@ int QTableView::sizeHintForRow(int row) const
if (right == -1) // the table don't have enough columns to fill the viewport
right = d->model->columnCount(d->root) - 1;
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
int hint = 0;
QModelIndex index;
@@ -2323,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;
@@ -2352,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;
}
@@ -2393,7 +2501,8 @@ int QTableView::sizeHintForColumn(int column) const
if (!isVisible() || bottom == -1) // the table don't have enough rows to fill the viewport
bottom = d->model->rowCount(d->root) - 1;
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
int hint = 0;
int rowsProcessed = 0;
@@ -2411,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;
@@ -2440,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;
}
@@ -2619,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;
}
@@ -2746,7 +2855,7 @@ bool QTableView::isCornerButtonEnabled() const
#endif
/*!
- \internal
+ \reimp
Returns the rectangle on the viewport occupied by the given \a
index.
@@ -2776,9 +2885,9 @@ QRect QTableView::visualRect(const QModelIndex &index) const
}
/*!
- \internal
+ \reimp
- Makes sure that the given \a item is visible in the table view,
+ Makes sure that the given \a index is visible in the table view,
scrolling if necessary.
*/
void QTableView::scrollTo(const QModelIndex &index, ScrollHint hint)
@@ -2939,14 +3048,19 @@ void QTableView::timerEvent(QTimerEvent *event)
Q_D(QTableView);
if (event->timerId() == d->columnResizeTimerID) {
- updateGeometries();
- killTimer(d->columnResizeTimerID);
- d->columnResizeTimerID = 0;
+ const int oldScrollMax = horizontalScrollBar()->maximum();
+ if (horizontalHeader()->d_func()->state != QHeaderViewPrivate::ResizeSection) {
+ updateGeometries();
+ killTimer(d->columnResizeTimerID);
+ d->columnResizeTimerID = 0;
+ } else {
+ updateEditorGeometries();
+ }
QRect rect;
int viewportHeight = d->viewport->height();
int viewportWidth = d->viewport->width();
- if (d->hasSpans()) {
+ if (d->hasSpans() || horizontalScrollBar()->value() == oldScrollMax) {
rect = QRect(0, 0, viewportWidth, viewportHeight);
} else {
for (int i = d->columnsToUpdate.size()-1; i >= 0; --i) {
@@ -2964,14 +3078,19 @@ void QTableView::timerEvent(QTimerEvent *event)
}
if (event->timerId() == d->rowResizeTimerID) {
- updateGeometries();
- killTimer(d->rowResizeTimerID);
- d->rowResizeTimerID = 0;
+ const int oldScrollMax = verticalScrollBar()->maximum();
+ if (verticalHeader()->d_func()->state != QHeaderViewPrivate::ResizeSection) {
+ updateGeometries();
+ killTimer(d->rowResizeTimerID);
+ d->rowResizeTimerID = 0;
+ } else {
+ updateEditorGeometries();
+ }
int viewportHeight = d->viewport->height();
int viewportWidth = d->viewport->width();
int top;
- if (d->hasSpans()) {
+ if (d->hasSpans() || verticalScrollBar()->value() == oldScrollMax) {
top = 0;
} else {
top = viewportHeight;
@@ -2995,8 +3114,9 @@ void QTableView::timerEvent(QTimerEvent *event)
\sa columnMoved()
*/
-void QTableView::rowMoved(int, int oldIndex, int newIndex)
+void QTableView::rowMoved(int row, int oldIndex, int newIndex)
{
+ Q_UNUSED(row);
Q_D(QTableView);
updateGeometries();
@@ -3023,8 +3143,9 @@ void QTableView::rowMoved(int, int oldIndex, int newIndex)
\sa rowMoved()
*/
-void QTableView::columnMoved(int, int oldIndex, int newIndex)
+void QTableView::columnMoved(int column, int oldIndex, int newIndex)
{
+ Q_UNUSED(column);
Q_D(QTableView);
updateGeometries();
@@ -3167,22 +3288,6 @@ void QTableView::resizeColumnsToContents()
d->horizontalHeader->resizeSections(QHeaderView::ResizeToContents);
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \obsolete
- \overload
-
- This function is deprecated. Use
- sortByColumn(int column, Qt::SortOrder order) instead.
- Sorts the model by the values in the given \a column.
-*/
-void QTableView::sortByColumn(int column)
-{
- Q_D(QTableView);
- sortByColumn(column, d->horizontalHeader->sortIndicatorOrder());
-}
-#endif
-
/*!
\since 4.2
@@ -3199,11 +3304,11 @@ void QTableView::sortByColumn(int column, Qt::SortOrder order)
Q_D(QTableView);
if (column < -1)
return;
- // If sorting is enabled it will emit a signal connected to
- // _q_sortIndicatorChanged, which then actually sorts
d->horizontalHeader->setSortIndicator(column, order);
- // If sorting is not enabled, force to sort now
- if (!d->sortingEnabled)
+ // If sorting is not enabled or has the same order as before, force to sort now
+ // else sorting will be trigger through sortIndicatorChanged()
+ if (!d->sortingEnabled ||
+ (d->horizontalHeader->sortIndicatorSection() == column && d->horizontalHeader->sortIndicatorOrder() == order))
d->model->sort(column, order);
}
@@ -3300,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);
@@ -3326,7 +3421,7 @@ void QTableViewPrivate::selectRow(int row, bool anchor)
selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
if ((anchor && !(command & QItemSelectionModel::Current))
|| (q->selectionMode() == QTableView::SingleSelection))
- rowSectionAnchor = row;
+ currentSelectionStartIndex = model->index(row, column, root);
if (q->selectionMode() != QTableView::SingleSelection
&& command.testFlag(QItemSelectionModel::Toggle)) {
@@ -3339,6 +3434,7 @@ void QTableViewPrivate::selectRow(int row, bool anchor)
command |= QItemSelectionModel::Current;
}
+ const auto rowSectionAnchor = currentSelectionStartIndex.row();
QModelIndex upper = model->index(qMin(rowSectionAnchor, row), column, root);
QModelIndex lower = model->index(qMax(rowSectionAnchor, row), column, root);
if ((verticalHeader->sectionsMoved() && upper.row() != lower.row())) {
@@ -3365,12 +3461,12 @@ void QTableViewPrivate::selectColumn(int column, bool anchor)
selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
if ((anchor && !(command & QItemSelectionModel::Current))
|| (q->selectionMode() == QTableView::SingleSelection))
- columnSectionAnchor = column;
+ currentSelectionStartIndex = model->index(row, column, root);
if (q->selectionMode() != QTableView::SingleSelection
&& command.testFlag(QItemSelectionModel::Toggle)) {
if (anchor)
- ctrlDragSelectionFlag = horizontalHeader->selectionModel()->selectedColumns().contains(index)
+ ctrlDragSelectionFlag = horizontalHeader->selectionModel()->selectedColumns(row).contains(index)
? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
command &= ~QItemSelectionModel::Toggle;
command |= ctrlDragSelectionFlag;
@@ -3378,6 +3474,7 @@ void QTableViewPrivate::selectColumn(int column, bool anchor)
command |= QItemSelectionModel::Current;
}
+ const auto columnSectionAnchor = currentSelectionStartIndex.column();
QModelIndex left = model->index(row, qMin(columnSectionAnchor, column), root);
QModelIndex right = model->index(row, qMax(columnSectionAnchor, column), root);
if ((horizontalHeader->sectionsMoved() && left.column() != right.column())) {
@@ -3393,9 +3490,9 @@ void QTableViewPrivate::selectColumn(int column, bool anchor)
*/
void QTableView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
-#ifndef QT_NO_ACCESSIBILITY
+#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);
@@ -3414,8 +3511,8 @@ void QTableView::selectionChanged(const QItemSelection &selected,
const QItemSelection &deselected)
{
Q_D(QTableView);
- Q_UNUSED(d)
-#ifndef QT_NO_ACCESSIBILITY
+ Q_UNUSED(d);
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
// ### does not work properly for selection ranges.
QModelIndex sel = selected.indexes().value(0);
diff --git a/src/widgets/itemviews/qtableview.h b/src/widgets/itemviews/qtableview.h
index 3275c09f88..eff0ea3502 100644
--- a/src/widgets/itemviews/qtableview.h
+++ b/src/widgets/itemviews/qtableview.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTABLEVIEW_H
#define QTABLEVIEW_H
@@ -130,10 +94,6 @@ public Q_SLOTS:
void resizeRowsToContents();
void resizeColumnToContents(int column);
void resizeColumnsToContents();
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTableView::sortByColumn(int column, Qt::SortOrder order) instead")
- void sortByColumn(int column);
-#endif
void sortByColumn(int column, Qt::SortOrder order);
void setShowGrid(bool show);
@@ -149,7 +109,7 @@ protected:
QTableView(QTableViewPrivate &, QWidget *parent);
void scrollContentsBy(int dx, int dy) override;
- QStyleOptionViewItem viewOptions() const override;
+ void initViewItemOption(QStyleOptionViewItem *option) const override;
void paintEvent(QPaintEvent *e) override;
void timerEvent(QTimerEvent *event) override;
@@ -185,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 8f174351d2..862a016d5f 100644
--- a/src/widgets/itemviews/qtableview_p.h
+++ b/src/widgets/itemviews/qtableview_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTABLEVIEW_P_H
#define QTABLEVIEW_P_H
@@ -52,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);
@@ -127,16 +96,17 @@ private:
bool cleanSpanSubIndex(SubIndex &subindex, int end, bool update = false);
};
-Q_DECLARE_TYPEINFO ( QSpanCollection::Span, Q_MOVABLE_TYPE);
-
+Q_DECLARE_TYPEINFO ( QSpanCollection::Span, Q_RELOCATABLE_TYPE);
-class QTableViewPrivate : public QAbstractItemViewPrivate
+#if QT_CONFIG(abstractbutton)
+class QTableCornerButton;
+#endif
+class Q_AUTOTEST_EXPORT QTableViewPrivate : public QAbstractItemViewPrivate
{
Q_DECLARE_PUBLIC(QTableView)
public:
QTableViewPrivate()
: showGrid(true), gridStyle(Qt::SolidLine),
- rowSectionAnchor(-1), columnSectionAnchor(-1),
columnResizeTimerID(0), rowResizeTimerID(0),
horizontalHeader(nullptr), verticalHeader(nullptr),
sortingEnabled(false), geometryRecursionBlock(false),
@@ -148,7 +118,9 @@ public:
#endif
}
void init();
+ void clearConnections();
void trimHiddenSelections(QItemSelectionRange *range) const;
+ QRect intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const override;
inline bool isHidden(int row, int col) const {
return verticalHeader->isSectionHidden(row)
@@ -185,17 +157,22 @@ public:
bool showGrid;
Qt::PenStyle gridStyle;
- int rowSectionAnchor;
- int columnSectionAnchor;
int columnResizeTimerID;
int rowResizeTimerID;
- QVector<int> columnsToUpdate;
- QVector<int> rowsToUpdate;
+ QList<int> columnsToUpdate;
+ QList<int> rowsToUpdate;
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.
@@ -248,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 60abd02564..6dd812f6fb 100644
--- a/src/widgets/itemviews/qtablewidget.cpp
+++ b/src/widgets/itemviews/qtablewidget.cpp
@@ -1,45 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtablewidget.h"
-#include <qitemdelegate.h>
#include <qpainter.h>
#include <private/qtablewidget_p.h>
@@ -63,12 +26,12 @@ QTableModel::~QTableModel()
bool QTableModel::insertRows(int row, int count, const QModelIndex &)
{
- if (count < 1 || row < 0 || row > verticalHeaderItems.count())
+ if (count < 1 || row < 0 || row > verticalHeaderItems.size())
return false;
beginInsertRows(QModelIndex(), row, row + count - 1);
- int rc = verticalHeaderItems.count();
- int cc = horizontalHeaderItems.count();
+ int rc = verticalHeaderItems.size();
+ int cc = horizontalHeaderItems.size();
verticalHeaderItems.insert(row, count, 0);
if (rc == 0)
tableItems.resize(cc * count);
@@ -80,12 +43,12 @@ bool QTableModel::insertRows(int row, int count, const QModelIndex &)
bool QTableModel::insertColumns(int column, int count, const QModelIndex &)
{
- if (count < 1 || column < 0 || column > horizontalHeaderItems.count())
+ if (count < 1 || column < 0 || column > horizontalHeaderItems.size())
return false;
beginInsertColumns(QModelIndex(), column, column + count - 1);
- int rc = verticalHeaderItems.count();
- int cc = horizontalHeaderItems.count();
+ int rc = verticalHeaderItems.size();
+ int cc = horizontalHeaderItems.size();
horizontalHeaderItems.insert(column, count, 0);
if (cc == 0)
tableItems.resize(rc * count);
@@ -98,7 +61,7 @@ bool QTableModel::insertColumns(int column, int count, const QModelIndex &)
bool QTableModel::removeRows(int row, int count, const QModelIndex &)
{
- if (count < 1 || row < 0 || row + count > verticalHeaderItems.count())
+ if (count < 1 || row < 0 || row + count > verticalHeaderItems.size())
return false;
beginRemoveRows(QModelIndex(), row, row + count - 1);
@@ -125,7 +88,7 @@ bool QTableModel::removeRows(int row, int count, const QModelIndex &)
bool QTableModel::removeColumns(int column, int count, const QModelIndex &)
{
- if (count < 1 || column < 0 || column + count > horizontalHeaderItems.count())
+ if (count < 1 || column < 0 || column + count > horizontalHeaderItems.size())
return false;
beginRemoveColumns(QModelIndex(), column, column + count - 1);
@@ -154,7 +117,7 @@ bool QTableModel::removeColumns(int column, int count, const QModelIndex &)
void QTableModel::setItem(int row, int column, QTableWidgetItem *item)
{
int i = tableIndex(row, column);
- if (i < 0 || i >= tableItems.count())
+ if (i < 0 || i >= tableItems.size())
return;
QTableWidgetItem *oldItem = tableItems.at(i);
if (item == oldItem)
@@ -176,15 +139,15 @@ void QTableModel::setItem(int row, int column, QTableWidgetItem *item)
&& view->horizontalHeader()->sortIndicatorSection() == column) {
// sorted insertion
Qt::SortOrder order = view->horizontalHeader()->sortIndicatorOrder();
- QVector<QTableWidgetItem*> colItems = columnItems(column);
- if (row < colItems.count())
+ QList<QTableWidgetItem *> colItems = columnItems(column);
+ if (row < colItems.size())
colItems.remove(row);
int sortedRow;
if (item == nullptr) {
// move to after all non-0 (sortable) items
- sortedRow = colItems.count();
+ sortedRow = colItems.size();
} else {
- QVector<QTableWidgetItem*>::iterator it;
+ QList<QTableWidgetItem *>::iterator it;
it = sortedInsertionIterator(colItems.begin(), colItems.end(), order, item);
sortedRow = qMax((int)(it - colItems.begin()), 0);
}
@@ -192,7 +155,7 @@ void QTableModel::setItem(int row, int column, QTableWidgetItem *item)
emit layoutAboutToBeChanged({}, QAbstractItemModel::VerticalSortHint);
// move the items @ row to sortedRow
int cc = columnCount();
- QVector<QTableWidgetItem*> rowItems(cc);
+ QList<QTableWidgetItem *> rowItems(cc);
for (int j = 0; j < cc; ++j)
rowItems[j] = tableItems.at(tableIndex(row, j));
tableItems.remove(tableIndex(row, 0), cc);
@@ -247,8 +210,8 @@ void QTableModel::removeItem(QTableWidgetItem *item)
{
int i = tableItems.indexOf(item);
if (i != -1) {
- tableItems[i] = 0;
QModelIndex idx = index(item);
+ tableItems[i] = nullptr;
emit dataChanged(idx, idx);
return;
}
@@ -270,7 +233,7 @@ void QTableModel::removeItem(QTableWidgetItem *item)
void QTableModel::setHorizontalHeaderItem(int section, QTableWidgetItem *item)
{
- if (section < 0 || section >= horizontalHeaderItems.count())
+ if (section < 0 || section >= horizontalHeaderItems.size())
return;
QTableWidgetItem *oldItem = horizontalHeaderItems.at(section);
if (item == oldItem)
@@ -284,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);
@@ -292,7 +255,7 @@ void QTableModel::setHorizontalHeaderItem(int section, QTableWidgetItem *item)
void QTableModel::setVerticalHeaderItem(int section, QTableWidgetItem *item)
{
- if (section < 0 || section >= verticalHeaderItems.count())
+ if (section < 0 || section >= verticalHeaderItems.size())
return;
QTableWidgetItem *oldItem = verticalHeaderItems.at(section);
if (item == oldItem)
@@ -306,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);
@@ -314,12 +277,12 @@ void QTableModel::setVerticalHeaderItem(int section, QTableWidgetItem *item)
QTableWidgetItem *QTableModel::takeHorizontalHeaderItem(int section)
{
- if (section < 0 || section >= horizontalHeaderItems.count())
+ if (section < 0 || section >= horizontalHeaderItems.size())
return nullptr;
QTableWidgetItem *itm = horizontalHeaderItems.at(section);
if (itm) {
itm->view = nullptr;
- itm->itemFlags &= ~ItemIsHeaderItem;
+ itm->d->headerItem = false;
horizontalHeaderItems[section] = 0;
}
return itm;
@@ -327,12 +290,12 @@ QTableWidgetItem *QTableModel::takeHorizontalHeaderItem(int section)
QTableWidgetItem *QTableModel::takeVerticalHeaderItem(int section)
{
- if (section < 0 || section >= verticalHeaderItems.count())
+ if (section < 0 || section >= verticalHeaderItems.size())
return nullptr;
QTableWidgetItem *itm = verticalHeaderItems.at(section);
if (itm) {
itm->view = nullptr;
- itm->itemFlags &= ~ItemIsHeaderItem;
+ itm->d->headerItem = false;
verticalHeaderItems[section] = 0;
}
return itm;
@@ -354,7 +317,7 @@ QModelIndex QTableModel::index(const QTableWidgetItem *item) const
return QModelIndex();
int i = -1;
const int id = item->d->id;
- if (id >= 0 && id < tableItems.count() && tableItems.at(id) == item) {
+ if (id >= 0 && id < tableItems.size() && tableItems.at(id) == item) {
i = id;
} else { // we need to search for the item
i = tableItems.indexOf(const_cast<QTableWidgetItem*>(item));
@@ -368,7 +331,7 @@ QModelIndex QTableModel::index(const QTableWidgetItem *item) const
void QTableModel::setRowCount(int rows)
{
- int rc = verticalHeaderItems.count();
+ int rc = verticalHeaderItems.size();
if (rows < 0 || rc == rows)
return;
if (rc < rows)
@@ -379,7 +342,7 @@ void QTableModel::setRowCount(int rows)
void QTableModel::setColumnCount(int columns)
{
- int cc = horizontalHeaderItems.count();
+ int cc = horizontalHeaderItems.size();
if (columns < 0 || cc == columns)
return;
if (cc < columns)
@@ -390,12 +353,12 @@ void QTableModel::setColumnCount(int columns)
int QTableModel::rowCount(const QModelIndex &parent) const
{
- return parent.isValid() ? 0 : verticalHeaderItems.count();
+ return parent.isValid() ? 0 : verticalHeaderItems.size();
}
int QTableModel::columnCount(const QModelIndex &parent) const
{
- return parent.isValid() ? 0 : horizontalHeaderItems.count();
+ return parent.isValid() ? 0 : horizontalHeaderItems.size();
}
QVariant QTableModel::data(const QModelIndex &index, int role) const
@@ -436,7 +399,7 @@ QMap<int, QVariant> QTableModel::itemData(const QModelIndex &index) const
QMap<int, QVariant> roles;
QTableWidgetItem *itm = item(index);
if (itm) {
- for (int i = 0; i < itm->values.count(); ++i) {
+ for (int i = 0; i < itm->values.size(); ++i) {
roles.insert(itm->values.at(i).role,
itm->values.at(i).value);
}
@@ -454,7 +417,7 @@ bool QTableModel::setItemData(const QModelIndex &index, const QMap<int, QVariant
QTableWidgetItem *itm = item(index);
if (itm) {
itm->view = nullptr; // prohibits item from calling itemChanged()
- QVector<int> rolesVec;
+ QList<int> rolesVec;
for (QMap<int, QVariant>::ConstIterator it = roles.constBegin(); it != roles.constEnd(); ++it) {
const int role = (it.key() == Qt::EditRole ? Qt::DisplayRole : it.key());
if (itm->data(role) != it.value()) {
@@ -480,7 +443,6 @@ bool QTableModel::setItemData(const QModelIndex &index, const QMap<int, QVariant
return true;
}
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool QTableModel::clearItemData(const QModelIndex &index)
{
if (!checkIndex(index, CheckIndexOption::IndexIsValid))
@@ -493,10 +455,9 @@ bool QTableModel::clearItemData(const QModelIndex &index)
if (std::all_of(beginIter, endIter, [](const QWidgetItemData& data) -> bool { return !data.value.isValid(); }))
return true; //it's already cleared
itm->values.clear();
- emit dataChanged(index, index, QVector<int>{});
+ emit dataChanged(index, index, QList<int> {});
return true;
}
-#endif
Qt::ItemFlags QTableModel::flags(const QModelIndex &index) const
{
@@ -514,8 +475,8 @@ Qt::ItemFlags QTableModel::flags(const QModelIndex &index) const
void QTableModel::sort(int column, Qt::SortOrder order)
{
- QVector<QPair<QTableWidgetItem*, int> > sortable;
- QVector<int> unsortable;
+ QList<QPair<QTableWidgetItem *, int>> sortable;
+ QList<int> unsortable;
sortable.reserve(rowCount());
unsortable.reserve(rowCount());
@@ -530,7 +491,7 @@ void QTableModel::sort(int column, Qt::SortOrder order)
const auto compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
std::stable_sort(sortable.begin(), sortable.end(), compare);
- QVector<QTableWidgetItem*> sorted_table(tableItems.count());
+ QList<QTableWidgetItem *> sorted_table(tableItems.size());
QModelIndexList from;
QModelIndexList to;
const int numRows = rowCount();
@@ -538,9 +499,9 @@ void QTableModel::sort(int column, Qt::SortOrder order)
from.reserve(numRows * numColumns);
to.reserve(numRows * numColumns);
for (int i = 0; i < numRows; ++i) {
- int r = (i < sortable.count()
+ int r = (i < sortable.size()
? sortable.at(i).second
- : unsortable.at(i - sortable.count()));
+ : unsortable.at(i - sortable.size()));
for (int c = 0; c < numColumns; ++c) {
sorted_table[tableIndex(i, c)] = item(r, c);
from.append(createIndex(r, c));
@@ -567,7 +528,7 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order,
int start, int end)
{
int count = end - start + 1;
- QVector < QPair<QTableWidgetItem*,int> > sorting;
+ QList<QPair<QTableWidgetItem *, int>> sorting;
sorting.reserve(count);
for (int row = start; row <= end; ++row) {
QTableWidgetItem *itm = item(row, column);
@@ -582,16 +543,19 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order,
const auto compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
std::stable_sort(sorting.begin(), sorting.end(), compare);
QModelIndexList oldPersistentIndexes, newPersistentIndexes;
- QVector<QTableWidgetItem*> newTable = tableItems;
- QVector<QTableWidgetItem*> newVertical = verticalHeaderItems;
- QVector<QTableWidgetItem*> colItems = columnItems(column);
- QVector<QTableWidgetItem*>::iterator vit = colItems.begin();
+ QList<QTableWidgetItem *> newTable = tableItems;
+ QList<QTableWidgetItem *> newVertical = verticalHeaderItems;
+ QList<QTableWidgetItem *> colItems = columnItems(column);
+ QList<QTableWidgetItem *>::iterator vit = colItems.begin();
+ qsizetype distanceFromBegin = 0;
bool changed = false;
- for (int i = 0; i < sorting.count(); ++i) {
+ for (int i = 0; i < sorting.size(); ++i) {
+ distanceFromBegin = std::distance(colItems.begin(), vit);
int oldRow = sorting.at(i).second;
QTableWidgetItem *item = colItems.at(oldRow);
colItems.remove(oldRow);
- vit = sortedInsertionIterator(vit, colItems.end(), order, item);
+ vit = sortedInsertionIterator(colItems.begin() + distanceFromBegin, colItems.end(), order,
+ item);
int newRow = qMax((int)(vit - colItems.begin()), 0);
if ((newRow < oldRow) && !(*item < *colItems.at(oldRow - 1)) && !(*colItems.at(oldRow - 1) < *item))
newRow = oldRow;
@@ -605,7 +569,7 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order,
}
// move the items @ oldRow to newRow
int cc = columnCount();
- QVector<QTableWidgetItem*> rowItems(cc);
+ QList<QTableWidgetItem *> rowItems(cc);
for (int j = 0; j < cc; ++j)
rowItems[j] = newTable.at(tableIndex(oldRow, j));
newTable.remove(tableIndex(oldRow, 0), cc);
@@ -618,7 +582,7 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order,
// update persistent indexes
updateRowIndexes(newPersistentIndexes, oldRow, newRow);
// the index of the remaining rows may have changed
- for (int j = i + 1; j < sorting.count(); ++j) {
+ for (int j = i + 1; j < sorting.size(); ++j) {
int otherRow = sorting.at(j).second;
if (oldRow < otherRow && newRow >= otherRow)
--sorting[j].second;
@@ -642,9 +606,9 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order,
Returns the non-0 items in column \a column.
*/
-QVector<QTableWidgetItem*> QTableModel::columnItems(int column) const
+QList<QTableWidgetItem *> QTableModel::columnItems(int column) const
{
- QVector<QTableWidgetItem*> items;
+ QList<QTableWidgetItem *> items;
int rc = rowCount();
items.reserve(rc);
for (int row = 0; row < rc; ++row) {
@@ -691,10 +655,10 @@ void QTableModel::updateRowIndexes(QModelIndexList &indexes,
inserted in the interval (\a begin, \a end) according to
the given sort \a order.
*/
-QVector<QTableWidgetItem*>::iterator QTableModel::sortedInsertionIterator(
- const QVector<QTableWidgetItem*>::iterator &begin,
- const QVector<QTableWidgetItem*>::iterator &end,
- Qt::SortOrder order, QTableWidgetItem *item)
+QList<QTableWidgetItem *>::iterator
+QTableModel::sortedInsertionIterator(const QList<QTableWidgetItem *>::iterator &begin,
+ const QList<QTableWidgetItem *>::iterator &end,
+ Qt::SortOrder order, QTableWidgetItem *item)
{
if (order == Qt::AscendingOrder)
return std::lower_bound(begin, end, item, QTableModelLessThan());
@@ -719,9 +683,9 @@ QVariant QTableModel::headerData(int section, Qt::Orientation orientation, int r
return QVariant();
QTableWidgetItem *itm = nullptr;
- if (orientation == Qt::Horizontal && section < horizontalHeaderItems.count())
+ if (orientation == Qt::Horizontal && section < horizontalHeaderItems.size())
itm = horizontalHeaderItems.at(section);
- else if (orientation == Qt::Vertical && section < verticalHeaderItems.count())
+ else if (orientation == Qt::Vertical && section < verticalHeaderItems.size())
itm = verticalHeaderItems.at(section);
else
return QVariant(); // section is out of bounds
@@ -756,20 +720,20 @@ bool QTableModel::setHeaderData(int section, Qt::Orientation orientation,
bool QTableModel::isValid(const QModelIndex &index) const
{
return (index.isValid()
- && index.row() < verticalHeaderItems.count()
- && index.column() < horizontalHeaderItems.count());
+ && index.row() < verticalHeaderItems.size()
+ && index.column() < horizontalHeaderItems.size());
}
void QTableModel::clear()
{
- for (int j = 0; j < verticalHeaderItems.count(); ++j) {
+ for (int j = 0; j < verticalHeaderItems.size(); ++j) {
if (verticalHeaderItems.at(j)) {
verticalHeaderItems.at(j)->view = nullptr;
delete verticalHeaderItems.at(j);
verticalHeaderItems[j] = 0;
}
}
- for (int k = 0; k < horizontalHeaderItems.count(); ++k) {
+ for (int k = 0; k < horizontalHeaderItems.size(); ++k) {
if (horizontalHeaderItems.at(k)) {
horizontalHeaderItems.at(k)->view = nullptr;
delete horizontalHeaderItems.at(k);
@@ -782,7 +746,7 @@ void QTableModel::clear()
void QTableModel::clearContents()
{
beginResetModel();
- for (int i = 0; i < tableItems.count(); ++i) {
+ for (int i = 0; i < tableItems.size(); ++i) {
if (tableItems.at(i)) {
tableItems.at(i)->view = nullptr;
delete tableItems.at(i);
@@ -792,11 +756,11 @@ void QTableModel::clearContents()
endResetModel();
}
-void QTableModel::itemChanged(QTableWidgetItem *item, const QVector<int> &roles)
+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);
@@ -844,7 +808,7 @@ QMimeData *QTableModel::internalMimeData() const
QMimeData *QTableModel::mimeData(const QModelIndexList &indexes) const
{
QList<QTableWidgetItem*> items;
- const int indexesCount = indexes.count();
+ const int indexesCount = indexes.size();
items.reserve(indexesCount);
for (int i = 0; i < indexesCount; ++i)
items << item(indexes.at(i));
@@ -900,38 +864,36 @@ Qt::DropActions QTableModel::supportedDropActions() const
*/
/*!
- Constructs an table selection range, i.e. a range
+ \fn QTableWidgetSelectionRange::QTableWidgetSelectionRange()
+
+ Constructs an empty table selection range, i.e. a range
whose rowCount() and columnCount() are 0.
+
+ \sa topRow(), leftColumn(), bottomRow(), rightColumn()
*/
-QTableWidgetSelectionRange::QTableWidgetSelectionRange()
- : top(-1), left(-1), bottom(-2), right(-2)
-{
-}
/*!
+ \fn QTableWidgetSelectionRange::QTableWidgetSelectionRange(int top, int left, int bottom, int right)
+
Constructs the table selection range from the given \a top, \a
left, \a bottom and \a right table rows and columns.
\sa topRow(), leftColumn(), bottomRow(), rightColumn()
*/
-QTableWidgetSelectionRange::QTableWidgetSelectionRange(int top, int left, int bottom, int right)
- : top(top), left(left), bottom(bottom), right(right)
-{
-}
/*!
- Constructs a the table selection range by copying the given \a
- other table selection range.
+ \fn bool QTableWidgetSelectionRange::operator==(const QTableWidgetSelectionRange &lhs, const QTableWidgetSelectionRange &rhs)
+ \since 6.3
+
+ Returns true if \a lhs and \a rhs are equal, otherwise returns false.
*/
-QTableWidgetSelectionRange::QTableWidgetSelectionRange(const QTableWidgetSelectionRange &) = default;
-QTableWidgetSelectionRange &QTableWidgetSelectionRange::operator=(const QTableWidgetSelectionRange &) = default;
/*!
- Destroys the table selection range.
+ \fn bool QTableWidgetSelectionRange::operator!=(const QTableWidgetSelectionRange &lhs, const QTableWidgetSelectionRange &rhs)
+ \since 6.3
+
+ Returns true if \a lhs and \a rhs are not equal, otherwise returns false.
*/
-QTableWidgetSelectionRange::~QTableWidgetSelectionRange()
-{
-}
/*!
\fn int QTableWidgetSelectionRange::topRow() const
@@ -1249,22 +1211,6 @@ void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
\sa font(), setText(), setForeground()
*/
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \fn QColor QTableWidgetItem::backgroundColor() const
- \obsolete
-
- This function is deprecated. Use background() instead.
-*/
-
-/*!
- \fn void QTableWidgetItem::setBackgroundColor(const QColor &color)
- \obsolete
-
- This function is deprecated. Use setBackground() instead.
-*/
-#endif
-
/*!
\fn QBrush QTableWidgetItem::background() const
\since 4.2
@@ -1285,22 +1231,6 @@ void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
\sa setForeground()
*/
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \fn QColor QTableWidgetItem::textColor() const
- \obsolete
-
- This function is deprecated. Use foreground() instead.
-*/
-
-/*!
- \fn void QTableWidgetItem::setTextColor(const QColor &color)
- \obsolete
-
- This function is deprecated. Use setForeground() instead.
-*/
-#endif
-
/*!
\fn QBrush QTableWidgetItem::foreground() const
\since 4.2
@@ -1322,14 +1252,29 @@ void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
*/
/*!
+ \if defined(qt7)
+
+ \fn Qt::Alignment QTableWidgetItem::textAlignment() const
+
+ Returns the text alignment for the list item.
+
+ \else
+
\fn int QTableWidgetItem::textAlignment() const
Returns the text alignment for the item's text.
+ \note This function returns an int for historical reasons. It will
+ be corrected to return Qt::Alignment in Qt 7.
+
\sa Qt::Alignment
+
+ \endif
*/
/*!
+ \obsolete [6.4] Use the overload that takes a Qt::Alignment argument.
+
\fn void QTableWidgetItem::setTextAlignment(int alignment)
Sets the text alignment for the item's text to the \a alignment
@@ -1339,6 +1284,20 @@ void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
*/
/*!
+ \since 6.4
+
+ \fn void QTableWidgetItem::setTextAlignment(Qt::Alignment alignment)
+
+ Sets the text alignment for the item's text to the \a alignment
+ specified.
+*/
+
+/*!
+ \fn void QTableWidgetItem::setTextAlignment(Qt::AlignmentFlag alignment)
+ \internal
+*/
+
+/*!
Constructs a table item of the specified \a type that does not belong
to any table.
@@ -1420,7 +1379,7 @@ void QTableWidgetItem::setData(int role, const QVariant &value)
{
bool found = false;
role = (role == Qt::EditRole ? Qt::DisplayRole : role);
- for (int i = 0; i < values.count(); ++i) {
+ for (int i = 0; i < values.size(); ++i) {
if (values.at(i).role == role) {
if (values[i].value == value)
return;
@@ -1434,9 +1393,9 @@ void QTableWidgetItem::setData(int role, const QVariant &value)
values.append(QWidgetItemData(role, value));
if (QTableModel *model = tableModel())
{
- const QVector<int> roles((role == Qt::DisplayRole) ?
- QVector<int>({Qt::DisplayRole, Qt::EditRole}) :
- QVector<int>({role}));
+ const QList<int> roles((role == Qt::DisplayRole)
+ ? QList<int>({ Qt::DisplayRole, Qt::EditRole })
+ : QList<int>({ role }));
model->itemChanged(this, roles);
}
}
@@ -1632,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))
@@ -1661,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))
@@ -1669,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))
@@ -1677,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))
@@ -1685,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))
@@ -1693,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))
@@ -1701,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);
@@ -1712,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();
@@ -1721,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();
@@ -1920,6 +1892,8 @@ QTableWidget::QTableWidget(int rows, int columns, QWidget *parent)
*/
QTableWidget::~QTableWidget()
{
+ Q_D(QTableWidget);
+ d->clearConnections();
}
/*!
@@ -2127,7 +2101,7 @@ void QTableWidget::setVerticalHeaderLabels(const QStringList &labels)
Q_D(QTableWidget);
QTableModel *model = d->tableModel();
QTableWidgetItem *item = nullptr;
- for (int i = 0; i < model->rowCount() && i < labels.count(); ++i) {
+ for (int i = 0; i < model->rowCount() && i < labels.size(); ++i) {
item = model->verticalHeaderItem(i);
if (!item) {
item = model->createItem();
@@ -2145,7 +2119,7 @@ void QTableWidget::setHorizontalHeaderLabels(const QStringList &labels)
Q_D(QTableWidget);
QTableModel *model = d->tableModel();
QTableWidgetItem *item = nullptr;
- for (int i = 0; i < model->columnCount() && i < labels.count(); ++i) {
+ for (int i = 0; i < model->columnCount() && i < labels.size(); ++i) {
item = model->horizontalHeaderItem(i);
if (!item) {
item = model->createItem();
@@ -2358,34 +2332,6 @@ void QTableWidget::setCellWidget(int row, int column, QWidget *widget)
QAbstractItemView::setIndexWidget(index, widget);
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- Returns \c true if the \a item is selected, otherwise returns \c false.
-
- \obsolete
-
- This function is deprecated. Use \l{QTableWidgetItem::isSelected()} instead.
-*/
-
-bool QTableWidget::isItemSelected(const QTableWidgetItem *item) const
-{
- return ((item && item->tableWidget() == this) ? item->isSelected() : false);
-}
-
-/*!
- Selects or deselects \a item depending on \a select.
-
- \obsolete
-
- This function is deprecated. Use \l{QTableWidgetItem::setSelected()} instead.
-*/
-void QTableWidget::setItemSelected(const QTableWidgetItem *item, bool select)
-{
- if (item && item->tableWidget() == this)
- const_cast<QTableWidgetItem*>(item)->setSelected(select);
-}
-#endif
-
/*!
Selects or deselects the \a range depending on \a select.
*/
@@ -2412,13 +2358,13 @@ QList<QTableWidgetSelectionRange> QTableWidget::selectedRanges() const
{
const QList<QItemSelectionRange> ranges = selectionModel()->selection();
QList<QTableWidgetSelectionRange> result;
- const int rangesCount = ranges.count();
+ const int rangesCount = ranges.size();
result.reserve(rangesCount);
for (int i = 0; i < rangesCount; ++i)
- result.append(QTableWidgetSelectionRange(ranges.at(i).top(),
- ranges.at(i).left(),
- ranges.at(i).bottom(),
- ranges.at(i).right()));
+ result.append({ranges.at(i).top(),
+ ranges.at(i).left(),
+ ranges.at(i).bottom(),
+ ranges.at(i).right()});
return result;
}
@@ -2642,11 +2588,7 @@ QStringList QTableWidget::mimeTypes() const
If the list of items is empty, \nullptr is returned rather than a
serialized empty list.
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
QMimeData *QTableWidget::mimeData(const QList<QTableWidgetItem *> &items) const
-#else
-QMimeData *QTableWidget::mimeData(const QList<QTableWidgetItem*> items) const
-#endif
{
Q_D(const QTableWidget);
@@ -2654,7 +2596,7 @@ QMimeData *QTableWidget::mimeData(const QList<QTableWidgetItem*> items) const
// if non empty, it's called from the model's own mimeData
if (cachedIndexes.isEmpty()) {
- cachedIndexes.reserve(items.count());
+ cachedIndexes.reserve(items.size());
for (QTableWidgetItem *item : items)
cachedIndexes << indexFromItem(item);
@@ -2725,18 +2667,6 @@ QModelIndex QTableWidget::indexFromItem(const QTableWidgetItem *item) const
return d->tableModel()->index(item);
}
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-/*!
- \internal
- \obsolete
- \overload
-*/
-QModelIndex QTableWidget::indexFromItem(QTableWidgetItem *item) const
-{
- return indexFromItem(const_cast<const QTableWidgetItem *>(item));
-}
-#endif
-
/*!
Returns a pointer to the QTableWidgetItem associated with the given \a index.
*/
@@ -2770,7 +2700,8 @@ void QTableWidget::dropEvent(QDropEvent *event) {
QModelIndex topIndex;
int col = -1;
int row = -1;
- if (d->dropOn(event, &row, &col, &topIndex)) {
+ // check whether a subclass has already accepted the event, ie. moved the data
+ if (!event->isAccepted() && d->dropOn(event, &row, &col, &topIndex)) {
const QModelIndexList indexes = selectedIndexes();
int top = INT_MAX;
int left = INT_MAX;
@@ -2780,7 +2711,7 @@ void QTableWidget::dropEvent(QDropEvent *event) {
}
QList<QTableWidgetItem *> taken;
- const int indexesCount = indexes.count();
+ const int indexesCount = indexes.size();
taken.reserve(indexesCount);
for (const auto &index : indexes)
taken.append(takeItem(index.row(), index.column()));
@@ -2792,9 +2723,11 @@ void QTableWidget::dropEvent(QDropEvent *event) {
}
event->accept();
- // Don't want QAbstractItemView to delete it because it was "moved" we already did it
- event->setDropAction(Qt::CopyAction);
}
+ // either we or a subclass accepted the move event, so assume that the data was
+ // moved and that QAbstractItemView shouldn't remove the source when QDrag::exec returns
+ if (event->isAccepted())
+ d->dropEventMoved = true;
}
QTableView::dropEvent(event);
diff --git a/src/widgets/itemviews/qtablewidget.h b/src/widgets/itemviews/qtablewidget.h
index 70e2046400..303f4d5f5b 100644
--- a/src/widgets/itemviews/qtablewidget.h
+++ b/src/widgets/itemviews/qtablewidget.h
@@ -1,74 +1,44 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTABLEWIDGET_H
#define QTABLEWIDGET_H
-#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qtableview.h>
+#include <QtWidgets/qtwidgetsglobal.h>
+#include <QtCore/qlist.h>
#include <QtCore/qvariant.h>
-#include <QtCore/qvector.h>
QT_REQUIRE_CONFIG(tablewidget);
QT_BEGIN_NAMESPACE
-// ### Qt6 unexport the class, remove the user-defined special 3 and make it a literal type.
-class Q_WIDGETS_EXPORT QTableWidgetSelectionRange
+class QTableWidgetSelectionRange
{
public:
- QTableWidgetSelectionRange();
- QTableWidgetSelectionRange(int top, int left, int bottom, int right);
- ~QTableWidgetSelectionRange();
-
- QTableWidgetSelectionRange(const QTableWidgetSelectionRange &other);
- QTableWidgetSelectionRange &operator=(const QTableWidgetSelectionRange &other);
-
- inline int topRow() const { return top; }
- inline int bottomRow() const { return bottom; }
- inline int leftColumn() const { return left; }
- inline int rightColumn() const { return right; }
- inline int rowCount() const { return bottom - top + 1; }
- inline int columnCount() const { return right - left + 1; }
-
+ QTableWidgetSelectionRange() = default;
+ QTableWidgetSelectionRange(int top, int left, int bottom, int right)
+ : m_top(top), m_left(left), m_bottom(bottom), m_right(right)
+ {}
+
+ 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;
+ }
+ friend bool operator!=(const QTableWidgetSelectionRange &lhs,
+ const QTableWidgetSelectionRange &rhs) noexcept
+ { return !(lhs == rhs); }
+
+ inline int topRow() const { return m_top; }
+ inline int bottomRow() const { return m_bottom; }
+ inline int leftColumn() const { return m_left; }
+ inline int rightColumn() const { return m_right; }
+ inline int rowCount() const { return m_bottom - m_top + 1; }
+ inline int columnCount() const { return m_right - m_left + 1; }
private:
- int top, left, bottom, right;
+ int m_top = -1, m_left = -1, m_bottom = -2, m_right = -2;
};
class QTableWidget;
@@ -113,7 +83,7 @@ public:
{ return data(Qt::StatusTipRole).toString(); }
inline void setStatusTip(const QString &statusTip);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
inline QString toolTip() const
{ return data(Qt::ToolTipRole).toString(); }
inline void setToolTip(const QString &toolTip);
@@ -129,41 +99,35 @@ public:
{ return qvariant_cast<QFont>(data(Qt::FontRole)); }
inline void setFont(const QFont &font);
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
inline int textAlignment() const
{ return data(Qt::TextAlignmentRole).toInt(); }
+#else
+ inline Qt::Alignment textAlignment() const
+ { return qvariant_cast<Qt::Alignment>(data(Qt::TextAlignmentRole)); }
+#endif
+#if QT_DEPRECATED_SINCE(6, 4)
+ QT_DEPRECATED_VERSION_X_6_4("Use the overload taking Qt::Alignment")
inline void setTextAlignment(int alignment)
{ setData(Qt::TextAlignmentRole, alignment); }
-
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTableWidgetItem::background() instead")
- inline QColor backgroundColor() const
- { return qvariant_cast<QColor>(data(Qt::BackgroundRole)); }
- QT_DEPRECATED_X ("Use QTableWidgetItem::setBackground() instead")
- inline void setBackgroundColor(const QColor &color)
- { setData(Qt::BackgroundRole, color); }
+ inline void setTextAlignment(Qt::AlignmentFlag alignment)
+ { setData(Qt::TextAlignmentRole, QVariant::fromValue(Qt::Alignment(alignment))); }
#endif
+ inline void setTextAlignment(Qt::Alignment alignment)
+ { setData(Qt::TextAlignmentRole, QVariant::fromValue(alignment)); }
inline QBrush background() const
{ return qvariant_cast<QBrush>(data(Qt::BackgroundRole)); }
inline void setBackground(const QBrush &brush)
{ setData(Qt::BackgroundRole, brush.style() != Qt::NoBrush ? QVariant(brush) : QVariant()); }
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTableWidgetItem::foreground() instead")
- inline QColor textColor() const
- { return qvariant_cast<QColor>(data(Qt::ForegroundRole)); }
- QT_DEPRECATED_X ("Use QTableWidgetItem::setForeground() instead")
- inline void setTextColor(const QColor &color)
- { setData(Qt::ForegroundRole, color); }
-#endif
-
inline QBrush foreground() const
{ return qvariant_cast<QBrush>(data(Qt::ForegroundRole)); }
inline void setForeground(const QBrush &brush)
{ setData(Qt::ForegroundRole, brush.style() != Qt::NoBrush ? QVariant(brush) : QVariant()); }
inline Qt::CheckState checkState() const
- { return static_cast<Qt::CheckState>(data(Qt::CheckStateRole).toInt()); }
+ { return qvariant_cast<Qt::CheckState>(data(Qt::CheckStateRole)); }
inline void setCheckState(Qt::CheckState state)
{ setData(Qt::CheckStateRole, state); }
@@ -190,7 +154,7 @@ private:
private:
int rtti;
- QVector<QWidgetItemData> values;
+ QList<QWidgetItemData> values;
QTableWidget *view;
QTableWidgetItemPrivate *d;
Qt::ItemFlags itemFlags;
@@ -205,7 +169,7 @@ inline void QTableWidgetItem::setIcon(const QIcon &aicon)
inline void QTableWidgetItem::setStatusTip(const QString &astatusTip)
{ setData(Qt::StatusTipRole, astatusTip); }
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
inline void QTableWidgetItem::setToolTip(const QString &atoolTip)
{ setData(Qt::ToolTipRole, atoolTip); }
#endif
@@ -249,6 +213,9 @@ public:
QTableWidgetItem *item(int row, int column) const;
void setItem(int row, int column, QTableWidgetItem *item);
QTableWidgetItem *takeItem(int row, int column);
+ QList<QTableWidgetItem*> items(const QMimeData *data) const;
+ QModelIndex indexFromItem(const QTableWidgetItem *item) const;
+ QTableWidgetItem *itemFromIndex(const QModelIndex &index) const;
QTableWidgetItem *verticalHeaderItem(int row) const;
void setVerticalHeaderItem(int row, QTableWidgetItem *item);
@@ -282,12 +249,6 @@ public:
void setCellWidget(int row, int column, QWidget *widget);
inline void removeCellWidget(int row, int column);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTableWidgetItem::isSelected() instead")
- bool isItemSelected(const QTableWidgetItem *item) const;
- QT_DEPRECATED_X ("Use QTableWidgetItem::setSelected() instead")
- void setItemSelected(const QTableWidgetItem *item, bool select);
-#endif
void setRangeSelected(const QTableWidgetSelectionRange &range, bool select);
QList<QTableWidgetSelectionRange> selectedRanges() const;
@@ -320,7 +281,6 @@ Q_SIGNALS:
void itemActivated(QTableWidgetItem *item);
void itemEntered(QTableWidgetItem *item);
- // ### Qt 6: add changed roles
void itemChanged(QTableWidgetItem *item);
void currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous);
@@ -339,27 +299,10 @@ Q_SIGNALS:
protected:
bool event(QEvent *e) override;
virtual QStringList mimeTypes() const;
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
virtual QMimeData *mimeData(const QList<QTableWidgetItem *> &items) const;
-#else
- virtual QMimeData *mimeData(const QList<QTableWidgetItem*> items) const;
-#endif
virtual bool dropMimeData(int row, int column, const QMimeData *data, Qt::DropAction action);
virtual Qt::DropActions supportedDropActions() const;
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
-public:
-#else
-protected:
-#endif
- QList<QTableWidgetItem*> items(const QMimeData *data) const;
-
- QModelIndex indexFromItem(const QTableWidgetItem *item) const;
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
- QModelIndex indexFromItem(QTableWidgetItem *item) const; // ### Qt 6: remove
-#endif
- QTableWidgetItem *itemFromIndex(const QModelIndex &index) const;
-
protected:
#if QT_CONFIG(draganddrop)
void dropEvent(QDropEvent *event) override;
@@ -369,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 d88326f129..210910fc52 100644
--- a/src/widgets/itemviews/qtablewidget_p.h
+++ b/src/widgets/itemviews/qtablewidget_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTABLEWIDGET_P_H
#define QTABLEWIDGET_P_H
@@ -58,6 +22,8 @@
#include <private/qtableview_p.h>
#include <private/qwidgetitemdata_p.h>
+#include <array>
+
QT_REQUIRE_CONFIG(tablewidget);
QT_BEGIN_NAMESPACE
@@ -89,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();
@@ -129,9 +91,7 @@ public:
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role) override;
bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles) override;
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool clearItemData(const QModelIndex &index) override;
-#endif
QMap<int, QVariant> itemData(const QModelIndex &index) const override;
@@ -147,20 +107,20 @@ public:
const QPair<QTableWidgetItem*,int> &right);
void ensureSorted(int column, Qt::SortOrder order, int start, int end);
- QVector<QTableWidgetItem*> columnItems(int column) const;
+ QList<QTableWidgetItem *> columnItems(int column) const;
void updateRowIndexes(QModelIndexList &indexes, int movedFromRow, int movedToRow);
- static QVector<QTableWidgetItem*>::iterator sortedInsertionIterator(
- const QVector<QTableWidgetItem*>::iterator &begin,
- const QVector<QTableWidgetItem*>::iterator &end,
- Qt::SortOrder order, QTableWidgetItem *item);
+ static QList<QTableWidgetItem *>::iterator
+ sortedInsertionIterator(const QList<QTableWidgetItem *>::iterator &begin,
+ const QList<QTableWidgetItem *>::iterator &end, Qt::SortOrder order,
+ QTableWidgetItem *item);
bool isValid(const QModelIndex &index) const;
inline long tableIndex(int row, int column) const
- { return (row * horizontalHeaderItems.count()) + column; }
+ { return (row * horizontalHeaderItems.size()) + column; }
void clear();
void clearContents();
- void itemChanged(QTableWidgetItem *item, const QVector<int> &roles = QVector<int>());
+ void itemChanged(QTableWidgetItem *item, const QList<int> &roles = QList<int>());
QTableWidgetItem *createItem() const;
const QTableWidgetItem *itemPrototype() const;
@@ -177,9 +137,9 @@ public:
private:
const QTableWidgetItem *prototype;
- QVector<QTableWidgetItem*> tableItems;
- QVector<QTableWidgetItem*> verticalHeaderItems;
- QVector<QTableWidgetItem*> horizontalHeaderItems;
+ QList<QTableWidgetItem *> tableItems;
+ QList<QTableWidgetItem *> verticalHeaderItems;
+ QList<QTableWidgetItem *> horizontalHeaderItems;
// A cache must be mutable if get-functions should have const modifiers
mutable QModelIndexList cachedIndexes;
@@ -192,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 9aba17be70..744f29ca17 100644
--- a/src/widgets/itemviews/qtreeview.cpp
+++ b/src/widgets/itemviews/qtreeview.cpp
@@ -1,45 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtreeview.h"
#include <qheaderview.h>
-#include <qitemdelegate.h>
+#include <qabstractitemdelegate.h>
#include <qapplication.h>
#include <qscrollbar.h>
#include <qpainter.h>
@@ -51,7 +15,7 @@
#include <qdebug.h>
#include <QMetaMethod>
#include <private/qscrollbar_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include <qaccessible.h>
#endif
@@ -160,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
*/
@@ -206,6 +169,8 @@ QTreeView::QTreeView(QTreeViewPrivate &dd, QWidget *parent)
*/
QTreeView::~QTreeView()
{
+ Q_D(QTreeView);
+ d->clearConnections();
}
/*!
@@ -217,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();
@@ -238,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());
}
/*!
@@ -273,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);
@@ -282,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);
}
}
@@ -323,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();
@@ -616,7 +581,7 @@ void QTreeView::setRowHidden(int row, const QModelIndex &parent, bool hide)
if (hide) {
d->hiddenIndexes.insert(index);
- } else if(d->isPersistent(index)) { //if the index is not persistent, it cannot be in the set
+ } else if (d->isPersistent(index)) { //if the index is not persistent, it cannot be in the set
d->hiddenIndexes.remove(index);
}
@@ -674,7 +639,8 @@ void QTreeView::setFirstColumnSpanned(int row, const QModelIndex &parent, bool s
/*!
\reimp
*/
-void QTreeView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
+void QTreeView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &roles)
{
Q_D(QTreeView);
@@ -875,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;
}
@@ -1037,9 +1004,9 @@ void QTreeView::keyboardSearch(const QString &search)
// special case for searches with same key like 'aaaaa'
bool sameKey = false;
- if (d->keyboardInput.length() > 1) {
- int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.length() - 1));
- sameKey = (c == d->keyboardInput.length());
+ if (d->keyboardInput.size() > 1) {
+ int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.size() - 1));
+ sameKey = (c == d->keyboardInput.size());
if (sameKey)
skipRow = true;
}
@@ -1064,7 +1031,7 @@ void QTreeView::keyboardSearch(const QString &search)
int bestAbove = -1;
int bestBelow = -1;
QString searchString = sameKey ? QString(d->keyboardInput.at(0)) : d->keyboardInput;
- for (int i = 0; i < d->viewItems.count(); ++i) {
+ for (int i = 0; i < d->viewItems.size(); ++i) {
if ((int)d->viewItems.at(i).level > previousLevel) {
QModelIndex searchFrom = d->viewItems.at(i).index;
if (start.column() > 0)
@@ -1072,7 +1039,7 @@ void QTreeView::keyboardSearch(const QString &search)
if (searchFrom.parent() == start.parent())
searchFrom = start;
QModelIndexList match = d->model->match(searchFrom, Qt::DisplayRole, searchString);
- if (match.count()) {
+ if (match.size()) {
int hitIndex = d->viewIndex(match.at(0));
if (hitIndex >= 0 && hitIndex < startIndex)
bestAbove = bestAbove == -1 ? hitIndex : qMin(hitIndex, bestAbove);
@@ -1103,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);
+}
- if (!d->isIndexValid(index) || isIndexHidden(index))
+/*!
+ \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 (!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();
- int vi = d->viewIndex(index);
- if (vi < 0)
+ executePostedLayout();
+
+ 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);
}
/*!
@@ -1239,6 +1237,22 @@ void QTreeView::scrollTo(const QModelIndex &index, ScrollHint hint)
/*!
\reimp
*/
+void QTreeView::changeEvent(QEvent *event)
+{
+ Q_D(QTreeView);
+ if (event->type() == QEvent::StyleChange) {
+ if (!d->customIndent) {
+ // QAbstractItemView calls this method in case of a style change,
+ // so update the indentation here if it wasn't set manually.
+ d->updateIndentationFromStyle();
+ }
+ }
+ QAbstractItemView::changeEvent(event);
+}
+
+/*!
+ \reimp
+*/
void QTreeView::timerEvent(QTimerEvent *event)
{
Q_D(QTreeView);
@@ -1296,16 +1310,13 @@ bool QTreeView::viewportEvent(QEvent *event)
case QEvent::HoverLeave:
case QEvent::HoverMove: {
QHoverEvent *he = static_cast<QHoverEvent*>(event);
- int oldBranch = d->hoverBranch;
- d->hoverBranch = d->itemDecorationAt(he->pos());
- QModelIndex newIndex = indexAt(he->pos());
+ 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:
@@ -1388,12 +1399,28 @@ 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
+{
+ const auto parentIdx = topLeft.parent();
+ executePostedLayout();
+ QRect updateRect;
+ for (int r = topLeft.row(); r <= bottomRight.row(); ++r) {
+ if (isRowHidden(model->index(r, 0, parentIdx)))
+ continue;
+ for (int c = topLeft.column(); c <= bottomRight.column(); ++c) {
+ const QModelIndex idx(model->index(r, c, parentIdx));
+ updateRect |= visualRect(idx, SingleSection);
+ }
+ }
+ return rect.intersected(updateRect);
}
/*!
@@ -1426,8 +1453,11 @@ void QTreeViewPrivate::adjustViewOptionsForIndex(QStyleOptionViewItem *option, c
option->showDecorationSelected = (selectionBehavior & QTreeView::SelectRows)
|| option->showDecorationSelected;
- QVector<int> logicalIndices; // index = visual index of visible columns only. data = logical index.
- QVector<QStyleOptionViewItem::ViewItemPosition> viewItemPosList; // vector of left/middle/end for each logicalIndex, visible columns only.
+ QList<int>
+ logicalIndices; // index = visual index of visible columns only. data = logical index.
+ QList<QStyleOptionViewItem::ViewItemPosition>
+ viewItemPosList; // vector of left/middle/end for each logicalIndex, visible columns
+ // only.
const bool spanning = viewItems.at(row).spanning;
const int left = (spanning ? header->visualIndex(0) : 0);
const int right = (spanning ? header->visualIndex(0) : header->count() - 1 );
@@ -1448,13 +1478,15 @@ void QTreeViewPrivate::adjustViewOptionsForIndex(QStyleOptionViewItem *option, c
void QTreeView::drawTree(QPainter *painter, const QRegion &region) const
{
Q_D(const QTreeView);
- const QVector<QTreeViewItem> viewItems = d->viewItems;
+ // d->viewItems changes when posted layouts are executed in itemDecorationAt, so don't copy
+ const QList<QTreeViewItem> &viewItems = d->viewItems;
- QStyleOptionViewItem option = d->viewOptionsV1();
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
const QStyle::State state = option.state;
d->current = 0;
- if (viewItems.count() == 0 || d->header->count() == 0 || !d->itemDelegate) {
+ if (viewItems.size() == 0 || d->header->count() == 0 || !d->itemDelegate) {
d->paintAlternatingRowColors(painter, &option, 0, region.boundingRect().bottom()+1);
return;
}
@@ -1471,7 +1503,7 @@ void QTreeView::drawTree(QPainter *painter, const QRegion &region) const
QPoint hoverPos = d->viewport->mapFromGlobal(QCursor::pos());
d->hoverBranch = d->itemDecorationAt(hoverPos);
- QVector<int> drawn;
+ QList<int> drawn;
bool multipleRects = (region.rectCount() > 1);
for (const QRect &a : region) {
const QRect area = (multipleRects
@@ -1483,7 +1515,7 @@ void QTreeView::drawTree(QPainter *painter, const QRegion &region) const
int y = firstVisibleItemOffset; // we may only see part of the first item
// start at the top of the viewport and iterate down to the update area
- for (; i < viewItems.count(); ++i) {
+ for (; i < viewItems.size(); ++i) {
const int itemHeight = d->itemHeight(i);
if (y + itemHeight > area.top())
break;
@@ -1491,9 +1523,10 @@ void QTreeView::drawTree(QPainter *painter, const QRegion &region) const
}
// paint the visible rows
- for (; i < viewItems.count() && y <= area.bottom(); ++i) {
+ 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);
@@ -1524,7 +1557,9 @@ static inline bool ancestorOf(QObject *widget, QObject *other)
return false;
}
-void QTreeViewPrivate::calcLogicalIndices(QVector<int> *logicalIndices, QVector<QStyleOptionViewItem::ViewItemPosition> *itemPositions, int left, int right) const
+void QTreeViewPrivate::calcLogicalIndices(
+ QList<int> *logicalIndices, QList<QStyleOptionViewItem::ViewItemPosition> *itemPositions,
+ int left, int right) const
{
const int columnCount = header->count();
/* 'left' and 'right' are the left-most and right-most visible visual indices.
@@ -1550,11 +1585,11 @@ void QTreeViewPrivate::calcLogicalIndices(QVector<int> *logicalIndices, QVector<
}
}
- itemPositions->resize(logicalIndices->count());
- for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices->count(); ++currentLogicalSection) {
+ itemPositions->resize(logicalIndices->size());
+ for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices->size(); ++currentLogicalSection) {
const int headerSection = logicalIndices->at(currentLogicalSection);
// determine the viewItemPosition depending on the position of column 0
- int nextLogicalSection = currentLogicalSection + 1 >= logicalIndices->count()
+ int nextLogicalSection = currentLogicalSection + 1 >= logicalIndices->size()
? logicalIndexAfterRight
: logicalIndices->at(currentLogicalSection + 1);
int prevLogicalSection = currentLogicalSection - 1 < 0
@@ -1580,6 +1615,7 @@ void QTreeViewPrivate::calcLogicalIndices(QVector<int> *logicalIndices, QVector<
*/
int QTreeViewPrivate::widthHintForIndex(const QModelIndex &index, int hint, const QStyleOptionViewItem &option, int i) const
{
+ Q_Q(const QTreeView);
QWidget *editor = editorForIndex(index).widget.data();
if (editor && persistent.contains(editor)) {
hint = qMax(hint, editor->sizeHint().width());
@@ -1587,7 +1623,7 @@ int QTreeViewPrivate::widthHintForIndex(const QModelIndex &index, int hint, cons
int max = editor->maximumSize().width();
hint = qBound(min, hint, max);
}
- int xhint = delegateForIndex(index)->sizeHint(option, index).width();
+ int xhint = q->itemDelegateForIndex(index)->sizeHint(option, index).width();
hint = qMax(hint, xhint + (isTreePosition(index.column()) ? indentationForItem(i) : 0));
return hint;
}
@@ -1652,8 +1688,11 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option,
}
}
- // ### special case: treeviews with multiple columns draw
- // the selections differently than with only one column
+ // ### special case: if we select entire rows, then we need to draw the
+ // selection in the first column all the way to the second column, rather
+ // than just around the item text. We abuse showDecorationSelected to
+ // indicate this to the style. Below we will reset this value temporarily
+ // to only respect the styleHint while we are rendering the decoration.
opt.showDecorationSelected = (d->selectionBehavior & SelectRows)
|| option.showDecorationSelected;
@@ -1664,11 +1703,12 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option,
&& index.parent() == hover.parent()
&& index.row() == hover.row();
- QVector<int> logicalIndices;
- QVector<QStyleOptionViewItem::ViewItemPosition> viewItemPosList; // vector of left/middle/end for each logicalIndex
+ QList<int> logicalIndices;
+ QList<QStyleOptionViewItem::ViewItemPosition>
+ viewItemPosList; // vector of left/middle/end for each logicalIndex
d->calcLogicalIndices(&logicalIndices, &viewItemPosList, left, right);
- for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices.count(); ++currentLogicalSection) {
+ for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices.size(); ++currentLogicalSection) {
int headerSection = logicalIndices.at(currentLogicalSection);
position = columnViewportPosition(headerSection) + offset.x();
width = header->sectionSize(headerSection);
@@ -1725,7 +1765,7 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option,
/* Prior to Qt 4.3, the background of the branch (in selected state and
alternate row color was provided by the view. For backward compatibility,
- this is now delegated to the style using PE_PanelViewItemRow which
+ this is now delegated to the style using PE_PanelItemViewRow which
does the appropriate fill */
if (d->isTreePosition(headerSection)) {
const int i = d->indentationForItem(d->current);
@@ -1737,8 +1777,16 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option,
}
// draw background for the branch (selection + alternate row)
opt.rect = branches;
- if (style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, &opt, this))
- style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this);
+
+ // We use showDecorationSelected both to store the style hint, and to indicate
+ // that the entire row has to be selected (see overrides of the value if
+ // selectionBehavior == SelectRow).
+ // While we are only painting the background we don't care for the
+ // selectionBehavior factor, so respect only the style value, and reset later.
+ const bool oldShowDecorationSelected = opt.showDecorationSelected;
+ opt.showDecorationSelected = style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected,
+ &opt, this);
+ style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this);
// draw background of the item (only alternate row). rest of the background
// is provided by the delegate
@@ -1747,6 +1795,7 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option,
opt.rect.setRect(reverse ? position : i + position, y, width - i, height);
style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this);
opt.state = oldState;
+ opt.showDecorationSelected = oldShowDecorationSelected;
if (d->indent != 0)
drawBranches(painter, branches, index);
@@ -1760,7 +1809,7 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option,
opt.state = oldState;
}
- d->delegateForIndex(modelIndex)->paint(painter, opt, modelIndex);
+ itemDelegateForIndex(modelIndex)->paint(painter, opt, modelIndex);
}
if (currentRowHasFocus) {
@@ -1809,7 +1858,8 @@ void QTreeView::drawBranches(QPainter *painter, const QRect &rect,
QModelIndex current = parent;
QModelIndex ancestor = current.parent();
- QStyleOptionViewItem opt = viewOptions();
+ QStyleOptionViewItem opt;
+ initViewItemOption(&opt);
QStyle::State extraFlags = QStyle::State_None;
if (isEnabled())
extraFlags |= QStyle::State_Enabled;
@@ -1889,8 +1939,8 @@ void QTreeView::mousePressEvent(QMouseEvent *event)
Q_D(QTreeView);
bool handled = false;
if (style()->styleHint(QStyle::SH_ListViewExpand_SelectMouseType, nullptr, this) == QEvent::MouseButtonPress)
- handled = d->expandOrCollapseItemAtPos(event->pos());
- if (!handled && d->itemDecorationAt(event->pos()) == -1)
+ handled = d->expandOrCollapseItemAtPos(event->position().toPoint());
+ if (!handled && d->itemDecorationAt(event->position().toPoint()) == -1)
QAbstractItemView::mousePressEvent(event);
else
d->pressedIndex = QModelIndex();
@@ -1902,13 +1952,13 @@ void QTreeView::mousePressEvent(QMouseEvent *event)
void QTreeView::mouseReleaseEvent(QMouseEvent *event)
{
Q_D(QTreeView);
- if (d->itemDecorationAt(event->pos()) == -1) {
+ if (d->itemDecorationAt(event->position().toPoint()) == -1) {
QAbstractItemView::mouseReleaseEvent(event);
} else {
if (state() == QAbstractItemView::DragSelectingState || state() == QAbstractItemView::DraggingState)
setState(QAbstractItemView::NoState);
if (style()->styleHint(QStyle::SH_ListViewExpand_SelectMouseType, nullptr, this) == QEvent::MouseButtonRelease)
- d->expandOrCollapseItemAtPos(event->pos());
+ d->expandOrCollapseItemAtPos(event->position().toPoint());
}
}
@@ -1918,17 +1968,17 @@ void QTreeView::mouseReleaseEvent(QMouseEvent *event)
void QTreeView::mouseDoubleClickEvent(QMouseEvent *event)
{
Q_D(QTreeView);
- if (state() != NoState || !d->viewport->rect().contains(event->pos()))
+ if (state() != NoState || !d->viewport->rect().contains(event->position().toPoint()))
return;
- int i = d->itemDecorationAt(event->pos());
+ int i = d->itemDecorationAt(event->position().toPoint());
if (i == -1) {
- i = d->itemAtCoordinate(event->y());
+ i = d->itemAtCoordinate(event->position().toPoint().y());
if (i == -1)
return; // user clicked outside the items
const QPersistentModelIndex firstColumnIndex = d->viewItems.at(i).index;
- const QPersistentModelIndex persistent = indexAt(event->pos());
+ const QPersistentModelIndex persistent = indexAt(event->position().toPoint());
if (d->pressedIndex != persistent) {
mousePressEvent(event);
@@ -1947,18 +1997,18 @@ void QTreeView::mouseDoubleClickEvent(QMouseEvent *event)
if (!style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, nullptr, this))
emit activated(persistent);
- d->pressedIndex = QModelIndex();
+ d->releaseFromDoubleClick = true;
d->executePostedLayout(); // we need to make sure viewItems is updated
if (d->itemsExpandable
&& d->expandsOnDoubleClick
&& d->hasVisibleChildren(persistent)) {
- if (!((i < d->viewItems.count()) && (d->viewItems.at(i).index == firstColumnIndex))) {
+ if (!((i < d->viewItems.size()) && (d->viewItems.at(i).index == firstColumnIndex))) {
// find the new index of the item
- for (i = 0; i < d->viewItems.count(); ++i) {
+ for (i = 0; i < d->viewItems.size(); ++i) {
if (d->viewItems.at(i).index == firstColumnIndex)
break;
}
- if (i == d->viewItems.count())
+ if (i == d->viewItems.size())
return;
}
if (d->viewItems.at(i).expanded)
@@ -1977,7 +2027,7 @@ void QTreeView::mouseDoubleClickEvent(QMouseEvent *event)
void QTreeView::mouseMoveEvent(QMouseEvent *event)
{
Q_D(QTreeView);
- if (d->itemDecorationAt(event->pos()) == -1) // ### what about expanding/collapsing state ?
+ if (d->itemDecorationAt(event->position().toPoint()) == -1) // ### what about expanding/collapsing state ?
QAbstractItemView::mouseMoveEvent(event);
}
@@ -2056,7 +2106,7 @@ QModelIndex QTreeView::indexBelow(const QModelIndex &index) const
return QModelIndex();
d->executePostedLayout();
int i = d->viewIndex(index);
- if (++i >= d->viewItems.count())
+ if (++i >= d->viewItems.size())
return QModelIndex();
const QModelIndex firstColumnIndex = d->viewItems.at(i).index;
return firstColumnIndex.sibling(firstColumnIndex.row(), index.column());
@@ -2070,12 +2120,6 @@ QModelIndex QTreeView::indexBelow(const QModelIndex &index) const
void QTreeView::doItemsLayout()
{
Q_D(QTreeView);
- if (!d->customIndent) {
- // ### Qt 6: move to event()
- // QAbstractItemView calls this method in case of a style change,
- // so update the indentation here if it wasn't set manually.
- d->updateIndentationFromStyle();
- }
if (d->hasRemovedItems) {
//clean the QSet that may contains old (and this invalid) indexes
d->hasRemovedItems = false;
@@ -2101,6 +2145,7 @@ void QTreeView::doItemsLayout()
}
QAbstractItemView::doItemsLayout();
d->header->doItemsLayout();
+ d->updateAccessibility();
}
/*!
@@ -2146,7 +2191,7 @@ int QTreeView::verticalOffset() const
// ### find a faster way to do this
d->executePostedLayout();
int offset = 0;
- const int cnt = std::min(d->viewItems.count(), verticalScrollBar()->value());
+ const int cnt = qMin(d->viewItems.size(), verticalScrollBar()->value());
for (int i = 0; i < cnt; ++i)
offset += d->itemHeight(i);
return offset;
@@ -2172,14 +2217,13 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
int c = 0;
while (c < d->header->count() && d->header->isSectionHidden(d->header->logicalIndex(c)))
++c;
- if (i < d->viewItems.count() && c < d->header->count()) {
+ if (i < d->viewItems.size() && c < d->header->count()) {
return d->modelIndex(i, d->header->logicalIndex(c));
}
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)
@@ -2204,7 +2248,7 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
return d->modelIndex(d->above(vi), current.column());
case MoveLeft: {
QScrollBar *sb = horizontalScrollBar();
- if (vi < d->viewItems.count() && d->viewItems.at(vi).expanded && d->itemsExpandable && sb->value() == sb->minimum()) {
+ if (vi < d->viewItems.size() && d->viewItems.at(vi).expanded && d->itemsExpandable && sb->value() == sb->minimum()) {
d->collapse(vi, true);
d->moveCursorUpdatedView = true;
} else {
@@ -2239,7 +2283,7 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
break;
}
case MoveRight:
- if (vi < d->viewItems.count() && !d->viewItems.at(vi).expanded && d->itemsExpandable
+ if (vi < d->viewItems.size() && !d->viewItems.at(vi).expanded && d->itemsExpandable
&& d->hasVisibleChildren(d->viewItems.at(vi).index)) {
d->expand(vi, true);
d->moveCursorUpdatedView = true;
@@ -2353,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)) {
@@ -2364,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);
@@ -2394,7 +2438,7 @@ QModelIndexList QTreeView::selectedIndexes() const
QModelIndexList modelSelected;
if (selectionModel())
modelSelected = selectionModel()->selectedIndexes();
- for (int i = 0; i < modelSelected.count(); ++i) {
+ for (int i = 0; i < modelSelected.size(); ++i) {
// check that neither the parents nor the index is hidden before we add
QModelIndex index = modelSelected.at(i);
while (index.isValid() && !isIndexHidden(index))
@@ -2431,7 +2475,7 @@ void QTreeView::scrollContentsBy(int dx, int dy)
// guestimate the number of items in the viewport
int viewCount = d->viewport->height() / itemHeight;
- int maxDeltaY = qMin(d->viewItems.count(), viewCount);
+ int maxDeltaY = qMin(d->viewItems.size(), viewCount);
// no need to do a lot of work if we are going to redraw the whole thing anyway
if (qAbs(dy) > qAbs(maxDeltaY) && d->editorIndexHash.isEmpty()) {
verticalScrollBar()->update();
@@ -2447,12 +2491,12 @@ void QTreeView::scrollContentsBy(int dx, int dy)
dy = 0;
if (previousViewIndex < currentViewIndex) { // scrolling down
for (int i = previousViewIndex; i < currentViewIndex; ++i) {
- if (i < d->viewItems.count())
+ if (i < d->viewItems.size())
dy -= d->itemHeight(i);
}
} else if (previousViewIndex > currentViewIndex) { // scrolling up
for (int i = previousViewIndex - 1; i >= currentViewIndex; --i) {
- if (i < d->viewItems.count())
+ if (i < d->viewItems.size())
dy += d->itemHeight(i);
}
}
@@ -2540,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);
}
/*!
@@ -2576,22 +2620,6 @@ void QTreeView::resizeColumnToContents(int column)
d->header->resizeSection(column, qMax(contents, header));
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \obsolete
- \overload
-
- This function is deprecated. Use
- sortByColumn(int column, Qt::SortOrder order) instead.
- Sorts the model by the values in the given \a column.
-*/
-void QTreeView::sortByColumn(int column)
-{
- Q_D(QTreeView);
- sortByColumn(column, d->header->sortIndicatorOrder());
-}
-#endif
-
/*!
\since 4.2
@@ -2608,11 +2636,11 @@ void QTreeView::sortByColumn(int column, Qt::SortOrder order)
Q_D(QTreeView);
if (column < -1)
return;
- // If sorting is enabled it will emit a signal connected to
- // _q_sortIndicatorChanged, which then actually sorts
d->header->setSortIndicator(column, order);
- // If sorting is not enabled, force to sort now
- if (!d->sortingEnabled)
+ // If sorting is not enabled or has the same order as before, force to sort now
+ // else sorting will be trigger through sortIndicatorChanged()
+ if (!d->sortingEnabled ||
+ (d->header->sortIndicatorSection() == column && d->header->sortIndicatorOrder() == order))
d->model->sort(column, order);
}
@@ -2647,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();
@@ -2664,7 +2693,10 @@ QSize QTreeView::viewportSizeHint() const
\since 4.2
Expands all expandable items.
- \warning: if the model contains a large number of items,
+ \note This function will not try to \l{QAbstractItemModel::fetchMore}{fetch more}
+ data.
+
+ \warning If the model contains a large number of items,
this function will take some time to execute.
\sa collapseAll(), expand(), collapse(), setExpanded()
@@ -2677,6 +2709,7 @@ void QTreeView::expandAll()
d->layout(-1, true);
updateGeometries();
d->viewport->update();
+ d->updateAccessibility();
}
/*!
@@ -2686,7 +2719,10 @@ void QTreeView::expandAll()
A \a depth of -1 will expand all children, a \a depth of 0 will
only expand the given \a index.
- \warning: if the model contains a large number of items,
+ \note This function will not try to \l{QAbstractItemModel::fetchMore}{fetch more}
+ data.
+
+ \warning If the model contains a large number of items,
this function will take some time to execute.
\sa expandAll()
@@ -2751,6 +2787,9 @@ void QTreeView::collapseAll()
\since 4.3
Expands all expandable items to the given \a depth.
+ \note This function will not try to \l{QAbstractItemModel::fetchMore}{fetch more}
+ data.
+
\sa expandAll(), collapseAll(), expand(), collapse(), setExpanded()
*/
void QTreeView::expandToDepth(int depth)
@@ -2762,7 +2801,7 @@ void QTreeView::expandToDepth(int depth)
d->expandedIndexes.clear();
d->interruptDelayedItemsLayout();
d->layout(-1);
- for (int i = 0; i < d->viewItems.count(); ++i) {
+ for (int i = 0; i < d->viewItems.size(); ++i) {
if (d->viewItems.at(i).level <= (uint)depth) {
d->viewItems[i].expanded = true;
d->layout(i);
@@ -2794,6 +2833,7 @@ void QTreeView::expandToDepth(int depth)
updateGeometries();
d->viewport->update();
+ d->updateAccessibility();
}
/*!
@@ -2859,8 +2899,9 @@ int QTreeView::sizeHintForColumn(int column) const
return -1;
ensurePolished();
int w = 0;
- QStyleOptionViewItem option = d->viewOptionsV1();
- const QVector<QTreeViewItem> viewItems = d->viewItems;
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
+ const QList<QTreeViewItem> viewItems = d->viewItems;
const int maximumProcessRows = d->header->resizeContentsPrecision(); // To avoid this to take forever.
@@ -2971,8 +3012,9 @@ int QTreeView::indexRowSizeHint(const QModelIndex &index) const
qSwap(end, start);
int height = -1;
- QStyleOptionViewItem option = d->viewOptionsV1();
- // ### If we want word wrapping in the items,
+ QStyleOptionViewItem option;
+ initViewItemOption(&option);
+ // ### If we want word wrapping in the items,
// ### we need to go through all the columns
// ### and set the width of the column
@@ -2992,7 +3034,7 @@ int QTreeView::indexRowSizeHint(const QModelIndex &index) const
int max = editor->maximumSize().height();
height = qBound(min, height, max);
}
- int hint = d->delegateForIndex(idx)->sizeHint(option, idx).height();
+ int hint = itemDelegateForIndex(idx)->sizeHint(option, idx).height();
height = qMax(height, hint);
}
}
@@ -3052,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);
@@ -3088,13 +3145,14 @@ void QTreeViewPrivate::expand(int item, bool emitSignal)
beginAnimatedOperation();
#endif // animation
}
+ updateAccessibility();
}
void QTreeViewPrivate::insertViewItems(int pos, int count, const QTreeViewItem &viewItem)
{
viewItems.insert(pos, count, viewItem);
QTreeViewItem *items = viewItems.data();
- for (int i = pos + count; i < viewItems.count(); i++)
+ for (int i = pos + count; i < viewItems.size(); i++)
if (items[i].parentItem >= pos)
items[i].parentItem += count;
}
@@ -3103,7 +3161,7 @@ void QTreeViewPrivate::removeViewItems(int pos, int count)
{
viewItems.remove(pos, count);
QTreeViewItem *items = viewItems.data();
- for (int i = pos; i < viewItems.count(); i++)
+ for (int i = pos; i < viewItems.size(); i++)
if (items[i].parentItem >= pos)
items[i].parentItem -= count;
}
@@ -3243,14 +3301,15 @@ QPixmap QTreeViewPrivate::renderTreeToPixmapForAnimation(const QRect &rect) cons
painter.end();
//and now let's render the editors the editors
- QStyleOptionViewItem option = viewOptionsV1();
+ QStyleOptionViewItem option;
+ q->initViewItemOption(&option);
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 = delegateForIndex(index))
+ if (QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index))
delegate->updateEditorGeometry(editor, option, index);
const QPoint pos = editor->pos();
@@ -3267,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);
@@ -3276,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
@@ -3315,11 +3389,32 @@ 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))
+ if (model->canFetchMore(parent)) {
+ // fetchMore first, otherwise we might not yet have any data for sizeHintForRow
model->fetchMore(parent);
- count = model->rowCount(parent);
+ // guestimate the number of items in the viewport, and fetch as many as might fit
+ const int itemHeight = defaultItemHeight <= 0 ? q->sizeHintForRow(0) : defaultItemHeight;
+ const int viewCount = itemHeight ? viewport->height() / itemHeight : 0;
+ int lastCount = -1;
+ while ((count = model->rowCount(parent)) < viewCount &&
+ count != lastCount && model->canFetchMore(parent)) {
+ model->fetchMore(parent);
+ lastCount = count;
+ }
+ } else {
+ count = model->rowCount(parent);
+ }
}
bool expanding = true;
@@ -3334,7 +3429,7 @@ void QTreeViewPrivate::layout(int i, bool recursiveExpanding, bool afterIsUninit
if (!afterIsUninitialized)
insertViewItems(i + 1, count, QTreeViewItem()); // expand
else if (count > 0)
- viewItems.resize(viewItems.count() + count);
+ viewItems.resize(viewItems.size() + count);
} else {
expanding = false;
}
@@ -3404,7 +3499,7 @@ int QTreeViewPrivate::pageUp(int i) const
index = 0;
while (isItemHiddenOrDisabled(index))
index++;
- return index >= viewItems.count() ? 0 : index;
+ return index >= viewItems.size() ? 0 : index;
}
int QTreeViewPrivate::pageDown(int i) const
@@ -3412,11 +3507,11 @@ int QTreeViewPrivate::pageDown(int i) const
int index = itemAtCoordinate(coordinateForItem(i) + viewport->height());
while (isItemHiddenOrDisabled(index))
index++;
- if (index == -1 || index >= viewItems.count())
- index = viewItems.count() - 1;
+ if (index == -1 || index >= viewItems.size())
+ index = viewItems.size() - 1;
while (isItemHiddenOrDisabled(index))
index--;
- return index == -1 ? viewItems.count() - 1 : index;
+ return index == -1 ? viewItems.size() - 1 : index;
}
int QTreeViewPrivate::itemForKeyHome() const
@@ -3424,20 +3519,20 @@ int QTreeViewPrivate::itemForKeyHome() const
int index = 0;
while (isItemHiddenOrDisabled(index))
index++;
- return index >= viewItems.count() ? 0 : index;
+ return index >= viewItems.size() ? 0 : index;
}
int QTreeViewPrivate::itemForKeyEnd() const
{
- int index = viewItems.count() - 1;
+ int index = viewItems.size() - 1;
while (isItemHiddenOrDisabled(index))
index--;
- return index == -1 ? viewItems.count() - 1 : index;
+ return index == -1 ? viewItems.size() - 1 : index;
}
int QTreeViewPrivate::indentationForItem(int item) const
{
- if (item < 0 || item >= viewItems.count())
+ if (item < 0 || item >= viewItems.size())
return 0;
int level = viewItems.at(item).level;
if (rootDecoration)
@@ -3447,6 +3542,7 @@ int QTreeViewPrivate::indentationForItem(int item) const
int QTreeViewPrivate::itemHeight(int item) const
{
+ Q_ASSERT(item < viewItems.size());
if (uniformRowHeights)
return defaultItemHeight;
if (viewItems.isEmpty())
@@ -3474,7 +3570,7 @@ int QTreeViewPrivate::coordinateForItem(int item) const
return (item * defaultItemHeight) - vbar->value();
// ### optimize (maybe do like QHeaderView by letting items have startposition)
int y = 0;
- for (int i = 0; i < viewItems.count(); ++i) {
+ for (int i = 0; i < viewItems.size(); ++i) {
if (i == item)
return y - vbar->value();
y += itemHeight(i);
@@ -3488,7 +3584,7 @@ int QTreeViewPrivate::coordinateForItem(int item) const
// ### slow if the item is not visible
int viewItemCoordinate = 0;
int viewItemIndex = topViewItemIndex;
- while (viewItemIndex < viewItems.count()) {
+ while (viewItemIndex < viewItems.size()) {
if (viewItemIndex == item)
return viewItemCoordinate;
viewItemCoordinate += itemHeight(viewItemIndex);
@@ -3520,7 +3616,7 @@ int QTreeViewPrivate::coordinateForItem(int item) const
*/
int QTreeViewPrivate::itemAtCoordinate(int coordinate) const
{
- const int itemCount = viewItems.count();
+ const int itemCount = viewItems.size();
if (itemCount == 0)
return -1;
if (uniformRowHeights && defaultItemHeight <= 0)
@@ -3533,7 +3629,7 @@ int QTreeViewPrivate::itemAtCoordinate(int coordinate) const
// ### optimize
int viewItemCoordinate = 0;
const int contentsCoordinate = coordinate + vbar->value();
- for (int viewItemIndex = 0; viewItemIndex < viewItems.count(); ++viewItemIndex) {
+ for (int viewItemIndex = 0; viewItemIndex < viewItems.size(); ++viewItemIndex) {
viewItemCoordinate += itemHeight(viewItemIndex);
if (viewItemCoordinate > contentsCoordinate)
return (viewItemIndex >= itemCount ? -1 : viewItemIndex);
@@ -3549,7 +3645,7 @@ int QTreeViewPrivate::itemAtCoordinate(int coordinate) const
if (coordinate >= 0) {
// the coordinate is in or below the viewport
int viewItemCoordinate = 0;
- for (int viewItemIndex = topViewItemIndex; viewItemIndex < viewItems.count(); ++viewItemIndex) {
+ for (int viewItemIndex = topViewItemIndex; viewItemIndex < viewItems.size(); ++viewItemIndex) {
viewItemCoordinate += itemHeight(viewItemIndex);
if (viewItemCoordinate > coordinate)
return (viewItemIndex >= itemCount ? -1 : viewItemIndex);
@@ -3572,7 +3668,7 @@ int QTreeViewPrivate::viewIndex(const QModelIndex &_index) const
if (!_index.isValid() || viewItems.isEmpty())
return -1;
- const int totalCount = viewItems.count();
+ const int totalCount = viewItems.size();
const QModelIndex index = _index.sibling(_index.row(), 0);
const int row = index.row();
const quintptr internalId = index.internalId();
@@ -3613,7 +3709,7 @@ int QTreeViewPrivate::viewIndex(const QModelIndex &_index) const
QModelIndex QTreeViewPrivate::modelIndex(int i, int column) const
{
- if (i < 0 || i >= viewItems.count())
+ if (i < 0 || i >= viewItems.size())
return QModelIndex();
QModelIndex ret = viewItems.at(i).index;
@@ -3628,7 +3724,7 @@ int QTreeViewPrivate::firstVisibleItem(int *offset) const
if (verticalScrollMode == QAbstractItemView::ScrollPerItem) {
if (offset)
*offset = 0;
- return (value < 0 || value >= viewItems.count()) ? -1 : value;
+ return (value < 0 || value >= viewItems.size()) ? -1 : value;
}
// ScrollMode == ScrollPerPixel
if (uniformRowHeights) {
@@ -3640,7 +3736,7 @@ int QTreeViewPrivate::firstVisibleItem(int *offset) const
return value / defaultItemHeight;
}
int y = 0; // ### (maybe do like QHeaderView by letting items have startposition)
- for (int i = 0; i < viewItems.count(); ++i) {
+ for (int i = 0; i < viewItems.size(); ++i) {
y += itemHeight(i); // the height value is cached
if (y > value) {
if (offset)
@@ -3661,7 +3757,7 @@ int QTreeViewPrivate::lastVisibleItem(int firstVisual, int offset) const
int y = - offset;
int value = viewport->height();
- for (int i = firstVisual; i < viewItems.count(); ++i) {
+ for (int i = firstVisual; i < viewItems.size(); ++i) {
y += itemHeight(i); // the height value is cached
if (y > value)
return i;
@@ -3689,11 +3785,11 @@ void QTreeViewPrivate::updateScrollBars()
int itemsInViewport = 0;
if (uniformRowHeights) {
if (defaultItemHeight <= 0)
- itemsInViewport = viewItems.count();
+ itemsInViewport = viewItems.size();
else
itemsInViewport = viewportSize.height() / defaultItemHeight;
} else {
- const int itemsCount = viewItems.count();
+ const int itemsCount = viewItems.size();
const int viewportHeight = viewportSize.height();
for (int height = 0, item = itemsCount - 1; item >= 0; --item) {
height += itemHeight(item);
@@ -3705,15 +3801,15 @@ void QTreeViewPrivate::updateScrollBars()
if (verticalScrollMode == QAbstractItemView::ScrollPerItem) {
if (!viewItems.isEmpty())
itemsInViewport = qMax(1, itemsInViewport);
- vbar->setRange(0, viewItems.count() - itemsInViewport);
+ vbar->setRange(0, viewItems.size() - itemsInViewport);
vbar->setPageStep(itemsInViewport);
vbar->setSingleStep(1);
} else { // scroll per pixel
int contentsHeight = 0;
if (uniformRowHeights) {
- contentsHeight = defaultItemHeight * viewItems.count();
+ contentsHeight = defaultItemHeight * viewItems.size();
} else { // ### (maybe do like QHeaderView by letting items have startposition)
- for (int i = 0; i < viewItems.count(); ++i)
+ for (int i = 0; i < viewItems.size(); ++i)
contentsHeight += itemHeight(i);
}
vbar->setRange(0, contentsHeight - viewportSize.height());
@@ -3755,7 +3851,8 @@ int QTreeViewPrivate::itemDecorationAt(const QPoint &pos) const
bool spanned = false;
if (!spanningIndexes.isEmpty()) {
const QModelIndex index = q->indexAt(pos);
- spanned = q->isFirstColumnSpanned(index.row(), index.parent());
+ if (index.isValid())
+ spanned = q->isFirstColumnSpanned(index.row(), index.parent());
}
const int column = spanned ? 0 : header->logicalIndexAt(pos.x());
if (!isTreePosition(column))
@@ -3796,8 +3893,8 @@ QRect QTreeViewPrivate::itemDecorationRect(const QModelIndex &index) const
return q->style()->subElementRect(QStyle::SE_TreeViewDisclosureItem, &opt, q);
}
-QVector<QPair<int, int> > QTreeViewPrivate::columnRanges(const QModelIndex &topIndex,
- const QModelIndex &bottomIndex) const
+QList<QPair<int, int>> QTreeViewPrivate::columnRanges(const QModelIndex &topIndex,
+ const QModelIndex &bottomIndex) const
{
const int topVisual = header->visualIndex(topIndex.column()),
bottomVisual = header->visualIndex(bottomIndex.column());
@@ -3817,11 +3914,11 @@ QVector<QPair<int, int> > QTreeViewPrivate::columnRanges(const QModelIndex &topI
//let's sort the list
std::sort(logicalIndexes.begin(), logicalIndexes.end());
- QVector<QPair<int, int> > ret;
+ QList<QPair<int, int>> ret;
QPair<int, int> current;
current.first = -2; // -1 is not enough because -1+1 = 0
current.second = -2;
- for(int i = 0; i < logicalIndexes.count(); ++i) {
+ for(int i = 0; i < logicalIndexes.size(); ++i) {
const int logicalColumn = logicalIndexes.at(i);
if (current.second + 1 != logicalColumn) {
if (current.first != -2) {
@@ -3851,8 +3948,8 @@ void QTreeViewPrivate::select(const QModelIndex &topIndex, const QModelIndex &bo
const int top = viewIndex(topIndex),
bottom = viewIndex(bottomIndex);
- const QVector<QPair<int, int> > colRanges = columnRanges(topIndex, bottomIndex);
- QVector<QPair<int, int> >::const_iterator it;
+ const QList<QPair<int, int>> colRanges = columnRanges(topIndex, bottomIndex);
+ QList<QPair<int, int>>::const_iterator it;
for (it = colRanges.begin(); it != colRanges.end(); ++it) {
const int left = (*it).first,
right = (*it).second;
@@ -3897,7 +3994,7 @@ void QTreeViewPrivate::select(const QModelIndex &topIndex, const QModelIndex &bo
}
if (currentRange.isValid())
selection.append(currentRange);
- for (int i = 0; i < rangeStack.count(); ++i)
+ for (int i = 0; i < rangeStack.size(); ++i)
selection.append(rangeStack.at(i));
}
q->selectionModel()->select(selection, command);
@@ -3915,7 +4012,7 @@ QPair<int,int> QTreeViewPrivate::startAndEndColumns(const QRect &rect) const
start = (start == -1 ? 0 : start);
end = (end == -1 ? header->count() - 1 : end);
}
- return qMakePair<int,int>(qMin(start, end), qMax(start, end));
+ return qMakePair(qMin(start, end), qMax(start, end));
}
bool QTreeViewPrivate::hasVisibleChildren(const QModelIndex& parent) const
@@ -3939,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);
}
@@ -3963,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));
}
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive() && current.isValid()) {
+#if QT_CONFIG(accessibility)
+ if (QAccessible::isActive() && current.isValid() && hasFocus()) {
Q_D(QTreeView);
QAccessibleEvent event(this, QAccessible::Focus);
@@ -3997,7 +4087,7 @@ void QTreeView::selectionChanged(const QItemSelection &selected,
const QItemSelection &deselected)
{
QAbstractItemView::selectionChanged(selected, deselected);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
Q_D(QTreeView);
diff --git a/src/widgets/itemviews/qtreeview.h b/src/widgets/itemviews/qtreeview.h
index bb00f1df07..1dd4650c5d 100644
--- a/src/widgets/itemviews/qtreeview.h
+++ b/src/widgets/itemviews/qtreeview.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTREEVIEW_H
#define QTREEVIEW_H
@@ -143,8 +107,8 @@ public:
void doItemsLayout() override;
void reset() override;
-
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>()) override;
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
+ const QList<int> &roles = QList<int>()) override;
void selectAll() override;
Q_SIGNALS:
@@ -157,10 +121,6 @@ public Q_SLOTS:
void expand(const QModelIndex &index);
void collapse(const QModelIndex &index);
void resizeColumnToContents(int column);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTreeView::sortByColumn(int column, Qt::SortOrder order) instead")
- void sortByColumn(int column);
-#endif
void sortByColumn(int column, Qt::SortOrder order);
void expandAll();
void expandRecursively(const QModelIndex &index, int depth = -1);
@@ -189,6 +149,7 @@ protected:
QRegion visualRegionForSelection(const QItemSelection &selection) const override;
QModelIndexList selectedIndexes() const override;
+ void changeEvent(QEvent *event) override;
void timerEvent(QTimerEvent *event) override;
void paintEvent(QPaintEvent *event) override;
@@ -234,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 836d8f0c2d..d0afdf1223 100644
--- a/src/widgets/itemviews/qtreeview_p.h
+++ b/src/widgets/itemviews/qtreeview_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTREEVIEW_P_H
#define QTREEVIEW_P_H
@@ -53,11 +17,13 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "private/qabstractitemview_p.h"
+#include <QtCore/qabstractitemmodel.h>
+#include <QtCore/qlist.h>
#if QT_CONFIG(animation)
#include <QtCore/qvariantanimation.h>
#endif
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qvector.h>
+
+#include <array>
QT_REQUIRE_CONFIG(treeview);
@@ -78,7 +44,7 @@ struct QTreeViewItem
int height : 16; // row height
};
-Q_DECLARE_TYPEINFO(QTreeViewItem, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QTreeViewItem, Q_RELOCATABLE_TYPE);
class Q_WIDGETS_EXPORT QTreeViewPrivate : public QAbstractItemViewPrivate
{
@@ -98,6 +64,7 @@ public:
~QTreeViewPrivate() {}
void initialize();
+ void clearConnections();
int logicalIndexForTree() const;
inline bool isTreePosition(int logicalIndex) const
{
@@ -124,17 +91,18 @@ 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);
@@ -169,8 +137,8 @@ public:
int itemDecorationAt(const QPoint &pos) const;
QRect itemDecorationRect(const QModelIndex &index) const;
-
- QVector<QPair<int, int> > columnRanges(const QModelIndex &topIndex, const QModelIndex &bottomIndex) const;
+ QList<QPair<int, int>> columnRanges(const QModelIndex &topIndex,
+ const QModelIndex &bottomIndex) const;
void select(const QModelIndex &start, const QModelIndex &stop, QItemSelectionModel::SelectionFlags command);
QPair<int,int> startAndEndColumns(const QRect &rect) const;
@@ -181,12 +149,29 @@ public:
// logicalIndices: vector of currently visibly logical indices
// itemPositions: vector of view item positions (beginning/middle/end/onlyone)
- void calcLogicalIndices(QVector<int> *logicalIndices, QVector<QStyleOptionViewItem::ViewItemPosition> *itemPositions, int left, int right) const;
+ void calcLogicalIndices(QList<int> *logicalIndices,
+ 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;
- mutable QVector<QTreeViewItem> viewItems;
+ mutable QList<QTreeViewItem> viewItems;
mutable int lastViewedItem;
int defaultItemHeight; // this is just a number; contentsHeight() / numItems
bool uniformRowHeights; // used when all rows have the same height
@@ -229,7 +214,7 @@ public:
}
inline bool isItemHiddenOrDisabled(int i) const {
- if (i < 0 || i >= viewItems.count())
+ if (i < 0 || i >= viewItems.size())
return false;
const QModelIndex index = viewItems.at(i).index;
return isRowHidden(index) || !isIndexEnabled(index);
@@ -238,7 +223,7 @@ public:
inline int above(int item) const
{ int i = item; while (isItemHiddenOrDisabled(--item)){} return item < 0 ? i : item; }
inline int below(int item) const
- { int i = item; while (isItemHiddenOrDisabled(++item)){} return item >= viewItems.count() ? i : item; }
+ { int i = item; while (isItemHiddenOrDisabled(++item)){} return item >= viewItems.size() ? i : item; }
inline void invalidateHeightCache(int item) const
{ viewItems[item].height = 0; }
@@ -261,7 +246,7 @@ public:
int autoExpandDelay;
QBasicTimer openTimer;
- // used for drawing hilighted expand/collapse indicators
+ // used for drawing highlighted expand/collapse indicators
mutable int hoverBranch;
// used for blocking recursion when calling setViewportMargins from updateGeometries
@@ -272,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 4908ad6ad2..8e46a0efbe 100644
--- a/src/widgets/itemviews/qtreewidget.cpp
+++ b/src/widgets/itemviews/qtreewidget.cpp
@@ -1,53 +1,18 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 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 "qtreewidget.h"
#include <qheaderview.h>
#include <qpainter.h>
-#include <qitemdelegate.h>
#include <qstack.h>
#include <qdebug.h>
#include <private/qtreewidget_p.h>
#include <private/qwidgetitemdata_p.h>
#include <private/qtreewidgetitemiterator_p.h>
+#include <QtCore/private/qduplicatetracker_p.h>
+
#include <algorithm>
QT_BEGIN_NAMESPACE
@@ -110,8 +75,9 @@ public:
*/
QTreeModel::QTreeModel(int columns, QTreeWidget *parent)
- : QAbstractItemModel(parent), rootItem(new QTreeWidgetItem),
- headerItem(new QTreeWidgetItem), skipPendingSort(false)
+ : QAbstractItemModel(*new QTreeModelPrivate, parent),
+ rootItem(new QTreeWidgetItem),
+ headerItem(new QTreeWidgetItem)
{
rootItem->view = parent;
rootItem->itemFlags = Qt::ItemIsDropEnabled;
@@ -125,8 +91,7 @@ QTreeModel::QTreeModel(int columns, QTreeWidget *parent)
*/
QTreeModel::QTreeModel(QTreeModelPrivate &dd, QTreeWidget *parent)
- : QAbstractItemModel(dd, parent), rootItem(new QTreeWidgetItem),
- headerItem(new QTreeWidgetItem), skipPendingSort(false)
+ : QAbstractItemModel(dd, parent), rootItem(new QTreeWidgetItem), headerItem(new QTreeWidgetItem)
{
rootItem->view = parent;
rootItem->itemFlags = Qt::ItemIsDropEnabled;
@@ -238,7 +203,7 @@ QModelIndex QTreeModel::index(const QTreeWidgetItem *item, int column) const
int row;
int guess = item->d->rowGuess;
if (guess >= 0
- && par->children.count() > guess
+ && par->children.size() > guess
&& par->children.at(guess) == itm) {
row = guess;
} else {
@@ -390,7 +355,6 @@ bool QTreeModel::setData(const QModelIndex &index, const QVariant &value, int ro
return false;
}
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool QTreeModel::clearItemData(const QModelIndex &index)
{
if (!checkIndex(index, CheckIndexOption::IndexIsValid))
@@ -406,10 +370,9 @@ bool QTreeModel::clearItemData(const QModelIndex &index)
}
itm->d->display[index.column()] = QVariant();
itm->values[index.column()].clear();
- emit dataChanged(index, index, QVector<int>{});
+ emit dataChanged(index, index, QList<int> {});
return true;
}
-#endif
QMap<int, QVariant> QTreeModel::itemData(const QModelIndex &index) const
{
@@ -417,8 +380,8 @@ QMap<int, QVariant> QTreeModel::itemData(const QModelIndex &index) const
QTreeWidgetItem *itm = item(index);
if (itm) {
int column = index.column();
- if (column < itm->values.count()) {
- for (int i = 0; i < itm->values.at(column).count(); ++i) {
+ if (column < itm->values.size()) {
+ for (int i = 0; i < itm->values.at(column).size(); ++i) {
roles.insert(itm->values.at(column).at(i).role,
itm->values.at(column).at(i).value);
}
@@ -487,11 +450,11 @@ bool QTreeModel::insertColumns(int column, int count, const QModelIndex &parent)
while (!itemstack.isEmpty()) {
QTreeWidgetItem *par = itemstack.pop();
QList<QTreeWidgetItem*> children = par ? par->children : rootItem->children;
- for (int row = 0; row < children.count(); ++row) {
+ for (int row = 0; row < children.size(); ++row) {
QTreeWidgetItem *child = children.at(row);
- if (child->children.count())
+ if (child->children.size())
itemstack.push(child);
- child->values.insert(column, count, QVector<QWidgetItemData>());
+ child->values.insert(column, count, QList<QWidgetItemData>());
}
}
@@ -506,22 +469,18 @@ bool QTreeModel::insertColumns(int column, int count, const QModelIndex &parent)
bool QTreeModel::removeRows(int row, int count, const QModelIndex &parent) {
if (count < 1 || row < 0 || (row + count) > rowCount(parent))
return false;
-
- beginRemoveRows(parent, row, row + count - 1);
-
- QSignalBlocker blocker(this);
-
- QTreeWidgetItem *itm = item(parent);
+ QTreeWidgetItem *parentItem = item(parent);
+ // if parentItem is valid, begin/end RemoveRows is handled by takeChild below
+ if (!parentItem)
+ beginRemoveRows(parent, row, row + count - 1);
for (int i = row + count - 1; i >= row; --i) {
- QTreeWidgetItem *child = itm ? itm->takeChild(i) : rootItem->children.takeAt(i);
+ QTreeWidgetItem *child = parentItem ? parentItem->takeChild(i) : rootItem->children.takeAt(i);
Q_ASSERT(child);
child->view = nullptr;
delete child;
- child = nullptr;
}
- blocker.unblock();
-
- endRemoveRows();
+ if (!parentItem)
+ endRemoveRows();
return true;
}
@@ -622,7 +581,7 @@ void QTreeModel::ensureSorted(int column, Qt::SortOrder order,
QList<QTreeWidgetItem*> lst = itm->children;
int count = end - start + 1;
- QVector < QPair<QTreeWidgetItem*,int> > sorting(count);
+ QList<QPair<QTreeWidgetItem *, int>> sorting(count);
for (int i = 0; i < count; ++i) {
sorting[i].first = lst.at(start + i);
sorting[i].second = start + i;
@@ -667,7 +626,7 @@ void QTreeModel::ensureSorted(int column, Qt::SortOrder order,
else if (oldRow > otherRow && newRow <= otherRow)
++sorting[j].second;
}
- for (int k = 0; k < newPersistentIndexes.count(); ++k) {
+ for (int k = 0; k < newPersistentIndexes.size(); ++k) {
QModelIndex pi = newPersistentIndexes.at(k);
if (pi.parent() != parent)
continue;
@@ -738,7 +697,10 @@ QList<QTreeWidgetItem*>::iterator QTreeModel::sortedInsertionIterator(
QStringList QTreeModel::mimeTypes() const
{
- return view()->mimeTypes();
+ auto v = view();
+ if (v)
+ return v->mimeTypes();
+ return {};
}
QMimeData *QTreeModel::internalMimeData() const
@@ -780,7 +742,7 @@ Qt::DropActions QTreeModel::supportedDropActions() const
void QTreeModel::itemChanged(QTreeWidgetItem *item)
{
- SkipSorting skipSorting(this); //this is kind of wrong, but not doing this would kill performence
+ SkipSorting skipSorting(this); //this is kind of wrong, but not doing this would kill performance
QModelIndex left = index(item, 0);
QModelIndex right = index(item, item->columnCount() - 1);
emit dataChanged(left, right);
@@ -798,7 +760,7 @@ bool QTreeModel::isChanging() const
if column is -1 then all columns have changed
*/
-void QTreeModel::emitDataChanged(QTreeWidgetItem *item, int column, const QVector<int> &roles)
+void QTreeModel::emitDataChanged(QTreeWidgetItem *item, int column, const QList<int> &roles)
{
if (signalsBlocked())
return;
@@ -811,7 +773,7 @@ void QTreeModel::emitDataChanged(QTreeWidgetItem *item, int column, const QVecto
return;
}
- SkipSorting skipSorting(this); //This is a little bit wrong, but not doing it would kill performence
+ SkipSorting skipSorting(this); //This is a little bit wrong, but not doing it would kill performance
QModelIndex bottomRight, topLeft;
if (column == -1) {
@@ -843,7 +805,7 @@ void QTreeModel::beginRemoveItems(QTreeWidgetItem *parent, int row, int count)
if (!parent)
parent = rootItem;
// now update the iterators
- for (int i = 0; i < iterators.count(); ++i) {
+ for (int i = 0; i < iterators.size(); ++i) {
for (int j = 0; j < count; j++) {
QTreeWidgetItem *c = parent->child(row + j);
iterators[i]->d_func()->ensureValidIterator(c);
@@ -864,8 +826,8 @@ void QTreeModel::sortItems(QList<QTreeWidgetItem*> *items, int column, Qt::SortO
return;
// store the original order of indexes
- QVector< QPair<QTreeWidgetItem*,int> > sorting(items->count());
- for (int i = 0; i < sorting.count(); ++i) {
+ QList<QPair<QTreeWidgetItem *, int>> sorting(items->size());
+ for (int i = 0; i < sorting.size(); ++i) {
sorting[i].first = items->at(i);
sorting[i].second = i;
}
@@ -877,7 +839,7 @@ void QTreeModel::sortItems(QList<QTreeWidgetItem*> *items, int column, Qt::SortO
QModelIndexList fromList;
QModelIndexList toList;
int colCount = columnCount();
- for (int r = 0; r < sorting.count(); ++r) {
+ for (int r = 0; r < sorting.size(); ++r) {
int oldRow = sorting.at(r).second;
if (oldRow == r)
continue;
@@ -1254,22 +1216,6 @@ bool QTreeWidgetItem::isFirstColumnSpanned() const
\sa font(), setText(), setForeground()
*/
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \fn QColor QTreeWidgetItem::backgroundColor(int column) const
- \obsolete
-
- This function is deprecated. Use background() instead.
-*/
-
-/*!
- \fn void QTreeWidgetItem::setBackgroundColor(int column, const QColor &color)
- \obsolete
-
- This function is deprecated. Use setBackground() instead.
-*/
-#endif
-
/*!
\fn QBrush QTreeWidgetItem::background(int column) const
\since 4.2
@@ -1294,21 +1240,6 @@ bool QTreeWidgetItem::isFirstColumnSpanned() const
\sa setForeground()
*/
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \fn QColor QTreeWidgetItem::textColor(int column) const
- \obsolete
-
- This function is deprecated. Use foreground() instead.
-*/
-
-/*!
- \fn void QTreeWidgetItem::setTextColor(int column, const QColor &color)
- \obsolete
-
- This function is deprecated. Use setForeground() instead.
-*/
-#endif
/*!
\fn QBrush QTreeWidgetItem::foreground(int column) const
@@ -1394,17 +1325,49 @@ bool QTreeWidgetItem::isFirstColumnSpanned() const
*/
/*!
+ \if defined(qt7)
+
+ \fn Qt::Alignment QTreeWidgetItem::textAlignment(int column) const
+
+ Returns the text alignment for the label in the given \a column.
+
+ \else
+
\fn int QTreeWidgetItem::textAlignment(int column) const
- Returns the text alignment for the label in the given \a column
- (see \l{Qt::AlignmentFlag}).
+ Returns the text alignment for the label in the given \a column.
+
+ \note This function returns an int for historical reasons. It will
+ be corrected to return Qt::Alignment in Qt 7.
+
+ \sa Qt::Alignment
+
+ \endif
*/
/*!
+ \obsolete [6.4] Use the overload that takes a Qt::Alignment argument.
+
\fn void QTreeWidgetItem::setTextAlignment(int column, int alignment)
Sets the text alignment for the label in the given \a column to
- the \a alignment specified (see \l{Qt::AlignmentFlag}).
+ the \a alignment specified.
+
+ \sa Qt::Alignment
+*/
+
+/*!
+ \since 6.4
+
+ \fn void QTreeWidgetItem::setTextAlignment(int column, Qt::Alignment alignment)
+
+ Sets the text alignment for the label in the given \a column to
+ the \a alignment specified.
+*/
+
+/*!
+ \fn void QTreeWidgetItem::setTextAlignment(int column, Qt::AlignmentFlag alignment)
+ \internal
*/
/*!
@@ -1419,16 +1382,7 @@ bool QTreeWidgetItem::isFirstColumnSpanned() const
\sa type()
*/
-QTreeWidgetItem::QTreeWidgetItem(int type)
- : rtti(type), view(nullptr), d(new QTreeWidgetItemPrivate(this)), par(nullptr),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
-}
-
+QTreeWidgetItem::QTreeWidgetItem(int type) : rtti(type), d(new QTreeWidgetItemPrivate(this)) { }
/*!
Constructs a tree widget item of the specified \a type. The item
@@ -1439,14 +1393,9 @@ QTreeWidgetItem::QTreeWidgetItem(int type)
\sa type()
*/
QTreeWidgetItem::QTreeWidgetItem(const QStringList &strings, int type)
- : rtti(type), view(nullptr), d(new QTreeWidgetItemPrivate(this)), par(nullptr),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- for (int i = 0; i < strings.count(); ++i)
+ : rtti(type), d(new QTreeWidgetItemPrivate(this))
+{
+ for (int i = 0; i < strings.size(); ++i)
setText(i, strings.at(i));
}
@@ -1460,12 +1409,7 @@ QTreeWidgetItem::QTreeWidgetItem(const QStringList &strings, int type)
*/
QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *treeview, int type)
- : rtti(type), view(nullptr), d(new QTreeWidgetItemPrivate(this)), par(nullptr),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
+ : rtti(type), d(new QTreeWidgetItemPrivate(this))
{
// do not set this->view here otherwise insertChild() will fail
if (QTreeModel *model = treeModel(treeview)) {
@@ -1485,14 +1429,9 @@ QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *treeview, int type)
*/
QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *treeview, const QStringList &strings, int type)
- : rtti(type), view(nullptr), d(new QTreeWidgetItemPrivate(this)), par(nullptr),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- for (int i = 0; i < strings.count(); ++i)
+ : rtti(type), d(new QTreeWidgetItemPrivate(this))
+{
+ for (int i = 0; i < strings.size(); ++i)
setText(i, strings.at(i));
// do not set this->view here otherwise insertChild() will fail
if (QTreeModel *model = treeModel(treeview)) {
@@ -1510,12 +1449,7 @@ QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *treeview, const QStringList &strin
\sa type()
*/
QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *treeview, QTreeWidgetItem *after, int type)
- : rtti(type), view(nullptr), d(new QTreeWidgetItemPrivate(this)), par(nullptr),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
+ : rtti(type), d(new QTreeWidgetItemPrivate(this))
{
// do not set this->view here otherwise insertChild() will fail
if (QTreeModel *model = treeModel(treeview)) {
@@ -1531,12 +1465,7 @@ QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *treeview, QTreeWidgetItem *after,
\sa type()
*/
QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, int type)
- : rtti(type), view(nullptr), d(new QTreeWidgetItemPrivate(this)), par(nullptr),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
+ : rtti(type), d(new QTreeWidgetItemPrivate(this))
{
if (parent)
parent->addChild(this);
@@ -1549,14 +1478,9 @@ QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, int type)
\sa type()
*/
QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, const QStringList &strings, int type)
- : rtti(type), view(nullptr), d(new QTreeWidgetItemPrivate(this)), par(nullptr),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- for (int i = 0; i < strings.count(); ++i)
+ : rtti(type), d(new QTreeWidgetItemPrivate(this))
+{
+ for (int i = 0; i < strings.size(); ++i)
setText(i, strings.at(i));
if (parent)
parent->addChild(this);
@@ -1571,12 +1495,7 @@ QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, const QStringList &str
\sa type()
*/
QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, QTreeWidgetItem *after, int type)
- : rtti(type), view(nullptr), d(new QTreeWidgetItemPrivate(this)), par(nullptr),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
+ : rtti(type), d(new QTreeWidgetItemPrivate(this))
{
if (parent) {
int i = parent->children.indexOf(after) + 1;
@@ -1595,11 +1514,8 @@ QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, QTreeWidgetItem *after
QTreeWidgetItem::~QTreeWidgetItem()
{
QTreeModel *model = treeModel();
- bool wasSkipSort = false;
- if (model) {
- wasSkipSort = model->skipPendingSort;
- model->skipPendingSort = true;
- }
+ QTreeModel::SkipSorting skipSorting(model);
+
if (par) {
int i = par->children.indexOf(this);
if (i >= 0) {
@@ -1627,7 +1543,7 @@ QTreeWidgetItem::~QTreeWidgetItem()
}
// at this point the persistent indexes for the children should also be invalidated
// since we invalidated the parent
- for (int i = 0; i < children.count(); ++i) {
+ for (int i = 0; i < children.size(); ++i) {
QTreeWidgetItem *child = children.at(i);
// make sure the child does not try to remove itself from our children list
child->par = nullptr;
@@ -1638,9 +1554,6 @@ QTreeWidgetItem::~QTreeWidgetItem()
children.clear();
delete d;
- if (model) {
- model->skipPendingSort = wasSkipSort;
- }
}
/*!
@@ -1685,7 +1598,7 @@ QTreeWidgetItem *QTreeWidgetItem::clone() const
/*!
Sets the item indicator \a policy. This policy decides when the
tree branch expand/collapse indicator is shown.
- The default value is ShowForChildren.
+ The default value is DontShowIndicatorWhenChildless.
\sa childIndicatorPolicy()
*/
@@ -1738,7 +1651,7 @@ void QTreeWidgetItem::setFlags(Qt::ItemFlags flags)
parents.push(this);
while (!parents.isEmpty()) {
QTreeWidgetItem *parent = parents.pop();
- for (int i = 0; i < parent->children.count(); ++i) {
+ for (int i = 0; i < parent->children.size(); ++i) {
QTreeWidgetItem *child = parent->children.at(i);
if (!child->d->disabled) { // if not explicitly disabled
parents.push(child);
@@ -1767,7 +1680,7 @@ void QTreeWidgetItemPrivate::updateHiddenStatus(QTreeWidgetItem *item, bool inse
const QModelIndex index = model->index(parent, 0);
item->view->setRowHidden(index.row(), index.parent(), inserting);
}
- for (int i = 0; i < parent->children.count(); ++i) {
+ for (int i = 0; i < parent->children.size(); ++i) {
QTreeWidgetItem *child = parent->children.at(i);
parents.push(child);
}
@@ -1793,7 +1706,7 @@ void QTreeWidgetItemPrivate::propagateDisabled(QTreeWidgetItem *item)
parent->itemChanged();
}
- for (int i = 0; i < parent->children.count(); ++i) {
+ for (int i = 0; i < parent->children.size(); ++i) {
QTreeWidgetItem *child = parent->children.at(i);
parents.push(child);
}
@@ -1835,14 +1748,14 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
switch (role) {
case Qt::EditRole:
case Qt::DisplayRole: {
- if (values.count() <= column) {
+ if (values.size() <= column) {
if (model && this == model->headerItem)
model->setColumnCount(column + 1);
else
values.resize(column + 1);
}
- if (d->display.count() <= column) {
- for (int i = d->display.count() - 1; i < column - 1; ++i)
+ if (d->display.size() <= column) {
+ for (int i = d->display.size() - 1; i < column - 1; ++i)
d->display.append(QVariant());
d->display.append(value);
} else if (d->display[column] != value) {
@@ -1853,7 +1766,7 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
} break;
case Qt::CheckStateRole:
if ((itemFlags & Qt::ItemIsAutoTristate) && value != Qt::PartiallyChecked) {
- for (int i = 0; i < children.count(); ++i) {
+ for (int i = 0; i < children.size(); ++i) {
QTreeWidgetItem *child = children.at(i);
if (child->data(column, role).isValid()) {// has a CheckState
Qt::ItemFlags f = itemFlags; // a little hack to avoid multiple dataChanged signals
@@ -1865,10 +1778,10 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
}
Q_FALLTHROUGH();
default:
- if (column < values.count()) {
+ if (column < values.size()) {
bool found = false;
- const QVector<QWidgetItemData> column_values = values.at(column);
- for (int i = 0; i < column_values.count(); ++i) {
+ const QList<QWidgetItemData> column_values = values.at(column);
+ for (int i = 0; i < column_values.size(); ++i) {
if (column_values.at(i).role == role) {
if (column_values.at(i).value == value)
return; // value is unchanged
@@ -1889,9 +1802,9 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
}
if (model) {
- const QVector<int> roles((role == Qt::DisplayRole || role == Qt::EditRole) ?
- QVector<int>({Qt::DisplayRole, Qt::EditRole}) :
- QVector<int>({role}));
+ const QList<int> roles((role == Qt::DisplayRole || role == Qt::EditRole)
+ ? QList<int>({ Qt::DisplayRole, Qt::EditRole })
+ : QList<int>({ role }));
model->emitDataChanged(this, column, roles);
if (role == Qt::CheckStateRole) {
QTreeWidgetItem *p;
@@ -1909,17 +1822,17 @@ QVariant QTreeWidgetItem::data(int column, int role) const
switch (role) {
case Qt::EditRole:
case Qt::DisplayRole:
- if (column >= 0 && column < d->display.count())
+ if (column >= 0 && column < d->display.size())
return d->display.at(column);
break;
case Qt::CheckStateRole:
// special case for check state in tristate
- if (children.count() && (itemFlags & Qt::ItemIsAutoTristate))
+ if (children.size() && (itemFlags & Qt::ItemIsAutoTristate))
return childrenCheckState(column);
Q_FALLTHROUGH();
default:
if (column >= 0 && column < values.size()) {
- const QVector<QWidgetItemData> &column_values = values.at(column);
+ const QList<QWidgetItemData> &column_values = values.at(column);
for (const auto &column_value : column_values) {
if (column_value.role == role)
return column_value.value;
@@ -1956,9 +1869,9 @@ void QTreeWidgetItem::read(QDataStream &in)
d->display.clear();
in >> values;
// move the display value over to the display string list
- for (int column = 0; column < values.count(); ++column) {
+ for (int column = 0; column < values.size(); ++column) {
d->display << QVariant();
- for (int i = 0; i < values.at(column).count(); ++i) {
+ for (int i = 0; i < values.at(column).size(); ++i) {
if (values.at(column).at(i).role == Qt::DisplayRole) {
d->display[column] = values.at(column).at(i).value;
values[column].remove(i--);
@@ -1992,8 +1905,9 @@ void QTreeWidgetItem::write(QDataStream &out) const
\sa data(), flags()
*/
QTreeWidgetItem::QTreeWidgetItem(const QTreeWidgetItem &other)
- : rtti(Type), values(other.values), view(nullptr),
- d(new QTreeWidgetItemPrivate(this)), par(nullptr),
+ : rtti(Type),
+ values(other.values),
+ d(new QTreeWidgetItemPrivate(this)),
itemFlags(other.itemFlags)
{
d->display = other.d->display;
@@ -2024,8 +1938,8 @@ QTreeWidgetItem &QTreeWidgetItem::operator=(const QTreeWidgetItem &other)
void QTreeWidgetItem::addChild(QTreeWidgetItem *child)
{
if (child) {
- insertChild(children.count(), child);
- child->d->rowGuess = children.count() - 1;
+ insertChild(children.size(), child);
+ child->d->rowGuess = children.size() - 1;
}
}
@@ -2036,12 +1950,11 @@ void QTreeWidgetItem::addChild(QTreeWidgetItem *child)
*/
void QTreeWidgetItem::insertChild(int index, QTreeWidgetItem *child)
{
- if (index < 0 || index > children.count() || child == nullptr || child->view != nullptr || child->par != nullptr)
+ if (index < 0 || index > children.size() || child == nullptr || child->view != nullptr || child->par != nullptr)
return;
if (QTreeModel *model = treeModel()) {
- const bool wasSkipSort = model->skipPendingSort;
- model->skipPendingSort = true;
+ QTreeModel::SkipSorting skipSorting(model);
if (model->rootItem == this)
child->par = nullptr;
else
@@ -2059,13 +1972,12 @@ void QTreeWidgetItem::insertChild(int index, QTreeWidgetItem *child)
QTreeWidgetItem *i = stack.pop();
i->view = view;
i->values.reserve(cols);
- for (int c = 0; c < i->children.count(); ++c)
+ for (int c = 0; c < i->children.size(); ++c)
stack.push(i->children.at(c));
}
children.insert(index, child);
d->updateHiddenStatus(child, true);
model->endInsertItems();
- model->skipPendingSort = wasSkipSort;
} else {
child->par = this;
children.insert(index, child);
@@ -2099,7 +2011,7 @@ QTreeWidgetItem *QTreeWidgetItem::takeChild(int index)
model->skipPendingSort = false;
model->executePendingSort();
}
- if (index >= 0 && index < children.count()) {
+ if (index >= 0 && index < children.size()) {
if (model) model->beginRemoveItems(this, index, 1);
d->updateHiddenStatus(children.at(index), false);
QTreeWidgetItem *item = children.takeAt(index);
@@ -2109,7 +2021,7 @@ QTreeWidgetItem *QTreeWidgetItem::takeChild(int index)
while (!stack.isEmpty()) {
QTreeWidgetItem *i = stack.pop();
i->view = nullptr;
- for (int c = 0; c < i->children.count(); ++c)
+ for (int c = 0; c < i->children.size(); ++c)
stack.push(i->children.at(c));
}
d->propagateDisabled(item);
@@ -2128,7 +2040,7 @@ QTreeWidgetItem *QTreeWidgetItem::takeChild(int index)
*/
void QTreeWidgetItem::addChildren(const QList<QTreeWidgetItem*> &children)
{
- insertChildren(this->children.count(), children);
+ insertChildren(this->children.size(), children);
}
/*!
@@ -2140,18 +2052,18 @@ void QTreeWidgetItem::addChildren(const QList<QTreeWidgetItem*> &children)
*/
void QTreeWidgetItem::insertChildren(int index, const QList<QTreeWidgetItem*> &children)
{
- if (index < 0 || index > this->children.count() || children.isEmpty())
+ if (index < 0 || index > this->children.size() || children.isEmpty())
return;
if (view && view->isSortingEnabled()) {
- for (int n = 0; n < children.count(); ++n)
+ for (int n = 0; n < children.size(); ++n)
insertChild(index, children.at(n));
return;
}
QTreeModel *model = treeModel();
QStack<QTreeWidgetItem*> stack;
QList<QTreeWidgetItem*> itemsToInsert;
- for (int n = 0; n < children.count(); ++n) {
+ for (int n = 0; n < children.size(); ++n) {
QTreeWidgetItem *child = children.at(n);
if (child->view || child->par)
continue;
@@ -2171,11 +2083,11 @@ void QTreeWidgetItem::insertChildren(int index, const QList<QTreeWidgetItem*> &c
while (!stack.isEmpty()) {
QTreeWidgetItem *i = stack.pop();
i->view = view;
- for (int c = 0; c < i->children.count(); ++c)
+ for (int c = 0; c < i->children.size(); ++c)
stack.push(i->children.at(c));
}
- if (model) model->beginInsertItems(this, index, itemsToInsert.count());
- for (int n = 0; n < itemsToInsert.count(); ++n) {
+ if (model) model->beginInsertItems(this, index, itemsToInsert.size());
+ for (int n = 0; n < itemsToInsert.size(); ++n) {
QTreeWidgetItem *child = itemsToInsert.at(n);
this->children.insert(index + n, child);
if (child->par)
@@ -2194,7 +2106,7 @@ void QTreeWidgetItem::insertChildren(int index, const QList<QTreeWidgetItem*> &c
QList<QTreeWidgetItem*> QTreeWidgetItem::takeChildren()
{
QList<QTreeWidgetItem*> removed;
- if (children.count() > 0) {
+ if (children.size() > 0) {
QTreeModel *model = treeModel();
if (model) {
// This will trigger a layoutChanged signal, thus we might want to optimize
@@ -2203,8 +2115,8 @@ QList<QTreeWidgetItem*> QTreeWidgetItem::takeChildren()
// is updated in case we take an item that is selected.
model->executePendingSort();
}
- if (model) model->beginRemoveItems(this, 0, children.count());
- for (int n = 0; n < children.count(); ++n) {
+ if (model) model->beginRemoveItems(this, 0, children.size());
+ for (int n = 0; n < children.size(); ++n) {
QTreeWidgetItem *item = children.at(n);
item->par = nullptr;
QStack<QTreeWidgetItem*> stack;
@@ -2212,7 +2124,7 @@ QList<QTreeWidgetItem*> QTreeWidgetItem::takeChildren()
while (!stack.isEmpty()) {
QTreeWidgetItem *i = stack.pop();
i->view = nullptr;
- for (int c = 0; c < i->children.count(); ++c)
+ for (int c = 0; c < i->children.size(); ++c)
stack.push(i->children.at(c));
}
d->propagateDisabled(item);
@@ -2388,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);
@@ -2426,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);
@@ -2447,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();
@@ -2456,19 +2374,19 @@ 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();
int i;
QTreeModel *m = treeModel();
- for (i = 0; i < indices.count(); ++i) {
+ for (i = 0; i < indices.size(); ++i) {
QTreeWidgetItem *item = m->item(indices.at(i));
item->d->selected = true;
}
indices = deselected.indexes();
- for (i = 0; i < indices.count(); ++i) {
+ for (i = 0; i < indices.size(); ++i) {
QTreeWidgetItem *item = m->item(indices.at(i));
item->d->selected = false;
}
@@ -2476,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()) {
@@ -2535,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}
*/
/*!
@@ -2596,9 +2514,6 @@ void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
This signal is emitted when the specified \a item is expanded so that
all of its children are displayed.
- \note This signal will not be emitted if an item changes its state when
- expandAll() is invoked.
-
\sa QTreeWidgetItem::isExpanded(), itemCollapsed(), expandItem()
*/
@@ -2660,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);
}
@@ -2694,10 +2612,12 @@ QTreeWidget::QTreeWidget(QWidget *parent)
QTreeWidget::~QTreeWidget()
{
+ Q_D(QTreeWidget);
+ d->clearConnections();
}
/*
- Retuns the number of header columns in the view.
+ Returns the number of header columns in the view.
\sa sortColumn(), currentColumn(), topLevelItemCount()
*/
@@ -2896,10 +2816,10 @@ void QTreeWidget::setHeaderItem(QTreeWidgetItem *item)
void QTreeWidget::setHeaderLabels(const QStringList &labels)
{
Q_D(QTreeWidget);
- if (columnCount() < labels.count())
- setColumnCount(labels.count());
+ if (columnCount() < labels.size())
+ setColumnCount(labels.size());
QTreeWidgetItem *item = d->treeModel()->headerItem;
- for (int i = 0; i < labels.count(); ++i)
+ for (int i = 0; i < labels.size(); ++i)
item->setText(i, labels.at(i));
}
@@ -3132,38 +3052,6 @@ void QTreeWidget::setItemWidget(QTreeWidgetItem *item, int column, QWidget *widg
QAbstractItemView::setIndexWidget(d->index(item, column), widget);
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- Returns \c true if the \a item is selected; otherwise returns \c false.
-
- \sa itemSelectionChanged()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::isSelected()} instead.
-*/
-bool QTreeWidget::isItemSelected(const QTreeWidgetItem *item) const
-{
- return ((item && item->treeWidget() == this) ? item->isSelected() : false);
-}
-
-/*!
- If \a select is true, the given \a item is selected; otherwise it is
- deselected.
-
- \sa itemSelectionChanged()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::setSelected()} instead.
-*/
-void QTreeWidget::setItemSelected(const QTreeWidgetItem *item, bool select)
-{
- if (item && item->treeWidget() == this)
- const_cast<QTreeWidgetItem*>(item)->setSelected(select);
-}
-#endif
-
/*!
Returns a list of all selected non-hidden items.
@@ -3174,14 +3062,12 @@ QList<QTreeWidgetItem*> QTreeWidget::selectedItems() const
Q_D(const QTreeWidget);
const QModelIndexList indexes = selectionModel()->selectedIndexes();
QList<QTreeWidgetItem*> items;
- items.reserve(indexes.count());
- QSet<QTreeWidgetItem *> seen;
- seen.reserve(indexes.count());
+ items.reserve(indexes.size());
+ QDuplicateTracker<QTreeWidgetItem *> seen(indexes.size());
for (const auto &index : indexes) {
QTreeWidgetItem *item = d->item(index);
- if (item->isHidden() || seen.contains(item))
+ if (item->isHidden() || seen.hasSeen(item))
continue;
- seen.insert(item);
items.append(item);
}
return items;
@@ -3203,99 +3089,6 @@ QList<QTreeWidgetItem*> QTreeWidget::findItems(const QString &text, Qt::MatchFla
return items;
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- Returns \c true if the \a item is explicitly hidden, otherwise returns \c false.
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::isHidden()} instead.
-*/
-bool QTreeWidget::isItemHidden(const QTreeWidgetItem *item) const
-{
- return ((item && item->treeWidget() == this) ? item->isHidden() : false);
-}
-
-/*!
- Hides the given \a item if \a hide is true; otherwise shows the item.
-
- \sa itemChanged()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::setHidden()} instead.
-*/
-void QTreeWidget::setItemHidden(const QTreeWidgetItem *item, bool hide)
-{
- if (item && item->treeWidget() == this)
- const_cast<QTreeWidgetItem*>(item)->setHidden(hide);
-}
-
-/*!
- Returns \c true if the given \a item is open; otherwise returns \c false.
-
- \sa itemExpanded()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::isExpanded()} instead.
-*/
-bool QTreeWidget::isItemExpanded(const QTreeWidgetItem *item) const
-{
- return ((item && item->treeWidget() == this) ? item->isExpanded() : false);
-}
-
-/*!
- Sets the item referred to by \a item to either closed or opened,
- depending on the value of \a expand.
-
- \sa expandItem(), collapseItem(), itemExpanded()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::setExpanded()} instead.
-*/
-void QTreeWidget::setItemExpanded(const QTreeWidgetItem *item, bool expand)
-{
- if (item && item->treeWidget() == this)
- const_cast<QTreeWidgetItem*>(item)->setExpanded(expand);
-}
-
-/*!
- \since 4.3
-
- Returns \c true if the given \a item is set to show only one section over all columns;
- otherwise returns \c false.
-
- \sa setFirstItemColumnSpanned()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::isFirstColumnSpanned()} instead.
-*/
-bool QTreeWidget::isFirstItemColumnSpanned(const QTreeWidgetItem *item) const
-{
- return ((item && item->treeWidget() == this) ? item->isFirstColumnSpanned() : false);
-}
-
-/*!
- \since 4.3
-
- Sets the given \a item to only show one section for all columns if \a span is true;
- otherwise the item will show one section per column.
-
- \sa isFirstItemColumnSpanned()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::setFirstColumnSpanned()} instead.
-*/
-void QTreeWidget::setFirstItemColumnSpanned(const QTreeWidgetItem *item, bool span)
-{
- if (item && item->treeWidget() == this)
- const_cast<QTreeWidgetItem*>(item)->setFirstColumnSpanned(span);
-}
-#endif
/*!
\since 4.3
@@ -3336,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());
}
/*!
@@ -3412,11 +3205,7 @@ QStringList QTreeWidget::mimeTypes() const
If the list of items is empty, \nullptr is returned rather than a
serialized empty list.
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
QMimeData *QTreeWidget::mimeData(const QList<QTreeWidgetItem *> &items) const
-#else
-QMimeData *QTreeWidget::mimeData(const QList<QTreeWidgetItem*> items) const
-#endif
{
Q_D(const QTreeWidget);
if (d->treeModel()->cachedIndexes.isEmpty()) {
@@ -3427,7 +3216,7 @@ QMimeData *QTreeWidget::mimeData(const QList<QTreeWidgetItem*> items) const
return nullptr;
}
- for (int c = 0; c < item->values.count(); ++c) {
+ for (int c = 0; c < item->values.size(); ++c) {
const QModelIndex index = indexFromItem(item, c);
if (Q_UNLIKELY(!index.isValid())) {
qWarning() << "QTreeWidget::mimeData: No index associated with item :" << item;
@@ -3470,18 +3259,6 @@ Qt::DropActions QTreeWidget::supportedDropActions() const
}
/*!
- \obsolete
- Returns an empty list
-
- \sa mimeData()
-*/
-QList<QTreeWidgetItem*> QTreeWidget::items(const QMimeData *data) const
-{
- Q_UNUSED(data);
- return QList<QTreeWidgetItem*>();
-}
-
-/*!
Returns the QModelIndex associated with the given \a item in the given \a column.
\note In Qt versions prior to 5.7, this function took a non-\c{const} \a item.
@@ -3494,17 +3271,6 @@ QModelIndex QTreeWidget::indexFromItem(const QTreeWidgetItem *item, int column)
return d->index(item, column);
}
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-/*!
- \overload
- \internal
-*/
-QModelIndex QTreeWidget::indexFromItem(QTreeWidgetItem *item, int column) const
-{
- return indexFromItem(const_cast<const QTreeWidgetItem *>(item), column);
-}
-#endif
-
/*!
Returns a pointer to the QTreeWidgetItem associated with the given \a index.
@@ -3525,10 +3291,11 @@ void QTreeWidget::dropEvent(QDropEvent *event) {
QModelIndex topIndex;
int col = -1;
int row = -1;
- if (d->dropOn(event, &row, &col, &topIndex)) {
+ // check whether a subclass has already accepted the event, ie. moved the data
+ if (!event->isAccepted() && d->dropOn(event, &row, &col, &topIndex)) {
const QList<QModelIndex> idxs = selectedIndexes();
QList<QPersistentModelIndex> indexes;
- const int indexesCount = idxs.count();
+ const int indexesCount = idxs.size();
indexes.reserve(indexesCount);
for (const auto &idx : idxs)
indexes.append(idx);
@@ -3551,7 +3318,7 @@ void QTreeWidget::dropEvent(QDropEvent *event) {
}
// insert them back in at their new positions
- for (int i = 0; i < indexes.count(); ++i) {
+ for (int i = 0; i < indexes.size(); ++i) {
// Either at a specific point or appended
if (row == -1) {
if (topIndex.isValid()) {
@@ -3572,9 +3339,11 @@ void QTreeWidget::dropEvent(QDropEvent *event) {
}
event->accept();
- // Don't want QAbstractItemView to delete it because it was "moved" we already did it
- event->setDropAction(Qt::CopyAction);
}
+ // either we or a subclass accepted the move event, so assume that the data was
+ // moved and that QAbstractItemView shouldn't remove the source when QDrag::exec returns
+ if (event->isAccepted())
+ d->dropEventMoved = true;
}
QTreeView::dropEvent(event);
@@ -3601,6 +3370,14 @@ bool QTreeWidget::event(QEvent *e)
return QTreeView::event(e);
}
+/*!
+ see QTBUG-94546
+*/
+void QTreeModelPrivate::executePendingOperations() const
+{
+ q_func()->executePendingSort();
+}
+
QT_END_NAMESPACE
#include "moc_qtreewidget.cpp"
diff --git a/src/widgets/itemviews/qtreewidget.h b/src/widgets/itemviews/qtreewidget.h
index b9543fb954..992f6cdb1c 100644
--- a/src/widgets/itemviews/qtreewidget.h
+++ b/src/widgets/itemviews/qtreewidget.h
@@ -1,50 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTREEWIDGET_H
#define QTREEWIDGET_H
-#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qtreeview.h>
#include <QtWidgets/qtreewidgetitemiterator.h>
+#include <QtWidgets/qtwidgetsglobal.h>
+#include <QtCore/qlist.h>
#include <QtCore/qvariant.h>
-#include <QtCore/qvector.h>
QT_REQUIRE_CONFIG(treewidget);
@@ -113,7 +77,7 @@ public:
{ return data(column, Qt::StatusTipRole).toString(); }
inline void setStatusTip(int column, const QString &statusTip);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
inline QString toolTip(int column) const
{ return data(column, Qt::ToolTipRole).toString(); }
inline void setToolTip(int column, const QString &toolTip);
@@ -129,41 +93,35 @@ public:
{ return qvariant_cast<QFont>(data(column, Qt::FontRole)); }
inline void setFont(int column, const QFont &font);
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
inline int textAlignment(int column) const
{ return data(column, Qt::TextAlignmentRole).toInt(); }
+#else
+ inline Qt::Alignment textAlignment(int column) const
+ { return qvariant_cast<Qt::Alignment>(data(column, Qt::TextAlignmentRole)); }
+#endif
+#if QT_DEPRECATED_SINCE(6, 4)
+ QT_DEPRECATED_VERSION_X_6_4("Use the overload taking Qt::Alignment")
inline void setTextAlignment(int column, int alignment)
{ setData(column, Qt::TextAlignmentRole, alignment); }
-
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTreeWidgetItem::background() instead")
- inline QColor backgroundColor(int column) const
- { return qvariant_cast<QColor>(data(column, Qt::BackgroundRole)); }
- QT_DEPRECATED_X ("Use QTreeWidgetItem::setBackground() instead")
- inline void setBackgroundColor(int column, const QColor &color)
- { setData(column, Qt::BackgroundRole, color); }
+ inline void setTextAlignment(int column, Qt::AlignmentFlag alignment)
+ { setData(column, Qt::TextAlignmentRole, QVariant::fromValue(Qt::Alignment(alignment))); }
#endif
+ inline void setTextAlignment(int column, Qt::Alignment alignment)
+ { setData(column, Qt::TextAlignmentRole, QVariant::fromValue(alignment)); }
inline QBrush background(int column) const
{ return qvariant_cast<QBrush>(data(column, Qt::BackgroundRole)); }
inline void setBackground(int column, const QBrush &brush)
{ setData(column, Qt::BackgroundRole, brush.style() != Qt::NoBrush ? QVariant(brush) : QVariant()); }
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTreeWidgetItem::foreground() instead")
- inline QColor textColor(int column) const
- { return qvariant_cast<QColor>(data(column, Qt::ForegroundRole)); }
- QT_DEPRECATED_X ("Use QTreeWidgetItem::setForeground() instead")
- inline void setTextColor(int column, const QColor &color)
- { setData(column, Qt::ForegroundRole, color); }
-#endif
-
inline QBrush foreground(int column) const
{ return qvariant_cast<QBrush>(data(column, Qt::ForegroundRole)); }
inline void setForeground(int column, const QBrush &brush)
{ setData(column, Qt::ForegroundRole, brush.style() != Qt::NoBrush ? QVariant(brush) : QVariant()); }
inline Qt::CheckState checkState(int column) const
- { return static_cast<Qt::CheckState>(data(column, Qt::CheckStateRole).toInt()); }
+ { return qvariant_cast<Qt::CheckState>(data(column, Qt::CheckStateRole)); }
inline void setCheckState(int column, Qt::CheckState state)
{ setData(column, Qt::CheckStateRole, state); }
@@ -190,8 +148,8 @@ public:
executePendingSort();
return children.at(index);
}
- inline int childCount() const { return children.count(); }
- inline int columnCount() const { return values.count(); }
+ inline int childCount() const { return int(children.size()); }
+ inline int columnCount() const { return int(values.size()); }
inline int indexOfChild(QTreeWidgetItem *child) const;
void addChild(QTreeWidgetItem *child);
@@ -219,12 +177,15 @@ private:
int rtti;
// One item has a vector of column entries. Each column has a vector of (role, value) pairs.
- QVector< QVector<QWidgetItemData> > values;
- QTreeWidget *view;
+ QList<QList<QWidgetItemData>> values;
+ QTreeWidget *view = nullptr;
QTreeWidgetItemPrivate *d;
- QTreeWidgetItem *par;
+ QTreeWidgetItem *par = nullptr;
+ // ### Qt7: Move children to d-pointer and replace QList by a suitable data structure.
+ // to fix QTBUG-94546
QList<QTreeWidgetItem*> children;
- Qt::ItemFlags itemFlags;
+ Qt::ItemFlags itemFlags = Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled
+ | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
};
inline void QTreeWidgetItem::setText(int column, const QString &atext)
@@ -238,7 +199,7 @@ inline void QTreeWidgetItem::setStatusTip(int column, const QString &astatusTip)
{ setData(column, Qt::StatusTipRole, astatusTip); }
#endif
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
inline void QTreeWidgetItem::setToolTip(int column, const QString &atoolTip)
{ setData(column, Qt::ToolTipRole, atoolTip); }
#endif
@@ -252,7 +213,7 @@ inline void QTreeWidgetItem::setFont(int column, const QFont &afont)
{ setData(column, Qt::FontRole, afont); }
inline int QTreeWidgetItem::indexOfChild(QTreeWidgetItem *achild) const
-{ executePendingSort(); return children.indexOf(achild); }
+{ executePendingSort(); return int(children.indexOf(achild)); }
#ifndef QT_NO_DATASTREAM
Q_WIDGETS_EXPORT QDataStream &operator<<(QDataStream &out, const QTreeWidgetItem &item);
@@ -315,36 +276,16 @@ public:
void setItemWidget(QTreeWidgetItem *item, int column, QWidget *widget);
inline void removeItemWidget(QTreeWidgetItem *item, int column);
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTreeWidgetItem::isSelected() instead")
- bool isItemSelected(const QTreeWidgetItem *item) const;
- QT_DEPRECATED_X ("Use QTreeWidgetItem::setSelected() instead")
- void setItemSelected(const QTreeWidgetItem *item, bool select);
-#endif
QList<QTreeWidgetItem*> selectedItems() const;
QList<QTreeWidgetItem*> findItems(const QString &text, Qt::MatchFlags flags,
int column = 0) const;
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTreeWidgetItem::isHidden() instead")
- bool isItemHidden(const QTreeWidgetItem *item) const;
- QT_DEPRECATED_X ("Use QTreeWidgetItem::setHidden() instead")
- void setItemHidden(const QTreeWidgetItem *item, bool hide);
-
- QT_DEPRECATED_X ("Use QTreeWidgetItem::isExpanded() instead")
- bool isItemExpanded(const QTreeWidgetItem *item) const;
- QT_DEPRECATED_X ("Use QTreeWidgetItem::setExpanded() instead")
- void setItemExpanded(const QTreeWidgetItem *item, bool expand);
-
- QT_DEPRECATED_X ("Use QTreeWidgetItem::isFirstColumnSpanned() instead")
- bool isFirstItemColumnSpanned(const QTreeWidgetItem *item) const;
- QT_DEPRECATED_X ("Use QTreeWidgetItem::setFirstColumnSpanned() instead")
- void setFirstItemColumnSpanned(const QTreeWidgetItem *item, bool span);
-#endif
-
QTreeWidgetItem *itemAbove(const QTreeWidgetItem *item) const;
QTreeWidgetItem *itemBelow(const QTreeWidgetItem *item) const;
+ QModelIndex indexFromItem(const QTreeWidgetItem *item, int column = 0) const;
+ QTreeWidgetItem *itemFromIndex(const QModelIndex &index) const;
+
void setSelectionModel(QItemSelectionModel *selectionModel) override;
public Q_SLOTS:
@@ -360,7 +301,6 @@ Q_SIGNALS:
void itemDoubleClicked(QTreeWidgetItem *item, int column);
void itemActivated(QTreeWidgetItem *item, int column);
void itemEntered(QTreeWidgetItem *item, int column);
- // ### Qt 6: add changed roles
void itemChanged(QTreeWidgetItem *item, int column);
void itemExpanded(QTreeWidgetItem *item);
void itemCollapsed(QTreeWidgetItem *item);
@@ -370,29 +310,11 @@ Q_SIGNALS:
protected:
bool event(QEvent *e) override;
virtual QStringList mimeTypes() const;
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
virtual QMimeData *mimeData(const QList<QTreeWidgetItem *> &items) const;
-#else
- virtual QMimeData *mimeData(const QList<QTreeWidgetItem*> items) const;
-#endif
virtual bool dropMimeData(QTreeWidgetItem *parent, int index,
const QMimeData *data, Qt::DropAction action);
virtual Qt::DropActions supportedDropActions() const;
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
-public:
-#else
-protected:
-#endif
- QList<QTreeWidgetItem*> items(const QMimeData *data) const;
-
- QModelIndex indexFromItem(const QTreeWidgetItem *item, int column = 0) const;
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
- QModelIndex indexFromItem(QTreeWidgetItem *item, int column = 0) const; // ### Qt 6: remove
-#endif
- QTreeWidgetItem *itemFromIndex(const QModelIndex &index) const;
-
-protected:
#if QT_CONFIG(draganddrop)
void dropEvent(QDropEvent *event) override;
#endif
@@ -401,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 81e7e86203..53fdea3ca8 100644
--- a/src/widgets/itemviews/qtreewidget_p.h
+++ b/src/widgets/itemviews/qtreewidget_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTREEWIDGET_P_H
#define QTREEWIDGET_P_H
@@ -59,6 +23,8 @@
#include <private/qtreeview_p.h>
#include <QtWidgets/qheaderview.h>
+#include <array>
+
QT_REQUIRE_CONFIG(treewidget);
QT_BEGIN_NAMESPACE
@@ -99,9 +65,7 @@ public:
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role) override;
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool clearItemData(const QModelIndex &index) override;
-#endif
QMap<int, QVariant> itemData(const QModelIndex &index) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
@@ -141,7 +105,7 @@ public:
protected:
QTreeModel(QTreeModelPrivate &, QTreeWidget *parent = nullptr);
- void emitDataChanged(QTreeWidgetItem *item, int column, const QVector<int> &roles);
+ void emitDataChanged(QTreeWidgetItem *item, int column, const QList<int> &roles);
void beginInsertItems(QTreeWidgetItem *parent, int row, int count);
void endInsertItems();
void beginRemoveItems(QTreeWidgetItem *parent, int row, int count);
@@ -157,7 +121,7 @@ private:
QList<QTreeWidgetItemIterator*> iterators;
mutable QBasicTimer sortPendingTimer;
- mutable bool skipPendingSort; //while doing internal operation we don't care about sorting
+ mutable bool skipPendingSort = false; // no sorting during internal operations
bool inline executePendingSort() const;
bool isChanging() const;
@@ -169,9 +133,9 @@ public:
{
const QTreeModel * const model;
const bool previous;
- SkipSorting(const QTreeModel *m) : model(m), previous(model->skipPendingSort)
- { model->skipPendingSort = true; }
- ~SkipSorting() { model->skipPendingSort = previous; }
+ SkipSorting(const QTreeModel *m) : model(m), previous(model ? model->skipPendingSort : false)
+ { if (model) model->skipPendingSort = true; }
+ ~SkipSorting() { if (model) model->skipPendingSort = previous; }
};
friend struct SkipSorting;
};
@@ -183,6 +147,7 @@ QT_END_INCLUDE_NAMESPACE
class QTreeModelPrivate : public QAbstractItemModelPrivate
{
Q_DECLARE_PUBLIC(QTreeModel)
+ void executePendingOperations() const override;
};
class QTreeWidgetItemPrivate
@@ -223,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/qtreewidgetitemiterator.cpp b/src/widgets/itemviews/qtreewidgetitemiterator.cpp
index a24106d90e..1dd677e209 100644
--- a/src/widgets/itemviews/qtreewidgetitemiterator.cpp
+++ b/src/widgets/itemviews/qtreewidgetitemiterator.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <private/qtreewidgetitemiterator_p.h>
#include "qtreewidget.h"
@@ -168,7 +132,7 @@ QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator=(const QTreeWidgetIte
}
/*!
- The prefix ++ operator (++it) advances the iterator to the next matching item
+ The prefix \c{++} operator (\c{++it}) advances the iterator to the next matching item
and returns a reference to the resulting iterator.
Sets the current pointer to \nullptr if the current item is the last matching item.
*/
@@ -183,7 +147,7 @@ QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator++()
}
/*!
- The prefix -- operator (--it) advances the iterator to the previous matching item
+ The prefix \c{--} operator (\c{--it}) advances the iterator to the previous matching item
and returns a reference to the resulting iterator.
Sets the current pointer to \nullptr if the current item is the first matching item.
*/
diff --git a/src/widgets/itemviews/qtreewidgetitemiterator.h b/src/widgets/itemviews/qtreewidgetitemiterator.h
index 39e0244776..5518b431fc 100644
--- a/src/widgets/itemviews/qtreewidgetitemiterator.h
+++ b/src/widgets/itemviews/qtreewidgetitemiterator.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTREEWIDGETITEMITERATOR_H
#define QTREEWIDGETITEMITERATOR_H
diff --git a/src/widgets/itemviews/qtreewidgetitemiterator_p.h b/src/widgets/itemviews/qtreewidgetitemiterator_p.h
index e68f6103d3..c7a04a2f9b 100644
--- a/src/widgets/itemviews/qtreewidgetitemiterator_p.h
+++ b/src/widgets/itemviews/qtreewidgetitemiterator_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTREEWIDGETITEMITERATOR_P_H
#define QTREEWIDGETITEMITERATOR_P_H
@@ -54,6 +18,7 @@
#include <QtCore/qstack.h>
#include "qtreewidgetitemiterator.h"
+#include "private/qglobal_p.h"
#if QT_CONFIG(treewidget)
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/itemviews/qwidgetitemdata_p.h b/src/widgets/itemviews/qwidgetitemdata_p.h
index b7ed6ed862..f8c2d47085 100644
--- a/src/widgets/itemviews/qwidgetitemdata_p.h
+++ b/src/widgets/itemviews/qwidgetitemdata_p.h
@@ -1,47 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIDGETITEMDATA_P_H
#define QWIDGETITEMDATA_P_H
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtCore/qdatastream.h>
+#include <QtCore/qvariant.h>
//
// W A R N I N G
@@ -65,7 +30,7 @@ public:
QVariant value;
inline bool operator==(const QWidgetItemData &other) const { return role == other.role && value == other.value; }
};
-Q_DECLARE_TYPEINFO(QWidgetItemData, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QWidgetItemData, Q_RELOCATABLE_TYPE);
#ifndef QT_NO_DATASTREAM
diff --git a/src/widgets/kernel/kernel.pri b/src/widgets/kernel/kernel.pri
deleted file mode 100644
index a960280959..0000000000
--- a/src/widgets/kernel/kernel.pri
+++ /dev/null
@@ -1,89 +0,0 @@
-# Qt kernel module
-
-# Only used on platforms with CONFIG += precompile_header
-PRECOMPILED_HEADER = kernel/qt_widgets_pch.h
-
-KERNEL_P= kernel
-HEADERS += \
- kernel/qtwidgetsglobal.h \
- kernel/qtwidgetsglobal_p.h \
- kernel/qapplication.h \
- kernel/qapplication_p.h \
- kernel/qwidgetrepaintmanager_p.h \
- kernel/qboxlayout.h \
- kernel/qdesktopwidget.h \
- kernel/qgridlayout.h \
- kernel/qlayout.h \
- kernel/qlayout_p.h \
- kernel/qlayoutengine_p.h \
- kernel/qlayoutitem.h \
- kernel/qsizepolicy.h \
- kernel/qstackedlayout.h \
- kernel/qwidget.h \
- kernel/qwidget_p.h \
- kernel/qgesture.h \
- kernel/qgesture_p.h \
- kernel/qstandardgestures_p.h \
- kernel/qgesturerecognizer.h \
- kernel/qgesturemanager_p.h \
- kernel/qdesktopwidget_p.h \
- kernel/qwidgetwindow_p.h \
- kernel/qwindowcontainer_p.h \
- kernel/qtestsupport_widgets.h
-
-SOURCES += \
- kernel/qapplication.cpp \
- kernel/qwidgetrepaintmanager.cpp \
- kernel/qboxlayout.cpp \
- kernel/qgridlayout.cpp \
- kernel/qlayout.cpp \
- kernel/qlayoutengine.cpp \
- kernel/qlayoutitem.cpp \
- kernel/qsizepolicy.cpp \
- kernel/qstackedlayout.cpp \
- kernel/qwidget.cpp \
- kernel/qgesture.cpp \
- kernel/qstandardgestures.cpp \
- kernel/qgesturerecognizer.cpp \
- kernel/qgesturemanager.cpp \
- kernel/qdesktopwidget.cpp \
- kernel/qwidgetsvariant.cpp \
- kernel/qwidgetwindow.cpp \
- kernel/qwindowcontainer.cpp \
- kernel/qtestsupport_widgets.cpp
-
-macx: {
- HEADERS += kernel/qmacgesturerecognizer_p.h
- SOURCES += kernel/qmacgesturerecognizer.cpp
-}
-
-qtConfig(action) {
- HEADERS += kernel/qaction.h \
- kernel/qaction_p.h \
- kernel/qactiongroup.h \
- kernel/qwidgetaction.h \
- kernel/qwidgetaction_p.h
- SOURCES += kernel/qaction.cpp \
- kernel/qactiongroup.cpp \
- kernel/qwidgetaction.cpp
-}
-
-qtConfig(formlayout) {
- HEADERS += kernel/qformlayout.h
- SOURCES += kernel/qformlayout.cpp
-}
-
-qtConfig(shortcut) {
- HEADERS += kernel/qshortcut.h
- SOURCES += kernel/qshortcut.cpp
-}
-
-qtConfig(tooltip) {
- HEADERS += kernel/qtooltip.h
- SOURCES += kernel/qtooltip.cpp
-}
-
-qtConfig(whatsthis) {
- HEADERS += kernel/qwhatsthis.h
- SOURCES += kernel/qwhatsthis.cpp
-}
diff --git a/src/widgets/kernel/mac.pri b/src/widgets/kernel/mac.pri
deleted file mode 100644
index d21e5d4a74..0000000000
--- a/src/widgets/kernel/mac.pri
+++ /dev/null
@@ -1 +0,0 @@
-macos: LIBS_PRIVATE += -framework AppKit -lz
diff --git a/src/widgets/kernel/qaction.cpp b/src/widgets/kernel/qaction.cpp
deleted file mode 100644
index 934fe576d1..0000000000
--- a/src/widgets/kernel/qaction.cpp
+++ /dev/null
@@ -1,354 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qaction.h"
-#include "qactiongroup.h"
-
-#include "qaction_p.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qlist.h"
-#include "qstylehints.h"
-#if QT_CONFIG(shortcut)
-# include <private/qshortcutmap_p.h>
-#endif
-#include <private/qguiapplication_p.h>
-#if QT_CONFIG(menu)
-#include <private/qmenu_p.h>
-#endif
-#include <private/qdebug_p.h>
-
-
-QT_BEGIN_NAMESPACE
-
-#if QT_CONFIG(shortcut)
-QShortcutMap::ContextMatcher QActionPrivate::contextMatcher() const
-{
- return qWidgetShortcutContextMatcher;
-}
-#endif // QT_CONFIG(shortcut)
-
-bool QActionPrivate::showStatusText(QWidget *widget, const QString &str)
-{
-#if !QT_CONFIG(statustip)
- Q_UNUSED(widget);
- Q_UNUSED(str);
-#else
- if(QObject *object = widget ? widget : parent) {
- QStatusTipEvent tip(str);
- QCoreApplication::sendEvent(object, &tip);
- return true;
- }
-#endif
- return false;
-}
-
-/*!
- \class QAction
- \brief The QAction class provides an abstract user interface
- action that can be inserted into widgets.
-
- \ingroup mainwindow-classes
- \inmodule QtWidgets
-
- \omit
- * parent and widget are different
- * parent does not define context
- \endomit
-
- In applications many common commands can be invoked via menus,
- toolbar buttons, and keyboard shortcuts. Since the user expects
- each command to be performed in the same way, regardless of the
- user interface used, it is useful to represent each command as
- an \e action.
-
- Actions can be added to menus and toolbars, and will
- automatically keep them in sync. For example, in a word processor,
- if the user presses a Bold toolbar button, the Bold menu item
- will automatically be checked.
-
- Actions can be created as independent objects, but they may
- also be created during the construction of menus; the QMenu class
- contains convenience functions for creating actions suitable for
- use as menu items.
-
- A QAction may contain an icon, menu text, a shortcut, status text,
- "What's This?" text, and a tooltip. Most of these can be set in
- the constructor. They can also be set independently with
- setIcon(), setText(), setIconText(), setShortcut(),
- setStatusTip(), setWhatsThis(), and setToolTip(). For menu items,
- it is possible to set an individual font with setFont().
-
- Actions are added to widgets using QWidget::addAction() or
- QGraphicsWidget::addAction(). Note that an action must be added to a
- widget before it can be used; this is also true when the shortcut should
- be global (i.e., Qt::ApplicationShortcut as Qt::ShortcutContext).
-
- Once a QAction has been created it should be added to the relevant
- menu and toolbar, then connected to the slot which will perform
- the action. For example:
-
- \snippet mainwindows/application/mainwindow.cpp 19
-
- We recommend that actions are created as children of the window
- they are used in. In most cases actions will be children of
- the application's main window.
-
- \sa QMenu, QToolBar, {Application Example}
-*/
-
-/*!
- \fn void QAction::trigger()
-
- This is a convenience slot that calls activate(Trigger).
-*/
-
-/*!
- \fn void QAction::hover()
-
- This is a convenience slot that calls activate(Hover).
-*/
-
-/*!
- \enum QAction::MenuRole
-
- This enum describes how an action should be moved into the application menu on \macos.
-
- \value NoRole This action should not be put into the application menu
- \value TextHeuristicRole This action should be put in the application menu based on the action's text
- as described in the QMenuBar documentation.
- \value ApplicationSpecificRole This action should be put in the application menu with an application specific role
- \value AboutQtRole This action handles the "About Qt" menu item.
- \value AboutRole This action should be placed where the "About" menu item is in the application menu. The text of
- the menu item will be set to "About <application name>". The application name is fetched from the
- \c{Info.plist} file in the application's bundle (See \l{Qt for macOS - Deployment}).
- \value PreferencesRole This action should be placed where the "Preferences..." menu item is in the application menu.
- \value QuitRole This action should be placed where the Quit menu item is in the application menu.
-
- Setting this value only has effect on items that are in the immediate menus
- of the menubar, not the submenus of those menus. For example, if you have
- File menu in your menubar and the File menu has a submenu, setting the
- MenuRole for the actions in that submenu have no effect. They will never be moved.
-*/
-
-/*!
- Constructs an action with \a parent. If \a parent is an action
- group the action will be automatically inserted into the group.
-
- \note The \a parent argument is optional since Qt 5.7.
-*/
-QAction::QAction(QObject* parent)
- : QAction(*new QActionPrivate, parent)
-{
-}
-
-
-/*!
- Constructs an action with some \a text and \a parent. If \a
- parent is an action group the action will be automatically
- inserted into the group.
-
- The action uses a stripped version of \a text (e.g. "\&Menu
- Option..." becomes "Menu Option") as descriptive text for
- tool buttons. You can override this by setting a specific
- description with setText(). The same text will be used for
- tooltips unless you specify a different text using
- setToolTip().
-
-*/
-QAction::QAction(const QString &text, QObject* parent)
- : QAction(parent)
-{
- Q_D(QAction);
- d->text = text;
-}
-
-/*!
- Constructs an action with an \a icon and some \a text and \a
- parent. If \a parent is an action group the action will be
- automatically inserted into the group.
-
- The action uses a stripped version of \a text (e.g. "\&Menu
- Option..." becomes "Menu Option") as descriptive text for
- tool buttons. You can override this by setting a specific
- description with setText(). The same text will be used for
- tooltips unless you specify a different text using
- setToolTip().
-*/
-QAction::QAction(const QIcon &icon, const QString &text, QObject* parent)
- : QAction(text, parent)
-{
- Q_D(QAction);
- d->icon = icon;
-}
-
-/*!
- \internal
-*/
-QAction::QAction(QActionPrivate &dd, QObject *parent)
- : QGuiAction(dd, parent)
-{
-}
-
-/*!
- \reimp
-*/
-
-bool QAction::event(QEvent *e)
-{
- Q_D(QAction);
- if (e->type() == QEvent::ActionChanged) {
- for (auto w : qAsConst(d->widgets))
- QCoreApplication::sendEvent(w, e);
-#if QT_CONFIG(graphicsview)
- for (auto gw : qAsConst(d->graphicsWidgets))
- QCoreApplication::sendEvent(gw, e);
-#endif
- }
- return QGuiAction::event(e);
-}
-
-/*!
- Returns the parent widget.
-*/
-QWidget *QAction::parentWidget() const
-{
- QObject *ret = parent();
- while (ret && !ret->isWidgetType())
- ret = ret->parent();
- return static_cast<QWidget*>(ret);
-}
-
-/*!
- \since 4.2
- Returns a list of widgets this action has been added to.
-
- \sa QWidget::addAction(), associatedGraphicsWidgets()
-*/
-QList<QWidget *> QAction::associatedWidgets() const
-{
- Q_D(const QAction);
- return d->widgets;
-}
-
-#if QT_CONFIG(graphicsview)
-/*!
- \since 4.5
- Returns a list of widgets this action has been added to.
-
- \sa QWidget::addAction(), associatedWidgets()
-*/
-QList<QGraphicsWidget *> QAction::associatedGraphicsWidgets() const
-{
- Q_D(const QAction);
- return d->graphicsWidgets;
-}
-#endif
-
-QAction::~QAction()
-{
- Q_D(QAction);
- for (int i = d->widgets.size()-1; i >= 0; --i) {
- QWidget *w = d->widgets.at(i);
- w->removeAction(this);
- }
-#if QT_CONFIG(graphicsview)
- for (int i = d->graphicsWidgets.size()-1; i >= 0; --i) {
- QGraphicsWidget *w = d->graphicsWidgets.at(i);
- w->removeAction(this);
- }
-#endif
-}
-
-/*!
- Returns the action group for this action. If no action group manages
- this action then \nullptr will be returned.
-
- \sa QActionGroup, QAction::setActionGroup()
- */
-QActionGroup *QAction::actionGroup() const
-{
- return static_cast<QActionGroup *>(guiActionGroup());
-}
-
-#if QT_CONFIG(menu)
-/*!
- Returns the menu contained by this action. Actions that contain
- menus can be used to create menu items with submenus, or inserted
- into toolbars to create buttons with popup menus.
-
- \sa QMenu::addAction()
-*/
-QMenu *QAction::menu() const
-{
- Q_D(const QAction);
- return d->menu;
-}
-
-/*!
- Sets the menu contained by this action to the specified \a menu.
-*/
-void QAction::setMenu(QMenu *menu)
-{
- Q_D(QAction);
- if (d->menu)
- d->menu->d_func()->setOverrideMenuAction(nullptr); //we reset the default action of any previous menu
- d->menu = menu;
- if (menu)
- menu->d_func()->setOverrideMenuAction(this);
- d->sendDataChanged();
-}
-#endif // QT_CONFIG(menu)
-
-/*!
- Updates the relevant status bar for the \a widget specified by sending a
- QStatusTipEvent to its parent widget. Returns \c true if an event was sent;
- otherwise returns \c false.
-
- If a null widget is specified, the event is sent to the action's parent.
-
- \sa statusTip
-*/
-bool
-QAction::showStatusText(QWidget *widget)
-{
- return d_func()->showStatusText(widget, statusTip());
-}
-
-QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qaction.h b/src/widgets/kernel/qaction.h
index 808ee9065d..4311d503d7 100644
--- a/src/widgets/kernel/qaction.h
+++ b/src/widgets/kernel/qaction.h
@@ -1,112 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QACTION_H
-#define QACTION_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtGui/qguiaction.h>
-#include <QtCore/qstring.h>
-#include <QtWidgets/qwidget.h>
-#include <QtCore/qvariant.h>
-
-QT_REQUIRE_CONFIG(action);
+#include <QtGui/QAction>
QT_BEGIN_NAMESPACE
-
-class QMenu;
-class QActionGroup;
-class QActionPrivate;
-class QGraphicsWidget;
-
-class Q_WIDGETS_EXPORT QAction : public QGuiAction
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QAction)
-public:
- QAction(QObject* parent = nullptr);
- QAction(const QString &text, QObject* parent = nullptr);
- QAction(const QIcon &icon, const QString &text, QObject* parent);
- ~QAction();
-
- QActionGroup *actionGroup() const;
-
-#if QT_CONFIG(menu)
- QMenu *menu() const;
- void setMenu(QMenu *menu);
-#endif
-
- bool showStatusText(QWidget *widget = nullptr);
-
- QWidget *parentWidget() const;
-
- QList<QWidget *> associatedWidgets() const;
-#if QT_CONFIG(graphicsview)
- QList<QGraphicsWidget *> associatedGraphicsWidgets() const; // ### suboptimal
-#endif
-
-protected:
- QAction(QActionPrivate &dd, QObject *parent);
- bool event(QEvent *) override;
-
-private:
- Q_DISABLE_COPY(QAction)
-
- friend class QGraphicsWidget;
- friend class QWidget;
- friend class QMenu;
- friend class QMenuPrivate;
- friend class QMenuBar;
- friend class QToolButton;
-#ifdef Q_OS_MAC
- friend void qt_mac_clear_status_text(QAction *action);
-#endif
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-Q_WIDGETS_EXPORT QDebug operator<<(QDebug, const QAction *);
-#endif
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <QtWidgets/qactiongroup.h>
-QT_END_INCLUDE_NAMESPACE
-
QT_END_NAMESPACE
-
-#endif // QACTION_H
diff --git a/src/widgets/kernel/qaction_p.h b/src/widgets/kernel/qaction_p.h
deleted file mode 100644
index b865769372..0000000000
--- a/src/widgets/kernel/qaction_p.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QACTION_P_H
-#define QACTION_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of other Qt classes. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtWidgets/private/qtwidgetsglobal_p.h>
-#include <QtGui/private/qguiaction_p.h>
-#include "QtWidgets/qaction.h"
-#if QT_CONFIG(menu)
-#include "QtWidgets/qmenu.h"
-#endif
-#if QT_CONFIG(graphicsview)
-#include "private/qgraphicswidget_p.h"
-#endif
-#include "private/qobject_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_ACTION
-
-
-class QShortcutMap;
-
-class Q_WIDGETS_EXPORT QActionPrivate : public QGuiActionPrivate
-{
- Q_DECLARE_PUBLIC(QAction)
-public:
- QActionPrivate() = default;
-
-#if QT_CONFIG(shortcut)
- QShortcutMap::ContextMatcher contextMatcher() const override;
-#endif
-
- static QActionPrivate *get(QAction *q)
- {
- return q->d_func();
- }
-
- bool showStatusText(QWidget *w, const QString &str);
-
- QPointer<QMenu> menu;
- QWidgetList widgets;
-#if QT_CONFIG(graphicsview)
- QList<QGraphicsWidget *> graphicsWidgets;
-#endif
-};
-
-#endif // QT_NO_ACTION
-
-QT_END_NAMESPACE
-
-#endif // QACTION_P_H
diff --git a/src/widgets/kernel/qaction_widgets.cpp b/src/widgets/kernel/qaction_widgets.cpp
new file mode 100644
index 0000000000..ad282ab104
--- /dev/null
+++ b/src/widgets/kernel/qaction_widgets.cpp
@@ -0,0 +1,71 @@
+// Copyright (C) 2020 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 "qaction.h"
+
+#include <private/qapplication_p.h>
+#include <private/qwidget_p.h>
+#include "qaction_widgets_p.h"
+#if QT_CONFIG(menu)
+#include <private/qmenu_p.h>
+#endif
+#if QT_CONFIG(graphicsview)
+#include "qgraphicswidget.h"
+#endif
+
+
+QT_BEGIN_NAMESPACE
+
+QActionPrivate *QApplicationPrivate::createActionPrivate() const
+{
+ return new QtWidgetsActionPrivate;
+}
+
+QtWidgetsActionPrivate::~QtWidgetsActionPrivate() = default;
+
+// we can't do this in the destructor, as it would only be called by ~QObject
+void QtWidgetsActionPrivate::destroy()
+{
+ Q_Q(QAction);
+ const auto objects = associatedObjects;
+ 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)
+ else if (QGraphicsWidget *graphicsWidget = qobject_cast<QGraphicsWidget*>(object))
+ graphicsWidget->removeAction(q);
+#endif
+ }
+}
+
+#if QT_CONFIG(shortcut)
+QShortcutMap::ContextMatcher QtWidgetsActionPrivate::contextMatcher() const
+{
+ return qWidgetShortcutContextMatcher;
+}
+#endif
+
+#if QT_CONFIG(menu)
+QObject *QtWidgetsActionPrivate::menu() const
+{
+ return m_menu;
+}
+
+void QtWidgetsActionPrivate::setMenu(QObject *menu)
+{
+ Q_Q(QAction);
+ QMenu *theMenu = qobject_cast<QMenu*>(menu);
+ Q_ASSERT_X(!menu || theMenu, "QAction::setMenu",
+ "QAction::setMenu expects a QMenu* in widget applications");
+ if (m_menu)
+ m_menu->d_func()->setOverrideMenuAction(nullptr); //we reset the default action of any previous menu
+ m_menu = theMenu;
+ if (m_menu)
+ m_menu->d_func()->setOverrideMenuAction(q);
+ sendDataChanged();
+}
+#endif // QT_CONFIG(menu)
+
+QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qaction_widgets_p.h b/src/widgets/kernel/qaction_widgets_p.h
new file mode 100644
index 0000000000..77c3d8a680
--- /dev/null
+++ b/src/widgets/kernel/qaction_widgets_p.h
@@ -0,0 +1,54 @@
+// Copyright (C) 2020 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 QACTION_WIDGETS_P_H
+#define QACTION_WIDGETS_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of other Qt classes. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtGui/private/qaction_p.h>
+#if QT_CONFIG(menu)
+#include <QtWidgets/qmenu.h>
+#endif
+
+#include <QtCore/qpointer.h>
+
+QT_REQUIRE_CONFIG(action);
+
+QT_BEGIN_NAMESPACE
+
+class QShortcutMap;
+
+class Q_WIDGETS_EXPORT QtWidgetsActionPrivate : public QActionPrivate
+{
+ Q_DECLARE_PUBLIC(QAction)
+public:
+ QtWidgetsActionPrivate() = default;
+ ~QtWidgetsActionPrivate();
+
+ void destroy() override;
+
+#if QT_CONFIG(shortcut)
+ QShortcutMap::ContextMatcher contextMatcher() const override;
+#endif
+
+#if QT_CONFIG(menu)
+ QPointer<QMenu> m_menu;
+
+ QObject *menu() const override;
+ void setMenu(QObject *menu) override;
+#endif
+};
+
+QT_END_NAMESPACE
+
+#endif // QACTION_WIDGETS_P_H
diff --git a/src/widgets/kernel/qactiongroup.cpp b/src/widgets/kernel/qactiongroup.cpp
deleted file mode 100644
index cc900cbb0f..0000000000
--- a/src/widgets/kernel/qactiongroup.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qactiongroup.h"
-#include <QtGui/private/qguiactiongroup_p.h>
-
-#include "qaction.h"
-
-QT_BEGIN_NAMESPACE
-
-class QActionGroupPrivate : public QGuiActionGroupPrivate
-{
- Q_DECLARE_PUBLIC(QActionGroup)
-public:
- void emitSignal(Signal, QGuiAction *) override;
-};
-
-void QActionGroupPrivate::emitSignal(Signal s, QGuiAction *action)
-{
- Q_Q(QActionGroup);
- switch (s) {
- case QGuiActionGroupPrivate::Triggered:
- emit q->triggered(static_cast<QAction *>(action));
- break;
- case QGuiActionGroupPrivate::Hovered:
- emit q->hovered(static_cast<QAction *>(action));
- break;
- }
-}
-
-/*!
- \class QActionGroup
- \brief The QActionGroup class groups actions together.
-
- \ingroup mainwindow-classes
- \inmodule QtWidgets
-
- In some situations it is useful to group QAction objects together.
- For example, if you have a \uicontrol{Left Align} action, a \uicontrol{Right
- Align} action, a \uicontrol{Justify} action, and a \uicontrol{Center} action,
- only one of these actions should be active at any one time. One
- simple way of achieving this is to group the actions together in
- an action group.
-
- Here's a example (from the \l{mainwindows/menus}{Menus} example):
-
- \snippet mainwindows/menus/mainwindow.cpp 6
-
- Here we create a new action group. Since the action group is
- exclusive by default, only one of the actions in the group is
- checked at any one time.
-
- \image qactiongroup-align.png Alignment options in a QMenu
-
- A QActionGroup emits an triggered() signal when one of its
- actions is chosen. Each action in an action group emits its
- triggered() signal as usual.
-
- As stated above, an action group is exclusive by default; it
- ensures that at most only one checkable action is active at any one time.
- If you want to group checkable actions without making them
- exclusive, you can turn off exclusiveness by calling
- setExclusive(false).
-
- By default the active action of an exclusive group cannot be unchecked.
- In some cases it may be useful to allow unchecking all the actions,
- you can allow this by calling
- setExclusionPolicy(QActionGroup::ExclusionPolicy::ExclusiveOptional).
-
- Actions can be added to an action group using addAction(), but it
- is usually more convenient to specify a group when creating
- actions; this ensures that actions are automatically created with
- a parent. Actions can be visually separated from each other by
- adding a separator action to the group; create an action and use
- QAction's \l {QAction::}{setSeparator()} function to make it
- considered a separator. Action groups are added to widgets with
- the QWidget::addActions() function.
-
- \sa QAction
-*/
-
-/*!
- Constructs an action group for the \a parent object.
-
- The action group is exclusive by default. Call setExclusive(false)
- to make the action group non-exclusive. To make the group exclusive
- but allow unchecking the active action call instead
- setExclusionPolicy(QActionGroup::ExclusionPolicy::ExclusiveOptional)
-*/
-QActionGroup::QActionGroup(QObject* parent) :
- QGuiActionGroup(*new QActionGroupPrivate, parent)
-{
-}
-
-/*!
- Destroys the action group.
-*/
-QActionGroup::~QActionGroup() = default;
-
-QAction *QActionGroup::checkedAction() const
-{
- return static_cast<QAction *>(checkedGuiAction());
-}
-
-QAction *QActionGroup::addAction(QAction *a)
-{
- QGuiActionGroup::addAction(a);
- return a;
-}
-
-/*!
- Creates and returns an action with \a text. The newly created
- action is a child of this action group.
-
- Normally an action is added to a group by creating it with the
- group as parent, so this function is not usually used.
-
- \sa QAction::setActionGroup()
-*/
-QAction *QActionGroup::addAction(const QString &text)
-{
- return new QAction(text, this);
-}
-
-/*!
- Creates and returns an action with \a text and an \a icon. The
- newly created action is a child of this action group.
-
- Normally an action is added to a group by creating it with the
- group as its parent, so this function is not usually used.
-
- \sa QAction::setActionGroup()
-*/
-QAction *QActionGroup::addAction(const QIcon &icon, const QString &text)
-{
- return new QAction(icon, text, this);
-}
-
-/*!
- Returns the list of this groups's actions. This may be empty.
-*/
-QList<QAction*> QActionGroup::actions() const
-{
- QList<QAction*> result;
- const auto baseActions = guiActions();
- result.reserve(baseActions.size());
- for (auto baseAction : baseActions)
- result.append(static_cast<QAction*>(baseAction));
- return result;
-}
-
-QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qactiongroup.h b/src/widgets/kernel/qactiongroup.h
index 0a6a85f093..2592eb17b4 100644
--- a/src/widgets/kernel/qactiongroup.h
+++ b/src/widgets/kernel/qactiongroup.h
@@ -1,80 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QACTIONGROUP_H
-#define QACTIONGROUP_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtGui/qguiactiongroup.h>
-#include <QtWidgets/qaction.h>
-
-QT_REQUIRE_CONFIG(action);
+#include <QtGui/QActionGroup>
QT_BEGIN_NAMESPACE
-
-class QActionGroupPrivate;
-
-class Q_WIDGETS_EXPORT QActionGroup : public QGuiActionGroup
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QActionGroup)
-
-public:
- explicit QActionGroup(QObject* parent);
- ~QActionGroup();
-
- QAction *checkedAction() const;
-
- QAction *addAction(QAction *a);
- QAction *addAction(const QString &text);
- QAction *addAction(const QIcon &icon, const QString &text);
-
- QList<QAction*> actions() const;
-
-Q_SIGNALS:
- void triggered(QAction *);
- void hovered(QAction *);
-
-private:
- Q_DISABLE_COPY(QActionGroup)
-};
-
QT_END_NAMESPACE
-
-#endif // QACTIONGROUP_H
diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp
index eea97b2c0b..de7d93ce20 100644
--- a/src/widgets/kernel/qapplication.cpp
+++ b/src/widgets/kernel/qapplication.cpp
@@ -1,48 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qabstracteventdispatcher.h"
#include "qapplication.h"
#include "qclipboard.h"
#include "qcursor.h"
-#include "qdesktopwidget.h"
#include "qdir.h"
#include "qevent.h"
#include "qfile.h"
@@ -58,7 +21,9 @@
#include "qstyle.h"
#include "qstyleoption.h"
#include "qstylefactory.h"
+#if QT_CONFIG(tooltip)
#include "qtooltip.h"
+#endif
#include "qtranslator.h"
#include "qvariant.h"
#include "qwidget.h"
@@ -77,45 +42,51 @@
#include <QtGui/qstylehints.h>
#include <QtGui/qinputmethod.h>
#include <QtGui/private/qwindow_p.h>
-#include <QtGui/qtouchdevice.h>
+#include <QtGui/qpointingdevice.h>
+#include <QtGui/private/qpointingdevice_p.h>
#include <qpa/qplatformtheme.h>
#if QT_CONFIG(whatsthis)
#include <QtWidgets/QWhatsThis>
#endif
+#if QT_CONFIG(accessibility)
+#include <QtGui/qaccessible_base.h>
+#include "private/qaccessiblewidgetfactory_p.h"
+#endif
#include "private/qkeymapper_p.h"
-#include "private/qaccessiblewidgetfactory_p.h"
#include <qthread.h>
#include <private/qthread_p.h>
+#include <QtGui/private/qevent_p.h>
+#include <QtGui/private/qeventpoint_p.h>
#include <private/qfont_p.h>
+#if QT_CONFIG(action)
+#include <private/qaction_p.h>
+#endif
#include <stdlib.h>
#include "qapplication_p.h"
-#include "private/qevent_p.h"
#include "qwidget_p.h"
#include "qgesture.h"
#include "private/qgesturemanager_p.h"
#include <qpa/qplatformfontdatabase.h>
-#ifdef Q_OS_WIN
-#include <QtCore/qt_windows.h> // for qt_win_display_dc()
-#endif
-
#include "qdatetime.h"
#include <qpa/qplatformwindow.h>
#include <qtwidgets_tracepoints_p.h>
+#ifdef Q_OS_MACOS
+#include <QtCore/private/qcore_mac_p.h>
+#endif
+
#include <algorithm>
#include <iterator>
-//#define ALIEN_DEBUG
-
static void initResources()
{
Q_INIT_RESOURCE(qstyle);
@@ -127,6 +98,15 @@ static void initResources()
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())) { \
@@ -142,8 +122,8 @@ QApplicationPrivate *QApplicationPrivate::self = nullptr;
bool QApplicationPrivate::autoSipEnabled = true;
-QApplicationPrivate::QApplicationPrivate(int &argc, char **argv, int flags)
- : QApplicationPrivateBase(argc, argv, flags)
+QApplicationPrivate::QApplicationPrivate(int &argc, char **argv)
+ : QGuiApplicationPrivate(argc, argv)
{
application_type = QApplicationPrivate::Gui;
@@ -218,8 +198,7 @@ void QApplicationPrivate::createEventDispatcher()
\li It provides localization of strings that are visible to the
user via translate().
- \li It provides some magical objects like the desktop() and the
- clipboard().
+ \li It provides some magical objects like the clipboard().
\li It knows about the application's windows. You can ask which
widget is at a certain position using widgetAt(), get a list of
@@ -266,7 +245,6 @@ void QApplicationPrivate::createEventDispatcher()
postEvent(),
sendPostedEvents(),
removePostedEvents(),
- hasPendingEvents(),
notify().
\row
@@ -284,7 +262,6 @@ void QApplicationPrivate::createEventDispatcher()
\li Widgets
\li allWidgets(),
topLevelWidgets(),
- desktop(),
activePopupWidget(),
activeModalWidget(),
clipboard(),
@@ -308,22 +285,6 @@ void QApplicationPrivate::createEventDispatcher()
\sa QCoreApplication, QAbstractEventDispatcher, QEventLoop, QSettings
*/
-#if QT_DEPRECATED_SINCE(5, 8)
-// ### fixme: Qt 6: Remove ColorSpec and accessors.
-/*!
- \enum QApplication::ColorSpec
- \obsolete
-
- \value NormalColor the default color allocation policy
- \value CustomColor the same as NormalColor for X11; allocates colors
- to a palette on demand under Windows
- \value ManyColor the right choice for applications that use thousands of
- colors
-
- See setColorSpec() for full details.
-*/
-#endif
-
/*!
\fn QWidget *QApplication::topLevelAt(const QPoint &point)
@@ -349,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
@@ -369,12 +329,11 @@ QPointer<QWidget> QApplicationPrivate::wheel_widget;
#endif
bool qt_in_tab_key_event = false;
int qt_antialiasing_threshold = -1;
-QSize QApplicationPrivate::app_strut = QSize(0,0); // no default application strut
int QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
bool QApplicationPrivate::widgetCount = false;
#ifdef QT_KEYPAD_NAVIGATION
Qt::NavigationMode QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadTabOrder;
-QWidget *QApplicationPrivate::oldEditFocus = 0;
+QWidget *QApplicationPrivate::oldEditFocus = nullptr;
#endif
inline bool QApplicationPrivate::isAlien(QWidget *widget)
@@ -395,7 +354,7 @@ FontHash *qt_app_fonts_hash() { return app_fonts(); }
QWidgetList *QApplicationPrivate::popupWidgets = nullptr; // has keyboard input focus
-QDesktopWidget *qt_desktopWidget = nullptr; // root window widgets
+QWidget *qt_desktopWidget = nullptr; // root window widgets
/*!
\internal
@@ -406,7 +365,7 @@ void QApplicationPrivate::process_cmdline()
styleOverride = QString::fromLocal8Bit(qgetenv("QT_STYLE_OVERRIDE"));
// process platform-indep command line
- if (!qt_is_gui_used || !argc)
+ if (qt_is_tty_app || !argc)
return;
int i, j;
@@ -426,10 +385,10 @@ void QApplicationPrivate::process_cmdline()
// obsolete argument
#ifndef QT_NO_STYLE_STYLESHEET
} else if (strcmp(arg, "-stylesheet") == 0 && i < argc -1) {
- styleSheet = QLatin1String("file:///");
+ styleSheet = "file:///"_L1;
styleSheet.append(QString::fromLocal8Bit(argv[++i]));
} else if (strncmp(arg, "-stylesheet=", 12) == 0) {
- styleSheet = QLatin1String("file:///");
+ styleSheet = "file:///"_L1;
styleSheet.append(QString::fromLocal8Bit(arg + 12));
#endif
} else if (qstrcmp(arg, "-widgetcount") == 0) {
@@ -439,7 +398,7 @@ void QApplicationPrivate::process_cmdline()
}
}
- if(j < argc) {
+ if (j < argc) {
argv[j] = nullptr;
argc = j;
}
@@ -493,9 +452,9 @@ void QApplicationPrivate::process_cmdline()
#ifdef Q_QDOC
QApplication::QApplication(int &argc, char **argv)
#else
-QApplication::QApplication(int &argc, char **argv, int _internal)
+QApplication::QApplication(int &argc, char **argv, int)
#endif
- : QGuiApplication(*new QApplicationPrivate(argc, argv, _internal))
+ : QGuiApplication(*new QApplicationPrivate(argc, argv))
{
Q_D(QApplication);
d->init();
@@ -514,7 +473,7 @@ void QApplicationPrivate::init()
initResources();
- qt_is_gui_used = (application_type != QApplicationPrivate::Tty);
+ qt_is_tty_app = (application_type == QApplicationPrivate::Tty);
process_cmdline();
// Must be called before initialize()
@@ -526,7 +485,7 @@ void QApplicationPrivate::init()
initialize();
eventDispatcher->startingUp();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
// factory for accessible interfaces for widgets shipped with Qt
QAccessible::installFactory(&qAccessibleFactory);
#endif
@@ -535,21 +494,18 @@ void QApplicationPrivate::init()
void qt_init_tooltip_palette()
{
-#ifndef QT_NO_TOOLTIP
- if (const QPalette *toolTipPalette = QGuiApplicationPrivate::platformTheme()->palette(QPlatformTheme::ToolTipPalette))
- QToolTip::setPalette(*toolTipPalette);
+#if QT_CONFIG(tooltip)
+ if (const QPalette *toolTipPalette = QGuiApplicationPrivate::platformTheme()->palette(QPlatformTheme::ToolTipPalette)) {
+ QPalette toolTipPal = *toolTipPalette;
+ toolTipPal.setResolveMask(0);
+ QToolTip::setPalette(toolTipPal);
+ }
#endif
}
-#if QT_CONFIG(statemachine)
-void qRegisterGuiStateMachine();
-void qUnregisterGuiStateMachine();
-#endif
extern void qRegisterWidgetsVariant();
/*!
- \fn void QApplicationPrivate::initialize()
-
Initializes the QApplication object, called from the constructors.
*/
void QApplicationPrivate::initialize()
@@ -572,22 +528,20 @@ void QApplicationPrivate::initialize()
} else {
qWarning("QApplication: invalid style override '%s' passed, ignoring it.\n"
"\tAvailable styles: %s", qPrintable(styleOverride),
- qPrintable(QStyleFactory::keys().join(QLatin1String(", "))));
+ qPrintable(QStyleFactory::keys().join(", "_L1)));
+ // Clear styleOverride so it is not picked by Qt Quick Controls (QTBUG-100563)
+ styleOverride.clear();
}
}
// Trigger default style if none was set already
Q_UNUSED(QApplication::style());
}
-#if QT_CONFIG(statemachine)
- // trigger registering of QStateMachine's GUI types
- qRegisterGuiStateMachine();
-#endif
if (qEnvironmentVariableIntValue("QT_USE_NATIVE_WINDOWS") > 0)
QCoreApplication::setAttribute(Qt::AA_NativeWindows);
- if (qt_is_gui_used)
+ if (!qt_is_tty_app)
initializeMultitouch();
if (QGuiApplication::desktopSettingsAware())
@@ -747,58 +701,24 @@ QApplication::~QApplication()
QApplicationPrivate::app_style = nullptr;
#if QT_CONFIG(draganddrop)
- if (qt_is_gui_used)
+ if (!qt_is_tty_app)
delete QDragManager::self();
#endif
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);
QApplicationPrivate::obey_desktop_settings = true;
- QApplicationPrivate::app_strut = QSize(0, 0);
QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
QApplicationPrivate::widgetCount = false;
-
-#if QT_CONFIG(statemachine)
- // trigger unregistering of QStateMachine's GUI types
- qUnregisterGuiStateMachine();
-#endif
-}
-
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
-// #fixme: Remove.
-static HDC displayDC = 0; // display device context
-
-Q_WIDGETS_EXPORT HDC qt_win_display_dc() // get display DC
-{
- Q_ASSERT(qApp && qApp->thread() == QThread::currentThread());
- if (!displayDC)
- displayDC = GetDC(0);
- return displayDC;
-}
-#endif
-#endif
-
-void qt_cleanup()
-{
- QPixmapCache::clear();
- QColormap::cleanup();
-
- QApplicationPrivate::active_window = nullptr; //### this should not be necessary
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
- if (displayDC) {
- ReleaseDC(0, displayDC);
- displayDC = 0;
- }
-#endif
-#endif
}
/*!
@@ -862,33 +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) {
- ((QResizeEvent *)(cur.event))->s = ((QResizeEvent *)event)->s;
- } else if (cur.event->type() == QEvent::Move) {
- ((QMoveEvent *)(cur.event))->p = ((QMoveEvent *)event)->p;
- } 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;
}
/*!
@@ -985,10 +926,7 @@ QStyle *QApplication::style()
// Take ownership of the style
defaultStyle->setParent(qApp);
- if (testAttribute(Qt::AA_SetPalette))
- defaultStyle->polish(*QGuiApplicationPrivate::app_pal);
- else
- QApplicationPrivate::initializeWidgetPalettesFromTheme();
+ QGuiApplicationPrivate::updatePalette();
#ifndef QT_NO_STYLE_STYLESHEET
if (!QApplicationPrivate::styleSheet.isEmpty()) {
@@ -1059,13 +997,10 @@ void QApplication::setStyle(QStyle *style)
QApplicationPrivate::app_style = style;
QApplicationPrivate::app_style->setParent(qApp); // take ownership
- // take care of possible palette requirements of certain gui
- // styles. Do it before polishing the application since the style
- // might call QApplication::setPalette() itself
- if (testAttribute(Qt::AA_SetPalette))
- QApplicationPrivate::app_style->polish(*QGuiApplicationPrivate::app_pal);
- else
- QApplicationPrivate::initializeWidgetPalettesFromTheme();
+ // Take care of possible palette requirements of certain
+ // styles. Do it before polishing the application since the
+ // style might call QApplication::setPalette() itself.
+ QGuiApplicationPrivate::updatePalette();
// The default widget font hash is based on the platform theme,
// not the style, but the widget fonts could in theory have been
@@ -1123,7 +1058,7 @@ void QApplication::setStyle(QStyle *style)
Requests a QStyle object for \a style from the QStyleFactory.
The string must be one of the QStyleFactory::keys(), typically one of
- "windows", "windowsvista", "fusion", or "macintosh". Style
+ "windows", "windowsvista", "fusion", or "macos". Style
names are case insensitive.
Returns \nullptr if an unknown \a style is passed, otherwise the QStyle object
@@ -1143,108 +1078,6 @@ QStyle* QApplication::setStyle(const QString& style)
return s;
}
-#if QT_DEPRECATED_SINCE(5, 8)
-/*!
- Returns the color specification.
- \obsolete
-
- \sa QApplication::setColorSpec()
-*/
-
-int QApplication::colorSpec()
-{
- return QApplication::NormalColor;
-}
-
-/*!
- Sets the color specification for the application to \a spec.
- \obsolete
-
- This call has no effect.
-
- The color specification controls how the application allocates colors when
- run on a display with a limited amount of colors, e.g. 8 bit / 256 color
- displays.
-
- The color specification must be set before you create the QApplication
- object.
-
- The options are:
- \list
- \li QApplication::NormalColor. This is the default color allocation
- strategy. Use this option if your application uses buttons, menus,
- texts and pixmaps with few colors. With this option, the
- application uses system global colors. This works fine for most
- applications under X11, but on the Windows platform, it may cause
- dithering of non-standard colors.
- \li QApplication::CustomColor. Use this option if your application
- needs a small number of custom colors. On X11, this option is the
- same as NormalColor. On Windows, Qt creates a Windows palette, and
- allocates colors to it on demand.
- \li QApplication::ManyColor. Use this option if your application is
- very color hungry, e.g., it requires thousands of colors. \br
- Under X11 the effect is:
- \list
- \li For 256-color displays which have at best a 256 color true
- color visual, the default visual is used, and colors are
- allocated from a color cube. The color cube is the 6x6x6
- (216 color) "Web palette" (the red, green, and blue
- components always have one of the following values: 0x00,
- 0x33, 0x66, 0x99, 0xCC, or 0xFF), but the number of colors
- can be changed by the \e -ncols option. The user can force
- the application to use the true color visual with the
- \l{QApplication::QApplication()}{-visual} option.
- \li For 256-color displays which have a true color visual with
- more than 256 colors, use that visual. Silicon Graphics X
- servers this feature, for example. They provide an 8 bit
- visual by default but can deliver true color when asked.
- \endlist
- On Windows, Qt creates a Windows palette, and fills it with a color
- cube.
- \endlist
-
- Be aware that the CustomColor and ManyColor choices may lead to colormap
- flashing: The foreground application gets (most) of the available colors,
- while the background windows will look less attractive.
-
- Example:
-
- \snippet code/src_gui_kernel_qapplication.cpp 2
-
- \sa colorSpec()
-*/
-
-void QApplication::setColorSpec(int spec)
-{
- Q_UNUSED(spec)
-}
-#endif
-
-/*!
- \property QApplication::globalStrut
- \brief the minimum size that any GUI element that the user can interact
- with should have
-
- For example, no button should be resized to be smaller than the global
- strut size. The strut size should be considered when reimplementing GUI
- controls that may be used on touch-screens or similar I/O devices.
-
- Example:
-
- \snippet code/src_gui_kernel_qapplication.cpp 3
-
- By default, this property contains a QSize object with zero width and height.
-*/
-QSize QApplication::globalStrut()
-{
- return QApplicationPrivate::app_strut;
-}
-
-void QApplication::setGlobalStrut(const QSize& strut)
-{
- QApplicationPrivate::app_strut = strut;
-}
-
// Widget specific palettes
QApplicationPrivate::PaletteHash QApplicationPrivate::widgetPalettes;
@@ -1261,6 +1094,13 @@ QPalette QApplicationPrivate::basePalette() const
if (const QPalette *themePalette = platformTheme() ? platformTheme()->palette() : nullptr)
palette = themePalette->resolve(palette);
+ // Finish off by letting the application style polish the palette. This will
+ // not result in the polished palette becoming a user-set palette, as the
+ // resulting base palette is only used as a fallback, with the resolve mask
+ // set to 0.
+ if (app_style)
+ app_style->polish(palette);
+
return palette;
}
@@ -1334,17 +1174,19 @@ QPalette QApplication::palette(const char *className)
*/
void QApplication::setPalette(const QPalette &palette, const char* className)
{
- QPalette polishedPalette = palette;
-
- if (QApplicationPrivate::app_style)
- QApplicationPrivate::app_style->polish(polishedPalette);
-
if (className) {
+ QPalette polishedPalette = palette;
+ if (QApplicationPrivate::app_style) {
+ auto originalResolveMask = palette.resolveMask();
+ QApplicationPrivate::app_style->polish(polishedPalette);
+ polishedPalette.setResolveMask(originalResolveMask);
+ }
+
QApplicationPrivate::widgetPalettes.insert(className, polishedPalette);
if (qApp)
qApp->d_func()->handlePaletteChanged(className);
} else {
- QGuiApplication::setPalette(polishedPalette);
+ QGuiApplication::setPalette(palette);
}
}
@@ -1355,23 +1197,20 @@ void QApplicationPrivate::handlePaletteChanged(const char *className)
// Setting the global application palette is documented to
// reset any previously set class specific widget palettes.
- bool sendPaletteChangeToAllWidgets = false;
- if (!className && !widgetPalettes.isEmpty()) {
- sendPaletteChangeToAllWidgets = true;
+ if (!className && !widgetPalettes.isEmpty())
widgetPalettes.clear();
- }
QGuiApplicationPrivate::handlePaletteChanged(className);
QEvent event(QEvent::ApplicationPaletteChange);
const QWidgetList widgets = QApplication::allWidgets();
for (auto widget : widgets) {
- if (sendPaletteChangeToAllWidgets || (!className && widget->isWindow()) || (className && widget->inherits(className)))
+ if (!widget->isWindow() && widget->inherits(className))
QCoreApplication::sendEvent(widget, &event);
}
#if QT_CONFIG(graphicsview)
- for (auto scene : qAsConst(scene_list))
+ for (auto scene : std::as_const(scene_list))
QCoreApplication::sendEvent(scene, &event);
#endif
@@ -1428,9 +1267,11 @@ QFont QApplication::font()
/*!
\overload
- Returns the default font for the \a widget.
+ Returns the default font for the \a widget. If a default font was not
+ registered for the \a{widget}'s class, it returns the default font of
+ its nearest registered superclass.
- \sa fontMetrics(), QWidget::setFont()
+ \sa fontMetrics(), setFont(), QWidget::setFont()
*/
QFont QApplication::font(const QWidget *widget)
@@ -1448,14 +1289,16 @@ QFont QApplication::font(const QWidget *widget)
return hash->value(QByteArrayLiteral("QMiniFont"));
}
#endif
- FontHashConstIt it = hash->constFind(widget->metaObject()->className());
+ // Return the font for the nearest registered superclass
+ const QMetaObject *metaObj = widget->metaObject();
+ FontHashConstIt it = hash->constFind(metaObj->className());
const FontHashConstIt cend = hash->constEnd();
+ while (it == cend && metaObj != &QWidget::staticMetaObject) {
+ metaObj = metaObj->superClass();
+ it = hash->constFind(metaObj->className());
+ }
if (it != cend)
return it.value();
- for (it = hash->constBegin(); it != cend; ++it) {
- if (widget->inherits(it.key()))
- return it.value();
- }
}
return font();
}
@@ -1500,26 +1343,20 @@ QFont QApplication::font(const char *className)
void QApplication::setFont(const QFont &font, const char *className)
{
- bool all = false;
FontHash *hash = app_fonts();
if (!className) {
QGuiApplication::setFont(font);
- if (hash && hash->size()) {
- all = true;
+ if (hash && hash->size())
hash->clear();
- }
} else if (hash) {
hash->insert(className, font);
}
if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
- // Send ApplicationFontChange to qApp itself, and to the widgets.
QEvent e(QEvent::ApplicationFontChange);
- QCoreApplication::sendEvent(QApplication::instance(), &e);
-
QWidgetList wids = QApplication::allWidgets();
for (QWidgetList::ConstIterator it = wids.constBegin(), cend = wids.constEnd(); it != cend; ++it) {
QWidget *w = *it;
- if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
+ if (!w->isWindow() && w->inherits(className)) // matching class
sendEvent(w, &e);
}
@@ -1557,6 +1394,12 @@ void QApplicationPrivate::setSystemFont(const QFont &font)
*/
QString QApplicationPrivate::desktopStyleKey()
{
+#if defined(QT_BUILD_INTERNAL)
+ // Allow auto-tests to override the desktop style
+ if (qEnvironmentVariableIsSet("QT_DESKTOP_STYLE_KEY"))
+ return QString::fromLocal8Bit(qgetenv("QT_DESKTOP_STYLE_KEY"));
+#endif
+
// The platform theme might return a style that is not available, find
// first valid one.
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
@@ -1570,24 +1413,6 @@ QString QApplicationPrivate::desktopStyleKey()
return QString();
}
-#if QT_VERSION < 0x060000 // remove these forwarders in Qt 6
-/*!
- \property QApplication::windowIcon
- \brief the default window icon
-
- \sa QWidget::setWindowIcon(), {Setting the Application Icon}
-*/
-QIcon QApplication::windowIcon()
-{
- return QGuiApplication::windowIcon();
-}
-
-void QApplication::setWindowIcon(const QIcon &icon)
-{
- QGuiApplication::setWindowIcon(icon);
-}
-#endif
-
void QApplicationPrivate::notifyWindowIconChanged()
{
QEvent ev(QEvent::ApplicationWindowIconChange);
@@ -1687,7 +1512,7 @@ void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
QWidget *prev = focus_widget;
focus_widget = focus;
- if(focus_widget)
+ if (focus_widget)
focus_widget->d_func()->setFocus_sys();
if (reason != Qt::NoFocusReason) {
@@ -1695,7 +1520,7 @@ void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
//send events
if (prev) {
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keyboardNavigationEnabled()) {
if (prev->hasEditFocus() && reason != Qt::PopupFocusReason)
prev->setEditFocus(false);
}
@@ -1706,7 +1531,7 @@ void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
if (that)
QCoreApplication::sendEvent(that->style(), &out);
}
- if(focus && QApplicationPrivate::focus_widget == focus) {
+ if (focus && QApplicationPrivate::focus_widget == focus) {
QFocusEvent in(QEvent::FocusIn, reason);
QPointer<QWidget> that = focus;
QCoreApplication::sendEvent(focus, &in);
@@ -1733,7 +1558,9 @@ QWidget *QApplication::activeWindow()
return QApplicationPrivate::active_window;
}
+#if QT_DEPRECATED_SINCE(6,0)
/*!
+ \deprecated Use the QFontMetricsF constructor instead.
Returns display (screen) font metrics for the application font.
\sa font(), setFont(), QWidget::fontMetrics(), QPainter::fontMetrics()
@@ -1741,8 +1568,9 @@ QWidget *QApplication::activeWindow()
QFontMetrics QApplication::fontMetrics()
{
- return desktop()->fontMetrics();
+ return QApplicationPrivate::desktop()->fontMetrics();
}
+#endif
bool QApplicationPrivate::tryCloseAllWidgetWindows(QWindowList *processedWindows)
{
@@ -1773,30 +1601,21 @@ retry:
return true;
}
-bool QApplicationPrivate::tryCloseAllWindows()
-{
- QWindowList processedWindows;
- return QApplicationPrivate::tryCloseAllWidgetWindows(&processedWindows)
- && QGuiApplicationPrivate::tryCloseRemainingWindows(processedWindows);
-}
-
/*!
Closes all top-level windows.
This function is particularly useful for applications with many top-level
- windows. It could, for example, be connected to a \uicontrol{Exit} entry in the
- \uicontrol{File} menu:
-
- \snippet mainwindows/mdi/mainwindow.cpp 0
+ windows.
The windows are closed in random order, until one window does not accept
- the close event. The application quits when the last window was
- successfully closed; this can be turned off by setting
- \l quitOnLastWindowClosed to false.
+ the close event. The application quits when the last window was successfully
+ closed, unless \l quitOnLastWindowClosed is set to false. To trigger application
+ termination from e.g. a menu, use QCoreApplication::quit() instead of this
+ function.
\sa quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(),
- QWidget::closeEvent(), lastWindowClosed(), QCoreApplication::quit(), topLevelWidgets(),
- QWidget::isWindow()
+ QWidget::closeEvent(), lastWindowClosed(), QCoreApplication::quit(),
+ topLevelWidgets(), QWidget::isWindow()
*/
void QApplication::closeAllWindows()
{
@@ -1841,9 +1660,16 @@ void QApplication::aboutQt()
bool QApplication::event(QEvent *e)
{
Q_D(QApplication);
- if (e->type() == QEvent::Quit) {
+ switch (e->type()) {
+ case QEvent::Quit:
+ // FIXME: This logic first tries to close all windows, and then
+ // checks whether it was successful, but the conditions used in
+ // closeAllWindows() differ from the verification logic below.
+ // We should build on the logic in tryCloseAllWidgetWindows().
closeAllWindows();
for (auto *w : topLevelWidgets()) {
+ if (w->data->is_closing)
+ continue;
if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) &&
(!(w->windowType() == Qt::Dialog) || !w->parentWidget()) && !w->testAttribute(Qt::WA_DontShowOnScreen)) {
e->ignore();
@@ -1855,7 +1681,7 @@ bool QApplication::event(QEvent *e)
// closeAllWindows(). FIXME: Unify all this close magic through closeAllWindows.
return QCoreApplication::event(e);
#ifndef Q_OS_WIN
- } else if (e->type() == QEvent::LocaleChange) {
+ case QEvent::LocaleChange: {
// on Windows the event propagation is taken care by the
// WM_SETTINGCHANGE event handler.
const QWidgetList list = topLevelWidgets();
@@ -1865,8 +1691,10 @@ bool QApplication::event(QEvent *e)
w->d_func()->setLocale_helper(QLocale(), true);
}
}
+ break;
+ }
#endif
- } else if (e->type() == QEvent::Timer) {
+ case QEvent::Timer: {
QTimerEvent *te = static_cast<QTimerEvent*>(e);
Q_ASSERT(te != nullptr);
if (te->timerId() == d->toolTipWakeUp.timerId()) {
@@ -1895,19 +1723,28 @@ bool QApplication::event(QEvent *e)
} else if (te->timerId() == d->toolTipFallAsleep.timerId()) {
d->toolTipFallAsleep.stop();
}
+ break;
+ }
#if QT_CONFIG(whatsthis)
- } else if (e->type() == QEvent::EnterWhatsThisMode) {
+ case QEvent::EnterWhatsThisMode:
QWhatsThis::enterWhatsThisMode();
return true;
#endif
- }
-
- if(e->type() == QEvent::LanguageChange) {
+ case QEvent::LanguageChange:
+ case QEvent::ApplicationFontChange:
+ case QEvent::ApplicationPaletteChange: {
+ // QGuiApplication::event does not account for the cases where
+ // there is a top level widget without a window handle. So they
+ // need to have the event posted here
const QWidgetList list = topLevelWidgets();
for (auto *w : list) {
- if (!(w->windowType() == Qt::Desktop))
- postEvent(w, new QEvent(QEvent::LanguageChange));
+ if (!w->windowHandle() && (w->windowType() != Qt::Desktop))
+ postEvent(w, new QEvent(e->type()));
}
+ break;
+ }
+ default:
+ break;
}
return QGuiApplication::event(e);
@@ -1939,6 +1776,7 @@ void QApplicationPrivate::notifyLayoutDirectionChange()
/*!
\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.
@@ -1955,8 +1793,15 @@ void QApplicationPrivate::notifyLayoutDirectionChange()
\sa activeWindow(), QWidget::activateWindow()
*/
+#if QT_DEPRECATED_SINCE(6,5)
void QApplication::setActiveWindow(QWidget* act)
{
+ QApplicationPrivate::setActiveWindow(act);
+}
+#endif
+
+void QApplicationPrivate::setActiveWindow(QWidget* act)
+{
QWidget* window = act?act->window():nullptr;
if (QApplicationPrivate::active_window == window)
@@ -1973,8 +1818,8 @@ void QApplication::setActiveWindow(QWidget* act)
QWidgetList toBeDeactivated;
if (QApplicationPrivate::active_window) {
- if (style()->styleHint(QStyle::SH_Widget_ShareActivation, nullptr, QApplicationPrivate::active_window)) {
- const QWidgetList list = topLevelWidgets();
+ if (QApplication::style()->styleHint(QStyle::SH_Widget_ShareActivation, nullptr, QApplicationPrivate::active_window)) {
+ const QWidgetList list = QApplication::topLevelWidgets();
for (auto *w : list) {
if (w->isVisible() && w->isActiveWindow())
toBeDeactivated.append(w);
@@ -1995,8 +1840,8 @@ void QApplication::setActiveWindow(QWidget* act)
QApplicationPrivate::active_window = window;
if (QApplicationPrivate::active_window) {
- if (style()->styleHint(QStyle::SH_Widget_ShareActivation, nullptr, QApplicationPrivate::active_window)) {
- const QWidgetList list = topLevelWidgets();
+ if (QApplication::style()->styleHint(QStyle::SH_Widget_ShareActivation, nullptr, QApplicationPrivate::active_window)) {
+ const QWidgetList list = QApplication::topLevelWidgets();
for (auto *w : list) {
if (w->isVisible() && w->isActiveWindow())
toBeActivated.append(w);
@@ -2014,14 +1859,14 @@ void QApplication::setActiveWindow(QWidget* act)
for (int i = 0; i < toBeActivated.size(); ++i) {
QWidget *w = toBeActivated.at(i);
- sendSpontaneousEvent(w, &windowActivate);
- sendSpontaneousEvent(w, &activationChange);
+ QApplication::sendSpontaneousEvent(w, &windowActivate);
+ QApplication::sendSpontaneousEvent(w, &activationChange);
}
for(int i = 0; i < toBeDeactivated.size(); ++i) {
QWidget *w = toBeDeactivated.at(i);
- sendSpontaneousEvent(w, &windowDeactivate);
- sendSpontaneousEvent(w, &activationChange);
+ QApplication::sendSpontaneousEvent(w, &windowDeactivate);
+ QApplication::sendSpontaneousEvent(w, &activationChange);
}
if (QApplicationPrivate::popupWidgets == nullptr) { // !inPopupMode()
@@ -2037,12 +1882,13 @@ void QApplication::setActiveWindow(QWidget* act)
if (w) {
w->setFocus(Qt::ActiveWindowFocusReason);
} else {
- // If the focus widget is not in the activate_window, clear the focus
w = QApplicationPrivate::focus_widget;
- if (!w && QApplicationPrivate::active_window->focusPolicy() != Qt::NoFocus)
- QApplicationPrivate::setFocusWidget(QApplicationPrivate::active_window, Qt::ActiveWindowFocusReason);
- else if (!QApplicationPrivate::active_window->isAncestorOf(w))
+ if (!w && QApplicationPrivate::active_window->focusPolicy() != Qt::NoFocus) {
+ QApplicationPrivate::active_window->setFocus(Qt::ActiveWindowFocusReason);
+ } else if (!QApplicationPrivate::active_window->isAncestorOf(w)) {
+ // If the focus widget is not in the activate_window, clear the focus
QApplicationPrivate::setFocusWidget(nullptr, Qt::ActiveWindowFocusReason);
+ }
}
}
}
@@ -2075,19 +1921,37 @@ QWidget *qt_tlw_for_window(QWindow *wnd)
void QApplicationPrivate::notifyActiveWindowChange(QWindow *previous)
{
- Q_UNUSED(previous);
- QWindow *wnd = QGuiApplicationPrivate::focus_window;
- if (inPopupMode()) // some delayed focus event to ignore
+#ifndef Q_OS_MACOS
+ // Some delayed focus event to ignore, unless we are on cocoa where
+ // popups can be opened via right-click on inactive applications
+ if (inPopupMode())
return;
- QWidget *tlw = qt_tlw_for_window(wnd);
- QApplication::setActiveWindow(tlw);
+#endif
+ QWindow *focusWindow = QGuiApplicationPrivate::focus_window;
+ QWidget *focusWidget = qt_tlw_for_window(focusWindow);
+ QApplicationPrivate::setActiveWindow(focusWidget);
// QTBUG-37126, Active X controls may set the focus on native child widgets.
- if (wnd && tlw && wnd != tlw->windowHandle()) {
- if (QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(wnd))
+ if (focusWindow && focusWidget && focusWindow != focusWidget->windowHandle()) {
+ if (QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(focusWindow))
if (QWidget *widget = widgetWindow->widget())
if (widget->inherits("QAxHostWidget"))
widget->setFocus(Qt::ActiveWindowFocusReason);
}
+
+ // QApplication::setActiveWindow() will deliver window activation events for
+ // QWidgetWindows. But for other subclasses of QWindow (like QQuickWindow), we
+ // need to send them explicitly, like we do from the base class implementation.
+ if (previous && !qobject_cast<QWidgetWindow *>(previous)) {
+ QEvent de(QEvent::WindowDeactivate);
+ QCoreApplication::sendEvent(previous, &de);
+ }
+
+ if (focusWindow && !qobject_cast<QWidgetWindow *>(focusWindow)) {
+ QEvent ae(QEvent::WindowActivate);
+ QCoreApplication::sendEvent(focusWindow, &ae);
+ }
+
+ // don't call base class to avoid double delivery of WindowActivate/Deactivate events
}
/*!internal
@@ -2105,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) {
@@ -2117,20 +1981,26 @@ QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool
// \a next). This is to ensure that we can tab in and out of compound widgets
// without getting stuck in a tab-loop between parent and child.
QWidget *focusProxy = test->d_func()->deepestFocusProxy();
-
- if ((test->focusPolicy() & focus_flag) == focus_flag
- && !(next && focusProxy && focusProxy->isAncestorOf(test))
- && !(!next && focusProxy && test->isAncestorOf(focusProxy))
+ auto effectiveFocusPolicy = [](QWidget *widget) {
+ return widget->isEnabled() ? widget->focusPolicy() : Qt::NoFocus;
+ };
+ const bool canTakeFocus = (effectiveFocusPolicy(focusProxy ? focusProxy : test)
+ & focus_flag) == focus_flag;
+ const bool composites = focusProxy ? (next ? focusProxy->isAncestorOf(test)
+ : test->isAncestorOf(focusProxy))
+ : false;
+ if (canTakeFocus && !composites
&& test->isVisibleTo(toplevel) && test->isEnabled()
&& !(w->windowType() == Qt::SubWindow && !w->isAncestorOf(test))
- && (toplevel->windowType() != Qt::SubWindow || toplevel->isAncestorOf(test))) {
+ && (toplevel->windowType() != Qt::SubWindow || toplevel->isAncestorOf(test))
+ && f != focusProxy) {
w = test;
if (seenWindow)
focusWidgetAfterWindow = true;
if (next)
break;
}
- test = test->d_func()->focus_next;
+ test = test->nextInFocusChain();
}
if (wrappingOccurred != nullptr)
@@ -2155,24 +2025,9 @@ 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;
-#ifdef ALIEN_DEBUG
- qDebug() << "QApplicationPrivate::dispatchEnterLeave, ENTER:" << enter << "LEAVE:" << leave;
-#endif
+
QWidgetList leaveList;
QWidgetList enterList;
@@ -2228,7 +2083,7 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, con
if (w->testAttribute(Qt::WA_Hover) &&
(!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
Q_ASSERT(instance());
- QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1), w->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos),
+ QHoverEvent he(QEvent::HoverLeave, QPointF(-1, -1), globalPosF, w->mapFromGlobal(globalPosF),
QGuiApplication::keyboardModifiers());
qApp->d_func()->notify_helper(w, &he);
}
@@ -2236,20 +2091,21 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, con
}
if (!enterList.isEmpty()) {
// Guard against QGuiApplicationPrivate::lastCursorPosition initialized to qInf(), qInf().
- const QPoint globalPos = qIsInf(globalPosF.x())
- ? QPoint(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)
- : globalPosF.toPoint();
- const QPoint windowPos = qAsConst(enterList).back()->window()->mapFromGlobal(globalPos);
+ const QPointF globalPos = qIsInf(globalPosF.x())
+ ? QPointF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)
+ : globalPosF;
+ const QPointF windowPos = std::as_const(enterList).back()->window()->mapFromGlobal(globalPos);
for (auto it = enterList.crbegin(), end = enterList.crend(); it != end; ++it) {
auto *w = *it;
if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, nullptr)) {
const QPointF localPos = w->mapFromGlobal(globalPos);
- QEnterEvent enterEvent(localPos, windowPos, globalPosF);
+ QEnterEvent enterEvent(localPos, windowPos, globalPos);
QCoreApplication::sendEvent(w, &enterEvent);
if (w->testAttribute(Qt::WA_Hover) &&
(!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
- QHoverEvent he(QEvent::HoverEnter, localPos, QPoint(-1, -1),
+ QHoverEvent he(QEvent::HoverEnter, windowPos, QPointF(-1, -1), globalPos,
QGuiApplication::keyboardModifiers());
+ QMutableEventPoint::setPosition(he.point(0), localPos);
qApp->d_func()->notify_helper(w, &he);
}
}
@@ -2283,7 +2139,7 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, con
if (!parentOfLeavingCursor->window()->graphicsProxyWidget())
#endif
{
- if (enter == QApplication::desktop()) {
+ if (enter == QApplicationPrivate::desktop()) {
qt_qpa_set_cursor(enter, true);
} else {
qt_qpa_set_cursor(parentOfLeavingCursor, true);
@@ -2326,107 +2182,16 @@ bool QApplicationPrivate::isBlockedByModal(QWidget *widget)
return window && self->isWindowBlocked(window);
}
-bool QApplicationPrivate::isWindowBlocked(QWindow *window, QWindow **blockingWindow) const
+Qt::WindowModality QApplicationPrivate::defaultModality() const
{
- QWindow *unused = nullptr;
- if (Q_UNLIKELY(!window)) {
- qWarning().nospace() << "window == 0 passed.";
- return false;
- }
- if (!blockingWindow)
- blockingWindow = &unused;
+ return Qt::ApplicationModal;
+}
- if (modalWindowList.isEmpty()) {
- *blockingWindow = nullptr;
- return false;
- }
+bool QApplicationPrivate::windowNeverBlocked(QWindow *window) const
+{
QWidget *popupWidget = QApplication::activePopupWidget();
QWindow *popupWindow = popupWidget ? popupWidget->windowHandle() : nullptr;
- if (popupWindow == window || (!popupWindow && QWindowPrivate::get(window)->isPopup())) {
- *blockingWindow = nullptr;
- return false;
- }
-
- for (int i = 0; i < modalWindowList.count(); ++i) {
- QWindow *modalWindow = modalWindowList.at(i);
-
- // A window is not blocked by another modal window if the two are
- // the same, or if the window is a child of the modal window.
- if (window == modalWindow || modalWindow->isAncestorOf(window, QWindow::IncludeTransients)) {
- *blockingWindow = nullptr;
- return false;
- }
-
- Qt::WindowModality windowModality = modalWindow->modality();
- QWidgetWindow *modalWidgetWindow = qobject_cast<QWidgetWindow *>(modalWindow);
- if (windowModality == Qt::NonModal) {
- // determine the modality type if it hasn't been set on the
- // modalWindow's widget, this normally happens when waiting for a
- // native dialog. use WindowModal if we are the child of a group
- // leader; otherwise use ApplicationModal.
- QWidget *m = modalWidgetWindow ? modalWidgetWindow->widget() : nullptr;
- while (m && !m->testAttribute(Qt::WA_GroupLeader)) {
- m = m->parentWidget();
- if (m)
- m = m->window();
- }
- windowModality = (m && m->testAttribute(Qt::WA_GroupLeader))
- ? Qt::WindowModal
- : Qt::ApplicationModal;
- }
-
- switch (windowModality) {
- case Qt::ApplicationModal:
- {
- QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(window);
- QWidget *groupLeaderForWidget = widgetWindow ? widgetWindow->widget() : nullptr;
- while (groupLeaderForWidget && !groupLeaderForWidget->testAttribute(Qt::WA_GroupLeader))
- groupLeaderForWidget = groupLeaderForWidget->parentWidget();
-
- if (groupLeaderForWidget) {
- // if \a widget has WA_GroupLeader, it can only be blocked by ApplicationModal children
- QWidget *m = modalWidgetWindow ? modalWidgetWindow->widget() : nullptr;
- while (m && m != groupLeaderForWidget && !m->testAttribute(Qt::WA_GroupLeader))
- m = m->parentWidget();
- if (m == groupLeaderForWidget) {
- *blockingWindow = m->windowHandle();
- return true;
- }
- } else if (modalWindow != window) {
- *blockingWindow = modalWindow;
- return true;
- }
- break;
- }
- case Qt::WindowModal:
- {
- QWindow *w = window;
- do {
- QWindow *m = modalWindow;
- do {
- if (m == w) {
- *blockingWindow = m;
- return true;
- }
- QWindow *p = m->parent();
- if (!p)
- p = m->transientParent();
- m = p;
- } while (m);
- QWindow *p = w->parent();
- if (!p)
- p = w->transientParent();
- w = p;
- } while (w);
- break;
- }
- default:
- Q_ASSERT_X(false, "QApplication", "internal error, a modal window cannot be modeless");
- break;
- }
- }
- *blockingWindow = nullptr;
- return false;
+ return popupWindow == window || (!popupWindow && QWindowPrivate::get(window)->isPopup());
}
/*!\internal
@@ -2457,12 +2222,6 @@ bool qt_try_modal(QWidget *widget, QEvent::Type type)
bool block_event = false;
switch (type) {
-#if 0
- case QEvent::Focus:
- if (!static_cast<QWSFocusEvent*>(event)->simpleData.get_focus)
- break;
- // drop through
-#endif
case QEvent::MouseButtonPress: // disallow mouse/key events
case QEvent::MouseButtonRelease:
case QEvent::MouseMove:
@@ -2512,9 +2271,6 @@ QWidget *QApplicationPrivate::pickMouseReceiver(QWidget *candidate, const QPoint
if (mouseGrabber && mouseGrabber != candidate) {
receiver = mouseGrabber;
*pos = receiver->mapFromGlobal(candidate->mapToGlobal(windowPos));
-#ifdef ALIEN_DEBUG
- qDebug() << " ** receiver adjusted to:" << receiver << "pos:" << pos;
-#endif
}
return receiver;
@@ -2544,7 +2300,7 @@ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
const bool graphicsWidget = nativeWidget->testAttribute(Qt::WA_DontShowOnScreen);
- bool widgetUnderMouse = QRectF(receiver->rect()).contains(event->localPos());
+ bool widgetUnderMouse = QRectF(receiver->rect()).contains(event->position());
// Clear the obsolete leaveAfterRelease value, if mouse button has been released but
// leaveAfterRelease has not been updated.
@@ -2570,21 +2326,14 @@ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
|| (isAlien(lastMouseReceiver) && !alienWidget)) {
if (activePopupWidget) {
if (!QWidget::mouseGrabber())
- dispatchEnterLeave(alienWidget ? alienWidget : nativeWidget, lastMouseReceiver, event->screenPos());
+ dispatchEnterLeave(alienWidget ? alienWidget : nativeWidget, lastMouseReceiver, event->globalPosition());
} else {
- dispatchEnterLeave(receiver, lastMouseReceiver, event->screenPos());
+ dispatchEnterLeave(receiver, lastMouseReceiver, event->globalPosition());
}
}
}
-#ifdef ALIEN_DEBUG
- qDebug() << "QApplicationPrivate::sendMouseEvent: receiver:" << receiver
- << "pos:" << event->pos() << "alien" << alienWidget << "button down"
- << *buttonDown << "last" << lastMouseReceiver << "leave after release"
- << leaveAfterRelease;
-#endif
-
// We need this quard in case someone opens a modal dialog / popup. If that's the case
// leaveAfterRelease is set to null, but we shall not update lastMouseReceiver.
const bool wasLeaveAfterRelease = leaveAfterRelease != nullptr;
@@ -2609,8 +2358,8 @@ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
if (nativeGuard)
enter = alienGuard ? alienWidget : nativeWidget;
else // The receiver is typically deleted on mouse release with drag'n'drop.
- enter = QApplication::widgetAt(event->globalPos());
- dispatchEnterLeave(enter, leaveAfterRelease, event->screenPos());
+ enter = QApplication::widgetAt(event->globalPosition().toPoint());
+ dispatchEnterLeave(enter, leaveAfterRelease, event->globalPosition());
leaveAfterRelease = nullptr;
lastMouseReceiver = enter;
} else if (!wasLeaveAfterRelease) {
@@ -2618,7 +2367,7 @@ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
if (!QWidget::mouseGrabber())
lastMouseReceiver = alienGuard ? alienWidget : (nativeGuard ? nativeWidget : nullptr);
} else {
- lastMouseReceiver = receiverGuard ? receiver : QApplication::widgetAt(event->globalPos());
+ lastMouseReceiver = receiverGuard ? receiver : QApplication::widgetAt(event->globalPosition().toPoint());
}
}
@@ -2629,7 +2378,7 @@ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
This function should only be called when the widget changes visibility, i.e.
when the \a widget is shown, hidden or deleted. This function does nothing
if the widget is a top-level or native, i.e. not an alien widget. In that
- case enter/leave events are genereated by the underlying windowing system.
+ case enter/leave events are generated by the underlying windowing system.
*/
extern QPointer<QWidget> qt_last_mouse_receiver;
extern Q_WIDGETS_EXPORT QWidget *qt_button_down;
@@ -2643,7 +2392,7 @@ void QApplicationPrivate::sendSyntheticEnterLeave(QWidget *widget)
return; // Widget was not under the cursor when it was hidden/deleted.
if (widgetInShow && widget->parentWidget()->data->in_show)
- return; // Ingore recursive show.
+ return; // Ignore recursive show.
QWidget *mouseGrabber = QWidget::mouseGrabber();
if (mouseGrabber && mouseGrabber != widget)
@@ -2683,22 +2432,19 @@ void QApplicationPrivate::sendSyntheticEnterLeave(QWidget *widget)
}
/*!
- Returns the desktop widget (also called the root window).
+ \internal
- The desktop may be composed of multiple screens, so it would be incorrect,
- for example, to attempt to \e center some widget in the desktop's geometry.
- QDesktopWidget has various functions for obtaining useful geometries upon
- the desktop, such as QDesktopWidget::screenGeometry() and
- QDesktopWidget::availableGeometry().
+ Returns the desktop widget (also called the root window).
- On X11, it is also possible to draw on the desktop.
+ The widget represents the entire virtual desktop, and its geometry will
+ be the union of all screens.
*/
-QDesktopWidget *QApplication::desktop()
+QWidget *QApplicationPrivate::desktop()
{
CHECK_QAPP_INSTANCE(nullptr)
if (!qt_desktopWidget || // not created yet
!(qt_desktopWidget->windowType() == Qt::Desktop)) { // reparented away
- qt_desktopWidget = new QDesktopWidget();
+ qt_desktopWidget = new QWidget(nullptr, Qt::Desktop);
}
return qt_desktopWidget;
}
@@ -2728,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()
@@ -2749,6 +2495,7 @@ void QApplication::setStartDragDistance(int l)
/*!
\property QApplication::startDragDistance
+ \brief the minimum distance required for a drag and drop operation to start.
If you support drag and drop in your application, and want to start a drag
and drop operation after the user has moved the cursor a certain distance
@@ -2766,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()
@@ -2788,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
@@ -2808,34 +2556,6 @@ int QApplication::exec()
return QGuiApplication::exec();
}
-bool QApplicationPrivate::shouldQuit()
-{
- /* if there is no non-withdrawn primary window left (except
- the ones without QuitOnClose), we emit the lastWindowClosed
- signal */
- QWidgetList list = QApplication::topLevelWidgets();
- QWindowList processedWindows;
- for (int i = 0; i < list.size(); ++i) {
- QWidget *w = list.at(i);
- if (QWindow *window = w->windowHandle()) { // Menus, popup widgets may not have a QWindow
- processedWindows.push_back(window);
- if (w->isVisible() && !w->parentWidget() && w->testAttribute(Qt::WA_QuitOnClose))
- return false;
- }
- }
- return QGuiApplicationPrivate::shouldQuitInternal(processedWindows);
-}
-
-static inline void closeAllPopups()
-{
- // Close all popups: In case some popup refuses to close,
- // we give up after 1024 attempts (to avoid an infinite loop).
- int maxiter = 1024;
- QWidget *popup;
- while ((popup = QApplication::activePopupWidget()) && maxiter--)
- popup->close();
-}
-
/*! \reimp
*/
bool QApplication::notify(QObject *receiver, QEvent *e)
@@ -2854,64 +2574,14 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
QCoreApplicationPrivate::checkReceiverThread(receiver);
#endif
- if (receiver->isWindowType()) {
- if (QGuiApplicationPrivate::sendQWindowEventToQPlatformWindow(static_cast<QWindow *>(receiver), e))
- return true; // Platform plugin ate the event
+ const bool isWindowType = receiver->isWindowType();
+ const bool isWidgetType = receiver->isWidgetType();
+ if (isWindowType
+ && QGuiApplicationPrivate::sendQWindowEventToQPlatformWindow(static_cast<QWindow *>(receiver), e)) {
+ return true; // Platform plugin ate the event
}
- if(e->spontaneous()) {
- // Capture the current mouse and keyboard states. Doing so here is
- // required in order to support Qt Test synthesized events. Real mouse
- // and keyboard state updates from the platform plugin are managed by
- // QGuiApplicationPrivate::process(Mouse|Wheel|Key|Touch|Tablet)Event();
- // ### FIXME: Qt Test should not call qapp->notify(), but rather route
- // the events through the proper QPA interface. This is required to
- // properly generate all other events such as enter/leave etc.
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- {
- QMouseEvent *me = static_cast<QMouseEvent*>(e);
- QApplicationPrivate::modifier_buttons = me->modifiers();
- QApplicationPrivate::mouse_buttons |= me->button();
- break;
- }
- case QEvent::MouseButtonDblClick:
- {
- QMouseEvent *me = static_cast<QMouseEvent*>(e);
- QApplicationPrivate::modifier_buttons = me->modifiers();
- QApplicationPrivate::mouse_buttons |= me->button();
- break;
- }
- case QEvent::MouseButtonRelease:
- {
- QMouseEvent *me = static_cast<QMouseEvent*>(e);
- QApplicationPrivate::modifier_buttons = me->modifiers();
- QApplicationPrivate::mouse_buttons &= ~me->button();
- break;
- }
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- case QEvent::MouseMove:
-#if QT_CONFIG(wheelevent)
- case QEvent::Wheel:
-#endif
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
-#if QT_CONFIG(tabletevent)
- case QEvent::TabletMove:
- case QEvent::TabletPress:
- case QEvent::TabletRelease:
-#endif
- {
- QInputEvent *ie = static_cast<QInputEvent*>(e);
- QApplicationPrivate::modifier_buttons = ie->modifiers();
- break;
- }
- default:
- break;
- }
- }
+ QGuiApplicationPrivate::captureGlobalModifierState(e);
#ifndef QT_NO_GESTURES
// walk through parents and check for gestures
@@ -2939,7 +2609,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
break;
default:
if (d->gestureManager->thread() == QThread::currentThread()) {
- if (receiver->isWidgetType()) {
+ if (isWidgetType) {
if (d->gestureManager->filterEvent(static_cast<QWidget *>(receiver), e))
return true;
} else {
@@ -2957,9 +2627,11 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
switch (e->type()) {
case QEvent::ApplicationDeactivate:
+ case QEvent::OrientationChange:
// Close all popups (triggers when switching applications
// by pressing ALT-TAB on Windows, which is not receive as key event.
- closeAllPopups();
+ // triggers when the screen rotates.)
+ d->closeAllPopups();
break;
case QEvent::Wheel: // User input and window activation makes tooltips sleep
case QEvent::ActivationChange:
@@ -2974,108 +2646,89 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
Q_FALLTHROUGH();
case QEvent::Leave:
d->toolTipWakeUp.stop();
+ break;
default:
break;
}
switch (e->type()) {
- case QEvent::KeyPress: {
- QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
- const int key = keyEvent->key();
- // When a key press is received which is not spontaneous then it needs to
- // be manually sent as a shortcut override event to ensure that any
- // matching shortcut is triggered first. This enables emulation/playback
- // of recorded events to still have the same effect.
- if (!e->spontaneous() && receiver->isWidgetType()) {
- if (qt_sendShortcutOverrideEvent(qobject_cast<QWidget *>(receiver), keyEvent->timestamp(),
- key, keyEvent->modifiers(), keyEvent->text(),
- keyEvent->isAutoRepeat(), keyEvent->count()))
- return true;
- }
- qt_in_tab_key_event = (key == Qt::Key_Backtab
- || key == Qt::Key_Tab
- || key == Qt::Key_Left
- || key == Qt::Key_Up
- || key == Qt::Key_Right
- || key == Qt::Key_Down);
+ case QEvent::KeyPress: {
+ QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
+ const int key = keyEvent->key();
+ // When a key press is received which is not spontaneous then it needs to
+ // be manually sent as a shortcut override event to ensure that any
+ // matching shortcut is triggered first. This enables emulation/playback
+ // of recorded events to still have the same effect.
+ if (!e->spontaneous() && isWidgetType
+ && qt_sendShortcutOverrideEvent(static_cast<QWidget *>(receiver), keyEvent->timestamp(),
+ key, keyEvent->modifiers(), keyEvent->text(),
+ keyEvent->isAutoRepeat(), keyEvent->count())) {
+ return true;
}
- default:
- break;
+ qt_in_tab_key_event = (key == Qt::Key_Backtab
+ || key == Qt::Key_Tab
+ || key == Qt::Key_Left
+ || key == Qt::Key_Up
+ || key == Qt::Key_Right
+ || key == Qt::Key_Down);
+ break;
+ }
+ default:
+ break;
}
bool res = false;
- if (!receiver->isWidgetType()) {
- res = d->notify_helper(receiver, e);
- } else switch (e->type()) {
- case QEvent::ShortcutOverride:
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- {
- bool isWidget = receiver->isWidgetType();
-#if QT_CONFIG(graphicsview)
- const bool isGraphicsWidget = !isWidget && qobject_cast<QGraphicsWidget *>(receiver);
-#endif
+ if (isWidgetType) {
+ QWidget * w = static_cast<QWidget *>(receiver);
+ switch (e->type()) {
+ case QEvent::ShortcutOverride:
+ case QEvent::KeyPress:
+ case QEvent::KeyRelease: {
QKeyEvent* key = static_cast<QKeyEvent*>(e);
bool def = key->isAccepted();
+ /*
+ QLineEdit will emit a signal on Key_Return, but
+ ignore the event, and sometimes the connected
+ slot deletes the QLineEdit (common in itemview
+ delegates), so we have to check if the widget
+ was destroyed even if the event was ignored (to
+ prevent a crash)
+
+ Note that we don't have to reset pr while
+ propagating (because the original receiver will
+ be destroyed if one of its ancestors is)
+ */
QPointer<QObject> pr = receiver;
- while (receiver) {
+ while (w) {
if (def)
key->accept();
else
key->ignore();
- QWidget *w = isWidget ? static_cast<QWidget *>(receiver) : nullptr;
-#if QT_CONFIG(graphicsview)
- QGraphicsWidget *gw = isGraphicsWidget ? static_cast<QGraphicsWidget *>(receiver) : nullptr;
-#endif
- res = d->notify_helper(receiver, e);
-
- if ((res && key->isAccepted())
- /*
- QLineEdit will emit a signal on Key_Return, but
- ignore the event, and sometimes the connected
- slot deletes the QLineEdit (common in itemview
- delegates), so we have to check if the widget
- was destroyed even if the event was ignored (to
- prevent a crash)
-
- note that we don't have to reset pw while
- propagating (because the original receiver will
- be destroyed if one of its ancestors is)
- */
- || !pr
- || (isWidget && (w->isWindow() || !w->parentWidget()))
-#if QT_CONFIG(graphicsview)
- || (isGraphicsWidget && (gw->isWindow() || !gw->parentWidget()))
-#endif
- ) {
+ res = d->notify_helper(w, e);
+
+ if (res && key->isAccepted())
+ break;
+ if (!pr || w->isWindow())
break;
- }
-#if QT_CONFIG(graphicsview)
- receiver = w ? (QObject *)w->parentWidget() : (QObject *)gw->parentWidget();
-#else
- receiver = w->parentWidget();
-#endif
+ w = w->parentWidget();
}
qt_in_tab_key_event = false;
+ break;
}
- break;
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- {
- QWidget* w = static_cast<QWidget *>(receiver);
-
+ case QEvent::MouseButtonPress:
+ case QEvent::MouseButtonRelease:
+ case QEvent::MouseButtonDblClick:
+ case QEvent::MouseMove: {
QMouseEvent* mouse = static_cast<QMouseEvent*>(e);
- QPoint relpos = mouse->pos();
+ QPoint relpos = mouse->position().toPoint();
if (e->spontaneous()) {
if (e->type() != QEvent::MouseMove)
QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, relpos);
- // ### Qt 5 These dynamic tool tips should be an OPT-IN feature. Some platforms
- // like OS X (probably others too), can optimize their views by not
+ // ### Qt 7 These dynamic tool tips should be an OPT-IN feature. Some platforms
+ // like macOS (probably others too), can optimize their views by not
// dispatching mouse move events. We have attributes to control hover,
// and mouse tracking, but as long as we are deciding to implement this
// feature without choice of opting-in or out, you ALWAYS have to have
@@ -3085,7 +2738,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
&& w->rect().contains(relpos)) { // Outside due to mouse grab?
d->toolTipWidget = w;
d->toolTipPos = relpos;
- d->toolTipGlobalPos = mouse->globalPos();
+ d->toolTipGlobalPos = mouse->globalPosition().toPoint();
QStyle *s = d->toolTipWidget->style();
int wakeDelay = s->styleHint(QStyle::SH_ToolTip_WakeUpDelay, nullptr, d->toolTipWidget, nullptr);
d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive() ? 20 : wakeDelay, this);
@@ -3096,11 +2749,12 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
QPointer<QWidget> pw = w;
while (w) {
- QMouseEvent me(mouse->type(), relpos, mouse->windowPos(), mouse->globalPos(),
- mouse->button(), mouse->buttons(), mouse->modifiers(), mouse->source());
- me.spont = mouse->spontaneous();
+ QMouseEvent me(mouse->type(), relpos, mouse->scenePosition(), mouse->globalPosition().toPoint(),
+ mouse->button(), mouse->buttons(), mouse->modifiers(), mouse->source(),
+ mouse->pointingDevice());
+ me.m_spont = mouse->spontaneous();
me.setTimestamp(mouse->timestamp());
- QGuiApplicationPrivate::setMouseEventFlags(&me, mouse->flags());
+ QMutableSinglePointEvent::from(me).setDoubleClick(QMutableSinglePointEvent::from(mouse)->isDoubleClick());
// throw away any mouse-tracking-only mouse events
if (!w->hasMouseTracking()
&& mouse->type() == QEvent::MouseMove && mouse->buttons() == 0) {
@@ -3110,7 +2764,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
} else {
w->setAttribute(Qt::WA_NoMouseReplay, false);
res = d->notify_helper(w, w == receiver ? mouse : &me);
- e->spont = false;
+ e->m_spont = false;
}
eventAccepted = (w == receiver ? mouse : &me)->isAccepted();
if (res && eventAccepted)
@@ -3128,12 +2782,13 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
break;
w = static_cast<QWidget *>(receiver);
- relpos = mouse->pos();
- QPoint diff = relpos - w->mapFromGlobal(d->hoverGlobalPos);
+ relpos = mouse->position().toPoint();
+ QPoint diff = relpos - w->mapFromGlobal(mouse->globalPosition().toPoint());
while (w) {
if (w->testAttribute(Qt::WA_Hover) &&
(!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
- QHoverEvent he(QEvent::HoverMove, relpos, relpos - diff, mouse->modifiers());
+ QHoverEvent he(QEvent::HoverMove, mouse->scenePosition(), mouse->globalPosition(), relpos - diff, mouse->modifiers());
+ QMutableEventPoint::setPosition(he.point(0), relpos);
d->notify_helper(w, &he);
}
if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
@@ -3143,14 +2798,11 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
}
}
- d->hoverGlobalPos = mouse->globalPos();
+ d->hoverGlobalPos = mouse->globalPosition().toPoint();
+ break;
}
- break;
#if QT_CONFIG(wheelevent)
- case QEvent::Wheel:
- {
- QWidget* w = static_cast<QWidget *>(receiver);
-
+ case QEvent::Wheel: {
// QTBUG-40656, QTBUG-42731: ignore wheel events when a popup (QComboBox) is open.
if (const QWidget *popup = QApplication::activePopupWidget()) {
if (w->window() != popup)
@@ -3158,8 +2810,18 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
}
QWheelEvent* wheel = static_cast<QWheelEvent*>(e);
- const bool spontaneous = wheel->spontaneous();
+ if (!wheel->spontaneous()) {
+ /*
+ Synthesized events shouldn't propagate, e.g. QScrollArea passes events from the
+ viewport on to the scrollbars, which might ignore the event if there is no more
+ space to scroll. If we would propagate, the event would come back to the viewport.
+ */
+ res = d->notify_helper(w, wheel);
+ break;
+ }
+
const Qt::ScrollPhase phase = wheel->phase();
+ QPoint relpos = wheel->position().toPoint();
// Ideally, we should lock on a widget when it starts receiving wheel
// events. This avoids other widgets to start receiving those events
@@ -3176,192 +2838,160 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
//
// We assume that, when supported, the phase cycle follows the pattern:
//
- // ScrollBegin (ScrollUpdate* ScrollEnd)+
+ // ScrollBegin (ScrollUpdate* ScrollMomentum* ScrollEnd)+
//
// This means that we can have scrolling sequences (starting with ScrollBegin)
// or partial sequences (after a ScrollEnd and starting with ScrollUpdate).
- // If wheel_widget is null because it was deleted, we also take the same
- // code path as an initial sequence.
- if (phase == Qt::NoScrollPhase || phase == Qt::ScrollBegin || !QApplicationPrivate::wheel_widget) {
- // A system-generated ScrollBegin event starts a new user scrolling
- // sequence, so we reset wheel_widget in case no one accepts the event
- // or if we didn't get (or missed) a ScrollEnd previously.
- if (spontaneous && phase == Qt::ScrollBegin)
- QApplicationPrivate::wheel_widget = nullptr;
+ // a widget has already grabbed the wheel for a sequence
+ if (QApplicationPrivate::wheel_widget) {
+ Q_ASSERT(phase != Qt::NoScrollPhase);
+ w = QApplicationPrivate::wheel_widget;
+ relpos = w->mapFromGlobal(wheel->globalPosition().toPoint());
+ }
+ /*
+ Start or finish a scrolling sequence by grabbing/releasing the wheel via
+ wheel_widget. The sequence might be partial (ie. not start with ScrollBegin),
+ e.g. if the previous wheel_widget was destroyed mid-sequence.
+ */
+ switch (phase) {
+ case Qt::ScrollEnd:
+ QApplicationPrivate::wheel_widget = nullptr;
+ break;
+ case Qt::ScrollBegin:
+ QApplicationPrivate::wheel_widget = w;
+ Q_FALLTHROUGH();
+ case Qt::ScrollUpdate:
+ case Qt::ScrollMomentum:
+ if (!QApplicationPrivate::wheel_widget)
+ QApplicationPrivate::wheel_widget = w;
+ Q_FALLTHROUGH();
+ case Qt::NoScrollPhase:
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, relpos);
+ break;
+ // no default: - we want warnings if we don't handle all phases explicitly
+ }
- QPoint relpos = wheel->position().toPoint();
+ QWheelEvent we(relpos, wheel->globalPosition(), wheel->pixelDelta(), wheel->angleDelta(), wheel->buttons(),
+ wheel->modifiers(), phase, wheel->inverted(), wheel->source(), wheel->pointingDevice());
- if (spontaneous && (phase == Qt::NoScrollPhase || phase == Qt::ScrollUpdate))
- QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, relpos);
-
-#if QT_DEPRECATED_SINCE(5, 14)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- QWheelEvent we(relpos, wheel->globalPos(), wheel->pixelDelta(), wheel->angleDelta(), wheel->delta(), wheel->orientation(), wheel->buttons(),
- wheel->modifiers(), phase, wheel->source(), wheel->inverted());
-QT_WARNING_POP
-#else
- QWheelEvent we(relpos, wheel->globalPosition(), wheel->pixelDelta(), wheel->angleDelta(), wheel->buttons(),
- wheel->modifiers(), phase, wheel->inverted(), wheel->source());
-#endif
- we.setTimestamp(wheel->timestamp());
- bool eventAccepted;
- do {
- we.spont = spontaneous && w == receiver;
- we.ignore();
- res = d->notify_helper(w, &we);
- eventAccepted = we.isAccepted();
- if (res && eventAccepted) {
- // A new scrolling sequence or partial sequence starts and w has accepted
- // the event. Therefore, we can set wheel_widget, but only if it's not
- // the end of a sequence.
- if (spontaneous && (phase == Qt::ScrollBegin || phase == Qt::ScrollUpdate))
- QApplicationPrivate::wheel_widget = w;
- break;
- }
- if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
- break;
+ we.setTimestamp(wheel->timestamp());
+ bool eventAccepted;
+ do {
+ // events are delivered as accepted and ignored by the default event handler
+ // since we always send the same QWheelEvent object, we need to reset the accepted state
+ we.setAccepted(true);
+ we.m_spont = wheel->spontaneous() && w == receiver;
+ res = d->notify_helper(w, &we);
+ eventAccepted = we.isAccepted();
+ if (res && eventAccepted)
+ break;
+ if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
+ break;
- we.p += w->pos();
- w = w->parentWidget();
- } while (w);
- wheel->setAccepted(eventAccepted);
- } else if (!spontaneous) {
- // wheel_widget may forward the wheel event to a delegate widget,
- // either directly or indirectly (e.g. QAbstractScrollArea will
- // forward to its QScrollBars through viewportEvent()). In that
- // case, the event will not be spontaneous but synthesized, so
- // we can send it straight to the receiver.
- d->notify_helper(w, wheel);
- } else {
- // The phase is either ScrollUpdate or ScrollEnd, and wheel_widget
- // is set. Since it accepted the wheel event previously, we continue
- // sending those events until we get a ScrollEnd, which signifies
- // the end of the natural scrolling sequence.
- const QPoint &relpos = QApplicationPrivate::wheel_widget->mapFromGlobal(wheel->globalPosition().toPoint());
-#if QT_DEPRECATED_SINCE(5, 0)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- QWheelEvent we(relpos, wheel->globalPos(), wheel->pixelDelta(), wheel->angleDelta(), wheel->delta(), wheel->orientation(), wheel->buttons(),
- wheel->modifiers(), wheel->phase(), wheel->source());
-QT_WARNING_POP
-#else
- QWheelEvent we(relpos, wheel->globalPosition(), wheel->pixelDelta(), wheel->angleDelta(), wheel->buttons(),
- wheel->modifiers(), wheel->phase(), wheel->inverted(), wheel->source());
-#endif
- we.setTimestamp(wheel->timestamp());
- we.spont = true;
- we.ignore();
- d->notify_helper(QApplicationPrivate::wheel_widget, &we);
- wheel->setAccepted(we.isAccepted());
- if (phase == Qt::ScrollEnd)
- QApplicationPrivate::wheel_widget = nullptr;
- }
+ QMutableEventPoint::setPosition(we.point(0), we.position() + w->pos());
+ w = w->parentWidget();
+ } while (w);
+ wheel->setAccepted(eventAccepted);
+ break;
}
- break;
#endif
#ifndef QT_NO_CONTEXTMENU
- case QEvent::ContextMenu:
- {
- QWidget* w = static_cast<QWidget *>(receiver);
+ case QEvent::ContextMenu: {
QContextMenuEvent *context = static_cast<QContextMenuEvent*>(e);
QPoint relpos = context->pos();
bool eventAccepted = context->isAccepted();
while (w) {
QContextMenuEvent ce(context->reason(), relpos, context->globalPos(), context->modifiers());
- ce.spont = e->spontaneous();
+ ce.m_spont = e->spontaneous();
res = d->notify_helper(w, w == receiver ? context : &ce);
eventAccepted = ((w == receiver) ? context : &ce)->isAccepted();
- e->spont = false;
+ e->m_spont = false;
- if ((res && eventAccepted)
- || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
+ if (res && eventAccepted)
+ break;
+ if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
break;
relpos += w->pos();
w = w->parentWidget();
}
context->setAccepted(eventAccepted);
+ break;
}
- break;
#endif // QT_NO_CONTEXTMENU
#if QT_CONFIG(tabletevent)
- case QEvent::TabletMove:
- case QEvent::TabletPress:
- case QEvent::TabletRelease:
- {
- QWidget *w = static_cast<QWidget *>(receiver);
+ case QEvent::TabletMove:
+ case QEvent::TabletPress:
+ case QEvent::TabletRelease: {
QTabletEvent *tablet = static_cast<QTabletEvent*>(e);
- QPointF relpos = tablet->posF();
+ QPointF relpos = tablet->position();
bool eventAccepted = tablet->isAccepted();
while (w) {
- QTabletEvent te(tablet->type(), relpos, tablet->globalPosF(),
- tablet->device(), tablet->pointerType(),
+ QTabletEvent te(tablet->type(), tablet->pointingDevice(), relpos, tablet->globalPosition(),
tablet->pressure(), tablet->xTilt(), tablet->yTilt(),
tablet->tangentialPressure(), tablet->rotation(), tablet->z(),
- tablet->modifiers(), tablet->uniqueId(), tablet->button(), tablet->buttons());
- te.spont = e->spontaneous();
+ 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();
- e->spont = false;
- if ((res && eventAccepted)
- || w->isWindow()
- || w->testAttribute(Qt::WA_NoMousePropagation))
+ e->m_spont = false;
+ if (res && eventAccepted)
+ break;
+ if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
break;
relpos += w->pos();
w = w->parentWidget();
}
tablet->setAccepted(eventAccepted);
+ break;
}
- break;
#endif // QT_CONFIG(tabletevent)
-#if !defined(QT_NO_TOOLTIP) || QT_CONFIG(whatsthis)
- case QEvent::ToolTip:
- case QEvent::WhatsThis:
- case QEvent::QueryWhatsThis:
- {
- QWidget* w = static_cast<QWidget *>(receiver);
+#if QT_CONFIG(tooltip) || QT_CONFIG(whatsthis)
+ case QEvent::ToolTip:
+ case QEvent::WhatsThis:
+ case QEvent::QueryWhatsThis: {
QHelpEvent *help = static_cast<QHelpEvent*>(e);
QPoint relpos = help->pos();
bool eventAccepted = help->isAccepted();
while (w) {
QHelpEvent he(help->type(), relpos, help->globalPos());
- he.spont = e->spontaneous();
+ he.m_spont = e->spontaneous();
res = d->notify_helper(w, w == receiver ? help : &he);
- e->spont = false;
+ e->m_spont = false;
eventAccepted = (w == receiver ? help : &he)->isAccepted();
- if ((res && eventAccepted) || w->isWindow())
+ if (res && eventAccepted)
+ break;
+ if (w->isWindow())
break;
relpos += w->pos();
w = w->parentWidget();
}
help->setAccepted(eventAccepted);
+ break;
}
- break;
#endif
#if QT_CONFIG(statustip) || QT_CONFIG(whatsthis)
- case QEvent::StatusTip:
- case QEvent::WhatsThisClicked:
- {
- QWidget *w = static_cast<QWidget *>(receiver);
+ case QEvent::StatusTip:
+ case QEvent::WhatsThisClicked:
while (w) {
res = d->notify_helper(w, e);
- if ((res && e->isAccepted()) || w->isWindow())
+ if (res && e->isAccepted())
+ break;
+ if (w->isWindow())
break;
w = w->parentWidget();
}
- }
- break;
+ break;
#endif
#if QT_CONFIG(draganddrop)
- case QEvent::DragEnter: {
- QWidget* w = static_cast<QWidget *>(receiver);
+ case QEvent::DragEnter: {
QDragEnterEvent *dragEvent = static_cast<QDragEnterEvent *>(e);
#if QT_CONFIG(graphicsview)
// QGraphicsProxyWidget handles its own propagation,
@@ -3382,15 +3012,14 @@ QT_WARNING_POP
}
if (w->isWindow())
break;
- dragEvent->p = w->mapToParent(dragEvent->p.toPoint());
+ dragEvent->m_pos = w->mapToParent(dragEvent->m_pos);
w = w->parentWidget();
}
+ break;
}
- break;
- case QEvent::DragMove:
- case QEvent::Drop:
- case QEvent::DragLeave: {
- QWidget* w = static_cast<QWidget *>(receiver);
+ case QEvent::DragMove:
+ case QEvent::Drop:
+ case QEvent::DragLeave: {
#if QT_CONFIG(graphicsview)
// QGraphicsProxyWidget handles its own propagation,
// and we must not change QDragManagers currentTarget.
@@ -3401,14 +3030,21 @@ QT_WARNING_POP
w = qobject_cast<QWidget *>(QDragManager::self()->currentTarget());
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 *origReciver = static_cast<QWidget *>(receiver);
- while (origReciver && w != origReciver) {
- dragEvent->p = origReciver->mapToParent(dragEvent->p.toPoint());
- origReciver = origReciver->parentWidget();
+ QWidget *origReceiver = static_cast<QWidget *>(receiver);
+ while (origReceiver && w != origReceiver) {
+ dragEvent->m_pos = origReceiver->mapToParent(dragEvent->m_pos);
+ origReceiver = origReceiver->parentWidget();
}
}
res = d->notify_helper(w, e);
@@ -3418,111 +3054,101 @@ QT_WARNING_POP
#endif
)
QDragManager::self()->setCurrentTarget(nullptr, e->type() == QEvent::Drop);
+ break;
}
- break;
-#endif
- case QEvent::TouchBegin:
- // Note: TouchUpdate and TouchEnd events are never propagated
- {
- QWidget *widget = static_cast<QWidget *>(receiver);
- QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
- bool eventAccepted = touchEvent->isAccepted();
- bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
-
- if (acceptTouchEvents && e->spontaneous()) {
- const QPoint localPos = touchEvent->touchPoints()[0].pos().toPoint();
- QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget, e, localPos);
- }
+#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()
+ && touchEvent->device()->type() != QInputDevice::DeviceType::TouchPad) {
+ const QPoint localPos = touchEvent->points()[0].position().toPoint();
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, localPos);
+ }
#ifndef QT_NO_GESTURES
- QPointer<QWidget> gesturePendingWidget;
+ QPointer<QWidget> gesturePendingWidget;
#endif
- while (widget) {
- // first, try to deliver the touch event
- acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
- touchEvent->setTarget(widget);
- touchEvent->setAccepted(acceptTouchEvents);
- QPointer<QWidget> p = widget;
- res = acceptTouchEvents && d->notify_helper(widget, touchEvent);
- eventAccepted = touchEvent->isAccepted();
- if (p.isNull()) {
- // widget was deleted
- widget = nullptr;
- } else {
- widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted);
- }
- touchEvent->spont = false;
- if (res && eventAccepted) {
- // the first widget to accept the TouchBegin gets an implicit grab.
- d->activateImplicitTouchGrab(widget, touchEvent);
- break;
- }
+ while (w) {
+ // first, try to deliver the touch event
+ acceptTouchEvents = w->testAttribute(Qt::WA_AcceptTouchEvents);
+ touchEvent->setTarget(w);
+ touchEvent->setAccepted(acceptTouchEvents);
+ QPointer<QWidget> p = w;
+ res = acceptTouchEvents && d->notify_helper(w, touchEvent);
+ eventAccepted = touchEvent->isAccepted();
+ if (p.isNull()) {
+ // widget was deleted
+ w = nullptr;
+ } else {
+ w->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted);
+ }
+ touchEvent->m_spont = false;
+ if (res && eventAccepted) {
+ // the first widget to accept the TouchBegin gets an implicit grab.
+ d->activateImplicitTouchGrab(w, touchEvent);
+ break;
+ }
#ifndef QT_NO_GESTURES
- if (gesturePendingWidget.isNull() && widget && QGestureManager::gesturePending(widget))
- gesturePendingWidget = widget;
+ if (gesturePendingWidget.isNull() && w && QGestureManager::gesturePending(w))
+ gesturePendingWidget = w;
#endif
- if (p.isNull() || widget->isWindow() || widget->testAttribute(Qt::WA_NoMousePropagation))
- break;
+ if (!w || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
+ break;
- QPoint offset = widget->pos();
- widget = widget->parentWidget();
- touchEvent->setTarget(widget);
- for (int i = 0; i < touchEvent->_touchPoints.size(); ++i) {
- QTouchEvent::TouchPoint &pt = touchEvent->_touchPoints[i];
- pt.d->pos = pt.pos() + offset;
- pt.d->startPos = pt.startPos() + offset;
- pt.d->lastPos = pt.lastPos() + offset;
+ const QPoint offset = w->pos();
+ w = w->parentWidget();
+ touchEvent->setTarget(w);
+ for (int i = 0; i < touchEvent->pointCount(); ++i) {
+ auto &pt = touchEvent->point(i);
+ QMutableEventPoint::setPosition(pt, pt.position() + offset);
+ }
}
- }
#ifndef QT_NO_GESTURES
- if (!eventAccepted && !gesturePendingWidget.isNull()) {
- // the first widget subscribed to a gesture gets an implicit grab
- d->activateImplicitTouchGrab(gesturePendingWidget, touchEvent);
- }
+ if (!eventAccepted && !gesturePendingWidget.isNull()) {
+ // the first widget subscribed to a gesture gets an implicit grab for all
+ // points, also for events and event points that have not been accepted.
+ d->activateImplicitTouchGrab(gesturePendingWidget, touchEvent, QApplicationPrivate::GrabAllPoints);
+ }
#endif
- touchEvent->setAccepted(eventAccepted);
- break;
- }
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- {
- QWidget *widget = static_cast<QWidget *>(receiver);
- // We may get here if the widget is subscribed to a gesture,
- // but has not accepted TouchBegin. Propagate touch events
- // only if TouchBegin has been accepted.
- if (widget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent))
- res = d->notify_helper(widget, e);
- break;
- }
- case QEvent::RequestSoftwareInputPanel:
- inputMethod()->show();
- break;
- case QEvent::CloseSoftwareInputPanel:
- inputMethod()->hide();
- break;
+ touchEvent->setAccepted(eventAccepted);
+ break;
+ }
+ case QEvent::TouchUpdate:
+ case QEvent::TouchEnd:
+ // We may get here if the widget is subscribed to a gesture,
+ // but has not accepted TouchBegin. Propagate touch events
+ // only if TouchBegin has been accepted.
+ if (w->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent))
+ res = d->notify_helper(w, e);
+ break;
+ case QEvent::RequestSoftwareInputPanel:
+ inputMethod()->show();
+ break;
+ case QEvent::CloseSoftwareInputPanel:
+ inputMethod()->hide();
+ break;
#ifndef QT_NO_GESTURES
- case QEvent::NativeGesture:
- {
- // only propagate the first gesture event (after the GID_BEGIN)
- QWidget *w = static_cast<QWidget *>(receiver);
- while (w) {
- e->ignore();
- res = d->notify_helper(w, e);
- if ((res && e->isAccepted()) || w->isWindow())
- break;
- w = w->parentWidget();
- }
- break;
- }
- case QEvent::Gesture:
- case QEvent::GestureOverride:
- {
- if (receiver->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(receiver);
+ case QEvent::NativeGesture:
+ while (w) {
+ e->ignore();
+ res = d->notify_helper(w, e);
+ if (res && e->isAccepted())
+ break;
+ if (w->isWindow())
+ break;
+ w = w->parentWidget();
+ }
+ break;
+ case QEvent::Gesture:
+ case QEvent::GestureOverride: {
QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(e);
QList<QGesture *> allGestures = gestureEvent->gestures();
@@ -3539,7 +3165,7 @@ QT_WARNING_POP
wd->gestureContext.find(type);
bool deliver = contextit != wd->gestureContext.end() &&
(g->state() == Qt::GestureStarted || w == receiver ||
- (contextit.value() & Qt::ReceivePartialGestures));
+ (contextit.value() & Qt::ReceivePartialGestures));
if (deliver) {
allGestures.removeAt(i);
gestures.append(g);
@@ -3550,11 +3176,11 @@ QT_WARNING_POP
if (!gestures.isEmpty()) { // we have gestures for this w
QGestureEvent ge(gestures);
ge.t = gestureEvent->t;
- ge.spont = gestureEvent->spont;
+ ge.m_spont = gestureEvent->spontaneous();
ge.m_accept = wasAccepted;
ge.m_accepted = gestureEvent->m_accepted;
res = d->notify_helper(w, &ge);
- gestureEvent->spont = false;
+ gestureEvent->m_spont = false;
eventAccepted = ge.isAccepted();
for (int i = 0; i < gestures.size(); ++i) {
QGesture *g = gestures.at(i);
@@ -3577,46 +3203,40 @@ QT_WARNING_POP
break;
w = w->parentWidget();
}
- for (QGesture *g : qAsConst(allGestures))
+ for (QGesture *g : std::as_const(allGestures))
gestureEvent->setAccepted(g, false);
gestureEvent->m_accept = false; // to make sure we check individual gestures
- } else {
- res = d->notify_helper(receiver, e);
+ break;
}
- break;
- }
#endif // QT_NO_GESTURES
#ifdef Q_OS_MAC
- // Enable touch events on enter, disable on leave.
- typedef void (*RegisterTouchWindowFn)(QWindow *, bool);
- case QEvent::Enter:
- if (receiver->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(receiver);
+ // Enable touch events on enter, disable on leave.
+ typedef void (*RegisterTouchWindowFn)(QWindow *, bool);
+ case QEvent::Enter:
if (w->testAttribute(Qt::WA_AcceptTouchEvents)) {
RegisterTouchWindowFn registerTouchWindow = reinterpret_cast<RegisterTouchWindowFn>
(platformNativeInterface()->nativeResourceFunctionForIntegration("registertouchwindow"));
if (registerTouchWindow)
registerTouchWindow(w->window()->windowHandle(), true);
}
- }
- res = d->notify_helper(receiver, e);
- break;
- case QEvent::Leave:
- if (receiver->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(receiver);
+ res = d->notify_helper(receiver, e);
+ break;
+ case QEvent::Leave:
if (w->testAttribute(Qt::WA_AcceptTouchEvents)) {
RegisterTouchWindowFn registerTouchWindow = reinterpret_cast<RegisterTouchWindowFn>
(platformNativeInterface()->nativeResourceFunctionForIntegration("registertouchwindow"));
if (registerTouchWindow)
registerTouchWindow(w->window()->windowHandle(), false);
}
- }
- res = d->notify_helper(receiver, e);
- break;
+ res = d->notify_helper(receiver, e);
+ break;
#endif
- default:
+ default:
+ res = d->notify_helper(receiver, e);
+ break;
+ }
+ } else {
res = d->notify_helper(receiver, e);
- break;
}
return res;
@@ -3709,6 +3329,18 @@ static void grabForPopup(QWidget *popup)
extern QWidget *qt_popup_down;
extern bool qt_replay_popup_mouse_event;
+extern bool qt_popup_down_closed;
+
+bool QApplicationPrivate::closeAllPopups()
+{
+ // Close all popups: In case some popup refuses to close,
+ // we give up after 1024 attempts (to avoid an infinite loop).
+ int maxiter = 1024;
+ QWidget *popup;
+ while ((popup = QApplication::activePopupWidget()) && maxiter--)
+ popup->close(); // this will call QApplicationPrivate::closePopup
+ return true;
+}
void QApplicationPrivate::closePopup(QWidget *popup)
{
@@ -3718,18 +3350,22 @@ void QApplicationPrivate::closePopup(QWidget *popup)
if (popup == qt_popup_down) {
qt_button_down = nullptr;
+ qt_popup_down_closed = true;
qt_popup_down = nullptr;
}
- if (QApplicationPrivate::popupWidgets->count() == 0) { // this was the last popup
+ if (QApplicationPrivate::popupWidgets->size() == 0) { // this was the last popup
delete QApplicationPrivate::popupWidgets;
QApplicationPrivate::popupWidgets = nullptr;
+ qt_popup_down_closed = false;
if (popupGrabOk) {
popupGrabOk = false;
- if (popup->geometry().contains(QPoint(QGuiApplicationPrivate::mousePressX,
- QGuiApplicationPrivate::mousePressY))
+ // TODO on multi-seat window systems, we have to know which mouse
+ auto devPriv = QPointingDevicePrivate::get(QPointingDevice::primaryPointingDevice());
+ auto mousePressPos = devPriv->pointById(0)->eventPoint.globalPressPosition();
+ if (popup->geometry().contains(mousePressPos.toPoint())
|| popup->testAttribute(Qt::WA_NoMouseReplay)) {
// mouse release event or inside
qt_replay_popup_mouse_event = false;
@@ -3761,7 +3397,9 @@ void QApplicationPrivate::closePopup(QWidget *popup)
if (QWidget *fw = aw->focusWidget())
fw->setFocus(Qt::PopupFocusReason);
- if (QApplicationPrivate::popupWidgets->count() == 1) // grab mouse/keyboard
+ // can become nullptr due to setFocus() above
+ if (QApplicationPrivate::popupWidgets &&
+ QApplicationPrivate::popupWidgets->size() == 1) // grab mouse/keyboard
grabForPopup(aw);
}
@@ -3776,7 +3414,7 @@ void QApplicationPrivate::openPopup(QWidget *popup)
popupWidgets = new QWidgetList;
popupWidgets->append(popup); // add to end of list
- if (QApplicationPrivate::popupWidgets->count() == 1) // grab mouse/keyboard
+ if (QApplicationPrivate::popupWidgets->size() == 1) // grab mouse/keyboard
grabForPopup(popup);
// popups are not focus-handled by the window system (the first
@@ -3784,7 +3422,7 @@ void QApplicationPrivate::openPopup(QWidget *popup)
// new popup gets the focus
if (popup->focusWidget()) {
popup->focusWidget()->setFocus(Qt::PopupFocusReason);
- } else if (popupWidgets->count() == 1) { // this was the first popup
+ } else if (popupWidgets->size() == 1) { // this was the first popup
if (QWidget *fw = QApplication::focusWidget()) {
QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
QCoreApplication::sendEvent(fw, &e);
@@ -3816,51 +3454,6 @@ Qt::NavigationMode QApplication::navigationMode()
{
return QApplicationPrivate::navigationMode;
}
-
-# if QT_DEPRECATED_SINCE(5, 13)
-/*!
- Sets whether Qt should use focus navigation suitable for use with a
- minimal keypad.
-
- This feature is available in Qt for Embedded Linux, and Windows CE only.
-
- \note On Windows CE this feature is disabled by default for touch device
- mkspecs. To enable keypad navigation, build Qt with
- QT_KEYPAD_NAVIGATION defined.
-
- \deprecated
-
- \sa setNavigationMode()
-*/
-void QApplication::setKeypadNavigationEnabled(bool enable)
-{
- if (enable) {
- QApplication::setNavigationMode(Qt::NavigationModeKeypadTabOrder);
- } else {
- QApplication::setNavigationMode(Qt::NavigationModeNone);
- }
-}
-
-/*!
- Returns \c true if Qt is set to use keypad navigation; otherwise returns
- false. The default value is false.
-
- This feature is available in Qt for Embedded Linux, and Windows CE only.
-
- \note On Windows CE this feature is disabled by default for touch device
- mkspecs. To enable keypad navigation, build Qt with
- QT_KEYPAD_NAVIGATION defined.
-
- \deprecated
-
- \sa navigationMode()
-*/
-bool QApplication::keypadNavigationEnabled()
-{
- return QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadTabOrder ||
- QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadDirectional;
-}
-# endif
#endif
/*!
@@ -3868,7 +3461,7 @@ bool QApplication::keypadNavigationEnabled()
\since 4.3
Causes an alert to be shown for \a widget if the window is not the active
- window. The alert is shown for \a msec miliseconds. If \a msec is zero (the
+ window. The alert is shown for \a msec milliseconds. If \a msec is zero (the
default), then the alert is shown indefinitely until the window becomes
active again.
@@ -4159,18 +3752,12 @@ bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy)
bool QApplicationPrivate::updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent)
{
bool containsPress = false;
- for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
- QTouchEvent::TouchPoint &touchPoint = touchEvent->_touchPoints[i];
-
- // preserve the sub-pixel resolution
- const QPointF screenPos = touchPoint.screenRect().center();
- const QPointF delta = screenPos - screenPos.toPoint();
- touchPoint.d->pos = widget->mapFromGlobal(screenPos.toPoint()) + delta;
- touchPoint.d->startPos = widget->mapFromGlobal(touchPoint.startScreenPos().toPoint()) + delta;
- touchPoint.d->lastPos = widget->mapFromGlobal(touchPoint.lastScreenPos().toPoint()) + delta;
+ for (int i = 0; i < touchEvent->pointCount(); ++i) {
+ auto &pt = touchEvent->point(i);
+ QMutableEventPoint::setPosition(pt, widget->mapFromGlobal(pt.globalPosition()));
- if (touchPoint.state() == Qt::TouchPointPressed)
+ if (pt.state() == QEventPoint::State::Pressed)
containsPress = true;
}
return containsPress;
@@ -4194,111 +3781,111 @@ void QApplicationPrivate::cleanupMultitouch_sys()
{
}
-QWidget *QApplicationPrivate::findClosestTouchPointTarget(QTouchDevice *device, const QTouchEvent::TouchPoint &touchPoint)
+QWidget *QApplicationPrivate::findClosestTouchPointTarget(const QPointingDevice *device, const QEventPoint &touchPoint)
{
- const QPointF screenPos = touchPoint.screenPos();
+ const QPointF globalPos = touchPoint.globalPosition();
int closestTouchPointId = -1;
QObject *closestTarget = nullptr;
- qreal closestDistance = qreal(0.);
- QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it = activeTouchPoints.constBegin(),
- ite = activeTouchPoints.constEnd();
- while (it != ite) {
- if (it.key().device == device && it.key().touchPointId != touchPoint.id()) {
- const QTouchEvent::TouchPoint &touchPoint = it->touchPoint;
- qreal dx = screenPos.x() - touchPoint.screenPos().x();
- qreal dy = screenPos.y() - touchPoint.screenPos().y();
+ qreal closestDistance = 0;
+ const QPointingDevicePrivate *devPriv = QPointingDevicePrivate::get(device);
+ for (auto &epd : devPriv->activePoints.values()) {
+ const auto &pt = epd.eventPoint;
+ if (pt.id() != touchPoint.id()) {
+ qreal dx = globalPos.x() - pt.globalPosition().x();
+ qreal dy = globalPos.y() - pt.globalPosition().y();
qreal distance = dx * dx + dy * dy;
if (closestTouchPointId == -1 || distance < closestDistance) {
- closestTouchPointId = touchPoint.id();
+ closestTouchPointId = pt.id();
closestDistance = distance;
- closestTarget = it.value().target.data();
+ closestTarget = QMutableEventPoint::target(pt);
}
}
- ++it;
}
return static_cast<QWidget *>(closestTarget);
}
-void QApplicationPrivate::activateImplicitTouchGrab(QWidget *widget, QTouchEvent *touchEvent)
+void QApplicationPrivate::activateImplicitTouchGrab(QWidget *widget, QTouchEvent *touchEvent,
+ ImplicitTouchGrabMode grabMode)
{
if (touchEvent->type() != QEvent::TouchBegin)
return;
- for (int i = 0, tc = touchEvent->touchPoints().count(); i < tc; ++i) {
- const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i);
- activeTouchPoints[QGuiApplicationPrivate::ActiveTouchPointsKey(touchEvent->device(), touchPoint.id())].target = widget;
+ // If the widget dispatched the event further (see QGraphicsProxyWidget), then
+ // there might already be an implicit grabber. Don't override that. A widget that
+ // has partially recognized a gesture needs to grab all points.
+ for (int i = 0; i < touchEvent->pointCount(); ++i) {
+ auto &ep = touchEvent->point(i);
+ if (!QMutableEventPoint::target(ep) && (ep.isAccepted() || grabMode == GrabAllPoints))
+ QMutableEventPoint::setTarget(ep, widget);
}
+ // TODO setExclusiveGrabber() to be consistent with Qt Quick?
}
-bool QApplicationPrivate::translateRawTouchEvent(QWidget *window,
- QTouchDevice *device,
- const QList<QTouchEvent::TouchPoint> &touchPoints,
- ulong timestamp)
+bool QApplicationPrivate::translateRawTouchEvent(QWidget *window, const QTouchEvent *te)
{
QApplicationPrivate *d = self;
- typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints;
+ // TODO get rid of this QPair
+ typedef QPair<QEventPoint::State, QList<QEventPoint> > StatesAndTouchPoints;
QHash<QWidget *, StatesAndTouchPoints> widgetsNeedingEvents;
- for (int i = 0; i < touchPoints.count(); ++i) {
- QTouchEvent::TouchPoint touchPoint = touchPoints.at(i);
- // explicitly detach from the original touch point that we got, so even
- // if the touchpoint structs are reused, we will make a copy that we'll
- // deliver to the user (which might want to store the struct for later use).
- touchPoint.d = touchPoint.d->detach();
-
+ const auto *device = te->pointingDevice();
+ auto touchPoints = te->points(); // touch points will be mutated
+ for (auto &touchPoint : touchPoints) {
// update state
QPointer<QObject> target;
- ActiveTouchPointsKey touchInfoKey(device, touchPoint.id());
- ActiveTouchPointsValue &touchInfo = d->activeTouchPoints[touchInfoKey];
- if (touchPoint.state() == Qt::TouchPointPressed) {
- if (device->type() == QTouchDevice::TouchPad) {
- // on touch-pads, send all touch points to the same widget
- target = d->activeTouchPoints.isEmpty()
- ? QPointer<QObject>()
- : d->activeTouchPoints.constBegin().value().target;
+ if (touchPoint.state() == QEventPoint::State::Pressed) {
+ if (device->type() == QInputDevice::DeviceType::TouchPad) {
+ // on touchpads, send all touch points to the same widget:
+ // pick the first non-null target if possible
+ target = QPointingDevicePrivate::get(device)->firstActiveTarget();
}
- if (!target) {
+ if (target.isNull()) {
// determine which widget this event will go to
if (!window)
- window = QApplication::topLevelAt(touchPoint.screenPos().toPoint());
+ window = QApplication::topLevelAt(touchPoint.globalPosition().toPoint());
if (!window)
continue;
- target = window->childAt(window->mapFromGlobal(touchPoint.screenPos().toPoint()));
+ target = window->childAt(window->mapFromGlobal(touchPoint.globalPosition().toPoint()));
if (!target)
target = window;
}
- if (device->type() == QTouchDevice::TouchScreen) {
+ bool usingClosestWidget = false;
+ if (device->type() == QInputDevice::DeviceType::TouchScreen) {
QWidget *closestWidget = d->findClosestTouchPointTarget(device, touchPoint);
QWidget *widget = static_cast<QWidget *>(target.data());
if (closestWidget
&& (widget->isAncestorOf(closestWidget) || closestWidget->isAncestorOf(widget))) {
target = closestWidget;
+ usingClosestWidget = true;
}
}
- touchInfo.target = target;
+ // on touch pads, implicitly grab all touch points
+ // on touch screens, grab touch points that are redirected to the closest widget
+ if (device->type() == QInputDevice::DeviceType::TouchPad || usingClosestWidget)
+ QMutableEventPoint::setTarget(touchPoint, target);
} else {
- target = touchInfo.target;
+ target = QMutableEventPoint::target(touchPoint);
if (!target)
continue;
}
- Q_ASSERT(target.data() != nullptr);
+ Q_ASSERT(!target.isNull());
QWidget *targetWidget = static_cast<QWidget *>(target.data());
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
// Single-touch events are normally not sent unless WA_TouchPadAcceptSingleTouchEvents is set.
// In Qt 4 this check was in OS X-only code. That behavior is preserved here by the #ifdef.
if (touchPoints.count() == 1
- && device->type() == QTouchDevice::TouchPad
+ && device->type() == QInputDevice::DeviceType::TouchPad
&& !targetWidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents))
continue;
#endif
StatesAndTouchPoints &maskAndPoints = widgetsNeedingEvents[targetWidget];
- maskAndPoints.first |= touchPoint.state();
+ maskAndPoints.first = QEventPoint::State(maskAndPoints.first | touchPoint.state());
maskAndPoints.second.append(touchPoint);
}
@@ -4315,13 +3902,13 @@ bool QApplicationPrivate::translateRawTouchEvent(QWidget *window,
QEvent::Type eventType;
switch (it.value().first) {
- case Qt::TouchPointPressed:
+ case QEventPoint::State::Pressed:
eventType = QEvent::TouchBegin;
break;
- case Qt::TouchPointReleased:
+ case QEventPoint::State::Released:
eventType = QEvent::TouchEnd;
break;
- case Qt::TouchPointStationary:
+ case QEventPoint::State::Stationary:
// don't send the event if nothing changed
continue;
default:
@@ -4329,14 +3916,10 @@ bool QApplicationPrivate::translateRawTouchEvent(QWidget *window,
break;
}
- QTouchEvent touchEvent(eventType,
- device,
- QGuiApplication::keyboardModifiers(),
- it.value().first,
- it.value().second);
+ QMutableTouchEvent touchEvent(eventType, device, QGuiApplication::keyboardModifiers(),
+ it.value().second);
bool containsPress = updateTouchPointsForWidget(widget, &touchEvent);
- touchEvent.setTimestamp(timestamp);
- touchEvent.setWindow(window->windowHandle());
+ touchEvent.setTimestamp(te->timestamp());
touchEvent.setTarget(widget);
if (containsPress)
@@ -4347,7 +3930,9 @@ bool QApplicationPrivate::translateRawTouchEvent(QWidget *window,
{
// if the TouchBegin handler recurses, we assume that means the event
// has been implicitly accepted and continue to send touch events
- if (QApplication::sendSpontaneousEvent(widget, &touchEvent) && touchEvent.isAccepted()) {
+ bool res = te->spontaneous() ? QApplication::sendSpontaneousEvent(widget, &touchEvent)
+ : QApplication::sendEvent(widget, &touchEvent);
+ if (res && touchEvent.isAccepted()) {
accepted = true;
if (!widget.isNull())
widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent);
@@ -4360,7 +3945,9 @@ bool QApplicationPrivate::translateRawTouchEvent(QWidget *window,
|| QGestureManager::gesturePending(widget)
#endif
) {
- if (QApplication::sendSpontaneousEvent(widget, &touchEvent) && touchEvent.isAccepted())
+ bool res = te->spontaneous() ? QApplication::sendSpontaneousEvent(widget, &touchEvent)
+ : QApplication::sendEvent(widget, &touchEvent);
+ if (res && touchEvent.isAccepted())
accepted = true;
// widget can be deleted on TouchEnd
if (touchEvent.type() == QEvent::TouchEnd && !widget.isNull())
@@ -4372,31 +3959,30 @@ bool QApplicationPrivate::translateRawTouchEvent(QWidget *window,
return accepted;
}
-void QApplicationPrivate::translateTouchCancel(QTouchDevice *device, ulong timestamp)
+void QApplicationPrivate::translateTouchCancel(const QPointingDevice *device, ulong timestamp)
{
- QTouchEvent touchEvent(QEvent::TouchCancel, device, QGuiApplication::keyboardModifiers());
+ QMutableTouchEvent touchEvent(QEvent::TouchCancel, device, QGuiApplication::keyboardModifiers());
touchEvent.setTimestamp(timestamp);
- QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it
- = self->activeTouchPoints.constBegin(), ite = self->activeTouchPoints.constEnd();
+
QSet<QWidget *> widgetsNeedingCancel;
- while (it != ite) {
- QWidget *widget = static_cast<QWidget *>(it->target.data());
- if (widget)
- widgetsNeedingCancel.insert(widget);
- ++it;
+ const QPointingDevicePrivate *devPriv = QPointingDevicePrivate::get(device);
+ for (auto &epd : devPriv->activePoints.values()) {
+ const auto &pt = epd.eventPoint;
+ QObject *target = QMutableEventPoint::target(pt);
+ if (target && target->isWidgetType())
+ widgetsNeedingCancel.insert(static_cast<QWidget *>(target));
}
for (QSet<QWidget *>::const_iterator widIt = widgetsNeedingCancel.constBegin(),
widItEnd = widgetsNeedingCancel.constEnd(); widIt != widItEnd; ++widIt) {
QWidget *widget = *widIt;
- touchEvent.setWindow(widget->windowHandle());
touchEvent.setTarget(widget);
QApplication::sendSpontaneousEvent(widget, &touchEvent);
}
}
-void QApplicationPrivate::notifyThemeChanged()
+void QApplicationPrivate::handleThemeChanged()
{
- QGuiApplicationPrivate::notifyThemeChanged();
+ QGuiApplicationPrivate::handleThemeChanged();
qt_init_tooltip_palette();
}
@@ -4433,6 +4019,11 @@ QPixmap QApplicationPrivate::applyQIconStyleHelper(QIcon::Mode mode, const QPixm
return QApplication::style()->generatedIconPixmap(mode, base, &opt);
}
+void *QApplication::resolveInterface(const char *name, int revision) const
+{
+ return QGuiApplication::resolveInterface(name, revision);
+}
+
QT_END_NAMESPACE
#include "moc_qapplication.cpp"
diff --git a/src/widgets/kernel/qapplication.h b/src/widgets/kernel/qapplication.h
index d7cc4489c4..fd698fb69f 100644
--- a/src/widgets/kernel/qapplication.h
+++ b/src/widgets/kernel/qapplication.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QAPPLICATION_H
#define QAPPLICATION_H
@@ -46,15 +10,11 @@
#include <QtCore/qpoint.h>
#include <QtCore/qsize.h>
#include <QtGui/qcursor.h>
-#ifdef QT_INCLUDE_COMPAT
-# include <QtWidgets/qdesktopwidget.h>
-#endif
#include <QtGui/qguiapplication.h>
QT_BEGIN_NAMESPACE
-class QDesktopWidget;
class QStyle;
class QEventLoop;
class QIcon;
@@ -71,14 +31,12 @@ class QApplicationPrivate;
class Q_WIDGETS_EXPORT QApplication : public QGuiApplication
{
Q_OBJECT
- Q_PROPERTY(QIcon windowIcon READ windowIcon WRITE setWindowIcon)
Q_PROPERTY(int cursorFlashTime READ cursorFlashTime WRITE setCursorFlashTime)
Q_PROPERTY(int doubleClickInterval READ doubleClickInterval WRITE setDoubleClickInterval)
Q_PROPERTY(int keyboardInputInterval READ keyboardInputInterval WRITE setKeyboardInputInterval)
#if QT_CONFIG(wheelevent)
Q_PROPERTY(int wheelScrollLines READ wheelScrollLines WRITE setWheelScrollLines)
#endif
- Q_PROPERTY(QSize globalStrut READ globalStrut WRITE setGlobalStrut)
Q_PROPERTY(int startDragTime READ startDragTime WRITE setStartDragTime)
Q_PROPERTY(int startDragDistance READ startDragDistance WRITE setStartDragDistance)
#ifndef QT_NO_STYLE_STYLESHEET
@@ -97,14 +55,6 @@ public:
static QStyle *style();
static void setStyle(QStyle*);
static QStyle *setStyle(const QString&);
- enum ColorSpec { NormalColor=0, CustomColor=1, ManyColor=2 };
-#if QT_DEPRECATED_SINCE(5, 8)
- QT_DEPRECATED static int colorSpec();
- QT_DEPRECATED static void setColorSpec(int);
-#endif // QT_DEPRECATED_SINCE(5, 8)
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED static inline void setGraphicsSystem(const QString &) {}
-#endif
using QGuiApplication::palette;
static QPalette palette(const QWidget *);
@@ -114,33 +64,31 @@ public:
static QFont font(const QWidget*);
static QFont font(const char *className);
static void setFont(const QFont &, const char* className = nullptr);
- static QFontMetrics fontMetrics();
-#if QT_VERSION < 0x060000 // remove these forwarders in Qt 6
- static void setWindowIcon(const QIcon &icon);
- static QIcon windowIcon();
+#if QT_DEPRECATED_SINCE(6,0)
+ QT_DEPRECATED_VERSION_X_6_0("Use the QFontMetricsF constructor instead.")
+ static QFontMetrics fontMetrics();
#endif
static QWidgetList allWidgets();
static QWidgetList topLevelWidgets();
- static QDesktopWidget *desktop();
-
static QWidget *activePopupWidget();
static QWidget *activeModalWidget();
static QWidget *focusWidget();
static QWidget *activeWindow();
+
+#if QT_DEPRECATED_SINCE(6, 5)
+ QT_DEPRECATED_VERSION_X_6_5("Use QWidget::activateWindow() instead.")
static void setActiveWindow(QWidget* act);
+#endif
static QWidget *widgetAt(const QPoint &p);
static inline QWidget *widgetAt(int x, int y) { return widgetAt(QPoint(x, y)); }
static QWidget *topLevelAt(const QPoint &p);
static inline QWidget *topLevelAt(int x, int y) { return topLevelAt(QPoint(x, y)); }
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED static inline void syncX() {}
-#endif
static void beep();
static void alert(QWidget *widget, int duration = 0);
@@ -157,8 +105,6 @@ public:
static void setWheelScrollLines(int);
static int wheelScrollLines();
#endif
- static void setGlobalStrut(const QSize &);
- static QSize globalStrut();
static void setStartDragTime(int ms);
static int startDragTime();
@@ -168,38 +114,27 @@ public:
static bool isEffectEnabled(Qt::UIEffect);
static void setEffectEnabled(Qt::UIEffect, bool enable = true);
-#if QT_DEPRECATED_SINCE(5, 0)
- QT_DEPRECATED static QLocale keyboardInputLocale()
- { return qApp ? QGuiApplication::inputMethod()->locale() : QLocale::c(); }
- QT_DEPRECATED static Qt::LayoutDirection keyboardInputDirection()
- { return qApp ? QGuiApplication::inputMethod()->inputDirection() : Qt::LeftToRight; }
-#endif
-
static int exec();
bool notify(QObject *, QEvent *) override;
#ifdef QT_KEYPAD_NAVIGATION
-# if QT_DEPRECATED_SINCE(5, 13)
- static QT_DEPRECATED_X ("Use QApplication::setNavigationMode() instead")
- void setKeypadNavigationEnabled(bool);
- static QT_DEPRECATED_X ("Use QApplication::navigationMode() instead")
- bool keypadNavigationEnabled();
-# endif
static void setNavigationMode(Qt::NavigationMode mode);
static Qt::NavigationMode navigationMode();
#endif
+ QT_DECLARE_NATIVE_INTERFACE_ACCESSOR(QApplication)
+
Q_SIGNALS:
void focusChanged(QWidget *old, QWidget *now);
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 ab6d85aeb9..21b1605dfc 100644
--- a/src/widgets/kernel/qapplication_p.h
+++ b/src/widgets/kernel/qapplication_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QAPPLICATION_P_H
#define QAPPLICATION_P_H
@@ -81,12 +45,12 @@ class QGraphicsScene;
class QObject;
class QWidget;
class QSocketNotifier;
-class QTouchDevice;
+class QPointingDevice;
#ifndef QT_NO_GESTURES
class QGestureManager;
#endif
-extern Q_GUI_EXPORT bool qt_is_gui_used;
+extern Q_GUI_EXPORT bool qt_is_tty_app;
#ifndef QT_NO_CLIPBOARD
extern QClipboard *qt_clipboard;
#endif
@@ -94,31 +58,34 @@ extern QClipboard *qt_clipboard;
typedef QHash<QByteArray, QFont> FontHash;
Q_WIDGETS_EXPORT FontHash *qt_app_fonts_hash();
-#define QApplicationPrivateBase QGuiApplicationPrivate
-
-class Q_WIDGETS_EXPORT QApplicationPrivate : public QApplicationPrivateBase
+class Q_WIDGETS_EXPORT QApplicationPrivate : public QGuiApplicationPrivate
{
Q_DECLARE_PUBLIC(QApplication)
public:
- QApplicationPrivate(int &argc, char **argv, int flags);
+ QApplicationPrivate(int &argc, char **argv);
~QApplicationPrivate();
virtual void notifyLayoutDirectionChange() override;
virtual void notifyActiveWindowChange(QWindow *) override;
- virtual bool shouldQuit() override;
- bool tryCloseAllWindows() override;
-
static bool autoSipEnabled;
static QString desktopStyleKey();
void createEventDispatcher() override;
static void dispatchEnterLeave(QWidget *enter, QWidget *leave, const QPointF &globalPosF);
-
+ static QWidget *desktop();
void notifyWindowIconChanged() override;
+#ifndef QT_NO_ACTION
+ QActionPrivate *createActionPrivate() const override;
+#endif
+#ifndef QT_NO_SHORTCUT
+ QShortcutPrivate *createShortcutPrivate() const override;
+#endif
+
//modality
- bool isWindowBlocked(QWindow *window, QWindow **blockingWindow = nullptr) const override;
+ Qt::WindowModality defaultModality() const override;
+ bool windowNeverBlocked(QWindow *window) const override;
static bool isBlockedByModal(QWidget *widget);
static bool modalState();
static bool tryModalHelper(QWidget *widget, QWidget **rettop = nullptr);
@@ -137,8 +104,11 @@ public:
void initialize();
void process_cmdline();
+ static void setActiveWindow(QWidget* act);
+
static bool inPopupMode();
bool popupActive() override { return inPopupMode(); }
+ bool closeAllPopups() override;
void closePopup(QWidget *popup);
void openPopup(QWidget *popup);
static void setFocusWidget(QWidget *focus, Qt::FocusReason reason);
@@ -160,7 +130,7 @@ public:
static QStyle *app_style;
protected:
- void notifyThemeChanged() override;
+ void handleThemeChanged() override;
QPalette basePalette() const override;
void handlePaletteChanged(const char *className = nullptr) override;
@@ -175,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
@@ -240,17 +208,17 @@ public:
void initializeMultitouch_sys();
void cleanupMultitouch();
void cleanupMultitouch_sys();
- QWidget *findClosestTouchPointTarget(QTouchDevice *device, const QTouchEvent::TouchPoint &touchPoint);
- void appendTouchPoint(const QTouchEvent::TouchPoint &touchPoint);
+ QWidget *findClosestTouchPointTarget(const QPointingDevice *device, const QEventPoint &touchPoint);
+ void appendTouchPoint(const QEventPoint &touchPoint);
void removeTouchPoint(int touchPointId);
- void activateImplicitTouchGrab(QWidget *widget, QTouchEvent *touchBeginEvent);
- static bool translateRawTouchEvent(QWidget *widget,
- QTouchDevice *device,
- const QList<QTouchEvent::TouchPoint> &touchPoints,
- ulong timestamp);
- static void translateTouchCancel(QTouchDevice *device, ulong timestamp);
+ enum ImplicitTouchGrabMode { GrabAcceptedPoints, GrabAllPoints };
+ void activateImplicitTouchGrab(QWidget *widget, QTouchEvent *touchBeginEvent,
+ ImplicitTouchGrabMode grabMode = GrabAcceptedPoints);
+ static bool translateRawTouchEvent(QWidget *widget, const QTouchEvent *touchEvent);
+ static void translateTouchCancel(const QPointingDevice *device, ulong timestamp);
QPixmap applyQIconStyleHelper(QIcon::Mode mode, const QPixmap& base) const override;
+
private:
static QApplicationPrivate *self;
static bool tryCloseAllWidgetWindows(QWindowList *processedWindows);
@@ -258,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/qboxlayout.cpp b/src/widgets/kernel/qboxlayout.cpp
index 7b09adfbf0..501883e85a 100644
--- a/src/widgets/kernel/qboxlayout.cpp
+++ b/src/widgets/kernel/qboxlayout.cpp
@@ -1,51 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qboxlayout.h"
#include "qapplication.h"
-#include "qwidget.h"
+#include "qboxlayout.h"
#include "qlist.h"
#include "qsizepolicy.h"
-#include "qvector.h"
+#include "qwidget.h"
-#include "qlayoutengine_p.h"
#include "qlayout_p.h"
+#include "qlayoutengine_p.h"
QT_BEGIN_NAMESPACE
@@ -64,7 +27,7 @@ struct QBoxLayoutItem
}
int mhfw(int w) {
if (item->hasHeightForWidth()) {
- return item->heightForWidth(w);
+ return item->minimumHeightForWidth(w);
} else {
return item->minimumSize().height();
}
@@ -104,7 +67,7 @@ public:
}
QList<QBoxLayoutItem *> list;
- QVector<QLayoutStruct> geomArray;
+ QList<QLayoutStruct> geomArray;
int hfwWidth;
int hfwHeight;
int hfwMinHeight;
@@ -125,6 +88,7 @@ public:
void effectiveMargins(int *left, int *top, int *right, int *bottom) const;
QLayoutItem* replaceAt(int index, QLayoutItem*) override;
+ int validateIndex(int index) const;
};
QBoxLayoutPrivate::~QBoxLayoutPrivate()
@@ -150,8 +114,8 @@ void QBoxLayoutPrivate::effectiveMargins(int *left, int *top, int *right, int *b
#ifdef Q_OS_MAC
Q_Q(const QBoxLayout);
if (horz(dir)) {
- QBoxLayoutItem *leftBox = 0;
- QBoxLayoutItem *rightBox = 0;
+ QBoxLayoutItem *leftBox = nullptr;
+ QBoxLayoutItem *rightBox = nullptr;
if (left || right) {
leftBox = list.value(0);
@@ -195,8 +159,8 @@ void QBoxLayoutPrivate::effectiveMargins(int *left, int *top, int *right, int *b
}
}
} else { // vertical layout
- QBoxLayoutItem *topBox = 0;
- QBoxLayoutItem *bottomBox = 0;
+ QBoxLayoutItem *topBox = nullptr;
+ QBoxLayoutItem *bottomBox = nullptr;
if (top || bottom) {
topBox = list.value(0);
@@ -269,9 +233,9 @@ void QBoxLayoutPrivate::setupGeom()
hasHfw = false;
- int n = list.count();
+ int n = list.size();
geomArray.clear();
- QVector<QLayoutStruct> a(n);
+ QList<QLayoutStruct> a(n);
QSizePolicy::ControlTypes controlTypes1;
QSizePolicy::ControlTypes controlTypes2;
@@ -400,8 +364,8 @@ void QBoxLayoutPrivate::setupGeom()
*/
void QBoxLayoutPrivate::calcHfw(int w)
{
- QVector<QLayoutStruct> &a = geomArray;
- int n = a.count();
+ QList<QLayoutStruct> &a = geomArray;
+ int n = a.size();
int h = 0;
int mh = 0;
@@ -444,6 +408,14 @@ QLayoutItem* QBoxLayoutPrivate::replaceAt(int index, QLayoutItem *item)
return r;
}
+int QBoxLayoutPrivate::validateIndex(int index) const
+{
+ if (index < 0)
+ return list.size(); // append
+
+ Q_ASSERT_X(index >= 0 && index <= list.size(), "QBoxLayout::insert", "index out of range");
+ return index;
+}
/*!
\class QBoxLayout
@@ -548,7 +520,11 @@ QLayoutItem* QBoxLayoutPrivate::replaceAt(int index, QLayoutItem *item)
Constructs a new QBoxLayout with direction \a dir and parent widget \a
parent.
- \sa direction()
+ The layout is set directly as the top-level layout for \a parent.
+ There can be only one top-level layout for a widget. It is returned
+ by QWidget::layout().
+
+ \sa direction(), QWidget::setLayout()
*/
QBoxLayout::QBoxLayout(Direction dir, QWidget *parent)
: QLayout(*new QBoxLayoutPrivate, nullptr, parent)
@@ -704,7 +680,7 @@ void QBoxLayout::invalidate()
int QBoxLayout::count() const
{
Q_D(const QBoxLayout);
- return d->list.count();
+ return d->list.size();
}
/*!
@@ -713,7 +689,7 @@ int QBoxLayout::count() const
QLayoutItem *QBoxLayout::itemAt(int index) const
{
Q_D(const QBoxLayout);
- return index >= 0 && index < d->list.count() ? d->list.at(index)->item : nullptr;
+ return index >= 0 && index < d->list.size() ? d->list.at(index)->item : nullptr;
}
/*!
@@ -722,7 +698,7 @@ QLayoutItem *QBoxLayout::itemAt(int index) const
QLayoutItem *QBoxLayout::takeAt(int index)
{
Q_D(QBoxLayout);
- if (index < 0 || index >= d->list.count())
+ if (index < 0 || index >= d->list.size())
return nullptr;
QBoxLayoutItem *b = d->list.takeAt(index);
QLayoutItem *item = b->item;
@@ -770,10 +746,10 @@ void QBoxLayout::setGeometry(const QRect &r)
cr.width() - (left + right),
cr.height() - (top + bottom));
- QVector<QLayoutStruct> a = d->geomArray;
+ QList<QLayoutStruct> a = d->geomArray;
int pos = horz(d->dir) ? s.x() : s.y();
int space = horz(d->dir) ? s.width() : s.height();
- int n = a.count();
+ int n = a.size();
if (d->hasHfw && !horz(d->dir)) {
for (int i = 0; i < n; i++) {
QBoxLayoutItem *box = d->list.at(i);
@@ -844,9 +820,7 @@ void QBoxLayout::addItem(QLayoutItem *item)
void QBoxLayout::insertItem(int index, QLayoutItem *item)
{
Q_D(QBoxLayout);
- if (index < 0) // append
- index = d->list.count();
-
+ index = d->validateIndex(index);
QBoxLayoutItem *it = new QBoxLayoutItem(item);
d->list.insert(index, it);
invalidate();
@@ -864,9 +838,7 @@ void QBoxLayout::insertItem(int index, QLayoutItem *item)
void QBoxLayout::insertSpacing(int index, int size)
{
Q_D(QBoxLayout);
- if (index < 0) // append
- index = d->list.count();
-
+ index = d->validateIndex(index);
QLayoutItem *b;
if (horz(d->dir))
b = QLayoutPrivate::createSpacerItem(this, size, 0, QSizePolicy::Fixed, QSizePolicy::Minimum);
@@ -889,9 +861,7 @@ void QBoxLayout::insertSpacing(int index, int size)
void QBoxLayout::insertStretch(int index, int stretch)
{
Q_D(QBoxLayout);
- if (index < 0) // append
- index = d->list.count();
-
+ index = d->validateIndex(index);
QLayoutItem *b;
if (horz(d->dir))
b = QLayoutPrivate::createSpacerItem(this, 0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
@@ -916,9 +886,7 @@ void QBoxLayout::insertStretch(int index, int stretch)
void QBoxLayout::insertSpacerItem(int index, QSpacerItem *spacerItem)
{
Q_D(QBoxLayout);
- if (index < 0) // append
- index = d->list.count();
-
+ index = d->validateIndex(index);
QBoxLayoutItem *it = new QBoxLayoutItem(spacerItem);
it->magic = true;
d->list.insert(index, it);
@@ -940,8 +908,7 @@ void QBoxLayout::insertLayout(int index, QLayout *layout, int stretch)
return;
if (!adoptLayout(layout))
return;
- if (index < 0) // append
- index = d->list.count();
+ index = d->validateIndex(index);
QBoxLayoutItem *it = new QBoxLayoutItem(layout, stretch);
d->list.insert(index, it);
invalidate();
@@ -974,8 +941,7 @@ void QBoxLayout::insertWidget(int index, QWidget *widget, int stretch,
if (!d->checkWidget(widget))
return;
addChildWidget(widget);
- if (index < 0) // append
- index = d->list.count();
+ index = d->validateIndex(index);
QWidgetItem *b = QLayoutPrivate::createWidgetItem(this, widget);
b->setAlignment(alignment);
@@ -1232,11 +1198,16 @@ QBoxLayout::Direction QBoxLayout::direction() const
\snippet layouts/layouts.cpp 4
\snippet layouts/layouts.cpp 5
- First, we create the widgets we want in the layout. Then, we
- create the QHBoxLayout object and add the widgets into the
- layout. Finally, we call QWidget::setLayout() to install the
- QHBoxLayout object onto the widget. At that point, the widgets in
- the layout are reparented to have \c window as their parent.
+ First, we create the widgets we want to add to the layout. Then,
+ we create the QHBoxLayout object, setting \c window as parent by
+ passing it in the constructor; next we add the widgets to the
+ layout. \c window will be the parent of the widgets that are
+ added to the layout.
+
+ If you don't pass a parent \c window to the constructor, you can
+ at a later point use QWidget::setLayout() to install the QHBoxLayout
+ object onto \c window. At that point, the widgets in the layout are
+ reparented to have \c window as their parent.
\image qhboxlayout-with-5-children.png Horizontal box layout with five child widgets
@@ -1245,8 +1216,13 @@ QBoxLayout::Direction QBoxLayout::direction() const
/*!
- Constructs a new top-level horizontal box with
- parent \a parent.
+ Constructs a new top-level horizontal box with parent \a parent.
+
+ The layout is set directly as the top-level layout for \a parent.
+ There can be only one top-level layout for a widget. It is returned
+ by QWidget::layout().
+
+ \sa QWidget::setLayout()
*/
QHBoxLayout::QHBoxLayout(QWidget *parent)
: QBoxLayout(LeftToRight, parent)
@@ -1295,11 +1271,16 @@ QHBoxLayout::~QHBoxLayout()
\snippet layouts/layouts.cpp 10
\snippet layouts/layouts.cpp 11
- First, we create the widgets we want in the layout. Then, we
- create the QVBoxLayout object and add the widgets into the
- layout. Finally, we call QWidget::setLayout() to install the
- QVBoxLayout object onto the widget. At that point, the widgets in
- the layout are reparented to have \c window as their parent.
+ First, we create the widgets we want to add to the layout. Then,
+ we create the QVBoxLayout object, setting \c window as parent by
+ passing it in the constructor; next we add the widgets to the
+ layout. \c window will be the parent of the widgets that are
+ added to the layout.
+
+ If you don't pass a parent \c window to the constructor, you can
+ at a later point use QWidget::setLayout() to install the QVBoxLayout
+ object onto \c window. At that point, the widgets in the layout are
+ reparented to have \c window as their parent.
\image qvboxlayout-with-5-children.png Horizontal box layout with five child widgets
@@ -1307,8 +1288,13 @@ QHBoxLayout::~QHBoxLayout()
*/
/*!
- Constructs a new top-level vertical box with
- parent \a parent.
+ Constructs a new top-level vertical box with parent \a parent.
+
+ The layout is set directly as the top-level layout for \a parent.
+ There can be only one top-level layout for a widget. It is returned
+ by QWidget::layout().
+
+ \sa QWidget::setLayout()
*/
QVBoxLayout::QVBoxLayout(QWidget *parent)
: QBoxLayout(TopToBottom, parent)
diff --git a/src/widgets/kernel/qboxlayout.h b/src/widgets/kernel/qboxlayout.h
index 6bb8f8aafa..a1adb2809b 100644
--- a/src/widgets/kernel/qboxlayout.h
+++ b/src/widgets/kernel/qboxlayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QBOXLAYOUT_H
#define QBOXLAYOUT_H
@@ -83,8 +47,8 @@ public:
void insertLayout(int index, QLayout *layout, int stretch = 0);
void insertItem(int index, QLayoutItem *);
- int spacing() const;
- void setSpacing(int spacing);
+ int spacing() const override;
+ void setSpacing(int spacing) override;
bool setStretchFactor(QWidget *w, int stretch);
bool setStretchFactor(QLayout *l, int stretch);
diff --git a/src/widgets/kernel/qdesktopwidget.cpp b/src/widgets/kernel/qdesktopwidget.cpp
deleted file mode 100644
index 9f98af86e3..0000000000
--- a/src/widgets/kernel/qdesktopwidget.cpp
+++ /dev/null
@@ -1,385 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qglobal.h"
-#include "qdesktopwidget.h"
-#include "qdesktopwidget_p.h"
-#include "qscreen.h"
-#include "qwidget_p.h"
-#include "qwindow.h"
-
-#include <private/qhighdpiscaling_p.h>
-#include <qpa/qplatformscreen.h>
-
-QT_BEGIN_NAMESPACE
-
-QDesktopScreenWidget::QDesktopScreenWidget(QScreen *screen, const QRect &geometry)
- : QWidget(nullptr, Qt::Desktop), m_screen(screen)
-{
- setVisible(false);
- if (QWindow *winHandle = windowHandle())
- winHandle->setScreen(screen);
- setScreenGeometry(geometry);
-}
-
-void QDesktopScreenWidget::setScreenGeometry(const QRect &geometry)
-{
- m_geometry = geometry;
- setGeometry(geometry);
-}
-
-int QDesktopScreenWidget::screenNumber() const
-{
- const QDesktopWidgetPrivate *desktopWidgetP
- = static_cast<const QDesktopWidgetPrivate *>(qt_widget_private(QApplication::desktop()));
- return desktopWidgetP->screens.indexOf(const_cast<QDesktopScreenWidget *>(this));
-}
-
-const QRect QDesktopWidget::screenGeometry(const QWidget *widget) const
-{
- return QDesktopWidgetPrivate::screenGeometry(widget);
-}
-
-const QRect QDesktopWidgetPrivate::screenGeometry(const QWidget *widget)
-{
- if (Q_UNLIKELY(!widget)) {
- qWarning("QDesktopWidget::screenGeometry(): Attempt "
- "to get the screen geometry of a null widget");
- return QRect();
- }
- QRect rect = QWidgetPrivate::screenGeometry(widget);
- if (rect.isNull())
- return screenGeometry(screenNumber(widget));
- else return rect;
-}
-
-const QRect QDesktopWidget::availableGeometry(const QWidget *widget) const
-{
- return QDesktopWidgetPrivate::availableGeometry(widget);
-}
-
-const QRect QDesktopWidgetPrivate::availableGeometry(const QWidget *widget)
-{
- if (Q_UNLIKELY(!widget)) {
- qWarning("QDesktopWidget::availableGeometry(): Attempt "
- "to get the available geometry of a null widget");
- return QRect();
- }
- QRect rect = QWidgetPrivate::screenGeometry(widget);
- if (rect.isNull())
- return availableGeometry(screenNumber(widget));
- else
- return rect;
-}
-
-QDesktopScreenWidget *QDesktopWidgetPrivate::widgetForScreen(QScreen *qScreen) const
-{
- foreach (QDesktopScreenWidget *widget, screens) {
- if (widget->assignedScreen() == qScreen)
- return widget;
- }
- return nullptr;
-}
-
-void QDesktopWidgetPrivate::_q_updateScreens()
-{
- Q_Q(QDesktopWidget);
- const QList<QScreen *> screenList = QGuiApplication::screens();
- const int targetLength = screenList.length();
- bool screenCountChanged = false;
-
- // Re-build our screens list. This is the easiest way to later compute which signals to emit.
- // Create new screen widgets as necessary. While iterating, keep the old list in place so
- // that widgetForScreen works.
- // Furthermore, we note which screens have changed, and compute the overall virtual geometry.
- QList<QDesktopScreenWidget *> newScreens;
- QList<int> changedScreens;
- QRegion virtualGeometry;
-
- for (int i = 0; i < targetLength; ++i) {
- QScreen *qScreen = screenList.at(i);
- const QRect screenGeometry = qScreen->geometry();
- QDesktopScreenWidget *screenWidget = widgetForScreen(qScreen);
- if (screenWidget) {
- // an old screen. update geometry and remember the index in the *new* list
- if (screenGeometry != screenWidget->screenGeometry()) {
- screenWidget->setScreenGeometry(screenGeometry);
- changedScreens.push_back(i);
- }
- } else {
- // a new screen, create a widget and connect the signals.
- screenWidget = new QDesktopScreenWidget(qScreen, screenGeometry);
- QObject::connect(qScreen, SIGNAL(geometryChanged(QRect)),
- q, SLOT(_q_updateScreens()), Qt::QueuedConnection);
- QObject::connect(qScreen, SIGNAL(availableGeometryChanged(QRect)),
- q, SLOT(_q_availableGeometryChanged()), Qt::QueuedConnection);
- QObject::connect(qScreen, SIGNAL(destroyed()),
- q, SLOT(_q_updateScreens()), Qt::QueuedConnection);
- screenCountChanged = true;
- }
- // record all the screens and the overall geometry.
- newScreens.push_back(screenWidget);
- virtualGeometry += screenGeometry;
- }
-
- // Now we apply the accumulated updates.
- screens.swap(newScreens); // now [newScreens] is the old screen list
- Q_ASSERT(screens.size() == targetLength);
- q->setGeometry(virtualGeometry.boundingRect());
-
- // Delete the QDesktopScreenWidget that are not used any more.
- foreach (QDesktopScreenWidget *screen, newScreens) {
- if (!screens.contains(screen)) {
- delete screen;
- screenCountChanged = true;
- }
- }
-
- // Finally, emit the signals.
- if (screenCountChanged) {
- // Notice that we trigger screenCountChanged even if a screen was removed and another one added,
- // in which case the total number of screens did not change. This is the only way for applications
- // to notice that a screen was swapped out against another one.
-#if QT_DEPRECATED_SINCE(5, 11)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit q->screenCountChanged(targetLength);
-QT_WARNING_POP
-#endif
- }
-#if QT_DEPRECATED_SINCE(5, 11)
- foreach (int changedScreen, changedScreens)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit q->resized(changedScreen);
-QT_WARNING_POP
-#endif
-}
-
-void QDesktopWidgetPrivate::_q_availableGeometryChanged()
-{
-#if QT_DEPRECATED_SINCE(5, 11)
- Q_Q(QDesktopWidget);
- if (QScreen *screen = qobject_cast<QScreen *>(q->sender()))
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit q->workAreaResized(QGuiApplication::screens().indexOf(screen));
-QT_WARNING_POP
-#endif
-}
-
-QDesktopWidget::QDesktopWidget()
- : QWidget(*new QDesktopWidgetPrivate, nullptr, Qt::Desktop)
-{
- Q_D(QDesktopWidget);
- setObjectName(QLatin1String("desktop"));
- d->_q_updateScreens();
- connect(qApp, SIGNAL(screenAdded(QScreen*)), this, SLOT(_q_updateScreens()));
-#if QT_DEPRECATED_SINCE(5, 11)
- connect(qApp, SIGNAL(primaryScreenChanged(QScreen*)), this, SIGNAL(primaryScreenChanged()));
-#endif
-}
-
-QDesktopWidget::~QDesktopWidget()
-{
-}
-
-#if QT_DEPRECATED_SINCE(5, 11)
-bool QDesktopWidget::isVirtualDesktop() const
-{
- return QDesktopWidgetPrivate::isVirtualDesktop();
-}
-#endif
-
-bool QDesktopWidgetPrivate::isVirtualDesktop()
-{
- return QGuiApplication::primaryScreen()->virtualSiblings().size() > 1;
-}
-
-QRect QDesktopWidgetPrivate::geometry()
-{
- return QGuiApplication::primaryScreen()->virtualGeometry();
-}
-
-QSize QDesktopWidgetPrivate::size()
-{
- return geometry().size();
-}
-
-int QDesktopWidgetPrivate::width()
-{
- return geometry().width();
-}
-
-int QDesktopWidgetPrivate::height()
-{
- return geometry().height();
-}
-
-#if QT_DEPRECATED_SINCE(5, 11)
-int QDesktopWidget::primaryScreen() const
-{
- return QDesktopWidgetPrivate::primaryScreen();
-}
-#endif
-
-int QDesktopWidgetPrivate::primaryScreen()
-{
- return 0;
-}
-
-int QDesktopWidgetPrivate::numScreens()
-{
- return qMax(QGuiApplication::screens().size(), 1);
-}
-
-#if QT_DEPRECATED_SINCE(5, 11)
-int QDesktopWidget::numScreens() const
-{
- return QDesktopWidgetPrivate::numScreens();
-}
-
-QWidget *QDesktopWidget::screen(int screen)
-{
- Q_D(QDesktopWidget);
- if (screen < 0 || screen >= d->screens.length())
- return d->screens.at(0);
- return d->screens.at(screen);
-}
-
-const QRect QDesktopWidget::availableGeometry(int screenNo) const
-{
- return QDesktopWidgetPrivate::availableGeometry(screenNo);
-}
-#endif
-
-const QRect QDesktopWidgetPrivate::availableGeometry(int screenNo)
-{
- const QScreen *screen = QDesktopWidgetPrivate::screen(screenNo);
- return screen ? screen->availableGeometry() : QRect();
-}
-
-#if QT_DEPRECATED_SINCE(5, 11)
-const QRect QDesktopWidget::screenGeometry(int screenNo) const
-{
- return QDesktopWidgetPrivate::screenGeometry(screenNo);
-}
-#endif
-
-const QRect QDesktopWidgetPrivate::screenGeometry(int screenNo)
-{
- const QScreen *screen = QDesktopWidgetPrivate::screen(screenNo);
- return screen ? screen->geometry() : QRect();
-}
-
-int QDesktopWidget::screenNumber(const QWidget *w) const
-{
- return QDesktopWidgetPrivate::screenNumber(w);
-}
-
-int QDesktopWidgetPrivate::screenNumber(const QWidget *w)
-{
- if (!w)
- return primaryScreen();
-
- const QList<QScreen *> allScreens = QGuiApplication::screens();
- QList<QScreen *> screens = allScreens;
- if (screens.isEmpty()) // This should never happen
- return primaryScreen();
-
- // If there is more than one virtual desktop
- if (screens.count() != screens.constFirst()->virtualSiblings().count()) {
- // Find the root widget, get a QScreen from it and use the
- // virtual siblings for checking the window position.
- if (const QScreen *winScreen = qt_widget_private(const_cast<QWidget *>(w))->associatedScreen())
- screens = winScreen->virtualSiblings();
- }
-
- // Get the screen number from window position using screen geometry
- // and proper screens.
- QRect frame = w->frameGeometry();
- if (!w->isWindow())
- frame.moveTopLeft(w->mapToGlobal(QPoint(0, 0)));
-
- QScreen *widgetScreen = nullptr;
- int largestArea = 0;
- foreach (QScreen *screen, screens) {
- const QRect deviceIndependentScreenGeometry =
- QHighDpi::fromNativePixels(screen->handle()->geometry(), screen);
- const QRect intersected = deviceIndependentScreenGeometry.intersected(frame);
- int area = intersected.width() * intersected.height();
- if (largestArea < area) {
- widgetScreen = screen;
- largestArea = area;
- }
- }
- return allScreens.indexOf(widgetScreen);
-}
-
-#if QT_DEPRECATED_SINCE(5, 11)
-int QDesktopWidget::screenNumber(const QPoint &p) const
-{
- return QDesktopWidgetPrivate::screenNumber(p);
-}
-#endif
-
-int QDesktopWidgetPrivate::screenNumber(const QPoint &p)
-{
- QScreen *screen = QGuiApplication::screenAt(p);
- return screen ? QGuiApplication::screens().indexOf(screen) : primaryScreen();
-}
-
-QScreen *QDesktopWidgetPrivate::screen(int screenNo)
-{
- QList<QScreen *> screens = QGuiApplication::screens();
- if (screenNo == -1)
- screenNo = 0;
- if (screenNo < 0 || screenNo >= screens.size())
- return nullptr;
- return screens.at(screenNo);
-}
-
-void QDesktopWidget::resizeEvent(QResizeEvent *)
-{
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qdesktopwidget.cpp"
-#include "moc_qdesktopwidget_p.cpp"
diff --git a/src/widgets/kernel/qdesktopwidget.h b/src/widgets/kernel/qdesktopwidget.h
deleted file mode 100644
index e5c587984f..0000000000
--- a/src/widgets/kernel/qdesktopwidget.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDESKTOPWIDGET_H
-#define QDESKTOPWIDGET_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtWidgets/qwidget.h>
-
-QT_BEGIN_NAMESPACE
-
-
-class QApplication;
-class QDesktopWidgetPrivate;
-
-class Q_WIDGETS_EXPORT QDesktopWidget : public QWidget
-{
- Q_OBJECT
-#if QT_DEPRECATED_SINCE(5, 11)
- Q_PROPERTY(bool virtualDesktop READ isVirtualDesktop)
- Q_PROPERTY(int screenCount READ screenCount NOTIFY screenCountChanged)
- Q_PROPERTY(int primaryScreen READ primaryScreen NOTIFY primaryScreenChanged)
-#endif
-public:
- QDesktopWidget();
- ~QDesktopWidget();
-
- int screenNumber(const QWidget *widget = nullptr) const;
- const QRect screenGeometry(const QWidget *widget) const;
- const QRect availableGeometry(const QWidget *widget) const;
-
-#if QT_DEPRECATED_SINCE(5, 11)
- QT_DEPRECATED_X("Use QScreen::virtualSiblings() of primary screen") bool isVirtualDesktop() const;
-
- QT_DEPRECATED_X("Use QGuiApplication::screens()") int numScreens() const;
- QT_DEPRECATED_X("Use QGuiApplication::screens()") int screenCount() const;
- QT_DEPRECATED_X("Use QGuiApplication::primaryScreen()") int primaryScreen() const;
-
- QT_DEPRECATED_X("Use QGuiApplication::screenAt()") int screenNumber(const QPoint &) const;
-
- QT_DEPRECATED_X("Use QScreen") QWidget *screen(int screen = -1);
-
- QT_DEPRECATED_X("Use QGuiApplication::screens()") const QRect screenGeometry(int screen = -1) const;
- QT_DEPRECATED_X("Use QGuiApplication::screenAt()") const QRect screenGeometry(const QPoint &point) const
- {
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- return screenGeometry(screenNumber(point));
-QT_WARNING_POP
- }
-
- QT_DEPRECATED_X("Use QGuiApplication::screens()") const QRect availableGeometry(int screen = -1) const;
- QT_DEPRECATED_X("Use QGuiApplication::screenAt()") const QRect availableGeometry(const QPoint &point) const
- {
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- return availableGeometry(screenNumber(point));
-QT_WARNING_POP
- }
-
-Q_SIGNALS:
- QT_DEPRECATED_X("Use QScreen::geometryChanged()") void resized(int);
- QT_DEPRECATED_X("Use QScreen::availableGeometryChanged()") void workAreaResized(int);
- QT_DEPRECATED_X("Use QGuiApplication::screenAdded/Removed()") void screenCountChanged(int);
- QT_DEPRECATED_X("Use QGuiApplication::primaryScreenChanged()") void primaryScreenChanged();
-#endif
-
-protected:
- void resizeEvent(QResizeEvent *e) override;
-
-private:
- Q_DISABLE_COPY(QDesktopWidget)
- Q_DECLARE_PRIVATE(QDesktopWidget)
- Q_PRIVATE_SLOT(d_func(), void _q_updateScreens())
- Q_PRIVATE_SLOT(d_func(), void _q_availableGeometryChanged())
-
- friend class QApplication;
- friend class QApplicationPrivate;
-};
-
-#if QT_DEPRECATED_SINCE(5, 11)
-inline int QDesktopWidget::screenCount() const
-{
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- return numScreens();
-QT_WARNING_POP
-}
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QDESKTOPWIDGET_H
diff --git a/src/widgets/kernel/qdesktopwidget.qdoc b/src/widgets/kernel/qdesktopwidget.qdoc
deleted file mode 100644
index dd2d9535ae..0000000000
--- a/src/widgets/kernel/qdesktopwidget.qdoc
+++ /dev/null
@@ -1,336 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*!
- \class QDesktopWidget
- \brief The QDesktopWidget class provides access to screen information on multi-head systems.
-
- \ingroup advanced
- \ingroup desktop
- \inmodule QtWidgets
- \obsolete
-
- Systems with more than one graphics card and monitor can manage the
- physical screen space available either as multiple desktops, or as a
- large virtual desktop.
-
- This class provides information about the user's desktop, such as its
- total size, number of screens, the geometry of each screen, and whether
- they are configured as separate desktops or a single virtual desktop.
-
- Widgets provided by Qt use this class to place tooltips, menus and
- dialog boxes on the correct screen for their parent or application
- widgets. Applications can use this class to obtain information that
- can be used to save window positions, or to place child widgets and
- dialogs on one particular screen.
-
- \section1 Obtaining a Desktop Widget
-
- The QApplication::desktop() function is used to get an instance of
- QDesktopWidget.
-
- The widget's screenGeometry() function provides information about the
- geometry of the available screens with. The number of screens
- available is returned by screenCount, and the screenCountChanged()
- signal is emitted when screens are added or removed.
- The screen number that a particular point or widget is located in
- is returned by screenNumber().
-
- \section1 Screen Geometry
-
- To obtain the dimensions of a particular screen, call the screenGeometry()
- function. On some desktop environments, not all of the screen is
- available for applications to use; for example, an application dock or
- menu bar may take up some space. Use the availableGeometry() function
- to obtain the available area for applications.
-
- QDesktopWidget also inherits the QWidget properties, width() and
- height(), which specify the size of the desktop. However, for
- desktops with multiple screens, the size of the desktop is the union
- of all the screen sizes, so width() and height() should \e not be
- used for computing the size of a widget to be placed on one of the
- screens.
-
- On systems that are configured to use the available screens as a
- single, large virtual desktop, the virtualDesktop property will be
- set to true. In this case, the widget's size is usually the size of
- the bounding rectangle of all the screens.
-
- \section1 Use of the Primary Screen
-
- For an application, the screen where the main widget resides is the
- primary screen. This is stored in the primaryScreen property.
- All windows opened in the context of the application should be
- constrained to the boundaries of the primary screen; for example,
- it would be inconvenient if a dialog box popped up on a different
- screen, or split over two screens.
-
- \image qdesktopwidget.png Managing Multiple Screens
-
- In the illustration above, Application One's primary screen is
- screen 0, and App Two's primary screen is screen 1.
-
- \sa QApplication, QApplication::desktop()
-*/
-
-/*!
- \fn QDesktopWidget::QDesktopWidget()
-
- \internal
-
- Creates the desktop widget.
-
- If the system supports a virtual desktop, this widget will have
- the size of the virtual desktop; otherwise this widget will have
- the size of the primary screen.
-
- Instead of using QDesktopWidget directly, use QApplication::desktop().
-*/
-
-/*!
- \fn QDesktopWidget::~QDesktopWidget()
-
- \internal
-
- Destroys the desktop widget and frees any allocated resources.
-*/
-
-/*!
- \fn int QDesktopWidget::numScreens() const
-
- Returns the number of available screens.
-
- \obsolete
-
- Use QGuiApplication::screens() instead.
-
- \sa primaryScreen
-*/
-
-/*!
- \fn QWidget *QDesktopWidget::screen(int screen)
-
- Returns a widget that represents the screen with index \a screen
- (a value of -1 means the default screen).
-
- If the system uses a virtual desktop, the returned widget will
- have the geometry of the entire virtual desktop; i.e., bounding
- every \a screen.
-
- \obsolete
-
- Use QScreen instead.
-
- \sa primaryScreen, screenCount, virtualDesktop
-*/
-
-/*!
- \fn const QRect QDesktopWidget::availableGeometry(int screen) const
-
- Returns the available geometry of the screen with index \a screen. What
- is available will be subrect of screenGeometry() based on what the
- platform decides is available (for example excludes the dock and menu bar
- on \macos, or the task bar on Windows). The default screen is used if
- \a screen is -1.
-
- \obsolete
-
- Use QGuiApplication::screens() instead.
-
- \sa screenNumber(), screenGeometry(), QScreen::availableGeometry()
-*/
-
-/*!
- \fn const QRect QDesktopWidget::availableGeometry(const QWidget *widget) const
- \overload
-
- Returns the available geometry of the screen which contains \a widget.
-
- \sa screenGeometry()
-*/
-
-/*!
- \fn const QRect QDesktopWidget::availableGeometry(const QPoint &p) const
- \overload
-
- Returns the available geometry of the screen which contains \a p.
-
- \obsolete
-
- Use QGuiApplication::screenAt() instead.
-
- \sa screenGeometry()
-*/
-
-
-/*!
- \fn const QRect QDesktopWidget::screenGeometry(int screen) const
-
- Returns the geometry of the screen with index \a screen. The default
- screen is used if \a screen is -1.
-
- \obsolete
-
- Use QGuiApplication::screens() instead.
-
- \sa screenNumber()
-*/
-
-/*!
- \fn const QRect QDesktopWidget::screenGeometry(const QWidget *widget) const
- \overload
-
- Returns the geometry of the screen which contains \a widget.
-*/
-
-/*!
- \fn const QRect QDesktopWidget::screenGeometry(const QPoint &p) const
- \overload
-
- Returns the geometry of the screen which contains \a p.
-
- \obsolete
-
- Use QGuiApplication::screenAt() instead.
-*/
-
-
-/*!
- \fn int QDesktopWidget::screenNumber(const QWidget *widget) const
-
- Returns the index of the screen that contains the largest
- part of \a widget, or -1 if the widget not on a screen.
-
- \sa primaryScreen
-*/
-
-/*!
- \fn int QDesktopWidget::screenNumber(const QPoint &point) const
-
- \overload
- Returns the index of the screen that contains the \a point, or the
- screen which is the shortest distance from the \a point.
-
- \obsolete
-
- Use QGuiApplication::screenAt() instead.
-
- \sa primaryScreen
-*/
-
-/*!
- \fn void QDesktopWidget::resizeEvent(QResizeEvent *event)
- \reimp
- \internal
-*/
-
-/*!
- \fn void QDesktopWidget::resized(int screen)
-
- This signal is emitted when the size of \a screen changes.
-
- \obsolete
-
- Use QScreen::geometryChanged() instead.
-*/
-
-/*!
- \fn void QDesktopWidget::workAreaResized(int screen)
-
- This signal is emitted when the work area available on \a screen changes.
-
- \obsolete
-
- Use QScreen::availableGeometryChanged() instead.
-*/
-
-/*!
- \property QDesktopWidget::screenCount
- \brief the number of screens currently available on the system.
-
- \obsolete
-
- Use QGuiApplication::screens() instead.
-
- \since 4.6
-*/
-
-/*!
- \property QDesktopWidget::primaryScreen
- \brief the index of the screen that is configured to be the primary screen
- on the system.
-
- \obsolete
-
- Use QGuiApplication::primaryScreen() instead.
-*/
-
-/*!
- \property QDesktopWidget::virtualDesktop
-
- \brief if the system manages the available screens in a virtual desktop.
-
- For virtual desktops, screen() will always return the same widget.
- The size of the virtual desktop is the size of this desktop
- widget.
-
- \obsolete
-
- Use QScreen::virtualSiblings() of primary screen instead.
-*/
-
-/*!
- \fn void QDesktopWidget::screenCountChanged(int newCount)
-
- \since 4.6
-
- This signal is emitted when the number of screens changes to \a newCount.
-
- \obsolete
-
- Use QGuiApplication::screenAdded and QGuiApplication::screenRemoved() instead.
-
- \sa screenCount
-*/
-
-
-/*!
- \fn void QDesktopWidget::primaryScreenChanged()
-
- \since 5.6
-
- \brief This signal is emitted whenever the primary screen changes.
-
- \note This doesn't mean the QDesktopWidget::primaryScreen index will
- necessarily be different, but now it will refer to the new primary screen.
-
- \obsolete
-
- Use QGuiApplication::primaryScreenChanged() instead.
-
- \sa primaryScreen, screenGeometry()
-*/
diff --git a/src/widgets/kernel/qdesktopwidget_p.h b/src/widgets/kernel/qdesktopwidget_p.h
deleted file mode 100644
index 63949055aa..0000000000
--- a/src/widgets/kernel/qdesktopwidget_p.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of other Qt classes. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QDESKTOPWIDGET_P_H
-#define QDESKTOPWIDGET_P_H
-
-#include <QtWidgets/private/qtwidgetsglobal_p.h>
-#include "QDesktopWidget"
-#include "private/qwidget_p.h"
-
-#include <QtCore/qalgorithms.h>
-#include <QtGui/qscreen.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDesktopScreenWidget : public QWidget {
- Q_OBJECT
-public:
- explicit QDesktopScreenWidget(QScreen *screen, const QRect &geometry);
-
- int screenNumber() const;
- void setScreenGeometry(const QRect &geometry);
-
- QScreen *assignedScreen() const { return m_screen.data(); }
- QRect screenGeometry() const { return m_geometry; }
-
-private:
- // The widget updates its screen and geometry automatically. We need to save them separately
- // to detect changes, and trigger the appropriate signals.
- const QPointer<QScreen> m_screen;
- QRect m_geometry;
-};
-
-class QDesktopWidgetPrivate : public QWidgetPrivate {
- Q_DECLARE_PUBLIC(QDesktopWidget)
-
-public:
- ~QDesktopWidgetPrivate() { qDeleteAll(screens); }
- void _q_updateScreens();
- void _q_availableGeometryChanged();
- QDesktopScreenWidget *widgetForScreen(QScreen *qScreen) const;
-
- static bool isVirtualDesktop();
-
- static QRect geometry();
- static QSize size();
- static int width();
- static int height();
-
- static int numScreens();
- static int primaryScreen();
-
- static int screenNumber(const QWidget *widget = nullptr);
- static int screenNumber(const QPoint &);
-
- static QScreen *screen(int screenNo = -1);
-
- static const QRect screenGeometry(int screen = -1);
- static const QRect screenGeometry(const QWidget *widget);
- static const QRect screenGeometry(const QPoint &point)
- { return screenGeometry(screenNumber(point)); }
-
- static const QRect availableGeometry(int screen = -1);
- static const QRect availableGeometry(const QWidget *widget);
- static const QRect availableGeometry(const QPoint &point)
- { return availableGeometry(screenNumber(point)); }
-
- QList<QDesktopScreenWidget *> screens;
-};
-
-QT_END_NAMESPACE
-
-#endif // QDESKTOPWIDGET_QPA_P_H
diff --git a/src/widgets/kernel/qformlayout.cpp b/src/widgets/kernel/qformlayout.cpp
index 4ffa226d7f..01097b6123 100644
--- a/src/widgets/kernel/qformlayout.cpp
+++ b/src/widgets/kernel/qformlayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qapplication.h"
#include "qdebug.h"
@@ -43,19 +7,19 @@
#include "qlabel.h"
#include "qlayout_p.h"
#include "qlayoutengine_p.h"
+#include "qlist.h"
#include "qrect.h"
-#include "qvector.h"
#include "qwidget.h"
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>
class FixedColumnMatrix {
public:
- typedef QVector<T> Storage;
+ typedef QList<T> Storage;
FixedColumnMatrix() { }
@@ -104,13 +68,11 @@ 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
{
- QFormLayoutItem(QLayoutItem* i) : item(i), fullRow(false), isHfw(false) { }
+ QFormLayoutItem(QLayoutItem* i) : item(i) { }
~QFormLayoutItem() { delete item; }
// Wrappers
@@ -127,37 +89,68 @@ struct QFormLayoutItem
void setGeometry(const QRect& r) { item->setGeometry(r); }
QRect geometry() const { return item->geometry(); }
+ void setVisible(bool on);
+ bool isHidden() const { return !isVisible || (widget() && widget()->isHidden()); }
+
// For use with FixedColumnMatrix
bool operator==(const QFormLayoutItem& other) { return item == other.item; }
- QLayoutItem *item;
- bool fullRow;
+ QLayoutItem *item = nullptr;
+ bool fullRow = false;
+ bool isVisible = true;
// set by updateSizes
- bool isHfw;
+ bool isHfw = false;
QSize minSize;
QSize sizeHint;
QSize maxSize;
// also set by updateSizes
- int sbsHSpace; // only used for side by side, for the field item only (not label)
- int vSpace; // This is the spacing to the item in the row above
+ int sbsHSpace = -1; // only used for side by side, for the field item only (not label)
+ int vSpace = -1; // This is the spacing to the item in the row above
// set by setupVerticalLayoutData
- bool sideBySide;
- int vLayoutIndex;
+ bool sideBySide = false;
+ int vLayoutIndex = -1;
// set by setupHorizontalLayoutData
- int layoutPos;
- int layoutWidth;
+ int layoutPos = -1;
+ int layoutWidth = -1;
};
+static void hideOrShowWidgetsInLayout(QLayout *layout, bool on)
+{
+ for (int i = 0; i < layout->count(); ++i) {
+ QLayoutItem *item = layout->itemAt(i);
+ if (QWidget *widget = item->widget())
+ widget->setVisible(on);
+ else if (item->layout())
+ hideOrShowWidgetsInLayout(item->layout(), on);
+ }
+}
+
+void QFormLayoutItem::setVisible(bool on)
+{
+ isVisible = on;
+ // Explicitly hide the widget so that it loses focus and
+ // doesn't automatically get shown again when this layout
+ // hides and shows.
+ if (widget()) {
+ widget()->setVisible(on);
+ return;
+ }
+ // Layouts can't be hidden, so we have to traverse the widgets
+ // inside and hide all of them so that they also lose focus.
+ if (layout())
+ hideOrShowWidgetsInLayout(layout(), on);
+}
+
class QFormLayoutPrivate : public QLayoutPrivate
{
Q_DECLARE_PUBLIC(QFormLayout)
public:
- typedef FixedColumnMatrix<QFormLayoutItem *, ColumnCount> ItemMatrix;
+ using ItemMatrix = QtPrivate::FixedColumnMatrix<QFormLayoutItem *, 2>;
QFormLayoutPrivate();
~QFormLayoutPrivate() { }
@@ -169,7 +162,7 @@ public:
void setLayout(int row, QFormLayout::ItemRole role, QLayout *layout);
void setWidget(int row, QFormLayout::ItemRole role, QWidget *widget);
- void arrangeWidgets(const QVector<QLayoutStruct>& layouts, QRect &rect);
+ void arrangeWidgets(const QList<QLayoutStruct> &layouts, QRect &rect);
void updateSizes();
@@ -215,11 +208,11 @@ public:
int formMaxWidth;
void calcSizeHints();
- QVector<QLayoutStruct> vLayouts; // set by setupVerticalLayoutData;
+ QList<QLayoutStruct> vLayouts; // set by setupVerticalLayoutData;
int vLayoutCount; // Number of rows we calculated in setupVerticalLayoutData
int maxLabelWidth; // the label width we calculated in setupVerticalLayoutData
- QVector<QLayoutStruct> hfwLayouts;
+ QList<QLayoutStruct> hfwLayouts;
int hSpacing = -1;
int vSpacing = -1;
@@ -378,23 +371,25 @@ void QFormLayoutPrivate::updateSizes()
QSizePolicy::ControlTypes(fldtop ? fldtop->controlTypes() : QSizePolicy::DefaultType);
// To be compatible to QGridLayout, we have to compare solitary labels & fields with both predecessors
- if (label) {
+ if (label && !label->isHidden()) {
if (!field) {
int lblspacing = style->combinedLayoutSpacing(lbltoptypes, lbltypes, Qt::Vertical, nullptr, parent);
int fldspacing = style->combinedLayoutSpacing(fldtoptypes, lbltypes, Qt::Vertical, nullptr, parent);
label->vSpace = qMax(lblspacing, fldspacing);
- } else
+ } else {
label->vSpace = style->combinedLayoutSpacing(lbltoptypes, lbltypes, Qt::Vertical, nullptr, parent);
+ }
}
- if (field) {
+ if (field && !field->isHidden()) {
// check spacing against both the previous label and field
if (!label) {
int lblspacing = style->combinedLayoutSpacing(lbltoptypes, fldtypes, Qt::Vertical, nullptr, parent);
int fldspacing = style->combinedLayoutSpacing(fldtoptypes, fldtypes, Qt::Vertical, nullptr, parent);
field->vSpace = qMax(lblspacing, fldspacing);
- } else
+ } else {
field->vSpace = style->combinedLayoutSpacing(fldtoptypes, fldtypes, Qt::Vertical, nullptr, parent);
+ }
}
}
}
@@ -483,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
@@ -507,7 +503,11 @@ void QFormLayoutPrivate::setupHfwLayoutData()
QFormLayoutItem *label = m_matrix(i, 0);
QFormLayoutItem *field = m_matrix(i, 1);
- if (label) {
+ // 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
// ever side by side with its field
@@ -522,7 +522,7 @@ void QFormLayoutPrivate::setupHfwLayoutData()
}
}
- if (field) {
+ if (field && field->vLayoutIndex > -1) {
int hfw = field->isHfw ? field->heightForWidth(field->layoutWidth) : 0;
int h = field->isHfw ? hfw : field->sizeHint.height();
int mh = field->isHfw ? hfw : field->minSize.height();
@@ -681,12 +681,18 @@ void QFormLayoutPrivate::setupVerticalLayoutData(int width)
bool prevRowSplit = false;
for (int i = 0; i < rr; ++i) {
- QFormLayoutItem *label = m_matrix(i, 0);
+ QFormLayoutItem *label = m_matrix(i, 0);
QFormLayoutItem *field = m_matrix(i, 1);
- // Totally ignore empty rows...
- if (!label && !field)
+ // 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;
@@ -1189,6 +1195,10 @@ QLayoutItem* QFormLayoutPrivate::replaceAt(int index, QLayoutItem *newitem)
/*!
Constructs a new form layout with the given \a parent widget.
+ The layout is set directly as the top-level layout for \a parent.
+ There can be only one top-level layout for a widget. It is returned
+ by QWidget::layout().
+
\sa QWidget::setLayout()
*/
QFormLayout::QFormLayout(QWidget *parent)
@@ -1642,7 +1652,7 @@ void QFormLayout::addItem(QLayoutItem *item)
int QFormLayout::count() const
{
Q_D(const QFormLayout);
- return d->m_things.count();
+ return d->m_things.size();
}
/*!
@@ -2167,7 +2177,7 @@ int QFormLayout::spacing() const
}
}
-void QFormLayoutPrivate::arrangeWidgets(const QVector<QLayoutStruct>& layouts, QRect &rect)
+void QFormLayoutPrivate::arrangeWidgets(const QList<QLayoutStruct> &layouts, QRect &rect)
{
Q_Q(QFormLayout);
@@ -2189,7 +2199,10 @@ void QFormLayoutPrivate::arrangeWidgets(const QVector<QLayoutStruct>& layouts, Q
QFormLayoutItem *label = m_matrix(i, 0);
QFormLayoutItem *field = m_matrix(i, 1);
- if (label) {
+ if (!q->isRowVisible(i))
+ continue;
+
+ if (label && label->vLayoutIndex > -1) {
int height = layouts.at(label->vLayoutIndex).size;
if ((label->expandingDirections() & Qt::Vertical) == 0) {
/*
@@ -2216,7 +2229,7 @@ void QFormLayoutPrivate::arrangeWidgets(const QVector<QLayoutStruct>& layouts, Q
label->setGeometry(QStyle::visualRect(layoutDirection, rect, QRect(p, sz)));
}
- if (field) {
+ if (field && field->vLayoutIndex > -1) {
QSize sz(field->layoutWidth, layouts.at(field->vLayoutIndex).size);
QPoint p(field->layoutPos + leftOffset + rect.x(), layouts.at(field->vLayoutIndex).pos);
/*
@@ -2296,6 +2309,158 @@ void QFormLayout::setItem(int row, ItemRole role, QLayoutItem *item)
}
/*!
+ \since 6.4
+
+ Shows the row \a row if \a on is true, otherwise hides the row.
+
+ \a row must be non-negative and less than rowCount().
+
+ \sa removeRow(), takeRow()
+*/
+void QFormLayout::setRowVisible(int row, bool on)
+{
+ Q_D(QFormLayout);
+ QFormLayoutItem *label = d->m_matrix(row, 0);
+ QFormLayoutItem *field = d->m_matrix(row, 1);
+ bool change = false;
+ if (label) {
+ change = label->isVisible != on;
+ label->setVisible(on);
+ }
+ if (field) {
+ change |= field->isVisible != on;
+ field->setVisible(on);
+ }
+ if (change)
+ invalidate();
+}
+
+/*!
+ \since 6.4
+
+ \overload
+
+ Shows the row corresponding to \a widget if \a on is true,
+ otherwise hides the row.
+
+ \sa removeRow(), takeRow()
+*/
+void QFormLayout::setRowVisible(QWidget *widget, bool on)
+{
+ Q_D(QFormLayout);
+ if (Q_UNLIKELY(!d->checkWidget(widget)))
+ return;
+
+ int row;
+ ItemRole role;
+ getWidgetPosition(widget, &row, &role);
+
+ if (Q_UNLIKELY(row < 0)) {
+ qWarning("QFormLayout::setRowVisible: Invalid widget");
+ return;
+ }
+
+ setRowVisible(row, on);
+}
+
+/*!
+ \since 6.4
+
+ \overload
+
+ Shows the row corresponding to \a layout if \a on is true,
+ otherwise hides the row.
+
+ \sa removeRow(), takeRow()
+*/
+void QFormLayout::setRowVisible(QLayout *layout, bool on)
+{
+ Q_D(QFormLayout);
+ if (Q_UNLIKELY(!d->checkLayout(layout)))
+ return;
+
+ int row;
+ ItemRole role;
+ getLayoutPosition(layout, &row, &role);
+
+ if (Q_UNLIKELY(row < 0)) {
+ qWarning("QFormLayout::setRowVisible: Invalid layout");
+ return;
+ }
+
+ setRowVisible(row, on);
+}
+
+/*!
+ \since 6.4
+
+ Returns true if some items in the row \a row are visible,
+ otherwise returns false.
+*/
+bool QFormLayout::isRowVisible(int row) const
+{
+ Q_D(const QFormLayout);
+ QFormLayoutItem *label = d->m_matrix(row, 0);
+ QFormLayoutItem *field = d->m_matrix(row, 1);
+
+ int visibleItemCount = 2;
+ if (!label || label->isHidden() || (label->widget() && label->widget()->isHidden()))
+ --visibleItemCount;
+ if (!field || field->isHidden() || (field->widget() && field->widget()->isHidden()))
+ --visibleItemCount;
+
+ return visibleItemCount > 0;
+}
+
+/*!
+ \since 6.4
+ \overload
+
+ Returns true if some items in the row corresponding to \a widget
+ are visible, otherwise returns false.
+*/
+bool QFormLayout::isRowVisible(QWidget *widget) const
+{
+ Q_D(const QFormLayout);
+ if (Q_UNLIKELY(!d->checkWidget(widget)))
+ return false;
+ int row;
+ ItemRole role;
+ getWidgetPosition(widget, &row, &role);
+
+ if (Q_UNLIKELY(row < 0)) {
+ qWarning("QFormLayout::takeRow: Invalid widget");
+ return false;
+ }
+
+ return isRowVisible(row);
+}
+
+/*!
+ \since 6.4
+ \overload
+
+ Returns true if some items in the row corresponding to \a layout
+ are visible, otherwise returns false.
+*/
+bool QFormLayout::isRowVisible(QLayout *layout) const
+{
+ Q_D(const QFormLayout);
+ if (Q_UNLIKELY(!d->checkLayout(layout)))
+ return false;
+ int row;
+ ItemRole role;
+ getLayoutPosition(layout, &row, &role);
+
+ if (Q_UNLIKELY(row < 0)) {
+ qWarning("QFormLayout::takeRow: Invalid layout");
+ return false;
+ }
+
+ return isRowVisible(row);
+}
+
+/*!
\internal
*/
diff --git a/src/widgets/kernel/qformlayout.h b/src/widgets/kernel/qformlayout.h
index 40424f2a49..b24fe131a0 100644
--- a/src/widgets/kernel/qformlayout.h
+++ b/src/widgets/kernel/qformlayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFORMLAYOUT_H
#define QFORMLAYOUT_H
@@ -54,10 +18,14 @@ class Q_WIDGETS_EXPORT QFormLayout : public QLayout
{
Q_OBJECT
Q_DECLARE_PRIVATE(QFormLayout)
- Q_PROPERTY(FieldGrowthPolicy fieldGrowthPolicy READ fieldGrowthPolicy WRITE setFieldGrowthPolicy RESET resetFieldGrowthPolicy)
- Q_PROPERTY(RowWrapPolicy rowWrapPolicy READ rowWrapPolicy WRITE setRowWrapPolicy RESET resetRowWrapPolicy)
- Q_PROPERTY(Qt::Alignment labelAlignment READ labelAlignment WRITE setLabelAlignment RESET resetLabelAlignment)
- Q_PROPERTY(Qt::Alignment formAlignment READ formAlignment WRITE setFormAlignment RESET resetFormAlignment)
+ Q_PROPERTY(FieldGrowthPolicy fieldGrowthPolicy READ fieldGrowthPolicy WRITE setFieldGrowthPolicy
+ RESET resetFieldGrowthPolicy)
+ Q_PROPERTY(RowWrapPolicy rowWrapPolicy READ rowWrapPolicy WRITE setRowWrapPolicy
+ RESET resetRowWrapPolicy)
+ Q_PROPERTY(Qt::Alignment labelAlignment READ labelAlignment WRITE setLabelAlignment
+ RESET resetLabelAlignment)
+ Q_PROPERTY(Qt::Alignment formAlignment READ formAlignment WRITE setFormAlignment
+ RESET resetFormAlignment)
Q_PROPERTY(int horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing)
Q_PROPERTY(int verticalSpacing READ verticalSpacing WRITE setVerticalSpacing)
@@ -105,8 +73,8 @@ public:
void setVerticalSpacing(int spacing);
int verticalSpacing() const;
- int spacing() const;
- void setSpacing(int);
+ int spacing() const override;
+ void setSpacing(int) override;
void addRow(QWidget *label, QWidget *field);
void addRow(QWidget *label, QLayout *field);
@@ -134,6 +102,14 @@ public:
void setWidget(int row, ItemRole role, QWidget *widget);
void setLayout(int row, ItemRole role, QLayout *layout);
+ void setRowVisible(int row, bool on);
+ void setRowVisible(QWidget *widget, bool on);
+ void setRowVisible(QLayout *layout, bool on);
+
+ bool isRowVisible(int row) const;
+ bool isRowVisible(QWidget *widget) const;
+ bool isRowVisible(QLayout *layout) const;
+
QLayoutItem *itemAt(int row, ItemRole role) const;
void getItemPosition(int index, int *rowPtr, ItemRole *rolePtr) const;
void getWidgetPosition(QWidget *widget, int *rowPtr, ItemRole *rolePtr) const;
diff --git a/src/widgets/kernel/qgesture.cpp b/src/widgets/kernel/qgesture.cpp
index 84dbed7043..82b4d9ced8 100644
--- a/src/widgets/kernel/qgesture.cpp
+++ b/src/widgets/kernel/qgesture.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgesture.h"
#include "private/qgesture_p.h"
@@ -49,6 +13,13 @@
QT_BEGIN_NAMESPACE
+QT_IMPL_METATYPE_EXTERN_TAGGED(Qt::GestureState, Qt__GestureState)
+QT_IMPL_METATYPE_EXTERN_TAGGED(Qt::GestureType, Qt__GestureType)
+QT_IMPL_METATYPE_EXTERN_TAGGED(QPinchGesture::ChangeFlags,
+ QPinchGesture__ChangeFlags)
+QT_IMPL_METATYPE_EXTERN_TAGGED(QGesture::GestureCancelPolicy,
+ QGesture__GestureCancelPolicy)
+
/*!
\class QGesture
\since 4.6
@@ -1033,7 +1004,7 @@ void QGestureEvent::accept(Qt::GestureType gestureType)
of calling \l{QGestureEvent::setAccepted()}{setAccepted(gesture, false)}.
Clearing the accept flag indicates that the event receiver does not
- want the gesture. Unwanted gestures may be propgated to the parent widget.
+ want the gesture. Unwanted gestures may be propagated to the parent widget.
\sa QGestureEvent::accept()
*/
diff --git a/src/widgets/kernel/qgesture.h b/src/widgets/kernel/qgesture.h
index c5b2cee83d..7e7041ef76 100644
--- a/src/widgets/kernel/qgesture.h
+++ b/src/widgets/kernel/qgesture.h
@@ -1,47 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGESTURE_H
#define QGESTURE_H
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtCore/qobject.h>
+#include <QtCore/qmap.h>
#include <QtCore/qlist.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qpoint.h>
@@ -51,8 +16,10 @@
#ifndef QT_NO_GESTURES
-Q_DECLARE_METATYPE(Qt::GestureState)
-Q_DECLARE_METATYPE(Qt::GestureType)
+// ### move to qnamespace.h
+QT_DECL_METATYPE_EXTERN_TAGGED(Qt::GestureState, Qt__GestureState, Q_WIDGETS_EXPORT)
+// ### move to qnamespace.h
+QT_DECL_METATYPE_EXTERN_TAGGED(Qt::GestureType, Qt__GestureType, Q_WIDGETS_EXPORT)
QT_BEGIN_NAMESPACE
@@ -65,7 +32,8 @@ class Q_WIDGETS_EXPORT QGesture : public QObject
Q_PROPERTY(Qt::GestureState state READ state)
Q_PROPERTY(Qt::GestureType gestureType READ gestureType)
- Q_PROPERTY(QGesture::GestureCancelPolicy gestureCancelPolicy READ gestureCancelPolicy WRITE setGestureCancelPolicy)
+ Q_PROPERTY(QGesture::GestureCancelPolicy gestureCancelPolicy READ gestureCancelPolicy
+ WRITE setGestureCancelPolicy)
Q_PROPERTY(QPointF hotSpot READ hotSpot WRITE setHotSpot RESET unsetHotSpot)
Q_PROPERTY(bool hasHotSpot READ hasHotSpot)
@@ -142,7 +110,7 @@ public:
RotationAngleChanged = 0x2,
CenterPointChanged = 0x4
};
- Q_FLAG(ChangeFlag)
+ Q_ENUM(ChangeFlag)
Q_DECLARE_FLAGS(ChangeFlags, ChangeFlag)
Q_FLAG(ChangeFlags)
@@ -199,7 +167,8 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(QPinchGesture::ChangeFlags)
QT_END_NAMESPACE
-Q_DECLARE_METATYPE(QPinchGesture::ChangeFlags)
+QT_DECL_METATYPE_EXTERN_TAGGED(QPinchGesture::ChangeFlags,
+ QPinchGesture__ChangeFlags, Q_WIDGETS_EXPORT)
QT_BEGIN_NAMESPACE
@@ -322,7 +291,9 @@ Q_WIDGETS_EXPORT QDebug operator<<(QDebug, const QGestureEvent *);
QT_END_NAMESPACE
-Q_DECLARE_METATYPE(QGesture::GestureCancelPolicy)
+QT_DECL_METATYPE_EXTERN_TAGGED(QGesture::GestureCancelPolicy,
+ QGesture__GestureCancelPolicy, Q_WIDGETS_EXPORT)
+
#endif // QT_NO_GESTURES
#endif // QGESTURE_H
diff --git a/src/widgets/kernel/qgesture_p.h b/src/widgets/kernel/qgesture_p.h
index 057302bda1..1e4292abf9 100644
--- a/src/widgets/kernel/qgesture_p.h
+++ b/src/widgets/kernel/qgesture_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGESTURE_P_H
#define QGESTURE_P_H
diff --git a/src/widgets/kernel/qgesturemanager.cpp b/src/widgets/kernel/qgesturemanager.cpp
index 5604391059..c93876c500 100644
--- a/src/widgets/kernel/qgesturemanager.cpp
+++ b/src/widgets/kernel/qgesturemanager.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "private/qgesturemanager_p.h"
#include "private/qstandardgestures_p.h"
@@ -51,12 +15,13 @@
#include "qgesture.h"
#include "qevent.h"
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
#include "qmacgesturerecognizer_p.h"
#endif
#include "qdebug.h"
#include <QtCore/QLoggingCategory>
+#include <QtCore/QVarLengthArray>
#ifndef QT_NO_GESTURES
@@ -64,7 +29,7 @@ QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcGestureManager, "qt.widgets.gestures")
-#if !defined(Q_OS_OSX)
+#if !defined(Q_OS_MACOS)
static inline int panTouchPoints()
{
// Override by environment variable for testing.
@@ -85,11 +50,11 @@ 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>();
-#if defined(Q_OS_OSX)
+#if defined(Q_OS_MACOS)
registerGestureRecognizer(new QMacSwipeGestureRecognizer);
registerGestureRecognizer(new QMacPinchGestureRecognizer);
registerGestureRecognizer(new QMacPanGestureRecognizer);
@@ -105,11 +70,10 @@ QGestureManager::QGestureManager(QObject *parent)
QGestureManager::~QGestureManager()
{
qDeleteAll(m_recognizers);
- foreach (QGestureRecognizer *recognizer, m_obsoleteGestures.keys()) {
- qDeleteAll(m_obsoleteGestures.value(recognizer));
- delete recognizer;
+ for (auto it = m_obsoleteGestures.cbegin(), end = m_obsoleteGestures.cend(); it != end; ++it) {
+ qDeleteAll(it.value());
+ delete it.key();
}
- m_obsoleteGestures.clear();
}
Qt::GestureType QGestureManager::registerGestureRecognizer(QGestureRecognizer *recognizer)
@@ -134,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;
}
}
@@ -275,8 +237,8 @@ bool QGestureManager::filterEventThroughContexts(const QMultiMap<QObject *,
ContextIterator contextEnd = contexts.end();
for (ContextIterator context = contexts.begin(); context != contextEnd; ++context) {
Qt::GestureType gestureType = context.value();
- const QMap<Qt::GestureType, QGestureRecognizer *> &const_recognizers = m_recognizers;
- QMap<Qt::GestureType, QGestureRecognizer *>::const_iterator
+ const QMultiMap<Qt::GestureType, QGestureRecognizer *> &const_recognizers = m_recognizers;
+ QMultiMap<Qt::GestureType, QGestureRecognizer *>::const_iterator
typeToRecognizerIterator = const_recognizers.lowerBound(gestureType),
typeToRecognizerEnd = const_recognizers.upperBound(gestureType);
for (; typeToRecognizerIterator != typeToRecognizerEnd; ++typeToRecognizerIterator) {
@@ -318,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;
@@ -347,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);
@@ -366,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() ||
@@ -394,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) {
@@ -407,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);
}
@@ -482,7 +444,7 @@ void QGestureManager::cancelGesturesForChildren(QGesture *original)
void QGestureManager::cleanupGesturesForRemovedRecognizer(QGesture *gesture)
{
QGestureRecognizer *recognizer = m_deletedRecognizers.value(gesture);
- if(!recognizer) //The Gesture is removed while in the even loop, so the recognizers for this gestures was removed
+ if (!recognizer) //The Gesture is removed while in the even loop, so the recognizers for this gestures was removed
return;
m_deletedRecognizers.remove(gesture);
if (m_deletedRecognizers.keys(recognizer).isEmpty()) {
@@ -586,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)
@@ -687,7 +649,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;
@@ -695,7 +657,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 3a5c9822eb..02beb024f9 100644
--- a/src/widgets/kernel/qgesturemanager_p.h
+++ b/src/widgets/kernel/qgesturemanager_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGESTUREMANAGER_P_H
#define QGESTUREMANAGER_P_H
@@ -57,6 +21,8 @@
#include "private/qwidget_p.h"
#include "qgesturerecognizer.h"
+#include <QtCore/qpointer.h>
+
#ifndef QT_NO_GESTURES
#include <functional>
@@ -100,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/qgesturerecognizer.cpp b/src/widgets/kernel/qgesturerecognizer.cpp
index 75d091ce4e..50c394e9b0 100644
--- a/src/widgets/kernel/qgesturerecognizer.cpp
+++ b/src/widgets/kernel/qgesturerecognizer.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgesturerecognizer.h"
diff --git a/src/widgets/kernel/qgesturerecognizer.h b/src/widgets/kernel/qgesturerecognizer.h
index 04e85c46cc..de48fec399 100644
--- a/src/widgets/kernel/qgesturerecognizer.h
+++ b/src/widgets/kernel/qgesturerecognizer.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGESTURERECOGNIZER_H
#define QGESTURERECOGNIZER_H
diff --git a/src/widgets/kernel/qgridlayout.cpp b/src/widgets/kernel/qgridlayout.cpp
index b4ac263c2b..7998567a21 100644
--- a/src/widgets/kernel/qgridlayout.cpp
+++ b/src/widgets/kernel/qgridlayout.cpp
@@ -1,49 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgridlayout.h"
#include "qapplication.h"
-#include "qwidget.h"
+#include "qgridlayout.h"
#include "qlist.h"
#include "qsizepolicy.h"
-#include "qvector.h"
#include "qvarlengtharray.h"
+#include "qwidget.h"
+
#include "qlayoutengine_p.h"
#include "qlayout_p.h"
@@ -145,18 +109,18 @@ public:
int minimumHeightForWidth(int width, int hSpacing, int vSpacing);
inline void getNextPos(int &row, int &col) { row = nextR; col = nextC; }
- inline int count() const { return things.count(); }
+ inline int count() const { return things.size(); }
QRect cellRect(int row, int col) const;
inline QLayoutItem *itemAt(int index) const {
- if (index < things.count())
+ if (index >= 0 && index < things.size())
return things.at(index)->item();
else
return nullptr;
}
inline QLayoutItem *takeAt(int index) {
Q_Q(QGridLayout);
- if (index < things.count()) {
+ if (index >= 0 && index < things.size()) {
if (QGridBox *b = things.takeAt(index)) {
QLayoutItem *item = b->takeItem();
if (QLayout *l = item->layout()) {
@@ -184,7 +148,7 @@ public:
}
void getItemPosition(int index, int *row, int *column, int *rowSpan, int *columnSpan) const {
- if (index < things.count()) {
+ if (index >= 0 && index < things.size()) {
const QGridBox *b = things.at(index);
int toRow = b->toRow(rr);
int toCol = b->toCol(cc);
@@ -204,7 +168,7 @@ private:
QSize findSize(int QLayoutStruct::*, int hSpacing, int vSpacing) const;
void addData(QGridBox *b, const QGridLayoutSizeTriple &sizes, bool r, bool c);
void setSize(int rows, int cols);
- void setupSpacings(QVector<QLayoutStruct> &chain, QGridBox *grid[], int fixedSpacing,
+ void setupSpacings(QList<QLayoutStruct> &chain, QGridBox *grid[], int fixedSpacing,
Qt::Orientation orientation);
void setupLayoutData(int hSpacing, int vSpacing);
void setupHfwLayoutData();
@@ -212,13 +176,13 @@ private:
int rr;
int cc;
- QVector<QLayoutStruct> rowData;
- QVector<QLayoutStruct> colData;
- QVector<QLayoutStruct> *hfwData;
- QVector<int> rStretch;
- QVector<int> cStretch;
- QVector<int> rMinHeights;
- QVector<int> cMinWidths;
+ QList<QLayoutStruct> rowData;
+ QList<QLayoutStruct> colData;
+ QList<QLayoutStruct> *hfwData;
+ QList<int> rStretch;
+ QList<int> cStretch;
+ QList<int> rMinHeights;
+ QList<int> cMinWidths;
QList<QGridBox *> things;
int hfw_width;
@@ -253,7 +217,7 @@ void QGridLayoutPrivate::effectiveMargins(int *left, int *top, int *right, int *
int rightMost = 0;
int bottomMost = 0;
- QWidget *w = 0;
+ QWidget *w = nullptr;
const int n = things.count();
for (int i = 0; i < n; ++i) {
QGridBox *box = things.at(i);
@@ -390,9 +354,9 @@ void QGridLayoutPrivate::recalcHFW(int w)
and put the results in hfwData.
*/
if (!hfwData)
- hfwData = new QVector<QLayoutStruct>(rr);
+ hfwData = new QList<QLayoutStruct>(rr);
setupHfwLayoutData();
- QVector<QLayoutStruct> &rData = *hfwData;
+ QList<QLayoutStruct> &rData = *hfwData;
int h = 0;
int mh = 0;
@@ -615,7 +579,7 @@ void QGridLayoutPrivate::addData(QGridBox *box, const QGridLayoutSizeTriple &siz
}
}
-static void initEmptyMultiBox(QVector<QLayoutStruct> &chain, int start, int end)
+static void initEmptyMultiBox(QList<QLayoutStruct> &chain, int start, int end)
{
for (int i = start; i <= end; i++) {
QLayoutStruct *data = &chain[i];
@@ -625,8 +589,8 @@ static void initEmptyMultiBox(QVector<QLayoutStruct> &chain, int start, int end)
}
}
-static void distributeMultiBox(QVector<QLayoutStruct> &chain, int start, int end, int minSize,
- int sizeHint, QVector<int> &stretchArray, int stretch)
+static void distributeMultiBox(QList<QLayoutStruct> &chain, int start, int end, int minSize,
+ int sizeHint, QList<int> &stretchArray, int stretch)
{
int i;
int w = 0;
@@ -698,9 +662,8 @@ static QGridBox *&gridAt(QGridBox *grid[], int r, int c, int cc,
return grid[(r * cc) + c];
}
-void QGridLayoutPrivate::setupSpacings(QVector<QLayoutStruct> &chain,
- QGridBox *grid[], int fixedSpacing,
- Qt::Orientation orientation)
+void QGridLayoutPrivate::setupSpacings(QList<QLayoutStruct> &chain, QGridBox *grid[],
+ int fixedSpacing, Qt::Orientation orientation)
{
Q_Q(QGridLayout);
int numRows = rr; // or columns if orientation is horizontal
@@ -868,7 +831,7 @@ void QGridLayoutPrivate::setupLayoutData(int hSpacing, int vSpacing)
void QGridLayoutPrivate::addHfwData(QGridBox *box, int width)
{
- QVector<QLayoutStruct> &rData = *hfwData;
+ QList<QLayoutStruct> &rData = *hfwData;
if (box->hasHeightForWidth()) {
int hint = box->heightForWidth(width);
rData[box->row].sizeHint = qMax(hint, rData.at(box->row).sizeHint);
@@ -888,7 +851,7 @@ void QGridLayoutPrivate::addHfwData(QGridBox *box, int width)
*/
void QGridLayoutPrivate::setupHfwLayoutData()
{
- QVector<QLayoutStruct> &rData = *hfwData;
+ QList<QLayoutStruct> &rData = *hfwData;
for (int i = 0; i < rr; i++) {
rData[i] = rowData.at(i);
rData[i].minimumSize = rData[i].sizeHint = rMinHeights.at(i);
@@ -944,7 +907,7 @@ void QGridLayoutPrivate::distribute(QRect r, int hSpacing, int vSpacing)
r.adjust(+left, +top, -right, -bottom);
qGeomCalc(colData, 0, cc, r.x(), r.width());
- QVector<QLayoutStruct> *rDataPtr;
+ QList<QLayoutStruct> *rDataPtr;
if (has_hfw) {
recalcHFW(r.width());
qGeomCalc(*hfwData, 0, rr, r.y(), r.height());
@@ -953,7 +916,7 @@ void QGridLayoutPrivate::distribute(QRect r, int hSpacing, int vSpacing)
qGeomCalc(rowData, 0, rr, r.y(), r.height());
rDataPtr = &rowData;
}
- QVector<QLayoutStruct> &rData = *rDataPtr;
+ QList<QLayoutStruct> &rData = *rDataPtr;
int i;
bool reverse = ((r.bottom() > rect.bottom()) || (r.bottom() == rect.bottom()
@@ -985,7 +948,7 @@ QRect QGridLayoutPrivate::cellRect(int row, int col) const
if (row < 0 || row >= rr || col < 0 || col >= cc)
return QRect();
- const QVector<QLayoutStruct> *rDataPtr;
+ const QList<QLayoutStruct> *rDataPtr;
if (has_hfw && hfwData)
rDataPtr = hfwData;
else
@@ -1073,31 +1036,24 @@ QRect QGridLayoutPrivate::cellRect(int row, int col) const
Constructs a new QGridLayout with parent widget, \a parent. The
layout has one row and one column initially, and will expand when
new items are inserted.
-*/
-QGridLayout::QGridLayout(QWidget *parent)
- : QLayout(*new QGridLayoutPrivate, nullptr, parent)
-{
- Q_D(QGridLayout);
- d->expand(1, 1);
-}
-/*!
- Constructs a new grid layout.
+ The layout is set directly as the top-level layout for \a parent.
+ There can be only one top-level layout for a widget. It is returned
+ by QWidget::layout().
- You must insert this grid into another layout. You can insert
- widgets and layouts into this layout at any time, but laying out
- will not be performed before this is inserted into another layout.
+ If \a parent is \nullptr, then you must insert this grid layout
+ into another layout, or set it as a widget's layout using
+ QWidget::setLayout().
+
+ \sa QWidget::setLayout()
*/
-QGridLayout::QGridLayout()
- : QLayout(*new QGridLayoutPrivate, nullptr, nullptr)
+QGridLayout::QGridLayout(QWidget *parent)
+ : QLayout(*new QGridLayoutPrivate, nullptr, parent)
{
Q_D(QGridLayout);
d->expand(1, 1);
}
-
-
-
/*!
\internal (mostly)
@@ -1338,7 +1294,7 @@ QLayoutItem *QGridLayout::itemAt(int index) const
QLayoutItem *QGridLayout::itemAtPosition(int row, int column) const
{
Q_D(const QGridLayout);
- int n = d->things.count();
+ int n = d->things.size();
for (int i = 0; i < n; ++i) {
QGridBox *box = d->things.at(i);
if (row >= box->row && row <= box->toRow(d->rr)
diff --git a/src/widgets/kernel/qgridlayout.h b/src/widgets/kernel/qgridlayout.h
index 0283ec2028..bb4887e2fd 100644
--- a/src/widgets/kernel/qgridlayout.h
+++ b/src/widgets/kernel/qgridlayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGRIDLAYOUT_H
#define QGRIDLAYOUT_H
@@ -61,9 +25,7 @@ class Q_WIDGETS_EXPORT QGridLayout : public QLayout
QDOC_PROPERTY(int verticalSpacing READ verticalSpacing WRITE setVerticalSpacing)
public:
- explicit QGridLayout(QWidget *parent);
- QGridLayout();
-
+ explicit QGridLayout(QWidget *parent = nullptr);
~QGridLayout();
QSize sizeHint() const override;
@@ -74,8 +36,8 @@ public:
int horizontalSpacing() const;
void setVerticalSpacing(int spacing);
int verticalSpacing() const;
- void setSpacing(int spacing);
- int spacing() const;
+ void setSpacing(int spacing) override;
+ int spacing() const override;
void setRowStretch(int row, int stretch);
void setColumnStretch(int column, int stretch);
diff --git a/src/widgets/kernel/qlayout.cpp b/src/widgets/kernel/qlayout.cpp
index d4ff9083f1..a826ea75bc 100644
--- a/src/widgets/kernel/qlayout.cpp
+++ b/src/widgets/kernel/qlayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qlayout.h"
@@ -55,9 +19,6 @@
#include "qvariant.h"
#include "qwidget_p.h"
#include "qlayout_p.h"
-#if QT_CONFIG(formlayout)
-#include "qformlayout.h"
-#endif
QT_BEGIN_NAMESPACE
@@ -96,24 +57,28 @@ 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}
*/
/*!
Constructs a new top-level QLayout, with parent \a parent.
- \a parent may not be \nullptr.
The layout is set directly as the top-level layout for
\a parent. There can be only one top-level layout for a
widget. It is returned by QWidget::layout().
+
+ If \a parent is \nullptr, then you must insert this layout
+ into another layout, or set it as a widget's layout using
+ QWidget::setLayout().
+
+ \sa QWidget::setLayout()
*/
QLayout::QLayout(QWidget *parent)
: QObject(*new QLayoutPrivate, parent)
@@ -123,18 +88,6 @@ QLayout::QLayout(QWidget *parent)
parent->setLayout(this);
}
-/*!
- Constructs a new child QLayout.
-
- This layout has to be inserted into another layout before geometry
- management will work.
-*/
-QLayout::QLayout()
- : QObject(*new QLayoutPrivate, nullptr)
-{
-}
-
-
/*! \internal
*/
QLayout::QLayout(QLayoutPrivate &dd, QLayout *lay, QWidget *w)
@@ -282,40 +235,6 @@ bool QLayout::setAlignment(QLayout *l, Qt::Alignment alignment)
return false;
}
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \property QLayout::margin
- \brief the width of the outside border of the layout
- \obsolete
-
- Use setContentsMargins() and getContentsMargins() instead.
-
- \sa contentsRect(), spacing
-*/
-
-/*!
- \obsolete
-*/
-int QLayout::margin() const
-{
- int left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- if (left == top && top == right && right == bottom) {
- return left;
- } else {
- return -1;
- }
-}
-
-/*!
- \obsolete
-*/
-void QLayout::setMargin(int margin)
-{
- setContentsMargins(margin, margin, margin, margin);
-}
-
-#endif
/*!
\property QLayout::spacing
\brief the spacing between widgets inside the layout
@@ -335,40 +254,20 @@ void QLayout::setMargin(int margin)
int QLayout::spacing() const
{
- if (const QBoxLayout* boxlayout = qobject_cast<const QBoxLayout*>(this)) {
- return boxlayout->spacing();
- } else if (const QGridLayout* gridlayout = qobject_cast<const QGridLayout*>(this)) {
- return gridlayout->spacing();
-#if QT_CONFIG(formlayout)
- } else if (const QFormLayout* formlayout = qobject_cast<const QFormLayout*>(this)) {
- return formlayout->spacing();
-#endif
+ Q_D(const QLayout);
+ if (d->insideSpacing >=0) {
+ return d->insideSpacing;
} else {
- Q_D(const QLayout);
- if (d->insideSpacing >=0) {
- return d->insideSpacing;
- } else {
- // arbitrarily prefer horizontal spacing to vertical spacing
- return qSmartSpacing(this, QStyle::PM_LayoutHorizontalSpacing);
- }
+ // arbitrarily prefer horizontal spacing to vertical spacing
+ return qSmartSpacing(this, QStyle::PM_LayoutHorizontalSpacing);
}
}
void QLayout::setSpacing(int spacing)
{
- if (QBoxLayout* boxlayout = qobject_cast<QBoxLayout*>(this)) {
- boxlayout->setSpacing(spacing);
- } else if (QGridLayout* gridlayout = qobject_cast<QGridLayout*>(this)) {
- gridlayout->setSpacing(spacing);
-#if QT_CONFIG(formlayout)
- } else if (QFormLayout* formlayout = qobject_cast<QFormLayout*>(this)) {
- formlayout->setSpacing(spacing);
-#endif
- } else {
- Q_D(QLayout);
- d->insideSpacing = spacing;
- invalidate();
- }
+ Q_D(QLayout);
+ d->insideSpacing = spacing;
+ invalidate();
}
/*!
@@ -417,6 +316,19 @@ void QLayout::setContentsMargins(const QMargins &margins)
}
/*!
+ \since 6.1
+
+ Unsets any user-defined margins around the layout. The layout will
+ use the default values provided by the style.
+
+ \sa setContentsMargins()
+*/
+void QLayout::unsetContentsMargins()
+{
+ setContentsMargins(-1, -1, -1, -1);
+}
+
+/*!
\since 4.3
For each of \a left, \a top, \a right and \a bottom that is not
@@ -608,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();
@@ -621,12 +534,14 @@ void QLayout::widgetEvent(QEvent *e)
case QEvent::ChildRemoved:
{
QChildEvent *c = (QChildEvent *)e;
- if (c->child()->isWidgetType()) {
+ QObject *child = c->child();
+ QObjectPrivate *op = QObjectPrivate::get(child);
+ if (op->wasWidget) {
#if QT_CONFIG(menubar)
- if (c->child() == d->menubar)
+ if (child == d->menubar)
d->menubar = nullptr;
#endif
- removeWidgetRecursively(this, c->child());
+ removeWidgetRecursively(this, child);
}
}
break;
@@ -659,6 +574,28 @@ void QLayout::childEvent(QChildEvent *e)
\internal
Also takes contentsMargins and menu bar into account.
*/
+int QLayout::totalMinimumHeightForWidth(int w) const
+{
+ Q_D(const QLayout);
+ int side=0, top=0;
+ if (d->topLevel) {
+ QWidget *parent = parentWidget();
+ parent->ensurePolished();
+ QWidgetPrivate *wd = parent->d_func();
+ side += wd->leftmargin + wd->rightmargin;
+ top += wd->topmargin + wd->bottommargin;
+ }
+ int h = minimumHeightForWidth(w - side) + top;
+#if QT_CONFIG(menubar)
+ h += menuBarHeightForWidth(d->menubar, w);
+#endif
+ return h;
+}
+
+/*!
+ \internal
+ Also takes contentsMargins and menu bar into account.
+*/
int QLayout::totalHeightForWidth(int w) const
{
Q_D(const QLayout);
@@ -772,24 +709,24 @@ QLayout::~QLayout()
/*!
This function is called from \c addLayout() or \c insertLayout() functions in
- subclasses to add layout \a l as a sub-layout.
+ subclasses to add layout \a childLayout as a sub-layout.
The only scenario in which you need to call it directly is if you
implement a custom layout that supports nested layouts.
\sa QBoxLayout::addLayout(), QBoxLayout::insertLayout(), QGridLayout::addLayout()
*/
-void QLayout::addChildLayout(QLayout *l)
+void QLayout::addChildLayout(QLayout *childLayout)
{
- if (Q_UNLIKELY(l->parent())) {
- qWarning("QLayout::addChildLayout: layout \"%ls\" already has a parent",
- qUtf16Printable(l->objectName()));
+ if (Q_UNLIKELY(childLayout->parent())) {
+ qWarning("QLayout::addChildLayout: layout %s \"%ls\" already has a parent",
+ childLayout->metaObject()->className(), qUtf16Printable(childLayout->objectName()));
return;
}
- l->setParent(this);
+ childLayout->setParent(this);
if (QWidget *mw = parentWidget()) {
- l->d_func()->reparentChildWidgets(mw);
+ childLayout->d_func()->reparentChildWidgets(mw);
}
}
@@ -808,7 +745,7 @@ bool QLayout::adoptLayout(QLayout *layout)
static bool layoutDebug()
{
static int checked_env = -1;
- if(checked_env == -1)
+ if (checked_env == -1)
checked_env = !!qEnvironmentVariableIntValue("QT_LAYOUT_DEBUG");
return checked_env;
@@ -836,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)
@@ -892,9 +829,10 @@ bool QLayoutPrivate::checkLayout(QLayout *otherLayout) const
This function is called from \c addWidget() functions in
subclasses to add \a w as a managed widget of a layout.
- If \a w is already managed by a layout, this function will give a warning
- and remove \a w from that layout. This function must therefore be
- called before adding \a w to the layout's data structure.
+ If \a w is already managed by a layout, this function will produce
+ a warning, and remove \a w from that layout. This function must
+ therefore be called before adding \a w to the layout's data
+ structure.
*/
void QLayout::addChildWidget(QWidget *w)
{
@@ -921,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);
@@ -1191,7 +1129,7 @@ QLayoutItem *QLayout::replaceWidget(QWidget *from, QWidget *to, Qt::FindChildOpt
\fn QLayoutItem *QLayout::itemAt(int index) const
Must be implemented in subclasses to return the layout item at \a
- index. If there is no such item, the function must return 0.
+ index. If there is no such item, the function must return \nullptr.
Items are numbered consecutively from 0. If an item is deleted, other items will be renumbered.
This function can be used to iterate over a layout. The following
@@ -1234,18 +1172,17 @@ QLayoutItem *QLayout::replaceWidget(QWidget *from, QWidget *to, Qt::FindChildOpt
Returns the index of \a widget, or -1 if \a widget is not found.
- The default implementation iterates over all items using itemAt()
+ The default implementation iterates over all items using itemAt().
*/
-int QLayout::indexOf(QWidget *widget) const
+int QLayout::indexOf(const QWidget *widget) const
{
- int i = 0;
- QLayoutItem *item = itemAt(i);
- while (item) {
- if (item->widget() == widget)
+ const int c = count();
+
+ for (int i = 0; i < c; ++i) {
+ if (itemAt(i)->widget() == widget)
return i;
- ++i;
- item = itemAt(i);
}
+
return -1;
}
@@ -1256,16 +1193,15 @@ int QLayout::indexOf(QWidget *widget) const
Returns the index of \a layoutItem, or -1 if \a layoutItem is not found.
*/
-int QLayout::indexOf(QLayoutItem *layoutItem) const
+int QLayout::indexOf(const QLayoutItem *layoutItem) const
{
- int i = 0;
- QLayoutItem *item = itemAt(i);
- while (item) {
- if (item == layoutItem)
+ const int c = count();
+
+ for (int i = 0; i < c; ++i) {
+ if (itemAt(i) == layoutItem)
return i;
- ++i;
- item = itemAt(i);
}
+
return -1;
}
@@ -1323,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
@@ -1386,6 +1322,11 @@ QRect QLayout::alignmentRect(const QRect &r) const
*/
void QLayout::removeWidget(QWidget *widget)
{
+ if (Q_UNLIKELY(!widget)) {
+ qWarning("QLayout::removeWidget: Cannot remove a null widget.");
+ return;
+ }
+
int i = 0;
QLayoutItem *child;
while ((child = itemAt(i))) {
diff --git a/src/widgets/kernel/qlayout.h b/src/widgets/kernel/qlayout.h
index 35a04a35b2..ee7b5e047c 100644
--- a/src/widgets/kernel/qlayout.h
+++ b/src/widgets/kernel/qlayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLAYOUT_H
#define QLAYOUT_H
@@ -63,10 +27,9 @@ class Q_WIDGETS_EXPORT QLayout : public QObject, public QLayoutItem
Q_OBJECT
Q_DECLARE_PRIVATE(QLayout)
-#if QT_DEPRECATED_SINCE(5, 13)
- Q_PROPERTY(int margin READ margin WRITE setMargin)
-#endif
Q_PROPERTY(int spacing READ spacing WRITE setSpacing)
+ Q_PROPERTY(QMargins contentsMargins READ contentsMargins WRITE setContentsMargins
+ RESET unsetContentsMargins)
Q_PROPERTY(SizeConstraint sizeConstraint READ sizeConstraint WRITE setSizeConstraint)
public:
enum SizeConstraint {
@@ -79,20 +42,15 @@ public:
};
Q_ENUM(SizeConstraint)
- QLayout(QWidget *parent);
- QLayout();
+ explicit QLayout(QWidget *parent = nullptr);
~QLayout();
-#if QT_DEPRECATED_SINCE(5, 13)
- int margin() const;
- void setMargin(int);
-#endif
-
- int spacing() const;
- void setSpacing(int);
+ virtual int spacing() const;
+ virtual void setSpacing(int);
void setContentsMargins(int left, int top, int right, int bottom);
void setContentsMargins(const QMargins &margins);
+ void unsetContentsMargins();
void getContentsMargins(int *left, int *top, int *right, int *bottom) const;
QMargins contentsMargins() const;
QRect contentsRect() const;
@@ -125,15 +83,16 @@ public:
virtual void setGeometry(const QRect&) override;
virtual QLayoutItem *itemAt(int index) const = 0;
virtual QLayoutItem *takeAt(int index) = 0;
- virtual int indexOf(QWidget *) const;
- QT6_VIRTUAL int indexOf(QLayoutItem *) const;
+ virtual int indexOf(const QWidget *) const;
+ virtual int indexOf(const QLayoutItem *) const;
virtual int count() const = 0;
bool isEmpty() const override;
QSizePolicy::ControlTypes controlTypes() const override;
- QT6_VIRTUAL QLayoutItem *replaceWidget(QWidget *from, QWidget *to,
- Qt::FindChildOptions options = Qt::FindChildrenRecursively);
+ virtual QLayoutItem *replaceWidget(QWidget *from, QWidget *to,
+ Qt::FindChildOptions options = Qt::FindChildrenRecursively);
+ int totalMinimumHeightForWidth(int w) const;
int totalHeightForWidth(int w) const;
QSize totalMinimumSize() const;
QSize totalMaximumSize() const;
diff --git a/src/widgets/kernel/qlayout_p.h b/src/widgets/kernel/qlayout_p.h
index 2b19af48be..cd40a98fb7 100644
--- a/src/widgets/kernel/qlayout_p.h
+++ b/src/widgets/kernel/qlayout_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLAYOUT_P_H
#define QLAYOUT_P_H
@@ -80,7 +44,7 @@ public:
static QWidgetItem *createWidgetItem(const QLayout *layout, QWidget *widget);
static QSpacerItem *createSpacerItem(const QLayout *layout, int w, int h, QSizePolicy::Policy hPolicy = QSizePolicy::Minimum, QSizePolicy::Policy vPolicy = QSizePolicy::Minimum);
- virtual QLayoutItem* replaceAt(int index, QLayoutItem *newitem) { Q_UNUSED(index); Q_UNUSED(newitem); return nullptr; }
+ virtual QLayoutItem* replaceAt(int, QLayoutItem *) { return nullptr; }
static QWidgetItemFactoryMethod widgetItemFactoryMethod;
static QSpacerItemFactoryMethod spacerItemFactoryMethod;
diff --git a/src/widgets/kernel/qlayoutengine.cpp b/src/widgets/kernel/qlayoutengine.cpp
index 83bbd69b55..576678ad0a 100644
--- a/src/widgets/kernel/qlayoutengine.cpp
+++ b/src/widgets/kernel/qlayoutengine.cpp
@@ -1,46 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qlayout.h"
#include "private/qlayoutengine_p.h"
-#include "qvector.h"
+#include "qlist.h"
#include "qwidget.h"
#include <qvarlengtharray.h>
@@ -73,12 +37,10 @@ static inline int fRound(Fixed64 i) {
count is the count of items in the chain; pos and space give the
interval (relative to parentWidget topLeft).
*/
-void qGeomCalc(QVector<QLayoutStruct> &chain, int start, int count,
- int pos, int space, int spacer)
+void qGeomCalc(QList<QLayoutStruct> &chain, int start, int count, int pos, int space, int spacer)
{
int cHint = 0;
int cMin = 0;
- int cMax = 0;
int sumStretch = 0;
int sumSpacing = 0;
int expandingCount = 0;
@@ -94,7 +56,6 @@ void qGeomCalc(QVector<QLayoutStruct> &chain, int start, int count,
data->done = false;
cHint += data->smartSizeHint();
cMin += data->minimumSize;
- cMax += data->maximumSize;
sumStretch += data->stretch;
if (!data->empty) {
/*
@@ -376,11 +337,7 @@ Q_WIDGETS_EXPORT QSize qSmartMinSize(const QSize &sizeHint, const QSize &minSize
Q_WIDGETS_EXPORT QSize qSmartMinSize(const QWidgetItem *i)
{
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
- QWidget *w = const_cast<QWidgetItem *>(i)->widget();
-#else
QWidget *w = i->widget();
-#endif
return qSmartMinSize(w->sizeHint(), w->minimumSizeHint(),
w->minimumSize(), w->maximumSize(),
w->sizePolicy());
@@ -418,11 +375,7 @@ Q_WIDGETS_EXPORT QSize qSmartMaxSize(const QSize &sizeHint,
Q_WIDGETS_EXPORT QSize qSmartMaxSize(const QWidgetItem *i, Qt::Alignment align)
{
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
- QWidget *w = const_cast<QWidgetItem *>(i)->widget();
-#else
QWidget *w = i->widget();
-#endif
return qSmartMaxSize(w->sizeHint().expandedTo(w->minimumSizeHint()), w->minimumSize(), w->maximumSize(),
w->sizePolicy(), align);
}
diff --git a/src/widgets/kernel/qlayoutengine_p.h b/src/widgets/kernel/qlayoutengine_p.h
index 2999bae646..ff7b4107e1 100644
--- a/src/widgets/kernel/qlayoutengine_p.h
+++ b/src/widgets/kernel/qlayoutengine_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLAYOUTENGINE_P_H
#define QLAYOUTENGINE_P_H
@@ -54,11 +18,10 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "QtWidgets/qlayoutitem.h"
#include "QtWidgets/qstyle.h"
+#include <QtCore/qcontainerfwd.h>
QT_BEGIN_NAMESPACE
-template <typename T> class QVector;
-
struct QLayoutStruct
{
inline void init(int stretchFactor = 0, int minSize = 0) {
@@ -95,9 +58,8 @@ struct QLayoutStruct
int size;
};
-
-Q_WIDGETS_EXPORT void qGeomCalc(QVector<QLayoutStruct> &chain, int start, int count,
- int pos, int space, int spacer = -1);
+Q_WIDGETS_EXPORT void qGeomCalc(QList<QLayoutStruct> &chain, int start, int count, int pos,
+ int space, int spacer = -1);
Q_WIDGETS_EXPORT QSize qSmartMinSize(const QSize &sizeHint, const QSize &minSizeHint,
const QSize &minSize, const QSize &maxSize,
const QSizePolicy &sizePolicy);
diff --git a/src/widgets/kernel/qlayoutitem.cpp b/src/widgets/kernel/qlayoutitem.cpp
index af5750771d..246d090828 100644
--- a/src/widgets/kernel/qlayoutitem.cpp
+++ b/src/widgets/kernel/qlayoutitem.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qlayout.h"
@@ -88,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
@@ -360,11 +324,7 @@ QSpacerItem * QSpacerItem::spacerItem()
\sa layout(), spacerItem()
*/
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-QWidget *QLayoutItem::widget()
-#else
QWidget *QLayoutItem::widget() const
-#endif
{
return nullptr;
}
@@ -372,11 +332,7 @@ QWidget *QLayoutItem::widget() const
/*!
Returns the widget managed by this item.
*/
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-QWidget *QWidgetItem::widget()
-#else
QWidget *QWidgetItem::widget() const
-#endif
{
return wid;
}
@@ -583,6 +539,36 @@ int QWidgetItem::heightForWidth(int w) const
return hfw;
}
+int QWidgetItem::minimumHeightForWidth(int w) const
+{
+ if (isEmpty())
+ return -1;
+
+ w = !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
+ ? fromLayoutItemSize(wid->d_func(), QSize(w, 0)).width()
+ : w;
+
+ int hfw;
+ if (wid->layout())
+ hfw = wid->layout()->totalMinimumHeightForWidth(w);
+ else
+ hfw = wid->heightForWidth(w); // QWidget doesn't have minimumHeightForWidth()
+
+ if (hfw > wid->maximumHeight())
+ hfw = wid->maximumHeight();
+ if (hfw < wid->minimumHeight())
+ hfw = wid->minimumHeight();
+
+ hfw = !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
+ ? toLayoutItemSize(wid->d_func(), QSize(0, hfw)).height()
+ : hfw;
+
+ if (hfw < 0)
+ hfw = 0;
+ return hfw;
+
+}
+
/*!
\reimp
*/
diff --git a/src/widgets/kernel/qlayoutitem.h b/src/widgets/kernel/qlayoutitem.h
index 8553e20adc..531498ea4b 100644
--- a/src/widgets/kernel/qlayoutitem.h
+++ b/src/widgets/kernel/qlayoutitem.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLAYOUTITEM_H
#define QLAYOUTITEM_H
@@ -49,7 +13,7 @@
QT_BEGIN_NAMESPACE
-static const Q_DECL_UNUSED int QLAYOUTSIZE_MAX = INT_MAX/256/16;
+inline constexpr int QLAYOUTSIZE_MAX = INT_MAX/256/16;
class QLayout;
class QLayoutItem;
@@ -74,11 +38,7 @@ public:
virtual int minimumHeightForWidth(int) const;
virtual void invalidate();
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
- virtual QWidget *widget();
-#else
virtual QWidget *widget() const;
-#endif
virtual QLayout *layout();
virtual QSpacerItem *spacerItem();
@@ -137,14 +97,11 @@ public:
bool isEmpty() const override;
void setGeometry(const QRect&) override;
QRect geometry() const override;
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
- QWidget *widget() override;
-#else
QWidget *widget() const override;
-#endif
bool hasHeightForWidth() const override;
int heightForWidth(int) const override;
+ int minimumHeightForWidth(int) const override;
QSizePolicy::ControlTypes controlTypes() const override;
protected:
QWidget *wid;
diff --git a/src/widgets/kernel/qmacgesturerecognizer.cpp b/src/widgets/kernel/qmacgesturerecognizer.cpp
index aac115a2cf..8149bea30d 100644
--- a/src/widgets/kernel/qmacgesturerecognizer.cpp
+++ b/src/widgets/kernel/qmacgesturerecognizer.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qmacgesturerecognizer_p.h"
#include "qgesture.h"
@@ -67,7 +31,7 @@ QMacSwipeGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *e
case Qt::SwipeNativeGesture: {
QSwipeGesture *g = static_cast<QSwipeGesture *>(gesture);
g->setSwipeAngle(ev->value());
- g->setHotSpot(ev->screenPos());
+ g->setHotSpot(ev->globalPosition());
return QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint;
break; }
default:
@@ -105,11 +69,11 @@ QMacPinchGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *e
switch (ev->gestureType()) {
case Qt::BeginNativeGesture:
reset(gesture);
- g->setStartCenterPoint(static_cast<QWidget*>(obj)->mapFromGlobal(ev->screenPos().toPoint()));
+ g->setStartCenterPoint(static_cast<QWidget*>(obj)->mapFromGlobal(ev->globalPosition().toPoint()));
g->setCenterPoint(g->startCenterPoint());
g->setChangeFlags(QPinchGesture::CenterPointChanged);
g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
- g->setHotSpot(ev->screenPos());
+ g->setHotSpot(ev->globalPosition());
return QGestureRecognizer::MayBeGesture | QGestureRecognizer::ConsumeEventHint;
case Qt::RotateNativeGesture:
g->setLastScaleFactor(g->scaleFactor());
@@ -117,7 +81,7 @@ QMacPinchGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *e
g->setRotationAngle(g->rotationAngle() + ev->value());
g->setChangeFlags(QPinchGesture::RotationAngleChanged);
g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
- g->setHotSpot(ev->screenPos());
+ g->setHotSpot(ev->globalPosition());
return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
case Qt::ZoomNativeGesture:
g->setLastScaleFactor(g->scaleFactor());
@@ -126,7 +90,7 @@ QMacPinchGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *e
g->setTotalScaleFactor(g->totalScaleFactor() * g->scaleFactor());
g->setChangeFlags(QPinchGesture::ScaleFactorChanged);
g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
- g->setHotSpot(ev->screenPos());
+ g->setHotSpot(ev->globalPosition());
return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
case Qt::SmartZoomNativeGesture:
g->setLastScaleFactor(g->scaleFactor());
@@ -134,7 +98,7 @@ QMacPinchGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *e
g->setScaleFactor(ev->value() ? 1.7f : 1.0f);
g->setChangeFlags(QPinchGesture::ScaleFactorChanged);
g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
- g->setHotSpot(ev->screenPos());
+ g->setHotSpot(ev->globalPosition());
return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
case Qt::EndNativeGesture:
return QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint;
@@ -179,7 +143,7 @@ QGesture *QMacPanGestureRecognizer::create(QObject *target)
w->setAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
return new QPanGesture;
}
- return 0;
+ return nullptr;
}
void QMacPanGestureRecognizer::timerEvent(QTimerEvent *ev)
@@ -203,7 +167,7 @@ QMacPanGestureRecognizer::recognize(QGesture *gesture, QObject *target, QEvent *
switch (event->type()) {
case QEvent::TouchBegin: {
const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
- if (ev->touchPoints().size() == 1) {
+ if (ev->points().size() == 1) {
reset(gesture);
_startPos = QCursor::pos();
_target = target;
@@ -217,7 +181,7 @@ QMacPanGestureRecognizer::recognize(QGesture *gesture, QObject *target, QEvent *
break;
const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
- if (ev->touchPoints().size() == 1)
+ if (ev->points().size() == 1)
return QGestureRecognizer::FinishGesture;
break;}
case QEvent::TouchUpdate: {
@@ -225,7 +189,7 @@ QMacPanGestureRecognizer::recognize(QGesture *gesture, QObject *target, QEvent *
break;
const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
- if (ev->touchPoints().size() == 1) {
+ if (ev->points().size() == 1) {
if (_panTimer.isActive()) {
// INVARIANT: Still in maybeGesture. Check if the user
// moved his finger so much that it makes sense to cancel the pan:
diff --git a/src/widgets/kernel/qmacgesturerecognizer_p.h b/src/widgets/kernel/qmacgesturerecognizer_p.h
index 739fc201b7..5c559c6cb9 100644
--- a/src/widgets/kernel/qmacgesturerecognizer_p.h
+++ b/src/widgets/kernel/qmacgesturerecognizer_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMACSWIPEGESTURERECOGNIZER_MAC_P_H
#define QMACSWIPEGESTURERECOGNIZER_MAC_P_H
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.cpp b/src/widgets/kernel/qshortcut.cpp
deleted file mode 100644
index 4a2f8d66c2..0000000000
--- a/src/widgets/kernel/qshortcut.cpp
+++ /dev/null
@@ -1,551 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qshortcut.h"
-#include "private/qwidget_p.h"
-
-#include <qevent.h>
-#if QT_CONFIG(whatsthis)
-#include <qwhatsthis.h>
-#endif
-#if QT_CONFIG(menu)
-#include <qmenu.h>
-#endif
-#if QT_CONFIG(menubar)
-#include <qmenubar.h>
-#endif
-#include <qapplication.h>
-#include <private/qapplication_p.h>
-#include "private/qguishortcut_p.h"
-#include <private/qshortcutmap_p.h>
-#if QT_CONFIG(action)
-# include <private/qaction_p.h>
-#endif
-#include <private/qwidgetwindow_p.h>
-#include <qpa/qplatformmenu.h>
-
-QT_BEGIN_NAMESPACE
-
-static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidget *active_window);
-#if QT_CONFIG(graphicsview)
-static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsWidget *w, QWidget *active_window);
-#endif
-#if QT_CONFIG(action)
-static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidget *active_window);
-#endif
-
-
-/*! \internal
- Returns \c true if the widget \a w is a logical sub window of the current
- top-level widget.
-*/
-bool qWidgetShortcutContextMatcher(QObject *object, Qt::ShortcutContext context)
-{
- Q_ASSERT_X(object, "QShortcutMap", "Shortcut has no owner. Illegal map state!");
-
- QWidget *active_window = QApplication::activeWindow();
-
- // popups do not become the active window,
- // so we fake it here to get the correct context
- // for the shortcut system.
- if (QApplication::activePopupWidget())
- active_window = QApplication::activePopupWidget();
-
- if (!active_window) {
- QWindow *qwindow = QGuiApplication::focusWindow();
- if (qwindow && qwindow->isActive()) {
- while (qwindow) {
- if (auto widgetWindow = qobject_cast<QWidgetWindow *>(qwindow)) {
- active_window = widgetWindow->widget();
- break;
- }
- qwindow = qwindow->parent();
- }
- }
- }
-
- if (!active_window)
- return false;
-
-#if QT_CONFIG(action)
- if (auto a = qobject_cast<QAction *>(object))
- return correctActionContext(context, a, active_window);
-#endif
-
-#if QT_CONFIG(graphicsview)
- if (auto gw = qobject_cast<QGraphicsWidget *>(object))
- return correctGraphicsWidgetContext(context, gw, active_window);
-#endif
-
- auto w = qobject_cast<QWidget *>(object);
- if (!w) {
- if (auto s = qobject_cast<QShortcut *>(object))
- w = s->parentWidget();
- }
-
- if (!w) {
- auto qwindow = qobject_cast<QWindow *>(object);
- while (qwindow) {
- if (auto widget_window = qobject_cast<QWidgetWindow *>(qwindow)) {
- w = widget_window->widget();
- break;
- }
- qwindow = qwindow->parent();
- }
- }
-
- if (!w)
- return false;
-
- return correctWidgetContext(context, w, active_window);
-}
-
-static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidget *active_window)
-{
- bool visible = w->isVisible();
-#if QT_CONFIG(menubar)
- if (auto menuBar = qobject_cast<QMenuBar *>(w)) {
- if (auto *pmb = menuBar->platformMenuBar()) {
- if (menuBar->parentWidget()) {
- visible = true;
- } else {
- if (auto *ww = qobject_cast<QWidgetWindow *>(pmb->parentWindow()))
- w = ww->widget(); // Good enough since we only care about the window
- else
- return false; // This is not a QWidget window. We won't deliver
- }
- }
- }
-#endif
-
- if (!visible || !w->isEnabled())
- return false;
-
- if (context == Qt::ApplicationShortcut)
- return QApplicationPrivate::tryModalHelper(w, nullptr); // true, unless w is shadowed by a modal dialog
-
- if (context == Qt::WidgetShortcut)
- return w == QApplication::focusWidget();
-
- if (context == Qt::WidgetWithChildrenShortcut) {
- const QWidget *tw = QApplication::focusWidget();
- while (tw && tw != w && (tw->windowType() == Qt::Widget || tw->windowType() == Qt::Popup || tw->windowType() == Qt::SubWindow))
- tw = tw->parentWidget();
- return tw == w;
- }
-
- // Below is Qt::WindowShortcut context
- QWidget *tlw = w->window();
-#if QT_CONFIG(graphicsview)
- if (auto topData = static_cast<QWidgetPrivate *>(QObjectPrivate::get(tlw))->extra.get()) {
- if (topData->proxyWidget) {
- bool res = correctGraphicsWidgetContext(context, topData->proxyWidget, active_window);
- return res;
- }
- }
-#endif
-
- if (active_window && active_window != tlw) {
- /* if a floating tool window is active, keep shortcuts on the parent working.
- * and if a popup window is active (f.ex a completer), keep shortcuts on the
- * focus proxy working */
- if (active_window->windowType() == Qt::Tool && active_window->parentWidget()) {
- active_window = active_window->parentWidget()->window();
- } else if (active_window->windowType() == Qt::Popup && active_window->focusProxy()) {
- active_window = active_window->focusProxy()->window();
- }
- }
-
- if (active_window != tlw) {
-#if QT_CONFIG(menubar)
- // If the tlw is a QMenuBar then we allow it to proceed as this indicates that
- // the QMenuBar is a parentless one and is therefore used for multiple top level
- // windows in the application. This is common on macOS platforms for example.
- if (!qobject_cast<QMenuBar *>(tlw))
-#endif
- return false;
- }
-
- /* if we live in a MDI subwindow, ignore the event if we are
- not the active document window */
- const QWidget* sw = w;
- while (sw && !(sw->windowType() == Qt::SubWindow) && !sw->isWindow())
- sw = sw->parentWidget();
- if (sw && (sw->windowType() == Qt::SubWindow)) {
- QWidget *focus_widget = QApplication::focusWidget();
- while (focus_widget && focus_widget != sw)
- focus_widget = focus_widget->parentWidget();
- return sw == focus_widget;
- }
-
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug().nospace() << "..true [Pass-through]";
-#endif
- return QApplicationPrivate::tryModalHelper(w, nullptr);
-}
-
-#if QT_CONFIG(graphicsview)
-static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsWidget *w, QWidget *active_window)
-{
- bool visible = w->isVisible();
-#if defined(Q_OS_DARWIN) && QT_CONFIG(menubar)
- if (!QCoreApplication::testAttribute(Qt::AA_DontUseNativeMenuBar) && qobject_cast<QMenuBar *>(w))
- visible = true;
-#endif
-
- if (!visible || !w->isEnabled() || !w->scene())
- return false;
-
- if (context == Qt::ApplicationShortcut) {
- // Applicationwide shortcuts are always reachable unless their owner
- // is shadowed by modality. In QGV there's no modality concept, but we
- // must still check if all views are shadowed.
- const auto &views = w->scene()->views();
- for (auto view : views) {
- if (QApplicationPrivate::tryModalHelper(view, nullptr))
- return true;
- }
- return false;
- }
-
- if (context == Qt::WidgetShortcut)
- return static_cast<QGraphicsItem *>(w) == w->scene()->focusItem();
-
- if (context == Qt::WidgetWithChildrenShortcut) {
- const QGraphicsItem *ti = w->scene()->focusItem();
- if (ti && ti->isWidget()) {
- const auto *tw = static_cast<const QGraphicsWidget *>(ti);
- while (tw && tw != w && (tw->windowType() == Qt::Widget || tw->windowType() == Qt::Popup))
- tw = tw->parentWidget();
- return tw == w;
- }
- return false;
- }
-
- // Below is Qt::WindowShortcut context
-
- // Find the active view (if any).
- const auto &views = w->scene()->views();
- QGraphicsView *activeView = nullptr;
- for (auto view : views) {
- if (view->window() == active_window) {
- activeView = view;
- break;
- }
- }
- if (!activeView)
- return false;
-
- // The shortcut is reachable if owned by a windowless widget, or if the
- // widget's window is the same as the focus item's window.
- QGraphicsWidget *a = w->scene()->activeWindow();
- return !w->window() || a == w->window();
-}
-#endif
-
-#if QT_CONFIG(action)
-static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidget *active_window)
-{
- const QWidgetList &widgets = static_cast<QActionPrivate *>(QObjectPrivate::get(a))->widgets;
-#if defined(DEBUG_QSHORTCUTMAP)
- if (widgets.isEmpty())
- qDebug() << a << "not connected to any widgets; won't trigger";
-#endif
- for (auto w : widgets) {
-#if QT_CONFIG(menu)
- if (auto menu = qobject_cast<QMenu *>(w)) {
-#ifdef Q_OS_DARWIN
- // On Mac, menu item shortcuts are processed before reaching any window.
- // That means that if a menu action shortcut has not been already processed
- // (and reaches this point), then the menu item itself has been disabled.
- // This occurs at the QPA level on Mac, where we disable all the Cocoa menus
- // when showing a modal window. (Notice that only the QPA menu is disabled,
- // not the QMenu.) Since we can also reach this code by climbing the menu
- // hierarchy (see below), or when the shortcut is not a key-equivalent, we
- // need to check whether the QPA menu is actually disabled.
- // When there is no QPA menu, there will be no QCocoaMenuDelegate checking
- // for the actual shortcuts. We can then fallback to our own logic.
- QPlatformMenu *pm = menu->platformMenu();
- if (pm && !pm->isEnabled())
- continue;
-#endif
- QAction *a = menu->menuAction();
- if (correctActionContext(context, a, active_window))
- return true;
- } else
-#endif
- if (correctWidgetContext(context, w, active_window))
- return true;
- }
-
-#if QT_CONFIG(graphicsview)
- const auto &graphicsWidgets = static_cast<QActionPrivate *>(QObjectPrivate::get(a))->graphicsWidgets;
-#if defined(DEBUG_QSHORTCUTMAP)
- if (graphicsWidgets.isEmpty())
- qDebug() << a << "not connected to any widgets; won't trigger";
-#endif
- for (auto graphicsWidget : graphicsWidgets) {
- if (correctGraphicsWidgetContext(context, graphicsWidget, active_window))
- return true;
- }
-#endif
- return false;
-}
-#endif // QT_CONFIG(action)
-
-
-/*!
- \class QShortcut
- \brief The QShortcut class is used to create keyboard shortcuts.
-
- \ingroup events
- \inmodule QtWidgets
-
- The QShortcut class provides a way of connecting keyboard
- shortcuts to Qt's \l{signals and slots} mechanism, so that
- objects can be informed when a shortcut is executed. The shortcut
- can be set up to contain all the key presses necessary to
- describe a keyboard shortcut, including the states of modifier
- keys such as \uicontrol Shift, \uicontrol Ctrl, and \uicontrol Alt.
-
- \target mnemonic
-
- On certain widgets, using '&' in front of a character will
- automatically create a mnemonic (a shortcut) for that character,
- e.g. "E&xit" will create the shortcut \uicontrol Alt+X (use '&&' to
- display an actual ampersand). The widget might consume and perform
- an action on a given shortcut. On X11 the ampersand will not be
- shown and the character will be underlined. On Windows, shortcuts
- are normally not displayed until the user presses the \uicontrol Alt
- key, but this is a setting the user can change. On Mac, shortcuts
- are disabled by default. Call \l qt_set_sequence_auto_mnemonic() to
- enable them. However, because mnemonic shortcuts do not fit in
- with Aqua's guidelines, Qt will not show the shortcut character
- underlined.
-
- For applications that use menus, it may be more convenient to
- use the convenience functions provided in the QMenu class to
- assign keyboard shortcuts to menu items as they are created.
- Alternatively, shortcuts may be associated with other types of
- actions in the QAction class.
-
- The simplest way to create a shortcut for a particular widget is
- to construct the shortcut with a key sequence. For example:
-
- \snippet code/src_gui_kernel_qshortcut.cpp 0
-
- When the user types the \l{QKeySequence}{key sequence}
- for a given shortcut, the shortcut's activated() signal is
- emitted. (In the case of ambiguity, the activatedAmbiguously()
- signal is emitted.) A shortcut is "listened for" by Qt's event
- loop when the shortcut's parent widget is receiving events.
-
- A shortcut's key sequence can be set with setKey() and retrieved
- with key(). A shortcut can be enabled or disabled with
- setEnabled(), and can have "What's This?" help text set with
- setWhatsThis().
-
- \sa QShortcutEvent, QKeySequence, QAction
-*/
-
-/*!
- \fn QWidget *QShortcut::parentWidget() const
-
- Returns the shortcut's parent widget.
-*/
-
-/*
- \internal
- Private data accessed through d-pointer.
-*/
-class QShortcutPrivate : public QGuiShortcutPrivate
-{
- Q_DECLARE_PUBLIC(QShortcut)
-public:
- QShortcutPrivate() = default;
-
- QShortcutMap::ContextMatcher contextMatcher() const override
- { return qWidgetShortcutContextMatcher; }
-
- bool handleWhatsThis() override;
-
- QString sc_whatsthis;
-};
-
-bool QShortcutPrivate::handleWhatsThis()
-{
-#if QT_CONFIG(whatsthis)
- const bool result = QWhatsThis::inWhatsThisMode();
- if (result)
- QWhatsThis::showText(QCursor::pos(), sc_whatsthis);
- return result;
-#else
- return false;
-#endif
-}
-
-/*!
- Constructs a QShortcut object for the \a parent widget. Since no
- shortcut key sequence is specified, the shortcut will not emit any
- signals.
-
- \sa setKey()
-*/
-QShortcut::QShortcut(QWidget *parent)
- : QGuiShortcut(*new QShortcutPrivate, parent)
-{
-}
-
-/*!
- Constructs a QShortcut object for the \a parent widget. The shortcut
- operates on its parent, listening for \l{QShortcutEvent}s that
- match the \a key sequence. Depending on the ambiguity of the
- event, the shortcut will call the \a member function, or the \a
- ambiguousMember function, if the key press was in the shortcut's
- \a shortcutContext.
-*/
-QShortcut::QShortcut(const QKeySequence &key, QWidget *parent,
- const char *member, const char *ambiguousMember,
- Qt::ShortcutContext shortcutContext)
- : QGuiShortcut(*new QShortcutPrivate, key, parent, member, ambiguousMember, shortcutContext)
-{
-}
-
-/*!
- \fn template<typename Functor>
- QShortcut(const QKeySequence &key, QWidget *parent,
- Functor functor,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
- \since 5.15
- \overload
-
- This is a QShortcut convenience constructor which connects the shortcut's
- \l{QShortcut::activated()}{activated()} signal to the \a functor.
-*/
-/*!
- \fn template<typename Functor>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const QObject *context, Functor functor,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
- \since 5.15
- \overload
-
- This is a QShortcut convenience constructor which connects the shortcut's
- \l{QShortcut::activated()}{activated()} signal to the \a functor.
-
- The \a functor can be a pointer to a member function of the \a context object.
-
- If the \a context object is destroyed, the \a functor will not be called.
-*/
-/*!
- \fn template<typename Functor, typename FunctorAmbiguous>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const QObject *context1, Functor functor,
- FunctorAmbiguous functorAmbiguous,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
- \since 5.15
- \overload
-
- This is a QShortcut convenience constructor which connects the shortcut's
- \l{QShortcut::activated()}{activated()} signal to the \a functor and
- \l{QShortcut::activatedAmbiguously()}{activatedAmbiguously()}
- signal to the \a FunctorAmbiguous.
-
- The \a functor and \a FunctorAmbiguous can be a pointer to a member
- function of the \a context object.
-
- If the \a context object is destroyed, the \a functor and
- \a FunctorAmbiguous will not be called.
-*/
-/*!
- \fn template<typename Functor, typename FunctorAmbiguous>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const QObject *context1, Functor functor,
- const QObject *context2, FunctorAmbiguous functorAmbiguous,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
- \since 5.15
- \overload
-
- This is a QShortcut convenience constructor which connects the shortcut's
- \l{QShortcut::activated()}{activated()} signal to the \a functor and
- \l{QShortcut::activatedAmbiguously()}{activatedAmbiguously()}
- signal to the \a FunctorAmbiguous.
-
- The \a functor can be a pointer to a member function of the
- \a context1 object.
- The \a FunctorAmbiguous can be a pointer to a member function of the
- \a context2 object.
-
- If the \a context1 object is destroyed, the \a functor will not be called.
- If the \a context2 object is destroyed, the \a FunctorAmbiguous
- will not be called.
-*/
-
-/*!
- \property QShortcut::whatsThis
- \brief the shortcut's "What's This?" help text
-
- The text will be shown when the application is in "What's
- This?" mode and the user types the shortcut key() sequence.
-
- To set "What's This?" help on a menu item (with or without a
- shortcut key), set the help on the item's action.
-
- By default, this property contains an empty string.
-
- \sa QWhatsThis::inWhatsThisMode(), QAction::setWhatsThis()
-*/
-void QShortcut::setWhatsThis(const QString &text)
-{
- Q_D(QShortcut);
- d->sc_whatsthis = text;
-}
-
-QString QShortcut::whatsThis() const
-{
- Q_D(const QShortcut);
- return d->sc_whatsthis;
-}
-
-/*!
- Destroys the shortcut.
-*/
-QShortcut::~QShortcut() = default;
-
-QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qshortcut.h b/src/widgets/kernel/qshortcut.h
index 6c92f87c46..6cec8d45ea 100644
--- a/src/widgets/kernel/qshortcut.h
+++ b/src/widgets/kernel/qshortcut.h
@@ -1,129 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QSHORTCUT_H
-#define QSHORTCUT_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtWidgets/qwidget.h>
-#include <QtGui/qguishortcut.h>
-
-QT_REQUIRE_CONFIG(shortcut);
+#include <QtGui/QShortcut>
QT_BEGIN_NAMESPACE
-
-class QShortcutPrivate;
-class Q_WIDGETS_EXPORT QShortcut : public QGuiShortcut
-{
- Q_OBJECT
- Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis)
- Q_DECLARE_PRIVATE(QShortcut)
-public:
- explicit QShortcut(QWidget *parent);
- explicit QShortcut(const QKeySequence& key, QWidget *parent,
- const char *member = nullptr, const char *ambiguousMember = nullptr,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
-#ifdef Q_CLANG_QDOC
- template<typename Functor>
- QShortcut(const QKeySequence &key, QWidget *parent,
- Functor functor,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
- template<typename Functor>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const QObject *context, Functor functor,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
- template<typename Functor, typename FunctorAmbiguous>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const QObject *context1, Functor functor,
- FunctorAmbiguous functorAmbiguous,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
- template<typename Functor, typename FunctorAmbiguous>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const QObject *context1, Functor functor,
- const QObject *context2, FunctorAmbiguous functorAmbiguous,
- Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
-#else
- template<typename Func1>
- QShortcut(const QKeySequence &key, QWidget *parent,
- Func1 slot1,
- Qt::ShortcutContext context = Qt::WindowShortcut)
- : QShortcut(key, parent, static_cast<const char*>(nullptr), static_cast<const char*>(nullptr), context)
- {
- connect(this, &QShortcut::activated, std::move(slot1));
- }
- template<class Obj1, typename Func1>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const Obj1 *object1, Func1 slot1,
- Qt::ShortcutContext context = Qt::WindowShortcut)
- : QShortcut(key, parent, static_cast<const char*>(nullptr), static_cast<const char*>(nullptr), context)
- {
- connect(this, &QShortcut::activated, object1, std::move(slot1));
- }
- template<class Obj1, typename Func1, typename Func2>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const Obj1 *object1, Func1 slot1, Func2 slot2,
- Qt::ShortcutContext context = Qt::WindowShortcut)
- : QShortcut(key, parent, static_cast<const char*>(nullptr), static_cast<const char*>(nullptr), context)
- {
- connect(this, &QShortcut::activated, object1, std::move(slot1));
- connect(this, &QShortcut::activatedAmbiguously, object1, std::move(slot2));
- }
- template<class Obj1, typename Func1, class Obj2, typename Func2>
- QShortcut(const QKeySequence &key, QWidget *parent,
- const Obj1 *object1, Func1 slot1,
- const Obj2 *object2, Func2 slot2,
- Qt::ShortcutContext context = Qt::WindowShortcut)
- : QShortcut(key, parent, static_cast<const char*>(nullptr), static_cast<const char*>(nullptr), context)
- {
- connect(this, &QShortcut::activated, object1, std::move(slot1));
- connect(this, &QShortcut::activatedAmbiguously, object2, std::move(slot2));
- }
-#endif
- ~QShortcut();
-
- void setWhatsThis(const QString &text);
- QString whatsThis() const;
-
- inline QWidget *parentWidget() const
- { return static_cast<QWidget *>(QObject::parent()); }
-};
-
QT_END_NAMESPACE
-
-#endif // QSHORTCUT_H
diff --git a/src/widgets/kernel/qshortcut_widgets.cpp b/src/widgets/kernel/qshortcut_widgets.cpp
new file mode 100644
index 0000000000..6e25d79bd6
--- /dev/null
+++ b/src/widgets/kernel/qshortcut_widgets.cpp
@@ -0,0 +1,328 @@
+// 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 "qshortcut.h"
+#include "private/qshortcut_p.h"
+
+#include "private/qwidget_p.h"
+
+#include <qevent.h>
+#if QT_CONFIG(whatsthis)
+#include <qwhatsthis.h>
+#endif
+#if QT_CONFIG(menu)
+#include <qmenu.h>
+#endif
+#if QT_CONFIG(menubar)
+#include <qmenubar.h>
+#endif
+#include <qapplication.h>
+#include <private/qapplication_p.h>
+#include <private/qshortcutmap_p.h>
+#if QT_CONFIG(action)
+# include <private/qaction_p.h>
+#endif
+#include <private/qwidgetwindow_p.h>
+#include <qpa/qplatformmenu.h>
+
+QT_BEGIN_NAMESPACE
+
+static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidget *active_window);
+#if QT_CONFIG(graphicsview)
+static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsWidget *w, QWidget *active_window);
+#endif
+#if QT_CONFIG(action)
+static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidget *active_window);
+#endif
+
+
+/*! \internal
+ Returns \c true if the widget \a w is a logical sub window of the current
+ top-level widget.
+*/
+bool qWidgetShortcutContextMatcher(QObject *object, Qt::ShortcutContext context)
+{
+ Q_ASSERT_X(object, "QShortcutMap", "Shortcut has no owner. Illegal map state!");
+
+ QWidget *active_window = QApplication::activeWindow();
+
+ // popups do not become the active window,
+ // so we fake it here to get the correct context
+ // for the shortcut system.
+ if (QApplication::activePopupWidget())
+ active_window = QApplication::activePopupWidget();
+
+ if (!active_window) {
+ QWindow *qwindow = QGuiApplication::focusWindow();
+ if (qwindow && qwindow->isActive()) {
+ while (qwindow) {
+ if (auto widgetWindow = qobject_cast<QWidgetWindow *>(qwindow)) {
+ active_window = widgetWindow->widget();
+ break;
+ }
+ qwindow = qwindow->parent();
+ }
+ }
+ }
+
+#if QT_CONFIG(action)
+ if (auto a = qobject_cast<QAction *>(object))
+ return correctActionContext(context, a, active_window);
+#endif
+
+#if QT_CONFIG(graphicsview)
+ if (auto gw = qobject_cast<QGraphicsWidget *>(object))
+ return correctGraphicsWidgetContext(context, gw, active_window);
+#endif
+
+ auto w = qobject_cast<QWidget *>(object);
+ if (!w) {
+ if (auto s = qobject_cast<QShortcut *>(object))
+ w = qobject_cast<QWidget *>(s->parent());
+ }
+
+ if (!w) {
+ auto qwindow = qobject_cast<QWindow *>(object);
+ while (qwindow) {
+ if (auto widget_window = qobject_cast<QWidgetWindow *>(qwindow)) {
+ w = widget_window->widget();
+ break;
+ }
+ qwindow = qwindow->parent();
+ }
+ }
+
+ if (w)
+ 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)) {
+ if (auto *pmb = menuBar->platformMenuBar()) {
+ if (menuBar->parentWidget()) {
+ visible = true;
+ } else {
+ if (auto *ww = qobject_cast<QWidgetWindow *>(pmb->parentWindow()))
+ w = ww->widget(); // Good enough since we only care about the window
+ else
+ return false; // This is not a QWidget window. We won't deliver
+ }
+ }
+ }
+#endif
+
+ if (!visible || !w->isEnabled())
+ return false;
+
+ if (context == Qt::ApplicationShortcut)
+ return QApplicationPrivate::tryModalHelper(w, nullptr); // true, unless w is shadowed by a modal dialog
+
+ if (context == Qt::WidgetShortcut)
+ return w == QApplication::focusWidget();
+
+ if (context == Qt::WidgetWithChildrenShortcut) {
+ const QWidget *tw = QApplication::focusWidget();
+ while (tw && tw != w && (tw->windowType() == Qt::Widget || tw->windowType() == Qt::Popup || tw->windowType() == Qt::SubWindow))
+ tw = tw->parentWidget();
+ return tw == w;
+ }
+
+ // Below is Qt::WindowShortcut context
+ QWidget *tlw = w->window();
+#if QT_CONFIG(graphicsview)
+ if (auto topData = static_cast<QWidgetPrivate *>(QObjectPrivate::get(tlw))->extra.get()) {
+ if (topData->proxyWidget) {
+ bool res = correctGraphicsWidgetContext(context, topData->proxyWidget, active_window);
+ return res;
+ }
+ }
+#endif
+
+ if (active_window && active_window != tlw) {
+ /* if a floating tool window is active, keep shortcuts on the parent working.
+ * and if a popup window is active (f.ex a completer), keep shortcuts on the
+ * focus proxy working */
+ if (active_window->windowType() == Qt::Tool && active_window->parentWidget()) {
+ active_window = active_window->parentWidget()->window();
+ } else if (active_window->windowType() == Qt::Popup && active_window->focusProxy()) {
+ active_window = active_window->focusProxy()->window();
+ }
+ }
+
+ if (active_window != tlw) {
+#if QT_CONFIG(menubar)
+ // If the tlw is a QMenuBar then we allow it to proceed as this indicates that
+ // the QMenuBar is a parentless one and is therefore used for multiple top level
+ // windows in the application. This is common on macOS platforms for example.
+ if (!qobject_cast<QMenuBar *>(tlw))
+#endif
+ return false;
+ }
+
+ /* if we live in a MDI subwindow, ignore the event if we are
+ not the active document window */
+ const QWidget* sw = w;
+ while (sw && !(sw->windowType() == Qt::SubWindow) && !sw->isWindow())
+ sw = sw->parentWidget();
+ if (sw && (sw->windowType() == Qt::SubWindow)) {
+ QWidget *focus_widget = QApplication::focusWidget();
+ while (focus_widget && focus_widget != sw)
+ focus_widget = focus_widget->parentWidget();
+ return sw == focus_widget;
+ }
+
+#if defined(DEBUG_QSHORTCUTMAP)
+ qDebug().nospace() << "..true [Pass-through]";
+#endif
+ return QApplicationPrivate::tryModalHelper(w, nullptr);
+}
+
+#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))
+ visible = true;
+#endif
+
+ if (!visible || !w->isEnabled() || !w->scene())
+ return false;
+
+ if (context == Qt::ApplicationShortcut) {
+ // Applicationwide shortcuts are always reachable unless their owner
+ // is shadowed by modality. In QGV there's no modality concept, but we
+ // must still check if all views are shadowed.
+ const auto &views = w->scene()->views();
+ for (auto view : views) {
+ if (QApplicationPrivate::tryModalHelper(view, nullptr))
+ return true;
+ }
+ return false;
+ }
+
+ if (context == Qt::WidgetShortcut)
+ return static_cast<QGraphicsItem *>(w) == w->scene()->focusItem();
+
+ if (context == Qt::WidgetWithChildrenShortcut) {
+ const QGraphicsItem *ti = w->scene()->focusItem();
+ if (ti && ti->isWidget()) {
+ const auto *tw = static_cast<const QGraphicsWidget *>(ti);
+ while (tw && tw != w && (tw->windowType() == Qt::Widget || tw->windowType() == Qt::Popup))
+ tw = tw->parentWidget();
+ return tw == w;
+ }
+ return false;
+ }
+
+ // Below is Qt::WindowShortcut context
+
+ // Find the active view (if any).
+ const auto &views = w->scene()->views();
+ QGraphicsView *activeView = nullptr;
+ for (auto view : views) {
+ if (view->window() == active_window) {
+ activeView = view;
+ break;
+ }
+ }
+ if (!activeView)
+ return false;
+
+ // The shortcut is reachable if owned by a windowless widget, or if the
+ // widget's window is the same as the focus item's window.
+ QGraphicsWidget *a = w->scene()->activeWindow();
+ return !w->window() || a == w->window();
+}
+#endif
+
+#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())
+ qDebug() << a << "not connected to any widgets; won't trigger";
+#endif
+ for (auto object : associatedObjects) {
+#if QT_CONFIG(menu)
+ if (auto menu = qobject_cast<QMenu *>(object)) {
+#ifdef Q_OS_DARWIN
+ // On Mac, menu item shortcuts are processed before reaching any window.
+ // That means that if a menu action shortcut has not been already processed
+ // (and reaches this point), then the menu item itself has been disabled.
+ // This occurs at the QPA level on Mac, where we disable all the Cocoa menus
+ // when showing a modal window. (Notice that only the QPA menu is disabled,
+ // not the QMenu.) Since we can also reach this code by climbing the menu
+ // hierarchy (see below), or when the shortcut is not a key-equivalent, we
+ // need to check whether the QPA menu is actually disabled.
+ // When there is no QPA menu, there will be no QCocoaMenuDelegate checking
+ // for the actual shortcuts. We can then fallback to our own logic.
+ QPlatformMenu *pm = menu->platformMenu();
+ if (pm && !pm->isEnabled())
+ continue;
+#endif
+ QAction *a = menu->menuAction();
+ if (a->isVisible() && a->isEnabled() && correctActionContext(context, a, active_window))
+ return true;
+ } else
+#endif
+ if (auto widget = qobject_cast<QWidget*>(object)) {
+ if (correctWidgetContext(context, widget, active_window))
+ return true;
+ }
+#if QT_CONFIG(graphicsview)
+ else if (auto graphicsWidget = qobject_cast<QGraphicsWidget*>(object)) {
+ if (correctGraphicsWidgetContext(context, graphicsWidget, active_window))
+ return true;
+ }
+#endif
+ }
+
+ return false;
+}
+#endif // QT_CONFIG(action)
+
+class QtWidgetsShortcutPrivate : public QShortcutPrivate
+{
+ Q_DECLARE_PUBLIC(QShortcut)
+public:
+ QtWidgetsShortcutPrivate() = default;
+
+ QShortcutMap::ContextMatcher contextMatcher() const override
+ { return qWidgetShortcutContextMatcher; }
+
+ bool handleWhatsThis() override;
+};
+
+bool QtWidgetsShortcutPrivate::handleWhatsThis()
+{
+#if QT_CONFIG(whatsthis)
+ if (QWhatsThis::inWhatsThisMode()) {
+ QWhatsThis::showText(QCursor::pos(), sc_whatsthis);
+ return true;
+ }
+#endif
+ return false;
+}
+
+QShortcutPrivate *QApplicationPrivate::createShortcutPrivate() const
+{
+ return new QtWidgetsShortcutPrivate;
+}
+
+QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qsizepolicy.cpp b/src/widgets/kernel/qsizepolicy.cpp
index 54bf8fe0dc..b883c1ed6f 100644
--- a/src/widgets/kernel/qsizepolicy.cpp
+++ b/src/widgets/kernel/qsizepolicy.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qsizepolicy.h"
@@ -317,9 +281,8 @@ void QSizePolicy::setControlType(ControlType type) noexcept
*/
/*!
- \fn uint qHash(QSizePolicy key, uint seed = 0)
+ \fn size_t QSizePolicy::qHash(QSizePolicy key, size_t seed = 0)
\since 5.6
- \relates QSizePolicy
Returns the hash value for \a key, using
\a seed to seed the calculation.
@@ -439,7 +402,7 @@ void QSizePolicy::setControlType(ControlType type) noexcept
*/
QSizePolicy::operator QVariant() const
{
- return QVariant(QVariant::SizePolicy, this);
+ return QVariant::fromValue(*this);
}
#ifndef QT_NO_DATASTREAM
diff --git a/src/widgets/kernel/qsizepolicy.h b/src/widgets/kernel/qsizepolicy.h
index f26923eeb0..af964bf6af 100644
--- a/src/widgets/kernel/qsizepolicy.h
+++ b/src/widgets/kernel/qsizepolicy.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSIZEPOLICY_H
#define QSIZEPOLICY_H
@@ -43,30 +7,13 @@
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtCore/qobject.h>
#include <QtCore/qalgorithms.h>
+#include <QtCore/qhashfunctions.h>
QT_BEGIN_NAMESPACE
-// gcc < 4.8.0 has problems with init'ing variant members in constexpr ctors
-// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54922
-#if !defined(Q_CC_GNU) || defined(Q_CC_INTEL) || defined(Q_CC_CLANG) || Q_CC_GNU >= 408
-# define QT_SIZEPOLICY_CONSTEXPR Q_DECL_CONSTEXPR
-# if defined(Q_COMPILER_UNIFORM_INIT)
-# define QT_SIZEPOLICY_CONSTEXPR_AND_UNIFORM_INIT Q_DECL_CONSTEXPR
-# endif // uniform-init
-#endif
-
-#ifndef QT_SIZEPOLICY_CONSTEXPR
-# define QT_SIZEPOLICY_CONSTEXPR
-#endif
-#ifndef QT_SIZEPOLICY_CONSTEXPR_AND_UNIFORM_INIT
-# define QT_SIZEPOLICY_CONSTEXPR_AND_UNIFORM_INIT
-#endif
-
class QVariant;
class QSizePolicy;
-Q_DECL_CONST_FUNCTION inline uint qHash(QSizePolicy key, uint seed = 0) noexcept;
-
class Q_WIDGETS_EXPORT QSizePolicy
{
Q_GADGET
@@ -110,60 +57,48 @@ public:
Q_DECLARE_FLAGS(ControlTypes, ControlType)
Q_FLAG(ControlTypes)
- QT_SIZEPOLICY_CONSTEXPR QSizePolicy() noexcept : data(0) { }
+ constexpr QSizePolicy() noexcept : data(0) { }
-#if defined(Q_COMPILER_UNIFORM_INIT) && !defined(Q_QDOC)
- QT_SIZEPOLICY_CONSTEXPR QSizePolicy(Policy horizontal, Policy vertical, ControlType type = DefaultType) noexcept
+ constexpr QSizePolicy(Policy horizontal, Policy vertical, ControlType type = DefaultType) noexcept
: bits{0, 0, quint32(horizontal), quint32(vertical),
type == DefaultType ? 0 : toControlTypeFieldValue(type), 0, 0, 0}
{}
-#else
- QSizePolicy(Policy horizontal, Policy vertical, ControlType type = DefaultType) noexcept
- : data(0) {
- bits.horPolicy = horizontal;
- bits.verPolicy = vertical;
- setControlType(type);
- }
-#endif // uniform-init
- QT_SIZEPOLICY_CONSTEXPR Policy horizontalPolicy() const noexcept { return static_cast<Policy>(bits.horPolicy); }
- QT_SIZEPOLICY_CONSTEXPR Policy verticalPolicy() const noexcept { return static_cast<Policy>(bits.verPolicy); }
+ constexpr Policy horizontalPolicy() const noexcept { return static_cast<Policy>(bits.horPolicy); }
+ constexpr Policy verticalPolicy() const noexcept { return static_cast<Policy>(bits.verPolicy); }
ControlType controlType() const noexcept;
- Q_DECL_RELAXED_CONSTEXPR void setHorizontalPolicy(Policy d) noexcept { bits.horPolicy = d; }
- Q_DECL_RELAXED_CONSTEXPR void setVerticalPolicy(Policy d) noexcept { bits.verPolicy = d; }
+ constexpr void setHorizontalPolicy(Policy d) noexcept { bits.horPolicy = d; }
+ constexpr void setVerticalPolicy(Policy d) noexcept { bits.verPolicy = d; }
void setControlType(ControlType type) noexcept;
- QT_SIZEPOLICY_CONSTEXPR Qt::Orientations expandingDirections() const noexcept {
- return ( (verticalPolicy() & ExpandFlag) ? Qt::Vertical : Qt::Orientations() )
- | ( (horizontalPolicy() & ExpandFlag) ? Qt::Horizontal : Qt::Orientations() ) ;
+ // ### Qt 7: consider making Policy a QFlags and removing these casts
+ constexpr Qt::Orientations expandingDirections() const noexcept {
+ return ( (verticalPolicy() & static_cast<Policy>(ExpandFlag)) ? Qt::Vertical : Qt::Orientations() )
+ | ( (horizontalPolicy() & static_cast<Policy>(ExpandFlag)) ? Qt::Horizontal : Qt::Orientations() ) ;
}
- Q_DECL_RELAXED_CONSTEXPR void setHeightForWidth(bool b) noexcept { bits.hfw = b; }
- QT_SIZEPOLICY_CONSTEXPR bool hasHeightForWidth() const noexcept { return bits.hfw; }
- Q_DECL_RELAXED_CONSTEXPR void setWidthForHeight(bool b) noexcept { bits.wfh = b; }
- QT_SIZEPOLICY_CONSTEXPR bool hasWidthForHeight() const noexcept { return bits.wfh; }
+ constexpr void setHeightForWidth(bool b) noexcept { bits.hfw = b; }
+ constexpr bool hasHeightForWidth() const noexcept { return bits.hfw; }
+ constexpr void setWidthForHeight(bool b) noexcept { bits.wfh = b; }
+ constexpr bool hasWidthForHeight() const noexcept { return bits.wfh; }
- QT_SIZEPOLICY_CONSTEXPR bool operator==(const QSizePolicy& s) const noexcept { return data == s.data; }
- QT_SIZEPOLICY_CONSTEXPR bool operator!=(const QSizePolicy& s) const noexcept { return data != s.data; }
+ constexpr bool operator==(const QSizePolicy& s) const noexcept { return data == s.data; }
+ constexpr bool operator!=(const QSizePolicy& s) const noexcept { return data != s.data; }
- friend Q_DECL_CONST_FUNCTION uint qHash(QSizePolicy key, uint seed) noexcept { return qHash(key.data, seed); }
+ friend Q_DECL_CONST_FUNCTION size_t qHash(QSizePolicy key, size_t seed = 0) noexcept { return qHash(key.data, seed); }
operator QVariant() const;
- QT_SIZEPOLICY_CONSTEXPR int horizontalStretch() const noexcept { return static_cast<int>(bits.horStretch); }
- QT_SIZEPOLICY_CONSTEXPR int verticalStretch() const noexcept { return static_cast<int>(bits.verStretch); }
- Q_DECL_RELAXED_CONSTEXPR void setHorizontalStretch(int stretchFactor) { bits.horStretch = static_cast<quint32>(qBound(0, stretchFactor, 255)); }
- Q_DECL_RELAXED_CONSTEXPR void setVerticalStretch(int stretchFactor) { bits.verStretch = static_cast<quint32>(qBound(0, stretchFactor, 255)); }
+ constexpr int horizontalStretch() const noexcept { return static_cast<int>(bits.horStretch); }
+ constexpr int verticalStretch() const noexcept { return static_cast<int>(bits.verStretch); }
+ constexpr void setHorizontalStretch(int stretchFactor) { bits.horStretch = static_cast<quint32>(qBound(0, stretchFactor, 255)); }
+ constexpr void setVerticalStretch(int stretchFactor) { bits.verStretch = static_cast<quint32>(qBound(0, stretchFactor, 255)); }
- QT_SIZEPOLICY_CONSTEXPR bool retainSizeWhenHidden() const noexcept { return bits.retainSizeWhenHidden; }
- Q_DECL_RELAXED_CONSTEXPR void setRetainSizeWhenHidden(bool retainSize) noexcept { bits.retainSizeWhenHidden = retainSize; }
+ constexpr bool retainSizeWhenHidden() const noexcept { return bits.retainSizeWhenHidden; }
+ constexpr void setRetainSizeWhenHidden(bool retainSize) noexcept { bits.retainSizeWhenHidden = retainSize; }
- Q_DECL_RELAXED_CONSTEXPR void transpose() noexcept { *this = transposed(); }
- Q_REQUIRED_RESULT
-#ifndef Q_QDOC
- QT_SIZEPOLICY_CONSTEXPR_AND_UNIFORM_INIT
-#endif
- QSizePolicy transposed() const noexcept
+ constexpr void transpose() noexcept { *this = transposed(); }
+ [[nodiscard]] constexpr QSizePolicy transposed() const noexcept
{
return QSizePolicy(bits.transposed());
}
@@ -173,11 +108,11 @@ private:
friend Q_WIDGETS_EXPORT QDataStream &operator<<(QDataStream &, const QSizePolicy &);
friend Q_WIDGETS_EXPORT QDataStream &operator>>(QDataStream &, QSizePolicy &);
#endif
- QT_SIZEPOLICY_CONSTEXPR QSizePolicy(int i) noexcept : data(i) { }
+ constexpr QSizePolicy(int i) noexcept : data(i) { }
struct Bits;
- QT_SIZEPOLICY_CONSTEXPR explicit QSizePolicy(Bits b) noexcept : bits(b) { }
+ constexpr explicit QSizePolicy(Bits b) noexcept : bits(b) { }
- static Q_DECL_RELAXED_CONSTEXPR quint32 toControlTypeFieldValue(ControlType type) noexcept
+ static constexpr quint32 toControlTypeFieldValue(ControlType type) noexcept
{
/*
The control type is a flag type, with values 0x1, 0x2, 0x4, 0x8, 0x10,
@@ -206,8 +141,7 @@ private:
quint32 wfh : 1;
quint32 retainSizeWhenHidden : 1;
- QT_SIZEPOLICY_CONSTEXPR_AND_UNIFORM_INIT
- Bits transposed() const noexcept
+ constexpr Bits transposed() const noexcept
{
return {verStretch, // \ swap
horStretch, // /
@@ -224,14 +158,11 @@ private:
quint32 data;
};
};
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
-// Can't add in Qt 5, as QList<QSizePolicy> would be BiC:
+
Q_DECLARE_TYPEINFO(QSizePolicy, Q_PRIMITIVE_TYPE);
-#else
-Q_DECLARE_TYPEINFO(QSizePolicy, Q_RELOCATABLE_TYPE);
-#endif
Q_DECLARE_OPERATORS_FOR_FLAGS(QSizePolicy::ControlTypes)
+Q_DECLARE_MIXED_ENUM_OPERATORS(int, QSizePolicy::Policy, QSizePolicy::PolicyFlag)
#ifndef QT_NO_DATASTREAM
Q_WIDGETS_EXPORT QDataStream &operator<<(QDataStream &, const QSizePolicy &);
@@ -242,10 +173,6 @@ Q_WIDGETS_EXPORT QDataStream &operator>>(QDataStream &, QSizePolicy &);
Q_WIDGETS_EXPORT QDebug operator<<(QDebug dbg, const QSizePolicy &);
#endif
-
-#undef QT_SIZEPOLICY_CONSTEXPR
-#undef QT_SIZEPOLICY_CONSTEXPR_AND_UNIFORM_INIT
-
QT_END_NAMESPACE
#endif // QSIZEPOLICY_H
diff --git a/src/widgets/kernel/qstackedlayout.cpp b/src/widgets/kernel/qstackedlayout.cpp
index f87fe96cc0..04eacf1d41 100644
--- a/src/widgets/kernel/qstackedlayout.cpp
+++ b/src/widgets/kernel/qstackedlayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstackedlayout.h"
#include "qlayout_p.h"
@@ -44,6 +8,10 @@
#include "private/qwidget_p.h"
#include "private/qlayoutengine_p.h"
+#include <QtCore/qpointer.h>
+
+#include <memory>
+
QT_BEGIN_NAMESPACE
class QStackedLayoutPrivate : public QLayoutPrivate
@@ -200,7 +168,7 @@ QStackedLayout::~QStackedLayout()
int QStackedLayout::addWidget(QWidget *widget)
{
Q_D(QStackedLayout);
- return insertWidget(d->list.count(), widget);
+ return insertWidget(d->list.size(), widget);
}
/*!
@@ -221,9 +189,9 @@ int QStackedLayout::insertWidget(int index, QWidget *widget)
{
Q_D(QStackedLayout);
addChildWidget(widget);
- index = qMin(index, d->list.count());
+ index = qMin(index, d->list.size());
if (index < 0)
- index = d->list.count();
+ index = d->list.size();
QWidgetItem *wi = QLayoutPrivate::createWidgetItem(this, widget);
d->list.insert(index, wi);
invalidate();
@@ -268,8 +236,8 @@ QLayoutItem *QStackedLayout::takeAt(int index)
QLayoutItem *item = d->list.takeAt(index);
if (index == d->index) {
d->index = -1;
- if ( d->list.count() > 0 ) {
- int newIndex = (index == d->list.count()) ? index-1 : index;
+ if ( d->list.size() > 0 ) {
+ int newIndex = (index == d->list.size()) ? index-1 : index;
setCurrentIndex(newIndex);
} else {
emit currentChanged(-1);
@@ -421,13 +389,13 @@ int QStackedLayout::count() const
*/
void QStackedLayout::addItem(QLayoutItem *item)
{
+ std::unique_ptr<QLayoutItem> guard(item);
QWidget *widget = item->widget();
if (Q_UNLIKELY(!widget)) {
qWarning("QStackedLayout::addItem: Only widgets can be added");
return;
}
addWidget(widget);
- delete item;
}
/*!
@@ -437,7 +405,7 @@ QSize QStackedLayout::sizeHint() const
{
Q_D(const QStackedLayout);
QSize s(0, 0);
- int n = d->list.count();
+ int n = d->list.size();
for (int i = 0; i < n; ++i)
if (QWidget *widget = d->list.at(i)->widget()) {
@@ -458,7 +426,7 @@ QSize QStackedLayout::minimumSize() const
{
Q_D(const QStackedLayout);
QSize s(0, 0);
- int n = d->list.count();
+ int n = d->list.size();
for (int i = 0; i < n; ++i)
if (QWidget *widget = d->list.at(i)->widget())
@@ -478,7 +446,7 @@ void QStackedLayout::setGeometry(const QRect &rect)
widget->setGeometry(rect);
break;
case StackAll:
- if (const int n = d->list.count())
+ if (const int n = d->list.size())
for (int i = 0; i < n; ++i)
if (QWidget *widget = d->list.at(i)->widget())
widget->setGeometry(rect);
@@ -565,7 +533,7 @@ void QStackedLayout::setStackingMode(StackingMode stackingMode)
return;
d->stackingMode = stackingMode;
- const int n = d->list.count();
+ const int n = d->list.size();
if (n == 0)
return;
diff --git a/src/widgets/kernel/qstackedlayout.h b/src/widgets/kernel/qstackedlayout.h
index 966ee2aae4..91d7d1e9f5 100644
--- a/src/widgets/kernel/qstackedlayout.h
+++ b/src/widgets/kernel/qstackedlayout.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTACKEDLAYOUT_H
#define QSTACKEDLAYOUT_H
diff --git a/src/widgets/kernel/qstandardgestures.cpp b/src/widgets/kernel/qstandardgestures.cpp
index a5c204d59d..4effc1a2d1 100644
--- a/src/widgets/kernel/qstandardgestures.cpp
+++ b/src/widgets/kernel/qstandardgestures.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstandardgestures_p.h"
#include "qgesture.h"
@@ -60,7 +24,7 @@ static const qreal kSingleStepScaleMin = 0.1;
QGesture *QPanGestureRecognizer::create(QObject *target)
{
if (target && target->isWidgetType()) {
-#if (defined(Q_OS_MACX) || defined(Q_OS_WIN)) && !defined(QT_NO_NATIVE_GESTURES)
+#if (defined(Q_OS_MACOS) || defined(Q_OS_WIN)) && !defined(QT_NO_NATIVE_GESTURES)
// for scroll areas on Windows and OS X we want to use native gestures instead
if (!qobject_cast<QAbstractScrollArea *>(target->parent()))
static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
@@ -71,12 +35,12 @@ QGesture *QPanGestureRecognizer::create(QObject *target)
return new QPanGesture;
}
-static QPointF panOffset(const QList<QTouchEvent::TouchPoint> &touchPoints, int maxCount)
+static QPointF panOffset(const QList<QEventPoint> &touchPoints, int maxCount)
{
QPointF result;
const int count = qMin(touchPoints.size(), maxCount);
for (int p = 0; p < count; ++p)
- result += touchPoints.at(p).pos() - touchPoints.at(p).startPos();
+ result += touchPoints.at(p).position() - touchPoints.at(p).pressPosition();
return result / qreal(count);
}
@@ -90,9 +54,7 @@ QGestureRecognizer::Result QPanGestureRecognizer::recognize(QGesture *state,
QGestureRecognizer::Result result = QGestureRecognizer::Ignore;
switch (event->type()) {
case QEvent::TouchBegin: {
- const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
result = QGestureRecognizer::MayBeGesture;
- QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
d->lastOffset = d->offset = QPointF();
d->pointCount = m_pointCount;
break;
@@ -100,9 +62,9 @@ QGestureRecognizer::Result QPanGestureRecognizer::recognize(QGesture *state,
case QEvent::TouchEnd: {
if (q->state() != Qt::NoGesture) {
const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
- if (ev->touchPoints().size() == d->pointCount) {
+ if (ev->points().size() == d->pointCount) {
d->lastOffset = d->offset;
- d->offset = panOffset(ev->touchPoints(), d->pointCount);
+ d->offset = panOffset(ev->points(), d->pointCount);
}
result = QGestureRecognizer::FinishGesture;
} else {
@@ -112,12 +74,12 @@ QGestureRecognizer::Result QPanGestureRecognizer::recognize(QGesture *state,
}
case QEvent::TouchUpdate: {
const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
- if (ev->touchPoints().size() >= d->pointCount) {
+ if (ev->points().size() >= d->pointCount) {
d->lastOffset = d->offset;
- d->offset = panOffset(ev->touchPoints(), d->pointCount);
+ d->offset = panOffset(ev->points(), d->pointCount);
if (d->offset.x() > 10 || d->offset.y() > 10 ||
d->offset.x() < -10 || d->offset.y() < -10) {
- q->setHotSpot(ev->touchPoints().first().startScreenPos());
+ q->setHotSpot(ev->points().first().globalPressPosition());
result = QGestureRecognizer::TriggerGesture;
} else {
result = QGestureRecognizer::MayBeGesture;
@@ -184,17 +146,17 @@ QGestureRecognizer::Result QPinchGestureRecognizer::recognize(QGesture *state,
case QEvent::TouchUpdate: {
const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
d->changeFlags = { };
- if (ev->touchPoints().size() == 2) {
- QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
- QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
+ if (ev->points().size() == 2) {
+ const QEventPoint &p1 = ev->points().at(0);
+ const QEventPoint &p2 = ev->points().at(1);
- d->hotSpot = p1.screenPos();
+ d->hotSpot = p1.globalPosition();
d->isHotSpotSet = true;
- QPointF centerPoint = (p1.screenPos() + p2.screenPos()) / 2.0;
+ QPointF centerPoint = (p1.globalPosition() + p2.globalPosition()) / 2.0;
if (d->isNewSequence) {
- d->startPosition[0] = p1.screenPos();
- d->startPosition[1] = p2.screenPos();
+ d->startPosition[0] = p1.globalPosition();
+ d->startPosition[1] = p2.globalPosition();
d->lastCenterPoint = centerPoint;
} else {
d->lastCenterPoint = d->centerPoint;
@@ -208,8 +170,8 @@ QGestureRecognizer::Result QPinchGestureRecognizer::recognize(QGesture *state,
d->lastScaleFactor = 1.0;
} else {
d->lastScaleFactor = d->scaleFactor;
- QLineF line(p1.screenPos(), p2.screenPos());
- QLineF lastLine(p1.lastScreenPos(), p2.lastScreenPos());
+ QLineF line(p1.globalPosition(), p2.globalPosition());
+ QLineF lastLine(p1.globalLastPosition(), p2.globalLastPosition());
qreal newScaleFactor = line.length() / lastLine.length();
if (newScaleFactor > kSingleStepScaleMax || newScaleFactor < kSingleStepScaleMin)
return QGestureRecognizer::Ignore;
@@ -218,10 +180,10 @@ QGestureRecognizer::Result QPinchGestureRecognizer::recognize(QGesture *state,
d->totalScaleFactor = d->totalScaleFactor * d->scaleFactor;
d->changeFlags |= QPinchGesture::ScaleFactorChanged;
- qreal angle = QLineF(p1.screenPos(), p2.screenPos()).angle();
+ qreal angle = QLineF(p1.globalPosition(), p2.globalPosition()).angle();
if (angle > 180)
angle -= 360;
- qreal startAngle = QLineF(p1.startScreenPos(), p2.startScreenPos()).angle();
+ qreal startAngle = QLineF(p1.globalPressPosition(), p2.globalPressPosition()).angle();
if (startAngle > 180)
startAngle -= 360;
const qreal rotationAngle = startAngle - angle;
@@ -313,41 +275,41 @@ QGestureRecognizer::Result QSwipeGestureRecognizer::recognize(QGesture *state,
const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
if (d->state == QSwipeGesturePrivate::NoGesture)
result = QGestureRecognizer::CancelGesture;
- else if (ev->touchPoints().size() == 3) {
+ else if (ev->points().size() == 3) {
d->state = QSwipeGesturePrivate::ThreePointsReached;
- QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
- QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
- QTouchEvent::TouchPoint p3 = ev->touchPoints().at(2);
+ const QEventPoint &p1 = ev->points().at(0);
+ const QEventPoint &p2 = ev->points().at(1);
+ const QEventPoint &p3 = ev->points().at(2);
if (d->lastPositions[0].isNull()) {
- d->lastPositions[0] = p1.startScreenPos().toPoint();
- d->lastPositions[1] = p2.startScreenPos().toPoint();
- d->lastPositions[2] = p3.startScreenPos().toPoint();
+ d->lastPositions[0] = p1.globalPressPosition().toPoint();
+ d->lastPositions[1] = p2.globalPressPosition().toPoint();
+ d->lastPositions[2] = p3.globalPressPosition().toPoint();
}
- d->hotSpot = p1.screenPos();
+ d->hotSpot = p1.globalPosition();
d->isHotSpotSet = true;
- int xDistance = (p1.screenPos().x() - d->lastPositions[0].x() +
- p2.screenPos().x() - d->lastPositions[1].x() +
- p3.screenPos().x() - d->lastPositions[2].x()) / 3;
- int yDistance = (p1.screenPos().y() - d->lastPositions[0].y() +
- p2.screenPos().y() - d->lastPositions[1].y() +
- p3.screenPos().y() - d->lastPositions[2].y()) / 3;
+ int xDistance = (p1.globalPosition().x() - d->lastPositions[0].x() +
+ p2.globalPosition().x() - d->lastPositions[1].x() +
+ p3.globalPosition().x() - d->lastPositions[2].x()) / 3;
+ int yDistance = (p1.globalPosition().y() - d->lastPositions[0].y() +
+ p2.globalPosition().y() - d->lastPositions[1].y() +
+ p3.globalPosition().y() - d->lastPositions[2].y()) / 3;
const int distance = xDistance >= yDistance ? xDistance : yDistance;
int elapsedTime = d->time.restart();
if (!elapsedTime)
elapsedTime = 1;
d->velocityValue = 0.9 * d->velocityValue + (qreal) distance / elapsedTime;
- d->swipeAngle = QLineF(p1.startScreenPos(), p1.screenPos()).angle();
+ d->swipeAngle = QLineF(p1.globalPressPosition(), p1.globalPosition()).angle();
static const int MoveThreshold = 50;
static const int directionChangeThreshold = MoveThreshold / 8;
if (qAbs(xDistance) > MoveThreshold || qAbs(yDistance) > MoveThreshold) {
// measure the distance to check if the direction changed
- d->lastPositions[0] = p1.screenPos().toPoint();
- d->lastPositions[1] = p2.screenPos().toPoint();
- d->lastPositions[2] = p3.screenPos().toPoint();
+ d->lastPositions[0] = p1.globalPosition().toPoint();
+ d->lastPositions[1] = p2.globalPosition().toPoint();
+ d->lastPositions[2] = p3.globalPosition().toPoint();
result = QGestureRecognizer::TriggerGesture;
// QTBUG-46195, small changes in direction should not cause the gesture to be canceled.
if (d->verticalDirection == QSwipeGesture::NoDirection || qAbs(yDistance) > directionChangeThreshold) {
@@ -370,7 +332,7 @@ QGestureRecognizer::Result QSwipeGestureRecognizer::recognize(QGesture *state,
else
result = QGestureRecognizer::MayBeGesture;
}
- } else if (ev->touchPoints().size() > 3) {
+ } else if (ev->points().size() > 3) {
result = QGestureRecognizer::CancelGesture;
} else { // less than 3 touch points
switch (d->state) {
@@ -381,7 +343,7 @@ QGestureRecognizer::Result QSwipeGestureRecognizer::recognize(QGesture *state,
result = QGestureRecognizer::Ignore;
break;
case QSwipeGesturePrivate::ThreePointsReached:
- result = (ev->touchPointStates() & Qt::TouchPointPressed)
+ result = (ev->touchPointStates() & QEventPoint::State::Pressed)
? QGestureRecognizer::CancelGesture : QGestureRecognizer::Ignore;
break;
}
@@ -439,16 +401,16 @@ QGestureRecognizer::Result QTapGestureRecognizer::recognize(QGesture *state,
switch (event->type()) {
case QEvent::TouchBegin: {
- d->position = ev->touchPoints().at(0).pos();
- q->setHotSpot(ev->touchPoints().at(0).screenPos());
+ d->position = ev->points().at(0).position();
+ q->setHotSpot(ev->points().at(0).globalPosition());
result = QGestureRecognizer::TriggerGesture;
break;
}
case QEvent::TouchUpdate:
case QEvent::TouchEnd: {
- if (q->state() != Qt::NoGesture && ev->touchPoints().size() == 1) {
- QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
- QPoint delta = p.pos().toPoint() - p.startPos().toPoint();
+ if (q->state() != Qt::NoGesture && ev->points().size() == 1) {
+ const QEventPoint &p = ev->points().at(0);
+ QPoint delta = p.position().toPoint() - p.pressPosition().toPoint();
enum { TapRadius = 40 };
if (delta.manhattanLength() <= TapRadius) {
if (event->type() == QEvent::TouchEnd)
@@ -526,7 +488,7 @@ QTapAndHoldGestureRecognizer::recognize(QGesture *state, QObject *object,
#endif
case QEvent::MouseButtonPress: {
const QMouseEvent *me = static_cast<const QMouseEvent *>(event);
- d->position = me->globalPos();
+ d->position = me->globalPosition().toPoint();
q->setHotSpot(d->position);
if (d->timerId)
q->killTimer(d->timerId);
@@ -535,7 +497,7 @@ QTapAndHoldGestureRecognizer::recognize(QGesture *state, QObject *object,
}
case QEvent::TouchBegin: {
const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
- d->position = ev->touchPoints().at(0).startScreenPos();
+ d->position = ev->points().at(0).globalPressPosition();
q->setHotSpot(d->position);
if (d->timerId)
q->killTimer(d->timerId);
@@ -550,9 +512,9 @@ QTapAndHoldGestureRecognizer::recognize(QGesture *state, QObject *object,
return QGestureRecognizer::CancelGesture; // get out of the MayBeGesture state
case QEvent::TouchUpdate: {
const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
- if (d->timerId && ev->touchPoints().size() == 1) {
- QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
- QPoint delta = p.pos().toPoint() - p.startPos().toPoint();
+ if (d->timerId && ev->points().size() == 1) {
+ const QEventPoint &p = ev->points().at(0);
+ QPoint delta = p.position().toPoint() - p.pressPosition().toPoint();
if (delta.manhattanLength() <= TapRadius)
return QGestureRecognizer::MayBeGesture;
}
@@ -560,7 +522,7 @@ QTapAndHoldGestureRecognizer::recognize(QGesture *state, QObject *object,
}
case QEvent::MouseMove: {
const QMouseEvent *me = static_cast<const QMouseEvent *>(event);
- QPoint delta = me->globalPos() - d->position.toPoint();
+ QPoint delta = me->globalPosition().toPoint() - d->position.toPoint();
if (d->timerId && delta.manhattanLength() <= TapRadius)
return QGestureRecognizer::MayBeGesture;
return QGestureRecognizer::CancelGesture;
diff --git a/src/widgets/kernel/qstandardgestures_p.h b/src/widgets/kernel/qstandardgestures_p.h
index 6de09361fe..ef1c1cb97c 100644
--- a/src/widgets/kernel/qstandardgestures_p.h
+++ b/src/widgets/kernel/qstandardgestures_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTANDARDGESTURES_P_H
#define QSTANDARDGESTURES_P_H
diff --git a/src/widgets/kernel/qt_widgets_pch.h b/src/widgets/kernel/qt_widgets_pch.h
index 3551f19e80..213e2c23e0 100644
--- a/src/widgets/kernel/qt_widgets_pch.h
+++ b/src/widgets/kernel/qt_widgets_pch.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*
* This is a precompiled header file for use in Xcode / Mac GCC /
@@ -48,6 +12,7 @@
#include "../../gui/kernel/qt_gui_pch.h"
#if defined __cplusplus
+#include <qtwidgetsexports.h>
#include <qtwidgetsglobal.h>
#include <qapplication.h>
#include <qabstractbutton.h>
diff --git a/src/widgets/kernel/qtestsupport_widgets.cpp b/src/widgets/kernel/qtestsupport_widgets.cpp
index 0056bebdc6..f7b25b6643 100644
--- a/src/widgets/kernel/qtestsupport_widgets.cpp
+++ b/src/widgets/kernel/qtestsupport_widgets.cpp
@@ -1,112 +1,179 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtTest module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
#include "qtestsupport_widgets.h"
#include "qwidget.h"
#include <QtGui/qwindow.h>
+#include <QtCore/qtestsupport_core.h>
+#include <QtCore/qthread.h>
#include <QtGui/qtestsupport_gui.h>
+#include <QtGui/private/qevent_p.h>
+#include <QtGui/private/qeventpoint_p.h>
+#include <private/qguiapplication_p.h>
+#include <qpa/qplatformintegration.h>
QT_BEGIN_NAMESPACE
+template <typename FunctorWindowGetter, typename FunctorPredicate, typename Timeout>
+static bool qWaitForWidgetWindow(FunctorWindowGetter windowGetter, FunctorPredicate predicate, Timeout timeout)
+{
+ if (!windowGetter())
+ return false;
+
+ return QTest::qWaitFor([&]() {
+ if (QWindow *window = windowGetter())
+ return predicate(window);
+ return false;
+ }, timeout);
+}
+
/*!
\since 5.0
- Waits for \a timeout milliseconds or until the \a widget's window is active.
+ Returns \c true if \a widget is active within \a timeout milliseconds. Otherwise returns \c false.
+
+ The method is useful in tests that call QWidget::show() and rely on the widget actually being
+ active (i.e. being visible and having focus) before proceeding.
+
+ \note The method will time out and return \c false if another window prevents \a widget from
+ becoming active.
- Returns \c true if \c widget's window is active within \a timeout milliseconds, otherwise returns \c false.
+ \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(), QWidget::isActiveWindow()
*/
-Q_WIDGETS_EXPORT Q_REQUIRED_RESULT bool QTest::qWaitForWindowActive(QWidget *widget, int timeout)
+Q_WIDGETS_EXPORT bool QTest::qWaitForWindowActive(QWidget *widget, int timeout)
{
- if (QWindow *window = widget->window()->windowHandle())
- return QTest::qWaitForWindowActive(window, timeout);
- return false;
+ if (Q_UNLIKELY(!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::WindowActivation))) {
+ qWarning() << "qWaitForWindowActive was called on a platform that doesn't support window"
+ << "activation. This means there is an error in the test and it should either"
+ << "check for the WindowActivation platform capability before calling"
+ << "qWaitForWindowActivate, use qWaitForWindowExposed instead, or skip the test."
+ << "Falling back to qWaitForWindowExposed.";
+ return qWaitForWindowExposed(widget, timeout);
+ }
+ return qWaitForWidgetWindow([&]() { return widget->window()->windowHandle(); },
+ [&](QWindow *window) { return window->isActive(); },
+ timeout);
}
+
/*!
- \since 5.0
+ \since 6.7
- Waits for \a timeout milliseconds or until the \a widget's window is exposed.
- Returns \c true if \c widget's window is exposed within \a timeout milliseconds, otherwise returns \c false.
+ Returns \c true, if \a widget is the focus window within \a timeout. Otherwise returns \c false.
- This is mainly useful for asynchronous systems like X11, where a window will be mapped to screen some
- time after being asked to show itself on the screen.
+ 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 that a window that is mapped to screen may still not be considered exposed if the window client
- area is completely covered by other windows, or if the window is otherwise not visible. This function
- will then time out when waiting for such a window.
+ \note The method will time out and return \c false if another window prevents \a widget from
+ becoming focused.
- A specific configuration where this happens is when using QGLWidget as a viewport widget on macOS:
- The viewport widget gets the expose event, not the parent widget.
+ \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 qWaitForWindowActive()
+ \sa qWaitForWindowExposed(), qWaitForWindowActive(), QGuiApplication::focusWindow()
*/
-Q_WIDGETS_EXPORT Q_REQUIRED_RESULT bool QTest::qWaitForWindowExposed(QWidget *widget, int timeout)
+Q_WIDGETS_EXPORT bool QTest::qWaitForWindowFocused(QWidget *widget, QDeadlineTimer timeout)
{
- if (QWindow *window = widget->window()->windowHandle())
- return QTest::qWaitForWindowExposed(window, timeout);
- return false;
+ return qWaitForWidgetWindow([&]() {
+ return widget->window()->windowHandle();
+ }, [&](QWindow *window) {
+ return qGuiApp->focusWindow() == window;
+ }, timeout);
}
-/*! \fn bool QTest::qWaitForWindowShown(QWidget *widget, int timeout)
+/*!
\since 5.0
- \deprecated
- Use qWaitForWindowExposed() instead.
+ Returns \c true if \a widget is exposed within \a timeout milliseconds. Otherwise returns \c false.
- Waits for \a timeout milliseconds or until the \a widget's window is exposed.
- Returns \c true if \c widget's window is exposed within \a timeout milliseconds, otherwise returns \c false.
+ The method is useful in tests that call QWidget::show() and rely on the widget actually being
+ being visible before proceeding.
- This function does the same as qWaitForWindowExposed().
+ \note A window mapped to screen may still not be considered exposed, if the window client area is
+ not visible, e.g. because it is completely covered by other windows.
+ In such cases, the method will time out and return \c false.
- Example:
+ \sa qWaitForWindowActive(), QWidget::isVisible(), QWindow::isExposed()
+*/
+Q_WIDGETS_EXPORT bool QTest::qWaitForWindowExposed(QWidget *widget, int timeout)
+{
+ return qWaitForWidgetWindow([&]() { return widget->window()->windowHandle(); },
+ [&](QWindow *window) { return window->isExposed(); },
+ timeout);
+}
- \code
- QWidget widget;
- widget.show();
- QTest::qWaitForWindowShown(&widget);
- \endcode
+namespace QTest {
- \sa qWaitForWindowActive(), qWaitForWindowExposed()
-*/
+QTouchEventWidgetSequence::~QTouchEventWidgetSequence()
+{
+ if (commitWhenDestroyed)
+ QTouchEventWidgetSequence::commit();
+}
+
+QTouchEventWidgetSequence& QTouchEventWidgetSequence::press(int touchId, const QPoint &pt, QWidget *widget)
+{
+ auto &p = point(touchId);
+ QMutableEventPoint::setGlobalPosition(p, mapToScreen(widget, pt));
+ QMutableEventPoint::setState(p, QEventPoint::State::Pressed);
+ return *this;
+}
+QTouchEventWidgetSequence& QTouchEventWidgetSequence::move(int touchId, const QPoint &pt, QWidget *widget)
+{
+ auto &p = point(touchId);
+ QMutableEventPoint::setGlobalPosition(p, mapToScreen(widget, pt));
+ QMutableEventPoint::setState(p, QEventPoint::State::Updated);
+ return *this;
+}
+QTouchEventWidgetSequence& QTouchEventWidgetSequence::release(int touchId, const QPoint &pt, QWidget *widget)
+{
+ auto &p = point(touchId);
+ QMutableEventPoint::setGlobalPosition(p, mapToScreen(widget, pt));
+ QMutableEventPoint::setState(p, QEventPoint::State::Released);
+ return *this;
+}
+
+QTouchEventWidgetSequence& QTouchEventWidgetSequence::stationary(int touchId)
+{
+ auto &p = pointOrPreviousPoint(touchId);
+ QMutableEventPoint::setState(p, QEventPoint::State::Stationary);
+ return *this;
+}
+
+bool QTouchEventWidgetSequence::commit(bool processEvents)
+{
+ bool ret = false;
+ if (points.isEmpty())
+ return ret;
+ QThread::sleep(std::chrono::milliseconds{1});
+ if (targetWindow) {
+ ret = qt_handleTouchEventv2(targetWindow, device, points.values());
+ } else if (targetWidget) {
+ ret = qt_handleTouchEventv2(targetWidget->windowHandle(), device, points.values());
+ }
+ if (processEvents)
+ QCoreApplication::processEvents();
+ previousPoints = points;
+ points.clear();
+ return ret;
+}
+
+QTest::QTouchEventWidgetSequence::QTouchEventWidgetSequence(QWidget *widget, QPointingDevice *aDevice, bool autoCommit)
+ : QTouchEventSequence(nullptr, aDevice, autoCommit), targetWidget(widget)
+{
+}
+
+QPoint QTouchEventWidgetSequence::mapToScreen(QWidget *widget, const QPoint &pt)
+{
+ if (widget)
+ return widget->mapToGlobal(pt);
+ return targetWidget ? targetWidget->mapToGlobal(pt) : pt;
+}
+
+} // namespace QTest
QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qtestsupport_widgets.h b/src/widgets/kernel/qtestsupport_widgets.h
index 2b37a9e858..b49e68db65 100644
--- a/src/widgets/kernel/qtestsupport_widgets.h
+++ b/src/widgets/kernel/qtestsupport_widgets.h
@@ -1,60 +1,45 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtTest module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
#ifndef QTESTSUPPORT_WIDGETS_H
#define QTESTSUPPORT_WIDGETS_H
#include <QtWidgets/qtwidgetsglobal.h>
+#include <QtGui/qtestsupport_gui.h>
QT_BEGIN_NAMESPACE
+class QPointingDevice;
class QWidget;
namespace QTest {
-Q_WIDGETS_EXPORT Q_REQUIRED_RESULT bool qWaitForWindowActive(QWidget *widget, int timeout = 5000);
-Q_WIDGETS_EXPORT Q_REQUIRED_RESULT bool qWaitForWindowExposed(QWidget *widget, int timeout = 5000);
-#if QT_DEPRECATED_SINCE(5, 0)
-QT_DEPRECATED Q_REQUIRED_RESULT inline static bool qWaitForWindowShown(QWidget *widget, int timeout = 5000)
-{ return QTest::qWaitForWindowExposed(widget, timeout); }
-#endif
-}
+[[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
+{
+public:
+ ~QTouchEventWidgetSequence() override;
+ QTouchEventWidgetSequence& press(int touchId, const QPoint &pt, QWidget *widget = nullptr);
+ QTouchEventWidgetSequence& move(int touchId, const QPoint &pt, QWidget *widget = nullptr);
+ QTouchEventWidgetSequence& release(int touchId, const QPoint &pt, QWidget *widget = nullptr);
+ QTouchEventWidgetSequence& stationary(int touchId) override;
+
+ bool commit(bool processEvents = true) override;
+
+private:
+ QTouchEventWidgetSequence(QWidget *widget, QPointingDevice *aDevice, bool autoCommit);
+
+ QPoint mapToScreen(QWidget *widget, const QPoint &pt);
+
+ QWidget *targetWidget = nullptr;
+
+ friend QTouchEventWidgetSequence touchEvent(QWidget *widget, QPointingDevice *device, bool autoCommit);
+};
+
+} // namespace QTest
QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qtooltip.cpp b/src/widgets/kernel/qtooltip.cpp
index 33dd3e59b6..35eaa8042a 100644
--- a/src/widgets/kernel/qtooltip.cpp
+++ b/src/widgets/kernel/qtooltip.cpp
@@ -1,47 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QtWidgets/private/qtwidgetsglobal_p.h>
#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <private/qdesktopwidget_p.h>
#include <qevent.h>
#include <qpointer.h>
#include <qstyle.h>
@@ -57,7 +19,6 @@
#include <qpa/qplatformcursor.h>
#include <private/qstylesheetstyle_p.h>
-#ifndef QT_NO_TOOLTIP
#include <qlabel.h>
#include <QtWidgets/private/qlabel_p.h>
#include <QtGui/private/qhighdpiscaling_p.h>
@@ -65,6 +26,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
\class QToolTip
@@ -82,15 +45,24 @@ QT_BEGIN_NAMESPACE
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
@@ -112,7 +84,7 @@ QT_BEGIN_NAMESPACE
\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
@@ -140,7 +112,7 @@ public:
bool tipChanged(const QPoint &pos, const QString &text, QObject *o);
void placeTip(const QPoint &pos, QWidget *w);
- static int getTipScreen(const QPoint &pos, QWidget *w);
+ static QScreen *getTipScreen(const QPoint &pos, QWidget *w);
protected:
void timerEvent(QTimerEvent *e) override;
void paintEvent(QPaintEvent *e) override;
@@ -150,7 +122,7 @@ protected:
#ifndef QT_NO_STYLE_STYLESHEET
public slots:
/** \internal
- Cleanup the _q_stylesheet_parent propery.
+ Cleanup the _q_stylesheet_parent property.
*/
void styleSheetParentDestroyed() {
setProperty("_q_stylesheet_parent", QVariant());
@@ -169,11 +141,11 @@ private:
QTipLabel *QTipLabel::instance = nullptr;
QTipLabel::QTipLabel(const QString &text, const QPoint &pos, QWidget *w, int msecDisplayTime)
+ : QLabel(w, Qt::ToolTip | Qt::BypassGraphicsProxyWidget)
#ifndef QT_NO_STYLE_STYLESHEET
- : QLabel(w, Qt::ToolTip | Qt::BypassGraphicsProxyWidget), styleSheetParent(nullptr), widget(nullptr)
-#else
- : QLabel(w, Qt::ToolTip | Qt::BypassGraphicsProxyWidget), widget(0)
+ , styleSheetParent(nullptr)
#endif
+ , widget(nullptr)
{
delete instance;
instance = this;
@@ -194,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().length()-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);
@@ -205,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
@@ -218,11 +192,7 @@ void QTipLabel::reuseTip(const QString &text, int msecDisplayTime, const QPoint
void QTipLabel::updateSize(const QPoint &pos)
{
-#ifndef Q_OS_WINRT
- // ### The code below does not always work well on WinRT
- // (e.g COIN fails an auto test - tst_QToolTip::qtbug64550_stylesheet - QTBUG-72652)
d_func()->setScreenForPoint(pos);
-#endif
// Ensure that we get correct sizeHints by placing this window on the right screen.
QFontMetrics fm(font());
QSize extra(1, 0);
@@ -231,16 +201,10 @@ void QTipLabel::updateSize(const QPoint &pos)
++extra.rheight();
setWordWrap(Qt::mightBeRichText(text()));
QSize sh = sizeHint();
- // ### When the above WinRT code is fixed, windowhandle should be used to find the screen.
- QScreen *screen = QGuiApplication::screenAt(pos);
- if (!screen)
- screen = QGuiApplication::primaryScreen();
- if (screen) {
- const qreal screenWidth = screen->geometry().width();
- if (!wordWrap() && sh.width() > screenWidth) {
- setWordWrap(true);
- sh = sizeHint();
- }
+ const QScreen *screen = getTipScreen(pos, this);
+ if (!wordWrap() && sh.width() > screen->geometry().width()) {
+ setWordWrap(true);
+ sh = sizeHint();
}
resize(sh + extra);
}
@@ -249,7 +213,7 @@ void QTipLabel::paintEvent(QPaintEvent *ev)
{
QStylePainter p(this);
QStyleOptionFrame opt;
- opt.init(this);
+ opt.initFrom(this);
p.drawPrimitive(QStyle::PE_PanelTipLabel, opt);
p.end();
@@ -260,7 +224,7 @@ void QTipLabel::resizeEvent(QResizeEvent *e)
{
QStyleHintReturnMask frameMask;
QStyleOption option;
- option.init(this);
+ option.initFrom(this);
if (style()->styleHint(QStyle::SH_ToolTip_Mask, &option, this, &frameMask))
setMask(frameMask.region);
@@ -270,7 +234,7 @@ void QTipLabel::resizeEvent(QResizeEvent *e)
void QTipLabel::mouseMoveEvent(QMouseEvent *e)
{
if (!rect.isNull()) {
- QPoint pos = e->globalPos();
+ QPoint pos = e->globalPosition().toPoint();
if (widget)
pos = widget->mapFromGlobal(pos);
if (!rect.contains(pos))
@@ -334,7 +298,7 @@ bool QTipLabel::eventFilter(QObject *o, QEvent *e)
break;
-#if defined (Q_OS_QNX) // On QNX the window activate and focus events are delayed and will appear
+#if defined (Q_OS_QNX) || defined (Q_OS_WASM) // On QNX the window activate and focus events are delayed and will appear
// after the window is shown.
case QEvent::WindowActivate:
case QEvent::FocusIn:
@@ -355,7 +319,6 @@ bool QTipLabel::eventFilter(QObject *o, QEvent *e)
case QEvent::FocusIn:
case QEvent::FocusOut:
#endif
- case QEvent::Close: // For QTBUG-55523 (QQC) specifically: Hide tooltip when windows are closed
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
@@ -364,20 +327,20 @@ bool QTipLabel::eventFilter(QObject *o, QEvent *e)
break;
case QEvent::MouseMove:
- if (o == widget && !rect.isNull() && !rect.contains(static_cast<QMouseEvent*>(e)->pos()))
+ if (o == widget && !rect.isNull() && !rect.contains(static_cast<QMouseEvent*>(e)->position().toPoint()))
hideTip();
+ break;
default:
break;
}
return false;
}
-int QTipLabel::getTipScreen(const QPoint &pos, QWidget *w)
+QScreen *QTipLabel::getTipScreen(const QPoint &pos, QWidget *w)
{
- if (QDesktopWidgetPrivate::isVirtualDesktop())
- return QDesktopWidgetPrivate::screenNumber(pos);
- else
- return QDesktopWidgetPrivate::screenNumber(w);
+ QScreen *guess = w ? w->screen() : QGuiApplication::primaryScreen();
+ QScreen *exact = guess->virtualSiblingAt(pos);
+ return exact ? exact : guess;
}
void QTipLabel::placeTip(const QPoint &pos, QWidget *w)
@@ -387,26 +350,30 @@ void QTipLabel::placeTip(const QPoint &pos, QWidget *w)
//the stylesheet need to know the real parent
QTipLabel::instance->setProperty("_q_stylesheet_parent", QVariant::fromValue(w));
//we force the style to be the QStyleSheetStyle, and force to clear the cache as well.
- QTipLabel::instance->setStyleSheet(QLatin1String("/* */"));
+ QTipLabel::instance->setStyleSheet("/* */"_L1);
// 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
QPoint p = pos;
- int screenNumber = getTipScreen(pos, w);
- QScreen *screen = QGuiApplication::screens().at(screenNumber);
- if (screen) {
- const QPlatformScreen *platformScreen = screen->handle();
- const QSize cursorSize = QHighDpi::fromNativePixels(platformScreen->cursor()->size(),
+ const QScreen *screen = getTipScreen(pos, w);
+ // a QScreen's handle *should* never be null, so this is a bit paranoid
+ if (const QPlatformScreen *platformScreen = screen ? screen->handle() : nullptr) {
+ QPlatformCursor *cursor = platformScreen->cursor();
+ // default implementation of QPlatformCursor::size() returns QSize(16, 16)
+ const QSize nativeSize = cursor ? cursor->size() : QSize(16, 16);
+ const QSize cursorSize = QHighDpi::fromNativePixels(nativeSize,
platformScreen);
QPoint offset(2, cursorSize.height());
// assuming an arrow shape, we can just move to the side for very large cursors
@@ -459,32 +426,23 @@ bool QTipLabel::tipChanged(const QPoint &pos, const QString &text, QObject *o)
Otherwise this argument can be \nullptr but it is used to
determine the appropriate screen on multi-head systems.
+ The \a msecDisplayTime parameter specifies for how long the tool tip
+ will be displayed, in milliseconds. With the default value of -1, the
+ time is based on the length of the text.
+
If \a text is empty the tool tip is hidden. If the text is the
same as the currently shown tooltip, the tip will \e not move.
You can force moving by first hiding the tip with an empty text,
and then showing the new tip at the new position.
*/
-void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect)
-{
- showText(pos, text, w, rect, -1);
-}
-
-/*!
- \since 5.2
- \overload
- This is similar to QToolTip::showText(\a pos, \a text, \a w, \a rect) but with an extra parameter \a msecDisplayTime
- that specifies how long the tool tip will be displayed, in milliseconds.
-*/
-
void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect, int msecDisplayTime)
{
- if (QTipLabel::instance && QTipLabel::instance->isVisible()){ // a tip does already exist
+ if (QTipLabel::instance && QTipLabel::instance->isVisible()) { // a tip does already exist
if (text.isEmpty()){ // empty text means hide current tip
QTipLabel::instance->hideTip();
return;
- }
- else if (!QTipLabel::instance->fadingOut){
+ } else if (!QTipLabel::instance->fadingOut) {
// If the tip has changed, reuse the one
// that is showing (removes flickering)
QPoint localPos = pos;
@@ -499,21 +457,22 @@ void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, cons
}
}
- if (!text.isEmpty()){ // no tip can be reused, create new tip:
+ if (!text.isEmpty()) { // no tip can be reused, create new tip:
+ QWidget *tipLabelParent = [w]() -> QWidget* {
#ifdef Q_OS_WIN32
- // On windows, we can't use the widget as parent otherwise the window will be
- // raised when the tooltip will be shown
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- new QTipLabel(text, pos, QApplication::desktop()->screen(QTipLabel::getTipScreen(pos, w)), msecDisplayTime);
-QT_WARNING_POP
+ // On windows, we can't use the widget as parent otherwise the window will be
+ // raised when the tooltip will be shown
+ Q_UNUSED(w);
+ return nullptr;
#else
- new QTipLabel(text, pos, w, msecDisplayTime); // sets QTipLabel::instance to itself
+ return w;
#endif
+ }();
+ new QTipLabel(text, pos, tipLabelParent, msecDisplayTime); // sets QTipLabel::instance to itself
+ QWidgetPrivate::get(QTipLabel::instance)->setScreen(QTipLabel::getTipScreen(pos, w));
QTipLabel::instance->setTipRect(w, rect);
QTipLabel::instance->placeTip(pos, w);
- QTipLabel::instance->setObjectName(QLatin1String("qtooltip_label"));
-
+ QTipLabel::instance->setObjectName("qtooltip_label"_L1);
#if QT_CONFIG(effects)
if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip))
@@ -529,18 +488,6 @@ QT_WARNING_POP
}
/*!
- \overload
-
- This is analogous to calling QToolTip::showText(\a pos, \a text, \a w, QRect())
-*/
-
-void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w)
-{
- QToolTip::showText(pos, text, w, QRect());
-}
-
-
-/*!
\fn void QToolTip::hideText()
\since 4.2
@@ -554,7 +501,7 @@ void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w)
/*!
\since 4.4
- Returns \c true if this tooltip is currently shown.
+ Returns \c true if a tooltip is currently shown.
\sa showText()
*/
@@ -628,4 +575,3 @@ void QToolTip::setFont(const QFont &font)
QT_END_NAMESPACE
#include "qtooltip.moc"
-#endif // QT_NO_TOOLTIP
diff --git a/src/widgets/kernel/qtooltip.h b/src/widgets/kernel/qtooltip.h
index 1b263a6629..863162e15b 100644
--- a/src/widgets/kernel/qtooltip.h
+++ b/src/widgets/kernel/qtooltip.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTOOLTIP_H
#define QTOOLTIP_H
@@ -43,19 +7,15 @@
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qwidget.h>
+QT_REQUIRE_CONFIG(tooltip);
QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_TOOLTIP
-
class Q_WIDGETS_EXPORT QToolTip
{
QToolTip() = delete;
public:
- // ### Qt 6 - merge the three showText functions below
- static void showText(const QPoint &pos, const QString &text, QWidget *w = nullptr);
- static void showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect);
- static void showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect, int msecShowTime);
+ static void showText(const QPoint &pos, const QString &text,
+ QWidget *w = nullptr, const QRect &rect = {}, int msecShowTime = -1);
static inline void hideText() { showText(QPoint(), QString()); }
static bool isVisible();
@@ -67,8 +27,6 @@ public:
static void setFont(const QFont &);
};
-#endif // QT_NO_TOOLTIP
-
QT_END_NAMESPACE
#endif // QTOOLTIP_H
diff --git a/src/widgets/kernel/qtwidgetsglobal.h b/src/widgets/kernel/qtwidgetsglobal.h
index 1c74f37618..bfa7272f19 100644
--- a/src/widgets/kernel/qtwidgetsglobal.h
+++ b/src/widgets/kernel/qtwidgetsglobal.h
@@ -1,60 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTWIDGETSGLOBAL_H
#define QTWIDGETSGLOBAL_H
#include <QtGui/qtguiglobal.h>
#include <QtWidgets/qtwidgets-config.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_STATIC
-# if defined(QT_BUILD_WIDGETS_LIB)
-# define Q_WIDGETS_EXPORT Q_DECL_EXPORT
-# else
-# define Q_WIDGETS_EXPORT Q_DECL_IMPORT
-# endif
-#else
-# define Q_WIDGETS_EXPORT
-#endif
-
-QT_END_NAMESPACE
+#include <QtWidgets/qtwidgetsexports.h>
#endif // QTGUIGLOBAL_H
diff --git a/src/widgets/kernel/qtwidgetsglobal_p.h b/src/widgets/kernel/qtwidgetsglobal_p.h
index 22ba876022..535071891e 100644
--- a/src/widgets/kernel/qtwidgetsglobal_p.h
+++ b/src/widgets/kernel/qtwidgetsglobal_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTWIDGETSGLOBAL_P_H
#define QTWIDGETSGLOBAL_P_H
diff --git a/src/widgets/kernel/qwhatsthis.cpp b/src/widgets/kernel/qwhatsthis.cpp
index 8a632a395a..c80f37267f 100644
--- a/src/widgets/kernel/qwhatsthis.cpp
+++ b/src/widgets/kernel/qwhatsthis.cpp
@@ -1,48 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qwhatsthis.h"
#include "qpointer.h"
#include "qapplication.h"
#include <private/qguiapplication_p.h>
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
+#include "qwidget.h"
#include "qevent.h"
#include "qpixmap.h"
#include "qscreen.h"
@@ -57,7 +20,7 @@
#include <qpa/qplatformtheme.h>
#include "private/qtextdocumentlayout_p.h"
#include "qdebug.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
@@ -134,8 +97,6 @@ QT_BEGIN_NAMESPACE
\sa QToolTip
*/
-Q_CORE_EXPORT void qDeleteInEventHandler(QObject *o);
-
class QWhatsThat : public QWidget
{
Q_OBJECT
@@ -147,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;
@@ -160,7 +120,6 @@ private:
QString text;
QTextDocument* doc;
QString anchor;
- QPixmap background;
};
QWhatsThat *QWhatsThat::instance = nullptr;
@@ -212,15 +171,15 @@ QWhatsThat::QWhatsThat(const QString& txt, QWidget* parent, QWidget *showTextFor
}
else
{
- int sw = QDesktopWidgetPrivate::width() / 3;
+ int sw = QGuiApplication::primaryScreen()->virtualGeometry().width() / 3;
if (sw < 200)
sw = 200;
else if (sw > 300)
sw = 300;
r = fontMetrics().boundingRect(0, 0, sw, 1000,
- Qt::AlignLeft + Qt::AlignTop
- + Qt::TextWordWrap + Qt::TextExpandTabs,
+ Qt::AlignLeft | Qt::AlignTop
+ | Qt::TextWordWrap | Qt::TextExpandTabs,
text);
}
shadowWidth = dropShadow() ? 0 : 6;
@@ -234,18 +193,12 @@ QWhatsThat::~QWhatsThat()
delete doc;
}
-void QWhatsThat::showEvent(QShowEvent *)
-{
- background = QGuiApplication::primaryScreen()->grabWindow(QApplication::desktop()->internalWinId(),
- x(), y(), width(), height());
-}
-
void QWhatsThat::mousePressEvent(QMouseEvent* e)
{
pressed = true;
- if (e->button() == Qt::LeftButton && rect().contains(e->pos())) {
+ if (e->button() == Qt::LeftButton && rect().contains(e->position().toPoint())) {
if (doc)
- anchor = doc->documentLayout()->anchorAt(e->pos() - QPoint(hMargin, vMargin));
+ anchor = doc->documentLayout()->anchorAt(e->position().toPoint() - QPoint(hMargin, vMargin));
return;
}
close();
@@ -255,8 +208,8 @@ void QWhatsThat::mouseReleaseEvent(QMouseEvent* e)
{
if (!pressed)
return;
- if (widget && e->button() == Qt::LeftButton && doc && rect().contains(e->pos())) {
- QString a = doc->documentLayout()->anchorAt(e->pos() - QPoint(hMargin, vMargin));
+ if (widget && e->button() == Qt::LeftButton && doc && rect().contains(e->position().toPoint())) {
+ QString a = doc->documentLayout()->anchorAt(e->position().toPoint() - QPoint(hMargin, vMargin));
QString href;
if (anchor == a)
href = a;
@@ -277,7 +230,7 @@ void QWhatsThat::mouseMoveEvent(QMouseEvent* e)
#else
if (!doc)
return;
- QString a = doc->documentLayout()->anchorAt(e->pos() - QPoint(hMargin, vMargin));
+ QString a = doc->documentLayout()->anchorAt(e->position().toPoint() - QPoint(hMargin, vMargin));
if (!a.isEmpty())
setCursor(Qt::PointingHandCursor);
else
@@ -299,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);
@@ -335,7 +287,7 @@ void QWhatsThat::paintEvent(QPaintEvent*)
}
else
{
- p.drawText(r, Qt::AlignLeft + Qt::AlignTop + Qt::TextWordWrap + Qt::TextExpandTabs, text);
+ p.drawText(r, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap | Qt::TextExpandTabs, text);
}
}
@@ -404,7 +356,7 @@ QWhatsThisPrivate::QWhatsThisPrivate()
QGuiApplication::setOverrideCursor(Qt::WhatsThisCursor);
#endif
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleEvent event(this, QAccessible::ContextHelpStart);
QAccessible::updateAccessibility(&event);
#endif
@@ -419,7 +371,7 @@ QWhatsThisPrivate::~QWhatsThisPrivate()
#ifndef QT_NO_CURSOR
QGuiApplication::restoreOverrideCursor();
#endif
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleEvent event(this, QAccessible::ContextHelpEnd);
QAccessible::updateAccessibility(&event);
#endif
@@ -438,7 +390,7 @@ bool QWhatsThisPrivate::eventFilter(QObject *o, QEvent *e)
QMouseEvent *me = static_cast<QMouseEvent*>(e);
if (me->button() == Qt::RightButton || customWhatsThis)
return false;
- QHelpEvent e(QEvent::WhatsThis, me->pos(), me->globalPos());
+ QHelpEvent e(QEvent::WhatsThis, me->position().toPoint(), me->globalPosition().toPoint());
if (!QCoreApplication::sendEvent(w, &e) || !e.isAccepted())
leaveOnMouseRelease = true;
@@ -447,7 +399,7 @@ bool QWhatsThisPrivate::eventFilter(QObject *o, QEvent *e)
case QEvent::MouseMove:
{
QMouseEvent *me = static_cast<QMouseEvent*>(e);
- QHelpEvent e(QEvent::QueryWhatsThis, me->pos(), me->globalPos());
+ QHelpEvent e(QEvent::QueryWhatsThis, me->position().toPoint(), me->globalPosition().toPoint());
const bool sentEvent = QCoreApplication::sendEvent(w, &e);
#ifdef QT_NO_CURSOR
Q_UNUSED(sentEvent);
@@ -466,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();
@@ -510,9 +462,9 @@ 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);
+ setShortcut(Qt::ShiftModifier | Qt::Key_F1);
#endif
}
@@ -580,16 +532,16 @@ void QWhatsThisPrivate::say(QWidget * widget, const QString &text, int x, int y)
QWhatsThat *whatsThat = new QWhatsThat(text, nullptr, widget);
// okay, now to find a suitable location
- int scr = (widget ?
- QDesktopWidgetPrivate::screenNumber(widget) :
- QDesktopWidgetPrivate::screenNumber(QPoint(x,y))
- );
- QRect screen = QDesktopWidgetPrivate::screenGeometry(scr);
+ QScreen *screen = widget ? widget->screen()
+ : QGuiApplication::screenAt(QPoint(x, y));
+ if (!screen)
+ screen = QGuiApplication::primaryScreen();
+ QRect screenRect = screen->geometry();
int w = whatsThat->width();
int h = whatsThat->height();
- int sx = screen.x();
- int sy = screen.y();
+ int sx = screenRect.x();
+ int sy = screenRect.y();
// first try locating the widget immediately above/below,
// with nice alignment if possible.
@@ -602,13 +554,13 @@ void QWhatsThisPrivate::say(QWidget * widget, const QString &text, int x, int y)
else
x = x - w/2;
- // squeeze it in if that would result in part of what's this
- // being only partially visible
- if (x + w + shadowWidth > sx+screen.width())
- x = (widget? (qMin(screen.width(),
- pos.x() + widget->width())
- ) : screen.width())
+ // squeeze it in if that would result in part of what's this
+ // being only partially visible
+ if (x + w + shadowWidth > sx+screenRect.width()) {
+ x = (widget ? qMin(screenRect.width(), pos.x() + widget->width())
+ : screenRect.width())
- w;
+ }
if (x < sx)
x = sx;
@@ -616,18 +568,18 @@ void QWhatsThisPrivate::say(QWidget * widget, const QString &text, int x, int y)
if (widget && h > widget->height() + 16) {
y = pos.y() + widget->height() + 2; // below, two pixels spacing
// what's this is above or below, wherever there's most space
- if (y + h + 10 > sy+screen.height())
+ if (y + h + 10 > sy + screenRect.height())
y = pos.y() + 2 - shadowWidth - h; // above, overlap
}
y = y + 2;
- // squeeze it in if that would result in part of what's this
- // being only partially visible
- if (y + h + shadowWidth > sy+screen.height())
- y = (widget ? (qMin(screen.height(),
- pos.y() + widget->height())
- ) : screen.height())
+ // squeeze it in if that would result in part of what's this
+ // being only partially visible
+ if (y + h + shadowWidth > sy + screenRect.height()) {
+ y = (widget ? qMin(screenRect.height(), pos.y() + widget->height())
+ : screenRect.height())
- h;
+ }
if (y < sy)
y = sy;
@@ -656,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/qwhatsthis.h b/src/widgets/kernel/qwhatsthis.h
index fa5b97d98a..0ab32d8bd6 100644
--- a/src/widgets/kernel/qwhatsthis.h
+++ b/src/widgets/kernel/qwhatsthis.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWHATSTHIS_H
#define QWHATSTHIS_H
diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp
index db3c269949..2cc40fc7ad 100644
--- a/src/widgets/kernel/qwidget.cpp
+++ b/src/widgets/kernel/qwidget.cpp
@@ -1,48 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qapplication.h"
#include "qapplication_p.h"
#include "qbrush.h"
#include "qcursor.h"
-#include "qdesktopwidget_p.h"
+#include "private/qduplicatetracker_p.h"
#include "qevent.h"
#include "qlayout.h"
#if QT_CONFIG(menu)
@@ -58,13 +22,16 @@
#include "qwidget.h"
#include "qstyleoption.h"
#include "qstylehints.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
# include "qaccessible.h"
#endif
#include <qpa/qplatformwindow.h>
+#include <qpa/qplatformwindow_p.h>
#include "private/qwidgetwindow_p.h"
#include "qpainter.h"
+#if QT_CONFIG(tooltip)
#include "qtooltip.h"
+#endif
#if QT_CONFIG(whatsthis)
#include "qwhatsthis.h"
#endif
@@ -75,9 +42,6 @@
#include "qscopeguard.h"
#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtGui/qinputmethod.h>
-#include <QtGui/qopenglcontext.h>
-#include <QtGui/private/qopenglcontext_p.h>
-#include <QtGui/qoffscreensurface.h>
#if QT_CONFIG(graphicseffect)
#include <private/qgraphicseffect_p.h>
@@ -89,7 +53,7 @@
#include "qwidget_p.h"
#include <QtGui/private/qwindow_p.h>
#if QT_CONFIG(action)
-# include "qaction_p.h"
+# include "QtGui/private/qaction_p.h"
#endif
#include "qlayout_p.h"
#if QT_CONFIG(graphicsview)
@@ -111,17 +75,24 @@
#include "qwindowcontainer_p.h"
-#include <QtPlatformHeaders/qxcbwindowfunctions.h>
-
-#include <private/qmemory_p.h>
-
-// widget/widget data creation count
-//#define QWIDGET_EXTRA_DEBUG
-//#define ALIEN_DEBUG
+#include <sstream>
QT_BEGIN_NAMESPACE
+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)
{
@@ -130,7 +101,6 @@ static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
}
extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
-extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
QWidgetPrivate::QWidgetPrivate(int version)
: QObjectPrivate(version)
@@ -147,11 +117,12 @@ QWidgetPrivate::QWidgetPrivate(int version)
#if !defined(QT_NO_IM)
, imHints(Qt::ImhNone)
#endif
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
, toolTipDuration(-1)
#endif
, directFontResolveMask(0)
, inheritedFontResolveMask(0)
+ , directPaletteResolveMask(0)
, inheritedPaletteResolveMask(0)
, leftmargin(0)
, topmargin(0)
@@ -178,10 +149,8 @@ QWidgetPrivate::QWidgetPrivate(int version)
#ifndef QT_NO_IM
, inheritsInputMethodHints(0)
#endif
-#ifndef QT_NO_OPENGL
, renderToTextureReallyDirty(1)
- , renderToTextureComposeActive(0)
-#endif
+ , usesRhiFlush(0)
, childrenHiddenByWState(0)
, childrenShownByExpose(0)
#if defined(Q_OS_WIN)
@@ -203,7 +172,7 @@ QWidgetPrivate::QWidgetPrivate(int version)
version, QObjectPrivateVersion);
#endif
- isWidget = true;
+ willBeWidget = true; // used in QObject's ctor
memset(high_attributes, 0, sizeof(high_attributes));
#ifdef QWIDGET_EXTRA_DEBUG
@@ -388,25 +357,25 @@ void QWidget::setAutoFillBackground(bool enabled)
A 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
- \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
+ \l{Qt::WindowFlags}{window flags}. In Qt, QMainWindow and the various
subclasses of QDialog are the most common window types.
Every widget's constructor accepts one or two standard arguments:
\list 1
- \li \c{QWidget *parent = \nullptr} is the parent of the new widget.
+ \li \c{QWidget *parent = nullptr} is the parent of the new widget.
If it is \nullptr (the default), the new widget will be a window.
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.
@@ -414,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
@@ -427,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.
@@ -437,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
@@ -458,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.
@@ -470,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
@@ -490,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
@@ -557,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
@@ -571,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.
@@ -709,12 +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 Qt::WA_ContentsPropagated widget attribute has been
- deprecated. Instead, 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
@@ -731,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
@@ -742,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
@@ -755,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
@@ -779,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
@@ -793,24 +756,26 @@ void QWidget::setAutoFillBackground(bool enabled)
and a compositing window manager.
\li Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
for the translucency to work.
+ \li \macos: The widget needs to have the Qt::FramelessWindowHint window flag set
+ for the translucency to work.
\endlist
\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
@@ -842,7 +807,6 @@ QWidgetSet *QWidgetPrivate::allWidgets = nullptr; // widgets with no wid
\li Qt::WA_WState_InPaintEvent Currently processing a paint event.
\li Qt::WA_WState_Reparented The widget has been reparented.
\li Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
- \li Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
\endlist
*/
@@ -856,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
}
};
@@ -966,18 +925,11 @@ void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
flags |= Qt::WindowSystemMenuHint;
flags |= Qt::WindowTitleHint;
}
- if (customize)
- ; // don't modify window flags if the user explicitly set them.
- else if (type == Qt::Dialog || type == Qt::Sheet) {
- flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
- // ### fixme: Qt 6: Never set Qt::WindowContextHelpButtonHint flag automatically
- if (!QApplicationPrivate::testAttribute(Qt::AA_DisableWindowContextHelpButton))
- flags |= Qt::WindowContextHelpButtonHint;
- } else if (type == Qt::Tool)
+ if (!customize) { // don't modify window flags if the user explicitly set them.
flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
- else
- flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint |
- Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint;
+ if (type != Qt::Dialog && type != Qt::Sheet && type != Qt::Tool)
+ flags |= Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowFullscreenButtonHint;
+ }
if (w->testAttribute(Qt::WA_TransparentForMouseEvents))
flags |= Qt::WindowTransparentForInput;
}
@@ -985,6 +937,9 @@ void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
{
Q_Q(QWidget);
+ isWidget = true;
+ wasWidget = true;
+
Q_ASSERT_X(q != parentWidget, Q_FUNC_INFO, "Cannot parent a QWidget to itself");
if (Q_UNLIKELY(!qobject_cast<QApplication *>(QCoreApplication::instance())))
@@ -994,13 +949,6 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
if (allWidgets)
allWidgets->insert(q);
- int targetScreen = -1;
- if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
- const QDesktopScreenWidget *sw = qobject_cast<const QDesktopScreenWidget *>(parentWidget);
- targetScreen = sw ? sw->screenNumber() : 0;
- parentWidget = nullptr;
- }
-
q->data = &data;
#if QT_CONFIG(thread)
@@ -1010,12 +958,6 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
}
#endif
- if (targetScreen >= 0) {
- topData()->initialScreenIndex = targetScreen;
- if (QWindow *window = q->windowHandle())
- window->setScreen(QGuiApplication::screens().value(targetScreen, nullptr));
- }
-
data.fstrut_dirty = true;
data.winid = 0;
@@ -1027,7 +969,7 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
data.window_modality = Qt::NonModal;
data.sizehint_forced = 0;
- data.is_closing = 0;
+ data.is_closing = false;
data.in_show = 0;
data.in_set_window_state = 0;
data.in_destructor = false;
@@ -1046,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();
@@ -1067,9 +1009,6 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
- if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation)) // ### fixme: Qt 6: Remove AA_ImmediateWidgetCreation.
- q->create();
-
QEvent e(QEvent::Create);
QCoreApplication::sendEvent(q, &e);
QCoreApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
@@ -1088,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) {
@@ -1097,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;
@@ -1111,13 +1076,70 @@ QWindow *QWidgetPrivate::windowHandle(WindowHandleMode mode) const
return nullptr;
}
+/*!
+ \internal
+
+ Used by clients outside of widgets to get a handle to the
+ closest QWindow without having to link to widgets.
+*/
+QWindow *QWidgetPrivate::_q_closestWindowHandle() const
+{
+ return windowHandle(QWidgetPrivate::WindowHandleMode::Closest);
+}
+
QScreen *QWidgetPrivate::associatedScreen() const
{
+#if QT_CONFIG(graphicsview)
+ // embedded widgets never have a screen associated, let QWidget::screen fall back to toplevel
+ if (nearestGraphicsProxyWidget(q_func()))
+ return nullptr;
+#endif
if (auto window = windowHandle(WindowHandleMode::Closest))
return window->screen();
return nullptr;
}
+// finds the first rhiconfig in the hierarchy that has enable==true
+static bool q_evaluateRhiConfigRecursive(const QWidget *w, QPlatformBackingStoreRhiConfig *outConfig, QSurface::SurfaceType *outType)
+{
+ QPlatformBackingStoreRhiConfig config = QWidgetPrivate::get(w)->rhiConfig();
+ if (config.isEnabled()) {
+ if (outConfig)
+ *outConfig = config;
+ if (outType)
+ *outType = QBackingStoreRhiSupport::surfaceTypeForConfig(config);
+ return true;
+ }
+ for (const QObject *child : w->children()) {
+ if (const QWidget *childWidget = qobject_cast<const QWidget *>(child)) {
+ if (q_evaluateRhiConfigRecursive(childWidget, outConfig, outType))
+ return true;
+ }
+ }
+ return false;
+}
+
+bool q_evaluateRhiConfig(const QWidget *w, QPlatformBackingStoreRhiConfig *outConfig, QSurface::SurfaceType *outType)
+{
+ // First, check env.vars. or other means that force the usage of rhi-based
+ // flushing with a specific graphics API. This takes precedence over what
+ // the widgets themselves declare. This is global, applying to all
+ // top-levels.
+ if (QBackingStoreRhiSupport::checkForceRhi(outConfig, outType)) {
+ qCDebug(lcWidgetPainting) << "Tree with root" << w << "evaluated to forced flushing with QRhi";
+ return true;
+ }
+
+ // Otherwise, check the widget hierarchy to see if there is a child (or
+ // ourselves) that declare the need for rhi-based composition.
+ if (q_evaluateRhiConfigRecursive(w, outConfig, outType)) {
+ qCDebug(lcWidgetPainting) << "Tree with root" << w << "evaluates to flushing with QRhi";
+ return true;
+ }
+
+ return false;
+}
+
// ### fixme: Qt 6: Remove parameter window from QWidget::create()
/*!
@@ -1178,11 +1200,6 @@ void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
setAttribute(Qt::WA_NativeWindow);
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
- << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
-#endif
-
d->updateIsOpaque();
setAttribute(Qt::WA_WState_Created); // set created flag
@@ -1260,6 +1277,7 @@ void QWidgetPrivate::create()
// in case the extra was already valid.
if (!win) {
createTLSysExtra();
+ Q_ASSERT(topData()->window);
win = topData()->window;
}
@@ -1271,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
@@ -1280,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)
@@ -1289,13 +1306,13 @@ void QWidgetPrivate::create()
else
win->resize(q->size());
if (win->isTopLevel()) {
- int screenNumber = topData()->initialScreenIndex;
- topData()->initialScreenIndex = -1;
- if (screenNumber < 0) {
- screenNumber = q->windowType() != Qt::Desktop
- ? QDesktopWidgetPrivate::screenNumber(q) : 0;
+ QScreen *targetScreen = topData()->initialScreen;
+ topData()->initialScreen = nullptr;
+ if (!targetScreen) {
+ targetScreen = q->windowType() != Qt::Desktop
+ ? q->screen() : nullptr;
}
- win->setScreen(QGuiApplication::screens().value(screenNumber, nullptr));
+ win->setScreen(targetScreen);
}
QSurfaceFormat format = win->requestedFormat();
@@ -1328,21 +1345,30 @@ 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 (!topData()->role.isNull())
- QXcbWindowFunctions::setWmWindowRole(win, topData()->role.toLatin1());
+#if QT_CONFIG(xcb)
+ if (!topData()->role.isNull()) {
+ if (auto *xcbWindow = dynamic_cast<QXcbWindow*>(win->handle()))
+ xcbWindow->setWindowRole(topData()->role);
+ }
+#endif
QBackingStore *store = q->backingStore();
+ usesRhiFlush = false;
if (!store) {
if (q->windowType() != Qt::Desktop) {
- if (q->isTopLevel())
+ if (q->isWindow()) {
q->setBackingStore(new QBackingStore(win));
+ QPlatformBackingStoreRhiConfig rhiConfig;
+ usesRhiFlush = q_evaluateRhiConfig(q, &rhiConfig, nullptr);
+ topData()->backingStore->handle()->setRhiConfig(rhiConfig);
+ }
} else {
q->setAttribute(Qt::WA_PaintOnScreen, true);
}
+ } else if (win->handle()) {
+ usesRhiFlush = q_evaluateRhiConfig(q, nullptr, nullptr);
}
setWindowModified_helper();
@@ -1353,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);
@@ -1396,6 +1423,8 @@ void QWidgetPrivate::createTLSysExtra()
#endif
if (isTipLabel || isAlphaWidget || q->inherits("QRollEffect"))
qt_window_private(extra->topextra->window)->setAutomaticPositionAndResizeEnabled(false);
+
+ updateIsTranslucent();
}
}
@@ -1428,9 +1457,9 @@ QWidget::~QWidget()
#ifndef QT_NO_ACTION
// remove all actions from this widget
- for (int i = 0; i < d->actions.size(); ++i) {
- QActionPrivate *apriv = d->actions.at(i)->d_func();
- apriv->widgets.removeAll(this);
+ for (auto action : std::as_const(d->actions)) {
+ QActionPrivate *apriv = action->d_func();
+ apriv->associatedObjects.removeAll(this);
}
d->actions.clear();
#endif
@@ -1445,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)
@@ -1475,7 +1496,7 @@ QWidget::~QWidget()
if (isWindow() && isVisible() && internalWinId()) {
QT_TRY {
- d->close_helper(QWidgetPrivate::CloseNoEvent);
+ d->close();
} QT_CATCH(...) {
// if we're out of memory, at least hide the window.
QT_TRY {
@@ -1548,6 +1569,8 @@ QWidget::~QWidget()
#if QT_CONFIG(graphicseffect)
delete d->graphicsEffect;
#endif
+
+ d->isWidget = false;
}
int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
@@ -1556,24 +1579,18 @@ int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
void QWidgetPrivate::setWinId(WId id) // set widget identifier
{
Q_Q(QWidget);
- // the user might create a widget with Qt::Desktop window
- // attribute (or create another QDesktopWidget instance), which
- // will have the same windowid (the root window id) as the
- // qt_desktopWidget. We should not add the second desktop widget
- // to the mapper.
- bool userDesktopWidget = qt_desktopWidget != nullptr && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
- if (mapper && data.winid && !userDesktopWidget) {
+ if (mapper && data.winid) {
mapper->remove(data.winid);
}
const WId oldWinId = data.winid;
data.winid = id;
- if (mapper && id && !userDesktopWidget) {
+ if (mapper && id) {
mapper->insert(data.winid, q);
}
- if(oldWinId != id) {
+ if (oldWinId != id) {
QEvent e(QEvent::WinIdChange);
QCoreApplication::sendEvent(q, &e);
}
@@ -1584,7 +1601,7 @@ void QWidgetPrivate::createTLExtra()
if (!extra)
createExtra();
if (!extra->topextra) {
- extra->topextra = qt_make_unique<QTLWExtra>();
+ extra->topextra = std::make_unique<QTLWExtra>();
QTLWExtra* x = extra->topextra.get();
x->backingStore = nullptr;
x->sharedPainter = nullptr;
@@ -1596,10 +1613,9 @@ void QWidgetPrivate::createTLExtra()
x->opacity = 255;
x->posIncludesFrame = 0;
x->sizeAdjusted = false;
- x->inTopLevelResize = false;
x->embedded = 0;
x->window = nullptr;
- x->initialScreenIndex = -1;
+ x->initialScreen = nullptr;
#ifdef QWIDGET_EXTRA_DEBUG
static int count = 0;
@@ -1616,7 +1632,7 @@ void QWidgetPrivate::createTLExtra()
void QWidgetPrivate::createExtra()
{
if (!extra) { // if not exists
- extra = qt_make_unique<QWExtra>();
+ extra = std::make_unique<QWExtra>();
extra->glContext = nullptr;
#if QT_CONFIG(graphicsview)
extra->proxyWidget = nullptr;
@@ -1660,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();
}
@@ -1673,37 +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);
-#ifndef QT_NO_OPENGL
- extra->topextra->widgetTextures.clear();
- extra->topextra->shareContext.reset();
-#endif
-
- //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;
-
}
}
@@ -1844,13 +1833,15 @@ void QWidgetPrivate::propagatePaletteChange()
#if QT_CONFIG(graphicsview)
if (!q->parentWidget() && extra && extra->proxyWidget) {
QGraphicsProxyWidget *p = extra->proxyWidget;
- inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
+ inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolveMask();
} else
#endif // QT_CONFIG(graphicsview)
if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
inheritedPaletteResolveMask = 0;
}
- QPalette::ResolveMask mask = data.pal.resolve() | inheritedPaletteResolveMask;
+
+ directPaletteResolveMask = data.pal.resolveMask();
+ auto mask = directPaletteResolveMask | inheritedPaletteResolveMask;
const bool useStyleSheetPropagationInWidgetStyles =
QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
@@ -1919,8 +1910,8 @@ QRegion QWidgetPrivate::clipRegion() const
while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
;
for ( ; i < w->d_func()->children.size(); ++i) {
- if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
- if(sibling->isVisible() && !sibling->isWindow()) {
+ if (QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
+ if (sibling->isVisible() && !sibling->isWindow()) {
QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
sibling->width(), sibling->height());
if (qRectIntersects(siblingRect, q->rect()))
@@ -2203,10 +2194,28 @@ void QWidgetPrivate::updateIsTranslucent()
if (QWindow *window = q->windowHandle()) {
QSurfaceFormat format = window->format();
const int oldAlpha = format.alphaBufferSize();
- const int newAlpha = q->testAttribute(Qt::WA_TranslucentBackground)? 8 : 0;
+ const int newAlpha = q->testAttribute(Qt::WA_TranslucentBackground) ? 8 : -1;
if (oldAlpha != newAlpha) {
- format.setAlphaBufferSize(newAlpha);
- window->setFormat(format);
+ // QTBUG-85714: Do this only when the QWindow has not yet been create()'ed yet.
+ //
+ // If that is not the case, then the setFormat() is not just futile
+ // but downright dangerous. Futile because the format matters only
+ // when creating the native window, no point in changing it
+ // afterwards. Dangerous because a QOpenGLContext or something else
+ // may eventually query the QWindow's format(), in order to ensure
+ // compatibility (in terms of native concepts such as pixel format,
+ // EGLConfig, etc.), and if we change it here, then the returned
+ // format does not describe reality anymore. (reality being the
+ // settings with which the native resource was created).
+ //
+ // Whereas if one does a destroy()-create() then this all here
+ // won't matter because the format is updated in
+ // QWidgetPrivate::create() again.
+ //
+ if (!window->handle()) {
+ format.setAlphaBufferSize(newAlpha);
+ window->setFormat(format);
+ }
}
}
}
@@ -2299,7 +2308,7 @@ void QWidgetPrivate::deactivateWidgetCleanup()
Q_Q(QWidget);
// If this was the active application window, reset it
if (QApplication::activeWindow() == q)
- QApplication::setActiveWindow(nullptr);
+ QApplicationPrivate::setActiveWindow(nullptr);
// If the is the active mouse press widget, reset it
if (q == qt_button_down)
qt_button_down = nullptr;
@@ -2307,7 +2316,7 @@ void QWidgetPrivate::deactivateWidgetCleanup()
/*!
- Returns a pointer to the widget with window identifer/handle \a
+ Returns a pointer to the widget with window identifier/handle \a
id.
The window identifier type depends on the underlying window
@@ -2347,10 +2356,9 @@ QWidget *QWidget::find(WId id)
*/
WId QWidget::winId() const
{
- if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidget::winId: creating native window for" << this;
-#endif
+ if (!data->in_destructor
+ && (!testAttribute(Qt::WA_WState_Created) || !internalWinId()))
+ {
QWidget *that = const_cast<QWidget*>(this);
that->setAttribute(Qt::WA_NativeWindow);
that->d_func()->createWinId();
@@ -2363,9 +2371,6 @@ void QWidgetPrivate::createWinId()
{
Q_Q(QWidget);
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidgetPrivate::createWinId for" << q;
-#endif
const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
if (!q->isWindow()) {
@@ -2419,8 +2424,7 @@ bool QWidgetPrivate::setScreen(QScreen *screen)
return false;
const QScreen *currentScreen = windowHandle() ? windowHandle()->screen() : nullptr;
if (currentScreen != screen) {
- if (!windowHandle()) // Try to create a window handle if not created.
- createWinId();
+ topData()->initialScreen = screen;
if (windowHandle())
windowHandle()->setScreen(screen);
return true;
@@ -2437,10 +2441,6 @@ Ensures that the widget has a window system identifier, i.e. that it is known to
void QWidget::createWinId()
{
Q_D(QWidget);
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidget::createWinId" << this;
-#endif
-// qWarning("QWidget::createWinId is obsolete, please fix your code.");
d->createWinId();
}
@@ -2500,8 +2500,8 @@ QScreen *QWidget::screen() const
return associatedScreen;
if (auto topLevel = window()) {
if (auto topData = qt_widget_private(topLevel)->topData()) {
- if (auto initialScreen = QGuiApplicationPrivate::screen_list.value(topData->initialScreenIndex))
- return initialScreen;
+ if (topData->initialScreen)
+ return topData->initialScreen;
}
if (auto screenByPos = QGuiApplication::screenAt(topLevel->geometry().center()))
return screenByPos;
@@ -2509,6 +2509,24 @@ QScreen *QWidget::screen() const
return QGuiApplication::primaryScreen();
}
+/*!
+ Sets the screen on which the widget should be shown to \a screen.
+
+ Setting the screen only makes sense for windows. If necessary, the widget's
+ window will get recreated on \a screen.
+
+ \note If the screen is part of a virtual desktop of multiple screens,
+ the window will not move automatically to \a screen. To place the
+ window relative to the screen, use the screen's topLeft() position.
+
+ \sa QWindow::setScreen()
+*/
+void QWidget::setScreen(QScreen *screen)
+{
+ Q_D(QWidget);
+ d->setScreen(screen);
+}
+
#ifndef QT_NO_STYLE_STYLESHEET
/*!
@@ -2552,7 +2570,16 @@ void QWidget::setStyleSheet(const QString& styleSheet)
}
if (proxy) { // style sheet update
- if (d->polished)
+ bool repolish = d->polished;
+ if (!repolish) {
+ const auto childWidgets = findChildren<QWidget*>();
+ for (auto child : childWidgets) {
+ repolish = child->d_func()->polished;
+ if (repolish)
+ break;
+ }
+ }
+ if (repolish)
proxy->repolish(this);
return;
}
@@ -2608,7 +2635,7 @@ void QWidget::setStyle(QStyle *style)
#ifndef QT_NO_STYLE_STYLESHEET
if (QStyleSheetStyle *styleSheetStyle = qt_styleSheet(style)) {
//if for some reason someone try to set a QStyleSheetStyle, ref it
- //(this may happen for exemple in QButtonDialogBox which propagates its style)
+ //(this may happen for example in QButtonDialogBox which propagates its style)
styleSheetStyle->ref();
d->setStyle_helper(style, false);
} else if (qt_styleSheet(d->extra->style) || !qApp->styleSheet().isEmpty()) {
@@ -2891,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
@@ -2960,14 +2987,14 @@ bool QWidget::isFullScreen() const
Calling this function only affects \l{isWindow()}{windows}.
- To return from full-screen mode, call showNormal().
+ To return from full-screen mode, call showNormal() or close().
- Full-screen mode works fine under Windows, but has certain
+ \note Full-screen mode works fine under Windows, but has certain
problems under X. These problems are due to limitations of the
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
@@ -2975,14 +3002,21 @@ 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.
X11 window managers that follow modern post-ICCCM specifications
support full-screen mode properly.
- \sa showNormal(), showMaximized(), show(), hide(), isVisible()
+ On macOS, showing a window full screen puts the entire application in
+ full-screen mode, providing it with a dedicated desktop. Showing another
+ window while the application runs in full-screen mode might automatically
+ make that window full screen as well. To prevent that, exit full-screen
+ mode by calling showNormal() or by close() on the full screen window
+ before showing another window.
+
+ \sa showNormal(), showMaximized(), show(), isVisible(), close()
*/
void QWidget::showFullScreen()
{
@@ -3068,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.
@@ -3090,13 +3124,9 @@ void QWidget::addAction(QAction *action)
\sa removeAction(), QMenu, addAction()
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void QWidget::addActions(const QList<QAction *> &actions)
-#else
-void QWidget::addActions(QList<QAction*> actions)
-#endif
{
- for(int i = 0; i < actions.count(); i++)
+ for(int i = 0; i < actions.size(); i++)
insertAction(nullptr, actions.at(i));
}
@@ -3117,7 +3147,7 @@ void QWidget::insertAction(QAction *before, QAction *action)
}
Q_D(QWidget);
- if(d->actions.contains(action))
+ if (d->actions.contains(action))
removeAction(action);
int pos = d->actions.indexOf(before);
@@ -3128,7 +3158,7 @@ void QWidget::insertAction(QAction *before, QAction *action)
d->actions.insert(pos, action);
QActionPrivate *apriv = action->d_func();
- apriv->widgets.append(this);
+ apriv->associatedObjects.append(this);
QActionEvent e(QEvent::ActionAdded, action, before);
QCoreApplication::sendEvent(this, &e);
@@ -3143,13 +3173,9 @@ void QWidget::insertAction(QAction *before, QAction *action)
\sa removeAction(), QMenu, insertAction(), contextMenuPolicy
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void QWidget::insertActions(QAction *before, const QList<QAction*> &actions)
-#else
-void QWidget::insertActions(QAction *before, QList<QAction*> actions)
-#endif
{
- for(int i = 0; i < actions.count(); ++i)
+ for(int i = 0; i < actions.size(); ++i)
insertAction(before, actions.at(i));
}
@@ -3165,7 +3191,7 @@ void QWidget::removeAction(QAction *action)
Q_D(QWidget);
QActionPrivate *apriv = action->d_func();
- apriv->widgets.removeAll(this);
+ apriv->associatedObjects.removeAll(this);
if (d->actions.removeAll(action)) {
QActionEvent e(QEvent::ActionRemoved, action);
@@ -3183,14 +3209,130 @@ QList<QAction*> QWidget::actions() const
Q_D(const QWidget);
return d->actions;
}
-#endif // QT_NO_ACTION
/*!
- \fn bool QWidget::isEnabledToTLW() const
- \obsolete
+ \fn QAction *QWidget::addAction(const QString &text);
+ \fn QAction *QWidget::addAction(const QString &text, const QKeySequence &shortcut);
+ \fn QAction *QWidget::addAction(const QIcon &icon, const QString &text);
+ \fn QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut);
+
+ \since 6.3
+
+ These convenience functions create a new action with text \a text,
+ icon \a icon and shortcut \a shortcut, if any.
+
+ The functions add the newly created action to the widget's
+ list of actions, and return it.
+
+ QWidget takes ownership of the returned QAction.
+*/
+QAction *QWidget::addAction(const QString &text)
+{
+ QAction *ret = new QAction(text, this);
+ addAction(ret);
+ return ret;
+}
+
+QAction *QWidget::addAction(const QIcon &icon, const QString &text)
+{
+ QAction *ret = new QAction(icon, text, this);
+ addAction(ret);
+ return ret;
+}
+
+#if QT_CONFIG(shortcut)
+QAction *QWidget::addAction(const QString &text, const QKeySequence &shortcut)
+{
+ QAction *ret = addAction(text);
+ ret->setShortcut(shortcut);
+ return ret;
+}
+
+QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut)
+{
+ QAction *ret = addAction(icon, text);
+ ret->setShortcut(shortcut);
+ return ret;
+}
+#endif
+
+/*!
+ \fn QAction *QWidget::addAction(const QString &text, const QObject *receiver, const char* member, Qt::ConnectionType type)
+ \fn QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char* member, Qt::ConnectionType type)
+ \fn QAction *QWidget::addAction(const QString &text, const QKeySequence &shortcut, const QObject *receiver, const char* member, Qt::ConnectionType type)
+ \fn QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut, const QObject *receiver, const char* member, Qt::ConnectionType type)
+
+ \overload
+ \since 6.3
+
+ This convenience function creates a new action with the text \a
+ text, icon \a icon, and shortcut \a shortcut, if any.
+
+ The action's \l{QAction::triggered()}{triggered()} signal is connected
+ to the \a receiver's \a member slot. The function adds the newly created
+ action to the widget's list of actions and returns it.
- This function is deprecated. It is equivalent to isEnabled()
+ QWidget takes ownership of the returned QAction.
*/
+QAction *QWidget::addAction(const QString &text, const QObject *receiver, const char* member,
+ Qt::ConnectionType type)
+{
+ QAction *action = addAction(text);
+ QObject::connect(action, SIGNAL(triggered(bool)), receiver, member, type);
+ return action;
+}
+
+QAction *QWidget::addAction(const QIcon &icon, const QString &text,
+ const QObject *receiver, const char* member,
+ Qt::ConnectionType type)
+{
+ QAction *action = addAction(icon, text);
+ QObject::connect(action, SIGNAL(triggered(bool)), receiver, member, type);
+ return action;
+}
+
+#if QT_CONFIG(shortcut)
+QAction *QWidget::addAction(const QString &text, const QKeySequence &shortcut,
+ const QObject *receiver, const char* member,
+ Qt::ConnectionType type)
+{
+ QAction *action = addAction(text, receiver, member, type);
+ action->setShortcut(shortcut);
+ return action;
+}
+
+QAction *QWidget::addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut,
+ const QObject *receiver, const char* member,
+ Qt::ConnectionType type)
+{
+ QAction *action = addAction(icon, text, receiver, member, type);
+ action->setShortcut(shortcut);
+ return action;
+}
+#endif // QT_CONFIG(shortcut)
+
+/*!
+ \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
+
+ These convenience functions create a new action with the text \a text,
+ icon \a icon, and shortcut \a shortcut, if any.
+
+ The action's \l{QAction::triggered()}{triggered()} signal is connected
+ as if by a call to QObject::connect(action, &QAction::triggered, args...),
+ perfectly forwarding \a args, including a possible Qt::ConnectionType.
+
+ The function adds the newly created action to the widget's list of
+ actions and returns it.
+
+ QWidget takes ownership of the returned QAction.
+*/
+#endif // QT_NO_ACTION
/*!
\property QWidget::enabled
@@ -3284,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
{
@@ -3398,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
@@ -3437,19 +3583,6 @@ QPoint QWidget::pos() const
*/
/*!
- \property QWidget::normalGeometry
-
- \brief the geometry of the widget as it will appear when shown as
- a normal (not maximized or full screen) top-level widget
-
- For child widgets this property always holds an empty rectangle.
-
- By default, this property contains an empty rectangle.
-
- \sa QWidget::windowState(), QWidget::geometry
-*/
-
-/*!
\property QWidget::size
\brief the size of the widget excluding any window frame
@@ -3480,8 +3613,7 @@ QPoint QWidget::pos() const
issues with windows.
\note Do not use this function to find the width of a screen on
- a \l{QDesktopWidget}{multiple screen desktop}. Read
- \l{QDesktopWidget#Screen Geometry}{this note} for details.
+ a multi-screen desktop. See QScreen for details.
By default, this property contains a value that depends on the user's
platform and screen geometry.
@@ -3496,12 +3628,8 @@ QPoint QWidget::pos() const
See the \l{Window Geometry} documentation for an overview of geometry
issues with windows.
- \note Do not use this function to find the height of a screen
- on a \l{QDesktopWidget}{multiple screen desktop}. Read
- \l{QDesktopWidget#Screen Geometry}{this note} for details.
-
By default, this property contains a value that depends on the user's
- platform and screen geometry.
+ platform and \l{QScreen::geometry}{screen geometry}.
\sa geometry, width, size
*/
@@ -3522,11 +3650,25 @@ QPoint QWidget::pos() const
\sa size
*/
+/*!
+ \property QWidget::normalGeometry
+
+ \brief the geometry of the widget as it will appear when shown as
+ a normal (not maximized or full screen) top-level widget
+
+ If the widget is already in this state the normal geometry will
+ reflect the widget's current geometry().
+ For child widgets this property always holds an empty rectangle.
+
+ By default, this property contains an empty rectangle.
+
+ \sa QWidget::windowState(), QWidget::geometry
+*/
QRect QWidget::normalGeometry() const
{
Q_D(const QWidget);
- if (!d->extra || !d->extra->topextra)
+ if (!isWindow())
return QRect();
if (!isMaximized() && !isFullScreen())
@@ -3599,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.
@@ -4049,15 +4191,16 @@ void QWidget::setFixedHeight(int h)
of the calling widget.
\sa mapFrom(), mapToParent(), mapToGlobal(), underMouse()
+ \since 6.0
*/
-QPoint QWidget::mapTo(const QWidget * parent, const QPoint & pos) const
+QPointF QWidget::mapTo(const QWidget *parent, const QPointF &pos) const
{
- QPoint p = pos;
+ QPointF p = pos;
if (parent) {
const QWidget * w = this;
while (w != parent) {
- Q_ASSERT_X(w, "QWidget::mapTo(const QWidget *parent, const QPoint &pos)",
+ Q_ASSERT_X(w, "QWidget::mapTo(const QWidget *parent, const QPointF &pos)",
"parent must be in parent hierarchy");
p = w->mapToParent(p);
w = w->parentWidget();
@@ -4066,6 +4209,13 @@ QPoint QWidget::mapTo(const QWidget * parent, const QPoint & pos) const
return p;
}
+/*!
+ \overload
+*/
+QPoint QWidget::mapTo(const QWidget *parent, const QPoint &pos) const
+{
+ return mapTo(parent, QPointF(pos)).toPoint();
+}
/*!
Translates the widget coordinate \a pos from the coordinate system
@@ -4073,11 +4223,12 @@ QPoint QWidget::mapTo(const QWidget * parent, const QPoint & pos) const
must not be \nullptr and must be a parent of the calling widget.
\sa mapTo(), mapFromParent(), mapFromGlobal(), underMouse()
+ \since 6.0
*/
-QPoint QWidget::mapFrom(const QWidget * parent, const QPoint & pos) const
+QPointF QWidget::mapFrom(const QWidget *parent, const QPointF &pos) const
{
- QPoint p(pos);
+ QPointF p(pos);
if (parent) {
const QWidget * w = this;
while (w != parent) {
@@ -4091,6 +4242,13 @@ QPoint QWidget::mapFrom(const QWidget * parent, const QPoint & pos) const
return p;
}
+/*!
+ \overload
+*/
+QPoint QWidget::mapFrom(const QWidget *parent, const QPoint &pos) const
+{
+ return mapFrom(parent, QPointF(pos)).toPoint();
+}
/*!
Translates the widget coordinate \a pos to a coordinate in the
@@ -4099,8 +4257,17 @@ QPoint QWidget::mapFrom(const QWidget * parent, const QPoint & pos) const
Same as mapToGlobal() if the widget has no parent.
\sa mapFromParent(), mapTo(), mapToGlobal(), underMouse()
+ \since 6.0
*/
+QPointF QWidget::mapToParent(const QPointF &pos) const
+{
+ return pos + QPointF(data->crect.topLeft());
+}
+
+/*!
+ \overload
+*/
QPoint QWidget::mapToParent(const QPoint &pos) const
{
return pos + data->crect.topLeft();
@@ -4113,8 +4280,17 @@ QPoint QWidget::mapToParent(const QPoint &pos) const
Same as mapFromGlobal() if the widget has no parent.
\sa mapToParent(), mapFrom(), mapFromGlobal(), underMouse()
+ \since 6.0
*/
+QPointF QWidget::mapFromParent(const QPointF &pos) const
+{
+ return pos - QPointF(data->crect.topLeft());
+}
+
+/*!
+ \overload
+*/
QPoint QWidget::mapFromParent(const QPoint &pos) const
{
return pos - data->crect.topLeft();
@@ -4163,7 +4339,7 @@ QWidget *QWidget::nativeParentWidget() const
}
/*! \fn QWidget *QWidget::topLevelWidget() const
- \obsolete
+ \deprecated
Use window() instead.
*/
@@ -4176,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()
@@ -4320,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,
@@ -4340,7 +4516,7 @@ const QPalette &QWidget::palette() const
if (!isEnabled()) {
data->pal.setCurrentColorGroup(QPalette::Disabled);
} else if ((!isVisible() || isActiveWindow())
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+#if defined(Q_OS_WIN)
&& !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
#endif
) {
@@ -4354,7 +4530,7 @@ const QPalette &QWidget::palette() const
void QWidget::setPalette(const QPalette &palette)
{
Q_D(QWidget);
- setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
+ setAttribute(Qt::WA_SetPalette, palette.resolveMask() != 0);
// Determine which palette is inherited from this widget's ancestors and
// QApplication::palette, resolve this against \a palette (attributes from
@@ -4392,7 +4568,7 @@ QPalette QWidgetPrivate::naturalWidgetPalette(QPalette::ResolveMask inheritedMas
if (!p->testAttribute(Qt::WA_StyleSheet) || useStyleSheetPropagationInWidgetStyles) {
if (!naturalPalette.isCopyOf(QGuiApplication::palette())) {
QPalette inheritedPalette = p->palette();
- inheritedPalette.resolve(inheritedMask);
+ inheritedPalette.setResolveMask(inheritedMask);
naturalPalette = inheritedPalette.resolve(naturalPalette);
} else {
naturalPalette = p->palette();
@@ -4402,12 +4578,12 @@ QPalette QWidgetPrivate::naturalWidgetPalette(QPalette::ResolveMask inheritedMas
#if QT_CONFIG(graphicsview)
else if (extra && extra->proxyWidget) {
QPalette inheritedPalette = extra->proxyWidget->palette();
- inheritedPalette.resolve(inheritedMask);
+ inheritedPalette.setResolveMask(inheritedMask);
naturalPalette = inheritedPalette.resolve(naturalPalette);
}
#endif // QT_CONFIG(graphicsview)
}
- naturalPalette.resolve(0);
+ naturalPalette.setResolveMask(0);
return naturalPalette;
}
/*!
@@ -4428,7 +4604,7 @@ void QWidgetPrivate::resolvePalette()
void QWidgetPrivate::setPalette_helper(const QPalette &palette)
{
Q_Q(QWidget);
- if (data.pal == palette && data.pal.resolve() == palette.resolve())
+ if (data.pal == palette && data.pal.resolveMask() == palette.resolveMask())
return;
data.pal = palette;
updateSystemBackground();
@@ -4498,7 +4674,7 @@ void QWidget::setFont(const QFont &font)
style->saveWidgetFont(this, font);
#endif
- setAttribute(Qt::WA_SetFont, font.resolve() != 0);
+ setAttribute(Qt::WA_SetFont, font.resolveMask() != 0);
// Determine which font is inherited from this widget's ancestors and
// QApplication::font, resolve this against \a font (attributes from the
@@ -4540,7 +4716,7 @@ QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
if (!naturalFont.isCopyOf(QApplication::font())) {
if (inheritedMask != 0) {
QFont inheritedFont = p->font();
- inheritedFont.resolve(inheritedMask);
+ inheritedFont.setResolveMask(inheritedMask);
naturalFont = inheritedFont.resolve(naturalFont);
} // else nothing to do (naturalFont = naturalFont)
} else {
@@ -4552,13 +4728,13 @@ QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
else if (extra && extra->proxyWidget) {
if (inheritedMask != 0) {
QFont inheritedFont = extra->proxyWidget->font();
- inheritedFont.resolve(inheritedMask);
+ inheritedFont.setResolveMask(inheritedMask);
naturalFont = inheritedFont.resolve(naturalFont);
} // else nothing to do (naturalFont = naturalFont)
}
#endif // QT_CONFIG(graphicsview)
}
- naturalFont.resolve(0);
+ naturalFont.setResolveMask(0);
return naturalFont;
}
@@ -4570,7 +4746,7 @@ QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
QFont QWidgetPrivate::localFont() const
{
QFont localfont = data.fnt;
- localfont.resolve(directFontResolveMask);
+ localfont.setResolveMask(directFontResolveMask);
return localfont;
}
@@ -4614,18 +4790,18 @@ void QWidgetPrivate::updateFont(const QFont &font)
#if QT_CONFIG(graphicsview)
if (!q->parentWidget() && extra && extra->proxyWidget) {
QGraphicsProxyWidget *p = extra->proxyWidget;
- inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
+ inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolveMask();
} else
#endif // QT_CONFIG(graphicsview)
if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
inheritedFontResolveMask = 0;
}
- uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
+ uint newMask = data.fnt.resolveMask() | inheritedFontResolveMask;
// Set the font as also having resolved inherited traits, so the result of reading QWidget::font()
// isn't all weak information, but save the original mask to be able to let new changes on the
// parent widget font propagate correctly.
- directFontResolveMask = data.fnt.resolve();
- data.fnt.resolve(newMask);
+ directFontResolveMask = data.fnt.resolveMask();
+ data.fnt.setResolveMask(newMask);
for (int i = 0; i < children.size(); ++i) {
QWidget *w = qobject_cast<QWidget*>(children.at(i));
@@ -4684,7 +4860,9 @@ void QWidgetPrivate::resolveLayoutDirection()
/*!
\property QWidget::layoutDirection
- \brief the layout direction for this widget
+ \brief the layout direction for this widget.
+
+ \note This method no longer affects text layout direction since Qt 4.7.
By default, this property is set to Qt::LeftToRight.
@@ -4695,7 +4873,6 @@ void QWidgetPrivate::resolveLayoutDirection()
has been called for the parent do not inherit the parent's layout
direction.
- This method no longer affects text layout direction since Qt 4.7.
\sa QApplication::layoutDirection
*/
@@ -4787,7 +4964,7 @@ void QWidget::setCursor(const QCursor &cursor)
|| (d->extra && d->extra->curs))
{
d->createExtra();
- d->extra->curs = qt_make_unique<QCursor>(cursor);
+ d->extra->curs = std::make_unique<QCursor>(cursor);
}
setAttribute(Qt::WA_SetCursor);
d->setCursor_sys(cursor);
@@ -4911,9 +5088,6 @@ void qt_qpa_set_cursor(QWidget *w, bool force)
\note To obtain the contents of a QOpenGLWidget, use QOpenGLWidget::grabFramebuffer()
instead.
-
- \note To obtain the contents of a QGLWidget (deprecated), use
- QGLWidget::grabFrameBuffer() or QGLWidget::renderPixmap() instead.
*/
void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
const QRegion &sourceRegion, RenderFlags renderFlags)
@@ -5055,7 +5229,7 @@ QPixmap QWidget::grab(const QRect &rectangle)
if (!r.intersects(rect()))
return QPixmap();
- const qreal dpr = devicePixelRatioF();
+ const qreal dpr = devicePixelRatio();
QPixmap res((QSizeF(r.size()) * dpr).toSize());
res.setDevicePixelRatio(dpr);
if (!d->isOpaque)
@@ -5220,7 +5394,7 @@ void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset
if (size.isNull())
return;
- const qreal pixmapDevicePixelRatio = painter->device()->devicePixelRatioF();
+ const qreal pixmapDevicePixelRatio = painter->device()->devicePixelRatio();
QPixmap pixmap(size * pixmapDevicePixelRatio);
pixmap.setDevicePixelRatio(pixmapDevicePixelRatio);
@@ -5288,10 +5462,11 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
(source->d_func());
if (!sourced->context) {
- QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, repaintManager);
+ const QRegion effectRgn((flags & UseEffectRegionBounds) ? rgn.boundingRect() : rgn);
+ QWidgetPaintContext context(pdev, effectRgn, offset, flags, sharedPainter, repaintManager);
sourced->context = &context;
if (!sharedPainter) {
- setSystemClip(pdev->paintEngine(), pdev->devicePixelRatioF(), rgn.translated(offset));
+ setSystemClip(pdev->paintEngine(), pdev->devicePixelRatio(), effectRgn.translated(offset));
QPainter p(pdev);
p.translate(offset);
context.painter = &p;
@@ -5305,7 +5480,7 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
}
sharedPainter->save();
sharedPainter->translate(offset);
- setSystemClip(sharedPainter->paintEngine(), sharedPainter->device()->devicePixelRatioF(), rgn.translated(offset));
+ setSystemClip(sharedPainter->paintEngine(), sharedPainter->device()->devicePixelRatio(), effectRgn.translated(offset));
graphicsEffect->draw(sharedPainter);
setSystemClip(sharedPainter->paintEngine(), 1, QRegion());
sharedPainter->restore();
@@ -5313,12 +5488,13 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
sourced->context = nullptr;
if (repaintManager)
- repaintManager->markNeedsFlush(q, rgn, offset);
+ repaintManager->markNeedsFlush(q, effectRgn, offset);
return;
}
}
#endif // QT_CONFIG(graphicseffect)
+ flags = flags & ~UseEffectRegionBounds;
const bool alsoOnScreen = flags & DrawPaintOnScreen;
const bool recursive = flags & DrawRecursive;
@@ -5345,37 +5521,30 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
setRedirected(pdev, -offset);
if (sharedPainter)
- setSystemClip(pdev->paintEngine(), pdev->devicePixelRatioF(), toBePainted);
+ setSystemClip(pdev->paintEngine(), pdev->devicePixelRatio(), toBePainted);
else
paintEngine->d_func()->systemRect = q->data->crect;
//paint the background
if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
&& !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
-#ifndef QT_NO_OPENGL
beginBackingStorePainting();
-#endif
QPainter p(q);
+ p.setRenderHint(QPainter::SmoothPixmapTransform);
paintBackground(&p, toBePainted, (asRoot || onScreen) ? (flags | DrawAsRoot) : DrawWidgetFlags());
-#ifndef QT_NO_OPENGL
endBackingStorePainting();
-#endif
}
if (!sharedPainter)
- setSystemClip(pdev->paintEngine(), pdev->devicePixelRatioF(), toBePainted.translated(offset));
+ setSystemClip(pdev->paintEngine(), pdev->devicePixelRatio(), toBePainted.translated(offset));
if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
-#ifndef QT_NO_OPENGL
beginBackingStorePainting();
-#endif
QPainter p(q);
QColor tint = q->palette().window().color();
- tint.setAlphaF(qreal(.6));
+ tint.setAlphaF(.6f);
p.fillRect(toBePainted.boundingRect(), tint);
-#ifndef QT_NO_OPENGL
endBackingStorePainting();
-#endif
}
}
@@ -5386,7 +5555,6 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
#endif
bool skipPaintEvent = false;
-#ifndef QT_NO_OPENGL
if (renderToTexture) {
// This widget renders into a texture which is composed later. We just need to
// punch a hole in the backingstore, so the texture will be visible.
@@ -5412,7 +5580,6 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
else
skipPaintEvent = true;
}
-#endif // QT_NO_OPENGL
if (!skipPaintEvent) {
//actually send the paint event
@@ -5468,10 +5635,8 @@ void QWidgetPrivate::sendPaintEvent(const QRegion &toBePainted)
QPaintEvent e(toBePainted);
QCoreApplication::sendSpontaneousEvent(q, &e);
-#ifndef QT_NO_OPENGL
if (renderToTexture)
resolveSamples();
-#endif // QT_NO_OPENGL
}
void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
@@ -5670,7 +5835,7 @@ QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *
qreal dpr(1.0);
if (const auto *paintDevice = context->painter->device())
- dpr = paintDevice->devicePixelRatioF();
+ dpr = paintDevice->devicePixelRatio();
else
qWarning("QWidgetEffectSourcePrivate::pixmap: Painter not active");
QPixmap pixmap(effectRect.size() * dpr);
@@ -5805,7 +5970,7 @@ QString QWidget::windowTitle() const
if (!d->extra->topextra->caption.isEmpty())
return d->extra->topextra->caption;
if (!d->extra->topextra->filePath.isEmpty())
- return QFileInfo(d->extra->topextra->filePath).fileName() + QLatin1String("[*]");
+ return QFileInfo(d->extra->topextra->filePath).fileName() + "[*]"_L1;
}
return QString();
}
@@ -5829,7 +5994,7 @@ QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widg
if (cap.isEmpty())
return cap;
- QLatin1String placeHolder("[*]");
+ const auto placeHolder = "[*]"_L1;
int index = cap.indexOf(placeHolder);
// here the magic begins
@@ -5853,7 +6018,7 @@ QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widg
index = cap.indexOf(placeHolder, index);
}
- cap.replace(QLatin1String("[*][*]"), placeHolder);
+ cap.replace("[*][*]"_L1, placeHolder);
return cap;
}
@@ -5885,11 +6050,17 @@ void QWidgetPrivate::setWindowIconText_helper(const QString &title)
void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
{
+#if QT_CONFIG(xcb)
Q_Q(QWidget);
// ### The QWidget property is deprecated, but the XCB window function is not.
// It should remain available for the rare application that needs it.
- if (QWindow *window = q->windowHandle())
- QXcbWindowFunctions::setWmWindowIconText(window, iconText);
+ if (QWindow *window = q->windowHandle()) {
+ if (auto *xcbWindow = dynamic_cast<QXcbWindow*>(window->handle()))
+ xcbWindow->setWindowIconText(iconText);
+ }
+#else
+ Q_UNUSED(iconText);
+#endif
}
/*!
@@ -5899,7 +6070,7 @@ void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
new \a iconText as an argument.
\since 5.2
- \obsolete
+ \deprecated
This signal is deprecated.
*/
@@ -5954,9 +6125,9 @@ void QWidget::setWindowTitle(const QString &title)
\note On \macos, window icons represent the active document,
and will not be displayed unless a file path has also been
- set using setFilePath.
+ set using setWindowFilePath.
- \sa windowTitle, setFilePath
+ \sa windowTitle, setWindowFilePath
*/
QIcon QWidget::windowIcon() const
{
@@ -6005,7 +6176,7 @@ void QWidget::setWindowIcon(const QIcon &icon)
d->createTLExtra();
if (!d->extra->topextra->icon)
- d->extra->topextra->icon = qt_make_unique<QIcon>(icon);
+ d->extra->topextra->icon = std::make_unique<QIcon>(icon);
else
*d->extra->topextra->icon = icon;
@@ -6031,7 +6202,7 @@ void QWidgetPrivate::setWindowIcon_sys()
It is only implemented on the X11 platform, and only certain
window managers use this window property.
- \obsolete
+ \deprecated
This property is deprecated.
\sa windowIcon, windowTitle
@@ -6129,11 +6300,17 @@ QString QWidget::windowRole() const
*/
void QWidget::setWindowRole(const QString &role)
{
+#if QT_CONFIG(xcb)
Q_D(QWidget);
d->createTLExtra();
d->topData()->role = role;
- if (windowHandle())
- QXcbWindowFunctions::setWmWindowRole(windowHandle(), role.toLatin1());
+ if (windowHandle()) {
+ if (auto *xcbWindow = dynamic_cast<QXcbWindow*>(windowHandle()->handle()))
+ xcbWindow->setWindowRole(role);
+ }
+#else
+ Q_UNUSED(role);
+#endif
}
/*!
@@ -6179,7 +6356,8 @@ void QWidget::setWindowRole(const QString &role)
setFocusProxy() sets the widget which will actually get focus when
"this widget" gets it. If there is a focus proxy, setFocus() and
- hasFocus() operate on the focus proxy.
+ hasFocus() operate on the focus proxy. If "this widget" is the focus
+ widget, then setFocusProxy() moves focus to the new focus proxy.
\sa focusProxy()
*/
@@ -6197,18 +6375,43 @@ void QWidget::setFocusProxy(QWidget * w)
}
}
- QWidget *oldDeepestFocusProxy = d_func()->deepestFocusProxy();
- if (!oldDeepestFocusProxy)
- oldDeepestFocusProxy = this;
- const bool changingAppFocusWidget = (QApplicationPrivate::focus_widget == oldDeepestFocusProxy);
+ const bool moveFocusToProxy = (QApplicationPrivate::focus_widget == this);
d->createExtra();
d->extra->focus_proxy = w;
- if (changingAppFocusWidget) {
- QWidget *newDeepestFocusProxy = d_func()->deepestFocusProxy();
- QApplicationPrivate::setFocusWidget(newDeepestFocusProxy ? newDeepestFocusProxy : this, Qt::NoFocusReason);
+ if (w && isAncestorOf(w)) {
+ // If the focus proxy is a child of this (so this is a compound widget), then
+ // we need to make sure that this widget is immediately in front of its own children
+ // in the focus chain. Otherwise focusNextPrev_helper might jump over unrelated
+ // widgets that are positioned between this compound widget, and its proxy in
+ // the focus chain.
+ const QWidget *parentOfW = w->parentWidget();
+ Q_ASSERT(parentOfW); // can't be nullptr since we are an ancestor of w
+ QWidget *firstChild = nullptr;
+ const auto childList = children();
+ for (QObject *child : childList) {
+ if ((firstChild = qobject_cast<QWidget *>(child)))
+ break;
+ }
+ Q_ASSERT(firstChild); // can't be nullptr since w is a child
+ 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)
+ setFocus(Qt::OtherFocusReason);
}
@@ -6306,7 +6509,7 @@ void QWidget::setFocus(Qt::FocusReason reason)
previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
if (previousProxyFocus && previousProxyFocus->focusProxy())
previousProxyFocus = previousProxyFocus->focusProxy();
- if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
+ if (previousProxyFocus == f && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
return;
}
}
@@ -6341,12 +6544,7 @@ void QWidget::setFocus(Qt::FocusReason reason)
f->d_func()->updateFocusChild();
QApplicationPrivate::setFocusWidget(f, reason);
-#ifndef QT_NO_ACCESSIBILITY
-# ifdef Q_OS_WIN
- // The negation of the condition in setFocus_sys
- if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
- //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
-# endif
+#if QT_CONFIG(accessibility)
// menus update the focus manually and this would create bogus events
if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
{
@@ -6470,8 +6668,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()
@@ -6487,6 +6685,16 @@ void QWidget::clearFocus()
QCoreApplication::sendEvent(this, &focusAboutToChange);
}
+ QTLWExtra *extra = window()->d_func()->maybeTopData();
+ QObject *originalFocusObject = nullptr;
+ if (extra && extra->window) {
+ originalFocusObject = extra->window->focusObject();
+ // the window's focus object might already be nullptr if we are in the destructor, but we still
+ // need to update QGuiApplication and input context if we have a focus widget.
+ if (!originalFocusObject)
+ originalFocusObject = focusWidget();
+ }
+
QWidget *w = this;
while (w) {
// Just like setFocus(), we update (clear) the focus_child of our parents
@@ -6495,14 +6703,12 @@ void QWidget::clearFocus()
w = w->parentWidget();
}
- // Since we've unconditionally cleared the focus_child of our parents, we need
+ // We've potentially cleared the focus_child of our parents, so we need
// to report this to the rest of Qt. Note that the focus_child is not the same
// thing as the application's focusWidget, which is why this piece of code is
- // not inside the hasFocus() block below.
- if (QTLWExtra *extra = window()->d_func()->maybeTopData()) {
- if (extra->window)
- emit extra->window->focusObjectChanged(extra->window->focusObject());
- }
+ // not inside a hasFocus() block.
+ if (originalFocusObject && originalFocusObject != extra->window->focusObject())
+ emit extra->window->focusObjectChanged(extra->window->focusObject());
#if QT_CONFIG(graphicsview)
const auto &topData = d_func()->extra;
@@ -6513,7 +6719,7 @@ void QWidget::clearFocus()
if (hasFocus()) {
// Update proxy state
QApplicationPrivate::setFocusWidget(nullptr, Qt::OtherFocusReason);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleEvent event(this, QAccessible::Focus);
QAccessible::updateAccessibility(&event);
#endif
@@ -6619,6 +6825,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.
@@ -6626,7 +6839,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);
}
/*!
@@ -6639,7 +6853,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);
}
/*!
@@ -6660,7 +6875,7 @@ QWidget *QWidget::previousInFocusChain() const
bool QWidget::isActiveWindow() const
{
QWidget *tlw = window();
- if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
+ if (tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
return true;
#if QT_CONFIG(graphicsview)
@@ -6671,7 +6886,7 @@ bool QWidget::isActiveWindow() const
#endif
if (style()->styleHint(QStyle::SH_Widget_ShareActivation, nullptr, this)) {
- if(tlw->windowType() == Qt::Tool &&
+ if (tlw->windowType() == Qt::Tool &&
!tlw->isModal() &&
(!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
return true;
@@ -6679,7 +6894,7 @@ bool QWidget::isActiveWindow() const
while(w && tlw->windowType() == Qt::Tool &&
!w->isModal() && w->parentWidget()) {
w = w->parentWidget()->window();
- if(w == tlw)
+ if (w == tlw)
return true;
}
}
@@ -6709,6 +6924,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
@@ -6746,64 +6985,74 @@ 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))
- 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;
+ 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 : target->children()) {
+ QWidget *w = qobject_cast<QWidget*>(object);
+ if (w && w->focusProxy() == target) {
+ lastFocusChild = w;
+ break;
+ }
+ }
+ } 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
@@ -6822,94 +7071,11 @@ void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
if (oldtlw == q->window())
return; // nothing to do
- if(focus_child)
+ 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;
- }
-
-}
-
-/*!\internal
-
- Measures the shortest distance from a point to a rect.
-
- This function is called from QDesktopwidget::screen(QPoint) to find the
- closest screen for a point.
- In directional KeypadNavigation, it is called to find the closest
- widget to the current focus widget center.
-*/
-int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
-{
- int dx = 0;
- int dy = 0;
- if (p.x() < r.left())
- dx = r.left() - p.x();
- else if (p.x() > r.right())
- dx = p.x() - r.right();
- if (p.y() < r.top())
- dy = r.top() - p.y();
- else if (p.y() > r.bottom())
- dy = p.y() - r.bottom();
- return dx + dy;
+ insertIntoFocusChain(QWidgetPrivate::FocusDirection::Previous, q->window());
+ reparentFocusChildren(QWidgetPrivate::FocusDirection::Next);
}
/*!
@@ -7175,7 +7341,7 @@ QByteArray QWidget::saveGeometry() const
// - Qt 5.12 - today : Version 3.0, save QWidget::geometry()
quint16 majorVersion = 3;
quint16 minorVersion = 0;
- const int screenNumber = QDesktopWidgetPrivate::screenNumber(this);
+ const int screenNumber = QGuiApplication::screens().indexOf(screen());
stream << magicNumber
<< majorVersion
<< minorVersion
@@ -7184,20 +7350,72 @@ QByteArray QWidget::saveGeometry() const
<< qint32(screenNumber)
<< quint8(windowState() & Qt::WindowMaximized)
<< quint8(windowState() & Qt::WindowFullScreen)
- << qint32(QDesktopWidgetPrivate::screenGeometry(screenNumber).width()) // added in 2.0
+ << qint32(screen()->geometry().width()) // added in 2.0
<< geometry(); // added in 3.0
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));
}
/*!
@@ -7267,9 +7485,10 @@ bool QWidget::restoreGeometry(const QByteArray &geometry)
// ### Qt 6 - Perhaps it makes sense to dumb down the restoreGeometry() logic, see QTBUG-69104
- if (restoredScreenNumber >= QDesktopWidgetPrivate::numScreens())
- restoredScreenNumber = QDesktopWidgetPrivate::primaryScreen();
- const qreal screenWidthF = qreal(QDesktopWidgetPrivate::screenGeometry(restoredScreenNumber).width());
+ if (restoredScreenNumber >= qMax(QGuiApplication::screens().size(), 1))
+ restoredScreenNumber = 0;
+ const QScreen *restoredScreen = QGuiApplication::screens().value(restoredScreenNumber, nullptr);
+ const qreal screenWidthF = restoredScreen ? qreal(restoredScreen->geometry().width()) : 0;
// Sanity check bailing out when large variations of screen sizes occur due to
// high DPI scaling or different levels of DPI awareness.
if (restoredScreenWidth) {
@@ -7283,7 +7502,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());
@@ -7294,15 +7515,16 @@ bool QWidget::restoreGeometry(const QByteArray &geometry)
.expandedTo(d_func()->adjustedSize()));
}
- const QRect availableGeometry = QDesktopWidgetPrivate::availableGeometry(restoredScreenNumber);
+ const QRect availableGeometry = restoredScreen ? restoredScreen->availableGeometry()
+ : QRect();
// 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
@@ -7318,7 +7540,7 @@ bool QWidget::restoreGeometry(const QByteArray &geometry)
// Setting a geometry on an already maximized window causes this to be
// restored into a broken, half-maximized state, non-resizable state (QTBUG-4397).
// Move the window in normal state if needed.
- if (restoredScreenNumber != QDesktopWidgetPrivate::screenNumber(this)) {
+ if (restoredScreen != screen()) {
setWindowState(Qt::WindowNoState);
setGeometry(restoredNormalGeometry);
}
@@ -7334,6 +7556,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
@@ -7415,37 +7639,6 @@ void QWidgetPrivate::updateContentsRect()
QCoreApplication::sendEvent(q, &e);
}
-#if QT_DEPRECATED_SINCE(5, 14)
-/*!
- \obsolete
- Use contentsMargins().
-
- Returns the widget's contents margins for \a left, \a top, \a
- right, and \a bottom.
-
- \sa setContentsMargins(), contentsRect()
- */
-void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
-{
- QMargins m = contentsMargins();
- if (left)
- *left = m.left();
- if (top)
- *top = m.top();
- if (right)
- *right = m.right();
- if (bottom)
- *bottom = m.bottom();
-}
-#endif
-
-// FIXME: Move to qmargins.h for next minor Qt release
-QMargins operator|(const QMargins &m1, const QMargins &m2)
-{
- return QMargins(qMax(m1.left(), m2.left()), qMax(m1.top(), m2.top()),
- qMax(m1.right(), m2.right()), qMax(m1.bottom(), m2.bottom()));
-}
-
/*!
\since 4.6
@@ -7511,7 +7704,7 @@ QMargins QWidgetPrivate::safeAreaMargins() const
if (layout->geometry().isNull())
continue; // Layout hasn't been activated yet
- if (layout->indexOf(const_cast<QWidget *>(w)) < 0)
+ if (layout->indexOf(w) < 0)
continue; // Widget is not in layout
assumedSafeWidget = w;
@@ -7663,21 +7856,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
@@ -7828,7 +8029,7 @@ void QWidgetPrivate::show_helper()
if (!isEmbedded && q->windowType() == Qt::Popup)
qApp->d_func()->openPopup(q);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (q->windowType() != Qt::ToolTip) { // Tooltips are read aloud twice in MS narrator.
QAccessibleEvent event(q, QAccessible::ObjectShow);
QAccessible::updateAccessibility(&event);
@@ -7974,7 +8175,7 @@ void QWidgetPrivate::hide_helper()
if (QWidgetRepaintManager *repaintManager = maybeRepaintManager())
repaintManager->removeDirtyWidget(q);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (wasVisible) {
QAccessibleEvent event(q, QAccessible::ObjectHide);
QAccessible::updateAccessibility(&event);
@@ -8044,13 +8245,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);
}
@@ -8060,6 +8265,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()
@@ -8137,9 +8346,10 @@ void QWidgetPrivate::setVisible(bool visible)
if (!q->isWindow() && q->parentWidget()) // && !d->getOpaqueRegion().isEmpty())
q->parentWidget()->d_func()->setDirtyOpaqueRegion();
- q->setAttribute(Qt::WA_WState_Hidden);
- if (q->testAttribute(Qt::WA_WState_Created))
+ if (!q->testAttribute(Qt::WA_WState_Hidden)) {
+ q->setAttribute(Qt::WA_WState_Hidden);
hide_helper();
+ }
// invalidate layout similar to updateGeometry()
if (!q->isWindow() && q->parentWidget()) {
@@ -8162,23 +8372,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);
@@ -8189,17 +8411,25 @@ 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);
}
}
}
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)
@@ -8220,27 +8450,57 @@ void QWidgetPrivate::hideChildren(bool spontaneous)
}
}
qApp->d_func()->sendSyntheticEnterLeave(widget);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (!spontaneous) {
QAccessibleEvent event(widget, QAccessible::ObjectHide);
QAccessible::updateAccessibility(&event);
}
#endif
}
+
+ // If the window of this widget is not closed, then the leave event
+ // will eventually handle the widget under mouse use case.
+ // Otherwise, we need to explicitly handle it here.
+ if (QWidget* widgetWindow = q->window();
+ widgetWindow && widgetWindow->data->is_closing) {
+ q->setAttribute(Qt::WA_UnderMouse, false);
+ }
}
-bool QWidgetPrivate::close_helper(CloseMode mode)
+/*!
+ \internal
+
+ For windows, this is called from the QWidgetWindow::handleCloseEvent implementation,
+ which QWidget::close indirectly calls by closing the QWindow. \a mode will be
+ CloseWithEvent if QWidgetWindow::handleCloseEvent is called indirectly by
+ QWindow::close, and CloseWithSpontaneousEvent if the close event originates from the
+ system (i.e. the user clicked the close button in the title bar).
+
+ QDialog calls this method directly in its hide() implementation, which might be
+ called from the QDialog::closeEvent override. \a mode will be set to CloseNoEvent
+ to prevent recursion.
+
+ For non-windows, this is called directly by QWidget::close, and \a mode will be
+ CloseWithEvent.
+
+ The function is also called by the QWidget destructor, with \a mode set to CloseNoEvent.
+*/
+bool QWidgetPrivate::handleClose(CloseMode mode)
{
+ Q_Q(QWidget);
+ qCDebug(lcWidgetShowHide) << "Handling close event for" << q;
+
if (data.is_closing)
return true;
- Q_Q(QWidget);
- data.is_closing = 1;
+ // We might not have initiated the close, so update the state now that we know
+ data.is_closing = true;
QPointer<QWidget> that = q;
- QPointer<QWidget> parentWidget = (q->parentWidget() && !QObjectPrivate::get(q->parentWidget())->wasDeleted) ? q->parentWidget() : nullptr;
- bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
+ if (data.in_destructor)
+ mode = CloseNoEvent;
+
if (mode != CloseNoEvent) {
QCloseEvent e;
if (mode == CloseWithSpontaneousEvent)
@@ -8248,40 +8508,17 @@ bool QWidgetPrivate::close_helper(CloseMode mode)
else
QCoreApplication::sendEvent(q, &e);
if (!that.isNull() && !e.isAccepted()) {
- data.is_closing = 0;
+ data.is_closing = false;
return false;
}
}
+ // even for windows, make sure we deliver a hide event and that all children get hidden
if (!that.isNull() && !q->isHidden())
q->hide();
- // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
- quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
-
- if (quitOnClose) {
- /* if there is no non-withdrawn primary window left (except
- the ones without QuitOnClose), we emit the lastWindowClosed
- signal */
- QWidgetList list = QApplication::topLevelWidgets();
- bool lastWindowClosed = true;
- for (int i = 0; i < list.size(); ++i) {
- QWidget *w = list.at(i);
- if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
- continue;
- lastWindowClosed = false;
- break;
- }
- if (lastWindowClosed) {
- QGuiApplicationPrivate::emitLastWindowClosed();
- QCoreApplicationPrivate *applicationPrivate = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(QCoreApplication::instance()));
- applicationPrivate->maybeQuit();
- }
- }
-
-
if (!that.isNull()) {
- data.is_closing = 0;
+ data.is_closing = false;
if (q->testAttribute(Qt::WA_DeleteOnClose)) {
q->setAttribute(Qt::WA_DeleteOnClose, false);
q->deleteLater();
@@ -8305,7 +8542,7 @@ bool QWidgetPrivate::close_helper(CloseMode mode)
is also deleted. A close events is delivered to the widget no
matter if the widget is visible or not.
- The \l QApplication::lastWindowClosed() signal is emitted when the
+ The \l QGuiApplication::lastWindowClosed() signal is emitted when the
last visible primary window (i.e. window with no parent) with the
Qt::WA_QuitOnClose attribute set is closed. By default this
attribute is set for all widgets except transient windows such as
@@ -8315,7 +8552,25 @@ bool QWidgetPrivate::close_helper(CloseMode mode)
bool QWidget::close()
{
- return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
+ return d_func()->close();
+}
+
+bool QWidgetPrivate::close()
+{
+ // FIXME: We're not setting is_closing here, even though that would
+ // make sense, as the code below will not end up in handleClose to
+ // reset is_closing when there's a QWindow, but no QPlatformWindow,
+ // and we can't assume close is synchronous so we can't reset it here.
+
+ // Close native widgets via QWindow::close() in order to run QWindow
+ // close code. The QWidget-specific close code in handleClose() will
+ // in this case be called from the Close event handler in QWidgetWindow.
+ if (QWindow *widgetWindow = windowHandle()) {
+ if (widgetWindow->isTopLevel())
+ return widgetWindow->close();
+ }
+
+ return handleClose(QWidgetPrivate::CloseWithEvent);
}
/*!
@@ -8350,7 +8605,7 @@ bool QWidget::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.
@@ -8437,7 +8692,11 @@ QSize QWidgetPrivate::adjustedSize() const
if (exp & Qt::Vertical)
s.setHeight(qMax(s.height(), 100));
- QRect screen = QDesktopWidgetPrivate::screenGeometry(q->pos());
+ QRect screen;
+ if (const QScreen *screenAtPoint = QGuiApplication::screenAt(q->pos()))
+ screen = screenAtPoint->geometry();
+ else
+ screen = QGuiApplication::primaryScreen()->geometry();
s.setWidth(qMin(s.width(), screen.width()*2/3));
s.setHeight(qMin(s.height(), screen.height()*2/3));
@@ -8673,7 +8932,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
@@ -8730,16 +8989,22 @@ bool QWidget::event(QEvent *event)
inputMethodEvent((QInputMethodEvent *) event);
break;
- case QEvent::InputMethodQuery:
- if (testAttribute(Qt::WA_InputMethodEnabled)) {
+ case QEvent::InputMethodQuery: {
QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
Qt::InputMethodQueries queries = query->queries();
for (uint i = 0; i < 32; ++i) {
Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
if (q) {
QVariant v = inputMethodQuery(q);
- if (q == Qt::ImEnabled && !v.isValid() && isEnabled())
- v = QVariant(true); // special case for Qt4 compatibility
+ if (q == Qt::ImEnabled && !v.isValid() && isEnabled()) {
+ // Qt:ImEnabled was added in Qt 5.3. So not all widgets support it, even
+ // if they implement IM otherwise (by overriding inputMethodQuery()). Instead
+ // they set the widget attribute Qt::WA_InputMethodEnabled. But this attribute
+ // will only be set if the widget supports IM _and_ is not read-only. So for
+ // read-only widgets, not all IM features will be supported when ImEnabled is
+ // not implemented explicitly (e.g selection handles for read-only widgets on iOS).
+ v = QVariant(testAttribute(Qt::WA_InputMethodEnabled));
+ }
query->setValue(q, v);
}
}
@@ -8783,7 +9048,7 @@ bool QWidget::event(QEvent *event)
QCoreApplication::sendEvent(const_cast<QWidget *>(this), &tip);
}
#endif
- enterEvent(event);
+ enterEvent(static_cast<QEnterEvent*>(event));
break;
case QEvent::Leave:
@@ -8836,7 +9101,7 @@ bool QWidget::event(QEvent *event)
break;
#if QT_CONFIG(menu)
case Qt::ActionsContextMenu:
- if (d->actions.count()) {
+ if (d->actions.size()) {
QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
nullptr, this);
break;
@@ -8997,7 +9262,7 @@ bool QWidget::event(QEvent *event)
}
}
break;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::ToolTip:
if (!d->toolTip.isEmpty())
QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this, QRect(), d->toolTipDuration);
@@ -9060,16 +9325,15 @@ 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);
-#ifndef QT_NO_OPENGL
d->renderToTextureReallyDirty = 1;
-#endif
break;
-#ifndef QT_NO_PROPERTIES
case QEvent::DynamicPropertyChange: {
const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
- if (propName.length() == 13 && !qstrncmp(propName, "_q_customDpi", 12)) {
+ if (propName.size() == 13 && !qstrncmp(propName, "_q_customDpi", 12)) {
uint value = property(propName.constData()).toUInt();
if (!d->extra)
d->createExtra();
@@ -9084,7 +9348,6 @@ bool QWidget::event(QEvent *event)
windowHandle()->setProperty(propName, property(propName));
Q_FALLTHROUGH();
}
-#endif
default:
return QObject::event(event);
}
@@ -9112,7 +9375,7 @@ void QWidget::changeEvent(QEvent * event)
switch(event->type()) {
case QEvent::EnabledChange: {
update();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessible::State s;
s.disabled = true;
QAccessibleStateChangeEvent event(this, s);
@@ -9219,7 +9482,7 @@ void QWidget::mousePressEvent(QMouseEvent *event)
if (QApplication::activePopupWidget() == w) // widget does not want to disappear
w->hide(); // hide at least
}
- if (!rect().contains(event->pos())){
+ if (!rect().contains(event->position().toPoint())){
close();
}
}
@@ -9328,7 +9591,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)
@@ -9379,7 +9642,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.)
@@ -9405,7 +9668,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.)
@@ -9429,7 +9692,7 @@ void QWidget::focusOutEvent(QFocusEvent *)
}
/*!
- \fn void QWidget::enterEvent(QEvent *event)
+ \fn void QWidget::enterEvent(QEnterEvent *event)
This event handler can be reimplemented in a subclass to receive
widget enter events which are passed in the \a event parameter.
@@ -9440,12 +9703,10 @@ void QWidget::focusOutEvent(QFocusEvent *)
\sa leaveEvent(), mouseMoveEvent(), event()
*/
-void QWidget::enterEvent(QEvent *)
+void QWidget::enterEvent(QEnterEvent *)
{
}
-// ### Qt 6: void QWidget::enterEvent(QEnterEvent *).
-
/*!
\fn void QWidget::leaveEvent(QEvent *event)
@@ -9507,7 +9768,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 *)
@@ -9579,13 +9840,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{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, {Application Example}
+ \sa event(), hide(), close(), QCloseEvent
*/
void QWidget::closeEvent(QCloseEvent *event)
@@ -9674,7 +9930,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)}.
@@ -9691,16 +9947,16 @@ QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
*/
Qt::InputMethodHints QWidget::inputMethodHints() const
{
-#ifndef QT_NO_IM
+#if QT_CONFIG(im)
const QWidgetPrivate *priv = d_func();
while (priv->inheritsInputMethodHints) {
priv = priv->q_func()->parentWidget()->d_func();
Q_ASSERT(priv);
}
return priv->imHints;
-#else //QT_NO_IM
- return 0;
-#endif //QT_NO_IM
+#else
+ return Qt::ImhNone;
+#endif
}
void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
@@ -9861,11 +10117,7 @@ void QWidget::hideEvent(QHideEvent *)
\endtable
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool QWidget::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
-#else
-bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
-#endif
{
Q_UNUSED(eventType);
Q_UNUSED(message);
@@ -9912,7 +10164,7 @@ void QWidget::ensurePolished() const
QList<QObject*> children = d->children;
for (int i = 0; i < children.size(); ++i) {
QObject *o = children.at(i);
- if(!o->isWidgetType())
+ if (!o->isWidgetType())
continue;
if (QWidget *w = qobject_cast<QWidget *>(o))
w->ensurePolished();
@@ -9928,7 +10180,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
{
@@ -10349,22 +10601,26 @@ void QWidget::setParent(QWidget *parent)
setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
}
-#ifndef QT_NO_OPENGL
-static void sendWindowChangeToTextureChildrenRecursively(QWidget *widget)
+void qSendWindowChangeToTextureChildrenRecursively(QWidget *widget, QEvent::Type eventType)
{
QWidgetPrivate *d = QWidgetPrivate::get(widget);
if (d->renderToTexture) {
- QEvent e(QEvent::WindowChangeInternal);
+ QEvent e(eventType);
QCoreApplication::sendEvent(widget, &e);
}
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);
+ 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);
}
}
-#endif
/*!
\overload
@@ -10391,9 +10647,10 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
});
#endif
- bool resized = testAttribute(Qt::WA_Resized);
- bool wasCreated = testAttribute(Qt::WA_WState_Created);
+ 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;
@@ -10401,7 +10658,7 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
QWidget *desktopWidget = nullptr;
if (parent && parent->windowType() == Qt::Desktop)
desktopWidget = parent;
- bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
+ bool newParent = (parent != parentWidget()) || desktopWidget;
if (newParent && parent && !desktopWidget) {
if (testAttribute(Qt::WA_NativeWindow) && !QCoreApplication::testAttribute(Qt::AA_DontCreateNativeWidgetSiblings))
@@ -10412,7 +10669,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) {
@@ -10420,7 +10690,15 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
QCoreApplication::sendEvent(this, &e);
}
}
- if (newParent && isAncestorOf(focusWidget()))
+
+ // 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 (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.
+ if (newParent && isAncestorOf(focusWidget()) && !(f & Qt::Window))
focusWidget()->clearFocus();
d->setParent_sys(parent, f);
@@ -10428,12 +10706,10 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
if (desktopWidget)
parent = nullptr;
-#ifndef QT_NO_OPENGL
if (d->textureChildSeen && parent) {
// set the textureChildSeen flag up the whole parent chain
QWidgetPrivate::get(parent)->setTextureChildSeen();
}
-#endif
if (QWidgetRepaintManager *oldPaintManager = oldtlw->d_func()->maybeRepaintManager()) {
if (newParent)
@@ -10443,10 +10719,6 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
oldPaintManager->moveStaticWidgets(this);
}
- // ### fixme: Qt 6: Remove AA_ImmediateWidgetCreation.
- if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation) && !testAttribute(Qt::WA_WState_Created))
- create();
-
d->reparentFocusWidgets(oldtlw);
setAttribute(Qt::WA_Resized, resized);
@@ -10455,6 +10727,12 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
if (!useStyleSheetPropagationInWidgetStyles && !testAttribute(Qt::WA_StyleSheet)
&& (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
+ // if the parent has a font set or inherited, then propagate the mask to the new child
+ if (parent) {
+ const auto pd = parent->d_func();
+ d->inheritedFontResolveMask = pd->directFontResolveMask | pd->inheritedFontResolveMask;
+ d->inheritedPaletteResolveMask = pd->directPaletteResolveMask | pd->inheritedPaletteResolveMask;
+ }
d->resolveFont();
d->resolvePalette();
}
@@ -10465,8 +10743,8 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
// event to handle recreation/rebinding of the GL context, hence the
// (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
// platforms).
- if (newParent
-#if defined(QT_OPENGL_ES)
+ if (newParent || !wasCreated
+#if QT_CONFIG(opengles2)
|| (f & Qt::MSWindowsOwnDC)
#endif
) {
@@ -10493,12 +10771,11 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
QEvent e(QEvent::ParentChange);
QCoreApplication::sendEvent(this, &e);
}
-#ifndef QT_NO_OPENGL
- //renderToTexture widgets also need to know when their top-level window changes
- if (d->textureChildSeen && oldtlw != window()) {
- sendWindowChangeToTextureChildrenRecursively(this);
- }
-#endif
+
+ // texture-based widgets need another event when their top-level window
+ // changes (more precisely, has already changed at this point)
+ if (oldtlw->d_func()->usesRhiFlush && oldtlw != window())
+ qSendWindowChangeToTextureChildrenRecursively(this, QEvent::WindowChangeInternal);
if (!wasCreated) {
if (isWindow() || parentWidget()->isVisible())
@@ -10524,6 +10801,37 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
if (d->extra && d->extra->hasWindowContainer)
QWindowContainer::parentWasChanged(this);
+
+ QWidget *newtlw = window();
+ if (oldtlw != newtlw) {
+ QSurface::SurfaceType surfaceType = QSurface::RasterSurface;
+ // Only evaluate the reparented subtree. While it might be tempting to
+ // 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 || !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);
+ }
+ }
+ }
}
void QWidgetPrivate::setParent_sys(QWidget *newparent, Qt::WindowFlags f)
@@ -10533,71 +10841,72 @@ void QWidgetPrivate::setParent_sys(QWidget *newparent, Qt::WindowFlags f)
Qt::WindowFlags oldFlags = data.window_flags;
bool wasCreated = q->testAttribute(Qt::WA_WState_Created);
- int targetScreen = -1;
+ QScreen *targetScreen = nullptr;
// Handle a request to move the widget to a particular screen
if (newparent && newparent->windowType() == Qt::Desktop) {
// make sure the widget is created on the same screen as the
// programmer specified desktop widget
- const QDesktopScreenWidget *sw = qobject_cast<const QDesktopScreenWidget *>(newparent);
- targetScreen = sw ? sw->screenNumber() : 0;
+ targetScreen = newparent->screen();
newparent = nullptr;
}
setWinId(0);
+ if (!newparent) {
+ f |= Qt::Window;
+ if (parent)
+ targetScreen = q->parentWidget()->window()->screen();
+ }
+
+ 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)
+ );
+
if (parent != newparent) {
- QObjectPrivate::setParent_helper(newparent); //### why does this have to be done in the _sys function???
- if (q->windowHandle()) {
+ // Update object parent now, so we can resolve new parent window below
+ QObjectPrivate::setParent_helper(newparent);
+
+ 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 (targetScreen == -1) {
- if (parent)
- targetScreen = QDesktopWidgetPrivate::screenNumber(q->parentWidget()->window());
- }
+ // 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 = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
+ bool explicitlyHidden = isExplicitlyHidden();
- // Reparenting toplevel to child
- if (wasCreated && !(f & Qt::Window) && (oldFlags & Qt::Window) && !q->testAttribute(Qt::WA_NativeWindow)) {
+ if (destroyWindow) {
if (extra && extra->hasWindowContainer)
QWindowContainer::toplevelAboutToBeDestroyed(q);
- QWindow *newParentWindow = newparent->windowHandle();
- if (!newParentWindow)
- if (QWidget *npw = newparent->nativeParentWidget())
- newParentWindow = npw->windowHandle();
-
- Q_FOREACH (QObject *child, q->windowHandle()->children()) {
- QWindow *childWindow = qobject_cast<QWindow *>(child);
- if (!childWindow)
- continue;
-
- QWidgetWindow *childWW = qobject_cast<QWidgetWindow *>(childWindow);
- QWidget *childWidget = childWW ? childWW->widget() : nullptr;
- if (!childWW || (childWidget && childWidget->testAttribute(Qt::WA_NativeWindow)))
- childWindow->setParent(newParentWindow);
+ // 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);
@@ -10614,12 +10923,59 @@ void QWidgetPrivate::setParent_sys(QWidget *newparent, Qt::WindowFlags f)
q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);
// move the window to the selected screen
- if (!newparent && targetScreen != -1) {
+ if (!newparent && targetScreen) {
// only if it is already created
if (q->testAttribute(Qt::WA_WState_Created))
- q->windowHandle()->setScreen(QGuiApplication::screens().value(targetScreen, 0));
+ q->windowHandle()->setScreen(targetScreen);
else
- topData()->initialScreenIndex = targetScreen;
+ topData()->initialScreen = targetScreen;
+ }
+}
+
+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);
+ }
}
}
@@ -10717,7 +11073,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.
@@ -10784,7 +11140,7 @@ void QWidgetPrivate::repaint(T r)
return;
QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
+ if (tlwExtra && tlwExtra->backingStore && tlwExtra->repaintManager)
tlwExtra->repaintManager->markDirty(r, q, QWidgetRepaintManager::UpdateNow);
}
@@ -10804,7 +11160,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()
{
@@ -10845,6 +11201,11 @@ void QWidgetPrivate::update(T r)
{
Q_Q(QWidget);
+ if (renderToTexture && !q->isVisible()) {
+ renderToTextureReallyDirty = 1;
+ return;
+ }
+
if (!q->isVisible() || !q->updatesEnabled())
return;
@@ -10859,7 +11220,7 @@ void QWidgetPrivate::update(T r)
}
QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
+ if (tlwExtra && tlwExtra->backingStore && tlwExtra->repaintManager)
tlwExtra->repaintManager->markDirty(clipped, q);
}
@@ -10916,7 +11277,7 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
return;
Q_D(QWidget);
- Q_STATIC_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
+ static_assert(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
"QWidget::setAttribute(WidgetAttribute, bool): "
"QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
#ifdef Q_OS_WIN
@@ -10987,21 +11348,9 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
// reset modality type to NonModal when clearing WA_ShowModal
data->window_modality = Qt::NonModal;
} else if (data->window_modality == Qt::NonModal) {
- // determine the modality type if it hasn't been set prior
- // to setting WA_ShowModal. set the default to WindowModal
- // if we are the child of a group leader; otherwise use
+ // If modality hasn't been set prior to setting WA_ShowModal, use
// ApplicationModal.
- QWidget *w = parentWidget();
- if (w)
- w = w->window();
- while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
- w = w->parentWidget();
- if (w)
- w = w->window();
- }
- data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
- ? Qt::WindowModal
- : Qt::ApplicationModal;
+ data->window_modality = Qt::ApplicationModal;
// Some window managers do not allow us to enter modality after the
// window is visible.The window must be hidden before changing the
// windowModality property and then reshown.
@@ -11152,7 +11501,7 @@ bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
\warning Changing this property from opaque to transparent might issue a
paint event that needs to be processed before the window is displayed
- correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
+ correctly. This affects mainly the use of QScreen::grabWindow(). Also note
that semi-transparent windows update and resize significantly slower than
opaque windows.
@@ -11220,7 +11569,7 @@ void QWidgetPrivate::setWindowOpacity_sys(qreal level)
its parent because other children of the parent might have been
modified.
- \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
+ \sa windowTitle
*/
bool QWidget::isWindowModified() const
{
@@ -11249,14 +11598,14 @@ void QWidgetPrivate::setWindowModified_helper()
return;
bool on = q->testAttribute(Qt::WA_WindowModified);
if (!platformWindow->setWindowModified(on)) {
- if (Q_UNLIKELY(on && !q->windowTitle().contains(QLatin1String("[*]"))))
+ if (Q_UNLIKELY(on && !q->windowTitle().contains("[*]"_L1)))
qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
setWindowTitle_helper(q->windowTitle());
setWindowIconText_helper(q->windowIconText());
}
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
/*!
\property QWidget::toolTip
@@ -11313,7 +11662,7 @@ int QWidget::toolTipDuration() const
return d->toolTipDuration;
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
#if QT_CONFIG(statustip)
@@ -11361,7 +11710,7 @@ QString QWidget::whatsThis() const
}
#endif // QT_CONFIG(whatsthis)
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
/*!
\property QWidget::accessibleName
@@ -11403,7 +11752,7 @@ QString QWidget::accessibleName() const
\brief the widget's description as seen by assistive technologies
The accessible description of a widget should convey what a widget does.
- While the \l accessibleName should be a short and consise string (e.g. \gui{Save}),
+ While the \l accessibleName should be a short and concise string (e.g. \gui{Save}),
the description should give more context, such as \gui{Saves the current document}.
This property has to be \l{Internationalization with Qt}{localized}.
@@ -11426,7 +11775,7 @@ QString QWidget::accessibleDescription() const
Q_D(const QWidget);
return d->accessibleDescription;
}
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
#ifndef QT_NO_SHORTCUT
/*!
@@ -11519,13 +11868,13 @@ void QWidget::setShortcutAutoRepeat(int id, bool enable)
#endif // QT_NO_SHORTCUT
/*!
- Updates the widget's micro focus.
+ Updates the widget's micro focus and informs input methods
+ that the state specified by \a query has changed.
*/
-void QWidget::updateMicroFocus()
+void QWidget::updateMicroFocus(Qt::InputMethodQuery query)
{
- // updating everything since this is currently called for any kind of state change
if (this == QGuiApplication::focusObject())
- QGuiApplication::inputMethod()->update(Qt::ImQueryAll);
+ QGuiApplication::inputMethod()->update(query);
}
/*!
@@ -11680,7 +12029,7 @@ void QWidgetPrivate::stackUnder_sys(QWidget*)
/*!
\fn bool QWidget::isTopLevel() const
- \obsolete
+ \deprecated
Use isWindow() instead.
*/
@@ -11827,7 +12176,20 @@ QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
&& targetCandidate->isVisible()
// ...is in the same window,
&& targetCandidate->window() == sourceWindow) {
- const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
+ const int targetCandidateDistance = [](const QPoint &sourcePoint,
+ const QRect &targetCandidateRect) {
+ int dx = 0;
+ int dy = 0;
+ if (p.x() < r.left())
+ dx = r.left() - p.x();
+ else if (p.x() > r.right())
+ dx = p.x() - r.right();
+ if (p.y() < r.top())
+ dy = r.top() - p.y();
+ else if (p.y() > r.bottom())
+ dy = p.y() - r.bottom();
+ return dx + dy;
+ }();
if (targetCandidateDistance < shortestDistance) {
shortestDistance = targetCandidateDistance;
targetWidget = targetCandidate;
@@ -11888,7 +12250,7 @@ void QWidget::setBackingStore(QBackingStore *store)
{
// ### createWinId() ??
- if (!isTopLevel())
+ if (!isWindow())
return;
Q_D(QWidget);
@@ -11898,14 +12260,14 @@ void QWidget::setBackingStore(QBackingStore *store)
return;
QBackingStore *oldStore = topData->backingStore;
- deleteBackingStore(d);
+ delete topData->backingStore;
topData->backingStore = store;
QWidgetRepaintManager *repaintManager = d->maybeRepaintManager();
if (!repaintManager)
return;
- if (isTopLevel()) {
+ if (isWindow()) {
if (repaintManager->backingStore() != oldStore && repaintManager->backingStore() != store)
delete repaintManager->backingStore();
repaintManager->setBackingStore(store);
@@ -11993,27 +12355,6 @@ void QWidgetPrivate::adjustQuitOnCloseAttribute()
}
}
-QOpenGLContext *QWidgetPrivate::shareContext() const
-{
-#ifdef QT_NO_OPENGL
- return 0;
-#else
- if (!extra || !extra->topextra || !extra->topextra->window)
- return nullptr;
-
- if (!extra->topextra->shareContext) {
- auto ctx = qt_make_unique<QOpenGLContext>();
- ctx->setShareContext(qt_gl_global_share_context());
- ctx->setFormat(extra->topextra->window->format());
- ctx->setScreen(extra->topextra->window->screen());
- ctx->create();
- extra->topextra->shareContext = std::move(ctx);
- }
- return extra->topextra->shareContext.get();
-#endif // QT_NO_OPENGL
-}
-
-#ifndef QT_NO_OPENGL
void QWidgetPrivate::sendComposeStatus(QWidget *w, bool end)
{
QWidgetPrivate *wd = QWidgetPrivate::get(w);
@@ -12029,7 +12370,6 @@ void QWidgetPrivate::sendComposeStatus(QWidget *w, bool end)
sendComposeStatus(w, end);
}
}
-#endif // QT_NO_OPENGL
Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
{
@@ -12118,8 +12458,8 @@ void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
if ((windowType() == Qt::Popup) && qApp)
qApp->d_func()->closePopup(this);
- if (this == QApplicationPrivate::active_window)
- QApplication::setActiveWindow(nullptr);
+ if (this == qApp->activeWindow())
+ QApplicationPrivate::setActiveWindow(nullptr);
if (QWidget::mouseGrabber() == this)
releaseMouse();
if (QWidget::keyboardGrabber() == this)
@@ -12240,36 +12580,54 @@ static MapToGlobalTransformResult mapToGlobalTransform(const QWidget *w)
}
/*!
- \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
+ \fn QPointF QWidget::mapToGlobal(const QPointF &pos) const
Translates the widget coordinate \a pos to global screen
- coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
+ coordinates. For example, \c{mapToGlobal(QPointF(0,0))} would give
the global coordinates of the top-left pixel of the widget.
\sa mapFromGlobal(), mapTo(), mapToParent()
+ \since 6.0
*/
-QPoint QWidget::mapToGlobal(const QPoint &pos) const
+QPointF QWidget::mapToGlobal(const QPointF &pos) const
{
const MapToGlobalTransformResult t = mapToGlobalTransform(this);
- const QPoint g = t.transform.map(pos);
+ const QPointF g = t.transform.map(pos);
return t.window ? t.window->mapToGlobal(g) : g;
}
/*!
- \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
+ \overload
+*/
+QPoint QWidget::mapToGlobal(const QPoint &pos) const
+{
+ return mapToGlobal(QPointF(pos)).toPoint();
+}
+
+/*!
+ \fn QPointF QWidget::mapFromGlobal(const QPointF &pos) const
Translates the global screen coordinate \a pos to widget
coordinates.
\sa mapToGlobal(), mapFrom(), mapFromParent()
+ \since 6.0
*/
-QPoint QWidget::mapFromGlobal(const QPoint &pos) const
+QPointF QWidget::mapFromGlobal(const QPointF &pos) const
{
const MapToGlobalTransformResult t = mapToGlobalTransform(this);
- const QPoint windowLocal = t.window ? t.window->mapFromGlobal(pos) : pos;
+ const QPointF windowLocal = t.window ? t.window->mapFromGlobal(pos) : pos;
return t.transform.inverted().map(windowLocal);
}
+/*!
+ \overload
+*/
+QPoint QWidget::mapFromGlobal(const QPoint &pos) const
+{
+ return mapFromGlobal(QPointF(pos)).toPoint();
+}
+
QWidget *qt_pressGrab = nullptr;
QWidget *qt_mouseGrb = nullptr;
static bool mouseGrabWithCursor = false;
@@ -12338,7 +12696,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.
@@ -12508,7 +12866,7 @@ QWidget *QWidget::keyboardGrabber()
does not allow an application to interrupt what the user is currently
doing in another application.
- \sa isActiveWindow(), window(), show(), QWindowsWindowFunctions::setWindowActivationBehavior()
+ \sa isActiveWindow(), window(), show()
*/
void QWidget::activateWindow()
{
@@ -12527,57 +12885,59 @@ void QWidget::activateWindow()
*/
int QWidget::metric(PaintDeviceMetric m) const
{
- QWindow *topLevelWindow = nullptr;
- QScreen *screen = nullptr;
- if (QWidget *topLevel = window()) {
- topLevelWindow = topLevel->windowHandle();
- if (topLevelWindow)
- screen = topLevelWindow->screen();
- }
- if (!screen && QGuiApplication::primaryScreen())
- screen = QGuiApplication::primaryScreen();
+ QScreen *screen = this->screen();
if (!screen) {
if (m == PdmDpiX || m == PdmDpiY)
return 72;
return QPaintDevice::metric(m);
}
- int val;
- if (m == PdmWidth) {
- val = data->crect.width();
- } else if (m == PdmWidthMM) {
- val = data->crect.width() * screen->physicalSize().width() / screen->geometry().width();
- } else if (m == PdmHeight) {
- val = data->crect.height();
- } else if (m == PdmHeightMM) {
- val = data->crect.height() * screen->physicalSize().height() / screen->geometry().height();
- } else if (m == PdmDepth) {
+
+ auto resolveDevicePixelRatio = [this, screen]() -> qreal {
+
+ // Note: keep in sync with QBackingStorePrivate::backingStoreDevicePixelRatio()!
+ static bool downscale = qEnvironmentVariableIntValue("QT_WIDGETS_HIGHDPI_DOWNSCALE") > 0;
+ QWindow *window = this->window()->windowHandle();
+ if (window)
+ return downscale ? std::ceil(window->devicePixelRatio()) : window->devicePixelRatio();
+ return screen->devicePixelRatio();
+ };
+
+ switch (m) {
+ case PdmWidth:
+ return data->crect.width();
+ case PdmWidthMM:
+ return data->crect.width() * screen->physicalSize().width() / screen->geometry().width();
+ case PdmHeight:
+ return data->crect.height();
+ case PdmHeightMM:
+ return data->crect.height() * screen->physicalSize().height() / screen->geometry().height();
+ case PdmDepth:
return screen->depth();
- } else if (m == PdmDpiX) {
+ case PdmDpiX:
for (const QWidget *p = this; p; p = p->parentWidget()) {
if (p->d_func()->extra && p->d_func()->extra->customDpiX)
return p->d_func()->extra->customDpiX;
}
return qRound(screen->logicalDotsPerInchX());
- } else if (m == PdmDpiY) {
+ case PdmDpiY:
for (const QWidget *p = this; p; p = p->parentWidget()) {
if (p->d_func()->extra && p->d_func()->extra->customDpiY)
return p->d_func()->extra->customDpiY;
}
return qRound(screen->logicalDotsPerInchY());
- } else if (m == PdmPhysicalDpiX) {
+ case PdmPhysicalDpiX:
return qRound(screen->physicalDotsPerInchX());
- } else if (m == PdmPhysicalDpiY) {
+ case PdmPhysicalDpiY:
return qRound(screen->physicalDotsPerInchY());
- } else if (m == PdmDevicePixelRatio) {
- return topLevelWindow ? topLevelWindow->devicePixelRatio() : qApp->devicePixelRatio();
- } else if (m == PdmDevicePixelRatioScaled) {
- return (QPaintDevice::devicePixelRatioFScale() *
- (topLevelWindow ? topLevelWindow->devicePixelRatio() : qApp->devicePixelRatio()));
- } else {
- val = QPaintDevice::metric(m);// XXX
+ case PdmDevicePixelRatio:
+ return resolveDevicePixelRatio();
+ case PdmDevicePixelRatioScaled:
+ return QPaintDevice::devicePixelRatioFScale() * resolveDevicePixelRatio();
+ default:
+ break;
}
- return val;
+ return QPaintDevice::metric(m);
}
/*!
@@ -12635,8 +12995,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
*/
@@ -12722,7 +13090,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)
{
@@ -12752,63 +13120,112 @@ void QWidgetPrivate::setWidgetParentHelper(QObject *widgetAsObject, QObject *new
widget->setParent(static_cast<QWidget*>(newParent));
}
+std::string QWidgetPrivate::flagsForDumping() const
+{
+ Q_Q(const QWidget);
+ std::string flags = QObjectPrivate::flagsForDumping();
+ if (QApplication::focusWidget() == q)
+ flags += 'F';
+ if (q->isVisible()) {
+ std::stringstream s;
+ s << '<'
+ << q->width() << 'x' << q->height()
+ << std::showpos << q->x() << q->y()
+ << '>';
+ flags += s.str();
+ } else {
+ flags += 'I';
+ }
+ return flags;
+}
+
void QWidgetPrivate::setNetWmWindowTypes(bool skipIfMissing)
{
+#if QT_CONFIG(xcb)
Q_Q(QWidget);
if (!q->windowHandle())
return;
- int wmWindowType = 0;
+ QXcbWindow::WindowTypes wmWindowType = QXcbWindow::None;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDesktop))
- wmWindowType |= QXcbWindowFunctions::Desktop;
+ wmWindowType |= QXcbWindow::Desktop;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDock))
- wmWindowType |= QXcbWindowFunctions::Dock;
+ wmWindowType |= QXcbWindow::Dock;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeToolBar))
- wmWindowType |= QXcbWindowFunctions::Toolbar;
+ wmWindowType |= QXcbWindow::Toolbar;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeMenu))
- wmWindowType |= QXcbWindowFunctions::Menu;
+ wmWindowType |= QXcbWindow::Menu;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeUtility))
- wmWindowType |= QXcbWindowFunctions::Utility;
+ wmWindowType |= QXcbWindow::Utility;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeSplash))
- wmWindowType |= QXcbWindowFunctions::Splash;
+ wmWindowType |= QXcbWindow::Splash;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDialog))
- wmWindowType |= QXcbWindowFunctions::Dialog;
+ wmWindowType |= QXcbWindow::Dialog;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDropDownMenu))
- wmWindowType |= QXcbWindowFunctions::DropDownMenu;
+ wmWindowType |= QXcbWindow::DropDownMenu;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypePopupMenu))
- wmWindowType |= QXcbWindowFunctions::PopupMenu;
+ wmWindowType |= QXcbWindow::PopupMenu;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeToolTip))
- wmWindowType |= QXcbWindowFunctions::Tooltip;
+ wmWindowType |= QXcbWindow::Tooltip;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeNotification))
- wmWindowType |= QXcbWindowFunctions::Notification;
+ wmWindowType |= QXcbWindow::Notification;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeCombo))
- wmWindowType |= QXcbWindowFunctions::Combo;
+ wmWindowType |= QXcbWindow::Combo;
if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDND))
- wmWindowType |= QXcbWindowFunctions::Dnd;
+ wmWindowType |= QXcbWindow::Dnd;
- if (wmWindowType == 0 && skipIfMissing)
+ if (wmWindowType == QXcbWindow::None && skipIfMissing)
return;
- QXcbWindowFunctions::setWmWindowType(q->windowHandle(), static_cast<QXcbWindowFunctions::WmWindowType>(wmWindowType));
+ if (auto *xcbWindow = dynamic_cast<QXcbWindow*>(q->windowHandle()->handle()))
+ xcbWindow->setWindowType(wmWindowType);
+#else
+ Q_UNUSED(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)
@@ -12828,7 +13245,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()
@@ -12840,7 +13257,7 @@ QDebug operator<<(QDebug debug, const QWidget *widget)
frameGeometry.bottom() - geometry.bottom());
debug << ", margins=" << margins;
}
- debug << ", devicePixelRatio=" << widget->devicePixelRatioF();
+ debug << ", devicePixelRatio=" << widget->devicePixelRatio();
if (const WId wid = widget->internalWinId())
debug << ", winId=0x" << Qt::hex << wid << Qt::dec;
}
@@ -12852,7 +13269,400 @@ 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"
-
+#include "moc_qwidget_p.cpp"
diff --git a/src/widgets/kernel/qwidget.h b/src/widgets/kernel/qwidget.h
index 5117fa94c8..e5e83a43f2 100644
--- a/src/widgets/kernel/qwidget.h
+++ b/src/widgets/kernel/qwidget.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIDGET_H
#define QWIDGET_H
@@ -44,6 +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>
@@ -65,7 +32,6 @@ QT_BEGIN_NAMESPACE
class QLayout;
-class QWSRegionManager;
class QStyle;
class QAction;
class QVariant;
@@ -75,6 +41,7 @@ class QMouseEvent;
class QWheelEvent;
class QHoverEvent;
class QKeyEvent;
+class QEnterEvent;
class QFocusEvent;
class QPaintEvent;
class QMoveEvent;
@@ -152,10 +119,14 @@ class Q_WIDGETS_EXPORT QWidget : public QObject, public QPaintDevice
Q_PROPERTY(QSizePolicy sizePolicy READ sizePolicy WRITE setSizePolicy)
Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize)
Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize)
- Q_PROPERTY(int minimumWidth READ minimumWidth WRITE setMinimumWidth STORED false DESIGNABLE false)
- Q_PROPERTY(int minimumHeight READ minimumHeight WRITE setMinimumHeight STORED false DESIGNABLE false)
- Q_PROPERTY(int maximumWidth READ maximumWidth WRITE setMaximumWidth STORED false DESIGNABLE false)
- Q_PROPERTY(int maximumHeight READ maximumHeight WRITE setMaximumHeight STORED false DESIGNABLE false)
+ Q_PROPERTY(int minimumWidth READ minimumWidth WRITE setMinimumWidth STORED false
+ DESIGNABLE false)
+ Q_PROPERTY(int minimumHeight READ minimumHeight WRITE setMinimumHeight STORED false
+ DESIGNABLE false)
+ Q_PROPERTY(int maximumWidth READ maximumWidth WRITE setMaximumWidth STORED false
+ DESIGNABLE false)
+ Q_PROPERTY(int maximumHeight READ maximumHeight WRITE setMaximumHeight STORED false
+ DESIGNABLE false)
Q_PROPERTY(QSize sizeIncrement READ sizeIncrement WRITE setSizeIncrement)
Q_PROPERTY(QSize baseSize READ baseSize WRITE setBaseSize)
Q_PROPERTY(QPalette palette READ palette WRITE setPalette)
@@ -182,7 +153,7 @@ class Q_WIDGETS_EXPORT QWidget : public QObject, public QPaintDevice
Q_PROPERTY(QString windowIconText READ windowIconText WRITE setWindowIconText NOTIFY windowIconTextChanged) // deprecated
Q_PROPERTY(double windowOpacity READ windowOpacity WRITE setWindowOpacity)
Q_PROPERTY(bool windowModified READ isWindowModified WRITE setWindowModified)
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip)
Q_PROPERTY(int toolTipDuration READ toolTipDuration WRITE setToolTipDuration)
#endif
@@ -192,7 +163,7 @@ class Q_WIDGETS_EXPORT QWidget : public QObject, public QPaintDevice
#if QT_CONFIG(whatsthis)
Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis)
#endif
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
Q_PROPERTY(QString accessibleName READ accessibleName WRITE setAccessibleName)
Q_PROPERTY(QString accessibleDescription READ accessibleDescription WRITE setAccessibleDescription)
#endif
@@ -206,6 +177,31 @@ 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>
+ using compatible_action_slot_args = std::void_t<
+ decltype(QObject::connect(std::declval<QAction*>(), &QAction::triggered,
+ std::declval<Args>()...))
+ >;
+#else
+ // good-enough compromise for now
+ template <typename...Args>
+ using compatible_action_slot_args = std::enable_if_t<std::conjunction_v<
+#if QT_CONFIG(shortcut)
+ std::disjunction<
+ std::is_same<Args, Qt::ConnectionType>,
+ std::negation<std::is_convertible<Args, QKeySequence>>
+ >...,
+#endif
+ std::negation<std::is_convertible<Args, QIcon>>...,
+ std::negation<std::is_convertible<Args, const char*>>...,
+ std::negation<std::is_convertible<Args, QString>>...
+ >>;
+#endif
+#endif // QT_CONFIG(action)
+
public:
enum RenderFlag {
DrawWindowBackground = 0x1,
@@ -229,7 +225,10 @@ public:
void setStyle(QStyle *);
// Widget types and states
+#if QT_DEPRECATED_SINCE(6, 1)
+ QT_DEPRECATED_VERSION_X_6_1("Use isWindow()")
bool isTopLevel() const;
+#endif
bool isWindow() const;
bool isModal() const;
@@ -238,10 +237,6 @@ public:
bool isEnabled() const;
bool isEnabledTo(const QWidget *) const;
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use isEnabled() instead")
- bool isEnabledToTLW() const;
-#endif
public Q_SLOTS:
void setEnabled(bool);
@@ -299,11 +294,17 @@ public:
// Widget coordinate mapping
+ QPointF mapToGlobal(const QPointF &) const;
QPoint mapToGlobal(const QPoint &) const;
+ QPointF mapFromGlobal(const QPointF &) const;
QPoint mapFromGlobal(const QPoint &) const;
+ QPointF mapToParent(const QPointF &) const;
QPoint mapToParent(const QPoint &) const;
+ QPointF mapFromParent(const QPointF &) const;
QPoint mapFromParent(const QPoint &) const;
+ QPointF mapTo(const QWidget *, const QPointF &) const;
QPoint mapTo(const QWidget *, const QPoint &) const;
+ QPointF mapFrom(const QWidget *, const QPointF &) const;
QPoint mapFrom(const QWidget *, const QPoint &) const;
QWidget *window() const;
@@ -386,7 +387,7 @@ public:
qreal windowOpacity() const;
bool isWindowModified() const;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
void setToolTip(const QString &);
QString toolTip() const;
void setToolTipDuration(int msec);
@@ -400,7 +401,7 @@ public:
void setWhatsThis(const QString &);
QString whatsThis() const;
#endif
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QString accessibleName() const;
void setAccessibleName(const QString &name);
QString accessibleDescription() const;
@@ -431,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;
@@ -527,10 +529,6 @@ public:
void setContentsMargins(int left, int top, int right, int bottom);
void setContentsMargins(const QMargins &margins);
-#if QT_DEPRECATED_SINCE(5, 14)
- QT_DEPRECATED_X("use contentsMargins()")
- void getContentsMargins(int *left, int *top, int *right, int *bottom) const;
-#endif
QMargins contentsMargins() const;
QRect contentsRect() const;
@@ -559,17 +557,60 @@ public:
#ifndef QT_NO_ACTION
//actions
void addAction(QAction *action);
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void addActions(const QList<QAction*> &actions);
void insertActions(QAction *before, const QList<QAction*> &actions);
-#else
- void addActions(QList<QAction*> actions);
- void insertActions(QAction *before, QList<QAction*> actions);
-#endif
void insertAction(QAction *before, QAction *action);
void removeAction(QAction *action);
QList<QAction*> actions() const;
-#endif
+
+ // convenience action factories
+ QAction *addAction(const QString &text);
+ QAction *addAction(const QIcon &icon, const QString &text);
+ QAction *addAction(const QString &text, const QObject *receiver,
+ const char *member, Qt::ConnectionType type = Qt::AutoConnection);
+ QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver,
+ const char *member, Qt::ConnectionType type = Qt::AutoConnection);
+ template <typename...Args, typename = compatible_action_slot_args<Args...>>
+ QAction *addAction(const QString &text, Args&&...args)
+ {
+ QAction *result = addAction(text);
+ connect(result, &QAction::triggered, std::forward<Args>(args)...);
+ return result;
+ }
+ template <typename...Args, typename = compatible_action_slot_args<Args...>>
+ QAction *addAction(const QIcon &icon, const QString &text, Args&&...args)
+ {
+ QAction *result = addAction(icon, text);
+ connect(result, &QAction::triggered, std::forward<Args>(args)...);
+ return result;
+ }
+
+#if QT_CONFIG(shortcut)
+ QAction *addAction(const QString &text, const QKeySequence &shortcut);
+ QAction *addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut);
+ QAction *addAction(const QString &text, const QKeySequence &shortcut,
+ const QObject *receiver, const char *member,
+ Qt::ConnectionType type = Qt::AutoConnection);
+ QAction *addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut,
+ const QObject *receiver, const char *member,
+ Qt::ConnectionType type = Qt::AutoConnection);
+
+ template <typename...Args, typename = compatible_action_slot_args<Args...>>
+ QAction *addAction(const QString &text, const QKeySequence &shortcut, Args&&...args)
+ {
+ QAction *result = addAction(text, shortcut);
+ connect(result, &QAction::triggered, std::forward<Args>(args)...);
+ return result;
+ }
+ template <typename...Args, typename = compatible_action_slot_args<Args...>>
+ QAction *addAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut, Args&&...args)
+ {
+ QAction *result = addAction(icon, text, shortcut);
+ connect(result, &QAction::triggered, std::forward<Args>(args)...);
+ return result;
+ }
+#endif // QT_CONFIG(shortcut)
+#endif // QT_NO_ACTION
QWidget *parentWidget() const;
@@ -605,11 +646,10 @@ public:
QWindow *windowHandle() const;
QScreen *screen() const;
+ void setScreen(QScreen *);
static QWidget *createWindowContainer(QWindow *window, QWidget *parent=nullptr, Qt::WindowFlags flags=Qt::WindowFlags());
- friend class QDesktopScreenWidget;
-
Q_SIGNALS:
void windowTitleChanged(const QString &title);
void windowIconChanged(const QIcon &icon);
@@ -630,7 +670,7 @@ protected:
virtual void keyReleaseEvent(QKeyEvent *event);
virtual void focusInEvent(QFocusEvent *event);
virtual void focusOutEvent(QFocusEvent *event);
- virtual void enterEvent(QEvent *event);
+ virtual void enterEvent(QEnterEvent *event);
virtual void leaveEvent(QEvent *event);
virtual void paintEvent(QPaintEvent *event);
virtual void moveEvent(QMoveEvent *event);
@@ -656,11 +696,7 @@ protected:
virtual void showEvent(QShowEvent *event);
virtual void hideEvent(QHideEvent *event);
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
virtual bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result);
-#else
- virtual bool nativeEvent(const QByteArray &eventType, void *message, long *result);
-#endif
// Misc. protected functions
virtual void changeEvent(QEvent *);
@@ -678,7 +714,7 @@ public:
void setInputMethodHints(Qt::InputMethodHints hints);
protected Q_SLOTS:
- void updateMicroFocus();
+ void updateMicroFocus(Qt::InputMethodQuery query = Qt::ImQueryAll);
protected:
void create(WId = 0, bool initializeWindow = true,
@@ -715,9 +751,6 @@ private:
friend class QLayout;
friend class QWidgetItem;
friend class QWidgetItemV2;
- friend class QGLContext;
- friend class QGLWidget;
- friend class QGLWindowSurface;
friend class QX11PaintEngine;
friend class QWin32PaintEngine;
friend class QShortcutPrivate;
@@ -736,15 +769,13 @@ 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);
private:
Q_DISABLE_COPY(QWidget)
Q_PRIVATE_SLOT(d_func(), void _q_showIfNotHidden())
+ Q_PRIVATE_SLOT(d_func(), QWindow *_q_closestWindowHandle())
QWidgetData *data;
};
@@ -768,15 +799,17 @@ inline QWidget *QWidget::childAt(int ax, int ay) const
{ return childAt(QPoint(ax, ay)); }
inline Qt::WindowType QWidget::windowType() const
-{ return static_cast<Qt::WindowType>(int(data->window_flags & Qt::WindowType_Mask)); }
+{ return static_cast<Qt::WindowType>((data->window_flags & Qt::WindowType_Mask).toInt()); }
inline Qt::WindowFlags QWidget::windowFlags() const
{ return data->window_flags; }
+#if QT_DEPRECATED_SINCE(6, 1)
inline bool QWidget::isTopLevel() const
-{ return (windowType() & Qt::Window); }
+{ return bool(windowType() & Qt::Window); }
+#endif
inline bool QWidget::isWindow() const
-{ return (windowType() & Qt::Window); }
+{ return bool(windowType() & Qt::Window); }
inline bool QWidget::isEnabled() const
{ return !testAttribute(Qt::WA_Disabled); }
@@ -784,11 +817,6 @@ inline bool QWidget::isEnabled() const
inline bool QWidget::isModal() const
{ return data->window_modality != Qt::NonModal; }
-#if QT_DEPRECATED_SINCE(5, 13)
-inline bool QWidget::isEnabledToTLW() const
-{ return isEnabled(); }
-#endif
-
inline int QWidget::minimumWidth() const
{ return minimumSize().width(); }
@@ -886,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 0d0077548c..9fab9efa62 100644
--- a/src/widgets/kernel/qwidget_p.h
+++ b/src/widgets/kernel/qwidget_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QWIDGET_P_H
#define QWIDGET_P_H
@@ -51,6 +15,8 @@
// We mean it.
//
+
+
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "QtWidgets/qwidget.h"
#include "private/qobject_p.h"
@@ -59,8 +25,8 @@
#include "QtCore/qset.h"
#include "QtGui/qregion.h"
#include "QtGui/qinputmethod.h"
-#include "QtGui/qopengl.h"
#include "QtGui/qsurfaceformat.h"
+#include "QtGui/qscreen.h"
#include "QtWidgets/qsizepolicy.h"
#include "QtWidgets/qstyle.h"
#include "QtWidgets/qapplication.h"
@@ -74,6 +40,10 @@
#endif
#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>
@@ -81,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.
@@ -91,7 +62,6 @@ class QPixmap;
class QWidgetRepaintManager;
class QGraphicsProxyWidget;
class QWidgetItemV2;
-class QOpenGLContext;
class QStyle;
@@ -99,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
{
@@ -108,13 +79,10 @@ public:
{
}
- ~QUpdateLaterEvent()
- {
- }
-
inline const QRegion &region() const { return m_region; }
protected:
+ friend class QApplication;
QRegion m_region;
};
@@ -127,9 +95,6 @@ struct QTLWExtra {
QBackingStore *backingStore;
QPainter *sharedPainter;
QWidgetWindow *window;
-#ifndef QT_NO_OPENGL
- mutable std::unique_ptr<QOpenGLContext> shareContext;
-#endif
// Implicit pointers (shared_null).
QString caption; // widget caption
@@ -144,18 +109,14 @@ struct QTLWExtra {
QRect frameStrut;
QRect normalGeometry; // used by showMin/maximized/FullScreen
Qt::WindowFlags savedFlags; // Save widget flags while showing fullscreen
- // ### TODO replace initialScreenIndex with QScreen *, in case the screens change at runtime
- int initialScreenIndex; // Screen number when passing a QDesktop[Screen]Widget as parent.
+ QScreen *initialScreen; // Screen when passing a QDesktop[Screen]Widget as parent.
-#ifndef QT_NO_OPENGL
std::vector<std::unique_ptr<QPlatformTextureList>> widgetTextures;
-#endif
// *************************** Cross-platform bit fields ****************************
uint opacity : 8;
uint posIncludesFrame : 1;
uint sizeAdjusted : 1;
- uint inTopLevelResize : 1;
uint embedded : 1;
};
@@ -230,18 +191,12 @@ public:
DontSubtractOpaqueChildren = 0x10,
DontDrawOpaqueChildren = 0x20,
DontDrawNativeChildren = 0x40,
- DontSetCompositionMode = 0x80
+ DontSetCompositionMode = 0x80,
+ UseEffectRegionBounds = 0x100
};
Q_DECLARE_FLAGS(DrawWidgetFlags, DrawWidgetFlag)
Q_FLAG(DrawWidgetFlags)
- enum CloseMode {
- CloseNoEvent,
- CloseWithEvent,
- CloseWithSpontaneousEvent
- };
- Q_ENUM(CloseMode)
-
enum Direction {
DirectionNorth = 0x01,
DirectionEast = 0x10,
@@ -257,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;
@@ -264,12 +222,15 @@ public:
void setSharedPainter(QPainter *painter);
QWidgetRepaintManager *maybeRepaintManager() const;
+ QRhi *rhi() const;
+
enum class WindowHandleMode {
Direct,
Closest,
TopLevel
};
QWindow *windowHandle(WindowHandleMode mode = WindowHandleMode::Direct) const;
+ QWindow *_q_closestWindowHandle() const; // Private slot in QWidget
QScreen *associatedScreen() const;
@@ -313,7 +274,7 @@ public:
void updateFont(const QFont &);
inline void setFont_helper(const QFont &font) {
- if (directFontResolveMask == font.resolve() && data.fnt == font)
+ if (directFontResolveMask == font.resolveMask() && data.fnt == font)
return;
updateFont(font);
}
@@ -372,7 +333,14 @@ public:
const QRegion &getOpaqueChildren() const;
void setDirtyOpaqueRegion();
- bool close_helper(CloseMode mode);
+ bool close();
+ enum CloseMode {
+ CloseNoEvent,
+ CloseWithEvent,
+ CloseWithSpontaneousEvent
+ };
+ Q_ENUM(CloseMode)
+ bool handleClose(CloseMode mode);
void setWindowIcon_helper();
void setWindowIcon_sys();
@@ -388,6 +356,7 @@ public:
void invalidateBackingStore(const T &);
QRegion overlappedRegion(const QRect &rect, bool breakAfterFirst = false) const;
+ bool isOverlapped(const QRect &rect) const { return !overlappedRegion(rect, true).isEmpty(); }
void syncBackingStore();
void syncBackingStore(const QRegion &region);
@@ -398,12 +367,12 @@ public:
void reparentFocusWidgets(QWidget *oldtlw);
- static int pointToRect(const QPoint &p, const QRect &r);
-
void setWinId(WId);
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();
@@ -416,6 +385,7 @@ public:
void show_sys();
void hide_sys();
void hide_helper();
+ bool isExplicitlyHidden() const;
void _q_showIfNotHidden();
void setVisible(bool);
@@ -476,33 +446,60 @@ public:
void setModal_sys();
- // This is an helper function that return the available geometry for
- // a widget and takes care is this one is in QGraphicsView.
- // If the widget is not embed in a scene then the geometry available is
- // null, we let QDesktopWidget decide for us.
- static QRect screenGeometry(const QWidget *widget)
+ // These helper functions return the (available) geometry for the screen
+ // the widget is on, and takes care if this one is embedded in a QGraphicsView.
+ static QWidget *parentGraphicsView(const QWidget *widget)
{
- QRect screen;
#if QT_CONFIG(graphicsview)
QGraphicsProxyWidget *ancestorProxy = widget->d_func()->nearestGraphicsProxyWidget(widget);
//It's embedded if it has an ancestor
if (ancestorProxy) {
if (!bypassGraphicsProxyWidget(widget) && ancestorProxy->scene() != nullptr) {
- // One view, let be smart and return the viewport rect then the popup is aligned
- if (ancestorProxy->scene()->views().size() == 1) {
- QGraphicsView *view = ancestorProxy->scene()->views().at(0);
- screen = view->mapToScene(view->viewport()->rect()).boundingRect().toRect();
- } else {
- screen = ancestorProxy->scene()->sceneRect().toRect();
+ if (!ancestorProxy->scene()->views().empty()) {
+ return ancestorProxy->scene()->views().at(0);
}
}
}
#else
Q_UNUSED(widget);
#endif
+ return nullptr;
+ }
+
+ static QRect screenGeometry(const QWidget *widget)
+ {
+ return screenGeometry(widget, QPoint(), false);
+ }
+
+ static QRect availableScreenGeometry(const QWidget *widget)
+ {
+ return availableScreenGeometry(widget, QPoint(), false);
+ }
+
+ static QScreen *screen(const QWidget *widget, const QPoint &globalPosition, bool hasPosition = true)
+ {
+ while (QWidget *view = parentGraphicsView(widget))
+ widget = view;
+
+ QScreen *screen = nullptr;
+ if (hasPosition)
+ screen = widget->screen()->virtualSiblingAt(globalPosition);
+ if (!screen)
+ screen = widget->screen();
+
return screen;
}
+ static QRect screenGeometry(const QWidget *widget, const QPoint &globalPosition, bool hasPosition = true)
+ {
+ return screen(widget, globalPosition, hasPosition)->geometry();
+ }
+
+ static QRect availableScreenGeometry(const QWidget *widget, const QPoint &globalPosition, bool hasPosition = true)
+ {
+ return screen(widget, globalPosition, hasPosition)->availableGeometry();
+ }
+
inline void setRedirected(QPaintDevice *replacement, const QPoint &offset)
{
Q_ASSERT(q_func()->testAttribute(Qt::WA_WState_InPaintEvent));
@@ -558,8 +555,14 @@ public:
inline void handleSoftwareInputPanel(Qt::MouseButton button, bool clickCausedFocus)
{
+ if (button == Qt::LeftButton)
+ handleSoftwareInputPanel(clickCausedFocus);
+ }
+
+ inline void handleSoftwareInputPanel(bool clickCausedFocus = false)
+ {
Q_Q(QWidget);
- if (button == Qt::LeftButton && qApp->autoSipEnabled()) {
+ if (qApp->autoSipEnabled()) {
QStyle::RequestSoftwareInputPanel behavior = QStyle::RequestSoftwareInputPanel(
q->style()->styleHint(QStyle::SH_RequestSoftwareInputPanel));
if (!clickCausedFocus || behavior == QStyle::RSIP_OnMouseClick) {
@@ -582,12 +585,17 @@ public:
inline QRect mapFromWS(const QRect &r) const
{ return r.translated(data.wrect.topLeft()); }
- QOpenGLContext *shareContext() const;
+ virtual QObject *focusObject();
- virtual QObject *focusObject() { return nullptr; }
+ virtual QPlatformBackingStoreRhiConfig rhiConfig() const { return {}; }
-#ifndef QT_NO_OPENGL
- virtual GLuint textureId() const { return 0; }
+ // Note that textureRight may be null, as it's only used in stereoscopic rendering
+ struct TextureData {
+ QRhiTexture *textureLeft = nullptr;
+ QRhiTexture *textureRight = nullptr;
+ };
+
+ virtual TextureData texture() const { return {}; }
virtual QPlatformTextureList::Flags textureListFlags() {
Q_Q(QWidget);
return q->testAttribute(Qt::WA_AlwaysStackOnTop)
@@ -622,10 +630,18 @@ public:
virtual void resizeViewportFramebuffer() { }
// Called after each paint event.
virtual void resolveSamples() { }
-#endif
+
+ // These two are used in QGraphicsView for supporting stereoscopic rendering with a
+ // QOpenGLWidget viewport.
+ virtual bool isStereoEnabled() { return false; } // Called in QGraphicsView::setupViewport
+ virtual bool toggleStereoTargetBuffer() { return false; } // Called in QGraphicsView::paintEvent
static void setWidgetParentHelper(QObject *widgetAsObject, QObject *newParent);
+ 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;
@@ -654,7 +670,7 @@ public:
// Implicit pointers (shared_null/shared_empty).
QRegion opaqueChildren;
QRegion dirty;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
QString toolTip;
int toolTipDuration;
#endif
@@ -664,7 +680,7 @@ public:
#if QT_CONFIG(whatsthis)
QString whatsThis;
#endif
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QString accessibleName;
QString accessibleDescription;
#endif
@@ -672,6 +688,7 @@ public:
// Other variables.
uint directFontResolveMask;
uint inheritedFontResolveMask;
+ decltype(std::declval<QPalette>().resolveMask()) directPaletteResolveMask;
QPalette::ResolveMask inheritedPaletteResolveMask;
short leftmargin;
short topmargin;
@@ -712,13 +729,45 @@ public:
#ifndef QT_NO_IM
uint inheritsInputMethodHints : 1;
#endif
-#ifndef QT_NO_OPENGL
uint renderToTextureReallyDirty : 1;
- uint renderToTextureComposeActive : 1;
-#endif
+ uint usesRhiFlush : 1;
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()
@@ -729,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 12250983f7..13f386d3ec 100644
--- a/src/widgets/kernel/qwidgetaction.cpp
+++ b/src/widgets/kernel/qwidgetaction.cpp
@@ -1,45 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qwidgetaction.h"
+#include "qwidget.h"
#include "qdebug.h"
+#include <QtWidgets/private/qwidget_p.h>
+
#include "qwidgetaction_p.h"
QT_BEGIN_NAMESPACE
@@ -117,9 +84,9 @@ QWidgetAction::QWidgetAction(QObject *parent)
QWidgetAction::~QWidgetAction()
{
Q_D(QWidgetAction);
- for (int i = 0; i < d->createdWidgets.count(); ++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);
@@ -143,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;
@@ -182,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;
}
@@ -210,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);
}
@@ -225,7 +192,7 @@ bool QWidgetAction::event(QEvent *event)
if (event->type() == QEvent::ActionChanged) {
if (d->defaultWidget)
d->defaultWidget->setEnabled(isEnabled());
- for (int i = 0; i < d->createdWidgets.count(); ++i)
+ for (int i = 0; i < d->createdWidgets.size(); ++i)
d->createdWidgets.at(i)->setEnabled(isEnabled());
}
return QAction::event(event);
@@ -249,7 +216,7 @@ bool QWidgetAction::eventFilter(QObject *obj, QEvent *event)
*/
QWidget *QWidgetAction::createWidget(QWidget *parent)
{
- Q_UNUSED(parent)
+ Q_UNUSED(parent);
return nullptr;
}
diff --git a/src/widgets/kernel/qwidgetaction.h b/src/widgets/kernel/qwidgetaction.h
index 4d302e8c61..296ff52d1e 100644
--- a/src/widgets/kernel/qwidgetaction.h
+++ b/src/widgets/kernel/qwidgetaction.h
@@ -1,47 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIDGETACTION_H
#define QWIDGETACTION_H
#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtWidgets/qaction.h>
+#include <QtGui/qaction.h>
QT_REQUIRE_CONFIG(action);
@@ -73,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 0e633a65e4..6a1cd8c186 100644
--- a/src/widgets/kernel/qwidgetaction_p.h
+++ b/src/widgets/kernel/qwidgetaction_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIDGETACTION_P_H
#define QWIDGETACTION_P_H
@@ -52,13 +16,15 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
-#include "private/qaction_p.h"
+#include "private/qaction_widgets_p.h"
+
+#include <QtCore/qpointer.h>
QT_REQUIRE_CONFIG(action);
QT_BEGIN_NAMESPACE
-class QWidgetActionPrivate : public QActionPrivate
+class QWidgetActionPrivate : public QtWidgetsActionPrivate
{
Q_DECLARE_PUBLIC(QWidgetAction)
public:
@@ -68,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 135a1527ac..607a767a20 100644
--- a/src/widgets/kernel/qwidgetrepaintmanager.cpp
+++ b/src/widgets/kernel/qwidgetrepaintmanager.cpp
@@ -1,42 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// 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"
@@ -63,16 +26,13 @@
#include <qpa/qplatformbackingstore.h>
-#include <private/qmemory_p.h>
-
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_OPENGL
Q_GLOBAL_STATIC(QPlatformTextureList, qt_dummy_platformTextureList)
// Watches one or more QPlatformTextureLists for changes in the lock state and
// triggers a backingstore sync when all the registered lists turn into
-// unlocked state. This is essential when a custom composeAndFlush()
+// unlocked state. This is essential when a custom rhiFlush()
// implementation in a platform plugin is not synchronous and keeps
// holding on to the textures for some time even after returning from there.
class QPlatformTextureListWatcher : public QObject
@@ -88,7 +48,7 @@ public:
}
bool isLocked() const {
- foreach (bool v, m_locked) {
+ for (const auto &[_, v] : m_locked.asKeyValueRange()) {
if (v)
return true;
}
@@ -107,7 +67,6 @@ private:
QHash<QPlatformTextureList *, bool> m_locked;
QWidgetRepaintManager *m_repaintManager;
};
-#endif
// ---------------------------------------------------------------------------
@@ -166,7 +125,7 @@ void QWidgetPrivate::invalidateBackingStore(const T &r)
return;
QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- if (!tlwExtra || tlwExtra->inTopLevelResize || !tlwExtra->backingStore)
+ if (!tlwExtra || !tlwExtra->backingStore || !tlwExtra->repaintManager)
return;
T clipped(r);
@@ -213,7 +172,6 @@ void QWidgetRepaintManager::markDirty(const T &r, QWidget *widget, UpdateTime up
Q_ASSERT(tlw->d_func()->extra);
Q_ASSERT(tlw->d_func()->extra->topextra);
- Q_ASSERT(!tlw->d_func()->extra->topextra->inTopLevelResize);
Q_ASSERT(widget->isVisible() && widget->updatesEnabled());
Q_ASSERT(widget->window() == tlw);
Q_ASSERT(!r.isEmpty());
@@ -343,7 +301,7 @@ void QWidgetRepaintManager::removeDirtyWidget(QWidget *w)
needsFlushWidgets.removeAll(w);
QWidgetPrivate *wd = w->d_func();
- const int n = wd->children.count();
+ const int n = wd->children.size();
for (int i = 0; i < n; ++i) {
if (QWidget *child = qobject_cast<QWidget*>(wd->children.at(i)))
removeDirtyWidget(child);
@@ -377,14 +335,13 @@ void QWidgetRepaintManager::sendUpdateRequest(QWidget *widget, UpdateTime update
qCInfo(lcWidgetPainting) << "Sending update request to" << widget << "with" << updateTime;
-#ifndef QT_NO_OPENGL
// Having every repaint() leading to a sync/flush is bad as it causes
// 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();
@@ -393,13 +350,16 @@ void QWidgetRepaintManager::sendUpdateRequest(QWidget *widget, UpdateTime update
const qint64 elapsed = wd->lastComposeTime.elapsed();
if (elapsed <= qint64(1000.0f / refresh))
updateTime = UpdateLater;
- }
+ }
}
-#endif
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: {
@@ -417,25 +377,6 @@ static bool hasPlatformWindow(QWidget *widget)
return widget && widget->windowHandle() && widget->windowHandle()->handle();
}
-static QVector<QRect> getSortedRectsToScroll(const QRegion &region, int dx, int dy)
-{
- QVector<QRect> rects;
- std::copy(region.begin(), region.end(), std::back_inserter(rects));
- if (rects.count() > 1) {
- std::sort(rects.begin(), rects.end(), [=](const QRect &r1, const QRect &r2) {
- if (r1.y() == r2.y()) {
- if (dx > 0)
- return r1.x() > r2.x();
- return r1.x() < r2.x();
- }
- if (dy > 0)
- return r1.y() > r2.y();
- return r1.y() < r2.y();
- });
- }
- return rects;
-}
-
//parent's coordinates; move whole rect; update parent and widget
//assume the screen blt has already been done, so we don't need to refresh that part
void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
@@ -445,16 +386,13 @@ void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
return;
QWidget *tlw = q->window();
- QTLWExtra* x = tlw->d_func()->topData();
- if (x->inTopLevelResize)
- return;
static const bool accelEnv = qEnvironmentVariableIntValue("QT_NO_FAST_MOVE") == 0;
- QWidget *pw = q->parentWidget();
- QPoint toplevelOffset = pw->mapTo(tlw, QPoint());
- QWidgetPrivate *pd = pw->d_func();
- QRect clipR(pd->clipRect());
+ QWidget *parentWidget = q->parentWidget();
+ QPoint toplevelOffset = parentWidget->mapTo(tlw, QPoint());
+ QWidgetPrivate *parentPrivate = parentWidget->d_func();
+ const QRect clipR(parentPrivate->clipRect());
const QRect newRect(rect.translated(dx, dy));
QRect destRect = rect.intersected(clipR);
if (destRect.isValid())
@@ -463,60 +401,40 @@ void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
const QRect parentRect(rect & clipR);
const bool nativeWithTextureChild = textureChildSeen && hasPlatformWindow(q);
- const bool accelerateMove = accelEnv && isOpaque && !nativeWithTextureChild
+ bool accelerateMove = accelEnv && isOpaque && !nativeWithTextureChild && sourceRect.isValid()
#if QT_CONFIG(graphicsview)
// No accelerate move for proxy widgets.
&& !tlw->d_func()->extra->proxyWidget
#endif
- ;
+ && !isOverlapped(sourceRect) && !isOverlapped(destRect);
if (!accelerateMove) {
- QRegion parentR(effectiveRectFor(parentRect));
+ QRegion parentRegion(effectiveRectFor(parentRect));
if (!extra || !extra->hasMask) {
- parentR -= newRect;
+ parentRegion -= newRect;
} else {
// invalidateBackingStore() excludes anything outside the mask
- parentR += newRect & clipR;
+ parentRegion += newRect & clipR;
}
- pd->invalidateBackingStore(parentR);
+ parentPrivate->invalidateBackingStore(parentRegion);
invalidateBackingStore((newRect & clipR).translated(-data.crect.topLeft()));
} else {
-
- QWidgetRepaintManager *repaintManager = x->repaintManager.get();
+ QWidgetRepaintManager *repaintManager = QWidgetPrivate::get(tlw)->maybeRepaintManager();
+ Q_ASSERT(repaintManager);
QRegion childExpose(newRect & clipR);
- QRegion overlappedExpose;
- if (sourceRect.isValid()) {
- overlappedExpose = (overlappedRegion(sourceRect) | overlappedRegion(destRect)) & clipR;
-
- const qreal factor = QHighDpiScaling::factor(q->windowHandle());
- if (overlappedExpose.isEmpty() || qFloor(factor) == factor) {
- const QVector<QRect> rectsToScroll
- = getSortedRectsToScroll(QRegion(sourceRect) - overlappedExpose, dx, dy);
- for (QRect rect : rectsToScroll) {
- if (repaintManager->bltRect(rect, dx, dy, pw)) {
- childExpose -= rect.translated(dx, dy);
- }
- }
- }
+ if (repaintManager->bltRect(sourceRect, dx, dy, parentWidget))
+ childExpose -= destRect;
- childExpose -= overlappedExpose;
- }
-
- if (!pw->updatesEnabled())
+ if (!parentWidget->updatesEnabled())
return;
const bool childUpdatesEnabled = q->updatesEnabled();
- if (childUpdatesEnabled) {
- if (!overlappedExpose.isEmpty()) {
- overlappedExpose.translate(-data.crect.topLeft());
- invalidateBackingStore(overlappedExpose);
- }
- if (!childExpose.isEmpty()) {
- childExpose.translate(-data.crect.topLeft());
- repaintManager->markDirty(childExpose, q);
- isMoved = true;
- }
+
+ if (childUpdatesEnabled && !childExpose.isEmpty()) {
+ childExpose.translate(-data.crect.topLeft());
+ repaintManager->markDirty(childExpose, q);
+ isMoved = true;
}
QRegion parentExpose(parentRect);
@@ -525,14 +443,14 @@ void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
parentExpose += QRegion(newRect) - extra->mask.translated(data.crect.topLeft());
if (!parentExpose.isEmpty()) {
- repaintManager->markDirty(parentExpose, pw);
- pd->isMoved = true;
+ repaintManager->markDirty(parentExpose, parentWidget);
+ parentPrivate->isMoved = true;
}
if (childUpdatesEnabled) {
QRegion needsFlush(sourceRect);
needsFlush += destRect;
- repaintManager->markNeedsFlush(pw, needsFlush, toplevelOffset);
+ repaintManager->markNeedsFlush(parentWidget, needsFlush, toplevelOffset);
}
}
}
@@ -542,22 +460,20 @@ void QWidgetPrivate::scrollRect(const QRect &rect, int dx, int dy)
{
Q_Q(QWidget);
QWidget *tlw = q->window();
- QTLWExtra* x = tlw->d_func()->topData();
- if (x->inTopLevelResize)
- return;
- QWidgetRepaintManager *repaintManager = x->repaintManager.get();
+ QWidgetRepaintManager *repaintManager = QWidgetPrivate::get(tlw)->maybeRepaintManager();
if (!repaintManager)
return;
static const bool accelEnv = qEnvironmentVariableIntValue("QT_NO_FAST_SCROLL") == 0;
- const QRect clipR = clipRect();
- const QRect scrollRect = rect & clipR;
- const bool accelerateScroll = accelEnv && isOpaque && !q_func()->testAttribute(Qt::WA_WState_InPaintEvent);
+ const QRect scrollRect = rect & clipRect();
+ bool overlapped = false;
+ bool accelerateScroll = accelEnv && isOpaque && !q_func()->testAttribute(Qt::WA_WState_InPaintEvent)
+ && !(overlapped = isOverlapped(scrollRect.translated(data.crect.topLeft())));
if (!accelerateScroll) {
- if (!overlappedRegion(scrollRect.translated(data.crect.topLeft()), true).isEmpty()) {
+ if (overlapped) {
QRegion region(scrollRect);
subtractOpaqueSiblings(region);
invalidateBackingStore(region);
@@ -569,23 +485,12 @@ void QWidgetPrivate::scrollRect(const QRect &rect, int dx, int dy)
const QRect destRect = scrollRect.translated(dx, dy) & scrollRect;
const QRect sourceRect = destRect.translated(-dx, -dy);
- const QRegion overlappedExpose = (overlappedRegion(scrollRect.translated(data.crect.topLeft())))
- .translated(-data.crect.topLeft()) & clipR;
QRegion childExpose(scrollRect);
-
- const qreal factor = QHighDpiScaling::factor(q->windowHandle());
- if (overlappedExpose.isEmpty() || qFloor(factor) == factor) {
- const QVector<QRect> rectsToScroll
- = getSortedRectsToScroll(QRegion(sourceRect) - overlappedExpose, dx, dy);
- for (const QRect &rect : rectsToScroll) {
- if (repaintManager->bltRect(rect, dx, dy, q)) {
- childExpose -= rect.translated(dx, dy);
- }
- }
+ if (sourceRect.isValid()) {
+ if (repaintManager->bltRect(sourceRect, dx, dy, q))
+ childExpose -= destRect;
}
- childExpose -= overlappedExpose;
-
if (inDirtyList) {
if (rect == q->rect()) {
dirty.translate(dx, dy);
@@ -602,8 +507,6 @@ void QWidgetPrivate::scrollRect(const QRect &rect, int dx, int dy)
if (!q->updatesEnabled())
return;
- if (!overlappedExpose.isEmpty())
- invalidateBackingStore(overlappedExpose);
if (!childExpose.isEmpty()) {
repaintManager->markDirty(childExpose, q);
isScrolled = true;
@@ -631,14 +534,16 @@ bool QWidgetRepaintManager::bltRect(const QRect &rect, int dx, int dy, QWidget *
// ---------------------------------------------------------------------------
-#ifndef QT_NO_OPENGL
-static void findTextureWidgetsRecursively(QWidget *tlw, QWidget *widget, QPlatformTextureList *widgetTextures, QVector<QWidget *> *nativeChildren)
+static void findTextureWidgetsRecursively(QWidget *tlw, QWidget *widget,
+ QPlatformTextureList *widgetTextures,
+ QList<QWidget *> *nativeChildren)
{
QWidgetPrivate *wd = QWidgetPrivate::get(widget);
if (wd->renderToTexture) {
QPlatformTextureList::Flags flags = wd->textureListFlags();
const QRect rect(widget->mapTo(tlw, QPoint()), widget->size());
- widgetTextures->appendTexture(widget, wd->textureId(), rect, wd->clipRect(), flags);
+ QWidgetPrivate::TextureData data = wd->texture();
+ widgetTextures->appendTexture(widget, data.textureLeft, data.textureRight, rect, wd->clipRect(), flags);
}
for (int i = 0; i < wd->children.size(); ++i) {
@@ -655,8 +560,8 @@ static void findAllTextureWidgetsRecursively(QWidget *tlw, QWidget *widget)
{
// textureChildSeen does not take native child widgets into account and that's good.
if (QWidgetPrivate::get(widget)->textureChildSeen) {
- QVector<QWidget *> nativeChildren;
- auto tl = qt_make_unique<QPlatformTextureList>();
+ QList<QWidget *> nativeChildren;
+ auto tl = std::make_unique<QPlatformTextureList>();
// Look for texture widgets (incl. widget itself) from 'widget' down,
// but skip subtrees with a parent of a native child widget.
findTextureWidgetsRecursively(tlw, widget, tl.get(), &nativeChildren);
@@ -664,7 +569,7 @@ static void findAllTextureWidgetsRecursively(QWidget *tlw, QWidget *widget)
if (!tl->isEmpty())
QWidgetPrivate::get(tlw)->topData()->widgetTextures.push_back(std::move(tl));
// Native child widgets, if there was any, get their own separate QPlatformTextureList.
- for (QWidget *ncw : qAsConst(nativeChildren)) {
+ for (QWidget *ncw : std::as_const(nativeChildren)) {
if (QWidgetPrivate::get(ncw)->textureChildSeen)
findAllTextureWidgetsRecursively(tlw, ncw);
}
@@ -682,33 +587,12 @@ static QPlatformTextureList *widgetTexturesFor(QWidget *tlw, QWidget *widget)
}
}
- if (QWidgetPrivate::get(widget)->textureChildSeen) {
- // No render-to-texture widgets in the (sub-)tree due to hidden or native
- // children. Returning null results in using the normal backingstore flush path
- // without OpenGL-based compositing. This is very desirable normally. However,
- // some platforms cannot handle switching between the non-GL and GL paths for
- // their windows so it has to be opt-in.
- static bool switchableWidgetComposition =
- QGuiApplicationPrivate::instance()->platformIntegration()
- ->hasCapability(QPlatformIntegration::SwitchableWidgetComposition);
- if (!switchableWidgetComposition)
- return qt_dummy_platformTextureList();
- }
+ if (QWidgetPrivate::get(widget)->textureChildSeen)
+ return qt_dummy_platformTextureList();
return nullptr;
}
-#else
-
-static QPlatformTextureList *widgetTexturesFor(QWidget *tlw, QWidget *widget)
-{
- Q_UNUSED(tlw);
- Q_UNUSED(widget);
- return nullptr;
-}
-
-#endif // QT_NO_OPENGL
-
// ---------------------------------------------------------------------------
/*!
@@ -722,8 +606,7 @@ void QWidgetRepaintManager::sync(QWidget *exposedWidget, const QRegion &exposedR
{
qCInfo(lcWidgetPainting) << "Syncing" << exposedRegion << "of" << exposedWidget;
- QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
- if (!tlw->isVisible() || !tlwExtra || tlwExtra->inTopLevelResize)
+ if (!tlw->isVisible())
return;
if (!exposedWidget || !hasPlatformWindow(exposedWidget)
@@ -784,7 +667,6 @@ bool QWidgetPrivate::shouldDiscardSyncRequest() const
bool QWidgetRepaintManager::syncAllowed()
{
-#ifndef QT_NO_OPENGL
QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
if (textureListWatcher && !textureListWatcher->isLocked()) {
textureListWatcher->deleteLater();
@@ -803,10 +685,21 @@ bool QWidgetRepaintManager::syncAllowed()
if (skipSync) // cannot compose due to widget textures being in use
return false;
}
-#endif
return true;
}
+static bool isDrawnInEffect(const QWidget *w)
+{
+#if QT_CONFIG(graphicseffect)
+ do {
+ if (w->graphicsEffect())
+ return true;
+ w = w->parentWidget();
+ } while (w);
+#endif
+ return false;
+}
+
void QWidgetRepaintManager::paintAndFlush()
{
qCInfo(lcWidgetPainting) << "Painting and flushing dirty"
@@ -815,13 +708,13 @@ void QWidgetRepaintManager::paintAndFlush()
const bool updatesDisabled = !tlw->updatesEnabled();
bool repaintAllWidgets = false;
- const bool inTopLevelResize = tlw->d_func()->maybeTopData()->inTopLevelResize;
const QRect tlwRect = tlw->data->crect;
- const QRect surfaceGeometry(tlwRect.topLeft(), store->size());
- if ((inTopLevelResize || surfaceGeometry.size() != tlwRect.size()) && !updatesDisabled) {
- if (hasStaticContents() && !store->size().isEmpty() ) {
+ if (!updatesDisabled && store->size() != tlwRect.size()) {
+ QPlatformIntegration *integration = QGuiApplicationPrivate::platformIntegration();
+ if (hasStaticContents() && !store->size().isEmpty()
+ && integration->hasCapability(QPlatformIntegration::BackingStoreStaticContents)) {
// Repaint existing dirty area and newly visible area.
- const QRect clipRect(0, 0, surfaceGeometry.width(), surfaceGeometry.height());
+ const QRect clipRect(QPoint(0, 0), store->size());
const QRegion staticRegion(staticContents(nullptr, clipRect));
QRegion newVisible(0, 0, tlwRect.width(), tlwRect.height());
newVisible -= staticRegion;
@@ -837,7 +730,7 @@ void QWidgetRepaintManager::paintAndFlush()
}
}
- if (inTopLevelResize || surfaceGeometry.size() != tlwRect.size())
+ if (store->size() != tlwRect.size())
store->resize(tlwRect.size());
if (updatesDisabled)
@@ -896,7 +789,8 @@ void QWidgetRepaintManager::paintAndFlush()
}
#endif
- if (!hasDirtySiblingsAbove && wd->isOpaque && !dirty.intersects(widgetDirty.boundingRect())) {
+ if (!isDrawnInEffect(w) && !hasDirtySiblingsAbove && wd->isOpaque
+ && !dirty.intersects(widgetDirty.boundingRect())) {
opaqueNonOverlappedWidgets.append(w);
} else {
resetWidget(w);
@@ -905,24 +799,21 @@ void QWidgetRepaintManager::paintAndFlush()
}
dirtyWidgets.clear();
-#ifndef QT_NO_OPENGL
// Find all render-to-texture child widgets (including self).
// The search is cut at native widget boundaries, meaning that each native child widget
// has its own list for the subtree below it.
QTLWExtra *tlwExtra = tlw->d_func()->topData();
tlwExtra->widgetTextures.clear();
findAllTextureWidgetsRecursively(tlw, tlw);
- qt_window_private(tlw->windowHandle())->compositing = false; // will get updated in flush()
-#endif
if (toClean.isEmpty()) {
// Nothing to repaint. However renderToTexture widgets are handled
// specially, they are not in the regular dirty list, in order to
// prevent triggering unnecessary backingstore painting when only the
- // OpenGL content changes. Check if we have such widgets in the special
+ // texture content changes. Check if we have such widgets in the special
// dirty list.
QVarLengthArray<QWidget *, 16> paintPending;
- const int numPaintPending = dirtyRenderToTextureWidgets.count();
+ const int numPaintPending = dirtyRenderToTextureWidgets.size();
paintPending.reserve(numPaintPending);
for (int i = 0; i < numPaintPending; ++i) {
QWidget *w = dirtyRenderToTextureWidgets.at(i);
@@ -951,7 +842,6 @@ void QWidgetRepaintManager::paintAndFlush()
return;
}
-#ifndef QT_NO_OPENGL
for (const auto &tl : tlwExtra->widgetTextures) {
for (int i = 0; i < tl->count(); ++i) {
QWidget *w = static_cast<QWidget *>(tl->source(i));
@@ -965,10 +855,9 @@ void QWidgetRepaintManager::paintAndFlush()
}
}
}
- for (int i = 0; i < dirtyRenderToTextureWidgets.count(); ++i)
+ for (int i = 0; i < dirtyRenderToTextureWidgets.size(); ++i)
resetWidget(dirtyRenderToTextureWidgets.at(i));
dirtyRenderToTextureWidgets.clear();
-#endif
#if QT_CONFIG(graphicsview)
if (tlw->d_func()->extra->proxyWidget) {
@@ -1013,7 +902,8 @@ void QWidgetRepaintManager::paintAndFlush()
// Paint the rest with composition.
if (repaintAllWidgets || !dirtyCopy.isEmpty()) {
- QWidgetPrivate::DrawWidgetFlags flags = QWidgetPrivate::DrawAsRoot | QWidgetPrivate::DrawRecursive;
+ QWidgetPrivate::DrawWidgetFlags flags = QWidgetPrivate::DrawAsRoot | QWidgetPrivate::DrawRecursive
+ | QWidgetPrivate::UseEffectRegionBounds;
tlw->d_func()->drawWidget(store->paintDevice(), dirtyCopy, QPoint(), flags, nullptr, this);
}
@@ -1094,18 +984,16 @@ void QWidgetRepaintManager::flush()
// Render-to-texture widgets are not in topLevelNeedsFlush so flush if we have not done it above.
if (!flushed && !hasNeedsFlushWidgets) {
-#ifndef QT_NO_OPENGL
if (!tlw->d_func()->topData()->widgetTextures.empty()) {
if (QPlatformTextureList *widgetTextures = widgetTexturesFor(tlw, tlw))
flush(tlw, QRegion(), widgetTextures);
}
-#endif
}
if (!hasNeedsFlushWidgets)
return;
- for (QWidget *w : qExchange(needsFlushWidgets, {})) {
+ for (QWidget *w : std::exchange(needsFlushWidgets, {})) {
QWidgetPrivate *wd = w->d_func();
Q_ASSERT(wd->needsFlush);
QPlatformTextureList *widgetTexturesForNative = wd->textureChildSeen ? widgetTexturesFor(tlw, w) : nullptr;
@@ -1121,12 +1009,7 @@ void QWidgetRepaintManager::flush()
*/
void QWidgetRepaintManager::flush(QWidget *widget, const QRegion &region, QPlatformTextureList *widgetTextures)
{
-#ifdef QT_NO_OPENGL
- Q_UNUSED(widgetTextures);
- Q_ASSERT(!region.isEmpty());
-#else
Q_ASSERT(!region.isEmpty() || widgetTextures);
-#endif
Q_ASSERT(widget);
Q_ASSERT(tlw);
@@ -1139,8 +1022,6 @@ void QWidgetRepaintManager::flush(QWidget *widget, const QRegion &region, QPlatf
return;
}
- qCInfo(lcWidgetPainting) << "Flushing" << region << "of" << widget;
-
static bool fpsDebug = qEnvironmentVariableIntValue("QT_DEBUG_FPS");
if (fpsDebug) {
if (!perfFrames++)
@@ -1156,40 +1037,70 @@ void QWidgetRepaintManager::flush(QWidget *widget, const QRegion &region, QPlatf
if (widget != tlw)
offset += widget->mapTo(tlw, QPoint());
- QRegion effectiveRegion = region;
-#ifndef QT_NO_OPENGL
- const bool compositionWasActive = widget->d_func()->renderToTextureComposeActive;
- if (!widgetTextures) {
- widget->d_func()->renderToTextureComposeActive = false;
- // Detect the case of falling back to the normal flush path when no
- // render-to-texture widgets are visible anymore. We will force one
- // last flush to go through the OpenGL-based composition to prevent
- // artifacts. The next flush after this one will use the normal path.
- if (compositionWasActive)
+ // 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
+ << "to window" << widget->windowHandle();
+ if (!widgetTextures)
widgetTextures = qt_dummy_platformTextureList;
- } else {
- widget->d_func()->renderToTextureComposeActive = true;
- }
- // When changing the composition status, make sure the dirty region covers
- // the entire widget. Just having e.g. the shown/hidden render-to-texture
- // widget's area marked as dirty is incorrect when changing flush paths.
- if (compositionWasActive != widget->d_func()->renderToTextureComposeActive)
- effectiveRegion = widget->rect();
-
- // re-test since we may have been forced to this path via the dummy texture list above
- if (widgetTextures) {
- qt_window_private(tlw->windowHandle())->compositing = true;
- widget->window()->d_func()->sendComposeStatus(widget->window(), false);
+
+ QWidgetPrivate *widgetWindowPrivate = widget->window()->d_func();
+ widgetWindowPrivate->sendComposeStatus(widget->window(), false);
// A window may have alpha even when the app did not request
// WA_TranslucentBackground. Therefore the compositor needs to know whether the app intends
// to rely on translucency, in order to decide if it should clear to transparent or opaque.
const bool translucentBackground = widget->testAttribute(Qt::WA_TranslucentBackground);
- store->handle()->composeAndFlush(widget->windowHandle(), effectiveRegion, offset,
- widgetTextures, translucentBackground);
- widget->window()->d_func()->sendComposeStatus(widget->window(), true);
- } else
-#endif
- store->flush(effectiveRegion, widget->windowHandle(), offset);
+
+ QPlatformBackingStore::FlushResult flushResult;
+ flushResult = store->handle()->rhiFlush(widget->windowHandle(),
+ widget->devicePixelRatio(),
+ region,
+ offset,
+ widgetTextures,
+ 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 {
+ qCInfo(lcWidgetPainting) << "Flushing" << region << "of" << widget;
+ store->flush(region, widget->windowHandle(), offset);
+ }
}
// ---------------------------------------------------------------------------
@@ -1233,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
}
/*!
@@ -1248,11 +1155,10 @@ bool QWidgetRepaintManager::hasStaticContents() const
QRegion QWidgetRepaintManager::staticContents(QWidget *parent, const QRect &withinClipRect) const
{
if (!parent && tlw->testAttribute(Qt::WA_StaticContents)) {
- const QSize surfaceGeometry(store->size());
- QRect surfaceRect(0, 0, surfaceGeometry.width(), surfaceGeometry.height());
+ QRect backingstoreRect(QPoint(0, 0), store->size());
if (!withinClipRect.isEmpty())
- surfaceRect &= withinClipRect;
- return QRegion(surfaceRect);
+ backingstoreRect &= withinClipRect;
+ return QRegion(backingstoreRect);
}
QRegion region;
@@ -1260,7 +1166,7 @@ QRegion QWidgetRepaintManager::staticContents(QWidget *parent, const QRect &with
return region;
const bool clipToRect = !withinClipRect.isEmpty();
- const int count = staticWidgets.count();
+ const int count = staticWidgets.size();
for (int i = 0; i < count; ++i) {
QWidget *w = staticWidgets.at(i);
QWidgetPrivate *wd = w->d_func();
@@ -1402,6 +1308,12 @@ void QWidgetPrivate::invalidateBackingStore_resizeHelper(const QPoint &oldPos, c
}
}
+QRhi *QWidgetRepaintManager::rhi() const
+{
+ return store->handle()->rhi();
+}
+
QT_END_NAMESPACE
#include "qwidgetrepaintmanager.moc"
+#include "moc_qwidgetrepaintmanager_p.cpp"
diff --git a/src/widgets/kernel/qwidgetrepaintmanager_p.h b/src/widgets/kernel/qwidgetrepaintmanager_p.h
index 58687383f4..4378974610 100644
--- a/src/widgets/kernel/qwidgetrepaintmanager_p.h
+++ b/src/widgets/kernel/qwidgetrepaintmanager_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIDGETREPAINTMANAGER_P_H
#define QWIDGETREPAINTMANAGER_P_H
@@ -62,8 +26,10 @@ QT_BEGIN_NAMESPACE
class QPlatformTextureList;
class QPlatformTextureListWatcher;
class QWidgetRepaintManager;
+class QRhi;
+class QRhiSwapChain;
-class Q_AUTOTEST_EXPORT QWidgetRepaintManager
+class Q_WIDGETS_EXPORT QWidgetRepaintManager
{
Q_GADGET
public:
@@ -100,9 +66,14 @@ public:
void moveStaticWidgets(QWidget *reparented);
void removeStaticWidget(QWidget *widget);
QRegion staticContents(QWidget *widget = nullptr, const QRect &withinClipRect = QRect()) const;
+ QRegion dirtyRegion() const { return dirty; }
+ QList<QWidget *> dirtyWidgetList() const { return dirtyWidgets; }
+ bool isDirty() const;
bool bltRect(const QRect &rect, int dx, int dy, QWidget *widget);
+ QRhi *rhi() const;
+
private:
void updateLists(QWidget *widget);
@@ -121,8 +92,6 @@ private:
void flush();
void flush(QWidget *widget, const QRegion &region, QPlatformTextureList *widgetTextures);
- bool isDirty() const;
-
bool hasStaticContents() const;
void updateStaticContentsSize();
@@ -130,11 +99,11 @@ private:
QBackingStore *store = nullptr;
QRegion dirty; // needsRepaint
- QVector<QWidget *> dirtyWidgets;
- QVector<QWidget *> dirtyRenderToTextureWidgets;
+ QList<QWidget *> dirtyWidgets;
+ QList<QWidget *> dirtyRenderToTextureWidgets;
QRegion topLevelNeedsFlush;
- QVector<QWidget *> needsFlushWidgets;
+ QList<QWidget *> needsFlushWidgets;
QList<QWidget *> staticWidgets;
diff --git a/src/widgets/kernel/qwidgetsvariant.cpp b/src/widgets/kernel/qwidgetsvariant.cpp
index 41600d2143..17a19aa780 100644
--- a/src/widgets/kernel/qwidgetsvariant.cpp
+++ b/src/widgets/kernel/qwidgetsvariant.cpp
@@ -1,161 +1,36 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qvariant.h"
#include "qsizepolicy.h"
#include "qwidget.h"
-#include "private/qvariant_p.h"
#include <private/qmetatype_p.h>
QT_BEGIN_NAMESPACE
namespace {
-static void construct(QVariant::Private *x, const void *copy)
-{
- switch (x->type) {
- case QVariant::SizePolicy:
- v_construct<QSizePolicy>(x, copy);
- break;
- default:
- qWarning("Trying to construct an instance of an invalid type, type id: %i", x->type);
- x->type = QVariant::Invalid;
- return;
- }
- x->is_null = !copy;
-}
-static void clear(QVariant::Private *d)
+// NOLINTNEXTLINE(cppcoreguidelines-virtual-class-destructor): this is not a base class
+static constexpr struct : QMetaTypeModuleHelper
{
- switch (d->type) {
- case QVariant::SizePolicy:
- v_clear<QSizePolicy>(d);
- break;
- default:
- Q_ASSERT(false);
- return;
+ const QtPrivate::QMetaTypeInterface *interfaceForType(int type) const override {
+ switch (type) {
+ QT_FOR_EACH_STATIC_WIDGETS_CLASS(QT_METATYPE_CONVERT_ID_TO_TYPE)
+ default: return nullptr;
+ }
}
+} qVariantWidgetsHelper;
- d->type = QVariant::Invalid;
- d->is_null = true;
- d->is_shared = false;
-}
-
-
-static bool isNull(const QVariant::Private *)
-{
- return false;
-}
-
-static bool compare(const QVariant::Private *a, const QVariant::Private *b)
-{
- Q_ASSERT(a->type == b->type);
- switch(a->type) {
- case QVariant::SizePolicy:
- return *v_cast<QSizePolicy>(a) == *v_cast<QSizePolicy>(b);
- default:
- Q_ASSERT(false);
- }
- return false;
-}
-
-static bool convert(const QVariant::Private *d, int type, void *result, bool *ok)
-{
- Q_UNUSED(d);
- Q_UNUSED(type);
- Q_UNUSED(result);
- if (ok)
- *ok = false;
- return false;
-}
-
-#if !defined(QT_NO_DEBUG_STREAM)
-static void streamDebug(QDebug dbg, const QVariant &v)
-{
- QVariant::Private *d = const_cast<QVariant::Private *>(&v.data_ptr());
- switch (d->type) {
- case QVariant::SizePolicy:
- dbg.nospace() << *v_cast<QSizePolicy>(d);
- break;
- default:
- dbg.nospace() << "QMetaType::Type(" << d->type << ')';
- }
-}
-#endif
-
-static const QVariant::Handler widgets_handler = {
- construct,
- clear,
- isNull,
-#ifndef QT_NO_DATASTREAM
- nullptr,
- nullptr,
-#endif
- compare,
- convert,
- nullptr,
-#if !defined(QT_NO_DEBUG_STREAM)
- streamDebug
-#else
- 0
-#endif
-};
-
-#define QT_IMPL_METATYPEINTERFACE_WIDGETS_TYPES(MetaTypeName, MetaTypeId, RealName) \
- QT_METATYPE_INTERFACE_INIT(RealName),
-
-static const QMetaTypeInterface qVariantWidgetsHelper[] = {
- QT_FOR_EACH_STATIC_WIDGETS_CLASS(QT_IMPL_METATYPEINTERFACE_WIDGETS_TYPES)
-};
#undef QT_IMPL_METATYPEINTERFACE_WIDGETS_TYPES
} // namespace
-extern Q_CORE_EXPORT const QMetaTypeInterface *qMetaTypeWidgetsHelper;
-
void qRegisterWidgetsVariant()
{
- qRegisterMetaType<QWidget*>();
- qMetaTypeWidgetsHelper = qVariantWidgetsHelper;
- QVariantPrivate::registerHandler(QModulesPrivate::Widgets, &widgets_handler);
+ qMetaTypeWidgetsHelper = &qVariantWidgetsHelper;
}
Q_CONSTRUCTOR_FUNCTION(qRegisterWidgetsVariant)
diff --git a/src/widgets/kernel/qwidgetwindow.cpp b/src/widgets/kernel/qwidgetwindow.cpp
index 904067afda..f51baba88b 100644
--- a/src/widgets/kernel/qwidgetwindow.cpp
+++ b/src/widgets/kernel/qwidgetwindow.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 "private/qwindow_p.h"
#include "qwidgetwindow_p.h"
@@ -43,7 +7,7 @@
#include "private/qwidget_p.h"
#include "private/qapplication_p.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include <QtGui/qaccessible.h>
#endif
#include <private/qwidgetrepaintmanager_p.h>
@@ -55,6 +19,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
Q_WIDGETS_EXPORT extern bool qt_tab_all_widgets();
Q_WIDGETS_EXPORT QWidget *qt_button_down = nullptr; // widget got last button-down
@@ -62,6 +28,7 @@ Q_WIDGETS_EXPORT QWidget *qt_button_down = nullptr; // widget got last button-do
// popup control
QWidget *qt_popup_down = nullptr; // popup that contains the pressed widget
extern int openPopupCount;
+bool qt_popup_down_closed = false; // qt_popup_down has been closed
bool qt_replay_popup_mouse_event = false;
extern bool qt_try_modal(QWidget *widget, QEvent::Type type);
@@ -72,18 +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 wasHidden = widget->testAttribute(Qt::WA_WState_Hidden);
- QWidgetPrivate::get(widget)->setVisible(visible);
- if (!wasHidden)
- widget->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- } 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 {
@@ -104,9 +78,6 @@ public:
}
QRectF closestAcceptableGeometry(const QRectF &rect) const override;
-#if QT_CONFIG(opengl)
- QOpenGLContext *shareContext() const override;
-#endif
void processSafeAreaMarginsChanged() override
{
@@ -114,7 +85,9 @@ public:
if (QWidget *widget = q->widget())
QWidgetPrivate::get(widget)->updateContentsRect();
}
- bool allowClickThrough(const QPoint &) const override;
+
+ bool participatesInLastWindowClosed() const override;
+ bool treatAsVisible() const override;
};
QRectF QWidgetWindowPrivate::closestAcceptableGeometry(const QRectF &rect) const
@@ -146,35 +119,43 @@ QRectF QWidgetWindowPrivate::closestAcceptableGeometry(const QRectF &rect) const
return result;
}
-#if QT_CONFIG(opengl)
-QOpenGLContext *QWidgetWindowPrivate::shareContext() const
-{
- Q_Q(const QWidgetWindow);
- const QWidgetPrivate *widgetPrivate = QWidgetPrivate::get(q->widget());
- return widgetPrivate->shareContext();
-}
-#endif // opengl
+bool q_evaluateRhiConfig(const QWidget *w, QPlatformBackingStoreRhiConfig *outConfig, QSurface::SurfaceType *outType);
QWidgetWindow::QWidgetWindow(QWidget *widget)
: QWindow(*new QWidgetWindowPrivate(), nullptr)
, m_widget(widget)
{
updateObjectName();
- // Enable QOpenGLWidget/QQuickWidget children if the platform plugin supports it,
- // and the application developer has not explicitly disabled it.
- if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RasterGLSurface)
- && !QCoreApplication::testAttribute(Qt::AA_ForceRasterWidgets)) {
- setSurfaceType(QSurface::RasterGLSurface);
+ if (!QCoreApplication::testAttribute(Qt::AA_ForceRasterWidgets)) {
+ QSurface::SurfaceType type = QSurface::RasterSurface;
+ q_evaluateRhiConfig(m_widget, nullptr, &type);
+ setSurfaceType(type);
}
+
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;
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleInterface *QWidgetWindow::accessibleRoot() const
{
if (m_widget)
@@ -208,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.
@@ -224,36 +208,20 @@ static inline bool shouldBePropagatedToWidget(QEvent *event)
case QEvent::DynamicPropertyChange:
case QEvent::ChildAdded:
case QEvent::ChildRemoved:
+ case QEvent::Paint:
+ case QEvent::Close: // Propagated manually in closeEvent
return false;
default:
return true;
}
}
-bool QWidgetWindowPrivate::allowClickThrough(const QPoint &) const
-{
- return true;
-}
-
bool QWidgetWindow::event(QEvent *event)
{
if (!m_widget)
return QWindow::event(event);
- if (m_widget->testAttribute(Qt::WA_DontShowOnScreen)) {
- // \a event is uninteresting for QWidgetWindow, the event was probably
- // generated before WA_DontShowOnScreen was set
- if (!shouldBePropagatedToWidget(event))
- return true;
- return QCoreApplication::forwardEvent(m_widget, event);
- }
-
switch (event->type()) {
- case QEvent::Close:
- handleCloseEvent(static_cast<QCloseEvent *>(event));
- QWindow::event(event);
- return true;
-
case QEvent::Enter:
case QEvent::Leave:
handleEnterLeaveEvent(event);
@@ -265,7 +233,7 @@ bool QWidgetWindow::event(QEvent *event)
handleFocusInEvent(static_cast<QFocusEvent *>(event));
Q_FALLTHROUGH();
case QEvent::FocusOut: {
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessible::State state;
state.active = true;
QAccessibleStateChangeEvent ev(m_widget, state);
@@ -383,6 +351,10 @@ bool QWidgetWindow::event(QEvent *event)
m_widget->repaint();
return true;
+ case QEvent::DevicePixelRatioChange:
+ handleDevicePixelRatioChange();
+ break;
+
default:
break;
}
@@ -397,14 +369,13 @@ QPointer<QWidget> qt_last_mouse_receiver = nullptr;
void QWidgetWindow::handleEnterLeaveEvent(QEvent *event)
{
-#if !defined(Q_OS_OSX) && !defined(Q_OS_IOS) // Cocoa tracks popups
// Ignore all enter/leave events from QPA if we are not on the first-level context menu.
// This prevents duplicated events on most platforms. Fake events will be delivered in
// QWidgetWindow::handleMouseEvent(QMouseEvent *). Make an exception whether the widget
// is already under mouse - let the mouse leave.
if (QApplicationPrivate::inPopupMode() && m_widget != QApplication::activePopupWidget() && !m_widget->underMouse())
return;
-#endif
+
if (event->type() == QEvent::Leave) {
QWidget *enter = nullptr;
// Check from window system event queue if the next queued enter targets a window
@@ -413,7 +384,7 @@ void QWidgetWindow::handleEnterLeaveEvent(QEvent *event)
QWindowSystemInterfacePrivate::EnterEvent *systemEvent =
static_cast<QWindowSystemInterfacePrivate::EnterEvent *>
(QWindowSystemInterfacePrivate::peekWindowSystemEvent(QWindowSystemInterfacePrivate::Enter));
- const QPointF globalPosF = systemEvent ? systemEvent->globalPos : QGuiApplicationPrivate::lastCursorPosition;
+ const QPointF globalPosF = systemEvent ? systemEvent->globalPos : QPointF(QGuiApplicationPrivate::lastCursorPosition);
if (systemEvent) {
if (QWidgetWindow *enterWindow = qobject_cast<QWidgetWindow *>(systemEvent->enter))
{
@@ -444,7 +415,7 @@ void QWidgetWindow::handleEnterLeaveEvent(QEvent *event)
}
} else {
const QEnterEvent *ee = static_cast<QEnterEvent *>(event);
- QWidget *child = m_widget->childAt(ee->pos());
+ QWidget *child = m_widget->childAt(ee->position().toPoint());
QWidget *receiver = child ? child : m_widget.data();
QWidget *leave = nullptr;
if (QApplicationPrivate::inPopupMode() && receiver == m_widget
@@ -453,7 +424,7 @@ void QWidgetWindow::handleEnterLeaveEvent(QEvent *event)
// action on first-level menu.
leave = qt_last_mouse_receiver;
}
- QApplicationPrivate::dispatchEnterLeave(receiver, leave, ee->screenPos());
+ QApplicationPrivate::dispatchEnterLeave(receiver, leave, ee->globalPosition());
qt_last_mouse_receiver = receiver;
}
}
@@ -505,12 +476,12 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::ContextMenuOnMouseRelease).toBool() ?
QEvent::MouseButtonRelease : QEvent::MouseButtonPress;
if (QApplicationPrivate::inPopupMode()) {
- QWidget *activePopupWidget = QApplication::activePopupWidget();
- QPoint mapped = event->pos();
+ QPointer<QWidget> activePopupWidget = QApplication::activePopupWidget();
+ QPointF mapped = event->position();
if (activePopupWidget != m_widget)
- mapped = activePopupWidget->mapFromGlobal(event->globalPos());
+ 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;
@@ -522,6 +493,7 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
case QEvent::MouseButtonDblClick:
qt_button_down = popupChild;
qt_popup_down = activePopupWidget;
+ qt_popup_down_closed = false;
break;
case QEvent::MouseButtonRelease:
releaseAfter = true;
@@ -536,38 +508,39 @@ 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->globalPos());
+ widgetPos = receiver->mapFromGlobal(event->globalPosition());
-#if !defined(Q_OS_OSX) && !defined(Q_OS_IOS) // Cocoa tracks popups
- 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) {
- const QPoint receiverMapped = receiver->mapFromGlobal(event->screenPos().toPoint());
+ const QPoint receiverMapped = receiver->mapFromGlobal(event->globalPosition().toPoint());
// Prevent negative mouse position on enter event - this event
// should be properly handled in "handleEnterLeaveEvent()".
if (receiverMapped.x() >= 0 && receiverMapped.y() >= 0) {
- QApplicationPrivate::dispatchEnterLeave(receiver, nullptr, event->screenPos());
+ QApplicationPrivate::dispatchEnterLeave(receiver, nullptr, event->globalPosition());
qt_last_mouse_receiver = receiver;
}
} else {
- QApplicationPrivate::dispatchEnterLeave(nullptr, qt_last_mouse_receiver, event->screenPos());
+ QApplicationPrivate::dispatchEnterLeave(nullptr, qt_last_mouse_receiver, event->globalPosition());
qt_last_mouse_receiver = receiver;
receiver = activePopupWidget;
}
}
-#endif
- if ((event->type() != QEvent::MouseButtonPress)
- || !(event->flags().testFlag(Qt::MouseEventCreatedDoubleClick))) {
- QMouseEvent e(event->type(), widgetPos, event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers(), event->source());
+ if ((event->type() != QEvent::MouseButtonPress) || !(QMutableSinglePointEvent::from(event)->isDoubleClick())) {
+ // if the widget that was pressed is gone, then deliver move events without buttons
+ const auto buttons = event->type() == QEvent::MouseMove && qt_popup_down_closed
+ ? Qt::NoButton : event->buttons();
+ QMouseEvent e(event->type(), widgetPos, event->scenePosition(), event->globalPosition(),
+ event->button(), buttons, event->modifiers(),
+ event->source(), event->pointingDevice());
e.setTimestamp(event->timestamp());
QApplicationPrivate::sendMouseEvent(receiver, &e, receiver, receiver->window(), &qt_button_down, qt_last_mouse_receiver);
qt_last_mouse_receiver = receiver;
@@ -592,7 +565,7 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
qt_button_down = nullptr;
if (event->type() == QEvent::MouseButtonPress) {
// the popup disappeared, replay the mouse press event
- QWidget *w = QApplication::widgetAt(event->globalPos());
+ QWidget *w = QApplication::widgetAt(event->globalPosition().toPoint());
if (w && !QApplicationPrivate::isBlockedByModal(w)) {
// activate window of the widget under mouse pointer
if (!w->isActiveWindow()) {
@@ -604,10 +577,10 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
const QRect globalGeometry = win->isTopLevel()
? win->geometry()
: QRect(win->mapToGlobal(QPoint(0, 0)), win->size());
- if (globalGeometry.contains(event->globalPos())) {
+ if (globalGeometry.contains(event->globalPosition().toPoint())) {
// Use postEvent() to ensure the local QEventLoop terminates when called from QMenu::exec()
- const QPoint localPos = win->mapFromGlobal(event->globalPos());
- QMouseEvent *e = new QMouseEvent(QEvent::MouseButtonPress, localPos, localPos, event->globalPos(),
+ const QPoint localPos = win->mapFromGlobal(event->globalPosition().toPoint());
+ QMouseEvent *e = new QMouseEvent(QEvent::MouseButtonPress, localPos, localPos, event->globalPosition().toPoint(),
event->button(), event->buttons(), event->modifiers(), event->source());
QCoreApplicationPrivate::setEventSpontaneous(e, true);
e->setTimestamp(event->timestamp());
@@ -624,31 +597,34 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
QWidget *receiver = activePopupWidget;
if (qt_button_down)
receiver = qt_button_down;
- else if(popupChild)
+ else if (popupChild)
receiver = popupChild;
- QContextMenuEvent e(QContextMenuEvent::Mouse, mapped, event->globalPos(), event->modifiers());
+ const QPoint localPos = receiver->mapFromGlobal(event->globalPosition().toPoint());
+ QContextMenuEvent e(QContextMenuEvent::Mouse, localPos, event->globalPosition().toPoint(), event->modifiers());
QApplication::forwardEvent(receiver, &e, event);
}
#else
- Q_UNUSED(contextMenuTrigger)
- Q_UNUSED(oldOpenPopupCount)
+ Q_UNUSED(contextMenuTrigger);
+ Q_UNUSED(oldOpenPopupCount);
}
#endif
if (releaseAfter) {
qt_button_down = nullptr;
+ qt_popup_down_closed = false;
qt_popup_down = nullptr;
}
return;
}
+ qt_popup_down_closed = false;
// modal event handling
if (QApplicationPrivate::instance()->modalState() && !qt_try_modal(m_widget, event->type()))
return;
// which child should have it?
- QWidget *widget = m_widget->childAt(event->pos());
- QPoint mapped = event->pos();
+ QWidget *widget = m_widget->childAt(event->position().toPoint());
+ QPoint mapped = event->position().toPoint();
if (!widget)
widget = m_widget;
@@ -657,18 +633,18 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
if (event->type() == QEvent::MouseButtonPress && initialPress)
qt_button_down = widget;
- QWidget *receiver = QApplicationPrivate::pickMouseReceiver(m_widget, event->windowPos().toPoint(), &mapped, event->type(), event->buttons(),
+ QWidget *receiver = QApplicationPrivate::pickMouseReceiver(m_widget, event->scenePosition().toPoint(), &mapped, event->type(), event->buttons(),
qt_button_down, widget);
if (!receiver)
return;
- if ((event->type() != QEvent::MouseButtonPress)
- || !(event->flags().testFlag(Qt::MouseEventCreatedDoubleClick))) {
+ if ((event->type() != QEvent::MouseButtonPress) || !QMutableSinglePointEvent::from(event)->isDoubleClick()) {
// The preceding statement excludes MouseButtonPress events which caused
// creation of a MouseButtonDblClick event. QTBUG-25831
- QMouseEvent translated(event->type(), mapped, event->windowPos(), event->screenPos(),
- event->button(), event->buttons(), event->modifiers(), event->source());
+ QMouseEvent translated(event->type(), mapped, event->scenePosition(), event->globalPosition(),
+ event->button(), event->buttons(), event->modifiers(),
+ event->source(), event->pointingDevice());
translated.setTimestamp(event->timestamp());
QApplicationPrivate::sendMouseEvent(receiver, &translated, widget, m_widget,
&qt_button_down, qt_last_mouse_receiver);
@@ -676,9 +652,11 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
}
#ifndef QT_NO_CONTEXTMENU
if (event->type() == contextMenuTrigger && event->button() == Qt::RightButton
- && m_widget->rect().contains(event->pos())) {
- QContextMenuEvent e(QContextMenuEvent::Mouse, mapped, event->globalPos(), event->modifiers());
+ && m_widget->rect().contains(event->position().toPoint())) {
+ QContextMenuEvent e(QContextMenuEvent::Mouse, mapped, event->globalPosition().toPoint(), event->modifiers());
QGuiApplication::forwardEvent(receiver, &e, event);
+ if (e.isAccepted())
+ event->accept();
}
#endif
}
@@ -686,14 +664,14 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
void QWidgetWindow::handleTouchEvent(QTouchEvent *event)
{
if (event->type() == QEvent::TouchCancel) {
- QApplicationPrivate::translateTouchCancel(event->device(), event->timestamp());
+ QApplicationPrivate::translateTouchCancel(event->pointingDevice(), event->timestamp());
event->accept();
} else if (QApplicationPrivate::inPopupMode()) {
// Ignore touch events for popups. This will cause QGuiApplication to synthesise mouse
// events instead, which QWidgetWindow::handleMouseEvent will forward correctly:
event->ignore();
} else {
- event->setAccepted(QApplicationPrivate::translateRawTouchEvent(m_widget, event->device(), event->touchPoints(), event->timestamp()));
+ event->setAccepted(QApplicationPrivate::translateRawTouchEvent(m_widget, event));
}
}
@@ -718,6 +696,9 @@ bool QWidgetWindow::updateSize()
bool changed = false;
if (m_widget->testAttribute(Qt::WA_OutsideWSRange))
return changed;
+ if (m_widget->testAttribute(Qt::WA_DontShowOnScreen))
+ return changed;
+
if (m_widget->data->crect.size() != geometry().size()) {
changed = true;
m_widget->data->crect.setSize(geometry().size());
@@ -727,44 +708,45 @@ bool QWidgetWindow::updateSize()
return changed;
}
-bool QWidgetWindow::updatePos()
-{
- bool changed = false;
- if (m_widget->testAttribute(Qt::WA_OutsideWSRange))
- return changed;
- if (m_widget->data->crect.topLeft() != geometry().topLeft()) {
- changed = true;
- m_widget->data->crect.moveTopLeft(geometry().topLeft());
- }
- updateMargins();
- return changed;
-}
-
void QWidgetWindow::updateMargins()
{
- const QMargins margins = frameMargins();
+ // QTBUG-79147 (Windows): Bail out on resize events after closing a dialog
+ // and destroying the platform window which would clear the margins.
QTLWExtra *te = m_widget->d_func()->topData();
+ if (te->window == nullptr || te->window->handle() == nullptr)
+ return;
+ const QMargins margins = frameMargins();
te->posIncludesFrame= false;
te->frameStrut.setCoords(margins.left(), margins.top(), margins.right(), margins.bottom());
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())
@@ -777,7 +759,7 @@ void QWidgetWindow::repaintWindow()
return;
QTLWExtra *tlwExtra = m_widget->window()->d_func()->maybeTopData();
- if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
+ if (tlwExtra && tlwExtra->backingStore)
tlwExtra->repaintManager->markDirty(m_widget->rect(), m_widget,
QWidgetRepaintManager::UpdateNow, QWidgetRepaintManager::BufferInvalid);
}
@@ -800,32 +782,82 @@ void QWidgetWindow::updateNormalGeometry()
void QWidgetWindow::handleMoveEvent(QMoveEvent *event)
{
- if (updatePos())
- QGuiApplication::forwardEvent(m_widget, event);
+ if (m_widget->testAttribute(Qt::WA_OutsideWSRange))
+ return;
+ if (m_widget->testAttribute(Qt::WA_DontShowOnScreen))
+ return;
+
+ auto oldPosition = m_widget->data->crect.topLeft();
+ auto newPosition = geometry().topLeft();
+
+ if (!m_widget->isWindow()) {
+ if (auto *nativeParent = m_widget->nativeParentWidget())
+ newPosition = m_widget->parentWidget()->mapFrom(nativeParent, newPosition);
+ }
+
+ bool changed = newPosition != oldPosition;
+
+ if (changed)
+ m_widget->data->crect.moveTopLeft(newPosition);
+
+ updateMargins(); // FIXME: Only do when changed?
+
+ if (changed) {
+ QMoveEvent widgetEvent(newPosition, oldPosition);
+ QGuiApplication::forwardEvent(m_widget, &widgetEvent, event);
+ }
}
void QWidgetWindow::handleResizeEvent(QResizeEvent *event)
{
- QSize oldSize = m_widget->data->crect.size();
+ auto oldRect = m_widget->rect();
if (updateSize()) {
QGuiApplication::forwardEvent(m_widget, event);
if (m_widget->d_func()->shouldPaintOnScreen()) {
- QRegion updateRegion(geometry());
+ QRegion dirtyRegion = m_widget->rect();
if (m_widget->testAttribute(Qt::WA_StaticContents))
- updateRegion -= QRect(0, 0, oldSize.width(), oldSize.height());
- m_widget->d_func()->syncBackingStore(updateRegion);
+ dirtyRegion -= oldRect;
+ m_widget->d_func()->syncBackingStore(dirtyRegion);
} else {
m_widget->d_func()->syncBackingStore();
}
}
}
-void QWidgetWindow::handleCloseEvent(QCloseEvent *event)
+void QWidgetWindow::closeEvent(QCloseEvent *event)
{
- bool is_closing = m_widget->d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
- event->setAccepted(is_closing);
+ Q_D(QWidgetWindow);
+ bool accepted = m_widget->d_func()->handleClose(d->inClose ? QWidgetPrivate::CloseWithEvent
+ : QWidgetPrivate::CloseWithSpontaneousEvent);
+ event->setAccepted(accepted);
+}
+
+bool QWidgetWindowPrivate::participatesInLastWindowClosed() const
+{
+ Q_Q(const QWidgetWindow);
+
+ // For historical reasons WA_QuitOnClose has been closely tied
+ // to the lastWindowClosed signal, since the default behavior
+ // is to quit the application after emitting lastWindowClosed.
+ // ### Qt 7: Rename this attribute, or decouple behavior.
+ if (!q->widget()->testAttribute(Qt::WA_QuitOnClose))
+ return false;
+
+ return QWindowPrivate::participatesInLastWindowClosed();
+}
+
+bool QWidgetWindowPrivate::treatAsVisible() const
+{
+ Q_Q(const QWidgetWindow);
+
+ // Widget windows may have Qt::WA_DontShowOnScreen, in which case the
+ // QQWidget will be visible, but the corresponding QWindow will not.
+ // Since the lastWindowClosed logic relies on checking whether the
+ // closed window was visible, and if there are any remaining visible
+ // windows, we need to reflect the QWidget state, not the QWindow one.
+ return q->widget()->isVisible();
}
#if QT_CONFIG(wheelevent)
@@ -836,30 +868,27 @@ void QWidgetWindow::handleWheelEvent(QWheelEvent *event)
return;
QWidget *rootWidget = m_widget;
- QPoint pos = event->position().toPoint();
+ QPointF pos = event->position();
// Use proper popup window for wheel event. Some QPA sends the wheel
// event to the root menu, so redirect it to the proper popup window.
QWidget *activePopupWidget = QApplication::activePopupWidget();
if (activePopupWidget && activePopupWidget != m_widget) {
rootWidget = activePopupWidget;
- pos = rootWidget->mapFromGlobal(event->globalPosition().toPoint());
+ pos = rootWidget->mapFromGlobal(event->globalPosition());
}
// which child should have it?
- QWidget *widget = rootWidget->childAt(pos);
+ QWidget *widget = rootWidget->childAt(pos.toPoint());
if (!widget)
widget = rootWidget;
- QPoint mapped = widget->mapFrom(rootWidget, pos);
+ QPointF mapped = widget->mapFrom(rootWidget, pos);
-#if QT_DEPRECATED_SINCE(5, 0)
- QWheelEvent translated(mapped, event->globalPos(), event->pixelDelta(), event->angleDelta(), event->delta(), event->orientation(), event->buttons(), event->modifiers(), event->phase(), event->source(), event->inverted());
-#else
- QWheelEvent translated(QPointF(mapped), event->globalPosition(), event->pixelDelta(), event->angleDelta(),
- event->buttons(), event->modifiers(), event->phase(), event->inverted(), event->source());
-#endif
+ QWheelEvent translated(mapped, event->globalPosition(), event->pixelDelta(), event->angleDelta(),
+ event->buttons(), event->modifiers(), event->phase(), event->inverted(),
+ event->source(), event->pointingDevice());
translated.setTimestamp(event->timestamp());
QGuiApplication::forwardEvent(widget, &translated, event);
}
@@ -884,16 +913,16 @@ void QWidgetWindow::handleDragEnterEvent(QDragEnterEvent *event, QWidget *widget
{
Q_ASSERT(m_dragTarget == nullptr);
if (!widget)
- widget = findDnDTarget(m_widget, event->pos());
+ widget = findDnDTarget(m_widget, event->position().toPoint());
if (!widget) {
event->ignore();
return;
}
m_dragTarget = widget;
- const QPoint mapped = widget->mapFromGlobal(m_widget->mapToGlobal(event->pos()));
+ const QPoint mapped = widget->mapFromGlobal(m_widget->mapToGlobal(event->position().toPoint()));
QDragEnterEvent translated(mapped, event->possibleActions(), event->mimeData(),
- event->mouseButtons(), event->keyboardModifiers());
+ event->buttons(), event->modifiers());
QGuiApplication::forwardEvent(m_dragTarget, &translated, event);
event->setAccepted(translated.isAccepted());
event->setDropAction(translated.dropAction());
@@ -901,18 +930,19 @@ void QWidgetWindow::handleDragEnterEvent(QDragEnterEvent *event, QWidget *widget
void QWidgetWindow::handleDragMoveEvent(QDragMoveEvent *event)
{
- QPointer<QWidget> widget = findDnDTarget(m_widget, event->pos());
+ QPointer<QWidget> widget = findDnDTarget(m_widget, event->position().toPoint());
if (!widget) {
event->ignore();
if (m_dragTarget) { // Send DragLeave to previous
QDragLeaveEvent leaveEvent;
- QGuiApplication::forwardEvent(m_dragTarget, &leaveEvent, event);
+ QWidget *dragTarget = m_dragTarget;
m_dragTarget = nullptr;
+ QGuiApplication::forwardEvent(dragTarget, &leaveEvent, event);
}
} else {
- const QPoint mapped = widget->mapFromGlobal(m_widget->mapToGlobal(event->pos()));
+ const QPoint mapped = widget->mapFromGlobal(m_widget->mapToGlobal(event->position().toPoint()));
QDragMoveEvent translated(mapped, event->possibleActions(), event->mimeData(),
- event->mouseButtons(), event->keyboardModifiers());
+ event->buttons(), event->modifiers());
if (widget == m_dragTarget) { // Target widget unchanged: Send DragMove
translated.setDropAction(event->dropAction());
@@ -921,8 +951,9 @@ void QWidgetWindow::handleDragMoveEvent(QDragMoveEvent *event)
} else {
if (m_dragTarget) { // Send DragLeave to previous
QDragLeaveEvent leaveEvent;
- QGuiApplication::forwardEvent(m_dragTarget, &leaveEvent, event);
+ QWidget *dragTarget = m_dragTarget;
m_dragTarget = nullptr;
+ QGuiApplication::forwardEvent(dragTarget, &leaveEvent, event);
}
// widget might have been deleted when handling the leaveEvent
if (widget) {
@@ -944,9 +975,11 @@ void QWidgetWindow::handleDragMoveEvent(QDragMoveEvent *event)
void QWidgetWindow::handleDragLeaveEvent(QDragLeaveEvent *event)
{
- if (m_dragTarget)
- QGuiApplication::forwardEvent(m_dragTarget, event);
- m_dragTarget = nullptr;
+ if (m_dragTarget) {
+ QWidget *dragTarget = m_dragTarget;
+ m_dragTarget = nullptr;
+ QGuiApplication::forwardEvent(dragTarget, event);
+ }
}
void QWidgetWindow::handleDropEvent(QDropEvent *event)
@@ -956,18 +989,22 @@ void QWidgetWindow::handleDropEvent(QDropEvent *event)
event->ignore();
return;
}
- const QPoint mapped = m_dragTarget->mapFromGlobal(m_widget->mapToGlobal(event->pos()));
- QDropEvent translated(mapped, event->possibleActions(), event->mimeData(), event->mouseButtons(), event->keyboardModifiers());
- QGuiApplication::forwardEvent(m_dragTarget, &translated, event);
+ const QPoint mapped = m_dragTarget->mapFromGlobal(m_widget->mapToGlobal(event->position().toPoint()));
+ QDropEvent translated(mapped, event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
+ QWidget *dragTarget = m_dragTarget;
+ m_dragTarget = nullptr;
+ QGuiApplication::forwardEvent(dragTarget, &translated, event);
event->setAccepted(translated.isAccepted());
event->setDropAction(translated.dropAction());
- m_dragTarget = nullptr;
}
#endif // QT_CONFIG(draganddrop)
void QWidgetWindow::handleExposeEvent(QExposeEvent *event)
{
+ if (m_widget->testAttribute(Qt::WA_DontShowOnScreen))
+ return; // Ignore for widgets that fake exposure
+
QWidgetPrivate *wPriv = m_widget->d_func();
const bool exposed = isExposed();
@@ -987,7 +1024,7 @@ void QWidgetWindow::handleExposeEvent(QExposeEvent *event)
// If the window becomes not exposed...
if (wPriv->childrenShownByExpose) {
// ... and child widgets was previously shown by the expose event - hide widgets again.
- // This is a workaround, because sometimes when window is minimized programatically,
+ // This is a workaround, because sometimes when window is minimized programmatically,
// the QPA can notify that the window is exposed after changing window state to minimized
// and then, the QPA can send next expose event with null exposed region (not exposed).
wPriv->hideChildren(true);
@@ -1003,8 +1040,8 @@ void QWidgetWindow::handleExposeEvent(QExposeEvent *event)
m_widget->setAttribute(Qt::WA_Mapped);
for (QWidget *p = m_widget->parentWidget(); p && !p->testAttribute(Qt::WA_Mapped); p = p->parentWidget())
p->setAttribute(Qt::WA_Mapped);
- if (!event->region().isNull())
- wPriv->syncBackingStore(event->region());
+ if (!event->m_region.isNull())
+ wPriv->syncBackingStore(event->m_region);
} else {
m_widget->setAttribute(Qt::WA_Mapped, false);
}
@@ -1038,11 +1075,7 @@ void QWidgetWindow::handleWindowStateChangedEvent(QWindowStateChangeEvent *event
}
}
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool QWidgetWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
-#else
-bool QWidgetWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
-#endif
{
return m_widget->nativeEvent(eventType, message, result);
}
@@ -1055,20 +1088,19 @@ void QWidgetWindow::handleTabletEvent(QTabletEvent *event)
QWidget *widget = qt_tablet_target;
if (!widget) {
- widget = m_widget->childAt(event->pos());
- if (event->type() == QEvent::TabletPress) {
- if (!widget)
- widget = m_widget;
+ widget = m_widget->childAt(event->position().toPoint());
+ if (!widget)
+ widget = m_widget;
+ if (event->type() == QEvent::TabletPress)
qt_tablet_target = widget;
- }
}
if (widget) {
- QPointF delta = event->globalPosF() - event->globalPos();
- QPointF mapped = widget->mapFromGlobal(event->globalPos()) + delta;
- QTabletEvent ev(event->type(), mapped, event->globalPosF(), event->device(), event->pointerType(),
+ QPointF delta = event->globalPosition() - event->globalPosition().toPoint();
+ QPointF mapped = widget->mapFromGlobal(event->globalPosition().toPoint()) + delta;
+ QTabletEvent ev(event->type(), event->pointingDevice(), mapped, event->globalPosition(),
event->pressure(), event->xTilt(), event->yTilt(), event->tangentialPressure(),
- event->rotation(), event->z(), event->modifiers(), event->uniqueId(), event->button(), event->buttons());
+ event->rotation(), event->z(), event->modifiers(), event->button(), event->buttons());
ev.setTimestamp(event->timestamp());
ev.setAccepted(false);
QGuiApplication::forwardEvent(widget, &ev, event);
@@ -1091,7 +1123,7 @@ void QWidgetWindow::handleGestureEvent(QNativeGestureEvent *e)
receiver = popupFocusWidget ? popupFocusWidget : popup;
}
if (!receiver)
- receiver = QApplication::widgetAt(e->globalPos());
+ receiver = QApplication::widgetAt(e->globalPosition().toPoint());
if (!receiver)
receiver = m_widget; // last resort
@@ -1132,8 +1164,8 @@ void QWidgetWindow::updateObjectName()
{
QString name = m_widget->objectName();
if (name.isEmpty())
- name = QString::fromUtf8(m_widget->metaObject()->className()) + QLatin1String("Class");
- name += QLatin1String("Window");
+ name = QString::fromUtf8(m_widget->metaObject()->className()) + "Class"_L1;
+ name += "Window"_L1;
setObjectName(name);
}
diff --git a/src/widgets/kernel/qwidgetwindow_p.h b/src/widgets/kernel/qwidgetwindow_p.h
index 80a345465d..0ee6b71a79 100644
--- a/src/widgets/kernel/qwidgetwindow_p.h
+++ b/src/widgets/kernel/qwidgetwindow_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIDGETWINDOW_P_H
#define QWIDGETWINDOW_P_H
@@ -58,6 +22,8 @@
#include <QtGui/private/qevent_p.h>
#include <QtWidgets/qwidget.h>
+#include <QtCore/qpointer.h>
+
QT_BEGIN_NAMESPACE
@@ -74,7 +40,7 @@ public:
~QWidgetWindow();
QWidget *widget() const { return m_widget; }
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleInterface *accessibleRoot() const override;
#endif
@@ -83,7 +49,8 @@ public:
protected:
bool event(QEvent *) override;
- void handleCloseEvent(QCloseEvent *);
+ void closeEvent(QCloseEvent *) override;
+
void handleEnterLeaveEvent(QEvent *);
void handleFocusInEvent(QFocusEvent *);
void handleKeyEvent(QKeyEvent *);
@@ -103,11 +70,7 @@ protected:
#endif
void handleExposeEvent(QExposeEvent *);
void handleWindowStateChangedEvent(QWindowStateChangeEvent *event);
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override;
-#else
- bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
-#endif
#if QT_CONFIG(tabletevent)
void handleTabletEvent(QTabletEvent *);
#endif
@@ -120,12 +83,12 @@ protected:
private slots:
void updateObjectName();
- void handleScreenChange();
private:
+ void handleScreenChange();
+ void handleDevicePixelRatioChange();
void repaintWindow();
bool updateSize();
- bool updatePos();
void updateMargins();
void updateNormalGeometry();
diff --git a/src/widgets/kernel/qwindowcontainer.cpp b/src/widgets/kernel/qwindowcontainer.cpp
index b4d889fdfa..c15ec54f35 100644
--- a/src/widgets/kernel/qwindowcontainer.cpp
+++ b/src/widgets/kernel/qwindowcontainer.cpp
@@ -1,44 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "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>
@@ -50,8 +15,12 @@
#include <QAbstractScrollArea>
#include <QPainter>
+#include <QtCore/qpointer.h>
+
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
class QWindowContainerPrivate : public QWidgetPrivate
{
public:
@@ -196,16 +165,34 @@ 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);
}
-
-
/*!
\internal
*/
@@ -219,24 +206,24 @@ QWindowContainer::QWindowContainer(QWindow *embeddedWindow, QWidget *parent, Qt:
return;
}
- // The embedded QWindow must use the same logic as QWidget when it comes to the surface type.
- // Otherwise we may end up with BadMatch failures on X11.
- if (embeddedWindow->surfaceType() == QSurface::RasterSurface
- && QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RasterGLSurface)
- && !QCoreApplication::testAttribute(Qt::AA_ForceRasterWidgets))
- embeddedWindow->setSurfaceType(QSurface::RasterGLSurface);
-
d->window = embeddedWindow;
QString windowName = d->window->objectName();
if (windowName.isEmpty())
windowName = QString::fromUtf8(d->window->metaObject()->className());
- d->fakeParent.setObjectName(windowName + QLatin1String("ContainerFakeParent"));
+ d->fakeParent.setObjectName(windowName + "ContainerFakeParent"_L1);
d->window->setParent(&d->fakeParent);
+ d->window->parent()->installEventFilter(this);
+ d->window->setFlag(Qt::SubWindow);
+
setAcceptDrops(true);
- connect(QGuiApplication::instance(), SIGNAL(focusWindowChanged(QWindow*)), this, SLOT(focusWindowChanged(QWindow*)));
+ connect(qGuiApp, &QGuiApplication::focusWindowChanged,
+ this, &QWindowContainer::focusWindowChanged);
+
+ connect(containedWindow(), &QWindow::minimumHeightChanged, this, &QWindowContainer::updateGeometry);
+ connect(containedWindow(), &QWindow::minimumWidthChanged, this, &QWindowContainer::updateGeometry);
}
QWindow *QWindowContainer::containedWindow() const
@@ -261,6 +248,9 @@ QWindowContainer::~QWindowContainer()
d->window->destroy();
delete d->window;
+
+ disconnect(qGuiApp, &QGuiApplication::focusWindowChanged,
+ this, &QWindowContainer::focusWindowChanged);
}
@@ -284,6 +274,26 @@ void QWindowContainer::focusWindowChanged(QWindow *focusWindow)
\internal
*/
+bool QWindowContainer::eventFilter(QObject *o, QEvent *e)
+{
+ Q_D(QWindowContainer);
+ if (!d->window)
+ return false;
+
+ if (e->type() == QEvent::ChildRemoved) {
+ QChildEvent *ce = static_cast<QChildEvent *>(e);
+ if (ce->child() == d->window) {
+ o->removeEventFilter(this);
+ d->window = nullptr;
+ }
+ }
+ return false;
+}
+
+/*!
+ \internal
+ */
+
bool QWindowContainer::event(QEvent *e)
{
Q_D(QWindowContainer);
@@ -292,12 +302,6 @@ bool QWindowContainer::event(QEvent *e)
QEvent::Type type = e->type();
switch (type) {
- case QEvent::ChildRemoved: {
- QChildEvent *ce = static_cast<QChildEvent *>(e);
- if (ce->child() == d->window)
- d->window = nullptr;
- break;
- }
// The only thing we are interested in is making sure our sizes stay
// in sync, so do a catch-all case.
case QEvent::Resize:
@@ -312,10 +316,13 @@ bool QWindowContainer::event(QEvent *e)
case QEvent::Show:
d->updateUsesNativeWidgets();
if (d->isStillAnOrphan()) {
+ d->window->parent()->removeEventFilter(this);
d->window->setParent(d->usesNativeWidgets
? windowHandle()
: window()->windowHandle());
d->fakeParent.destroy();
+ if (d->window->parent())
+ d->window->parent()->installEventFilter(this);
}
if (d->window->parent()) {
d->markParentChain();
@@ -369,6 +376,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)
{
@@ -386,7 +398,10 @@ static void qwindowcontainer_traverse(QWidget *parent, qwindowcontainer_traverse
void QWindowContainer::toplevelAboutToBeDestroyed(QWidget *parent)
{
if (QWindowContainerPrivate *d = QWindowContainerPrivate::get(parent)) {
+ if (d->window->parent())
+ d->window->parent()->removeEventFilter(parent);
d->window->setParent(&d->fakeParent);
+ d->window->parent()->installEventFilter(parent);
}
qwindowcontainer_traverse(parent, toplevelAboutToBeDestroyed);
}
@@ -404,7 +419,9 @@ void QWindowContainer::parentWasChanged(QWidget *parent)
tld->createTLSysExtra();
Q_ASSERT(toplevel->windowHandle());
}
+ d->window->parent()->removeEventFilter(parent);
d->window->setParent(toplevel->windowHandle());
+ toplevel->windowHandle()->installEventFilter(parent);
d->fakeParent.destroy();
d->updateGeometry();
}
diff --git a/src/widgets/kernel/qwindowcontainer_p.h b/src/widgets/kernel/qwindowcontainer_p.h
index 72474077aa..a303f25424 100644
--- a/src/widgets/kernel/qwindowcontainer_p.h
+++ b/src/widgets/kernel/qwindowcontainer_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWINDOWCONTAINER_H
#define QWINDOWCONTAINER_H
@@ -67,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);
@@ -76,6 +41,7 @@ public:
protected:
bool event(QEvent *ev) override;
+ bool eventFilter(QObject *, QEvent *ev) override;
private slots:
void focusWindowChanged(QWindow *focusWindow);
diff --git a/src/widgets/kernel/win.pri b/src/widgets/kernel/win.pri
deleted file mode 100644
index eede987b4c..0000000000
--- a/src/widgets/kernel/win.pri
+++ /dev/null
@@ -1,7 +0,0 @@
-# Qt/Windows only configuration file
-# --------------------------------------------------------------------
-
-!winrt {
- LIBS_PRIVATE *= -luxtheme -ldwmapi
- QMAKE_USE_PRIVATE += shell32
-}
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/qt_cmdline.cmake b/src/widgets/qt_cmdline.cmake
new file mode 100644
index 0000000000..fa78b9bf9c
--- /dev/null
+++ b/src/widgets/qt_cmdline.cmake
@@ -0,0 +1,9 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+qt_commandline_option(gtk TYPE boolean NAME gtk3)
+qt_commandline_option(style-windows TYPE boolean)
+qt_commandline_option(style-windowsvista TYPE boolean)
+qt_commandline_option(style-fusion TYPE boolean)
+qt_commandline_option(style-mac TYPE boolean)
+qt_commandline_option(style-android TYPE boolean)
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/statemachine/qbasickeyeventtransition.cpp b/src/widgets/statemachine/qbasickeyeventtransition.cpp
deleted file mode 100644
index c833e64822..0000000000
--- a/src/widgets/statemachine/qbasickeyeventtransition.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qbasickeyeventtransition_p.h"
-
-#include <QtGui/qevent.h>
-#include <qdebug.h>
-#include <private/qabstracttransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
- \class QBasicKeyEventTransition
- \since 4.6
- \ingroup statemachine
-
- \brief The QBasicKeyEventTransition class provides a transition for Qt key events.
-*/
-
-class QBasicKeyEventTransitionPrivate : public QAbstractTransitionPrivate
-{
- Q_DECLARE_PUBLIC(QBasicKeyEventTransition)
-public:
- QBasicKeyEventTransitionPrivate();
-
- static QBasicKeyEventTransitionPrivate *get(QBasicKeyEventTransition *q);
-
- QEvent::Type eventType;
- int key;
- Qt::KeyboardModifiers modifierMask;
-};
-
-QBasicKeyEventTransitionPrivate::QBasicKeyEventTransitionPrivate()
-{
- eventType = QEvent::None;
- key = 0;
- modifierMask = Qt::NoModifier;
-}
-
-QBasicKeyEventTransitionPrivate *QBasicKeyEventTransitionPrivate::get(QBasicKeyEventTransition *q)
-{
- return q->d_func();
-}
-
-/*!
- Constructs a new key event transition with the given \a sourceState.
-*/
-QBasicKeyEventTransition::QBasicKeyEventTransition(QState *sourceState)
- : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState)
-{
-}
-
-/*!
- Constructs a new event transition for events of the given \a type for the
- given \a key, with the given \a sourceState.
-*/
-QBasicKeyEventTransition::QBasicKeyEventTransition(QEvent::Type type, int key,
- QState *sourceState)
- : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState)
-{
- Q_D(QBasicKeyEventTransition);
- d->eventType = type;
- d->key = key;
-}
-
-/*!
- Constructs a new event transition for events of the given \a type for the
- given \a key, with the given \a modifierMask and \a sourceState.
-*/
-QBasicKeyEventTransition::QBasicKeyEventTransition(QEvent::Type type, int key,
- Qt::KeyboardModifiers modifierMask,
- QState *sourceState)
- : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState)
-{
- Q_D(QBasicKeyEventTransition);
- d->eventType = type;
- d->key = key;
- d->modifierMask = modifierMask;
-}
-
-/*!
- Destroys this event transition.
-*/
-QBasicKeyEventTransition::~QBasicKeyEventTransition()
-{
-}
-
-/*!
- Returns the event type that this key event transition is associated with.
-*/
-QEvent::Type QBasicKeyEventTransition::eventType() const
-{
- Q_D(const QBasicKeyEventTransition);
- return d->eventType;
-}
-
-/*!
- Sets the event \a type that this key event transition is associated with.
-*/
-void QBasicKeyEventTransition::setEventType(QEvent::Type type)
-{
- Q_D(QBasicKeyEventTransition);
- d->eventType = type;
-}
-
-/*!
- Returns the key that this key event transition checks for.
-*/
-int QBasicKeyEventTransition::key() const
-{
- Q_D(const QBasicKeyEventTransition);
- return d->key;
-}
-
-/*!
- Sets the key that this key event transition will check for.
-*/
-void QBasicKeyEventTransition::setKey(int key)
-{
- Q_D(QBasicKeyEventTransition);
- d->key = key;
-}
-
-/*!
- Returns the keyboard modifier mask that this key event transition checks
- for.
-*/
-Qt::KeyboardModifiers QBasicKeyEventTransition::modifierMask() const
-{
- Q_D(const QBasicKeyEventTransition);
- return d->modifierMask;
-}
-
-/*!
- Sets the keyboard modifier mask that this key event transition will check
- for.
-*/
-void QBasicKeyEventTransition::setModifierMask(Qt::KeyboardModifiers modifierMask)
-{
- Q_D(QBasicKeyEventTransition);
- d->modifierMask = modifierMask;
-}
-
-/*!
- \reimp
-*/
-bool QBasicKeyEventTransition::eventTest(QEvent *event)
-{
- Q_D(const QBasicKeyEventTransition);
- if (event->type() == d->eventType) {
- QKeyEvent *ke = static_cast<QKeyEvent*>(event);
- return (ke->key() == d->key)
- && ((ke->modifiers() & d->modifierMask) == d->modifierMask);
- }
- return false;
-}
-
-/*!
- \reimp
-*/
-void QBasicKeyEventTransition::onTransition(QEvent *)
-{
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qbasickeyeventtransition_p.cpp"
diff --git a/src/widgets/statemachine/qbasickeyeventtransition_p.h b/src/widgets/statemachine/qbasickeyeventtransition_p.h
deleted file mode 100644
index f23c078570..0000000000
--- a/src/widgets/statemachine/qbasickeyeventtransition_p.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QBASICKEYEVENTTRANSITION_P_H
-#define QBASICKEYEVENTTRANSITION_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 <QtCore/qabstracttransition.h>
-#include <QtGui/qevent.h>
-
-QT_REQUIRE_CONFIG(qeventtransition);
-
-QT_BEGIN_NAMESPACE
-
-class QBasicKeyEventTransitionPrivate;
-class Q_AUTOTEST_EXPORT QBasicKeyEventTransition : public QAbstractTransition
-{
- Q_OBJECT
-public:
- QBasicKeyEventTransition(QState *sourceState = nullptr);
- QBasicKeyEventTransition(QEvent::Type type, int key, QState *sourceState = nullptr);
- QBasicKeyEventTransition(QEvent::Type type, int key,
- Qt::KeyboardModifiers modifierMask,
- QState *sourceState = nullptr);
- ~QBasicKeyEventTransition();
-
- QEvent::Type eventType() const;
- void setEventType(QEvent::Type type);
-
- int key() const;
- void setKey(int key);
-
- Qt::KeyboardModifiers modifierMask() const;
- void setModifierMask(Qt::KeyboardModifiers modifiers);
-
-protected:
- bool eventTest(QEvent *event) override;
- void onTransition(QEvent *) override;
-
-private:
- Q_DISABLE_COPY_MOVE(QBasicKeyEventTransition)
- Q_DECLARE_PRIVATE(QBasicKeyEventTransition)
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/widgets/statemachine/qbasicmouseeventtransition.cpp b/src/widgets/statemachine/qbasicmouseeventtransition.cpp
deleted file mode 100644
index f404c33a2f..0000000000
--- a/src/widgets/statemachine/qbasicmouseeventtransition.cpp
+++ /dev/null
@@ -1,208 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qbasicmouseeventtransition_p.h"
-#include <QtGui/qevent.h>
-#include <QtGui/qpainterpath.h>
-#include <qdebug.h>
-#include <private/qabstracttransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
- \class QBasicMouseEventTransition
- \since 4.6
- \ingroup statemachine
-
- \brief The QBasicMouseEventTransition class provides a transition for Qt mouse events.
-*/
-
-class QBasicMouseEventTransitionPrivate : public QAbstractTransitionPrivate
-{
- Q_DECLARE_PUBLIC(QBasicMouseEventTransition)
-public:
- QBasicMouseEventTransitionPrivate();
-
- static QBasicMouseEventTransitionPrivate *get(QBasicMouseEventTransition *q);
-
- QEvent::Type eventType;
- Qt::MouseButton button;
- Qt::KeyboardModifiers modifierMask;
- QPainterPath path;
-};
-
-QBasicMouseEventTransitionPrivate::QBasicMouseEventTransitionPrivate()
-{
- eventType = QEvent::None;
- button = Qt::NoButton;
-}
-
-QBasicMouseEventTransitionPrivate *QBasicMouseEventTransitionPrivate::get(QBasicMouseEventTransition *q)
-{
- return q->d_func();
-}
-
-/*!
- Constructs a new mouse event transition with the given \a sourceState.
-*/
-QBasicMouseEventTransition::QBasicMouseEventTransition(QState *sourceState)
- : QAbstractTransition(*new QBasicMouseEventTransitionPrivate, sourceState)
-{
-}
-
-/*!
- Constructs a new mouse event transition for events of the given \a type.
-*/
-QBasicMouseEventTransition::QBasicMouseEventTransition(QEvent::Type type,
- Qt::MouseButton button,
- QState *sourceState)
- : QAbstractTransition(*new QBasicMouseEventTransitionPrivate, sourceState)
-{
- Q_D(QBasicMouseEventTransition);
- d->eventType = type;
- d->button = button;
-}
-
-/*!
- Destroys this mouse event transition.
-*/
-QBasicMouseEventTransition::~QBasicMouseEventTransition()
-{
-}
-
-/*!
- Returns the event type that this mouse event transition is associated with.
-*/
-QEvent::Type QBasicMouseEventTransition::eventType() const
-{
- Q_D(const QBasicMouseEventTransition);
- return d->eventType;
-}
-
-/*!
- Sets the event \a type that this mouse event transition is associated with.
-*/
-void QBasicMouseEventTransition::setEventType(QEvent::Type type)
-{
- Q_D(QBasicMouseEventTransition);
- d->eventType = type;
-}
-
-/*!
- Returns the button that this mouse event transition checks for.
-*/
-Qt::MouseButton QBasicMouseEventTransition::button() const
-{
- Q_D(const QBasicMouseEventTransition);
- return d->button;
-}
-
-/*!
- Sets the button that this mouse event transition will check for.
-*/
-void QBasicMouseEventTransition::setButton(Qt::MouseButton button)
-{
- Q_D(QBasicMouseEventTransition);
- d->button = button;
-}
-
-/*!
- Returns the keyboard modifier mask that this mouse event transition checks
- for.
-*/
-Qt::KeyboardModifiers QBasicMouseEventTransition::modifierMask() const
-{
- Q_D(const QBasicMouseEventTransition);
- return d->modifierMask;
-}
-
-/*!
- Sets the keyboard modifier mask that this mouse event transition will check
- for.
-*/
-void QBasicMouseEventTransition::setModifierMask(Qt::KeyboardModifiers modifierMask)
-{
- Q_D(QBasicMouseEventTransition);
- d->modifierMask = modifierMask;
-}
-
-/*!
- Returns the hit test path for this mouse event transition.
-*/
-QPainterPath QBasicMouseEventTransition::hitTestPath() const
-{
- Q_D(const QBasicMouseEventTransition);
- return d->path;
-}
-
-/*!
- Sets the hit test path for this mouse event transition.
-*/
-void QBasicMouseEventTransition::setHitTestPath(const QPainterPath &path)
-{
- Q_D(QBasicMouseEventTransition);
- d->path = path;
-}
-
-/*!
- \reimp
-*/
-bool QBasicMouseEventTransition::eventTest(QEvent *event)
-{
- Q_D(const QBasicMouseEventTransition);
- if (event->type() == d->eventType) {
- QMouseEvent *me = static_cast<QMouseEvent*>(event);
- return (me->button() == d->button)
- && ((me->modifiers() & d->modifierMask) == d->modifierMask)
- && (d->path.isEmpty() || d->path.contains(me->pos()));
- }
- return false;
-}
-
-/*!
- \reimp
-*/
-void QBasicMouseEventTransition::onTransition(QEvent *)
-{
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qbasicmouseeventtransition_p.cpp"
diff --git a/src/widgets/statemachine/qbasicmouseeventtransition_p.h b/src/widgets/statemachine/qbasicmouseeventtransition_p.h
deleted file mode 100644
index dd619d189c..0000000000
--- a/src/widgets/statemachine/qbasicmouseeventtransition_p.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QBASICMOUSEEVENTTRANSITION_P_H
-#define QBASICMOUSEEVENTTRANSITION_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 <QtCore/qabstracttransition.h>
-#include <QtGui/qevent.h>
-
-QT_REQUIRE_CONFIG(qeventtransition);
-
-QT_BEGIN_NAMESPACE
-
-class QPainterPath;
-
-class QBasicMouseEventTransitionPrivate;
-class Q_AUTOTEST_EXPORT QBasicMouseEventTransition : public QAbstractTransition
-{
- Q_OBJECT
-public:
- QBasicMouseEventTransition(QState *sourceState = nullptr);
- QBasicMouseEventTransition(QEvent::Type type, Qt::MouseButton button,
- QState *sourceState = nullptr);
- ~QBasicMouseEventTransition();
-
- QEvent::Type eventType() const;
- void setEventType(QEvent::Type type);
-
- Qt::MouseButton button() const;
- void setButton(Qt::MouseButton button);
-
- Qt::KeyboardModifiers modifierMask() const;
- void setModifierMask(Qt::KeyboardModifiers modifiers);
-
- QPainterPath hitTestPath() const;
- void setHitTestPath(const QPainterPath &path);
-
-protected:
- bool eventTest(QEvent *event) override;
- void onTransition(QEvent *) override;
-
-private:
- Q_DISABLE_COPY_MOVE(QBasicMouseEventTransition)
- Q_DECLARE_PRIVATE(QBasicMouseEventTransition)
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/widgets/statemachine/qguistatemachine.cpp b/src/widgets/statemachine/qguistatemachine.cpp
deleted file mode 100644
index b310da5781..0000000000
--- a/src/widgets/statemachine/qguistatemachine.cpp
+++ /dev/null
@@ -1,473 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtCore/qstatemachine.h>
-#include <private/qstatemachine_p.h>
-#include <QtGui/qevent.h>
-#include <QtWidgets/qtwidgetsglobal.h>
-#if QT_CONFIG(graphicsview)
-#include <QtWidgets/qgraphicssceneevent.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-Q_CORE_EXPORT const QStateMachinePrivate::Handler *qcoreStateMachineHandler();
-
-static QEvent *cloneEvent(QEvent *e)
-{
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- return new QMouseEvent(*static_cast<QMouseEvent*>(e));
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- return new QKeyEvent(*static_cast<QKeyEvent*>(e));
- case QEvent::FocusIn:
- case QEvent::FocusOut:
- return new QFocusEvent(*static_cast<QFocusEvent*>(e));
- case QEvent::Enter:
- return new QEvent(*e);
- case QEvent::Leave:
- return new QEvent(*e);
- case QEvent::Paint:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::Move:
- return new QMoveEvent(*static_cast<QMoveEvent*>(e));
- case QEvent::Resize:
- return new QResizeEvent(*static_cast<QResizeEvent*>(e));
- case QEvent::Create:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::Destroy:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::Show:
- return new QShowEvent(*static_cast<QShowEvent*>(e));
- case QEvent::Hide:
- return new QHideEvent(*static_cast<QHideEvent*>(e));
- case QEvent::Close:
- return new QCloseEvent(*static_cast<QCloseEvent*>(e));
- case QEvent::Quit:
- return new QEvent(*e);
- case QEvent::ParentChange:
- return new QEvent(*e);
- case QEvent::ParentAboutToChange:
- return new QEvent(*e);
- case QEvent::ThreadChange:
- return new QEvent(*e);
-
- case QEvent::WindowActivate:
- case QEvent::WindowDeactivate:
- return new QEvent(*e);
-
- case QEvent::ShowToParent:
- return new QEvent(*e);
- case QEvent::HideToParent:
- return new QEvent(*e);
-#if QT_CONFIG(wheelevent)
- case QEvent::Wheel:
- return new QWheelEvent(*static_cast<QWheelEvent*>(e));
-#endif // QT_CONFIG(wheelevent)
- case QEvent::WindowTitleChange:
- return new QEvent(*e);
- case QEvent::WindowIconChange:
- return new QEvent(*e);
- case QEvent::ApplicationWindowIconChange:
- return new QEvent(*e);
- case QEvent::ApplicationFontChange:
- return new QEvent(*e);
- case QEvent::ApplicationLayoutDirectionChange:
- return new QEvent(*e);
- case QEvent::ApplicationPaletteChange:
- return new QEvent(*e);
- case QEvent::PaletteChange:
- return new QEvent(*e);
- case QEvent::Clipboard:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::Speech:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::MetaCall:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::SockAct:
- return new QEvent(*e);
- case QEvent::WinEventAct:
- return new QEvent(*e);
- case QEvent::DeferredDelete:
- return new QEvent(*e);
-#if QT_CONFIG(draganddrop)
- case QEvent::DragEnter:
- return new QDragEnterEvent(*static_cast<QDragEnterEvent*>(e));
- case QEvent::DragMove:
- return new QDragMoveEvent(*static_cast<QDragMoveEvent*>(e));
- case QEvent::DragLeave:
- return new QDragLeaveEvent(*static_cast<QDragLeaveEvent*>(e));
- case QEvent::Drop:
- return new QDropEvent(*static_cast<QDragMoveEvent*>(e));
-#endif
- case QEvent::ChildAdded:
- return new QChildEvent(*static_cast<QChildEvent*>(e));
- case QEvent::ChildPolished:
- return new QChildEvent(*static_cast<QChildEvent*>(e));
- case QEvent::ChildRemoved:
- return new QChildEvent(*static_cast<QChildEvent*>(e));
- case QEvent::ShowWindowRequest:
- return new QEvent(*e);
- case QEvent::PolishRequest:
- return new QEvent(*e);
- case QEvent::Polish:
- return new QEvent(*e);
- case QEvent::LayoutRequest:
- return new QEvent(*e);
- case QEvent::UpdateRequest:
- return new QEvent(*e);
- case QEvent::UpdateLater:
- return new QEvent(*e);
-
- case QEvent::EmbeddingControl:
- return new QEvent(*e);
- case QEvent::ActivateControl:
- return new QEvent(*e);
- case QEvent::DeactivateControl:
- return new QEvent(*e);
-
-#ifndef QT_NO_CONTEXTMENU
- case QEvent::ContextMenu:
- return new QContextMenuEvent(*static_cast<QContextMenuEvent*>(e));
-#endif
- case QEvent::InputMethod:
- return new QInputMethodEvent(*static_cast<QInputMethodEvent*>(e));
- case QEvent::LocaleChange:
- return new QEvent(*e);
- case QEvent::LanguageChange:
- return new QEvent(*e);
- case QEvent::LayoutDirectionChange:
- return new QEvent(*e);
- case QEvent::Style:
- return new QEvent(*e);
-#if QT_CONFIG(tabletevent)
- case QEvent::TabletMove:
- case QEvent::TabletPress:
- case QEvent::TabletRelease:
- return new QTabletEvent(*static_cast<QTabletEvent*>(e));
-#endif // QT_CONFIG(tabletevent)
- case QEvent::OkRequest:
- return new QEvent(*e);
- case QEvent::HelpRequest:
- return new QEvent(*e);
-
- case QEvent::IconDrag:
- return new QIconDragEvent(*static_cast<QIconDragEvent*>(e));
-
- case QEvent::FontChange:
- return new QEvent(*e);
- case QEvent::EnabledChange:
- return new QEvent(*e);
- case QEvent::ActivationChange:
- return new QEvent(*e);
- case QEvent::StyleChange:
- return new QEvent(*e);
- case QEvent::IconTextChange:
- return new QEvent(*e);
- case QEvent::ModifiedChange:
- return new QEvent(*e);
- case QEvent::MouseTrackingChange:
- return new QEvent(*e);
-
- case QEvent::WindowBlocked:
- return new QEvent(*e);
- case QEvent::WindowUnblocked:
- return new QEvent(*e);
- case QEvent::WindowStateChange:
- return new QWindowStateChangeEvent(*static_cast<QWindowStateChangeEvent*>(e));
-
- case QEvent::ToolTip:
- return new QHelpEvent(*static_cast<QHelpEvent*>(e));
- case QEvent::WhatsThis:
- return new QHelpEvent(*static_cast<QHelpEvent*>(e));
-#if QT_CONFIG(statustip)
- case QEvent::StatusTip:
- return new QStatusTipEvent(*static_cast<QStatusTipEvent*>(e));
-#endif // QT_CONFIG(statustip)
-#ifndef QT_NO_ACTION
- case QEvent::ActionChanged:
- case QEvent::ActionAdded:
- case QEvent::ActionRemoved:
- return new QActionEvent(*static_cast<QActionEvent*>(e));
-#endif
- case QEvent::FileOpen:
- return new QFileOpenEvent(*static_cast<QFileOpenEvent*>(e));
-
-#ifndef QT_NO_SHORTCUT
- case QEvent::Shortcut:
- return new QShortcutEvent(*static_cast<QShortcutEvent*>(e));
-#endif //QT_NO_SHORTCUT
- case QEvent::ShortcutOverride:
- return new QKeyEvent(*static_cast<QKeyEvent*>(e));
-
-#if QT_CONFIG(whatsthis)
- case QEvent::WhatsThisClicked:
- return new QWhatsThisClickedEvent(*static_cast<QWhatsThisClickedEvent*>(e));
-#endif // QT_CONFIG(whatsthis)
-
-#if QT_CONFIG(toolbar)
- case QEvent::ToolBarChange:
- return new QToolBarChangeEvent(*static_cast<QToolBarChangeEvent*>(e));
-#endif // QT_CONFIG(toolbar)
-
- case QEvent::ApplicationActivate:
- return new QEvent(*e);
- case QEvent::ApplicationDeactivate:
- return new QEvent(*e);
-
- case QEvent::QueryWhatsThis:
- return new QHelpEvent(*static_cast<QHelpEvent*>(e));
- case QEvent::EnterWhatsThisMode:
- return new QEvent(*e);
- case QEvent::LeaveWhatsThisMode:
- return new QEvent(*e);
-
- case QEvent::ZOrderChange:
- return new QEvent(*e);
-
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove:
- return new QHoverEvent(*static_cast<QHoverEvent*>(e));
-
-#ifdef QT_KEYPAD_NAVIGATION
- case QEvent::EnterEditFocus:
- return new QEvent(*e);
- case QEvent::LeaveEditFocus:
- return new QEvent(*e);
-#endif
- case QEvent::AcceptDropsChange:
- return new QEvent(*e);
-
- case QEvent::ZeroTimerEvent:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-#if QT_CONFIG(graphicsview)
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::GraphicsSceneMousePress:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMouseDoubleClick: {
- QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent*>(e);
- QGraphicsSceneMouseEvent *me2 = new QGraphicsSceneMouseEvent(me->type());
- me2->setWidget(me->widget());
- me2->setPos(me->pos());
- me2->setScenePos(me->scenePos());
- me2->setScreenPos(me->screenPos());
-// ### for all buttons
- me2->setButtonDownPos(Qt::LeftButton, me->buttonDownPos(Qt::LeftButton));
- me2->setButtonDownPos(Qt::RightButton, me->buttonDownPos(Qt::RightButton));
- me2->setButtonDownScreenPos(Qt::LeftButton, me->buttonDownScreenPos(Qt::LeftButton));
- me2->setButtonDownScreenPos(Qt::RightButton, me->buttonDownScreenPos(Qt::RightButton));
- me2->setLastPos(me->lastPos());
- me2->setLastScenePos(me->lastScenePos());
- me2->setLastScreenPos(me->lastScreenPos());
- me2->setButtons(me->buttons());
- me2->setButton(me->button());
- me2->setModifiers(me->modifiers());
- me2->setSource(me->source());
- me2->setFlags(me->flags());
- return me2;
- }
-
- case QEvent::GraphicsSceneContextMenu: {
- QGraphicsSceneContextMenuEvent *me = static_cast<QGraphicsSceneContextMenuEvent*>(e);
- QGraphicsSceneContextMenuEvent *me2 = new QGraphicsSceneContextMenuEvent(me->type());
- me2->setWidget(me->widget());
- me2->setPos(me->pos());
- me2->setScenePos(me->scenePos());
- me2->setScreenPos(me->screenPos());
- me2->setModifiers(me->modifiers());
- me2->setReason(me->reason());
- return me2;
- }
-
- case QEvent::GraphicsSceneHoverEnter:
- case QEvent::GraphicsSceneHoverMove:
- case QEvent::GraphicsSceneHoverLeave: {
- QGraphicsSceneHoverEvent *he = static_cast<QGraphicsSceneHoverEvent*>(e);
- QGraphicsSceneHoverEvent *he2 = new QGraphicsSceneHoverEvent(he->type());
- he2->setPos(he->pos());
- he2->setScenePos(he->scenePos());
- he2->setScreenPos(he->screenPos());
- he2->setLastPos(he->lastPos());
- he2->setLastScenePos(he->lastScenePos());
- he2->setLastScreenPos(he->lastScreenPos());
- he2->setModifiers(he->modifiers());
- return he2;
- }
- case QEvent::GraphicsSceneHelp:
- return new QHelpEvent(*static_cast<QHelpEvent*>(e));
- case QEvent::GraphicsSceneDragEnter:
- case QEvent::GraphicsSceneDragMove:
- case QEvent::GraphicsSceneDragLeave:
- case QEvent::GraphicsSceneDrop: {
- QGraphicsSceneDragDropEvent *dde = static_cast<QGraphicsSceneDragDropEvent*>(e);
- QGraphicsSceneDragDropEvent *dde2 = new QGraphicsSceneDragDropEvent(dde->type());
- dde2->setPos(dde->pos());
- dde2->setScenePos(dde->scenePos());
- dde2->setScreenPos(dde->screenPos());
- dde2->setButtons(dde->buttons());
- dde2->setModifiers(dde->modifiers());
- return dde2;
- }
- case QEvent::GraphicsSceneWheel: {
- QGraphicsSceneWheelEvent *we = static_cast<QGraphicsSceneWheelEvent*>(e);
- QGraphicsSceneWheelEvent *we2 = new QGraphicsSceneWheelEvent(we->type());
- we2->setPos(we->pos());
- we2->setScenePos(we->scenePos());
- we2->setScreenPos(we->screenPos());
- we2->setButtons(we->buttons());
- we2->setModifiers(we->modifiers());
- we2->setOrientation(we->orientation());
- we2->setDelta(we->delta());
- return we2;
- }
-#endif
- case QEvent::KeyboardLayoutChange:
- return new QEvent(*e);
-
- case QEvent::DynamicPropertyChange:
- return new QDynamicPropertyChangeEvent(*static_cast<QDynamicPropertyChangeEvent*>(e));
-
-#if QT_CONFIG(tabletevent)
- case QEvent::TabletEnterProximity:
- case QEvent::TabletLeaveProximity:
- return new QTabletEvent(*static_cast<QTabletEvent*>(e));
-#endif // QT_CONFIG(tabletevent)
-
- case QEvent::NonClientAreaMouseMove:
- case QEvent::NonClientAreaMouseButtonPress:
- case QEvent::NonClientAreaMouseButtonRelease:
- case QEvent::NonClientAreaMouseButtonDblClick:
- return new QMouseEvent(*static_cast<QMouseEvent*>(e));
-
- case QEvent::MacSizeChange:
- return new QEvent(*e);
-
- case QEvent::ContentsRectChange:
- return new QEvent(*e);
-
- case QEvent::MacGLWindowChange:
- return new QEvent(*e);
-
- case QEvent::FutureCallOut:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-#if QT_CONFIG(graphicsview)
- case QEvent::GraphicsSceneResize: {
- QGraphicsSceneResizeEvent *re = static_cast<QGraphicsSceneResizeEvent*>(e);
- QGraphicsSceneResizeEvent *re2 = new QGraphicsSceneResizeEvent();
- re2->setOldSize(re->oldSize());
- re2->setNewSize(re->newSize());
- return re2;
- }
- case QEvent::GraphicsSceneMove: {
- QGraphicsSceneMoveEvent *me = static_cast<QGraphicsSceneMoveEvent*>(e);
- QGraphicsSceneMoveEvent *me2 = new QGraphicsSceneMoveEvent();
- me2->setWidget(me->widget());
- me2->setNewPos(me->newPos());
- me2->setOldPos(me->oldPos());
- return me2;
- }
-#endif
- case QEvent::CursorChange:
- return new QEvent(*e);
- case QEvent::ToolTipChange:
- return new QEvent(*e);
-
- case QEvent::NetworkReplyUpdated:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-
- case QEvent::GrabMouse:
- case QEvent::UngrabMouse:
- case QEvent::GrabKeyboard:
- case QEvent::UngrabKeyboard:
- return new QEvent(*e);
-
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- return new QTouchEvent(*static_cast<QTouchEvent*>(e));
-
-#ifndef QT_NO_GESTURES
- case QEvent::NativeGesture:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-#endif
-
- case QEvent::User:
- case QEvent::MaxUser:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- default:
- ;
- }
- return qcoreStateMachineHandler()->cloneEvent(e);
-}
-
-const QStateMachinePrivate::Handler qt_gui_statemachine_handler = {
- cloneEvent
-};
-
-static const QStateMachinePrivate::Handler *qt_guistatemachine_last_handler = nullptr;
-void qRegisterGuiStateMachine()
-{
- qt_guistatemachine_last_handler = QStateMachinePrivate::handler;
- QStateMachinePrivate::handler = &qt_gui_statemachine_handler;
-}
-Q_CONSTRUCTOR_FUNCTION(qRegisterGuiStateMachine)
-
-void qUnregisterGuiStateMachine()
-{
- QStateMachinePrivate::handler = qt_guistatemachine_last_handler;
-}
-Q_DESTRUCTOR_FUNCTION(qUnregisterGuiStateMachine)
-
-QT_END_NAMESPACE
diff --git a/src/widgets/statemachine/qkeyeventtransition.cpp b/src/widgets/statemachine/qkeyeventtransition.cpp
deleted file mode 100644
index 1578f294d5..0000000000
--- a/src/widgets/statemachine/qkeyeventtransition.cpp
+++ /dev/null
@@ -1,174 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qkeyeventtransition.h"
-#include "qbasickeyeventtransition_p.h"
-#include <QtCore/qstatemachine.h>
-#include <private/qeventtransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QKeyEventTransition
-
- \brief The QKeyEventTransition class provides a transition for key events.
-
- \since 4.6
- \ingroup statemachine
- \inmodule QtWidgets
-
- QKeyEventTransition is part of \l{The State Machine Framework}.
-
- \sa QState::addTransition()
-*/
-
-/*!
- \property QKeyEventTransition::key
-
- \brief the key that this key event transition is associated with
-*/
-
-/*!
- \property QKeyEventTransition::modifierMask
-
- \brief the keyboard modifier mask that this key event transition checks for
-*/
-
-class QKeyEventTransitionPrivate : public QEventTransitionPrivate
-{
- Q_DECLARE_PUBLIC(QKeyEventTransition)
-public:
- QKeyEventTransitionPrivate() {}
-
- QBasicKeyEventTransition *transition;
-};
-
-/*!
- Constructs a new key event transition with the given \a sourceState.
-*/
-QKeyEventTransition::QKeyEventTransition(QState *sourceState)
- : QEventTransition(*new QKeyEventTransitionPrivate, sourceState)
-{
- Q_D(QKeyEventTransition);
- d->transition = new QBasicKeyEventTransition();
-}
-
-/*!
- Constructs a new key event transition for events of the given \a type for
- the given \a object, with the given \a key and \a sourceState.
-*/
-QKeyEventTransition::QKeyEventTransition(QObject *object, QEvent::Type type,
- int key, QState *sourceState)
- : QEventTransition(*new QKeyEventTransitionPrivate, object, type, sourceState)
-{
- Q_D(QKeyEventTransition);
- d->transition = new QBasicKeyEventTransition(type, key);
-}
-
-/*!
- Destroys this key event transition.
-*/
-QKeyEventTransition::~QKeyEventTransition()
-{
- Q_D(QKeyEventTransition);
- delete d->transition;
-}
-
-/*!
- Returns the key that this key event transition checks for.
-*/
-int QKeyEventTransition::key() const
-{
- Q_D(const QKeyEventTransition);
- return d->transition->key();
-}
-
-/*!
- Sets the \a key that this key event transition will check for.
-*/
-void QKeyEventTransition::setKey(int key)
-{
- Q_D(QKeyEventTransition);
- d->transition->setKey(key);
-}
-
-/*!
- Returns the keyboard modifier mask that this key event transition checks
- for.
-*/
-Qt::KeyboardModifiers QKeyEventTransition::modifierMask() const
-{
- Q_D(const QKeyEventTransition);
- return d->transition->modifierMask();
-}
-
-/*!
- Sets the keyboard modifier mask that this key event transition will
- check for to \a modifierMask.
-*/
-void QKeyEventTransition::setModifierMask(Qt::KeyboardModifiers modifierMask)
-{
- Q_D(QKeyEventTransition);
- d->transition->setModifierMask(modifierMask);
-}
-
-/*!
- \reimp
-*/
-bool QKeyEventTransition::eventTest(QEvent *event)
-{
- Q_D(const QKeyEventTransition);
- if (!QEventTransition::eventTest(event))
- return false;
- QStateMachine::WrappedEvent *we = static_cast<QStateMachine::WrappedEvent*>(event);
- d->transition->setEventType(we->event()->type());
- return QAbstractTransitionPrivate::get(d->transition)->callEventTest(we->event());
-}
-
-/*!
- \reimp
-*/
-void QKeyEventTransition::onTransition(QEvent *event)
-{
- QEventTransition::onTransition(event);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qkeyeventtransition.cpp"
diff --git a/src/widgets/statemachine/qkeyeventtransition.h b/src/widgets/statemachine/qkeyeventtransition.h
deleted file mode 100644
index 676f5f7846..0000000000
--- a/src/widgets/statemachine/qkeyeventtransition.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QKEYEVENTTRANSITION_H
-#define QKEYEVENTTRANSITION_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtCore/qeventtransition.h>
-
-QT_REQUIRE_CONFIG(qeventtransition);
-
-QT_BEGIN_NAMESPACE
-
-class QKeyEventTransitionPrivate;
-class Q_WIDGETS_EXPORT QKeyEventTransition : public QEventTransition
-{
- Q_OBJECT
- Q_PROPERTY(int key READ key WRITE setKey)
- Q_PROPERTY(Qt::KeyboardModifiers modifierMask READ modifierMask WRITE setModifierMask)
-public:
- QKeyEventTransition(QState *sourceState = nullptr);
- QKeyEventTransition(QObject *object, QEvent::Type type, int key,
- QState *sourceState = nullptr);
- ~QKeyEventTransition();
-
- int key() const;
- void setKey(int key);
-
- Qt::KeyboardModifiers modifierMask() const;
- void setModifierMask(Qt::KeyboardModifiers modifiers);
-
-protected:
- void onTransition(QEvent *event) override;
- bool eventTest(QEvent *event) override;
-
-private:
- Q_DISABLE_COPY(QKeyEventTransition)
- Q_DECLARE_PRIVATE(QKeyEventTransition)
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/widgets/statemachine/qmouseeventtransition.cpp b/src/widgets/statemachine/qmouseeventtransition.cpp
deleted file mode 100644
index c58dae55a3..0000000000
--- a/src/widgets/statemachine/qmouseeventtransition.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmouseeventtransition.h"
-#include "qbasicmouseeventtransition_p.h"
-#include <QtCore/qstatemachine.h>
-#include <QtGui/qpainterpath.h>
-#include <private/qeventtransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QMouseEventTransition
-
- \brief The QMouseEventTransition class provides a transition for mouse events.
-
- \since 4.6
- \ingroup statemachine
- \inmodule QtWidgets
-
- QMouseEventTransition is part of \l{The State Machine Framework}.
-
- \sa QState::addTransition()
-*/
-
-/*!
- \property QMouseEventTransition::button
-
- \brief the button that this mouse event transition is associated with
-*/
-
-/*!
- \property QMouseEventTransition::modifierMask
-
- \brief the keyboard modifier mask that this mouse event transition checks for
-*/
-
-class QMouseEventTransitionPrivate : public QEventTransitionPrivate
-{
- Q_DECLARE_PUBLIC(QMouseEventTransition)
-public:
- QMouseEventTransitionPrivate();
-
- QBasicMouseEventTransition *transition;
-};
-
-QMouseEventTransitionPrivate::QMouseEventTransitionPrivate()
-{
-}
-
-/*!
- Constructs a new mouse event transition with the given \a sourceState.
-*/
-QMouseEventTransition::QMouseEventTransition(QState *sourceState)
- : QEventTransition(*new QMouseEventTransitionPrivate, sourceState)
-{
- Q_D(QMouseEventTransition);
- d->transition = new QBasicMouseEventTransition();
-}
-
-/*!
- Constructs a new mouse event transition for events of the given \a type for
- the given \a object, with the given \a button and \a sourceState.
-*/
-QMouseEventTransition::QMouseEventTransition(QObject *object, QEvent::Type type,
- Qt::MouseButton button,
- QState *sourceState)
- : QEventTransition(*new QMouseEventTransitionPrivate, object, type, sourceState)
-{
- Q_D(QMouseEventTransition);
- d->transition = new QBasicMouseEventTransition(type, button);
-}
-
-/*!
- Destroys this mouse event transition.
-*/
-QMouseEventTransition::~QMouseEventTransition()
-{
- Q_D(QMouseEventTransition);
- delete d->transition;
-}
-
-/*!
- Returns the button that this mouse event transition checks for.
-*/
-Qt::MouseButton QMouseEventTransition::button() const
-{
- Q_D(const QMouseEventTransition);
- return d->transition->button();
-}
-
-/*!
- Sets the \a button that this mouse event transition will check for.
-*/
-void QMouseEventTransition::setButton(Qt::MouseButton button)
-{
- Q_D(QMouseEventTransition);
- d->transition->setButton(button);
-}
-
-/*!
- Returns the keyboard modifier mask that this mouse event transition checks
- for.
-*/
-Qt::KeyboardModifiers QMouseEventTransition::modifierMask() const
-{
- Q_D(const QMouseEventTransition);
- return d->transition->modifierMask();
-}
-
-/*!
- Sets the keyboard modifier mask that this mouse event transition will
- check for to \a modifierMask.
-*/
-void QMouseEventTransition::setModifierMask(Qt::KeyboardModifiers modifierMask)
-{
- Q_D(QMouseEventTransition);
- d->transition->setModifierMask(modifierMask);
-}
-
-/*!
- Returns the hit test path for this mouse event transition.
-*/
-QPainterPath QMouseEventTransition::hitTestPath() const
-{
- Q_D(const QMouseEventTransition);
- return d->transition->hitTestPath();
-}
-
-/*!
- Sets the hit test path for this mouse event transition to \a path.
- If a valid path has been set, the transition will only trigger if the mouse
- event position (QMouseEvent::pos()) is inside the path.
-
- \sa QPainterPath::contains()
-*/
-void QMouseEventTransition::setHitTestPath(const QPainterPath &path)
-{
- Q_D(QMouseEventTransition);
- d->transition->setHitTestPath(path);
-}
-
-/*!
- \reimp
-*/
-bool QMouseEventTransition::eventTest(QEvent *event)
-{
- Q_D(const QMouseEventTransition);
- if (!QEventTransition::eventTest(event))
- return false;
- QStateMachine::WrappedEvent *we = static_cast<QStateMachine::WrappedEvent*>(event);
- d->transition->setEventType(we->event()->type());
- return QAbstractTransitionPrivate::get(d->transition)->callEventTest(we->event());
-}
-
-/*!
- \reimp
-*/
-void QMouseEventTransition::onTransition(QEvent *event)
-{
- QEventTransition::onTransition(event);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qmouseeventtransition.cpp"
diff --git a/src/widgets/statemachine/qmouseeventtransition.h b/src/widgets/statemachine/qmouseeventtransition.h
deleted file mode 100644
index 41f738d894..0000000000
--- a/src/widgets/statemachine/qmouseeventtransition.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QMOUSEEVENTTRANSITION_H
-#define QMOUSEEVENTTRANSITION_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtCore/qeventtransition.h>
-
-QT_REQUIRE_CONFIG(qeventtransition);
-
-QT_BEGIN_NAMESPACE
-
-class QMouseEventTransitionPrivate;
-class QPainterPath;
-class Q_WIDGETS_EXPORT QMouseEventTransition : public QEventTransition
-{
- Q_OBJECT
- Q_PROPERTY(Qt::MouseButton button READ button WRITE setButton)
- Q_PROPERTY(Qt::KeyboardModifiers modifierMask READ modifierMask WRITE setModifierMask)
-public:
- QMouseEventTransition(QState *sourceState = nullptr);
- QMouseEventTransition(QObject *object, QEvent::Type type,
- Qt::MouseButton button, QState *sourceState = nullptr);
- ~QMouseEventTransition();
-
- Qt::MouseButton button() const;
- void setButton(Qt::MouseButton button);
-
- Qt::KeyboardModifiers modifierMask() const;
- void setModifierMask(Qt::KeyboardModifiers modifiers);
-
- QPainterPath hitTestPath() const;
- void setHitTestPath(const QPainterPath &path);
-
-protected:
- void onTransition(QEvent *event) override;
- bool eventTest(QEvent *event) override;
-
-private:
- Q_DISABLE_COPY(QMouseEventTransition)
- Q_DECLARE_PRIVATE(QMouseEventTransition)
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/widgets/statemachine/statemachine.pri b/src/widgets/statemachine/statemachine.pri
deleted file mode 100644
index 7b6407bde5..0000000000
--- a/src/widgets/statemachine/statemachine.pri
+++ /dev/null
@@ -1,16 +0,0 @@
-
-qtConfig(statemachine): \
- SOURCES += $$PWD/qguistatemachine.cpp
-
-qtConfig(qeventtransition) {
- HEADERS += \
- $$PWD/qkeyeventtransition.h \
- $$PWD/qmouseeventtransition.h \
- $$PWD/qbasickeyeventtransition_p.h \
- $$PWD/qbasicmouseeventtransition_p.h
- SOURCES += \
- $$PWD/qkeyeventtransition.cpp \
- $$PWD/qmouseeventtransition.cpp \
- $$PWD/qbasickeyeventtransition.cpp \
- $$PWD/qbasicmouseeventtransition.cpp
-}
diff --git a/src/widgets/styles/images/check_list_controller.svg b/src/widgets/styles/images/check_list_controller.svg
new file mode 100644
index 0000000000..ea94cf4d5d
--- /dev/null
+++ b/src/widgets/styles/images/check_list_controller.svg
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="16px" height="16px" viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#BDBEBF;}
+ .st1{fill:#FACE20;}
+ .st2{fill:none;}
+</style>
+<g>
+ <g>
+ <rect x="3" y="4" class="st0" width="10" height="10"/>
+ </g>
+ <g>
+ <rect x="1" y="2" class="st1" width="10" height="10"/>
+ </g>
+ <g>
+ <rect class="st2" width="16" height="16"/>
+ </g>
+</g>
+</svg>
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/closedock-down-macstyle-10.png b/src/widgets/styles/images/closedock-down-macstyle-10.png
new file mode 100644
index 0000000000..45862f93ff
--- /dev/null
+++ b/src/widgets/styles/images/closedock-down-macstyle-10.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-down-macstyle-20.png b/src/widgets/styles/images/closedock-down-macstyle-20.png
new file mode 100644
index 0000000000..9112f6968f
--- /dev/null
+++ b/src/widgets/styles/images/closedock-down-macstyle-20.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-down-macstyle-32.png b/src/widgets/styles/images/closedock-down-macstyle-32.png
new file mode 100644
index 0000000000..ec91d61c1c
--- /dev/null
+++ b/src/widgets/styles/images/closedock-down-macstyle-32.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-down-macstyle-48.png b/src/widgets/styles/images/closedock-down-macstyle-48.png
new file mode 100644
index 0000000000..dee933d8b3
--- /dev/null
+++ b/src/widgets/styles/images/closedock-down-macstyle-48.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-down-macstyle-64.png b/src/widgets/styles/images/closedock-down-macstyle-64.png
new file mode 100644
index 0000000000..134e9c5a1f
--- /dev/null
+++ b/src/widgets/styles/images/closedock-down-macstyle-64.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-down-macstyle.svg b/src/widgets/styles/images/closedock-down-macstyle.svg
new file mode 100644
index 0000000000..04f841937a
--- /dev/null
+++ b/src/widgets/styles/images/closedock-down-macstyle.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:none;}
+</style>
+<g>
+ <path d="M8,1C4.13,1,1,4.13,1,8c0,3.87,3.13,7,7,7s7-3.13,7-7C15,4.13,11.87,1,8,1z M11.18,9.77c0.39,0.39,0.39,1.02,0,1.41
+ c-0.2,0.2-0.45,0.29-0.71,0.29s-0.51-0.1-0.71-0.29L8,9.41l-1.77,1.77c-0.2,0.2-0.45,0.29-0.71,0.29s-0.51-0.1-0.71-0.29
+ c-0.39-0.39-0.39-1.02,0-1.41L6.59,8L4.82,6.23c-0.39-0.39-0.39-1.02,0-1.41s1.02-0.39,1.41,0L8,6.59l1.77-1.77
+ c0.39-0.39,1.02-0.39,1.41,0s0.39,1.02,0,1.41L9.41,8L11.18,9.77z"/>
+ <rect class="st0" width="16" height="16"/>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/closedock-macstyle-10.png b/src/widgets/styles/images/closedock-macstyle-10.png
new file mode 100644
index 0000000000..3746c7af00
--- /dev/null
+++ b/src/widgets/styles/images/closedock-macstyle-10.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-macstyle-20.png b/src/widgets/styles/images/closedock-macstyle-20.png
new file mode 100644
index 0000000000..78cc630ea1
--- /dev/null
+++ b/src/widgets/styles/images/closedock-macstyle-20.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-macstyle-32.png b/src/widgets/styles/images/closedock-macstyle-32.png
new file mode 100644
index 0000000000..564efe187b
--- /dev/null
+++ b/src/widgets/styles/images/closedock-macstyle-32.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-macstyle-48.png b/src/widgets/styles/images/closedock-macstyle-48.png
new file mode 100644
index 0000000000..7c9f1b8960
--- /dev/null
+++ b/src/widgets/styles/images/closedock-macstyle-48.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-macstyle-64.png b/src/widgets/styles/images/closedock-macstyle-64.png
new file mode 100644
index 0000000000..399548d014
--- /dev/null
+++ b/src/widgets/styles/images/closedock-macstyle-64.png
Binary files differ
diff --git a/src/widgets/styles/images/closedock-macstyle.svg b/src/widgets/styles/images/closedock-macstyle.svg
new file mode 100644
index 0000000000..9348997f7b
--- /dev/null
+++ b/src/widgets/styles/images/closedock-macstyle.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#5E5E5E;}
+ .st1{fill:none;}
+</style>
+<g>
+ <path class="st0" d="M8,1C4.1,1,1,4.1,1,8c0,3.9,3.1,7,7,7s7-3.1,7-7C15,4.1,11.9,1,8,1z M11.2,9.8c0.4,0.4,0.4,1,0,1.4
+ c-0.2,0.2-0.5,0.3-0.7,0.3s-0.5-0.1-0.7-0.3L8,9.4l-1.8,1.8c-0.2,0.2-0.5,0.3-0.7,0.3S5,11.4,4.8,11.2c-0.4-0.4-0.4-1,0-1.4L6.6,8
+ L4.8,6.2c-0.4-0.4-0.4-1,0-1.4s1-0.4,1.4,0L8,6.6l1.8-1.8c0.4-0.4,1-0.4,1.4,0s0.4,1,0,1.4L9.4,8L11.2,9.8z"/>
+ <rect class="st1" width="16" height="16"/>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/closedock.svg b/src/widgets/styles/images/closedock.svg
new file mode 100644
index 0000000000..dfd6be6d48
--- /dev/null
+++ b/src/widgets/styles/images/closedock.svg
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="8px" height="8px" viewBox="0 0 8 8" style="enable-background:new 0 0 8 8;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:none;}
+ .st1{fill:#353637;}
+</style>
+<g>
+ <g>
+ <rect class="st0" width="8" height="8"/>
+ </g>
+ <g>
+ <rect x="3.3" y="0.1" transform="matrix(0.7071 0.7071 -0.7071 0.7071 4 -1.6569)" class="st1" width="1.4" height="7.8"/>
+ <rect x="3.3" y="0.1" transform="matrix(-0.7071 0.7071 -0.7071 -0.7071 9.6569 4)" class="st1" width="1.4" height="7.8"/>
+ </g>
+</g>
+</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/critical.svg b/src/widgets/styles/images/critical.svg
new file mode 100644
index 0000000000..8be2931e68
--- /dev/null
+++ b/src/widgets/styles/images/critical.svg
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="32px" height="32px" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#E41E25;}
+ .st1{fill:none;}
+</style>
+<g id="editclear">
+ <path class="st0" d="M16,2.1c-7.7,0-14,6.3-14,14s6.3,14,14,14c7.7,0,14-6.3,14-14S23.8,2.1,16,2.1z M23.5,21.3l-2.3,2.3L16,18.3
+ l-5.2,5.2l-2.3-2.3l5.2-5.2l-5.2-5.2l2.3-2.3l5.2,5.2l5.2-5.2l2.3,2.3L18.3,16L23.5,21.3z"/>
+ <rect class="st1" width="32" height="32"/>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/dockdock-down-macstyle-10.png b/src/widgets/styles/images/dockdock-down-macstyle-10.png
new file mode 100644
index 0000000000..44215cadec
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-down-macstyle-10.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-down-macstyle-20.png b/src/widgets/styles/images/dockdock-down-macstyle-20.png
new file mode 100644
index 0000000000..265da15789
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-down-macstyle-20.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-down-macstyle-32.png b/src/widgets/styles/images/dockdock-down-macstyle-32.png
new file mode 100644
index 0000000000..394e90dcd3
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-down-macstyle-32.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-down-macstyle-48.png b/src/widgets/styles/images/dockdock-down-macstyle-48.png
new file mode 100644
index 0000000000..34c1640597
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-down-macstyle-48.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-down-macstyle-64.png b/src/widgets/styles/images/dockdock-down-macstyle-64.png
new file mode 100644
index 0000000000..12435d8c73
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-down-macstyle-64.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-down-macstyle.svg b/src/widgets/styles/images/dockdock-down-macstyle.svg
new file mode 100644
index 0000000000..d970fe7edf
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-down-macstyle.svg
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:none;}
+</style>
+<g>
+ <rect class="st0" width="16" height="16"/>
+ <g>
+ <rect x="5" y="8" width="4" height="3"/>
+ <polygon points="10,9 11,9 11,6 7,6 7,7 10,7 "/>
+ <path d="M8,1C4.13,1,1,4.13,1,8c0,3.87,3.13,7,7,7s7-3.13,7-7C15,4.13,11.87,1,8,1z M12,10h-2v2H4V7h2V5h6V10z"/>
+ </g>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/dockdock-macstyle-10.png b/src/widgets/styles/images/dockdock-macstyle-10.png
new file mode 100644
index 0000000000..e4d9d147ca
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-macstyle-10.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-macstyle-20.png b/src/widgets/styles/images/dockdock-macstyle-20.png
new file mode 100644
index 0000000000..3e9233dc82
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-macstyle-20.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-macstyle-32.png b/src/widgets/styles/images/dockdock-macstyle-32.png
new file mode 100644
index 0000000000..5639a73e94
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-macstyle-32.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-macstyle-48.png b/src/widgets/styles/images/dockdock-macstyle-48.png
new file mode 100644
index 0000000000..fd8c91b094
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-macstyle-48.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-macstyle-64.png b/src/widgets/styles/images/dockdock-macstyle-64.png
new file mode 100644
index 0000000000..43dc7ed091
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-macstyle-64.png
Binary files differ
diff --git a/src/widgets/styles/images/dockdock-macstyle.svg b/src/widgets/styles/images/dockdock-macstyle.svg
new file mode 100644
index 0000000000..f29fb8bc9f
--- /dev/null
+++ b/src/widgets/styles/images/dockdock-macstyle.svg
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:none;}
+ .st1{fill:#5E5E5E;}
+</style>
+<g>
+ <rect class="st0" width="16" height="16"/>
+ <g>
+ <rect x="5" y="8" class="st1" width="4" height="3"/>
+ <polygon class="st1" points="10,9 11,9 11,6 7,6 7,7 10,7 "/>
+ <path class="st1" d="M8,1C4.1,1,1,4.1,1,8c0,3.9,3.1,7,7,7s7-3.1,7-7C15,4.1,11.9,1,8,1z M12,10h-2v2H4V7h2V5h6V10z"/>
+ </g>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/file_open.svg b/src/widgets/styles/images/file_open.svg
new file mode 100644
index 0000000000..d80bd5b32e
--- /dev/null
+++ b/src/widgets/styles/images/file_open.svg
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="22px" height="22px" viewBox="0 0 22 22" style="enable-background:new 0 0 22 22;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#FACE20;}
+ .st1{fill:none;}
+ .st2{fill:#353637;}
+</style>
+<g>
+ <polygon class="st0" points="8,13 2.7,18 2,18 2,17 7,12 17,12 17,9 8,9 6,7 0,7 0,16 0,20 1,20 2,20 4,20 15,20 21,13 "/>
+ <rect class="st1" width="22" height="22"/>
+ <g>
+ <path class="st2" d="M19.4,9.9l-0.7-0.7C18.9,8.6,19,8.1,19,7.5c0-2.2-1.8-4-4-4c-0.9,0-1.7,0.3-2.4,0.8l-0.7-0.7
+ c0.9-0.7,1.9-1.1,3.1-1.1c2.8,0,5,2.2,5,5C20,8.4,19.8,9.2,19.4,9.9z"/>
+ <polygon class="st2" points="17,7.5 22,7.5 19.5,10 "/>
+ </g>
+</g>
+</svg>
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_end.svg b/src/widgets/styles/images/filedialog_end.svg
new file mode 100644
index 0000000000..b52b4b66a3
--- /dev/null
+++ b/src/widgets/styles/images/filedialog_end.svg
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="16px" height="16px" viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#FACE20;}
+ .st1{fill:#FFFFFF;}
+ .st2{fill:#353637;}
+ .st3{fill:none;}
+</style>
+<g>
+ <polygon class="st0" points="13,8 15,16 16,16 16,5 7,5 6,4 2,4 2,8 "/>
+ <g>
+ <g>
+ <polygon class="st1" points="2.5,13.5 2.5,3.5 6.8,3.5 9.5,6.2 9.5,13.5 "/>
+ <path class="st2" d="M6.6,4L9,6.4V13H3V4H6.6 M7,3H2v11h8V6L7,3L7,3z"/>
+ </g>
+ <g>
+ <polygon class="st2" points="9,7 6,7 6,4 7,4 7,6 9,6 "/>
+ </g>
+ </g>
+ <polygon class="st0" points="12,9 13.3,14 16,14 16,16 10,16 2,16 0,9 "/>
+ <g>
+ <rect class="st3" width="16" height="16"/>
+ </g>
+</g>
+</svg>
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/filedialog_start.svg b/src/widgets/styles/images/filedialog_start.svg
new file mode 100644
index 0000000000..2dad8e1922
--- /dev/null
+++ b/src/widgets/styles/images/filedialog_start.svg
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="16px" height="16px" viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#FACE20;}
+ .st1{fill:#FFFFFF;}
+ .st2{fill:#353637;}
+ .st3{fill:none;}
+</style>
+<g>
+ <polygon class="st0" points="13,8 15,16 16,16 16,5 7,5 6,4 2,4 2,8 "/>
+ <g>
+ <g>
+ <polygon class="st1" points="6.5,13.5 6.5,2.5 11.8,2.5 15.5,6.2 15.5,13.5 "/>
+ <path class="st2" d="M11.6,3L15,6.4V13H7V3H11.6 M12,2H6v12h10V6L12,2L12,2z"/>
+ </g>
+ <g>
+ <polygon class="st2" points="15,7 11,7 11,3 12,3 12,6 15,6 "/>
+ </g>
+ </g>
+ <polygon class="st0" points="12,9 13.3,14 16,14 16,16 9,16 2,16 0,9 "/>
+ <g>
+ <rect class="st3" width="16" height="16"/>
+ </g>
+</g>
+</svg>
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/information.svg b/src/widgets/styles/images/information.svg
new file mode 100644
index 0000000000..da73144eec
--- /dev/null
+++ b/src/widgets/styles/images/information.svg
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="32px" height="32px" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#46A2DA;}
+ .st1{fill:none;}
+</style>
+<g>
+ <path class="st0" d="M16,4C9.4,4,4,9.4,4,16c0,6.6,5.4,12,12,12s12-5.4,12-12C28,9.4,22.6,4,16,4z M18,24h-4V14h4V24z M18,12h-4V8
+ h4V12z"/>
+ <rect class="st1" width="32" height="32"/>
+</g>
+</svg>
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/qt_close.svg b/src/widgets/styles/images/qt_close.svg
new file mode 100644
index 0000000000..7e95cba298
--- /dev/null
+++ b/src/widgets/styles/images/qt_close.svg
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="10px" height="10px" viewBox="0 0 10 10" style="enable-background:new 0 0 10 10;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:none;}
+ .st1{fill:#353637;}
+</style>
+<g>
+ <g>
+ <rect class="st0" width="10" height="10"/>
+ </g>
+ <g>
+ <rect x="4.1" y="0.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 5.0216 -2.0621)" class="st1" width="1.7" height="9.7"/>
+ <rect x="4.1" y="0.2" transform="matrix(-0.7071 0.7071 -0.7071 -0.7071 12.0926 5.0521)" class="st1" width="1.7" height="9.7"/>
+ </g>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/qt_help.svg b/src/widgets/styles/images/qt_help.svg
new file mode 100644
index 0000000000..8ffa5746ea
--- /dev/null
+++ b/src/widgets/styles/images/qt_help.svg
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="10px" height="10px" viewBox="0 0 10 10" style="enable-background:new 0 0 10 10;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#353637;}
+ .st1{fill:none;}
+</style>
+<g>
+ <g>
+ <path class="st0" d="M5.8,9.7C5.6,9.9,5.4,10,5.1,10C5,10,4.8,10,4.7,9.9C4.6,9.9,4.5,9.8,4.4,9.7C4.3,9.6,4.2,9.5,4.1,9.4
+ C4.1,9.3,4,9.1,4,9c0-0.3,0.1-0.5,0.3-0.7C4.6,8.1,4.8,8,5.1,8c0.3,0,0.5,0.1,0.7,0.3C6,8.5,6.1,8.7,6.1,9C6.1,9.3,6,9.5,5.8,9.7z
+ "/>
+ <path class="st0" d="M7.8,3.4C7.7,3.6,7.6,3.8,7.5,4C7.3,4.2,7.2,4.3,7,4.5C6.8,4.7,6.6,4.8,6.4,5C6.3,5.1,6.2,5.2,6.1,5.3
+ C6,5.4,6,5.5,5.9,5.6C5.8,5.7,5.8,5.8,5.8,5.9c0,0.1,0,0.3,0,0.4v0.5H4.1V6.1c0-0.2,0-0.4,0-0.5c0-0.1,0.1-0.3,0.1-0.4
+ C4.4,5.1,4.4,5,4.5,4.9c0.1-0.1,0.2-0.2,0.3-0.4l1-1C6.1,3.3,6.2,3,6.2,2.7c0-0.3-0.1-0.6-0.3-0.8C5.7,1.6,5.4,1.5,5,1.5
+ c-0.4,0-0.7,0.1-0.9,0.4C3.9,2.1,3.7,2.4,3.7,2.8L2,2.7c0.1-0.4,0.2-0.8,0.3-1.1C2.5,1.2,2.7,0.9,3,0.7c0.3-0.2,0.6-0.4,0.9-0.5
+ S4.7,0,5.1,0c0.4,0,0.8,0.1,1.1,0.2c0.3,0.1,0.6,0.3,0.9,0.5c0.3,0.2,0.4,0.5,0.6,0.8c0.1,0.3,0.2,0.7,0.2,1.1
+ C7.9,2.9,7.8,3.1,7.8,3.4z"/>
+ </g>
+ <g>
+ <rect class="st1" width="10" height="10"/>
+ </g>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/qt_maximize.svg b/src/widgets/styles/images/qt_maximize.svg
new file mode 100644
index 0000000000..db88025174
--- /dev/null
+++ b/src/widgets/styles/images/qt_maximize.svg
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="10px" height="10px" viewBox="0 0 10 10" style="enable-background:new 0 0 10 10;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#343638;}
+</style>
+<g>
+ <path class="st0" d="M9,1v8H1V1H9 M10,0H0v10h10V0L10,0z"/>
+ <rect class="st0" width="10" height="3"/>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/qt_menu.svg b/src/widgets/styles/images/qt_menu.svg
new file mode 100644
index 0000000000..77c7f23d0c
--- /dev/null
+++ b/src/widgets/styles/images/qt_menu.svg
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="16px" height="16px" viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#41CD52;}
+ .st1{fill:#FFFFFF;}
+ .st2{fill:none;}
+</style>
+<g>
+ <g>
+ <polygon class="st0" points="2.2,2 2.2,2 0,4.2 0,14 13.8,14 16,11.8 16,2 "/>
+ <path class="st1" d="M6,11.3c-1.1,0-1.8-0.3-2.2-0.9C3.3,9.9,3.1,9,3.1,7.8c0-1.2,0.2-2.1,0.6-2.7S4.9,4.2,6,4.2
+ c1,0,1.8,0.3,2.2,0.9c0.4,0.6,0.6,1.5,0.6,2.7c0,0.8-0.1,1.5-0.3,2c-0.2,0.5-0.5,0.9-0.8,1.1l0.9,1.4l-1,0.5l-0.9-1.5
+ C6.4,11.3,6.2,11.3,6,11.3z M4.6,9.8c0.2,0.4,0.7,0.6,1.3,0.6S7,10.2,7.3,9.8c0.2-0.4,0.3-1,0.3-2c0-0.9-0.1-1.6-0.3-2
+ S6.6,5.2,6,5.2c-0.6,0-1.1,0.2-1.3,0.6c-0.2,0.4-0.4,1.1-0.4,2C4.3,8.7,4.4,9.4,4.6,9.8z"/>
+ <path class="st1" d="M12.7,7h-1.4v2.2c0,0.4,0,0.7,0.1,0.8c0.1,0.1,0.2,0.2,0.5,0.2l0.8,0l0,0.9c-0.5,0.1-0.8,0.1-1,0.1
+ c-0.6,0-1-0.1-1.2-0.4s-0.3-0.8-0.3-1.5V7H9.4V6h0.8V4.6h1.1V6h1.4L12.7,7L12.7,7z"/>
+ </g>
+ <rect class="st2" width="16" height="16"/>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/qt_minimize.svg b/src/widgets/styles/images/qt_minimize.svg
new file mode 100644
index 0000000000..891e401c37
--- /dev/null
+++ b/src/widgets/styles/images/qt_minimize.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="10px" height="10px" viewBox="0 0 10 10" style="enable-background:new 0 0 10 10;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#353637;}
+ .st1{fill:none;}
+</style>
+<g>
+ <rect x="1" y="7" class="st0" width="7" height="2"/>
+ <g>
+ <rect class="st1" width="10" height="10"/>
+ </g>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/qt_normalizeup.svg b/src/widgets/styles/images/qt_normalizeup.svg
new file mode 100644
index 0000000000..865cebca76
--- /dev/null
+++ b/src/widgets/styles/images/qt_normalizeup.svg
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="10px" height="10px" viewBox="0 0 10 10" style="enable-background:new 0 0 10 10;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#353637;}
+ .st1{fill:none;}
+</style>
+<g>
+ <g>
+ <rect x="4" class="st0" width="6" height="2"/>
+ <polygon class="st0" points="4,0 4,5 5,5 5,1 9,1 9,5 7,5 7,6 10,6 10,0 "/>
+ </g>
+ <g>
+ <path class="st0" d="M7,4v4H3V4H7 M8,3H2v6h6V3L8,3z"/>
+ <rect x="2" y="3" class="st0" width="6" height="2"/>
+ </g>
+ <rect class="st1" width="10" height="10"/>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/qt_shade.svg b/src/widgets/styles/images/qt_shade.svg
new file mode 100644
index 0000000000..e90a86e861
--- /dev/null
+++ b/src/widgets/styles/images/qt_shade.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="10px" height="10px" viewBox="0 0 10 10" style="enable-background:new 0 0 10 10;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#353637;}
+ .st1{fill:none;}
+</style>
+<g>
+ <polygon class="st0" points="9,8 1,8 5,3 "/>
+ <g>
+ <rect class="st1" width="10" height="10"/>
+ </g>
+</g>
+</svg>
diff --git a/src/widgets/styles/images/qt_unshade.svg b/src/widgets/styles/images/qt_unshade.svg
new file mode 100644
index 0000000000..805292cd7f
--- /dev/null
+++ b/src/widgets/styles/images/qt_unshade.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="10px" height="10px" viewBox="0 0 10 10" style="enable-background:new 0 0 10 10;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#353637;}
+ .st1{fill:none;}
+</style>
+<g>
+ <polygon class="st0" points="1,2 9,2 5,7 "/>
+ <g>
+ <rect class="st1" width="10" height="10"/>
+ </g>
+</g>
+</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/question.svg b/src/widgets/styles/images/question.svg
new file mode 100644
index 0000000000..20fafa8941
--- /dev/null
+++ b/src/widgets/styles/images/question.svg
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="32px" height="32px" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#46A2DA;}
+ .st1{fill:none;}
+</style>
+<g>
+ <path class="st0" d="M16,4C9.4,4,4,9.4,4,16s5.4,12,12,12s12-5.4,12-12S22.6,4,16,4z M17.4,23.3c-0.3,0.3-0.7,0.5-1.2,0.5
+ c-0.2,0-0.4,0-0.6-0.1c-0.2-0.1-0.4-0.2-0.5-0.3c-0.2-0.1-0.3-0.3-0.4-0.5c-0.1-0.2-0.1-0.4-0.1-0.6c0-0.4,0.2-0.8,0.5-1.2
+ c0.3-0.3,0.7-0.5,1.2-0.5c0.4,0,0.8,0.2,1.2,0.5c0.3,0.3,0.5,0.7,0.5,1.1C17.9,22.6,17.7,22.9,17.4,23.3z M20.7,13.7
+ c-0.1,0.4-0.3,0.7-0.5,1c-0.2,0.3-0.5,0.6-0.7,0.8c-0.3,0.3-0.6,0.5-0.9,0.8c-0.2,0.2-0.4,0.3-0.5,0.5c-0.1,0.1-0.3,0.3-0.3,0.4
+ c-0.1,0.1-0.2,0.3-0.2,0.5c0,0.2-0.1,0.4-0.1,0.7v0.8h-2.5v-1.2c0-0.3,0-0.6,0.1-0.8c0-0.2,0.1-0.4,0.2-0.6
+ c0.1-0.2,0.2-0.3,0.4-0.5c0.1-0.2,0.3-0.4,0.5-0.6l1.6-1.6c0.3-0.4,0.5-0.8,0.5-1.4c0-0.5-0.2-1-0.5-1.3c-0.4-0.3-0.8-0.5-1.4-0.5
+ c-0.6,0-1.1,0.2-1.5,0.6c-0.4,0.4-0.6,0.9-0.7,1.5l-2.7-0.2c0.1-0.7,0.3-1.3,0.5-1.8c0.3-0.5,0.6-1,1-1.3c0.4-0.4,0.9-0.6,1.5-0.8
+ c0.6-0.2,1.2-0.3,1.8-0.3c0.6,0,1.2,0.1,1.8,0.3c0.5,0.2,1,0.4,1.4,0.8c0.4,0.3,0.7,0.8,0.9,1.3c0.2,0.5,0.3,1.1,0.3,1.8
+ C20.8,12.9,20.8,13.3,20.7,13.7z"/>
+ <rect class="st1" width="32" height="32"/>
+</g>
+</svg>
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
new file mode 100644
index 0000000000..effcc89eed
--- /dev/null
+++ 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
new file mode 100644
index 0000000000..dfd88920ab
--- /dev/null
+++ 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
new file mode 100644
index 0000000000..aa6afd72b2
--- /dev/null
+++ 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-h.svg b/src/widgets/styles/images/toolbar-ext-h.svg
new file mode 100644
index 0000000000..203b77625e
--- /dev/null
+++ b/src/widgets/styles/images/toolbar-ext-h.svg
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="8px" height="5px" viewBox="0 0 8 5" style="enable-background:new 0 0 8 5;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#353637;}
+ .st1{fill:none;}
+</style>
+<g>
+ <g>
+ <path class="st0" d="M4.2,2.6L2.2,5L1.5,4.6l1.7-2.1L1.5,0.4L2.2,0l2,2.4V2.6z M7.6,2.6L5.6,5L4.9,4.6l1.7-2.1L4.9,0.4L5.6,0
+ l2,2.4V2.6z"/>
+ </g>
+ <rect class="st1" width="8" height="5"/>
+</g>
+</svg>
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/toolbar-ext-v.svg b/src/widgets/styles/images/toolbar-ext-v.svg
new file mode 100644
index 0000000000..ba2eac25ee
--- /dev/null
+++ b/src/widgets/styles/images/toolbar-ext-v.svg
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="5px" height="8px" viewBox="0 0 5 8" style="enable-background:new 0 0 5 8;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#353637;}
+ .st1{fill:none;}
+</style>
+<g>
+ <g>
+ <path class="st0" d="M2.4,4.2L0,2.2l0.4-0.7l2.1,1.7l2.1-1.7L5,2.2l-2.4,2H2.4z M2.4,7.6L0,5.6l0.4-0.7l2.1,1.7l2.1-1.7L5,5.6
+ l-2.4,2H2.4z"/>
+ </g>
+ <rect x="-1.5" y="1.5" transform="matrix(-1.836970e-16 1 -1 -1.836970e-16 6.5 1.5)" class="st1" width="8" height="5"/>
+</g>
+</svg>
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/images/warning.svg b/src/widgets/styles/images/warning.svg
new file mode 100644
index 0000000000..5f6994ab33
--- /dev/null
+++ b/src/widgets/styles/images/warning.svg
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ width="32px" height="32px" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve">
+<style type="text/css">
+ .st0{fill:#FACE20;}
+ .st1{fill:none;}
+</style>
+<g>
+ <g>
+ <path class="st0" d="M17,4h-2L4,26v2h24v-2L17,4z M16,26c-1.1,0-2-0.9-2-2s0.9-2,2-2s2,0.9,2,2S17.1,26,16,26z M17.4,20h-2.8
+ L14,10h4L17.4,20z"/>
+ </g>
+ <rect class="st1" width="32" height="32"/>
+</g>
+</svg>
diff --git a/src/widgets/styles/qcommonstyle.cpp b/src/widgets/styles/qcommonstyle.cpp
index c241f7a936..046af3a073 100644
--- a/src/widgets/styles/qcommonstyle.cpp
+++ b/src/widgets/styles/qcommonstyle.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qcommonstyle.h"
#include "qcommonstyle_p.h"
@@ -114,6 +78,8 @@
#include <private/qstyleanimation_p.h>
#endif
+#include <qloggingcategory.h>
+
#include <limits.h>
#include <private/qtextengine_p.h>
@@ -121,11 +87,40 @@
QT_BEGIN_NAMESPACE
-static QWindow *qt_getWindow(const QWidget *widget)
+Q_LOGGING_CATEGORY(lcCommonStyle, "qt.widgets.commonstyle");
+
+using namespace Qt::StringLiterals;
+
+static qreal qt_getDevicePixelRatio(const QWidget *widget)
{
- return widget ? widget->window()->windowHandle() : nullptr;
+ 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.
@@ -213,29 +208,25 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
if (opt->state & (State_Sunken | State_On)) {
ir.adjust(2, 2, -2, -2);
p->setBrush(opt->palette.windowText());
- bool oldQt4CompatiblePainting = p->testRenderHint(QPainter::Qt4CompatiblePainting);
- p->setRenderHint(QPainter::Qt4CompatiblePainting);
p->drawEllipse(ir);
- p->setRenderHint(QPainter::Qt4CompatiblePainting, oldQt4CompatiblePainting);
}
break; }
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: {
@@ -244,7 +235,7 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
int posX = opt->rect.x() + (opt->rect.width() - markW)/2 + 1;
int posY = opt->rect.y() + (opt->rect.height() - markH)/2;
- QVector<QLineF> a;
+ QList<QLineF> a;
a.reserve(markH);
int i, xx, yy;
@@ -262,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);
@@ -307,7 +297,7 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
{
bool vertical = false;
if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt))
- vertical = pb->orientation == Qt::Vertical;
+ vertical = !(pb->state & QStyle::State_Horizontal);
if (!vertical) {
p->fillRect(opt->rect.x(), opt->rect.y() + 3, opt->rect.width() -2, opt->rect.height() - 6,
opt->palette.brush(QPalette::Highlight));
@@ -388,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:
@@ -415,23 +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.addPixmap(QPixmap(
- QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-closetab-16.png")),
- QIcon::Normal, QIcon::Off);
- d->tabBarcloseButtonIcon.addPixmap(QPixmap(
- QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-closetab-down-16.png")),
- QIcon::Normal, QIcon::On);
- d->tabBarcloseButtonIcon.addPixmap(QPixmap(
- QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-closetab-hover-16.png")),
- QIcon::Active, QIcon::Off);
- }
-
- int size = proxy()->pixelMetric(QStyle::PM_SmallIconSize);
+ if (d->tabBarcloseButtonIcon.isNull())
+ d->tabBarcloseButtonIcon = proxy()->standardIcon(QStyle::SP_TabCloseButton, opt, widget);
+
+ 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;
@@ -441,7 +421,7 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
mode = QIcon::Disabled;
QIcon::State state = opt->state & State_Sunken ? QIcon::On : QIcon::Off;
- QPixmap pixmap = d->tabBarcloseButtonIcon.pixmap(qt_getWindow(widget), QSize(size, size), mode, state);
+ QPixmap pixmap = d->tabBarcloseButtonIcon.pixmap(QSize(size, size), p->device()->devicePixelRatio(), mode, state);
proxy()->drawItemPixmap(p, opt->rect, Qt::AlignCenter, pixmap);
break;
}
@@ -477,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);
+ 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;
@@ -506,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;
@@ -528,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;
@@ -563,14 +577,12 @@ 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);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
+ 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());
- p->setRenderHint(QPainter::Qt4CompatiblePainting);
if (pe == PE_IndicatorSpinDown) {
const QPoint points[] = { QPoint(0, 1), QPoint(sw-1, 1), QPoint(sh-2, sh-1) };
p->drawPolygon(points, sizeof points / sizeof *points);
@@ -578,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: {
@@ -636,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);
@@ -681,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)
@@ -700,7 +710,7 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
cg = QPalette::Inactive;
- if ((vopt->state & QStyle::State_Selected) && proxy()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, opt, widget))
+ if ((vopt->state & QStyle::State_Selected) && vopt->showDecorationSelected)
p->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::Highlight));
else if (vopt->features & QStyleOptionViewItem::Alternate)
p->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::AlternateBase));
@@ -745,30 +755,31 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q
QRect r = opt->rect;
int size = qMin(r.height(), r.width());
QPixmap pixmap;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("$qt_ia-")
- % QLatin1String(metaObject()->className()), opt, QSize(size, size))
- % HexString<uint>(pe);
+ const QString pixmapName = QStyleHelper::uniqueName("$qt_ia-"_L1
+ % QLatin1StringView(metaObject()->className())
+ % HexString<uint>(pe),
+ opt, QSize(size, size));
if (!QPixmapCache::find(pixmapName, &pixmap)) {
- qreal pixelRatio = p->device()->devicePixelRatioF();
- int border = qRound(pixelRatio*(size/5));
- int sqsize = qRound(pixelRatio*(2*(size/2)));
+ const qreal pixelRatio = p->device()->devicePixelRatio();
+ const qreal border = pixelRatio * (size / 5.);
+ const qreal sqsize = pixelRatio * size;
QImage image(sqsize, sqsize, QImage::Format_ARGB32_Premultiplied);
- image.fill(0);
+ image.fill(Qt::transparent);
QPainter imagePainter(&image);
- QPolygon a;
+ 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;
@@ -782,25 +793,24 @@ 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 QRectF bounds = poly.boundingRect();
+ const qreal sx = sqsize / 2 - bounds.center().x() - 1;
+ const qreal sy = sqsize / 2 - bounds.center().y() - 1;
imagePainter.translate(sx + bsx, sy + bsy);
imagePainter.setPen(opt->palette.buttonText().color());
imagePainter.setBrush(opt->palette.buttonText());
- imagePainter.setRenderHint(QPainter::Qt4CompatiblePainting);
if (!(opt->state & State_Enabled)) {
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);
@@ -983,18 +993,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) - 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);
@@ -1150,7 +1169,7 @@ void QCommonStylePrivate::viewItemLayout(const QStyleOptionViewItem *opt, QRect
}
break; }
default:
- qWarning("doLayout: decoration position is invalid");
+ qCWarning(lcCommonStyle, "doLayout: decoration position is invalid");
decoration = *pixmapRect;
break;
}
@@ -1160,12 +1179,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;
@@ -1182,7 +1197,7 @@ QString QCommonStylePrivate::toolButtonElideText(const QStyleOptionToolButton *o
return option->text;
QString text = option->text;
- text.replace('\n', QChar::LineSeparator);
+ text.replace(u'\n', QChar::LineSeparator);
QTextOption textOption;
textOption.setWrapMode(QTextOption::ManualWrap);
textOption.setTextDirection(option->direction);
@@ -1240,7 +1255,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);
+ int iconExtent = proxyStyle->pixelMetric(QStyle::PM_SmallIconSize, opt, widget);
iconSize = QSize(iconExtent, iconExtent);
}
QSize tabIconSize = opt->icon.actualSize(iconSize,
@@ -1266,12 +1281,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);
@@ -1281,9 +1290,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();
}
@@ -1298,12 +1309,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
@@ -1349,7 +1357,8 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, btn, widget);
QRect ir = btn->rect;
QStyleOptionButton newBtn = *btn;
- newBtn.rect = QRect(ir.right() - mbi + 2, ir.height()/2 - mbi/2 + 3, mbi - 6, mbi - 6);
+ newBtn.rect = QRect(ir.right() - mbi - 2, ir.height()/2 - mbi/2 + 3, mbi - 6, mbi - 6);
+ newBtn.rect = visualRect(btn->direction, br, newBtn.rect);
proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget);
}
}
@@ -1357,10 +1366,18 @@ 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;
+ if (button->features & QStyleOptionButton::HasMenu) {
+ int indicatorSize = proxy()->pixelMetric(PM_MenuButtonIndicator, button, widget);
+ if (button->direction == Qt::LeftToRight)
+ textRect = textRect.adjusted(0, 0, -indicatorSize, 0);
+ else
+ textRect = textRect.adjusted(indicatorSize, 0, 0, 0);
+ }
+
if (!button->icon.isNull()) {
//Center both icon and text
QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
@@ -1370,7 +1387,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
if (button->state & State_On)
state = QIcon::On;
- QPixmap pixmap = button->icon.pixmap(qt_getWindow(widget), button->iconSize, mode, state);
+ QPixmap pixmap = button->icon.pixmap(button->iconSize, p->device()->devicePixelRatio(), mode, state);
int pixmapWidth = pixmap.width() / pixmap.devicePixelRatio();
int pixmapHeight = pixmap.height() / pixmap.devicePixelRatio();
int labelWidth = pixmapWidth;
@@ -1387,13 +1404,16 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
iconRect = visualRect(button->direction, textRect, iconRect);
- if (button->direction == Qt::RightToLeft) {
+ if (button->direction == Qt::RightToLeft)
+ textRect.setRight(iconRect.left() - iconSpacing / 2);
+ 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;
- textRect.setRight(iconRect.left() - iconSpacing);
- } else {
- tf |= Qt::AlignLeft; //left align, we adjust the text-rect instead
- textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing);
- }
if (button->state & (State_On | State_Sunken))
iconRect.translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget),
@@ -1406,13 +1426,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
textRect.translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget),
proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget));
- if (button->features & QStyleOptionButton::HasMenu) {
- int indicatorSize = proxy()->pixelMetric(PM_MenuButtonIndicator, button, widget);
- if (button->direction == Qt::LeftToRight)
- textRect = textRect.adjusted(0, 0, -indicatorSize, 0);
- else
- textRect = textRect.adjusted(indicatorSize, 0, 0, 0);
- }
proxy()->drawItemText(p, textRect, tf, button->palette, (button->state & State_Enabled),
button->text, QPalette::ButtonText);
}
@@ -1441,14 +1454,14 @@ 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;
QPixmap pix;
QRect textRect = btn->rect;
if (!btn->icon.isNull()) {
- pix = btn->icon.pixmap(qt_getWindow(widget), btn->iconSize, btn->state & State_Enabled ? QIcon::Normal : QIcon::Disabled);
+ pix = btn->icon.pixmap(btn->iconSize, p->device()->devicePixelRatio(), btn->state & State_Enabled ? QIcon::Normal : QIcon::Disabled);
proxy()->drawItemPixmap(p, btn->rect, alignment, pix);
if (btn->direction == Qt::RightToLeft)
textRect.setRight(textRect.right() - btn->iconSize.width() - 4);
@@ -1485,12 +1498,12 @@ 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);
- QPixmap pix = mbi->icon.pixmap(qt_getWindow(widget), QSize(iconExtent, iconExtent), (mbi->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
+ 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);
else
@@ -1525,7 +1538,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
break;
case CE_ProgressBarLabel:
if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- const bool vertical = pb->orientation == Qt::Vertical;
+ const bool vertical = !(pb->state & QStyle::State_Horizontal);
if (!vertical) {
QPalette::ColorRole textRole = QPalette::NoRole;
if ((pb->textAlignment & Qt::AlignCenter) && pb->textVisible
@@ -1550,13 +1563,13 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
QRect rect = pb->rect;
- const bool vertical = pb->orientation == Qt::Vertical;
+ const bool vertical = !(pb->state & QStyle::State_Horizontal);
const bool inverted = pb->invertedAppearance;
qint64 minimum = qint64(pb->minimum);
qint64 maximum = qint64(pb->maximum);
qint64 progress = qint64(pb->progress);
- QMatrix m;
+ QTransform m;
if (vertical) {
rect = QRect(rect.y(), rect.x(), rect.height(), rect.width()); // flip width and height
@@ -1645,9 +1658,9 @@ 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);
+ int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
QPixmap pixmap
- = header->icon.pixmap(qt_getWindow(widget), QSize(iconExtent, iconExtent), (header->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
+ = header->icon.pixmap(QSize(iconExtent, iconExtent), p->device()->devicePixelRatio(), (header->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
int pixw = pixmap.width() / pixmap.devicePixelRatio();
QRect aligned = alignedRect(header->direction, QFlag(header->iconAlignment), pixmap.size() / pixmap.devicePixelRatio(), rect);
@@ -1663,13 +1676,23 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
else
rect.setRight(rect.right() - pixw - margin);
}
+ QFontMetrics fm(header->fontMetrics);
if (header->state & QStyle::State_On) {
QFont fnt = p->font();
- fnt.setBold(true);
- p->setFont(fnt);
+ // 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)) {
+ if (headerV2->textElideMode != Qt::ElideNone)
+ text = fm.elidedText(header->text, headerV2->textElideMode, rect.width());
}
proxy()->drawItemText(p, rect, header->textAlignment, header->palette,
- (header->state & State_Enabled), header->text, QPalette::ButtonText);
+ header->state.testFlag(State_Enabled), text, QPalette::ButtonText);
}
break;
#if QT_CONFIG(toolbutton)
@@ -1692,8 +1715,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;
@@ -1707,7 +1731,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
mode = QIcon::Active;
else
mode = QIcon::Normal;
- pm = toolbutton->icon.pixmap(qt_getWindow(widget), toolbutton->rect.size().boundedTo(toolbutton->iconSize),
+ pm = toolbutton->icon.pixmap(toolbutton->rect.size().boundedTo(toolbutton->iconSize), p->device()->devicePixelRatio(),
mode, state);
pmSize = pm.size() / pm.devicePixelRatio();
}
@@ -1768,8 +1792,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
case CE_ToolBoxTabShape:
if (const QStyleOptionToolBox *tb = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
p->setPen(tb->palette.mid().color().darker(150));
- bool oldQt4CompatiblePainting = p->testRenderHint(QPainter::Qt4CompatiblePainting);
- p->setRenderHint(QPainter::Qt4CompatiblePainting);
int d = 20 + tb->rect.height() - 3;
if (tb->direction != Qt::RightToLeft) {
const QPoint points[] = {
@@ -1794,7 +1816,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
};
p->drawPolygon(points, sizeof points / sizeof *points);
}
- p->setRenderHint(QPainter::Qt4CompatiblePainting, oldQt4CompatiblePainting);
p->setPen(tb->palette.light().color());
if (tb->direction != Qt::RightToLeft) {
p->drawLine(0, 2, tb->rect.width() - d, 2);
@@ -1820,8 +1841,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;
@@ -1831,22 +1851,22 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
switch (tab->shape) {
case QTabBar::TriangularNorth:
rect.adjust(0, 0, 0, -tabOverlap);
- if(!selected)
+ if (!selected)
rect.adjust(1, 1, -1, 0);
break;
case QTabBar::TriangularSouth:
rect.adjust(0, tabOverlap, 0, 0);
- if(!selected)
+ if (!selected)
rect.adjust(1, 0, -1, -1);
break;
case QTabBar::TriangularEast:
rect.adjust(tabOverlap, 0, 0, 0);
- if(!selected)
+ if (!selected)
rect.adjust(0, 1, -1, -1);
break;
case QTabBar::TriangularWest:
rect.adjust(0, 0, -tabOverlap, 0);
- if(!selected)
+ if (!selected)
rect.adjust(1, 1, 0, -1);
break;
default:
@@ -1922,7 +1942,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
default:
break;
}
- p->restore();
}
break;
case CE_ToolBoxTabLabel:
@@ -1930,7 +1949,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
bool enabled = tb->state & State_Enabled;
bool selected = tb->state & State_Selected;
int iconExtent = proxy()->pixelMetric(QStyle::PM_SmallIconSize, tb, widget);
- QPixmap pm = tb->icon.pixmap(qt_getWindow(widget), QSize(iconExtent, iconExtent),
+ QPixmap pm = tb->icon.pixmap(QSize(iconExtent, iconExtent), p->device()->devicePixelRatio(),
enabled ? QIcon::Normal : QIcon::Disabled);
QRect cr = subElementRect(QStyle::SE_ToolBoxTabContents, tb, widget);
@@ -1983,8 +2002,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();
@@ -2001,10 +2020,13 @@ 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(qt_getWindow(widget), tab->iconSize,
+ QPixmap tabIcon = tab->icon.pixmap(tab->iconSize, p->device()->devicePixelRatio(),
(tab->state & State_Enabled) ? QIcon::Normal
: QIcon::Disabled,
(tab->state & State_Selected) ? QIcon::On
@@ -2012,12 +2034,12 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
p->drawPixmap(iconRect.x(), iconRect.y(), tabIcon);
}
- proxy()->drawItemText(p, tr, alignment, tab->palette, tab->state & State_Enabled, tab->text, QPalette::WindowText);
- if (verticalTabs)
- p->restore();
+ proxy()->drawItemText(p, tr, alignment, tab->palette, tab->state & State_Enabled, tab->text,
+ widget ? widget->foregroundRole() : QPalette::WindowText);
+ 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();
@@ -2034,7 +2056,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);
@@ -2103,7 +2125,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
sy += s;
}
}
- p->restore();
break; }
#endif // QT_CONFIG(sizegrip)
#if QT_CONFIG(rubberband)
@@ -2120,7 +2141,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))
@@ -2131,7 +2152,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)
@@ -2147,10 +2167,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());
@@ -2158,12 +2178,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;
@@ -2173,7 +2190,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);
@@ -2199,12 +2222,12 @@ 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
: QIcon::Disabled;
- QPixmap pixmap = cb->currentIcon.pixmap(qt_getWindow(widget), cb->iconSize, mode);
+ QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, p->device()->devicePixelRatio(), mode);
QRect iconRect(editRect);
iconRect.setWidth(cb->iconSize.width() + 4);
iconRect = alignedRect(cb->direction,
@@ -2221,10 +2244,9 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
}
if (!cb->currentText.isEmpty() && !cb->editable) {
proxy()->drawItemText(p, editRect.adjusted(1, 0, -1, 0),
- visualAlignment(cb->direction, Qt::AlignLeft | Qt::AlignVCenter),
+ visualAlignment(cb->direction, cb->textAlignment),
cb->palette, cb->state & State_Enabled, cb->currentText);
}
- p->restore();
}
break;
#endif // QT_CONFIG(combobox)
@@ -2270,8 +2292,10 @@ 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();
- p->setClipRect(opt->rect);
+ 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);
QRect checkRect = proxy()->subElementRect(SE_ItemViewItemCheckIndicator, vopt, widget);
QRect iconRect = proxy()->subElementRect(SE_ItemViewItemDecoration, vopt, widget);
@@ -2342,8 +2366,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
? QPalette::Highlight : QPalette::Window);
proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, p, widget);
}
-
- p->restore();
}
break;
@@ -2465,6 +2487,12 @@ QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt,
r = visualRect(opt->direction, opt->rect, r);
}
break;
+ case SE_PushButtonBevel:
+ {
+ r = opt->rect;
+ r = visualRect(opt->direction, opt->rect, r);
+ }
+ break;
case SE_CheckBoxIndicator:
{
int h = proxy()->pixelMetric(PM_IndicatorHeight, opt, widget);
@@ -2506,7 +2534,7 @@ QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt,
if (!btn->icon.isNull()) {
iconRect = itemPixmapRect(cr, Qt::AlignAbsolute | Qt::AlignLeft | Qt::AlignVCenter
| Qt::TextShowMnemonic,
- btn->icon.pixmap(qt_getWindow(widget), btn->iconSize, QIcon::Normal));
+ btn->icon.pixmap(btn->iconSize, qt_getDevicePixelRatio(widget), QIcon::Normal));
if (!textRect.isEmpty())
textRect.translate(iconRect.right() + 4, 0);
}
@@ -2554,7 +2582,7 @@ QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt,
}
if (!btn->icon.isNull()) {
iconRect = itemPixmapRect(cr, Qt::AlignAbsolute | Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic,
- btn->icon.pixmap(qt_getWindow(widget), btn->iconSize, QIcon::Normal));
+ btn->icon.pixmap(btn->iconSize, qt_getDevicePixelRatio(widget), QIcon::Normal));
if (!textRect.isEmpty())
textRect.translate(iconRect.right() + 4, 0);
}
@@ -2584,10 +2612,10 @@ QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt,
case SE_ProgressBarLabel:
if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
int textw = 0;
- const bool vertical = pb->orientation == Qt::Vertical;
+ const bool vertical = !(pb->state & QStyle::State_Horizontal);
if (!vertical) {
if (pb->textVisible)
- textw = qMax(pb->fontMetrics.horizontalAdvance(pb->text), pb->fontMetrics.horizontalAdvance(QLatin1String("100%"))) + 6;
+ textw = qMax(pb->fontMetrics.horizontalAdvance(pb->text), pb->fontMetrics.horizontalAdvance("100%"_L1)) + 6;
}
if ((pb->textAlignment & Qt::AlignCenter) == 0) {
@@ -2931,7 +2959,7 @@ QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt,
case SE_TabBarScrollLeftButton: {
const bool vertical = opt->rect.width() < opt->rect.height();
const Qt::LayoutDirection ld = widget->layoutDirection();
- const int buttonWidth = qMax(proxy()->pixelMetric(QStyle::PM_TabBarScrollButtonWidth, nullptr, widget), QApplication::globalStrut().width());
+ const int buttonWidth = proxy()->pixelMetric(QStyle::PM_TabBarScrollButtonWidth, nullptr, widget);
const int buttonOverlap = proxy()->pixelMetric(QStyle::PM_TabBar_ScrollButtonOverlap, nullptr, widget);
r = vertical ? QRect(0, opt->rect.height() - (buttonWidth * 2) + buttonOverlap, opt->rect.width(), buttonWidth)
@@ -2940,7 +2968,7 @@ QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt,
case SE_TabBarScrollRightButton: {
const bool vertical = opt->rect.width() < opt->rect.height();
const Qt::LayoutDirection ld = widget->layoutDirection();
- const int buttonWidth = qMax(proxy()->pixelMetric(QStyle::PM_TabBarScrollButtonWidth, nullptr, widget), QApplication::globalStrut().width());
+ const int buttonWidth = proxy()->pixelMetric(QStyle::PM_TabBarScrollButtonWidth, nullptr, widget);
r = vertical ? QRect(0, opt->rect.height() - buttonWidth, opt->rect.width(), buttonWidth)
: QStyle::visualRect(ld, opt->rect, QRect(opt->rect.width() - buttonWidth, 0, buttonWidth, opt->rect.height()));
@@ -3187,9 +3215,9 @@ struct StaticPolygonF
{
QPointF data[N];
- Q_DECL_CONSTEXPR int size() const { return N; }
- Q_DECL_CONSTEXPR const QPointF *cbegin() const { return data; }
- Q_DECL_CONSTEXPR const QPointF &operator[](int idx) const { return data[idx]; }
+ constexpr int size() const { return N; }
+ constexpr const QPointF *cbegin() const { return data; }
+ constexpr const QPointF &operator[](int idx) const { return data[idx]; }
};
static StaticPolygonF<3> calcArrow(const QStyleOptionSlider *dial, qreal &a)
@@ -3208,8 +3236,8 @@ static StaticPolygonF<3> calcArrow(const QStyleOptionSlider *dial, qreal &a)
a = (Q_PI * 8 - (currentSliderPosition - dial->minimum) * 10 * Q_PI
/ (dial->maximum - dial->minimum)) / 6;
- int xc = width / 2;
- int yc = height / 2;
+ int xc = width / 2 + dial->rect.left();
+ int yc = height / 2 + dial->rect.top();
int len = r - QStyleHelper::calcBigLineSize(r) - 5;
if (len < 5)
@@ -3259,7 +3287,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;
@@ -3288,7 +3316,6 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
break;
v = nextInterval;
}
- p->restore();
}
}
break;
@@ -3547,19 +3574,18 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
|| qobject_cast<const QDockWidget *>(widget)
#endif
)
- pm = proxy()->standardIcon(SP_DockWidgetCloseButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(10, 10));
+ pm = proxy()->standardIcon(SP_DockWidgetCloseButton, &tool, widget).pixmap(QSize(10, 10), p->device()->devicePixelRatio());
else
- pm = proxy()->standardIcon(SP_TitleBarCloseButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(10, 10));
+ pm = proxy()->standardIcon(SP_TitleBarCloseButton, &tool, widget).pixmap(QSize(10, 10), p->device()->devicePixelRatio());
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_TitleBarMaxButton
@@ -3568,17 +3594,16 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarMaxButton, widget);
down = tb->activeSubControls & SC_TitleBarMaxButton && (opt->state & State_Sunken);
- pm = proxy()->standardIcon(SP_TitleBarMaxButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(10, 10));
+ pm = proxy()->standardIcon(SP_TitleBarMaxButton, &tool, widget).pixmap(QSize(10, 10), p->device()->devicePixelRatio());
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_TitleBarMinButton
@@ -3586,17 +3611,16 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
&& !(tb->titleBarState & Qt::WindowMinimized)) {
ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarMinButton, widget);
down = tb->activeSubControls & SC_TitleBarMinButton && (opt->state & State_Sunken);
- pm = proxy()->standardIcon(SP_TitleBarMinButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(10, 10));
+ pm = proxy()->standardIcon(SP_TitleBarMinButton, &tool, widget).pixmap(QSize(10, 10), p->device()->devicePixelRatio());
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();
}
bool drawNormalButton = (tb->subControls & SC_TitleBarNormalButton)
@@ -3608,17 +3632,16 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
if (drawNormalButton) {
ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarNormalButton, widget);
down = tb->activeSubControls & SC_TitleBarNormalButton && (opt->state & State_Sunken);
- pm = proxy()->standardIcon(SP_TitleBarNormalButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(10, 10));
+ pm = proxy()->standardIcon(SP_TitleBarNormalButton, &tool, widget).pixmap(QSize(10, 10), p->device()->devicePixelRatio());
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_TitleBarShadeButton
@@ -3626,16 +3649,15 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
&& !(tb->titleBarState & Qt::WindowMinimized)) {
ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarShadeButton, widget);
down = (tb->activeSubControls & SC_TitleBarShadeButton && (opt->state & State_Sunken));
- pm = proxy()->standardIcon(SP_TitleBarShadeButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(10, 10));
+ pm = proxy()->standardIcon(SP_TitleBarShadeButton, &tool, widget).pixmap(QSize(10, 10), p->device()->devicePixelRatio());
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
@@ -3644,32 +3666,30 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarUnshadeButton, widget);
down = tb->activeSubControls & SC_TitleBarUnshadeButton && (opt->state & State_Sunken);
- pm = proxy()->standardIcon(SP_TitleBarUnshadeButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(10, 10));
+ pm = proxy()->standardIcon(SP_TitleBarUnshadeButton, &tool, widget).pixmap(QSize(10, 10), p->device()->devicePixelRatio());
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) {
ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarContextHelpButton, widget);
down = tb->activeSubControls & SC_TitleBarContextHelpButton && (opt->state & State_Sunken);
- pm = proxy()->standardIcon(SP_TitleBarContextHelpButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(10, 10));
+ pm = proxy()->standardIcon(SP_TitleBarContextHelpButton, &tool, widget).pixmap(QSize(10, 10), p->device()->devicePixelRatio());
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);
@@ -3677,11 +3697,10 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
tb->icon.paint(p, ir);
} else {
int iconSize = proxy()->pixelMetric(PM_SmallIconSize, tb, widget);
- pm = proxy()->standardIcon(SP_TitleBarMenuButton, &tool, widget).pixmap(qt_getWindow(widget), QSize(iconSize, iconSize));
+ 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();
}
}
}
@@ -3690,7 +3709,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))
@@ -3728,7 +3747,6 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
p->setPen(Qt::NoPen);
p->setBrush(pal.button());
- p->setRenderHint(QPainter::Qt4CompatiblePainting);
p->drawPolygon(arrow.cbegin(), arrow.size());
a = QStyleHelper::angle(QPointF(width / 2, height / 2), arrow[0]);
@@ -3776,7 +3794,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)
@@ -3793,7 +3810,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;
@@ -3808,7 +3825,6 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
}
p->setClipRegion(region);
proxy()->drawPrimitive(PE_FrameGroupBox, &frame, p, widget);
- p->restore();
}
// Draw title
@@ -3856,8 +3872,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);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
+ bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget);
+ bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget);
} else {
btnOpt.state |= State_Raised;
btnOpt.state &= ~State_Sunken;
@@ -3866,15 +3882,15 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
}
btnOpt.rect = proxy()->subControlRect(CC_MdiControls, opt, SC_MdiCloseButton, widget);
proxy()->drawPrimitive(PE_PanelButtonCommand, &btnOpt, p, widget);
- QPixmap pm = proxy()->standardIcon(SP_TitleBarCloseButton).pixmap(qt_getWindow(widget), buttonIconSize);
+ QPixmap pm = proxy()->standardIcon(SP_TitleBarCloseButton).pixmap(buttonIconSize, p->device()->devicePixelRatio());
proxy()->drawItemPixmap(p, btnOpt.rect.translated(bsx, bsy), Qt::AlignCenter, pm);
}
if (opt->subControls & QStyle::SC_MdiNormalButton) {
if (opt->activeSubControls & QStyle::SC_MdiNormalButton && (opt->state & State_Sunken)) {
btnOpt.state |= State_Sunken;
btnOpt.state &= ~State_Raised;
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
+ bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget);
+ bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget);
} else {
btnOpt.state |= State_Raised;
btnOpt.state &= ~State_Sunken;
@@ -3883,15 +3899,15 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
}
btnOpt.rect = proxy()->subControlRect(CC_MdiControls, opt, SC_MdiNormalButton, widget);
proxy()->drawPrimitive(PE_PanelButtonCommand, &btnOpt, p, widget);
- QPixmap pm = proxy()->standardIcon(SP_TitleBarNormalButton).pixmap(qt_getWindow(widget), buttonIconSize);
+ QPixmap pm = proxy()->standardIcon(SP_TitleBarNormalButton).pixmap(buttonIconSize, p->device()->devicePixelRatio());
proxy()->drawItemPixmap(p, btnOpt.rect.translated(bsx, bsy), Qt::AlignCenter, pm);
}
if (opt->subControls & QStyle::SC_MdiMinButton) {
if (opt->activeSubControls & QStyle::SC_MdiMinButton && (opt->state & State_Sunken)) {
btnOpt.state |= State_Sunken;
btnOpt.state &= ~State_Raised;
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
+ bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget);
+ bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget);
} else {
btnOpt.state |= State_Raised;
btnOpt.state &= ~State_Sunken;
@@ -3900,14 +3916,14 @@ void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionCompl
}
btnOpt.rect = proxy()->subControlRect(CC_MdiControls, opt, SC_MdiMinButton, widget);
proxy()->drawPrimitive(PE_PanelButtonCommand, &btnOpt, p, widget);
- QPixmap pm = proxy()->standardIcon(SP_TitleBarMinButton).pixmap(qt_getWindow(widget), buttonIconSize);
+ QPixmap pm = proxy()->standardIcon(SP_TitleBarMinButton).pixmap(buttonIconSize, p->device()->devicePixelRatio());
proxy()->drawItemPixmap(p, btnOpt.rect.translated(bsx, bsy), Qt::AlignCenter, pm);
}
}
break;
#endif // QT_CONFIG(mdiarea)
default:
- qWarning("QCommonStyle::drawComplexControl: Control %d not handled", cc);
+ qCWarning(lcCommonStyle, "QCommonStyle::drawComplexControl: Control %d not handled", cc);
}
}
@@ -4043,7 +4059,7 @@ QStyle::SubControl QCommonStyle::hitTestComplexControl(ComplexControl cc, const
}
break;
default:
- qWarning("QCommonStyle::hitTestComplexControl: Case %d not handled", cc);
+ qCWarning(lcCommonStyle, "QCommonStyle::hitTestComplexControl: Case %d not handled", cc);
}
return sc;
}
@@ -4185,7 +4201,6 @@ QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex
bs.setHeight(qMax(8, spinbox->rect.height()/2 - fw));
// 1.6 -approximate golden mean
bs.setWidth(qMax(16, qMin(bs.height() * 8 / 5, spinbox->rect.width() / 4)));
- bs = bs.expandedTo(QApplication::globalStrut());
int y = fw + spinbox->rect.y();
int x, lx, rx;
x = spinbox->rect.x() + spinbox->rect.width() - fw - bs.width();
@@ -4212,6 +4227,7 @@ QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex
break;
case SC_SpinBoxFrame:
ret = spinbox->rect;
+ break;
default:
break;
}
@@ -4372,7 +4388,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;
@@ -4394,7 +4410,7 @@ QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex
case SC_GroupBoxLabel: {
QFontMetrics fontMetrics = groupBox->fontMetrics;
int th = fontMetrics.height();
- int tw = fontMetrics.size(Qt::TextShowMnemonic, groupBox->text + QLatin1Char(' ')).width();
+ int tw = fontMetrics.size(Qt::TextShowMnemonic, groupBox->text + u' ').width();
int marg = (groupBox->features & QStyleOptionFrame::Flat) ? 0 : 8;
ret = groupBox->rect.adjusted(marg, 0, -marg, 0);
@@ -4483,7 +4499,7 @@ QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex
}
#endif // QT_CONFIG(mdiarea)
default:
- qWarning("QCommonStyle::subControlRect: Case %d not handled", cc);
+ qCWarning(lcCommonStyle, "QCommonStyle::subControlRect: Case %d not handled", cc);
}
#if !QT_CONFIG(slider) && !QT_CONFIG(spinbox) && !QT_CONFIG(toolbutton) && !QT_CONFIG(groupbox)
Q_UNUSED(widget);
@@ -4505,16 +4521,8 @@ 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: {
+ case PM_TitleBarHeight:
+ {
if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
if ((tb->titleBarFlags & Qt::WindowType_Mask) == Qt::Tool) {
ret = qMax(widget ? widget->fontMetrics().height() : opt->fontMetrics.height(), 16);
@@ -4528,8 +4536,8 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
} else {
ret = int(QStyleHelper::dpiScaled(18., opt));
}
-
- break; }
+ break;
+ }
case PM_TitleBarButtonSize:
ret = int(QStyleHelper::dpiScaled(16., opt));
break;
@@ -4582,14 +4590,10 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
#if QT_CONFIG(scrollbar)
case PM_ScrollBarExtent:
- if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int s = sb->orientation == Qt::Horizontal ?
- QApplication::globalStrut().height()
- : QApplication::globalStrut().width();
- ret = qMax(16, s);
- } else {
+ if (qstyleoption_cast<const QStyleOptionSlider *>(opt))
+ ret = 16;
+ else
ret = int(QStyleHelper::dpiScaled(16, opt));
- }
break;
#endif
case PM_MaximumDragDistance:
@@ -4698,17 +4702,19 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
ret = 2;
break;
- case PM_TabBarTabVSpace: {
+ case PM_TabBarTabVSpace:
+ {
const QStyleOptionTab *tb = qstyleoption_cast<const QStyleOptionTab *>(opt);
if (tb && (tb->shape == QTabBar::RoundedNorth || tb->shape == QTabBar::RoundedSouth
|| tb->shape == QTabBar::RoundedWest || tb->shape == QTabBar::RoundedEast))
ret = 8;
else
- if(tb && (tb->shape == QTabBar::TriangularWest || tb->shape == QTabBar::TriangularEast))
+ if (tb && (tb->shape == QTabBar::TriangularWest || tb->shape == QTabBar::TriangularEast))
ret = 3;
else
ret = 2;
- break; }
+ break;
+ }
#endif
case PM_ProgressBarChunkWidth:
@@ -4767,28 +4773,18 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
case PM_LayoutTopMargin:
case PM_LayoutRightMargin:
case PM_LayoutBottomMargin:
- {
- bool isWindow = false;
- if (opt) {
- isWindow = (opt->state & State_Window);
- } else if (widget) {
- isWindow = widget->isWindow();
- }
- ret = proxy()->pixelMetric(isWindow ? PM_DefaultTopLevelMargin : PM_DefaultChildMargin);
+ {
+ bool isWindow = false;
+ if (opt) {
+ isWindow = (opt->state & State_Window);
+ } else if (widget) {
+ isWindow = widget->isWindow();
}
+ ret = int(QStyleHelper::dpiScaled(isWindow ? 11 : 9, opt));
break;
+ }
case PM_LayoutHorizontalSpacing:
case PM_LayoutVerticalSpacing:
- ret = proxy()->pixelMetric(PM_DefaultLayoutSpacing);
- break;
-
- case PM_DefaultTopLevelMargin:
- ret = int(QStyleHelper::dpiScaled(11, opt));
- break;
- case PM_DefaultChildMargin:
- ret = int(QStyleHelper::dpiScaled(9, opt));
- break;
- case PM_DefaultLayoutSpacing:
ret = int(QStyleHelper::dpiScaled(6, opt));
break;
@@ -4819,6 +4815,12 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
case PM_IconViewIconSize:
ret = proxy()->pixelMetric(PM_LargeIconSize, opt, widget);
break;
+ case PM_LineEditIconSize:
+ ret = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
+ break;
+ case PM_LineEditIconMargin:
+ ret = proxy()->pixelMetric(PM_LineEditIconSize, opt, widget) / 4;
+ break;
case PM_LargeIconSize:
ret = int(QStyleHelper::dpiScaled(32, opt));
@@ -4877,125 +4879,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);
- 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(QLatin1Char('\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) + 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)
@@ -5004,34 +5022,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
@@ -5047,7 +5067,7 @@ QSize QCommonStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
default:
break;
}
- return sz;
+ return size;
}
@@ -5062,7 +5082,7 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
ret = false;
break;
case SH_Slider_AbsoluteSetButtons:
- ret = Qt::MidButton;
+ ret = Qt::MiddleButton;
break;
case SH_Slider_PageSetButtons:
ret = Qt::LeftButton;
@@ -5162,9 +5182,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;
@@ -5205,10 +5228,10 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
case SH_FocusFrame_Mask:
ret = 1;
if (widget) {
- if(QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
+ if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
mask->region = widget->rect();
- int vmargin = proxy()->pixelMetric(QStyle::PM_FocusFrameVMargin),
- hmargin = proxy()->pixelMetric(QStyle::PM_FocusFrameHMargin);
+ 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));
}
}
@@ -5219,9 +5242,9 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
ret = 0;
if (rbOpt->shape == QRubberBand::Rectangle) {
ret = true;
- if(QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
+ if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
mask->region = opt->rect;
- int margin = proxy()->pixelMetric(PM_DefaultFrameWidth) * 2;
+ const int margin = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget) * 2;
mask->region -= opt->rect.adjusted(margin, margin, -margin, -margin);
}
}
@@ -5280,9 +5303,6 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
ret = theme->themeHint(QPlatformTheme::DialogButtonBoxButtonsHaveIcons).toBool() ? 1 : 0;
break;
- case SH_SpellCheckUnderlineStyle:
- ret = QTextCharFormat::WaveUnderline;
- break;
case SH_MessageBox_CenterButtons:
ret = true;
break;
@@ -5359,7 +5379,7 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
case SH_Menu_SupportsSections:
ret = false;
break;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case SH_ToolTip_WakeUpDelay:
ret = 700;
break;
@@ -5402,8 +5422,57 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
case SH_SpinBox_StepModifier:
ret = Qt::ControlModifier;
break;
- default:
- ret = 0;
+ case SH_TabBar_AllowWheelScrolling:
+ ret = true;
+ break;
+ case SH_SpinBox_SelectOnStep:
+ ret = true;
+ break;
+ case SH_EtchDisabledText:
+ case SH_DitherDisabledText:
+ case SH_ScrollBar_MiddleClickAbsolutePosition:
+ case SH_ScrollBar_ScrollWhenPointerLeavesControl:
+ case SH_Slider_SnapToValue:
+ case SH_Slider_SloppyKeyEvents:
+ case SH_ProgressDialog_CenterCancelButton:
+ case SH_PrintDialog_RightAlignButtons:
+ case SH_MainWindow_SpaceBelowMenuBar:
+ case SH_FontDialog_SelectAssociatedText:
+ case SH_Menu_AllowActiveAndDisabled:
+ case SH_Menu_SpaceActivatesItem:
+ case SH_ScrollView_FrameOnlyAroundContents:
+ case SH_ComboBox_ListMouseTracking:
+ case SH_Menu_MouseTracking:
+ case SH_MenuBar_MouseTracking:
+ case SH_ItemView_ChangeHighlightOnFocus:
+ case SH_Widget_ShareActivation:
+ case SH_Workspace_FillSpaceOnMaximize:
+ case SH_ComboBox_Popup:
+ case SH_TitleBar_NoBorder:
+ case SH_Slider_StopMouseOverSlider:
+ case SH_RichText_FullWidthSelection:
+ case SH_Menu_Scrollable:
+ case SH_TabBar_PreferNoArrows:
+ case SH_ScrollBar_LeftClickAbsolutePosition:
+ case SH_SpinBox_AnimateButton:
+ case SH_DrawMenuBarSeparator:
+ case SH_WindowFrame_Mask:
+ case SH_ToolTip_Mask:
+ case SH_Menu_Mask:
+ case SH_Menu_FlashTriggeredItem:
+ case SH_Menu_FadeOutOnHide:
+ case SH_ItemView_PaintAlternatingRowColorsForEmptyArea:
+ case SH_ComboBox_UseNativePopup:
+ case SH_Table_AlwaysDrawLeftTopGridLines:
+ ret = false;
+ break;
+ case SH_MenuBar_AltKeyNavigation:
+ if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
+ ret = theme->themeHint(QPlatformTheme::MenuBarFocusOnAltPressRelease).toBool();
+ break;
+ case SH_CustomBase:
+ // Added to get compiler errors when a style hint is missing
+ ret = false;
break;
}
@@ -5425,653 +5494,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(QLatin1String("dialog-ok")).pixmap(16);
- break;
- case SP_DialogApplyButton:
- pixmap = QIcon::fromTheme(QLatin1String("dialog-ok-apply")).pixmap(16);
- break;
- case SP_DialogDiscardButton:
- pixmap = QIcon::fromTheme(QLatin1String("edit-delete")).pixmap(16);
- break;
- case SP_DialogCloseButton:
- pixmap = QIcon::fromTheme(QLatin1String("dialog-close")).pixmap(16);
- break;
- case SP_DirHomeIcon:
- pixmap = QIcon::fromTheme(QLatin1String("user-home")).pixmap(16);
- break;
- case SP_MessageBoxInformation:
- pixmap = QIcon::fromTheme(QLatin1String("messagebox_info")).pixmap(16);
- break;
- case SP_MessageBoxWarning:
- pixmap = QIcon::fromTheme(QLatin1String("messagebox_warning")).pixmap(16);
- break;
- case SP_MessageBoxCritical:
- pixmap = QIcon::fromTheme(QLatin1String("messagebox_critical")).pixmap(16);
- break;
- case SP_MessageBoxQuestion:
- pixmap = QIcon::fromTheme(QLatin1String("help")).pixmap(16);
- break;
- case SP_DialogOpenButton:
- case SP_DirOpenIcon:
- pixmap = QIcon::fromTheme(QLatin1String("folder-open")).pixmap(16);
- break;
- case SP_FileIcon:
- pixmap = QIcon::fromTheme(QLatin1String("text-x-generic"),
- QIcon::fromTheme(QLatin1String("empty"))).pixmap(16);
- break;
- case SP_DirClosedIcon:
- case SP_DirIcon:
- pixmap = QIcon::fromTheme(QLatin1String("folder")).pixmap(16);
- break;
- case SP_DriveFDIcon:
- pixmap = QIcon::fromTheme(QLatin1String("media-floppy"),
- QIcon::fromTheme(QLatin1String("3floppy_unmount"))).pixmap(16);
- break;
- case SP_ComputerIcon:
- pixmap = QIcon::fromTheme(QLatin1String("computer"),
- QIcon::fromTheme(QLatin1String("system"))).pixmap(16);
- break;
- case SP_DesktopIcon:
- pixmap = QIcon::fromTheme(QLatin1String("user-desktop"),
- QIcon::fromTheme(QLatin1String("desktop"))).pixmap(16);
- break;
- case SP_TrashIcon:
- pixmap = QIcon::fromTheme(QLatin1String("user-trash"),
- QIcon::fromTheme(QLatin1String("trashcan_empty"))).pixmap(16);
- break;
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- pixmap = QIcon::fromTheme(QLatin1String("media-optical"),
- QIcon::fromTheme(QLatin1String("cdrom_unmount"))).pixmap(16);
- break;
- case SP_DriveHDIcon:
- pixmap = QIcon::fromTheme(QLatin1String("drive-harddisk"),
- QIcon::fromTheme(QLatin1String("hdd_unmount"))).pixmap(16);
- break;
- case SP_FileDialogToParent:
- pixmap = QIcon::fromTheme(QLatin1String("go-up"),
- QIcon::fromTheme(QLatin1String("up"))).pixmap(16);
- break;
- case SP_FileDialogNewFolder:
- pixmap = QIcon::fromTheme(QLatin1String("folder_new")).pixmap(16);
- break;
- case SP_ArrowUp:
- pixmap = QIcon::fromTheme(QLatin1String("go-up"),
- QIcon::fromTheme(QLatin1String("up"))).pixmap(16);
- break;
- case SP_ArrowDown:
- pixmap = QIcon::fromTheme(QLatin1String("go-down"),
- QIcon::fromTheme(QLatin1String("down"))).pixmap(16);
- break;
- case SP_ArrowRight:
- pixmap = QIcon::fromTheme(QLatin1String("go-next"),
- QIcon::fromTheme(QLatin1String("forward"))).pixmap(16);
- break;
- case SP_ArrowLeft:
- pixmap = QIcon::fromTheme(QLatin1String("go-previous"),
- QIcon::fromTheme(QLatin1String("back"))).pixmap(16);
- break;
- case SP_FileDialogDetailedView:
- pixmap = QIcon::fromTheme(QLatin1String("view_detailed")).pixmap(16);
- break;
- case SP_FileDialogListView:
- pixmap = QIcon::fromTheme(QLatin1String("view_icon")).pixmap(16);
- break;
- case SP_BrowserReload:
- pixmap = QIcon::fromTheme(QLatin1String("reload")).pixmap(16);
- break;
- case SP_BrowserStop:
- pixmap = QIcon::fromTheme(QLatin1String("process-stop")).pixmap(16);
- break;
- case SP_MediaPlay:
- pixmap = QIcon::fromTheme(QLatin1String("media-playback-start")).pixmap(16);
- break;
- case SP_MediaPause:
- pixmap = QIcon::fromTheme(QLatin1String("media-playback-pause")).pixmap(16);
- break;
- case SP_MediaStop:
- pixmap = QIcon::fromTheme(QLatin1String("media-playback-stop")).pixmap(16);
- break;
- case SP_MediaSeekForward:
- pixmap = QIcon::fromTheme(QLatin1String("media-seek-forward")).pixmap(16);
- break;
- case SP_MediaSeekBackward:
- pixmap = QIcon::fromTheme(QLatin1String("media-seek-backward")).pixmap(16);
- break;
- case SP_MediaSkipForward:
- pixmap = QIcon::fromTheme(QLatin1String("media-skip-forward")).pixmap(16);
- break;
- case SP_MediaSkipBackward:
- pixmap = QIcon::fromTheme(QLatin1String("media-skip-backward")).pixmap(16);
- break;
- case SP_DialogResetButton:
- pixmap = QIcon::fromTheme(QLatin1String("edit-clear")).pixmap(24);
- break;
- case SP_DialogHelpButton:
- pixmap = QIcon::fromTheme(QLatin1String("help-contents")).pixmap(24);
- break;
- case SP_DialogNoButton:
- case SP_DialogCancelButton:
- pixmap = QIcon::fromTheme(QLatin1String("dialog-cancel"),
- QIcon::fromTheme(QLatin1String("process-stop"))).pixmap(24);
- break;
- case SP_DialogSaveButton:
- pixmap = QIcon::fromTheme(QLatin1String("document-save")).pixmap(24);
- break;
- case SP_FileLinkIcon:
- pixmap = QIcon::fromTheme(QLatin1String("emblem-symbolic-link")).pixmap(16);
- if (!pixmap.isNull()) {
- QPixmap fileIcon = QIcon::fromTheme(QLatin1String("text-x-generic")).pixmap(16);
- if (fileIcon.isNull())
- fileIcon = QIcon::fromTheme(QLatin1String("empty")).pixmap(16);
- if (!fileIcon.isNull()) {
- QPainter painter(&fileIcon);
- painter.drawPixmap(0, 0, 16, 16, pixmap);
- return fileIcon;
- }
- }
- break;
- case SP_DirLinkIcon:
- pixmap = QIcon::fromTheme(QLatin1String("emblem-symbolic-link")).pixmap(16);
- if (!pixmap.isNull()) {
- QPixmap dirIcon = QIcon::fromTheme(QLatin1String("folder")).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(QLatin1String(":/qt-project.org/styles/commonstyle/images/left-16.png"));
- case SP_ArrowRight:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/right-16.png"));
- case SP_ArrowUp:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/up-16.png"));
- case SP_ArrowDown:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/down-16.png"));
- case SP_FileDialogToParent:
- return proxy()->standardPixmap(SP_ArrowUp, option, widget);
- case SP_FileDialogNewFolder:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/newdirectory-16.png"));
- case SP_FileDialogDetailedView:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/viewdetailed-16.png"));
- case SP_FileDialogInfoView:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/fileinfo-16.png"));
- case SP_FileDialogContentsView:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/filecontents-16.png"));
- case SP_FileDialogListView:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/viewlist-16.png"));
- case SP_FileDialogBack:
- return proxy()->standardPixmap(SP_ArrowBack, option, widget);
- case SP_DriveHDIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/harddrive-16.png"));
- case SP_TrashIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/trash-16.png"));
- case SP_DriveFDIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/floppy-16.png"));
- case SP_DriveNetIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/networkdrive-16.png"));
- case SP_DesktopIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/desktop-16.png"));
- case SP_ComputerIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/computer-16.png"));
- case SP_DriveCDIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/cdr-16.png"));
- case SP_DriveDVDIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/dvd-16.png"));
- case SP_DirHomeIcon:
- case SP_DirOpenIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/diropen-16.png"));
- case SP_DirIcon:
- case SP_DirClosedIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/dirclosed-16.png"));
- case SP_DirLinkIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/dirlink-16.png"));
- case SP_FileIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/file-16.png"));
- case SP_FileLinkIcon:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/filelink-16.png"));
- case SP_DialogOkButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-ok-16.png"));
- case SP_DialogCancelButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-cancel-16.png"));
- case SP_DialogHelpButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-help-16.png"));
- case SP_DialogOpenButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-open-16.png"));
- case SP_DialogSaveButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-save-16.png"));
- case SP_DialogCloseButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-close-16.png"));
- case SP_DialogApplyButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-apply-16.png"));
- case SP_DialogResetButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-clear-16.png"));
- case SP_DialogDiscardButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-delete-16.png"));
- case SP_DialogYesButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-yes-16.png"));
- case SP_DialogNoButton:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-no-16.png"));
- case SP_BrowserReload:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/refresh-24.png"));
- case SP_BrowserStop:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/stop-24.png"));
- case SP_MediaPlay:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-play-32.png"));
- case SP_MediaPause:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-pause-32.png"));
- case SP_MediaStop:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-stop-32.png"));
- case SP_MediaSeekForward:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-seek-forward-32.png"));
- case SP_MediaSeekBackward:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-seek-backward-32.png"));
- case SP_MediaSkipForward:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-skip-forward-32.png"));
- case SP_MediaSkipBackward:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-skip-backward-32.png"));
- case SP_MediaVolume:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-volume-16.png"));
- case SP_MediaVolumeMuted:
- return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-volume-muted-16.png"));
- case SP_LineEditClearButton:
- return QPixmap(clearText16IconPath());
-#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(QLatin1String("user-home"));
- break;
- case SP_MessageBoxInformation:
- icon = QIcon::fromTheme(QLatin1String("dialog-information"));
- break;
- case SP_MessageBoxWarning:
- icon = QIcon::fromTheme(QLatin1String("dialog-warning"));
- break;
- case SP_MessageBoxCritical:
- icon = QIcon::fromTheme(QLatin1String("dialog-error"));
- break;
- case SP_MessageBoxQuestion:
- icon = QIcon::fromTheme(QLatin1String("dialog-question"));
- break;
- case SP_DialogOpenButton:
- case SP_DirOpenIcon:
- icon = QIcon::fromTheme(QLatin1String("folder-open"));
- break;
- case SP_DialogSaveButton:
- icon = QIcon::fromTheme(QLatin1String("document-save"));
- break;
- case SP_DialogApplyButton:
- icon = QIcon::fromTheme(QLatin1String("dialog-ok-apply"));
- break;
- case SP_DialogYesButton:
- case SP_DialogOkButton:
- icon = QIcon::fromTheme(QLatin1String("dialog-ok"));
- break;
- case SP_DialogDiscardButton:
- icon = QIcon::fromTheme(QLatin1String("edit-delete"));
- break;
- case SP_DialogResetButton:
- icon = QIcon::fromTheme(QLatin1String("edit-clear"));
- break;
- case SP_DialogHelpButton:
- icon = QIcon::fromTheme(QLatin1String("help-contents"));
- break;
- case SP_FileIcon:
- icon = QIcon::fromTheme(QLatin1String("text-x-generic"));
- break;
- case SP_DirClosedIcon:
- case SP_DirIcon:
- icon = QIcon::fromTheme(QLatin1String("folder"));
- break;
- case SP_DriveFDIcon:
- icon = QIcon::fromTheme(QLatin1String("floppy_unmount"));
- break;
- case SP_ComputerIcon:
- icon = QIcon::fromTheme(QLatin1String("computer"),
- QIcon::fromTheme(QLatin1String("system")));
- break;
- case SP_DesktopIcon:
- icon = QIcon::fromTheme(QLatin1String("user-desktop"));
- break;
- case SP_TrashIcon:
- icon = QIcon::fromTheme(QLatin1String("user-trash"));
- break;
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- icon = QIcon::fromTheme(QLatin1String("media-optical"));
- break;
- case SP_DriveHDIcon:
- icon = QIcon::fromTheme(QLatin1String("drive-harddisk"));
- break;
- case SP_FileDialogToParent:
- icon = QIcon::fromTheme(QLatin1String("go-up"));
- break;
- case SP_FileDialogNewFolder:
- icon = QIcon::fromTheme(QLatin1String("folder-new"));
- break;
- case SP_ArrowUp:
- icon = QIcon::fromTheme(QLatin1String("go-up"));
- break;
- case SP_ArrowDown:
- icon = QIcon::fromTheme(QLatin1String("go-down"));
- break;
- case SP_ArrowRight:
- icon = QIcon::fromTheme(QLatin1String("go-next"));
- break;
- case SP_ArrowLeft:
- icon = QIcon::fromTheme(QLatin1String("go-previous"));
- break;
- case SP_DialogNoButton:
- case SP_DialogCancelButton:
- icon = QIcon::fromTheme(QLatin1String("dialog-cancel"),
- QIcon::fromTheme(QLatin1String("process-stop")));
- break;
- case SP_DialogCloseButton:
- icon = QIcon::fromTheme(QLatin1String("window-close"));
- break;
- case SP_FileDialogDetailedView:
- icon = QIcon::fromTheme(QLatin1String("view-list-details"));
- break;
- case SP_FileDialogListView:
- icon = QIcon::fromTheme(QLatin1String("view-list-icons"));
- break;
- case SP_BrowserReload:
- icon = QIcon::fromTheme(QLatin1String("view-refresh"));
- break;
- case SP_BrowserStop:
- icon = QIcon::fromTheme(QLatin1String("process-stop"));
- break;
- case SP_MediaPlay:
- icon = QIcon::fromTheme(QLatin1String("media-playback-start"));
- break;
- case SP_MediaPause:
- icon = QIcon::fromTheme(QLatin1String("media-playback-pause"));
- break;
- case SP_MediaStop:
- icon = QIcon::fromTheme(QLatin1String("media-playback-stop"));
- break;
- case SP_MediaSeekForward:
- icon = QIcon::fromTheme(QLatin1String("media-seek-forward"));
- break;
- case SP_MediaSeekBackward:
- icon = QIcon::fromTheme(QLatin1String("media-seek-backward"));
- break;
- case SP_MediaSkipForward:
- icon = QIcon::fromTheme(QLatin1String("media-skip-forward"));
- break;
- case SP_MediaSkipBackward:
- icon = QIcon::fromTheme(QLatin1String("media-skip-backward"));
- break;
- case SP_MediaVolume:
- icon = QIcon::fromTheme(QLatin1String("audio-volume-medium"));
- break;
- case SP_MediaVolumeMuted:
- icon = QIcon::fromTheme(QLatin1String("audio-volume-muted"));
- 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(QLatin1String("emblem-symbolic-link"));
- 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(qt_getWindow(widget), QSize(size, size));
- QPixmap linkPixmap = linkIcon.pixmap(qt_getWindow(widget), QSize(size / 2, size / 2));
+ 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(QLatin1String("emblem-symbolic-link"));
- 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(qt_getWindow(widget), QSize(size, size));
- QPixmap linkPixmap = linkIcon.pixmap(qt_getWindow(widget), QSize(size / 2, size / 2));
- 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);
@@ -6079,309 +5808,337 @@ 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;
- if (standardIcon == SP_TitleBarCloseButton) {
- titleBarIcon.addFile(QLatin1String(":/qt-project.org/styles/macstyle/images/closedock-16.png"));
- titleBarIcon.addFile(QLatin1String(":/qt-project.org/styles/macstyle/images/closedock-down-16.png"), QSize(16, 16), QIcon::Normal, QIcon::On);
- } else {
- titleBarIcon.addFile(QLatin1String(":/qt-project.org/styles/macstyle/images/dockdock-16.png"));
- titleBarIcon.addFile(QLatin1String(":/qt-project.org/styles/macstyle/images/dockdock-down-16.png"), QSize(16, 16), QIcon::Normal, QIcon::On);
+ 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(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;
const QList<QSize> sizes = theme->themeHint(QPlatformTheme::IconPixmapSizes).value<QList<QSize> >();
for (const QSize &size : sizes) {
QPixmap mainIcon;
- const QString cacheKey = QLatin1String("qt_mac_constructQIconFromIconRef") + QString::number(standardIcon) + QString::number(size.width());
+ const QString cacheKey = "qt_mac_constructQIconFromIconRef"_L1 + QString::number(standardIcon) + QString::number(size.width());
if (standardIcon >= QStyle::SP_CustomBase) {
mainIcon = theme->standardPixmap(sp, QSizeF(size));
- } else if (QPixmapCache::find(cacheKey, mainIcon) == false) {
+ } else if (QPixmapCache::find(cacheKey, &mainIcon) == false) {
mainIcon = theme->standardPixmap(sp, QSizeF(size));
QPixmapCache::insert(cacheKey, mainIcon);
}
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(QLatin1String(":/qt-project.org/styles/commonstyle/images/newdirectory-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/newdirectory-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/newdirectory-128.png"), 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(QLatin1String(":/qt-project.org/styles/commonstyle/images/viewdetailed-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/viewdetailed-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/viewdetailed-128.png"), QSize(128, 128));
- break;
- case SP_FileDialogInfoView:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/fileinfo-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/fileinfo-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/fileinfo-128.png"), QSize(128, 128));
- break;
- case SP_FileDialogContentsView:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/filecontents-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/filecontents-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/filecontents-128.png"), QSize(128, 128));
- break;
- case SP_FileDialogListView:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/viewlist-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/viewlist-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/viewlist-128.png"), QSize(128, 128));
- break;
- case SP_DialogOkButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-ok-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-ok-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-ok-128.png"), QSize(128, 128));
- break;
- case SP_DialogCancelButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-cancel-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-cancel-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-cancel-128.png"), QSize(128, 128));
- break;
- case SP_DialogHelpButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-help-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-help-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-help-128.png"), QSize(128, 128));
- break;
- case SP_DialogOpenButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-open-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-open-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-open-128.png"), QSize(128, 128));
- break;
- case SP_DialogSaveButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-save-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-save-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-save-128.png"), QSize(128, 128));
- break;
- case SP_DialogCloseButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-close-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-close-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-close-128.png"), QSize(128, 128));
- break;
- case SP_DialogApplyButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-apply-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-apply-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-apply-128.png"), QSize(128, 128));
- break;
- case SP_DialogResetButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-clear-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-clear-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-clear-128.png"), QSize(128, 128));
- break;
- case SP_DialogDiscardButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-delete-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-delete-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-delete-128.png"), QSize(128, 128));
- break;
- case SP_DialogYesButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-yes-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-yes-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-yes-128.png"), QSize(128, 128));
- break;
- case SP_DialogNoButton:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-no-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-no-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/standardbutton-no-128.png"), 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(QLatin1String(":/qt-project.org/styles/commonstyle/images/left-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/left-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/left-128.png"), QSize(128, 128));
- break;
- case SP_ArrowRight:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/right-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/right-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/right-128.png"), QSize(128, 128));
- break;
- case SP_ArrowUp:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/up-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/up-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/up-128.png"), QSize(128, 128));
- break;
- case SP_ArrowDown:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/down-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/down-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/down-128.png"), QSize(128, 128));
- break;
- case SP_DirHomeIcon:
- case SP_DirIcon:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/dirclosed-16.png"),
- QSize(), QIcon::Normal, QIcon::Off);
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/diropen-16.png"),
- QSize(), QIcon::Normal, QIcon::On);
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/dirclosed-32.png"),
- QSize(32, 32), QIcon::Normal, QIcon::Off);
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/diropen-32.png"),
- QSize(32, 32), QIcon::Normal, QIcon::On);
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/dirclosed-128.png"),
- QSize(128, 128), QIcon::Normal, QIcon::Off);
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/diropen-128.png"),
- QSize(128, 128), QIcon::Normal, QIcon::On);
- break;
- case SP_DriveCDIcon:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/cdr-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/cdr-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/cdr-128.png"), QSize(128, 128));
- break;
- case SP_DriveDVDIcon:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/dvd-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/dvd-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/dvd-128.png"), QSize(128, 128));
- break;
- case SP_FileIcon:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/file-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/file-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/file-128.png"), QSize(128, 128));
- break;
- case SP_FileLinkIcon:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/filelink-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/filelink-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/filelink-128.png"), QSize(128, 128));
- break;
- case SP_TrashIcon:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/trash-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/trash-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/trash-128.png"), QSize(128, 128));
- break;
- case SP_BrowserReload:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/refresh-24.png"), QSize(24, 24));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/refresh-32.png"), QSize(32, 32));
- break;
- case SP_BrowserStop:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/stop-24.png"), QSize(24, 24));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/stop-32.png"), QSize(32, 32));
- break;
- case SP_MediaPlay:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-play-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-play-32.png"), QSize(32, 32));
- break;
- case SP_MediaPause:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-pause-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-pause-32.png"), QSize(32, 32));
- break;
- case SP_MediaStop:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-stop-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-stop-32.png"), QSize(32, 32));
- break;
- case SP_MediaSeekForward:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-seek-forward-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-seek-forward-32.png"), QSize(32, 32));
- break;
- case SP_MediaSeekBackward:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-seek-backward-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-seek-backward-32.png"), QSize(32, 32));
- break;
- case SP_MediaSkipForward:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-skip-forward-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-skip-forward-32.png"), QSize(32, 32));
- break;
- case SP_MediaSkipBackward:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-skip-backward-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-skip-backward-32.png"), QSize(32, 32));
- break;
- case SP_MediaVolume:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-volume-16.png"), QSize(16, 16));
- break;
- case SP_MediaVolumeMuted:
- icon.addFile(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-volume-muted-16.png"), 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(QLatin1String(":/qt-project.org/qmessagebox/images/qtlogo-64.png"));
+ 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
+ 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;
}
@@ -6441,17 +6198,17 @@ 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);
QColor color = opt->palette.color(QPalette::Normal, QPalette::Highlight);
- color.setAlphaF(qreal(0.3));
+ color.setAlphaF(0.3f);
QPainter painter(&img);
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 78c5171717..40ed13d453 100644
--- a/src/widgets/styles/qcommonstyle.h
+++ b/src/widgets/styles/qcommonstyle.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOMMONSTYLE_H
#define QCOMMONSTYLE_H
@@ -97,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 6223a26a54..2fa90a8949 100644
--- a/src/widgets/styles/qcommonstyle_p.h
+++ b/src/widgets/styles/qcommonstyle_p.h
@@ -1,46 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOMMONSTYLE_P_H
#define QCOMMONSTYLE_P_H
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "qhash.h"
#include "qcommonstyle.h"
#include "qstyle_p.h"
#if QT_CONFIG(animation)
@@ -61,7 +26,6 @@ QT_BEGIN_NAMESPACE
// We mean it.
//
-class QStringList;
class QTextOption;
// Private class
@@ -112,7 +76,8 @@ public:
&& option.features == cachedOption->features
&& option.icon.isNull() == cachedOption->icon.isNull()
&& option.font == cachedOption->font
- && option.viewItemPosition == cachedOption->viewItemPosition);
+ && option.viewItemPosition == cachedOption->viewItemPosition
+ && option.showDecorationSelected == cachedOption->showDecorationSelected);
}
#endif
#if QT_CONFIG(toolbutton)
@@ -127,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/qcommonstylepixmaps_p.h b/src/widgets/styles/qcommonstylepixmaps_p.h
index 58b979465a..313c5b9375 100644
--- a/src/widgets/styles/qcommonstylepixmaps_p.h
+++ b/src/widgets/styles/qcommonstylepixmaps_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QtWidgets/private/qtwidgetsglobal_p.h>
@@ -52,6 +16,8 @@
// We mean it.
//
+// the SVG sources for these pixmaps are in styles/images
+
static const char * const check_list_controller_xpm[] = {
"16 16 4 1",
" c None",
diff --git a/src/widgets/styles/qdrawutil.cpp b/src/widgets/styles/qdrawutil.cpp
index d30b43a679..5bdbdb1139 100644
--- a/src/widgets/styles/qdrawutil.cpp
+++ b/src/widgets/styles/qdrawutil.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qdrawutil.h"
#include "qbitmap.h"
@@ -80,6 +44,7 @@ private:
/*!
\headerfile <qdrawutil.h>
+ \inmodule QtWidgets
\title Drawing Utility Functions
\sa QPainter
@@ -126,6 +91,20 @@ void qDrawShadeLine(QPainter *p, int x1, int y1, int x2, int y2,
qWarning("qDrawShadeLine: Invalid parameters");
return;
}
+ 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);
+ x1 = qRound(devicePixelRatio * x1);
+ y1 = qRound(devicePixelRatio * y1);
+ x2 = qRound(devicePixelRatio * x2);
+ y2 = qRound(devicePixelRatio * y2);
+ lineWidth = qRound(devicePixelRatio * lineWidth);
+ midLineWidth = qRound(devicePixelRatio * midLineWidth);
+ p->translate(0.5, 0.5);
+ }
int tlw = lineWidth*2 + midLineWidth; // total line width
QPen oldPen = p->pen(); // save pen
if (sunken)
@@ -214,7 +193,7 @@ void qDrawShadeLine(QPainter *p, int x1, int y1, int x2, int y2,
specifies the line width for each of the lines; it is not the
total line width. The \a midLineWidth specifies the width of a
middle line drawn in the QPalette::mid() color. The rectangle's
- interior is filled with the \a fill brush unless \a fill is 0.
+ interior is filled with the \a fill brush unless \a fill is \nullptr.
The rectangle appears sunken if \a sunken is true, otherwise
raised.
@@ -244,17 +223,18 @@ void qDrawShadeRect(QPainter *p, int x, int y, int w, int h,
}
PainterStateGuard painterGuard(p);
- const qreal devicePixelRatio = p->device()->devicePixelRatioF();
+ 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 = 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);
}
QPen oldPen = p->pen();
@@ -317,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,
@@ -331,7 +310,7 @@ void qDrawShadeRect(QPainter *p, int x, int y, int w, int h,
The given \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors). The panel's interior is filled
- with the \a fill brush unless \a fill is 0.
+ with the \a fill brush unless \a fill is \nullptr.
The panel appears sunken if \a sunken is true, otherwise raised.
@@ -358,16 +337,19 @@ void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
}
PainterStateGuard painterGuard(p);
- const qreal devicePixelRatio = p->device()->devicePixelRatioF();
+ const qreal devicePixelRatio = p->device()->devicePixelRatio();
+ bool isTranslated = false;
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 = 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;
}
QColor shade = pal.dark().color();
@@ -379,7 +361,7 @@ void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
light = pal.midlight().color();
}
QPen oldPen = p->pen(); // save pen
- QVector<QLineF> lines;
+ QList<QLineF> lines;
lines.reserve(2*lineWidth);
if (sunken)
@@ -418,12 +400,14 @@ void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
lines << QLineF(x1--, y1++, x2--, y2);
}
p->drawLines(lines);
- if (fill) // fill with fill color
+ if (fill) { // fill with fill color
+ if (isTranslated)
+ p->translate(-0.5, -0.5);
p->fillRect(x+lineWidth, y+lineWidth, w-lineWidth*2, h-lineWidth*2, *fill);
+ }
p->setPen(oldPen); // restore pen
}
-
/*!
\internal
This function draws a rectangle with two pixel line width.
@@ -449,15 +433,18 @@ static void qDrawWinShades(QPainter *p,
return;
PainterStateGuard painterGuard(p);
- const qreal devicePixelRatio = p->device()->devicePixelRatioF();
+ const qreal devicePixelRatio = p->device()->devicePixelRatio();
+ bool isTranslated = false;
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 = qRound(devicePixelRatio * w);
- h = qRound(devicePixelRatio * h);
+ w = devicePixelRatio * w;
+ h = devicePixelRatio * h;
+ p->translate(0.5, 0.5);
+ isTranslated = true;
}
QPen oldPen = p->pen();
@@ -474,8 +461,11 @@ static void qDrawWinShades(QPainter *p,
QPoint d[3] = { QPoint(x+1, y+h-2), QPoint(x+w-2, y+h-2), QPoint(x+w-2, y+1) };
p->setPen(c4);
p->drawPolyline(d, 3);
- if (fill)
+ if (fill) {
+ if (isTranslated)
+ p->translate(-0.5, -0.5);
p->fillRect(QRect(x+2, y+2, w-4, h-4), *fill);
+ }
}
p->setPen(oldPen);
}
@@ -490,7 +480,7 @@ static void qDrawWinShades(QPainter *p,
Draws the Windows-style button specified by the given point (\a x,
\a y}, \a width and \a height using the provided \a painter with a
line width of 2 pixels. The button's interior is filled with the
- \a{fill} brush unless \a fill is 0.
+ \a{fill} brush unless \a fill is \nullptr.
The given \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
@@ -528,7 +518,7 @@ void qDrawWinButton(QPainter *p, int x, int y, int w, int h,
Draws the Windows-style panel specified by the given point(\a x,
\a y), \a width and \a height using the provided \a painter with a
line width of 2 pixels. The button's interior is filled with the
- \a fill brush unless \a fill is 0.
+ \a fill brush unless \a fill is \nullptr.
The given \a palette specifies the shading colors. The panel
appears sunken if \a sunken is true, otherwise raised.
@@ -567,7 +557,7 @@ void qDrawWinPanel(QPainter *p, int x, int y, int w, int h,
Draws the plain rectangle beginning at (\a x, \a y) with the given
\a width and \a height, using the specified \a painter, \a lineColor
and \a lineWidth. The rectangle's interior is filled with the \a
- fill brush unless \a fill is 0.
+ 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
@@ -591,16 +581,17 @@ void qDrawPlainRect(QPainter *p, int x, int y, int w, int h, const QColor &c,
}
PainterStateGuard painterGuard(p);
- const qreal devicePixelRatio = p->device()->devicePixelRatioF();
+ 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 = qRound(devicePixelRatio * w);
- h = qRound(devicePixelRatio * h);
+ w = devicePixelRatio * w;
+ h = devicePixelRatio * h;
lineWidth = qRound(devicePixelRatio * lineWidth);
+ p->translate(0.5, 0.5);
}
QPen oldPen = p->pen();
@@ -618,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.
*****************************************************************************/
@@ -676,7 +735,7 @@ void qDrawShadeLine(QPainter *p, const QPoint &p1, const QPoint &p2,
specifies the line width for each of the lines; it is not the
total line width. The \a midLineWidth specifies the width of a
middle line drawn in the QPalette::mid() color. The rectangle's
- interior is filled with the \a fill brush unless \a fill is 0.
+ interior is filled with the \a fill brush unless \a fill is \nullptr.
The rectangle appears sunken if \a sunken is true, otherwise
raised.
@@ -714,7 +773,7 @@ void qDrawShadeRect(QPainter *p, const QRect &r,
The given \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors). The panel's interior is filled
- with the \a fill brush unless \a fill is 0.
+ with the \a fill brush unless \a fill is \nullptr.
The panel appears sunken if \a sunken is true, otherwise raised.
@@ -746,7 +805,7 @@ void qDrawShadePanel(QPainter *p, const QRect &r,
Draws the Windows-style button at the rectangle specified by \a rect using
the given \a painter with a line width of 2 pixels. The button's interior
- is filled with the \a{fill} brush unless \a fill is 0.
+ is filled with the \a{fill} brush unless \a fill is \nullptr.
The given \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
@@ -770,11 +829,12 @@ void qDrawWinButton(QPainter *p, const QRect &r,
/*!
\fn void qDrawWinPanel(QPainter *painter, const QRect &rect, const QPalette &palette,
bool sunken, const QBrush *fill)
+ \relates <qdrawutil.h>
\overload
Draws the Windows-style panel at the rectangle specified by \a rect using
the given \a painter with a line width of 2 pixels. The button's interior
- is filled with the \a fill brush unless \a fill is 0.
+ is filled with the \a fill brush unless \a fill is \nullptr.
The given \a palette specifies the shading colors. The panel
appears sunken if \a sunken is true, otherwise raised.
@@ -804,7 +864,7 @@ void qDrawWinPanel(QPainter *p, const QRect &r,
Draws the plain rectangle specified by \a rect using the given \a painter,
\a lineColor and \a lineWidth. The rectangle's interior is filled with the
- \a fill brush unless \a fill is 0.
+ \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
@@ -825,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
@@ -866,6 +952,7 @@ void qDrawPlainRect(QPainter *p, const QRect &r, const QColor &c,
typedef QVarLengthArray<QPainter::PixmapFragment, 16> QPixmapFragmentsArray;
/*!
+ \relates <qdrawutil.h>
\since 4.6
Draws the indicated \a sourceRect rectangle from the given \a pixmap into
@@ -883,7 +970,7 @@ typedef QVarLengthArray<QPainter::PixmapFragment, 16> QPixmapFragmentsArray;
void qDrawBorderPixmap(QPainter *painter, const QRect &targetRect, const QMargins &targetMargins,
const QPixmap &pixmap, const QRect &sourceRect,const QMargins &sourceMargins,
const QTileRules &rules
-#ifndef Q_CLANG_QDOC
+#ifndef Q_QDOC
, QDrawBorderPixmap::DrawingHints hints
#endif
)
diff --git a/src/widgets/styles/qdrawutil.h b/src/widgets/styles/qdrawutil.h
index 346029e1b4..26d8d5075f 100644
--- a/src/widgets/styles/qdrawutil.h
+++ b/src/widgets/styles/qdrawutil.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDRAWUTIL_H
#define QDRAWUTIL_H
@@ -107,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
@@ -119,7 +94,7 @@ struct QTileRules
Qt::TileRule vertical;
};
-#ifndef Q_CLANG_QDOC
+#ifndef Q_QDOC
// For internal use only.
namespace QDrawBorderPixmap
{
@@ -151,7 +126,7 @@ Q_WIDGETS_EXPORT void qDrawBorderPixmap(QPainter *painter,
const QRect &sourceRect,
const QMargins &sourceMargins,
const QTileRules &rules = QTileRules()
-#ifndef Q_CLANG_QDOC
+#ifndef Q_QDOC
, QDrawBorderPixmap::DrawingHints hints = QDrawBorderPixmap::DrawingHints()
#endif
);
diff --git a/src/widgets/styles/qfusionstyle.cpp b/src/widgets/styles/qfusionstyle.cpp
index c4bc52aa87..8328459976 100644
--- a/src/widgets/styles/qfusionstyle.cpp
+++ b/src/widgets/styles/qfusionstyle.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qfusionstyle_p.h"
#include "qfusionstyle_p_p.h"
@@ -52,6 +16,7 @@
#include <qabstractbutton.h>
#endif
#include <qpainter.h>
+#include <qpainterpath.h>
#include <qdir.h>
#include <qstyleoption.h>
#include <qapplication.h>
@@ -92,6 +57,7 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
using namespace QStyleHelper;
enum Direction {
@@ -103,85 +69,12 @@ enum Direction {
// from windows style
static const int windowsItemFrame = 2; // menu item frame width
-static const int windowsItemHMargin = 3; // menu item hor text margin
static const int windowsItemVMargin = 8; // menu item ver text margin
-static const int windowsRightBorder = 15; // right border on windows
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",
@@ -260,9 +153,10 @@ 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(QLatin1String("fusion-arrow"), 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());
if (!QPixmapCache::find(cacheKey, &cachePixmap)) {
cachePixmap = styleCachePixmap(rect.size());
cachePixmap.fill(Qt::transparent);
@@ -276,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);
}
@@ -365,11 +258,6 @@ static void qt_fusion_draw_mdibutton(QPainter *painter, const QStyleOptionTitleB
painter->drawPoint(tmp.right() , tmp.bottom() - 1);
}
-static QWindow *qt_getWindow(const QWidget *widget)
-{
- return widget ? QWidgetPrivate::get(widget)->windowHandle(QWidgetPrivate::WindowHandleMode::Closest) : nullptr;
-}
-
/*
\internal
*/
@@ -396,7 +284,7 @@ QFusionStylePrivate::QFusionStylePrivate()
*/
QFusionStyle::QFusionStyle() : QCommonStyle(*new QFusionStylePrivate)
{
- setObjectName(QLatin1String("Fusion"));
+ setObjectName("Fusion"_L1);
}
/*!
@@ -416,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);
}
@@ -465,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) {
@@ -476,17 +345,8 @@ void QFusionStyle::drawPrimitive(PrimitiveElement elem,
// No frame drawn
case PE_FrameGroupBox:
{
- QPixmap pixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/fusion_groupbox.png"));
- int topMargin = 0;
- auto control = dynamic_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);
+ QPixmap pixmap(":/qt-project.org/styles/commonstyle/images/fusion_groupbox.png"_L1);
+ qDrawBorderPixmap(painter, option->rect, QMargins(6, 6, 6, 6), pixmap);
break;
}
#endif // QT_CONFIG(groupbox)
@@ -940,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);
@@ -994,17 +854,6 @@ void QFusionStyle::drawPrimitive(PrimitiveElement elem,
case PE_FrameStatusBarItem:
break;
- case PE_IndicatorTabClose:
- {
- Q_D(const QFusionStyle);
- if (d->tabBarcloseButtonIcon.isNull())
- d->tabBarcloseButtonIcon = proxy()->standardIcon(SP_DialogCloseButton, option, widget);
- if ((option->state & State_Enabled) && (option->state & State_MouseOver))
- proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
- QPixmap pixmap = d->tabBarcloseButtonIcon.pixmap(qt_getWindow(widget), QSize(16, 16), QIcon::Normal, QIcon::On);
- proxy()->drawItemPixmap(painter, option->rect, Qt::AlignCenter, pixmap);
- }
- break;
case PE_PanelMenu: {
painter->save();
const QBrush menuBackground = option->palette.base().color().lighter(108);
@@ -1041,7 +890,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
if (!cb->currentIcon.isNull()) {
QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal
: QIcon::Disabled;
- QPixmap pixmap = cb->currentIcon.pixmap(qt_getWindow(widget), cb->iconSize, mode);
+ QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, painter->device()->devicePixelRatio(), mode);
QRect iconRect(editRect);
iconRect.setWidth(cb->iconSize.width() + 4);
iconRect = alignedRect(cb->direction,
@@ -1058,7 +907,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
}
if (!cb->currentText.isEmpty() && !cb->editable) {
proxy()->drawItemText(painter, editRect.adjusted(1, 0, -1, 0),
- visualAlignment(cb->direction, Qt::AlignLeft | Qt::AlignVCenter),
+ visualAlignment(cb->direction, cb->textAlignment),
cb->palette, cb->state & State_Enabled, cb->currentText,
cb->editable ? QPalette::Text : QPalette::ButtonText);
}
@@ -1095,7 +944,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
QColor dimHighlight(qMin(highlight.red()/2 + 110, 255),
qMin(highlight.green()/2 + 110, 255),
qMin(highlight.blue()/2 + 110, 255));
- dimHighlight.setAlpha(widget && widget->isTopLevel() ? 255 : 80);
+ dimHighlight.setAlpha(widget && widget->isWindow() ? 255 : 80);
QLinearGradient gradient(rect.topLeft(), QPoint(rect.bottomLeft().x(), rect.bottomLeft().y()));
gradient.setColorAt(0, dimHighlight.lighter(120));
gradient.setColorAt(1, dimHighlight);
@@ -1103,10 +952,13 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
painter->translate(0.5, 0.5);
painter->setBrush(dimHighlight);
painter->drawRoundedRect(option->rect.adjusted(0, 0, -1, -1), 1, 1);
- QColor innerLine = Qt::white;
- innerLine.setAlpha(40);
- painter->setPen(innerLine);
- painter->drawRoundedRect(option->rect.adjusted(1, 1, -2, -2), 1, 1);
+ //when the rectangle we get is large enough, draw the inner rectangle.
+ if (option->rect.width() > 2 && option->rect.height() > 2) {
+ QColor innerLine = Qt::white;
+ innerLine.setAlpha(40);
+ painter->setPen(innerLine);
+ painter->drawRoundedRect(option->rect.adjusted(1, 1, -2, -2), 1, 1);
+ }
painter->restore();
}
break;
@@ -1273,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);
}
@@ -1284,10 +1136,13 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
painter->save();
// Draws the header in tables.
if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("headersection"), option, option->rect.size());
- pixmapName += QString::number(- int(header->position));
- pixmapName += QString::number(- int(header->orientation));
-
+ const QStyleOptionHeaderV2 *headerV2 = qstyleoption_cast<const QStyleOptionHeaderV2 *>(option);
+ const bool isSectionDragTarget = headerV2 ? headerV2->isSectionDragTarget : false;
+ const QString pixmapName = QStyleHelper::uniqueName("headersection-"_L1
+ % HexString(header->position)
+ % HexString(header->orientation)
+ % QLatin1Char(isSectionDragTarget ? '1' : '0'),
+ option, option->rect.size());
QPixmap cache;
if (!QPixmapCache::find(pixmapName, &cache)) {
cache = styleCachePixmap(rect.size());
@@ -1295,9 +1150,12 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
QRect pixmapRect(0, 0, rect.width(), rect.height());
QPainter cachePainter(&cache);
QColor buttonColor = d->buttonColor(option->palette);
- QColor gradientStopColor;
QColor gradientStartColor = buttonColor.lighter(104);
- gradientStopColor = buttonColor.darker(102);
+ QColor gradientStopColor = buttonColor.darker(102);
+ if (isSectionDragTarget) {
+ gradientStopColor = gradientStartColor.darker(130);
+ gradientStartColor = gradientStartColor.darker(130);
+ }
QLinearGradient gradient(pixmapRect.topLeft(), pixmapRect.bottomLeft());
if (option->palette.window().gradient()) {
@@ -1361,37 +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;
-
- // Get extra style options if version 2
- vertical = (bar->orientation == Qt::Vertical);
- 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;
@@ -1400,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) {
@@ -1436,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();
@@ -1466,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->orientation == Qt::Vertical);
- 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;
@@ -1531,7 +1396,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
//draw text
QPalette::ColorRole textRole = dis ? QPalette::Text : QPalette::HighlightedText;
uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!styleHint(SH_UnderlineShortcut, mbi, widget))
+ if (!proxy()->styleHint(SH_UnderlineShortcut, mbi, widget))
alignment |= Qt::TextHideMnemonic;
proxy()->drawItemText(painter, item.rect, alignment, mbi->palette, mbi->state & State_Enabled, mbi->text, textRole);
} else {
@@ -1555,34 +1420,37 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
const int margin = int(QStyleHelper::dpiScaled(5, option));
if (!menuItem->text.isEmpty()) {
painter->setFont(menuItem->font);
- proxy()->drawItemText(painter, menuItem->rect.adjusted(margin, 0, -margin, 0), Qt::AlignLeft | Qt::AlignVCenter,
+ proxy()->drawItemText(painter, menuItem->rect.adjusted(margin, 0, -margin, 0),
+ Qt::AlignLeft | Qt::AlignVCenter,
menuItem->palette, menuItem->state & State_Enabled, menuItem->text,
QPalette::Text);
w = menuItem->fontMetrics.horizontalAdvance(menuItem->text) + margin;
}
painter->setPen(shadow.lighter(106));
- bool reverse = menuItem->direction == Qt::RightToLeft;
- painter->drawLine(menuItem->rect.left() + margin + (reverse ? 0 : w), menuItem->rect.center().y(),
- menuItem->rect.right() - margin - (reverse ? w : 0), menuItem->rect.center().y());
+ const bool reverse = menuItem->direction == Qt::RightToLeft;
+ qreal y = menuItem->rect.center().y() + 0.5f;
+ painter->drawLine(QPointF(menuItem->rect.left() + margin + (reverse ? 0 : w), y),
+ QPointF(menuItem->rect.right() - margin - (reverse ? w : 0), y));
painter->restore();
break;
}
- bool selected = menuItem->state & State_Selected && menuItem->state & State_Enabled;
+ const bool selected = menuItem->state & State_Selected && menuItem->state & State_Enabled;
if (selected) {
QRect r = option->rect;
painter->fillRect(r, highlight);
painter->setPen(QPen(highlightOutline));
painter->drawRect(QRectF(r).adjusted(0.5, 0.5, -0.5, -0.5));
}
- bool checkable = menuItem->checkType != QStyleOptionMenuItem::NotCheckable;
- bool checked = menuItem->checked;
- bool sunken = menuItem->state & State_Sunken;
- bool enabled = menuItem->state & State_Enabled;
+ const bool checkable = menuItem->checkType != QStyleOptionMenuItem::NotCheckable;
+ const bool checked = menuItem->checked;
+ const bool sunken = menuItem->state & State_Sunken;
+ const bool enabled = menuItem->state & State_Enabled;
- bool ignoreCheckMark = false;
- const int checkColHOffset = windowsItemHMargin + windowsItemFrame - 1;
+ const int checkColHOffset = QFusionStylePrivate::menuItemHMargin + windowsItemFrame - 1;
+ // icon checkbox's highlight column width
int checkcol = qMax<int>(menuItem->rect.height() * 0.79,
- qMax<int>(menuItem->maxIconWidth, dpiScaled(21, option))); // icon checkbox's highlight column width
+ qMax<int>(menuItem->maxIconWidth, dpiScaled(21, option)));
+ bool ignoreCheckMark = false;
if (
#if QT_CONFIG(combobox)
qobject_cast<const QComboBox*>(widget) ||
@@ -1594,8 +1462,9 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
// Check, using qreal and QRectF to avoid error accumulation
const qreal boxMargin = dpiScaled(3.5, option);
const qreal boxWidth = checkcol - 2 * boxMargin;
- QRectF checkRectF(option->rect.left() + boxMargin + checkColHOffset, option->rect.center().y() - boxWidth/2 + 1, boxWidth, boxWidth);
- QRect checkRect = checkRectF.toRect();
+ QRect checkRect = QRectF(option->rect.left() + boxMargin + checkColHOffset,
+ option->rect.center().y() - boxWidth/2 + 1, boxWidth,
+ boxWidth).toRect();
checkRect.setWidth(checkRect.height()); // avoid .toRect() round error results in non-perfect square
checkRect = visualRect(menuItem->direction, menuItem->rect, checkRect);
if (checkable) {
@@ -1605,8 +1474,10 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
painter->setRenderHint(QPainter::Antialiasing);
painter->setPen(Qt::NoPen);
- QPalette::ColorRole textRole = !enabled ? QPalette::Text:
- selected ? QPalette::HighlightedText : QPalette::ButtonText;
+ QPalette::ColorRole textRole = !enabled
+ ? QPalette::Text :
+ selected ? QPalette::HighlightedText
+ : QPalette::ButtonText;
painter->setBrush(option->palette.brush( option->palette.currentColorGroup(), textRole));
const int adjustment = checkRect.height() * 0.3;
painter->drawEllipse(checkRect.adjusted(adjustment, adjustment, -adjustment, -adjustment));
@@ -1633,8 +1504,8 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
}
// Text and icon, ripped from windows style
- bool dis = !(menuItem->state & State_Enabled);
- bool act = menuItem->state & State_Selected;
+ const bool dis = !(menuItem->state & State_Enabled);
+ const bool act = menuItem->state & State_Selected;
const QStyleOption *opt = option;
const QStyleOptionMenuItem *menuitem = menuItem;
@@ -1655,14 +1526,11 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
iconSize = combo->iconSize();
#endif
if (checked)
- pixmap = menuItem->icon.pixmap(qt_getWindow(widget), iconSize, mode, QIcon::On);
+ pixmap = menuItem->icon.pixmap(iconSize, painter->device()->devicePixelRatio(), mode, QIcon::On);
else
- pixmap = menuItem->icon.pixmap(qt_getWindow(widget), iconSize, mode);
-
- const int pixw = pixmap.width() / pixmap.devicePixelRatio();
- const int pixh = pixmap.height() / pixmap.devicePixelRatio();
+ pixmap = menuItem->icon.pixmap(iconSize, painter->device()->devicePixelRatio(), mode);
- QRect pmr(0, 0, pixw, pixh);
+ QRect pmr(QPoint(0, 0), pixmap.deviceIndependentSize().toSize());
pmr.moveCenter(vCheckRect.center());
painter->setPen(menuItem->palette.text().color());
if (!ignoreCheckMark && checkable && checked) {
@@ -1685,36 +1553,38 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
}
int x, y, w, h;
menuitem->rect.getRect(&x, &y, &w, &h);
- int tab = menuitem->tabWidth;
QColor discol;
if (dis) {
discol = menuitem->palette.text().color();
p->setPen(discol);
}
- int xm = checkColHOffset + checkcol + windowsItemHMargin;
- int xpos = menuitem->rect.x() + xm;
+ const int xm = checkColHOffset + checkcol + QFusionStylePrivate::menuItemHMargin;
+ const int xpos = menuitem->rect.x() + xm;
- QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
- QRect vTextRect = visualRect(opt->direction, menuitem->rect, textRect);
- QStringRef s(&menuitem->text);
+ const QRect textRect(xpos, y + windowsItemVMargin,
+ w - xm - QFusionStylePrivate::menuRightBorder - menuitem->reservedShortcutWidth + 2,
+ h - 2 * windowsItemVMargin);
+ const QRect vTextRect = visualRect(opt->direction, menuitem->rect, textRect);
+ QStringView s(menuitem->text);
if (!s.isEmpty()) { // draw text
p->save();
- int t = s.indexOf(QLatin1Char('\t'));
+ const qsizetype tabIndex = s.indexOf(u'\t');
int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!styleHint(SH_UnderlineShortcut, menuitem, widget))
+ if (!proxy()->styleHint(SH_UnderlineShortcut, menuitem, widget))
text_flags |= Qt::TextHideMnemonic;
text_flags |= Qt::AlignLeft;
- if (t >= 0) {
+ if (tabIndex >= 0) {
QRect vShortcutRect = visualRect(opt->direction, menuitem->rect,
- QRect(textRect.topRight(), QPoint(menuitem->rect.right(), textRect.bottom())));
- const QString textToDraw = s.mid(t + 1).toString();
+ QRect(textRect.topRight(),
+ QPoint(menuitem->rect.right(), textRect.bottom())));
+ const QString textToDraw = s.mid(tabIndex + 1).toString();
if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, option, widget)) {
p->setPen(menuitem->palette.light().color());
p->drawText(vShortcutRect.adjusted(1, 1, 1, 1), text_flags, textToDraw);
p->setPen(discol);
}
p->drawText(vShortcutRect, text_flags, textToDraw);
- s = s.left(t);
+ s = s.left(tabIndex);
}
QFont font = menuitem->font;
// font may not have any "hard" flags set. We override
@@ -1728,7 +1598,10 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
font.setBold(true);
p->setFont(font);
- const QString textToDraw = s.left(t).toString();
+ const QFontMetrics fontMetrics(font);
+ const QString textToDraw = fontMetrics.elidedText(s.left(tabIndex).toString(),
+ Qt::ElideMiddle, vTextRect.width(),
+ text_flags);
if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, option, widget)) {
p->setPen(menuitem->palette.light().color());
p->drawText(vTextRect.adjusted(1, 1, 1, 1), text_flags, textToDraw);
@@ -1740,10 +1613,10 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
// Arrow
if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
- int dim = (menuItem->rect.height() - 4) / 2;
+ const int dim = (menuItem->rect.height() - 4) / 2;
PrimitiveElement arrow;
arrow = option->direction == Qt::RightToLeft ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- int xpos = menuItem->rect.left() + menuItem->rect.width() - 3 - dim;
+ const int xpos = menuItem->rect.left() + menuItem->rect.width() - 3 - dim;
QRect vSubMenuRect = visualRect(option->direction, menuItem->rect,
QRect(xpos, menuItem->rect.top() + menuItem->rect.height() / 2 - dim / 2, dim, dim));
QStyleOptionMenuItem newMI = *menuItem;
@@ -1770,14 +1643,6 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
proxy()->drawControl(CE_PushButtonLabel, &subopt, painter, widget);
}
break;
- case CE_PushButtonLabel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- QStyleOptionButton b(*button);
- // no PM_ButtonShiftHorizontal and PM_ButtonShiftVertical for fusion style
- b.state &= ~(State_On | State_Sunken);
- QCommonStyle::drawControl(element, &b, painter, widget);
- }
- break;
case CE_MenuBarEmptyArea:
painter->save();
{
@@ -1963,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
@@ -1999,7 +1880,7 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
case CC_SpinBox:
if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("spinbox"), spinBox, spinBox->rect.size());
+ QString pixmapName = QStyleHelper::uniqueName("spinbox"_L1, spinBox, spinBox->rect.size());
if (!QPixmapCache::find(pixmapName, &cache)) {
cache = styleCachePixmap(spinBox->rect.size());
@@ -2038,22 +1919,24 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
cachePainter.setPen(d->topShadow());
cachePainter.drawLine(QPoint(r.left() + 2, r.top() + 1), QPoint(r.right() - 2, r.top() + 1));
- // Draw button gradient
- QColor buttonColor = d->buttonColor(option->palette);
- QRect updownRect = upRect.adjusted(0, -2, 0, downRect.height() + 2);
- QLinearGradient gradient = qt_fusion_gradient(updownRect, (isEnabled && option->state & State_MouseOver ) ? buttonColor : buttonColor.darker(104));
+ if (!upRect.isNull()) {
+ // Draw button gradient
+ const QColor buttonColor = d->buttonColor(option->palette);
+ const QRect updownRect = upRect.adjusted(0, -2, 0, downRect.height() + 2);
+ const QLinearGradient gradient = qt_fusion_gradient(updownRect, (isEnabled && option->state & State_MouseOver )
+ ? buttonColor : buttonColor.darker(104));
- // Draw button gradient
- cachePainter.setPen(Qt::NoPen);
- cachePainter.setBrush(gradient);
+ cachePainter.setPen(Qt::NoPen);
+ cachePainter.setBrush(gradient);
- cachePainter.save();
- cachePainter.setClipRect(updownRect);
- cachePainter.drawRoundedRect(r.adjusted(0, 0, -1, -1), 2, 2);
- cachePainter.setPen(QPen(d->innerContrastLine()));
- cachePainter.setBrush(Qt::NoBrush);
- cachePainter.drawRoundedRect(r.adjusted(1, 1, -2, -2), 2, 2);
- cachePainter.restore();
+ cachePainter.save();
+ cachePainter.setClipRect(updownRect);
+ cachePainter.drawRoundedRect(r.adjusted(0, 0, -1, -1), 2, 2);
+ cachePainter.setPen(QPen(d->innerContrastLine()));
+ cachePainter.setBrush(Qt::NoBrush);
+ cachePainter.drawRoundedRect(r.adjusted(1, 1, -2, -2), 2, 2);
+ cachePainter.restore();
+ }
if ((spinBox->stepEnabled & QAbstractSpinBox::StepUpEnabled) && upIsActive) {
if (sunken)
@@ -2081,12 +1964,14 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
cachePainter.restore();
}
- // outline the up/down buttons
- cachePainter.setPen(outline);
- if (spinBox->direction == Qt::RightToLeft) {
- cachePainter.drawLine(upRect.right(), upRect.top() - 1, upRect.right(), downRect.bottom() + 1);
- } else {
- cachePainter.drawLine(upRect.left(), upRect.top() - 1, upRect.left(), downRect.bottom() + 1);
+ if (spinBox->buttonSymbols != QAbstractSpinBox::NoButtons) {
+ // buttonSymbols == NoButtons results in 'null' rects
+ // and a tiny rect painted in the corner.
+ cachePainter.setPen(outline);
+ if (spinBox->direction == Qt::RightToLeft)
+ cachePainter.drawLine(QLineF(upRect.right(), upRect.top() - 0.5, upRect.right(), downRect.bottom() + 1.5));
+ else
+ cachePainter.drawLine(QLineF(upRect.left(), upRect.top() - 0.5, upRect.left(), downRect.bottom() + 1.5));
}
if (upIsActive && sunken) {
@@ -2416,7 +2301,7 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
QStyle::State oldState = static_cast<QStyle::State>(qvariant_cast<QStyle::State::Int>(styleObject->property("_q_stylestate")));
uint oldActiveControls = styleObject->property("_q_stylecontrols").toUInt();
- // a scrollbar is transient when the the scrollbar itself and
+ // a scrollbar is transient when the scrollbar itself and
// its sibling are both inactive (ie. not pressed/hovered/moved)
bool transient = !option->activeSubControls && !(option->state & State_On);
@@ -2561,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();
}
@@ -2601,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));
@@ -2634,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);
@@ -2671,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);
@@ -2696,7 +2568,7 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
}
painter->restore();
- break;;
+ break;
#endif // QT_CONFIG(slider)
case CC_ComboBox:
painter->save();
@@ -2705,16 +2577,12 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
bool sunken = comboBox->state & State_On; // play dead, if combobox has no items
bool isEnabled = (comboBox->state & State_Enabled);
QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("combobox"), option, comboBox->rect.size());
- if (sunken)
- pixmapName += QLatin1String("-sunken");
- if (comboBox->editable)
- pixmapName += QLatin1String("-editable");
- if (isEnabled)
- pixmapName += QLatin1String("-enabled");
- if (!comboBox->frame)
- pixmapName += QLatin1String("-frameless");
-
+ 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());
if (!QPixmapCache::find(pixmapName, &cache)) {
cache = styleCachePixmap(comboBox->rect.size());
cache.fill(Qt::transparent);
@@ -2826,7 +2694,7 @@ 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(QLatin1String("slider_groove"), option, groove.size());
+ QString groovePixmapName = QStyleHelper::uniqueName("slider_groove"_L1, option, groove.size());
QRect pixmapRect(0, 0, groove.width(), groove.height());
// draw background groove
@@ -2857,7 +2725,8 @@ void QFusionStyle::drawComplexControl(ComplexControl control, const QStyleOption
// draw blue groove highlight
QRect clipRect;
- groovePixmapName += QLatin1String("_blue");
+ if (!groovePixmapName.isEmpty())
+ groovePixmapName += "_blue"_L1;
if (!QPixmapCache::find(groovePixmapName, &cache)) {
cache = styleCachePixmap(pixmapRect.size());
cache.fill(Qt::transparent);
@@ -2873,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);
@@ -2894,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());
}
@@ -2908,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);
@@ -2925,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;
@@ -2938,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
@@ -2961,10 +2834,12 @@ 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(QLatin1String("slider_handle"), option, handle.size());
+ QString handlePixmapName = QStyleHelper::uniqueName("slider_handle"_L1, option, handle.size());
if (!QPixmapCache::find(handlePixmapName, &cache)) {
cache = styleCachePixmap(handle.size());
cache.fill(Qt::transparent);
@@ -2981,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)
@@ -3051,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;
@@ -3166,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;
@@ -3192,22 +3066,22 @@ QSize QFusionStyle::sizeFromContents(ContentsType type, const QStyleOption *opti
case CT_MenuItem:
if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
int w = size.width(); // Don't rely of QCommonStyle's width calculation here
- int maxpmw = menuItem->maxIconWidth;
- int tabSpacing = 20;
- if (menuItem->text.contains(QLatin1Char('\t')))
- w += tabSpacing;
+ if (menuItem->text.contains(u'\t'))
+ w += menuItem->reservedShortcutWidth;
else if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu)
w += 2 * QStyleHelper::dpiScaled(QFusionStylePrivate::menuArrowHMargin, option);
else if (menuItem->menuItemType == QStyleOptionMenuItem::DefaultItem) {
- QFontMetrics fm(menuItem->font);
+ const QFontMetrics fm(menuItem->font);
QFont fontBold = menuItem->font;
fontBold.setBold(true);
- QFontMetrics fmBold(fontBold);
+ const QFontMetrics fmBold(fontBold);
w += fmBold.horizontalAdvance(menuItem->text) - fm.horizontalAdvance(menuItem->text);
}
const qreal dpi = QStyleHelper::dpi(option);
- const int checkcol = qMax<int>(maxpmw, QStyleHelper::dpiScaled(QFusionStylePrivate::menuCheckMarkWidth, dpi)); // Windows always shows a check column
- w += checkcol;
+ // Windows always shows a check column
+ const int checkcol = qMax<int>(menuItem->maxIconWidth,
+ QStyleHelper::dpiScaled(QFusionStylePrivate::menuCheckMarkWidth, dpi));
+ w += checkcol + windowsItemFrame;
w += QStyleHelper::dpiScaled(int(QFusionStylePrivate::menuRightBorder) + 10, dpi);
newSize.setWidth(w);
if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
@@ -3348,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));
- rect.setWidth(proxy()->pixelMetric(PM_SliderLength));
+ 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));
- rect.setHeight(proxy()->pixelMetric(PM_SliderLength));
+ 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);
}
}
@@ -3372,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;
@@ -3426,6 +3310,7 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
break;
case SC_SpinBoxFrame:
rect = spinbox->rect;
+ break;
default:
break;
}
@@ -3435,14 +3320,20 @@ 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;
- int topMargin = qMax(pixelMetric(PM_ExclusiveIndicatorHeight), option->fontMetrics.height()) + groupBoxTopMargin;
+ 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);
}
@@ -3456,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;
}
}
@@ -3713,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;
}
@@ -3755,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);
}
@@ -3780,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 cbefe3e1af..7dfeb34d7c 100644
--- a/src/widgets/styles/qfusionstyle_p.h
+++ b/src/widgets/styles/qfusionstyle_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFUSIONSTYLE_P_H
#define QFUSIONSTYLE_P_H
@@ -90,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/qfusionstyle_p_p.h b/src/widgets/styles/qfusionstyle_p_p.h
index a92041fcfe..da8e26ba04 100644
--- a/src/widgets/styles/qfusionstyle_p_p.h
+++ b/src/widgets/styles/qfusionstyle_p_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFUSIONSTYLE_P_P_H
#define QFUSIONSTYLE_P_P_H
@@ -87,7 +51,7 @@ public:
// On mac we want a standard blue color used when the system palette is used
bool isMacSystemPalette(const QPalette &pal) const {
Q_UNUSED(pal);
-#if defined(Q_OS_MACX)
+#if defined(Q_OS_MACOS)
const QPalette *themePalette = QGuiApplicationPrivate::platformTheme()->palette();
if (themePalette && themePalette->color(QPalette::Normal, QPalette::Highlight) ==
pal.color(QPalette::Normal, QPalette::Highlight) &&
diff --git a/src/widgets/styles/qpixmapstyle.cpp b/src/widgets/styles/qpixmapstyle.cpp
index 05e8467528..8eadba9443 100644
--- a/src/widgets/styles/qpixmapstyle.cpp
+++ b/src/widgets/styles/qpixmapstyle.cpp
@@ -1,43 +1,7 @@
-/***************************************************************************
-**
-** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
-** Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2014 BlackBerry Limited. All rights reserved.
+// Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
+// 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 "qpixmapstyle_p.h"
#include "qpixmapstyle_p_p.h"
@@ -825,7 +789,7 @@ void QPixmapStyle::drawProgressBarBackground(const QStyleOption *option,
bool vertical = false;
if (const QStyleOptionProgressBar *pb =
qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- vertical = pb->orientation == Qt::Vertical;
+ vertical = !(pb->state & QStyle::State_Horizontal);
}
drawCachedPixmap(vertical ? PB_VBackground : PB_HBackground, option->rect, painter);
}
@@ -835,7 +799,7 @@ void QPixmapStyle::drawProgressBarLabel(const QStyleOption *option,
{
if (const QStyleOptionProgressBar *pb =
qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- const bool vertical = pb->orientation == Qt::Vertical;
+ const bool vertical = !(pb->state & QStyle::State_Horizontal);
if (!vertical) {
QPalette::ColorRole textRole = QPalette::ButtonText;
proxy()->drawItemText(painter, pb->rect,
@@ -850,7 +814,7 @@ void QPixmapStyle::drawProgressBarFill(const QStyleOption *option,
{
const QStyleOptionProgressBar *pbar =
qstyleoption_cast<const QStyleOptionProgressBar*>(option);
- const bool vertical = pbar->orientation == Qt::Vertical;
+ const bool vertical = !(pbar->state & QStyle::State_Horizontal);
const bool flip = (pbar->direction == Qt::RightToLeft) ^ pbar->invertedAppearance;
if (pbar->progress == pbar->maximum) {
@@ -1003,13 +967,13 @@ QSize QPixmapStyle::pushButtonSizeFromContents(const QStyleOption *option,
return d->computeSize(desc, w, h);
}
-QSize QPixmapStyle::lineEditSizeFromContents(const QStyleOption *,
+QSize QPixmapStyle::lineEditSizeFromContents(const QStyleOption *option,
const QSize &contentsSize, const QWidget *) const
{
Q_D(const QPixmapStyle);
const QPixmapStyleDescriptor &desc = d->descriptors.value(LE_Enabled);
- const int border = 2 * proxy()->pixelMetric(PM_DefaultFrameWidth);
+ const int border = 2 * proxy()->pixelMetric(PM_DefaultFrameWidth, option);
int w = contentsSize.width() + border + desc.margins.left() + desc.margins.right();
int h = contentsSize.height() + border + desc.margins.top() + desc.margins.bottom();
@@ -1026,7 +990,7 @@ QSize QPixmapStyle::progressBarSizeFromContents(const QStyleOption *option,
bool vertical = false;
if (const QStyleOptionProgressBar *pb =
qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- vertical = pb->orientation == Qt::Vertical;
+ vertical = !(pb->state & QStyle::State_Horizontal);
}
QSize result = QCommonStyle::sizeFromContents(CT_Slider, option, contentsSize, widget);
if (vertical) {
@@ -1205,10 +1169,10 @@ QPixmap QPixmapStylePrivate::getCachedPixmap(QPixmapStyle::ControlDescriptor con
{
Q_Q(const QPixmapStyle);
- const QString sizeString = QString::number(size.width()) % QLatin1Char('*')
+ const QString sizeString = QString::number(size.width()) % u'*'
% QString::number(size.height());
- const QString key = QLatin1String(q->metaObject()->className()) % QString::number(control)
- % QLatin1Char('@') % sizeString;
+ const QString key = QLatin1StringView(q->metaObject()->className()) % QString::number(control)
+ % u'@' % sizeString;
QPixmap result;
@@ -1230,3 +1194,5 @@ QSize QPixmapStylePrivate::computeSize(const QPixmapStyleDescriptor &desc, int w
}
QT_END_NAMESPACE
+
+#include "moc_qpixmapstyle_p.cpp"
diff --git a/src/widgets/styles/qpixmapstyle_p.h b/src/widgets/styles/qpixmapstyle_p.h
index d32631a527..62233add74 100644
--- a/src/widgets/styles/qpixmapstyle_p.h
+++ b/src/widgets/styles/qpixmapstyle_p.h
@@ -1,43 +1,7 @@
-/***************************************************************************
-**
-** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
-** Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2014 BlackBerry Limited. All rights reserved.
+// Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
+// 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 QPIXMAPSTYLE_H
#define QPIXMAPSTYLE_H
diff --git a/src/widgets/styles/qpixmapstyle_p_p.h b/src/widgets/styles/qpixmapstyle_p_p.h
index 481262d5c5..9e0495f788 100644
--- a/src/widgets/styles/qpixmapstyle_p_p.h
+++ b/src/widgets/styles/qpixmapstyle_p_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPIXMAPSTYLE_P_H
#define QPIXMAPSTYLE_P_H
diff --git a/src/widgets/styles/qproxystyle.cpp b/src/widgets/styles/qproxystyle.cpp
index cfaa5a2011..a85c40a329 100644
--- a/src/widgets/styles/qproxystyle.cpp
+++ b/src/widgets/styles/qproxystyle.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <qstyle.h>
#include <private/qproxystyle_p.h>
@@ -48,6 +12,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
\class QProxyStyle
@@ -72,6 +38,13 @@ QT_BEGIN_NAMESPACE
or system controlled styles. It would not work on a Mac, for
example, where menus are handled by the operating system.
+ When a proxy style should be set on a specific widget only, you have
+ to make sure to not set the proxy on the global application style which
+ is returned by QWidget::style(). You have to create a separate custom style
+ for the widget similar to:
+
+ \snippet code/src_gui_qproxystyle.cpp 2
+
\sa QStyle
*/
@@ -99,7 +72,7 @@ void QProxyStylePrivate::ensureBaseStyle() const
baseStyle = QStyleFactory::create(QApplicationPrivate::desktopStyleKey());
if (!baseStyle) // Fallback to windows style
- baseStyle = QStyleFactory::create(QLatin1String("windows"));
+ baseStyle = QStyleFactory::create("windows"_L1);
baseStyle->setProxy(const_cast<QProxyStyle*>(q));
baseStyle->setParent(const_cast<QProxyStyle*>(q)); // Take ownership
@@ -162,7 +135,7 @@ QStyle *QProxyStyle::baseStyle() const
Ownership of \a style is transferred to QProxyStyle.
- If style is zero, a desktop-dependant style will be
+ If style is \nullptr, a desktop-dependent style will be
assigned automatically.
*/
void QProxyStyle::setBaseStyle(QStyle *style)
@@ -376,8 +349,18 @@ void QProxyStyle::unpolish(QApplication *app)
bool QProxyStyle::event(QEvent *e)
{
Q_D (QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->event(e);
+
+ 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);
}
/*!
@@ -403,7 +386,7 @@ QIcon QProxyStyle::standardIcon(StandardPixmap standardIcon,
orientation specifies whether the controls are laid out side by side
or stacked vertically. The \a option parameter can be used to pass
extra information about the parent widget. The \a widget parameter
- is optional and can also be used if \a option is 0.
+ is optional and can also be used if \a option is \nullptr.
The default implementation returns -1.
diff --git a/src/widgets/styles/qproxystyle.h b/src/widgets/styles/qproxystyle.h
index c26d9abf59..7b3ec9a939 100644
--- a/src/widgets/styles/qproxystyle.h
+++ b/src/widgets/styles/qproxystyle.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPROXYSTYLE_H
#define QPROXYSTYLE_H
diff --git a/src/widgets/styles/qproxystyle_p.h b/src/widgets/styles/qproxystyle_p.h
index 2321f0fed0..6b686023a5 100644
--- a/src/widgets/styles/qproxystyle_p.h
+++ b/src/widgets/styles/qproxystyle_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPROXYSTYLE_P_H
#define QPROXYSTYLE_P_H
@@ -56,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 e462d0696b..60b2f51e95 100644
--- a/src/widgets/styles/qstyle.cpp
+++ b/src/widgets/styles/qstyle.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstyle.h"
#include "qapplication.h"
@@ -64,7 +28,7 @@ static int unpackControlTypes(QSizePolicy::ControlTypes controls, QSizePolicy::C
return 0;
// optimization: exactly one bit is set
- if ((controls & (controls - 1)) == 0) {
+ if (qPopulationCount(uint(controls)) == 1) {
array[0] = QSizePolicy::ControlType(uint(controls));
return 1;
}
@@ -91,7 +55,7 @@ static int unpackControlTypes(QSizePolicy::ControlTypes controls, QSizePolicy::C
look of the different platforms supported by Qt (QWindowsStyle,
QMacStyle, etc.). These styles are built into the
Qt GUI module, other styles can be made available using Qt's
- plugin mechansim.
+ plugin mechanism.
Most functions for drawing style elements take four arguments:
@@ -285,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.
@@ -372,7 +333,7 @@ static int unpackControlTypes(QSizePolicy::ControlTypes controls, QSizePolicy::C
We include a small example where we customize the drawing of item
backgrounds.
- \snippet customviewstyle.cpp 0
+ \snippet customviewstyle/customviewstyle.cpp 0
The primitive element PE_PanelItemViewItem is responsible for
painting the background of items, and is called from
@@ -388,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}
*/
@@ -412,6 +373,9 @@ QStyle::QStyle(QStylePrivate &dd)
{
Q_D(QStyle);
d->proxyStyle = this;
+ Q_STATIC_ASSERT_X(int(StandardPixmap::NStandardPixmap) ==
+ int(QPlatformTheme::StandardPixmap::NStandardPixmap),
+ "StandardPixmap in QPlatformTheme and QStyle out of sync");
}
/*!
@@ -422,6 +386,30 @@ QStyle::~QStyle()
}
/*!
+ Returns the name of the style.
+
+ This value can be used to create a style with QStyleFactory::create().
+
+ \sa QStyleFactory::create()
+ \since 6.1
+*/
+QString QStyle::name() const
+{
+ Q_D(const QStyle);
+ return d->name;
+}
+
+/*!
+ \internal
+ Set the style name
+*/
+void QStyle::setName(const QString &name)
+{
+ Q_D(QStyle);
+ d->name = name;
+}
+
+/*!
Initializes the appearance of the given \a widget.
This function is called for every widget at some point after it
@@ -549,8 +537,9 @@ QRect QStyle::itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pi
int x, y, w, h;
rect.getRect(&x, &y, &w, &h);
- const int pixmapWidth = pixmap.width()/pixmap.devicePixelRatio();
- const int pixmapHeight = pixmap.height()/pixmap.devicePixelRatio();
+ QSizeF pixmapSize = pixmap.deviceIndependentSize();
+ const int pixmapWidth = pixmapSize.width();
+ const int pixmapHeight = pixmapSize.height();
if ((alignment & Qt::AlignVCenter) == Qt::AlignVCenter)
y += h/2 - pixmapHeight/2;
@@ -627,7 +616,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
QRect aligned = alignedRect(QGuiApplication::layoutDirection(), QFlag(alignment), pixmap.size() / scale, rect);
QRect inter = aligned.intersected(rect);
- painter->drawPixmap(inter.x(), inter.y(), pixmap, inter.x() - aligned.x(), inter.y() - aligned.y(), inter.width() * scale, inter.height() *scale);
+ painter->drawPixmap(inter.x(), inter.y(), pixmap, inter.x() - aligned.x(), inter.y() - aligned.y(), qRound(inter.width() * scale), qRound(inter.height() *scale));
}
/*!
@@ -637,8 +626,6 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
primitive element is a common GUI element, such as a checkbox
indicator or button bevel.
- \omitvalue PE_IndicatorViewItemCheck
-
\value PE_PanelButtonCommand Button used to initiate an action, for
example, a QPushButton.
@@ -696,7 +683,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value PE_IndicatorToolBarSeparator The separator in a toolbar.
\value PE_PanelToolBar The panel for a toolbar.
\value PE_PanelTipLabel The panel for a tip label.
- \value PE_FrameTabBarBase The frame that is drawn for a tab bar, ususally drawn for a tab bar that isn't part of a tab widget.
+ \value PE_FrameTabBarBase The frame that is drawn for a tab bar, usually drawn for a tab bar that isn't part of a tab widget.
\value PE_IndicatorTabTear Deprecated. Use \l{PE_IndicatorTabTearLeft} instead.
\value PE_IndicatorTabTearLeft An indicator that a tab is partially scrolled out on the left side of the visible tab bar when there are many tabs.
\value PE_IndicatorTabTearRight An indicator that a tab is partially scrolled out on the right side of the visible tab bar when there are many tabs.
@@ -1011,6 +998,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SE_PushButtonFocusRect Area for the focus rect (usually
larger than the contents rect).
\value SE_PushButtonLayoutItem Area that counts for the parent layout.
+ \value SE_PushButtonBevel [since 5.15] Area used for the bevel of the button.
\value SE_CheckBoxIndicator Area for the state indicator (e.g., check mark).
\value SE_CheckBoxContents Area for the label (text or pixmap).
@@ -1038,8 +1026,6 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SE_ProgressBarLabel Area for the text label.
\value SE_ProgressBarLayoutItem Area that counts for the parent layout.
- \omitvalue SE_ViewItemCheckIndicator
-
\value SE_FrameContents Area for a frame's contents.
\value SE_ShapedFrameContents Area for a frame's contents using the shape in QStyleOptionFrame; see QFrame
\value SE_FrameLayoutItem Area that counts for the parent layout.
@@ -1073,8 +1059,6 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SE_TreeViewDisclosureItem Area for the actual disclosure item in a tree branch.
- \value SE_DialogButtonBoxLayoutItem Area that counts for the parent layout.
-
\value SE_GroupBoxLayoutItem Area that counts for the parent layout.
\value SE_CustomBase Base value for custom sub-elements.
@@ -1119,6 +1103,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\header \li Sub Element \li QStyleOption Subclass
\row \li \l SE_PushButtonContents \li \l QStyleOptionButton
\row \li \l SE_PushButtonFocusRect \li \l QStyleOptionButton
+ \row \li \l SE_PushButtonBevel \li \l QStyleOptionButton
\row \li \l SE_CheckBoxIndicator \li \l QStyleOptionButton
\row \li \l SE_CheckBoxContents \li \l QStyleOptionButton
\row \li \l SE_CheckBoxFocusRect \li \l QStyleOptionButton
@@ -1357,9 +1342,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value PM_SpinBoxFrameWidth Frame width of a spin box, defaults to PM_DefaultFrameWidth.
\value PM_ComboBoxFrameWidth Frame width of a combo box, defaults to PM_DefaultFrameWidth.
- \value PM_MDIFrameWidth Obsolete. Use PM_MdiSubWindowFrameWidth instead.
\value PM_MdiSubWindowFrameWidth Frame width of an MDI window.
- \value PM_MDIMinimizedWidth Obsolete. Use PM_MdiSubWindowMinimizedWidth instead.
\value PM_MdiSubWindowMinimizedWidth Width of a minimized MDI window.
\value PM_LayoutLeftMargin Default \l{QLayout::setContentsMargins()}{left margin} for a
@@ -1485,36 +1468,22 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value PM_SubMenuOverlap The horizontal overlap between a submenu and its parent.
- \value PM_TreeViewIndentation The indentation of items in a tree view.
- This enum value has been introduced in Qt 5.4.
+ \value [since 5.4] PM_TreeViewIndentation The indentation of items in a tree view.
\value PM_HeaderDefaultSectionSizeHorizontal The default size of sections
in a horizontal header. This enum value has been introduced in Qt 5.5.
\value PM_HeaderDefaultSectionSizeVertical The default size of sections
in a vertical header. This enum value has been introduced in Qt 5.5.
- \value PM_TitleBarButtonIconSize The size of button icons on a title bar.
- This enum value has been introduced in Qt 5.8.
- \value PM_TitleBarButtonSize The size of buttons on a title bar.
- This enum value has been introduced in Qt 5.8.
-
- \value PM_CustomBase Base value for custom pixel metrics. Custom
- values must be greater than this value.
+ \value [since 5.8] PM_TitleBarButtonIconSize The size of button icons on a title bar.
+ \value [since 5.8] PM_TitleBarButtonSize The size of buttons on a title bar.
- The following values are obsolete:
+ \value [since 6.2] PM_LineEditIconSize The default size for icons in a line edit.
- \value PM_DefaultTopLevelMargin Use PM_LayoutLeftMargin,
- PM_LayoutTopMargin,
- PM_LayoutRightMargin, and
- PM_LayoutBottomMargin instead.
- \value PM_DefaultChildMargin Use PM_LayoutLeftMargin,
- PM_LayoutTopMargin,
- PM_LayoutRightMargin, and
- PM_LayoutBottomMargin instead.
- \value PM_DefaultLayoutSpacing Use PM_LayoutHorizontalSpacing
- and PM_LayoutVerticalSpacing
- instead.
+ \value [since 6.3] PM_LineEditIconMargin The margin around icons in a line edit.
+ \value PM_CustomBase Base value for custom pixel metrics. Custom
+ values must be greater than this value.
\sa pixelMetric()
*/
@@ -1525,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:
@@ -1715,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.
@@ -1793,7 +1761,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
cause a list view expansion to be selected.
\value SH_TabBar_PreferNoArrows Whether a tab bar should suggest a size
- to prevent scoll arrows.
+ to prevent scroll arrows.
\value SH_ComboBox_Popup Allows popups as a combobox drop-down
menu.
@@ -1805,9 +1773,6 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SH_TitleBar_NoBorder The title bar has no border.
- \value SH_ScrollBar_StopMouseOverSlider Obsolete. Use
- SH_Slider_StopMouseOverSlider instead.
-
\value SH_Slider_StopMouseOverSlider Stops auto-repeat when
the slider reaches the mouse position.
@@ -1838,9 +1803,6 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SH_UnderlineShortcut Whether shortcuts are underlined.
- \value SH_SpellCheckUnderlineStyle Obsolete. Use SpellCheckUnderlineStyle
- hint in QPlatformTheme instead.
-
\value SH_SpinBox_AnimateButton Animate a click when up or down is
pressed in a spin box.
\value SH_SpinBox_KeyPressAutoRepeatRate Auto-repeat interval for
@@ -1849,6 +1811,9 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
spinbox mouse clicks.
\value SH_SpinBox_ClickAutoRepeatThreshold Auto-repeat threshold for
spinbox mouse clicks.
+ \value [since 6.3] SH_SpinBox_SelectOnStep Whether changing the value using
+ the buttons or up/down keys automatically selects the text.
+
\value SH_ToolTipLabel_Opacity An integer indicating the opacity for
the tip label, 0 is completely transparent, 255 is completely
opaque.
@@ -2008,6 +1973,16 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
disables this feature.
This enum value has been introduced in Qt 5.12.
+ \value SH_TabBar_AllowWheelScrolling
+ Determines if the mouse wheel can be used to cycle through the tabs
+ of a QTabBar.
+ This enum value has been introduced in Qt 6.1.
+
+ \value SH_Table_AlwaysDrawLeftTopGridLines
+ Determines if the far left and top grid lines are drawn in a table or
+ not when the header is hidden. Defaults to false.
+ This enum value has been introduced in Qt 6.3.
+
\sa styleHint()
*/
@@ -2099,21 +2074,16 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SP_MediaSeekBackward Icon indicating that media should seek backward.
\value SP_MediaVolume Icon indicating a volume control.
\value SP_MediaVolumeMuted Icon indicating a muted volume control.
- \value SP_LineEditClearButton Icon for a standard clear button in a QLineEdit. This enum value was added in Qt 5.2.
- \value SP_DialogYesToAllButton Icon for a standard YesToAll button in a QDialogButtonBox.
- This enum value was added in Qt 5.14.
- \value SP_DialogNoToAllButton Icon for a standard NoToAll button in a QDialogButtonBox.
- This enum value was added in Qt 5.14.
- \value SP_DialogSaveAllButton Icon for a standard SaveAll button in a QDialogButtonBox.
- This enum value was added in Qt 5.14.
- \value SP_DialogAbortButton Icon for a standard Abort button in a QDialogButtonBox.
- This enum value was added in Qt 5.14.
- \value SP_DialogRetryButton Icon for a standard Retry button in a QDialogButtonBox.
- This enum value was added in Qt 5.14.
- \value SP_DialogIgnoreButton Icon for a standard Ignore button in a QDialogButtonBox.
- This enum value was added in Qt 5.14.
- \value SP_RestoreDefaultsButton Icon for a standard RestoreDefaults button in a QDialogButtonBox.
- This enum value was added in Qt 5.14.
+ \value [since 5.2] SP_LineEditClearButton Icon for a standard clear button in a QLineEdit.
+ \value [since 5.14] SP_DialogYesToAllButton Icon for a standard YesToAll button in a QDialogButtonBox.
+ \value [since 5.14] SP_DialogNoToAllButton Icon for a standard NoToAll button in a QDialogButtonBox.
+ \value [since 5.14] SP_DialogSaveAllButton Icon for a standard SaveAll button in a QDialogButtonBox.
+ \value [since 5.14] SP_DialogAbortButton Icon for a standard Abort button in a QDialogButtonBox.
+ \value [since 5.14] SP_DialogRetryButton Icon for a standard Retry button in a QDialogButtonBox.
+ \value [since 5.14] SP_DialogIgnoreButton Icon for a standard Ignore button in a QDialogButtonBox.
+ \value [since 5.14] SP_RestoreDefaultsButton Icon for a standard RestoreDefaults button in a QDialogButtonBox.
+ \value [since 6.3] SP_TabCloseButton Icon for the close button in the tab of a QTabBar.
+ \omitvalue NStandardPixmap
\value SP_CustomBase Base value for custom standard pixmaps;
custom values must be greater than this value.
@@ -2140,7 +2110,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
/*!
\fn QPixmap QStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option, const QWidget *widget) const
- \obsolete
+ \deprecated
Returns a pixmap for the given \a standardPixmap.
A standard pixmap is a pixmap that can follow some existing GUI
@@ -2251,13 +2221,15 @@ Qt::Alignment QStyle::visualAlignment(Qt::LayoutDirection direction, Qt::Alignme
int QStyle::sliderPositionFromValue(int min, int max, int logicalValue, int span, bool upsideDown)
{
- if (span <= 0 || logicalValue < min || max <= min)
+ if (span <= 0 || max <= min)
return 0;
+ if (logicalValue < min)
+ return upsideDown ? span : 0;
if (logicalValue > max)
- return upsideDown ? span : min;
+ return upsideDown ? 0 : span;
- uint range = max - min;
- uint p = upsideDown ? max - logicalValue : logicalValue - min;
+ const uint range = qint64(max) - min;
+ const uint p = upsideDown ? qint64(max) - logicalValue : qint64(logicalValue) - min;
if (range > (uint)INT_MAX/4096) {
double dpos = (double(p))/(double(range)/span);
@@ -2299,15 +2271,15 @@ int QStyle::sliderValueFromPosition(int min, int max, int pos, int span, bool up
if (pos >= span)
return upsideDown ? min : max;
- uint range = max - min;
+ const qint64 range = qint64(max) - min;
if ((uint)span > range) {
- int tmp = (2 * pos * range + span) / (2 * span);
+ const int tmp = (2 * range * pos + span) / (qint64(2) * span);
return upsideDown ? max - tmp : tmp + min;
} else {
- uint div = range / span;
- uint mod = range % span;
- int tmp = pos * div + (2 * pos * mod + span) / (2 * span);
+ const qint64 div = range / span;
+ const qint64 mod = range % span;
+ const int tmp = pos * div + (2 * mod * pos + span) / (qint64(2) * span);
return upsideDown ? max - tmp : tmp + min;
}
// equiv. to min + (pos*range)/span + 0.5
@@ -2344,8 +2316,8 @@ QPalette QStyle::standardPalette() const
/*!
\since 4.1
- \fn QIcon QStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option = 0,
- const QWidget *widget = 0) const = 0;
+ \fn QIcon QStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option = nullptr,
+ const QWidget *widget = nullptr) const = 0;
Returns an icon for the given \a standardIcon.
@@ -2361,14 +2333,14 @@ QPalette QStyle::standardPalette() const
\fn int QStyle::layoutSpacing(QSizePolicy::ControlType control1,
QSizePolicy::ControlType control2, Qt::Orientation orientation,
- const QStyleOption *option = 0, const QWidget *widget = 0) const
+ const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const
Returns the spacing that should be used between \a control1 and
\a control2 in a layout. \a orientation specifies whether the
controls are laid out side by side or stacked vertically. The \a
option parameter can be used to pass extra information about the
parent widget. The \a widget parameter is optional and can also
- be used if \a option is 0.
+ be used if \a option is \nullptr.
This function is called by the layout system. It is used only if
PM_LayoutHorizontalSpacing or PM_LayoutVerticalSpacing returns a
@@ -2385,7 +2357,7 @@ QPalette QStyle::standardPalette() const
controls are laid out side by side or stacked vertically. The \a
option parameter can be used to pass extra information about the
parent widget. The \a widget parameter is optional and can also
- be used if \a option is 0.
+ be used if \a option is \nullptr.
\a controls1 and \a controls2 are OR-combination of zero or more
\l{QSizePolicy::ControlTypes}{control types}.
@@ -2415,25 +2387,6 @@ int QStyle::combinedLayoutSpacing(QSizePolicy::ControlTypes controls1,
return result;
}
-// ### Qt 6: Remove in favor of template<class T> QDebug operator<<(QDebug, const QFlags<T> &).
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
-QT_BEGIN_INCLUDE_NAMESPACE
-# include <QDebug>
-QT_END_INCLUDE_NAMESPACE
-
-# if !defined(QT_NO_DEBUG_STREAM)
-QDebug operator<<(QDebug debug, QStyle::State state)
-{
-# if !defined(QT_NO_DEBUG)
- return operator<< <QStyle::StateFlag>(debug, state);
-# else
- Q_UNUSED(state);
- return debug;
-# endif
-}
-# endif // !QT_NO_DEBUG_STREAM
-#endif // QT_VERSION < QT_VERSION_CHECK(6,0,0)
-
/*!
\since 4.6
@@ -2447,17 +2400,19 @@ QDebug operator<<(QDebug debug, QStyle::State state)
const QStyle * QStyle::proxy() const
{
Q_D(const QStyle);
- return d->proxyStyle;
+ return d->proxyStyle == this ? this : d->proxyStyle->proxy();
}
/* \internal
This function sets the base style that style calls will be
- redirected to. Note that ownership is not transferred.
+ redirected to. Note that ownership is not transferred. \a style
+ must be a valid pointer (not nullptr).
*/
void QStyle::setProxy(QStyle *style)
{
Q_D(QStyle);
+ Q_ASSERT(style);
d->proxyStyle = style;
}
diff --git a/src/widgets/styles/qstyle.h b/src/widgets/styles/qstyle.h
index b51bcbe8d6..198aea9557 100644
--- a/src/widgets/styles/qstyle.h
+++ b/src/widgets/styles/qstyle.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTYLE_H
#define QSTYLE_H
@@ -73,6 +37,8 @@ public:
QStyle();
virtual ~QStyle();
+ QString name() const;
+
virtual void polish(QWidget *widget);
virtual void unpolish(QWidget *widget);
@@ -185,7 +151,7 @@ public:
PE_IndicatorItemViewItemDrop,
PE_PanelItemViewItem,
- PE_PanelItemViewRow, // ### Qt 6: remove
+ PE_PanelItemViewRow,
PE_PanelStatusBar,
@@ -307,9 +273,6 @@ public:
SE_TabWidgetRightCorner,
SE_ItemViewItemCheckIndicator,
-#if QT_DEPRECATED_SINCE(5, 13) // ### Qt 6: remove
- SE_ViewItemCheckIndicator Q_DECL_ENUMERATOR_DEPRECATED = SE_ItemViewItemCheckIndicator,
-#endif
SE_TabBarTearIndicator,
SE_TabBarTearIndicatorLeft = SE_TabBarTearIndicator,
@@ -326,7 +289,6 @@ public:
SE_CheckBoxLayoutItem,
SE_ComboBoxLayoutItem,
SE_DateTimeEditLayoutItem,
- SE_DialogButtonBoxLayoutItem, // ### Qt 6: remove
SE_LabelLayoutItem,
SE_ProgressBarLayoutItem,
SE_PushButtonLayoutItem,
@@ -355,6 +317,8 @@ public:
SE_TabBarScrollRightButton,
SE_TabBarTearIndicatorRight,
+ SE_PushButtonBevel,
+
// do not add any values below/greater than this
SE_CustomBase = 0xf0000000
};
@@ -500,16 +464,14 @@ 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,
-#if QT_DEPRECATED_SINCE(5, 13) // ### Qt 6: remove
- PM_MDIFrameWidth Q_DECL_ENUMERATOR_DEPRECATED = PM_MdiSubWindowFrameWidth,
- PM_MDIMinimizedWidth Q_DECL_ENUMERATOR_DEPRECATED = PM_MdiSubWindowMinimizedWidth,
-#endif
PM_HeaderMargin,
PM_HeaderMarkSize,
@@ -527,10 +489,6 @@ public:
PM_SpinBoxSliderHeight,
- PM_DefaultTopLevelMargin, // ### Qt 6: remove
- PM_DefaultChildMargin, // ### Qt 6: remove
- PM_DefaultLayoutSpacing, // ### Qt 6: remove
-
PM_ToolBarIconSize,
PM_ListViewIconSize,
PM_IconViewIconSize,
@@ -575,6 +533,8 @@ public:
PM_TitleBarButtonIconSize,
PM_TitleBarButtonSize,
+ PM_LineEditIconSize,
+ PM_LineEditIconMargin,
// do not add any values below/greater than this
PM_CustomBase = 0xf0000000
};
@@ -650,9 +610,6 @@ public:
SH_ComboBox_Popup,
SH_TitleBar_NoBorder,
SH_Slider_StopMouseOverSlider,
-#if QT_DEPRECATED_SINCE(5, 13) // ### Qt 6: remove
- SH_ScrollBar_StopMouseOverSlider Q_DECL_ENUMERATOR_DEPRECATED = SH_Slider_StopMouseOverSlider,
-#endif
SH_BlinkCursorWhenTextSelected,
SH_RichText_FullWidthSelection,
SH_Menu_Scrollable,
@@ -697,7 +654,6 @@ public:
SH_ComboBox_PopupFrameStyle,
SH_MessageBox_TextInteractionFlags,
SH_DialogButtonBox_ButtonsHaveIcons,
- SH_SpellCheckUnderlineStyle,
SH_MessageBox_CenterButtons,
SH_Menu_SelectionWrap,
SH_ItemView_MovementWithoutUpdatingSelection,
@@ -745,6 +701,9 @@ public:
SH_ComboBox_AllowWheelScrolling,
SH_SpinBox_ButtonsInsideFrame,
SH_SpinBox_StepModifier,
+ SH_TabBar_AllowWheelScrolling,
+ SH_Table_AlwaysDrawLeftTopGridLines,
+ SH_SpinBox_SelectOnStep,
// Add new style hint values here
SH_CustomBase = 0xf0000000
@@ -833,6 +792,8 @@ public:
SP_DialogRetryButton,
SP_DialogIgnoreButton,
SP_RestoreDefaultsButton,
+ SP_TabCloseButton,
+ NStandardPixmap, // assertion value for sync with QPlatformTheme::StandardPixmap
// do not add any values below/greater than this
SP_CustomBase = 0xf0000000
};
@@ -869,25 +830,22 @@ public:
const QStyle * proxy() const;
private:
+ void setName(const QString &name);
+
+private:
Q_DISABLE_COPY(QStyle)
friend class QWidget;
friend class QWidgetPrivate;
friend class QApplication;
friend class QProxyStyle;
friend class QProxyStylePrivate;
+ friend class QStyleFactory;
void setProxy(QStyle *style);
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QStyle::State)
Q_DECLARE_OPERATORS_FOR_FLAGS(QStyle::SubControls)
-#if !defined(QT_NO_DEBUG_STREAM)
-// ### Qt 6: Remove in favor of template<class T> QDebug operator<<(QDebug, const QFlags<T> &).
-# if QT_VERSION < QT_VERSION_CHECK(6,0,0)
-Q_WIDGETS_EXPORT QDebug operator<<(QDebug debug, QStyle::State state);
-# endif
-#endif
-
QT_END_NAMESPACE
#endif // QSTYLE_H
diff --git a/src/widgets/styles/qstyle.qrc b/src/widgets/styles/qstyle.qrc
deleted file mode 100644
index d3511ee754..0000000000
--- a/src/widgets/styles/qstyle.qrc
+++ /dev/null
@@ -1,176 +0,0 @@
-<RCC>
- <qresource prefix="/qt-project.org/styles/commonstyle">
- <file>images/cleartext-16.png</file>
- <file>images/cleartext-32.png</file>
- <file>images/filelink-16.png</file>
- <file>images/filelink-32.png</file>
- <file>images/filelink-128.png</file>
- <file>images/file-16.png</file>
- <file>images/file-32.png</file>
- <file>images/file-128.png</file>
- <file>images/newdirectory-16.png</file>
- <file>images/newdirectory-32.png</file>
- <file>images/newdirectory-128.png</file>
- <file>images/parentdir-16.png</file>
- <file>images/parentdir-32.png</file>
- <file>images/parentdir-128.png</file>
- <file>images/dvd-16.png</file>
- <file>images/dvd-32.png</file>
- <file>images/dvd-128.png</file>
- <file>images/cdr-16.png</file>
- <file>images/cdr-32.png</file>
- <file>images/cdr-128.png</file>
- <file>images/floppy-16.png</file>
- <file>images/floppy-32.png</file>
- <file>images/floppy-128.png</file>
- <file>images/harddrive-16.png</file>
- <file>images/harddrive-32.png</file>
- <file>images/harddrive-128.png</file>
- <file>images/trash-16.png</file>
- <file>images/trash-32.png</file>
- <file>images/trash-128.png</file>
- <file>images/networkdrive-16.png</file>
- <file>images/networkdrive-32.png</file>
- <file>images/networkdrive-128.png</file>
- <file>images/computer-16.png</file>
- <file>images/computer-32.png</file>
- <file>images/desktop-16.png</file>
- <file>images/desktop-32.png</file>
- <file>images/dirclosed-16.png</file>
- <file>images/dirclosed-32.png</file>
- <file>images/dirclosed-128.png</file>
- <file>images/dirlink-16.png</file>
- <file>images/dirlink-32.png</file>
- <file>images/dirlink-128.png</file>
- <file>images/diropen-16.png</file>
- <file>images/diropen-32.png</file>
- <file>images/diropen-128.png</file>
- <file>images/left-16.png</file>
- <file>images/left-32.png</file>
- <file>images/left-128.png</file>
- <file>images/right-16.png</file>
- <file>images/right-32.png</file>
- <file>images/right-128.png</file>
- <file>images/up-16.png</file>
- <file>images/up-32.png</file>
- <file>images/up-128.png</file>
- <file>images/down-16.png</file>
- <file>images/down-32.png</file>
- <file>images/down-128.png</file>
- <file>images/filecontents-16.png</file>
- <file>images/filecontents-32.png</file>
- <file>images/filecontents-128.png</file>
- <file>images/fileinfo-16.png</file>
- <file>images/fileinfo-32.png</file>
- <file>images/fileinfo-128.png</file>
- <file>images/viewdetailed-16.png</file>
- <file>images/viewdetailed-32.png</file>
- <file>images/viewdetailed-128.png</file>
- <file>images/viewlist-16.png</file>
- <file>images/viewlist-32.png</file>
- <file>images/viewlist-128.png</file>
- <file>images/fontbitmap-16.png</file>
- <file>images/fonttruetype-16.png</file>
- <file>images/standardbutton-apply-128.png</file>
- <file>images/standardbutton-apply-16.png</file>
- <file>images/standardbutton-apply-32.png</file>
- <file>images/standardbutton-cancel-128.png</file>
- <file>images/standardbutton-cancel-16.png</file>
- <file>images/standardbutton-cancel-32.png</file>
- <file>images/standardbutton-clear-128.png</file>
- <file>images/standardbutton-clear-16.png</file>
- <file>images/standardbutton-clear-32.png</file>
- <file>images/standardbutton-close-128.png</file>
- <file>images/standardbutton-close-16.png</file>
- <file>images/standardbutton-close-32.png</file>
- <file>images/standardbutton-delete-128.png</file>
- <file>images/standardbutton-delete-16.png</file>
- <file>images/standardbutton-delete-32.png</file>
- <file>images/standardbutton-help-128.png</file>
- <file>images/standardbutton-help-16.png</file>
- <file>images/standardbutton-help-32.png</file>
- <file>images/standardbutton-no-128.png</file>
- <file>images/standardbutton-no-16.png</file>
- <file>images/standardbutton-no-32.png</file>
- <file>images/standardbutton-ok-128.png</file>
- <file>images/standardbutton-ok-16.png</file>
- <file>images/standardbutton-ok-32.png</file>
- <file>images/standardbutton-open-128.png</file>
- <file>images/standardbutton-open-16.png</file>
- <file>images/standardbutton-open-32.png</file>
- <file>images/standardbutton-save-128.png</file>
- <file>images/standardbutton-save-16.png</file>
- <file>images/standardbutton-save-32.png</file>
- <file>images/standardbutton-yes-128.png</file>
- <file>images/standardbutton-yes-16.png</file>
- <file>images/standardbutton-yes-32.png</file>
- <file>images/standardbutton-closetab-16.png</file>
- <file>images/standardbutton-closetab-down-16.png</file>
- <file>images/standardbutton-closetab-hover-16.png</file>
- <file>images/refresh-24.png</file>
- <file>images/refresh-32.png</file>
- <file>images/stop-24.png</file>
- <file>images/stop-32.png</file>
- <file>images/media-stop-16.png</file>
- <file>images/media-stop-32.png</file>
- <file>images/media-play-16.png</file>
- <file>images/media-play-32.png</file>
- <file>images/media-pause-16.png</file>
- <file>images/media-pause-32.png</file>
- <file>images/media-seek-forward-16.png</file>
- <file>images/media-seek-forward-32.png</file>
- <file>images/media-seek-backward-16.png</file>
- <file>images/media-seek-backward-32.png</file>
- <file>images/media-skip-forward-16.png</file>
- <file>images/media-skip-forward-32.png</file>
- <file>images/media-skip-backward-16.png</file>
- <file>images/media-skip-backward-32.png</file>
- <file>images/media-volume-16.png</file>
- <file>images/media-volume-muted-16.png</file>
- <file>images/fusion_groupbox.png</file>
- <file>images/closedock-10.png</file>
- <file>images/closedock-16.png</file>
- <file>images/closedock-20.png</file>
- <file>images/closedock-32.png</file>
- <file>images/closedock-48.png</file>
- <file>images/closedock-64.png</file>
- <file>images/normalizedockup-10.png</file>
- <file>images/normalizedockup-16.png</file>
- <file>images/normalizedockup-20.png</file>
- <file>images/normalizedockup-32.png</file>
- <file>images/normalizedockup-48.png</file>
- <file>images/normalizedockup-64.png</file>
- <file>images/toolbar-ext-h-8.png</file>
- <file>images/toolbar-ext-h-16.png</file>
- <file>images/toolbar-ext-h-32.png</file>
- <file>images/toolbar-ext-h-rtl-8.png</file>
- <file>images/toolbar-ext-h-rtl-16.png</file>
- <file>images/toolbar-ext-h-rtl-32.png</file>
- <file>images/toolbar-ext-v-5.png</file>
- <file>images/toolbar-ext-v-10.png</file>
- <file>images/toolbar-ext-v-20.png</file>
- <file>images/titlebar-contexthelp-16.png</file>
- <file>images/titlebar-contexthelp-32.png</file>
- <file>images/titlebar-contexthelp-48.png</file>
- <file>images/titlebar-max-16.png</file>
- <file>images/titlebar-max-32.png</file>
- <file>images/titlebar-max-48.png</file>
- <file>images/titlebar-min-16.png</file>
- <file>images/titlebar-min-32.png</file>
- <file>images/titlebar-min-48.png</file>
- <file>images/titlebar-shade-16.png</file>
- <file>images/titlebar-shade-32.png</file>
- <file>images/titlebar-shade-48.png</file>
- <file>images/titlebar-unshade-16.png</file>
- <file>images/titlebar-unshade-32.png</file>
- <file>images/titlebar-unshade-48.png</file>
- </qresource>
- <qresource prefix="/qt-project.org/styles/macstyle">
- <file alias="images/closedock-16.png">images/closedock-macstyle-16.png</file>
- <file alias="images/closedock-down-16.png">images/closedock-down-macstyle-16.png</file>
- <file alias="images/dockdock-16.png">images/dockdock-macstyle-16.png</file>
- <file alias="images/dockdock-down-16.png">images/dockdock-down-macstyle-16.png</file>
- <file alias="images/toolbar-ext.png">images/toolbar-ext-macstyle.png</file>
- <file alias="images/toolbar-ext@2x.png">images/toolbar-ext-macstyle@2x.png</file>
- </qresource>
-</RCC>
diff --git a/src/widgets/styles/qstyle_p.h b/src/widgets/styles/qstyle_p.h
index 7942cafaf7..c4daa09c11 100644
--- a/src/widgets/styles/qstyle_p.h
+++ b/src/widgets/styles/qstyle_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTYLE_P_H
#define QSTYLE_P_H
@@ -72,6 +36,7 @@ public:
mutable int layoutSpacingIndex;
QStyle *proxyStyle;
+ QString name;
};
inline QImage styleCacheImage(const QSize &size)
@@ -95,9 +60,9 @@ inline QPixmap styleCachePixmap(const QSize &size)
QPixmap internalPixmapCache; \
QImage imageCache; \
QPainter *p = painter; \
- QString unique = QStyleHelper::uniqueName((a), option, option->rect.size()); \
+ const QString unique = QStyleHelper::uniqueName((a), option, option->rect.size()); \
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); \
diff --git a/src/widgets/styles/qstyleanimation.cpp b/src/widgets/styles/qstyleanimation.cpp
index b9202eae69..8e71bb4fae 100644
--- a/src/widgets/styles/qstyleanimation.cpp
+++ b/src/widgets/styles/qstyleanimation.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 "qstyleanimation_p.h"
@@ -87,7 +51,7 @@ QTime QStyleAnimation::startTime() const
return _startTime;
}
-void QStyleAnimation::setStartTime(const QTime &time)
+void QStyleAnimation::setStartTime(QTime time)
{
_startTime = time;
}
@@ -122,9 +86,9 @@ bool QStyleAnimation::isUpdateNeeded() const
return currentTime() > _delay;
}
-void QStyleAnimation::updateCurrentTime(int)
+void QStyleAnimation::updateCurrentTime(int time)
{
- if (++_skip >= _fps) {
+ if (++_skip >= _fps || time >= duration()) {
_skip = 0;
if (target() && isUpdateNeeded())
updateTarget();
@@ -266,7 +230,7 @@ static QImage blendedImage(const QImage &start, const QImage &end, float alpha)
const int ia = 256 - a;
const int sw = start.width();
const int sh = start.height();
- const int bpl = start.bytesPerLine();
+ const qsizetype bpl = start.bytesPerLine();
switch (start.depth()) {
case 32:
{
@@ -292,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/qstyleanimation_p.h b/src/widgets/styles/qstyleanimation_p.h
index d28fc6ebab..fc05607f96 100644
--- a/src/widgets/styles/qstyleanimation_p.h
+++ b/src/widgets/styles/qstyleanimation_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QSTYLEANIMATION_P_H
#define QSTYLEANIMATION_P_H
@@ -77,7 +41,7 @@ public:
void setDelay(int delay);
QTime startTime() const;
- void setStartTime(const QTime &time);
+ void setStartTime(QTime time);
enum FrameRate {
DefaultFps,
diff --git a/src/widgets/styles/qstylefactory.cpp b/src/widgets/styles/qstylefactory.cpp
index 2c4f6f83a1..fc87b2b0c8 100644
--- a/src/widgets/styles/qstylefactory.cpp
+++ b/src/widgets/styles/qstylefactory.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstylefactory.h"
#include "qstyleplugin.h"
@@ -50,8 +14,10 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
- (QStyleFactoryInterface_iid, QLatin1String("/styles"), Qt::CaseInsensitive))
+ (QStyleFactoryInterface_iid, "/styles"_L1, Qt::CaseInsensitive))
/*!
\class QStyleFactory
@@ -69,7 +35,7 @@ Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
The valid keys can be retrieved using the keys()
function. Typically they include "windows" and "fusion".
Depending on the platform, "windowsvista"
- and "macintosh" may be available.
+ and "macos" may be available.
Note that keys are case insensitive.
\sa QStyle
@@ -91,20 +57,28 @@ QStyle *QStyleFactory::create(const QString& key)
QStyle *ret = nullptr;
QString style = key.toLower();
#if QT_CONFIG(style_windows)
- if (style == QLatin1String("windows"))
+ if (style == "windows"_L1)
ret = new QWindowsStyle;
else
#endif
#if QT_CONFIG(style_fusion)
- if (style == QLatin1String("fusion"))
+ if (style == "fusion"_L1)
ret = new QFusionStyle;
else
#endif
+#if defined(Q_OS_MACOS) && QT_DEPRECATED_SINCE(6, 0)
+ if (style == "macintosh"_L1) {
+ qWarning() << "The style key 'macintosh' is deprecated. Please use 'macos' instead.";
+ style = QStringLiteral("macos");
+ } else
+#endif
{ } // Keep these here - they make the #ifdefery above work
if (!ret)
ret = qLoadPlugin<QStyle, QStylePlugin>(loader(), style);
- if(ret)
+ if (ret) {
ret->setObjectName(style);
+ ret->setName(style);
+ }
return ret;
}
@@ -124,12 +98,12 @@ QStringList QStyleFactory::keys()
for (PluginKeyMap::const_iterator it = keyMap.constBegin(); it != cend; ++it)
list.append(it.value());
#if QT_CONFIG(style_windows)
- if (!list.contains(QLatin1String("Windows")))
- list << QLatin1String("Windows");
+ if (!list.contains("Windows"_L1))
+ list << "Windows"_L1;
#endif
#if QT_CONFIG(style_fusion)
- if (!list.contains(QLatin1String("Fusion")))
- list << QLatin1String("Fusion");
+ if (!list.contains("Fusion"_L1))
+ list << "Fusion"_L1;
#endif
return list;
}
diff --git a/src/widgets/styles/qstylefactory.h b/src/widgets/styles/qstylefactory.h
index 50c3750b6c..ccaee95d44 100644
--- a/src/widgets/styles/qstylefactory.h
+++ b/src/widgets/styles/qstylefactory.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTYLEFACTORY_H
#define QSTYLEFACTORY_H
diff --git a/src/widgets/styles/qstylehelper.cpp b/src/widgets/styles/qstylehelper.cpp
index 61a59b03c1..1084761d30 100644
--- a/src/widgets/styles/qstylehelper.cpp
+++ b/src/widgets/styles/qstylehelper.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <qstyleoption.h>
#include <qpainter.h>
@@ -61,8 +25,18 @@ Q_GUI_EXPORT int qt_defaultDpiX();
namespace QStyleHelper {
+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)
{
+ if (!usePixmapCache(option))
+ return {};
+
const QStyleOptionComplex *complexOption = qstyleoption_cast<const QStyleOptionComplex *>(option);
QString tmp = key % HexString<uint>(option->state)
% HexString<uint>(option->direction)
@@ -75,7 +49,7 @@ QString uniqueName(const QString &key, const QStyleOption *option, const QSize &
if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
tmp = tmp % HexString<uint>(spinBox->buttonSymbols)
% HexString<uint>(spinBox->stepEnabled)
- % QLatin1Char(spinBox->frame ? '1' : '0'); ;
+ % QChar(spinBox->frame ? u'1' : u'0');
}
#endif // QT_CONFIG(spinbox)
@@ -101,7 +75,13 @@ Q_WIDGETS_EXPORT qreal dpi(const QStyleOption *option)
if (option)
return option->fontMetrics.fontDpi();
+ // Fall back to historical Qt behavior: hardocded 72 DPI on mac,
+ // primary screen DPI on other platforms.
+#ifdef Q_OS_DARWIN
return qstyleBaseDpi;
+#else
+ return qt_defaultDpiX();
+#endif
}
Q_WIDGETS_EXPORT qreal dpiScaled(qreal value, qreal dpi)
@@ -119,7 +99,7 @@ Q_WIDGETS_EXPORT qreal dpiScaled(qreal value, const QStyleOption *option)
return dpiScaled(value, dpi(option));
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
bool isInstanceOf(QObject *obj, QAccessible::Role role)
{
bool match = false;
@@ -140,7 +120,7 @@ bool hasAncestor(QObject *obj, QAccessible::Role role)
}
return found;
}
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
#if QT_CONFIG(dial)
@@ -175,7 +155,7 @@ static QPointF calcRadialPos(const QStyleOptionSlider *dial, qreal offset)
qreal len = r - QStyleHelper::calcBigLineSize(r) - 3;
qreal back = offset * len;
QPointF pos(QPointF(xc + back * qCos(a), yc - back * qSin(a)));
- return pos;
+ return pos + dial->rect.topLeft();
}
qreal angle(const QPointF &p1, const QPointF &p2)
@@ -248,7 +228,7 @@ QPolygonF calcLines(const QStyleOptionSlider *dial)
poly[2 * i + 1] = QPointF(xc + (r - 1) * c, yc -(r - 1) * s);
}
}
- return poly;
+ return poly.translated(dial->rect.topLeft());
}
// This will draw a nice and shiny QDial for us. We don't want
@@ -256,7 +236,7 @@ QPolygonF calcLines(const QStyleOptionSlider *dial)
void drawDial(const QStyleOptionSlider *option, QPainter *painter)
{
- QPalette pal = option->palette;
+ const QPalette pal = option->palette;
QColor buttonColor = pal.button().color();
const int width = option->rect.width();
const int height = option->rect.height();
@@ -270,7 +250,11 @@ void drawDial(const QStyleOptionSlider *option, QPainter *painter)
// Draw notches
if (option->subControls & QStyle::SC_DialTickmarks) {
- painter->setPen(option->palette.dark().color().darker(120));
+ const bool inverted = pal.window().color().lightness() < pal.text().color().lightness()
+ && pal.light().color().lightness() > pal.dark().color().lightness();
+ const QColor notchColor = inverted ? pal.light().color().lighter(120)
+ : pal.dark().color().darker(120);
+ painter->setPen(notchColor);
painter->drawLines(QStyleHelper::calcLines(option));
}
@@ -285,8 +269,8 @@ void drawDial(const QStyleOptionSlider *option, QPainter *painter)
p->setRenderHint(QPainter::Antialiasing);
const qreal d_ = r / 6;
- const qreal dx = option->rect.x() + d_ + (width - 2 * r) / 2 + 1;
- const qreal dy = option->rect.y() + d_ + (height - 2 * r) / 2 + 1;
+ const qreal dx = d_ + (width - 2 * r) / 2 + 1;
+ const qreal dy = d_ + (height - 2 * r) / 2 + 1;
QRectF br = QRectF(dx + 0.5, dy + 0.5,
int(r * 2 - 2 * d_ - 2),
@@ -342,7 +326,7 @@ void drawDial(const QStyleOptionSlider *option, QPainter *painter)
QPointF dp = calcRadialPos(option, qreal(0.70));
buttonColor = buttonColor.lighter(104);
- buttonColor.setAlphaF(qreal(0.8));
+ buttonColor.setAlphaF(0.8f);
const qreal ds = r/qreal(7.0);
QRectF dialRect(dp.x() - ds, dp.y() - ds, 2*ds, 2*ds);
QRadialGradient dialGradient(dialRect.center().x() + dialRect.width()/2,
@@ -379,7 +363,7 @@ void drawBorderPixmap(const QPixmap &pixmap, QPainter *painter, const QRect &rec
QRect(left, 0, size.width() -right - left, top));
//top-left
- if(left > 0)
+ if (left > 0)
painter->drawPixmap(QRect(rect.left(), rect.top(), left, top), pixmap,
QRect(0, 0, left, top));
diff --git a/src/widgets/styles/qstylehelper_p.h b/src/widgets/styles/qstylehelper_p.h
index 165608257a..524417e405 100644
--- a/src/widgets/styles/qstylehelper_p.h
+++ b/src/widgets/styles/qstylehelper_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtCore/qpoint.h>
@@ -92,7 +56,7 @@ namespace QStyleHelper
Q_WIDGETS_EXPORT void drawBorderPixmap(const QPixmap &pixmap, QPainter *painter, const QRect &rect,
int left = 0, int top = 0, int right = 0,
int bottom = 0);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
Q_WIDGETS_EXPORT bool isInstanceOf(QObject *obj, QAccessible::Role role);
Q_WIDGETS_EXPORT bool hasAncestor(QObject *obj, QAccessible::Role role);
#endif
diff --git a/src/widgets/styles/qstyleoption.cpp b/src/widgets/styles/qstyleoption.cpp
index 5a2ca2f2e7..d3a395246c 100644
--- a/src/widgets/styles/qstyleoption.cpp
+++ b/src/widgets/styles/qstyleoption.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QtWidgets/private/qtwidgetsglobal_p.h>
#include "private/qstylehelper_p.h"
@@ -58,9 +22,9 @@ QT_BEGIN_NAMESPACE
For performance reasons, there are few member functions and the
access to the member variables is direct (i.e., using the \c . or
- \c -> operator). This low-level feel makes the structures
- straightforward to use and emphasizes that these are simply
- parameters used by the style functions.
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
The caller of a QStyle function usually creates QStyleOption
objects on the stack. This combined with Qt's extensive use of
@@ -86,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
*/
@@ -176,13 +137,7 @@ QStyleOption::~QStyleOption()
\sa QWidget::layoutDirection(), QWidget::rect(),
QWidget::palette(), QWidget::fontMetrics()
*/
-
-/*!
- \obsolete
-
- Use initFrom(\a widget) instead.
-*/
-void QStyleOption::init(const QWidget *widget)
+void QStyleOption::initFrom(const QWidget *widget)
{
QWidget *window = widget->window();
state = QStyle::State_None;
@@ -365,13 +320,11 @@ QStyleOption &QStyleOption::operator=(const QStyleOption &other)
\inmodule QtWidgets
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption
*/
@@ -382,9 +335,8 @@ QStyleOption &QStyleOption::operator=(const QStyleOption &other)
*/
QStyleOptionFocusRect::QStyleOptionFocusRect()
- : QStyleOption(Version, SO_FocusRect)
+ : QStyleOptionFocusRect(Version)
{
- state |= QStyle::State_KeyboardFocusChange; // assume we had one, will be corrected in initFrom()
}
/*!
@@ -452,6 +404,12 @@ QStyleOptionFocusRect::QStyleOptionFocusRect(int version)
QStyleOptionFrame is used for drawing several built-in Qt widgets,
including QFrame, QGroupBox, QLineEdit, and QMenu.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
+
An instance of the QStyleOptionFrame class has
\l{QStyleOption::type} {type} SO_Frame and \l{QStyleOption::version}
{version} 3.
@@ -464,36 +422,16 @@ 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
*/
/*!
- \typedef QStyleOptionFrameV2
- \relates QStyleOptionFrame
- \obsolete
-
- Synonym for QStyleOptionFrame.
-*/
-
-/*!
- \typedef QStyleOptionFrameV3
- \relates QStyleOptionFrame
- \obsolete
-
- Synonym for QStyleOptionFrame.
-*/
-
-/*!
Constructs a QStyleOptionFrame, initializing the members
variables to their default values.
*/
QStyleOptionFrame::QStyleOptionFrame()
- : QStyleOption(Version, SO_Frame), lineWidth(0), midLineWidth(0),
- features(None), frameShape(QFrame::NoFrame)
+ : QStyleOptionFrame(Version)
{
}
@@ -602,13 +540,11 @@ QStyleOptionFrame::QStyleOptionFrame(int version)
the group box's \l {text}{title} and the title's \l
{textAlignment}{alignment} and \l {textColor}{color}.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QStyleOptionComplex, QGroupBox
*/
@@ -704,8 +640,7 @@ QStyleOptionFrame::QStyleOptionFrame(int version)
variables to their default values.
*/
QStyleOptionGroupBox::QStyleOptionGroupBox()
- : QStyleOptionComplex(Version, Type), features(QStyleOptionFrame::None),
- textAlignment(Qt::AlignLeft), lineWidth(0), midLineWidth(0)
+ : QStyleOptionGroupBox(Version)
{
}
@@ -735,13 +670,11 @@ QStyleOptionGroupBox::QStyleOptionGroupBox(int version)
functions need to draw the item views' header pane, header sort
arrow, and header label.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption
*/
@@ -752,11 +685,7 @@ QStyleOptionGroupBox::QStyleOptionGroupBox(int version)
*/
QStyleOptionHeader::QStyleOptionHeader()
- : QStyleOption(QStyleOptionHeader::Version, SO_Header),
- section(0), textAlignment(Qt::AlignLeft), iconAlignment(Qt::AlignLeft),
- position(QStyleOptionHeader::Beginning),
- selectedPosition(QStyleOptionHeader::NotAdjacent), sortIndicator(None),
- orientation(Qt::Horizontal)
+ : QStyleOptionHeader(QStyleOptionHeader::Version)
{
}
@@ -912,6 +841,49 @@ QStyleOptionHeader::QStyleOptionHeader(int version)
*/
/*!
+ \class QStyleOptionHeaderV2
+ \brief The QStyleOptionHeaderV2 class is used to describe the
+ parameters for drawing a header.
+
+ \inmodule QtWidgets
+*/
+
+/*!
+ Constructs a QStyleOptionHeaderV2, initializing the members
+ variables to their default values.
+*/
+QStyleOptionHeaderV2::QStyleOptionHeaderV2()
+ : QStyleOptionHeaderV2(QStyleOptionHeaderV2::Version)
+{
+}
+
+/*!
+ \internal
+*/
+QStyleOptionHeaderV2::QStyleOptionHeaderV2(int version)
+: QStyleOptionHeader(version), textElideMode(Qt::ElideNone), isSectionDragTarget(false), unused(0)
+{}
+
+/*!
+ \variable QStyleOptionHeaderV2::textElideMode
+ \brief where ellipsis should be added for text that is too long to fit
+ into an item
+
+ The default value is Qt::ElideNone.
+
+ \sa Qt::TextElideMode
+*/
+
+/*!
+ \variable QStyleOptionHeaderV2::isSectionDragTarget
+
+ \brief whether the section is the location at which a dragged section
+ will be inserted
+
+ \sa QHeaderView::setSectionsMovable
+*/
+
+/*!
\class QStyleOptionButton
\brief The QStyleOptionButton class is used to describe the
parameters for drawing buttons.
@@ -922,13 +894,11 @@ QStyleOptionHeader::QStyleOptionHeader(int version)
functions need to draw graphical elements like QPushButton,
QCheckBox, and QRadioButton.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QStyleOptionToolButton
*/
@@ -954,7 +924,7 @@ QStyleOptionHeader::QStyleOptionHeader(int version)
*/
QStyleOptionButton::QStyleOptionButton()
- : QStyleOption(QStyleOptionButton::Version, SO_Button), features(None)
+ : QStyleOptionButton(QStyleOptionButton::Version)
{
}
@@ -1047,11 +1017,6 @@ QStyleOptionButton::QStyleOptionButton(int version)
QStyleOptionToolBar contains all the information that QStyle
functions need to draw QToolBar.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
The QStyleOptionToolBar class holds the lineWidth and the
midLineWidth for drawing the widget. It also stores information
about which \l {toolBarArea}{area} the toolbar should be located
@@ -1065,8 +1030,11 @@ QStyleOptionButton::QStyleOptionButton(int version)
the position of a toolbar line, as well as the toolbar's position
within the line.
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption
*/
@@ -1077,8 +1045,7 @@ QStyleOptionButton::QStyleOptionButton(int version)
*/
QStyleOptionToolBar::QStyleOptionToolBar()
- : QStyleOption(Version, SO_ToolBar), positionOfLine(OnlyOne), positionWithinLine(OnlyOne),
- toolBarArea(Qt::TopToolBarArea), features(None), lineWidth(0), midLineWidth(0)
+ : QStyleOptionToolBar(Version)
{
}
@@ -1244,41 +1211,22 @@ QStyleOptionToolBar::QStyleOptionToolBar(int version)
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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption
*/
/*!
- \typedef QStyleOptionTabV2
- \relates QStyleOptionTab
- \obsolete
-
- Synonym for QStyleOptionTab.
-*/
-
-/*!
- \typedef QStyleOptionTabV3
- \relates QStyleOptionTab
- \obsolete
-
- Synonym for QStyleOptionTab.
-*/
-
-/*!
Constructs a QStyleOptionTab object, initializing the members
variables to their default values.
*/
QStyleOptionTab::QStyleOptionTab()
- : QStyleOption(QStyleOptionTab::Version, SO_Tab),
- shape(QTabBar::RoundedNorth),
- row(0),
- position(Beginning),
- selectedPosition(NotAdjacent), cornerWidgets(QStyleOptionTab::NoCornerWidgets),
- documentMode(false),
- features(QStyleOptionTab::None)
+ : QStyleOptionTab(QStyleOptionTab::Version)
{
}
@@ -1342,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
*/
@@ -1393,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
*/
@@ -1471,16 +1420,7 @@ QStyleOptionTab::QStyleOptionTab(int version)
*/
/*!
- Constructs a QStyleOptionTabV4 object, initializing the members
- variables to their default values.
- */
-
-QStyleOptionTabV4::QStyleOptionTabV4() : QStyleOptionTab(QStyleOptionTabV4::Version)
-{
-}
-
-/*!
- \variable QStyleOptionTabV4::tabIndex
+ \variable QStyleOptionTab::tabIndex
\brief the index for the tab being represented.
The default value is -1, i.e. a tab not on a tabbar;
@@ -1506,29 +1446,22 @@ QStyleOptionTabV4::QStyleOptionTabV4() : QStyleOptionTab(QStyleOptionTabV4::Vers
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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption
*/
/*!
- \typedef QStyleOptionProgressBarV2
- \relates QStyleOptionProgressBar
- \obsolete
-
- Synonym for QStyleOptionProgressBar.
-*/
-
-/*!
Constructs a QStyleOptionProgressBar, initializing the members
variables to their default values.
*/
QStyleOptionProgressBar::QStyleOptionProgressBar()
- : QStyleOption(QStyleOptionProgressBar::Version, SO_ProgressBar),
- minimum(0), maximum(0), progress(0), textAlignment(Qt::AlignLeft), textVisible(false),
- orientation(Qt::Horizontal), invertedAppearance(false), bottomToTop(false)
+ : QStyleOptionProgressBar(QStyleOptionProgressBar::Version)
{
}
@@ -1538,8 +1471,9 @@ QStyleOptionProgressBar::QStyleOptionProgressBar()
QStyleOptionProgressBar::QStyleOptionProgressBar(int version)
: QStyleOption(version, SO_ProgressBar),
minimum(0), maximum(0), progress(0), textAlignment(Qt::AlignLeft), textVisible(false),
- orientation(Qt::Horizontal), invertedAppearance(false), bottomToTop(false)
+ invertedAppearance(false), bottomToTop(false)
{
+ state |= QStyle::State_Horizontal;
}
/*!
@@ -1623,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.
@@ -1641,17 +1575,6 @@ QStyleOptionProgressBar::QStyleOptionProgressBar(int version)
*/
/*!
- \variable QStyleOptionProgressBar::orientation
- \brief the progress bar's orientation (horizontal or vertical);
- the default orentation is Qt::Horizontal
-
- \deprecated
- Use the QStyle::State_Horizontal flag instead (in the the QStyleOption::state member).
-
- \sa QProgressBar::orientation
-*/
-
-/*!
\variable QStyleOptionProgressBar::invertedAppearance
\brief whether the progress bar's appearance is inverted
@@ -1681,13 +1604,11 @@ QStyleOptionProgressBar::QStyleOptionProgressBar(int version)
functions need to draw the menu items from \l QMenu. It is also
used for drawing other menu-related widgets.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption
*/
@@ -1698,8 +1619,7 @@ QStyleOptionProgressBar::QStyleOptionProgressBar(int version)
*/
QStyleOptionMenuItem::QStyleOptionMenuItem()
- : QStyleOption(QStyleOptionMenuItem::Version, SO_MenuItem), menuItemType(Normal),
- checkType(NotCheckable), checked(false), menuHasCheckableItems(true), maxIconWidth(0), tabWidth(0)
+ : QStyleOptionMenuItem(QStyleOptionMenuItem::Version)
{
}
@@ -1708,7 +1628,8 @@ QStyleOptionMenuItem::QStyleOptionMenuItem()
*/
QStyleOptionMenuItem::QStyleOptionMenuItem(int version)
: QStyleOption(version, SO_MenuItem), menuItemType(Normal),
- checkType(NotCheckable), checked(false), menuHasCheckableItems(true), maxIconWidth(0), tabWidth(0)
+ checkType(NotCheckable), checked(false), menuHasCheckableItems(true), maxIconWidth(0),
+ reservedShortcutWidth(0)
{
}
@@ -1776,7 +1697,7 @@ QStyleOptionMenuItem::QStyleOptionMenuItem(int version)
\value Exclusive The item is an exclusive check item (like a radio button).
\value NonExclusive The item is a non-exclusive check item (like a check box).
- \sa checkType, QGuiAction::checkable, QGuiAction::checked, QGuiActionGroup::exclusionPolicy
+ \sa checkType, QAction::checkable, QAction::checked, QActionGroup::exclusionPolicy
*/
/*!
@@ -1852,7 +1773,7 @@ QStyleOptionMenuItem::QStyleOptionMenuItem(int version)
*/
/*!
- \variable QStyleOptionMenuItem::tabWidth
+ \variable QStyleOptionMenuItem::reservedShortcutWidth
\brief the reserved width for the menu item's shortcut
QMenu sets it to the width occupied by the widest shortcut among
@@ -1883,11 +1804,11 @@ QStyleOptionMenuItem::QStyleOptionMenuItem(int version)
other complex control options, for example QStyleOptionSlider and
QStyleOptionSpinBox.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator).
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption
*/
@@ -1973,13 +1894,11 @@ QStyleOptionComplex::QStyleOptionComplex(int version, int type)
QStyleOptionSlider contains all the information that QStyle
functions need to draw QSlider and QScrollBar.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOptionComplex, QSlider, QScrollBar
*/
@@ -1990,10 +1909,7 @@ QStyleOptionComplex::QStyleOptionComplex(int version, int type)
*/
QStyleOptionSlider::QStyleOptionSlider()
- : QStyleOptionComplex(Version, SO_Slider), orientation(Qt::Horizontal), minimum(0), maximum(0),
- tickPosition(QSlider::NoTicks), tickInterval(0), upsideDown(false),
- sliderPosition(0), sliderValue(0), singleStep(0), pageStep(0), notchTarget(0.0),
- dialWrapping(false)
+ : QStyleOptionSlider(Version)
{
}
@@ -2004,7 +1920,7 @@ QStyleOptionSlider::QStyleOptionSlider(int version)
: QStyleOptionComplex(version, SO_Slider), orientation(Qt::Horizontal), minimum(0), maximum(0),
tickPosition(QSlider::NoTicks), tickInterval(0), upsideDown(false),
sliderPosition(0), sliderValue(0), singleStep(0), pageStep(0), notchTarget(0.0),
- dialWrapping(false)
+ dialWrapping(false), keyboardModifiers{}
{
}
@@ -2172,13 +2088,11 @@ QStyleOptionSlider::QStyleOptionSlider(int version)
QStyleOptionSpinBox contains all the information that QStyle
functions need to draw QSpinBox and QDateTimeEdit.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QStyleOptionComplex
*/
@@ -2189,8 +2103,7 @@ QStyleOptionSlider::QStyleOptionSlider(int version)
*/
QStyleOptionSpinBox::QStyleOptionSpinBox()
- : QStyleOptionComplex(Version, SO_SpinBox), buttonSymbols(QAbstractSpinBox::UpDownArrows),
- stepEnabled(QAbstractSpinBox::StepNone), frame(false)
+ : QStyleOptionSpinBox(Version)
{
}
@@ -2277,33 +2190,22 @@ QStyleOptionSpinBox::QStyleOptionSpinBox(int version)
QStyleOptionDockWidget contains all the information that QStyle
functions need to draw graphical elements like QDockWidget.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption
*/
/*!
- \typedef QStyleOptionDockWidgetV2
- \relates QStyleOptionDockWidget
- \obsolete
-
- Synonym for QStyleOptionDockWidget.
-*/
-
-/*!
Constructs a QStyleOptionDockWidget, initializing the member
variables to their default values.
*/
QStyleOptionDockWidget::QStyleOptionDockWidget()
- : QStyleOption(Version, SO_DockWidget), closable(false),
- movable(false), floatable(false), verticalTitleBar(false)
+ : QStyleOptionDockWidget(Version)
{
}
@@ -2391,13 +2293,11 @@ QStyleOptionDockWidget::QStyleOptionDockWidget(int version)
QStyleOptionToolButton contains all the information that QStyle
functions need to draw QToolButton.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QStyleOptionComplex, QStyleOptionButton
*/
@@ -2423,8 +2323,7 @@ QStyleOptionDockWidget::QStyleOptionDockWidget(int version)
*/
QStyleOptionToolButton::QStyleOptionToolButton()
- : QStyleOptionComplex(Version, SO_ToolButton), features(None), arrowType(Qt::DownArrow)
- , toolButtonStyle(Qt::ToolButtonIconOnly)
+ : QStyleOptionToolButton(Version)
{
}
@@ -2555,13 +2454,11 @@ QStyleOptionToolButton::QStyleOptionToolButton(int version)
QStyleOptionButton contains all the information that QStyle
functions need to draw QComboBox.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QStyleOptionComplex, QComboBox
*/
@@ -2572,7 +2469,7 @@ QStyleOptionToolButton::QStyleOptionToolButton(int version)
*/
QStyleOptionComboBox::QStyleOptionComboBox()
- : QStyleOptionComplex(Version, SO_ComboBox), editable(false), frame(true)
+ : QStyleOptionComboBox(Version)
{
}
@@ -2612,7 +2509,7 @@ QStyleOptionComboBox::QStyleOptionComboBox(int version)
This enum is used to hold information about the version of the style option, and
is defined for each QStyleOption subclass.
- \value Version 1
+ \value Version 2
The version is used by QStyleOption subclasses to implement
extensions without breaking compatibility. If you use
@@ -2674,6 +2571,13 @@ QStyleOptionComboBox::QStyleOptionComboBox(int version)
*/
/*!
+ \variable QStyleOptionComboBox::textAlignment
+ \brief the alignment of the current text in the combo box
+
+ The default value is Qt::AlignLeft | Qt::AlignVCenter.
+*/
+
+/*!
\class QStyleOptionToolBox
\brief The QStyleOptionToolBox class is used to describe the
parameters needed for drawing a tool box.
@@ -2683,32 +2587,22 @@ QStyleOptionComboBox::QStyleOptionComboBox(int version)
QStyleOptionToolBox contains all the information that QStyle
functions need to draw QToolBox.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QToolBox
*/
/*!
- \typedef QStyleOptionToolBoxV2
- \relates QStyleOptionToolBox
- \obsolete
-
- Synonym for QStyleOptionToolBox.
-*/
-
-/*!
Creates a QStyleOptionToolBox, initializing the members variables
to their default values.
*/
QStyleOptionToolBox::QStyleOptionToolBox()
- : QStyleOption(Version, SO_ToolBox), position(Beginning), selectedPosition(NotAdjacent)
+ : QStyleOptionToolBox(Version)
{
}
@@ -2817,13 +2711,11 @@ QStyleOptionToolBox::QStyleOptionToolBox(int version)
QStyleOptionRubberBand contains all the information that
QStyle functions need to draw QRubberBand.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QRubberBand
*/
@@ -2834,7 +2726,7 @@ QStyleOptionToolBox::QStyleOptionToolBox(int version)
*/
QStyleOptionRubberBand::QStyleOptionRubberBand()
- : QStyleOption(Version, SO_RubberBand), shape(QRubberBand::Line), opaque(false)
+ : QStyleOptionRubberBand(Version)
{
}
@@ -2908,13 +2800,11 @@ QStyleOptionRubberBand::QStyleOptionRubberBand(int version)
QStyleOptionTitleBar contains all the information that QStyle
functions need to draw the title bar of a QMdiSubWindow.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QStyleOptionComplex, QMdiSubWindow
*/
@@ -2925,7 +2815,7 @@ QStyleOptionRubberBand::QStyleOptionRubberBand(int version)
*/
QStyleOptionTitleBar::QStyleOptionTitleBar()
- : QStyleOptionComplex(Version, SO_TitleBar), titleBarState(0)
+ : QStyleOptionTitleBar(Version)
{
}
@@ -3020,43 +2910,17 @@ QStyleOptionTitleBar::QStyleOptionTitleBar(int version)
QStyleOptionViewItem contains all the information that QStyle
functions need to draw the items for Qt's model/view classes.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, {model-view-programming.html}{Model/View
Programming}
*/
/*!
- \typedef QStyleOptionViewItemV2
- \relates QStyleOptionViewItem
- \obsolete
-
- Synonym for QStyleOptionViewItem.
-*/
-
-/*!
- \typedef QStyleOptionViewItemV3
- \relates QStyleOptionViewItem
- \obsolete
-
- Synonym for QStyleOptionViewItem.
-*/
-
-/*!
- \typedef QStyleOptionViewItemV4
- \relates QStyleOptionViewItem
- \obsolete
-
- Synonym for QStyleOptionViewItem.
-*/
-
-/*!
\enum QStyleOptionViewItem::Position
This enum describes the position of the item's decoration.
@@ -3098,11 +2962,7 @@ QStyleOptionTitleBar::QStyleOptionTitleBar(int version)
*/
QStyleOptionViewItem::QStyleOptionViewItem()
- : QStyleOption(Version, SO_ViewItem),
- displayAlignment(Qt::AlignLeft), decorationAlignment(Qt::AlignLeft),
- textElideMode(Qt::ElideMiddle), decorationPosition(Left),
- showDecorationSelected(false), features(None), widget(nullptr),
- checkState(Qt::Unchecked), viewItemPosition(QStyleOptionViewItem::Invalid)
+ : QStyleOptionViewItem(Version)
{
}
@@ -3310,32 +3170,21 @@ QStyleOptionViewItem::QStyleOptionViewItem(int version)
QStyleOptionTabWidgetFrame contains all the information that
QStyle functions need to draw the frame around QTabWidget.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QTabWidget
*/
/*!
- \typedef QStyleOptionTabWidgetFrameV2
- \relates QStyleOptionTabWidgetFrame
- \obsolete
-
- Synonym for QStyleOptionTabWidgetFrame.
-*/
-
-/*!
Constructs a QStyleOptionTabWidgetFrame, initializing the members
variables to their default values.
*/
QStyleOptionTabWidgetFrame::QStyleOptionTabWidgetFrame()
- : QStyleOption(Version, SO_TabWidgetFrame), lineWidth(0), midLineWidth(0),
- shape(QTabBar::RoundedNorth)
+ : QStyleOptionTabWidgetFrame(Version)
{
}
@@ -3460,32 +3309,21 @@ QStyleOptionTabWidgetFrame::QStyleOptionTabWidgetFrame(int version)
drawn for a standalone QTabBar (one that isn't part of a
QTabWidget).
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QTabBar::drawBase()
*/
/*!
- \typedef QStyleOptionTabBarBaseV2
- \relates QStyleOptionTabBarBase
- \obsolete
-
- Synonym for QStyleOptionTabBarBase.
-*/
-
-/*!
Construct a QStyleOptionTabBarBase, initializing the members
- vaiables to their default values.
+ variables to their default values.
*/
QStyleOptionTabBarBase::QStyleOptionTabBarBase()
- : QStyleOption(Version, SO_TabBarBase), shape(QTabBar::RoundedNorth),
- documentMode(false)
+ : QStyleOptionTabBarBase(Version)
{
}
@@ -3578,13 +3416,11 @@ QStyleOptionTabBarBase::QStyleOptionTabBarBase(int version)
QStyleOptionButton contains all the information that QStyle
functions need to draw QSizeGrip.
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use 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.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QStyleOptionComplex, QSizeGrip
*/
@@ -3593,7 +3429,7 @@ QStyleOptionTabBarBase::QStyleOptionTabBarBase(int version)
Constructs a QStyleOptionSizeGrip.
*/
QStyleOptionSizeGrip::QStyleOptionSizeGrip()
- : QStyleOptionComplex(Version, Type), corner(Qt::BottomRightCorner)
+ : QStyleOptionSizeGrip(Version)
{
}
@@ -3657,13 +3493,11 @@ QStyleOptionSizeGrip::QStyleOptionSizeGrip(int version)
\ingroup graphicsview-api
\inmodule QtWidgets
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
+ For performance reasons, there are few member functions and the
+ access to the member variables is direct (i.e., using the \c . or
+ \c -> operator). This makes the structures straightforward to use
+ and emphasizes that these are simply parameters used by the style
+ functions.
\sa QStyleOption, QGraphicsItem::paint()
*/
@@ -3703,7 +3537,7 @@ QStyleOptionSizeGrip::QStyleOptionSizeGrip(int version)
Constructs a QStyleOptionGraphicsItem.
*/
QStyleOptionGraphicsItem::QStyleOptionGraphicsItem()
- : QStyleOption(Version, Type), levelOfDetail(1)
+ : QStyleOptionGraphicsItem(Version)
{
}
@@ -3711,7 +3545,7 @@ QStyleOptionGraphicsItem::QStyleOptionGraphicsItem()
\internal
*/
QStyleOptionGraphicsItem::QStyleOptionGraphicsItem(int version)
- : QStyleOption(version, Type), levelOfDetail(1)
+ : QStyleOption(version, Type)
{
}
@@ -3759,38 +3593,6 @@ qreal QStyleOptionGraphicsItem::levelOfDetailFromTransform(const QTransform &wor
*/
/*!
- \variable QStyleOptionGraphicsItem::matrix
- \brief the complete transformation matrix for the item
- \obsolete
-
- The QMatrix provided through this member does include information about
- any perspective transformations applied to the view or item. To get the
- correct transformation matrix, use QPainter::transform() on the painter
- passed into the QGraphicsItem::paint() implementation.
-
- This matrix is the combination of the item's scene matrix and the matrix
- of the painter used for drawing the item. It is provided for convenience,
- allowing anvanced level-of-detail metrics that can be used to speed up
- item drawing.
-
- To find the dimensions of an item in screen coordinates (i.e., pixels),
- you can use the mapping functions of QMatrix, such as QMatrix::map().
-
- This member is only initialized for items that have the
- QGraphicsItem::ItemUsesExtendedStyleOption flag set.
-
- \sa QStyleOptionGraphicsItem::levelOfDetailFromTransform()
-*/
-
-/*!
- \variable QStyleOptionGraphicsItem::levelOfDetail
- \obsolete
-
- Use QStyleOptionGraphicsItem::levelOfDetailFromTransform()
- together with QPainter::worldTransform() instead.
-*/
-
-/*!
\class QStyleHintReturn
\brief The QStyleHintReturn class provides style hints that return more
than basic data types.
@@ -3802,10 +3604,6 @@ qreal QStyleOptionGraphicsItem::levelOfDetailFromTransform(const QTransform &wor
from a style back to the querying widget. This is most useful
when the return value from QStyle::styleHint() does not provide enough
detail; for example, when a mask is to be returned.
-
- \omit
- ### --Sam
- \endomit
*/
/*!
@@ -3895,10 +3693,6 @@ QStyleHintReturn::~QStyleHintReturn()
\ingroup appearance
\inmodule QtWidgets
-
- \omit
- ### --Sam
- \endomit
*/
/*!
diff --git a/src/widgets/styles/qstyleoption.h b/src/widgets/styles/qstyleoption.h
index a8ce3b465e..0e0118f6e9 100644
--- a/src/widgets/styles/qstyleoption.h
+++ b/src/widgets/styles/qstyleoption.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QSTYLEOPTION_H
#define QSTYLEOPTION_H
@@ -47,7 +11,7 @@
#include <QtWidgets/qabstractspinbox.h>
#endif
#include <QtGui/qicon.h>
-#include <QtGui/qmatrix.h>
+#include <QtGui/qtransform.h>
#if QT_CONFIG(slider)
#include <QtWidgets/qslider.h>
#endif
@@ -103,8 +67,7 @@ public:
QStyleOption(const QStyleOption &other);
~QStyleOption();
- void init(const QWidget *w);
- inline void initFrom(const QWidget *w) { init(w); }
+ void initFrom(const QWidget *w);
QStyleOption &operator=(const QStyleOption &other);
};
@@ -128,7 +91,7 @@ class Q_WIDGETS_EXPORT QStyleOptionFrame : public QStyleOption
{
public:
enum StyleOptionType { Type = SO_Frame };
- enum StyleOptionVersion { Version = 3 };
+ enum StyleOptionVersion { Version = 1 };
int lineWidth;
int midLineWidth;
@@ -151,15 +114,12 @@ protected:
Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionFrame::FrameFeatures)
-typedef Q_DECL_DEPRECATED QStyleOptionFrame QStyleOptionFrameV2;
-typedef Q_DECL_DEPRECATED QStyleOptionFrame QStyleOptionFrameV3;
-
#if QT_CONFIG(tabwidget)
class Q_WIDGETS_EXPORT QStyleOptionTabWidgetFrame : public QStyleOption
{
public:
enum StyleOptionType { Type = SO_TabWidgetFrame };
- enum StyleOptionVersion { Version = 2 };
+ enum StyleOptionVersion { Version = 1 };
int lineWidth;
int midLineWidth;
@@ -179,7 +139,6 @@ protected:
QStyleOptionTabWidgetFrame(int version);
};
-typedef Q_DECL_DEPRECATED QStyleOptionTabWidgetFrame QStyleOptionTabWidgetFrameV2;
#endif // QT_CONFIG(tabwidget)
@@ -188,7 +147,7 @@ class Q_WIDGETS_EXPORT QStyleOptionTabBarBase : public QStyleOption
{
public:
enum StyleOptionType { Type = SO_TabBarBase };
- enum StyleOptionVersion { Version = 2 };
+ enum StyleOptionVersion { Version = 1 };
QTabBar::Shape shape;
QRect tabBarRect;
@@ -203,7 +162,6 @@ protected:
QStyleOptionTabBarBase(int version);
};
-typedef Q_DECL_DEPRECATED QStyleOptionTabBarBase QStyleOptionTabBarBaseV2;
#endif // QT_CONFIG(tabbar)
class Q_WIDGETS_EXPORT QStyleOptionHeader : public QStyleOption
@@ -235,6 +193,25 @@ protected:
QStyleOptionHeader(int version);
};
+// ### Qt7: merge with QStyleOptionHeader
+class Q_WIDGETS_EXPORT QStyleOptionHeaderV2 : public QStyleOptionHeader
+{
+public:
+ enum StyleOptionType { Type = SO_Header };
+ enum StyleOptionVersion { Version = 2 };
+
+ QStyleOptionHeaderV2();
+ QStyleOptionHeaderV2(const QStyleOptionHeaderV2 &other) : QStyleOptionHeader(Version) { *this = other; }
+ QStyleOptionHeaderV2 &operator=(const QStyleOptionHeaderV2 &) = default;
+
+ Qt::TextElideMode textElideMode:2;
+ bool isSectionDragTarget:1;
+ int unused:29;
+
+protected:
+ QStyleOptionHeaderV2(int version);
+};
+
class Q_WIDGETS_EXPORT QStyleOptionButton : public QStyleOption
{
public:
@@ -265,9 +242,9 @@ class Q_WIDGETS_EXPORT QStyleOptionTab : public QStyleOption
{
public:
enum StyleOptionType { Type = SO_Tab };
- enum StyleOptionVersion { Version = 3 };
+ 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 };
@@ -287,6 +264,7 @@ public:
QSize leftButtonSize;
QSize rightButtonSize;
TabFeatures features;
+ int tabIndex = -1;
QStyleOptionTab();
QStyleOptionTab(const QStyleOptionTab &other) : QStyleOption(Version, Type) { *this = other; }
@@ -296,18 +274,8 @@ protected:
QStyleOptionTab(int version);
};
-class Q_WIDGETS_EXPORT QStyleOptionTabV4 : public QStyleOptionTab
-{
-public:
- enum StyleOptionVersion { Version = 4 };
- QStyleOptionTabV4();
- int tabIndex = -1;
-};
-
Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionTab::CornerWidgets)
-typedef Q_DECL_DEPRECATED QStyleOptionTab QStyleOptionTabV2;
-typedef Q_DECL_DEPRECATED QStyleOptionTab QStyleOptionTabV3;
#endif // QT_CONFIG(tabbar)
@@ -343,7 +311,7 @@ class Q_WIDGETS_EXPORT QStyleOptionProgressBar : public QStyleOption
{
public:
enum StyleOptionType { Type = SO_ProgressBar };
- enum StyleOptionVersion { Version = 2 };
+ enum StyleOptionVersion { Version = 1 };
int minimum;
int maximum;
@@ -351,7 +319,6 @@ public:
QString text;
Qt::Alignment textAlignment;
bool textVisible;
- Qt::Orientation orientation; // ### Qt 6: remove
bool invertedAppearance;
bool bottomToTop;
@@ -363,8 +330,6 @@ protected:
QStyleOptionProgressBar(int version);
};
-typedef Q_DECL_DEPRECATED QStyleOptionProgressBar QStyleOptionProgressBarV2;
-
class Q_WIDGETS_EXPORT QStyleOptionMenuItem : public QStyleOption
{
public:
@@ -383,7 +348,7 @@ public:
QString text;
QIcon icon;
int maxIconWidth;
- int tabWidth; // ### Qt 6: rename to reservedShortcutWidth
+ int reservedShortcutWidth;
QFont font;
QStyleOptionMenuItem();
@@ -398,7 +363,7 @@ class Q_WIDGETS_EXPORT QStyleOptionDockWidget : public QStyleOption
{
public:
enum StyleOptionType { Type = SO_DockWidget };
- enum StyleOptionVersion { Version = 2 };
+ enum StyleOptionVersion { Version = 1 };
QString title;
bool closable;
@@ -414,15 +379,13 @@ protected:
QStyleOptionDockWidget(int version);
};
-typedef Q_DECL_DEPRECATED QStyleOptionDockWidget QStyleOptionDockWidgetV2;
-
#if QT_CONFIG(itemviews)
class Q_WIDGETS_EXPORT QStyleOptionViewItem : public QStyleOption
{
public:
enum StyleOptionType { Type = SO_ViewItem };
- enum StyleOptionVersion { Version = 4 };
+ enum StyleOptionVersion { Version = 1 };
enum Position { Left, Right, Top, Bottom };
@@ -468,17 +431,13 @@ protected:
Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionViewItem::ViewItemFeatures)
-typedef Q_DECL_DEPRECATED QStyleOptionViewItem QStyleOptionViewItemV2;
-typedef Q_DECL_DEPRECATED QStyleOptionViewItem QStyleOptionViewItemV3;
-typedef Q_DECL_DEPRECATED QStyleOptionViewItem QStyleOptionViewItemV4;
-
#endif // QT_CONFIG(itemviews)
class Q_WIDGETS_EXPORT QStyleOptionToolBox : public QStyleOption
{
public:
enum StyleOptionType { Type = SO_ToolBox };
- enum StyleOptionVersion { Version = 2 };
+ enum StyleOptionVersion { Version = 1 };
QString text;
QIcon icon;
@@ -497,8 +456,6 @@ protected:
QStyleOptionToolBox(int version);
};
-typedef Q_DECL_DEPRECATED QStyleOptionToolBox QStyleOptionToolBoxV2;
-
#if QT_CONFIG(rubberband)
class Q_WIDGETS_EXPORT QStyleOptionRubberBand : public QStyleOption
{
@@ -552,6 +509,7 @@ public:
int pageStep;
qreal notchTarget;
bool dialWrapping;
+ Qt::KeyboardModifiers keyboardModifiers;
QStyleOptionSlider();
QStyleOptionSlider(const QStyleOptionSlider &other) : QStyleOptionComplex(Version, Type) { *this = other; }
@@ -623,6 +581,7 @@ public:
QString currentText;
QIcon currentIcon;
QSize iconSize;
+ Qt::Alignment textAlignment = Qt::AlignLeft | Qt::AlignVCenter;
QStyleOptionComboBox();
QStyleOptionComboBox(const QStyleOptionComboBox &other) : QStyleOptionComplex(Version, Type) { *this = other; }
@@ -693,8 +652,6 @@ public:
enum StyleOptionVersion { Version = 1 };
QRectF exposedRect;
- QMatrix matrix;
- qreal levelOfDetail;
QStyleOptionGraphicsItem();
QStyleOptionGraphicsItem(const QStyleOptionGraphicsItem &other) : QStyleOption(Version, Type) { *this = other; }
diff --git a/src/widgets/styles/qstylepainter.cpp b/src/widgets/styles/qstylepainter.cpp
index 66cf494519..375928ae4b 100644
--- a/src/widgets/styles/qstylepainter.cpp
+++ b/src/widgets/styles/qstylepainter.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstylepainter.h"
diff --git a/src/widgets/styles/qstylepainter.h b/src/widgets/styles/qstylepainter.h
index b5e7956cb1..240ffbd137 100644
--- a/src/widgets/styles/qstylepainter.h
+++ b/src/widgets/styles/qstylepainter.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTYLEPAINTER_H
#define QSTYLEPAINTER_H
@@ -59,8 +23,10 @@ public:
Q_ASSERT_X(w, "QStylePainter::QStylePainter", "Widget must be non-zero");
widget = w;
wstyle = w->style();
- return QPainter::begin(pd);
- };
+ 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/qstyleplugin.cpp b/src/widgets/styles/qstyleplugin.cpp
index b29ff0b9a1..94ea92e0a3 100644
--- a/src/widgets/styles/qstyleplugin.cpp
+++ b/src/widgets/styles/qstyleplugin.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstyleplugin.h"
#include "qstyle.h"
diff --git a/src/widgets/styles/qstyleplugin.h b/src/widgets/styles/qstyleplugin.h
index e9a26f9127..3a24f9e387 100644
--- a/src/widgets/styles/qstyleplugin.h
+++ b/src/widgets/styles/qstyleplugin.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTYLEPLUGIN_H
#define QSTYLEPLUGIN_H
diff --git a/src/widgets/styles/qstylesheetstyle.cpp b/src/widgets/styles/qstylesheetstyle.cpp
index 2eccb24431..655b224617 100644
--- a/src/widgets/styles/qstylesheetstyle.cpp
+++ b/src/widgets/styles/qstylesheetstyle.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <qglobal.h>
#include "qstylesheetstyle_p.h"
@@ -57,6 +21,10 @@
#if QT_CONFIG(lineedit)
#include <qlineedit.h>
#endif
+#if QT_CONFIG(textedit)
+#include <qtextedit.h>
+#include <qplaintextedit.h>
+#endif
#include <private/qwindowsstyle_p.h>
#if QT_CONFIG(combobox)
#include <qcombobox.h>
@@ -65,7 +33,9 @@
#include "private/qmath_p.h"
#include <qabstractscrollarea.h>
#include "private/qabstractscrollarea_p.h"
+#if QT_CONFIG(tooltip)
#include <qtooltip.h>
+#endif
#include <qshareddata.h>
#if QT_CONFIG(toolbutton)
#include <qtoolbutton.h>
@@ -89,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)
@@ -117,11 +87,19 @@
#if QT_CONFIG(toolbar)
#include <QtWidgets/qtoolbar.h>
#endif
+#if QT_CONFIG(pushbutton)
+#include <QtWidgets/qpushbutton.h>
+#endif
+#include <QtGui/qpainterpath.h>
#include <QtGui/qscreen.h>
+#include <QtCore/private/qduplicatetracker_p.h>
+
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
using namespace QCss;
@@ -139,7 +117,7 @@ static QStyleSheetStyleCaches *styleSheetCaches = nullptr;
* the QStyleSheetStyle is a proxy. If used with others proxy style, we may end up with something like:
* QStyleSheetStyle -> ProxyStyle -> QStyleSheetStyle -> OriginalStyle
* Recursion may happen if the style call the widget()->style() again.
- * Not to mention the performence penalty of having two lookup of rules.
+ * Not to mention the performance penalty of having two lookup of rules.
*
* The first instance of QStyleSheetStyle will set globalStyleSheetStyle to itself. The second one
* will notice the globalStyleSheetStyle is not istelf and call its base style directly.
@@ -160,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,
@@ -182,7 +158,7 @@ enum PseudoElement {
PseudoElement_GroupBoxIndicator,
PseudoElement_ToolButtonMenu,
PseudoElement_ToolButtonMenuArrow,
- PseudoElement_ToolButtonDownArrow,
+ PseudoElement_ToolButtonMenuIndicator,
PseudoElement_ToolBoxTab,
PseudoElement_ScrollBarSlider,
PseudoElement_ScrollBarAddPage,
@@ -458,15 +434,26 @@ struct QStyleSheetBoxData : public QSharedData
struct QStyleSheetPaletteData : public QSharedData
{
- QStyleSheetPaletteData(const QBrush &fg, const QBrush &sfg, const QBrush &sbg,
- const QBrush &abg)
- : foreground(fg), selectionForeground(sfg), selectionBackground(sbg),
- alternateBackground(abg) { }
+ 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
@@ -503,7 +490,7 @@ class QRenderRule
{
public:
QRenderRule() : features(0), hasFont(false), pal(nullptr), b(nullptr), bg(nullptr), bd(nullptr), ou(nullptr), geo(nullptr), p(nullptr), img(nullptr), clipset(0) { }
- QRenderRule(const QVector<QCss::Declaration> &, const QObject *);
+ QRenderRule(const QList<QCss::Declaration> &, const QObject *);
QRect borderRect(const QRect &r) const;
QRect outlineRect(const QRect &r) const;
@@ -635,10 +622,10 @@ public:
int clipset;
QPainterPath clipPath;
};
-Q_DECLARE_TYPEINFO(QRenderRule, Q_MOVABLE_TYPE);
+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",
@@ -686,6 +673,7 @@ static const char knownStyleHints[][45] = {
"gridline-color",
"harddisk-icon",
"home-icon",
+ "lineedit-clear-button-icon",
"icon-size",
"leftarrow-icon",
"lineedit-password-character",
@@ -730,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.count(); i++) {
- int button = layout[i].toLatin1();
+ for (int button : layout) {
switch (button) {
case 'm':
buttons.append(PseudoElement_MdiMinButton);
@@ -791,17 +776,16 @@ QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget
const bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
QRenderRule subRule = renderRule(w, tb);
QRect cr = subRule.contentsRect(tb->rect);
- QList<QVariant> layout = subRule.styleHint(QLatin1String("button-layout")).toList();
+ QList<QVariant> layout = subRule.styleHint("button-layout"_L1).toList();
if (layout.isEmpty())
- layout = subControlLayout(QLatin1String("I(T)HSmMX"));
+ layout = subControlLayout("I(T)HSmMX"_L1);
int offsets[3] = { 0, 0, 0 };
enum Where { Left, Right, Center, NoWhere } where = Left;
- QVector<ButtonInfo> infos;
- const int numLayouts = layout.size();
- infos.reserve(numLayouts);
- for (int i = 0; i < numLayouts; i++) {
- const int element = layout[i].toInt();
+ QList<ButtonInfo> infos;
+ infos.reserve(layout.size());
+ for (const QVariant &val : std::as_const(layout)) {
+ const int element = val.toInt();
if (element == '(') {
where = Center;
} else if (element == ')') {
@@ -854,14 +838,13 @@ QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget
info.rule = subRule;
info.offset = offsets[where];
info.where = where;
- infos.append(std::move(info));
-
offsets[where] += info.width;
+
+ infos.append(std::move(info));
}
}
- 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: {
@@ -909,8 +892,18 @@ static QStyle::StandardPixmap subControlIcon(int pe)
return QStyle::SP_CustomBase;
}
-QRenderRule::QRenderRule(const QVector<Declaration> &declarations, const QObject *object)
-: features(0), hasFont(false), pal(nullptr), b(nullptr), bg(nullptr), bd(nullptr), ou(nullptr), geo(nullptr), p(nullptr), img(nullptr), clipset(0)
+QRenderRule::QRenderRule(const QList<Declaration> &declarations, const QObject *object)
+ : features(0),
+ hasFont(false),
+ pal(nullptr),
+ b(nullptr),
+ bg(nullptr),
+ bd(nullptr),
+ ou(nullptr),
+ geo(nullptr),
+ p(nullptr),
+ img(nullptr),
+ clipset(0)
{
QPalette palette = QGuiApplication::palette(); // ###: ideally widget's palette
ValueExtractor v(declarations, palette);
@@ -967,10 +960,17 @@ QRenderRule::QRenderRule(const QVector<Declaration> &declarations, const QObject
bg = new QStyleSheetBackgroundData(brush, pixmap, repeat, alignment, origin, attachment, clip);
}
- QBrush sfg, fg;
- QBrush sbg, abg;
- if (v.extractPalette(&fg, &sfg, &sbg, &abg))
- pal = new QStyleSheetPaletteData(fg, sfg, sbg, abg);
+ 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;
@@ -986,12 +986,12 @@ QRenderRule::QRenderRule(const QVector<Declaration> &declarations, const QObject
int adj = -255;
hasFont = v.extractFont(&font, &adj);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
if (object && qstrcmp(object->metaObject()->className(), "QTipLabel") == 0)
palette = QToolTip::palette();
#endif
- for (int i = 0; i < declarations.count(); i++) {
+ for (int i = 0; i < declarations.size(); i++) {
const Declaration& decl = declarations.at(i);
if (decl.d->propertyId == BorderImage) {
QString uri;
@@ -999,7 +999,7 @@ QRenderRule::QRenderRule(const QVector<Declaration> &declarations, const QObject
int cuts[4];
decl.borderImageValue(&uri, cuts, &horizStretch, &vertStretch);
- if (uri.isEmpty() || uri == QLatin1String("none")) {
+ if (uri.isEmpty() || uri == "none"_L1) {
if (bd && bd->bi)
bd->bi->pixmap = QPixmap();
} else {
@@ -1021,38 +1021,66 @@ QRenderRule::QRenderRule(const QVector<Declaration> &declarations, const QObject
int role = decl.d->values.at(0).variant.toInt();
if (role >= Value_FirstColorRole && role <= Value_LastColorRole)
defaultBackground = palette.color((QPalette::ColorRole)(role-Value_FirstColorRole));
- } else if (decl.d->property.startsWith(QLatin1String("qproperty-"), Qt::CaseInsensitive)) {
+ } else if (decl.d->property.startsWith("qproperty-"_L1, Qt::CaseInsensitive)) {
// intentionally left blank...
} else if (decl.d->propertyId == UnknownProperty) {
bool knownStyleHint = false;
- for (int i = 0; i < numKnownStyleHints; i++) {
- QLatin1String styleHint(knownStyleHints[i]);
+ for (const auto sh : knownStyleHints) {
+ QLatin1StringView styleHint(sh);
if (decl.d->property.compare(styleHint) == 0) {
- QString hintName = QString(styleHint);
- QVariant hintValue;
- if (hintName.endsWith(QLatin1String("alignment"))) {
- hintValue = (int) decl.alignmentValue();
- } else if (hintName.endsWith(QLatin1String("color"))) {
- hintValue = (int) decl.colorValue().rgba();
- } else if (hintName.endsWith(QLatin1String("size"))) {
- hintValue = decl.sizeValue();
- } else if (hintName.endsWith(QLatin1String("icon"))) {
- hintValue = decl.iconValue();
- } else if (hintName == QLatin1String("button-layout")
- && decl.d->values.count() != 0 && decl.d->values.at(0).type == Value::String) {
- hintValue = subControlLayout(decl.d->values.at(0).variant.toString());
- } else {
- int integer;
- decl.intValue(&integer);
- hintValue = integer;
- }
- styleHints[decl.d->property] = hintValue;
- knownStyleHint = true;
- break;
+ QString hintName = QString(styleHint);
+ QVariant hintValue;
+ if (hintName.endsWith("alignment"_L1)) {
+ hintValue = (int) decl.alignmentValue();
+ } else if (hintName.endsWith("color"_L1)) {
+ hintValue = (int) decl.colorValue().rgba();
+ } else if (hintName.endsWith("size"_L1)) {
+ // Check only for the 'em' case
+ const QString valueString = decl.d->values.at(0).variant.toString();
+ const bool isEmSize = valueString.endsWith(u"em", Qt::CaseInsensitive);
+ if (isEmSize || valueString.endsWith(u"ex", Qt::CaseInsensitive)) {
+ // 1em == size of font; 1ex == xHeight of font
+ // See lengthValueFromData helper in qcssparser.cpp
+ QFont fontForSize(font);
+ // if no font is specified, then use the widget font if possible
+ if (const QWidget *widget; !hasFont && (widget = qobject_cast<const QWidget*>(object)))
+ fontForSize = widget->font();
+
+ const QFontMetrics fontMetrics(fontForSize);
+ qreal pixelSize = isEmSize ? fontMetrics.height() : fontMetrics.xHeight();
+
+ // Transform size according to the 'em'/'ex' value
+ qreal emexSize = {};
+ if (decl.realValue(&emexSize, isEmSize ? "em" : "ex") && emexSize > 0) {
+ pixelSize *= emexSize;
+ const QSizeF newSize(pixelSize, pixelSize);
+ decl.d->parsed = QVariant::fromValue<QSizeF>(newSize);
+ hintValue = newSize;
+ } else {
+ qWarning("Invalid '%s' size for %s. Skipping.",
+ isEmSize ? "em" : "ex", qPrintable(valueString));
+ }
+ } else {
+ // Normal case where we receive a 'px' or 'pt' unit
+ hintValue = decl.sizeValue();
+ }
+ } 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 == QCss::Value::String) {
+ hintValue = subControlLayout(decl.d->values.at(0).variant.toString().toLatin1());
+ } else {
+ int integer;
+ decl.intValue(&integer);
+ hintValue = integer;
+ }
+ styleHints[decl.d->property] = hintValue;
+ knownStyleHint = true;
+ break;
}
}
if (!knownStyleHint)
- qDebug("Unknown property %s", qPrintable(decl.d->property));
+ qWarning("Unknown property %s", qPrintable(decl.d->property));
}
}
@@ -1323,11 +1351,11 @@ QPainterPath QRenderRule::borderClip(QRect r)
path.lineTo(rect.x() + blr.width(), curY);
curX = rect.left() + borders[LeftEdge]/2.0;
- path.arcTo(curX, rect.bottom() - 2*blr.height() + borders[BottomEdge]/2,
+ path.arcTo(curX, rect.bottom() - 2*blr.height() + borders[BottomEdge]/2.0,
blr.width()*2 - borders[LeftEdge], blr.height()*2 - borders[BottomEdge], 270, -90);
path.lineTo(curX, rect.top() + tlr.height());
- path.arcTo(curX, rect.top() + borders[TopEdge]/2,
+ path.arcTo(curX, rect.top() + borders[TopEdge]/2.0,
tlr.width()*2 - borders[LeftEdge], tlr.height()*2 - borders[TopEdge], 180, -90);
path.closeSubpath();
@@ -1367,7 +1395,7 @@ void QRenderRule::drawBackground(QPainter *p, const QRect& rect, const QPoint& o
// ### fix for gradients
const QPainterPath &borderPath = borderClip(originRect(rect, origin));
if (!borderPath.isEmpty()) {
- // Drawn intead of being used as clipping path for better visual quality
+ // Drawn instead of being used as clipping path for better visual quality
bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
p->setRenderHint(QPainter::Antialiasing);
p->fillPath(borderPath, brush);
@@ -1432,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) {
@@ -1453,10 +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);
+ setDefault(p, cg, QPalette::PlaceholderText, placeholder, w);
}
if (pal->selectionBackground.style() != Qt::NoBrush)
p->setBrush(cg, QPalette::Highlight, pal->selectionBackground);
@@ -1464,6 +1507,10 @@ void QRenderRule::configurePalette(QPalette *p, QPalette::ColorGroup cg, const Q
p->setBrush(cg, QPalette::HighlightedText, pal->selectionForeground);
if (pal->alternateBackground.style() != Qt::NoBrush)
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
@@ -1507,51 +1554,64 @@ public:
if (isNullNode(node))
return QStringList();
const QMetaObject *metaObject = OBJECT_PTR(node)->metaObject();
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
- return QStringList(QLatin1String("QToolTip"));
+ return QStringList("QToolTip"_L1);
#endif
QStringList result;
do {
- result += QString::fromLatin1(metaObject->className()).replace(QLatin1Char(':'), QLatin1Char('-'));
+ result += QString::fromLatin1(metaObject->className()).replace(u':', u'-');
metaObject = metaObject->superClass();
} while (metaObject != nullptr);
return result;
}
- QString attribute(NodePtr node, const QString& name) const override
+ QString attributeValue(NodePtr node, const QCss::AttributeSelector& aSelector) const override
{
if (isNullNode(node))
return QString();
+ const QString &name = aSelector.name;
QHash<QString, QString> &cache = m_attributeCache[OBJECT_PTR(node)];
QHash<QString, QString>::const_iterator cacheIt = cache.constFind(name);
if (cacheIt != cache.constEnd())
return cacheIt.value();
+ QVariant value;
+ QString valueStr;
QObject *obj = OBJECT_PTR(node);
- QVariant value = obj->property(name.toLatin1());
- if (!value.isValid()) {
- if (name == QLatin1String("class")) {
- QString className = QString::fromLatin1(obj->metaObject()->className());
- if (className.contains(QLatin1Char(':')))
- className.replace(QLatin1Char(':'), QLatin1Char('-'));
- cache[name] = className;
- return className;
- } else if (name == QLatin1String("style")) {
- QWidget *w = qobject_cast<QWidget *>(obj);
- QStyleSheetStyle *proxy = w ? qt_styleSheet(w->style()) : nullptr;
- if (proxy) {
- QString styleName = QString::fromLatin1(proxy->baseStyle()->metaObject()->className());
- cache[name] = styleName;
- return styleName;
+ const int propertyIndex = obj->metaObject()->indexOfProperty(name.toLatin1());
+ if (propertyIndex == -1) {
+ value = obj->property(name.toLatin1()); // might be a dynamic property
+ if (!value.isValid()) {
+ if (name == "class"_L1) {
+ QString className = QString::fromLatin1(obj->metaObject()->className());
+ if (className.contains(u':'))
+ className.replace(u':', u'-');
+ valueStr = className;
+ } else if (name == "style"_L1) {
+ QWidget *w = qobject_cast<QWidget *>(obj);
+ QStyleSheetStyle *proxy = w ? qt_styleSheet(w->style()) : nullptr;
+ if (proxy)
+ valueStr = QString::fromLatin1(proxy->baseStyle()->metaObject()->className());
}
}
+ } else {
+ const QMetaProperty property = obj->metaObject()->property(propertyIndex);
+ value = property.read(obj);
+ // support Qt 5 selector syntax, which required the integer enum value
+ if (property.isEnumType()) {
+ bool isNumber;
+ aSelector.value.toInt(&isNumber);
+ if (isNumber)
+ value.convert(QMetaType::fromType<int>());
+ }
+ }
+ if (value.isValid()) {
+ valueStr = (value.userType() == QMetaType::QStringList
+ || value.userType() == QMetaType::QVariantList)
+ ? value.toStringList().join(u' ')
+ : value.toString();
}
- QString valueStr;
- if(value.type() == QVariant::StringList || value.type() == QVariant::List)
- valueStr = value.toStringList().join(QLatin1Char(' '));
- else
- valueStr = value.toString();
cache[name] = valueStr;
return valueStr;
}
@@ -1560,13 +1620,13 @@ public:
if (isNullNode(node))
return false;
const QMetaObject *metaObject = OBJECT_PTR(node)->metaObject();
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
- return nodeName == QLatin1String("QToolTip");
+ return nodeName == "QToolTip"_L1;
#endif
do {
- const ushort *uc = (const ushort *)nodeName.constData();
- const ushort *e = uc + nodeName.length();
+ 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;
@@ -1597,14 +1657,15 @@ private:
mutable QHash<const QObject *, QHash<QString, QString> > m_attributeCache;
};
-QVector<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const
+QList<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const
{
- QHash<const QObject *, QVector<StyleRule> >::const_iterator cacheIt = styleSheetCaches->styleRulesCache.constFind(obj);
+ QHash<const QObject *, QList<StyleRule>>::const_iterator cacheIt =
+ styleSheetCaches->styleRulesCache.constFind(obj);
if (cacheIt != styleSheetCaches->styleRulesCache.constEnd())
return cacheIt.value();
if (!initObject(obj)) {
- return QVector<StyleRule>();
+ return QList<StyleRule>();
}
QStyleSheetStyleSelector styleSelector;
@@ -1615,7 +1676,8 @@ QVector<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();
}
@@ -1626,7 +1688,7 @@ QVector<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const
QHash<const void *, StyleSheet>::const_iterator appCacheIt = styleSheetCaches->styleSheetCache.constFind(qApp);
if (appCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
QString ss = qApp->styleSheet();
- if (ss.startsWith(QLatin1String("file:///")))
+ if (ss.startsWith("file:///"_L1))
ss.remove(0, 8);
parser.init(ss, qApp->styleSheet() != ss);
if (Q_UNLIKELY(!parser.parse(&appSs)))
@@ -1640,7 +1702,7 @@ QVector<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const
styleSelector.styleSheets += appSs;
}
- QVector<QCss::StyleSheet> objectSs;
+ QList<QCss::StyleSheet> objectSs;
for (const QObject *o = obj; o; o = parentObject(o)) {
QString styleSheet = o->property("styleSheet").toString();
if (styleSheet.isEmpty())
@@ -1650,7 +1712,7 @@ QVector<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const
if (objCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
parser.init(styleSheet);
if (!parser.parse(&ss)) {
- parser.init(QLatin1String("* {") + styleSheet + QLatin1Char('}'));
+ parser.init("* {"_L1 + styleSheet + u'}');
if (Q_UNLIKELY(!parser.parse(&ss)))
qWarning() << "Could not parse stylesheet of object" << o;
}
@@ -1662,24 +1724,25 @@ QVector<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const
objectSs.append(ss);
}
- for (int i = 0; i < objectSs.count(); i++)
- objectSs[i].depth = objectSs.count() - i + 2;
+ for (int i = 0; i < objectSs.size(); i++)
+ objectSs[i].depth = objectSs.size() - i + 2;
styleSelector.styleSheets += objectSs;
StyleSelector::NodePtr n;
n.ptr = const_cast<QObject *>(obj);
- QVector<QCss::StyleRule> rules = styleSelector.styleRulesForNode(n);
+ QList<QCss::StyleRule> rules = styleSelector.styleRulesForNode(n);
styleSheetCaches->styleRulesCache.insert(obj, rules);
return rules;
}
/////////////////////////////////////////////////////////////////////////////////////////
// Rendering rules
-static QVector<Declaration> declarations(const QVector<StyleRule> &styleRules, const QString &part, quint64 pseudoClass = PseudoClass_Unspecified)
+static QList<Declaration> declarations(const QList<StyleRule> &styleRules, const QString &part,
+ quint64 pseudoClass = PseudoClass_Unspecified)
{
- QVector<Declaration> decls;
- for (int i = 0; i < styleRules.count(); i++) {
+ QList<Declaration> decls;
+ for (int i = 0; i < styleRules.size(); i++) {
const Selector& selector = styleRules.at(i).selectors.at(0);
// Rules with pseudo elements don't cascade. This is an intentional
// diversion for CSS
@@ -1786,9 +1849,9 @@ static void qt_check_if_internal_object(const QObject **obj, int *element)
Q_UNUSED(element);
#else
if (*obj && qstrcmp((*obj)->metaObject()->className(), "QDockWidgetTitleButton") == 0) {
- if ((*obj)->objectName() == QLatin1String("qt_dockwidget_closebutton")) {
+ if ((*obj)->objectName() == "qt_dockwidget_closebutton"_L1) {
*element = PseudoElement_DockWidgetCloseButton;
- } else if ((*obj)->objectName() == QLatin1String("qt_dockwidget_floatbutton")) {
+ } else if ((*obj)->objectName() == "qt_dockwidget_floatbutton"_L1) {
*element = PseudoElement_DockWidgetFloatButton;
}
*obj = (*obj)->parent();
@@ -1808,8 +1871,8 @@ QRenderRule QStyleSheetStyle::renderRule(const QObject *obj, int element, quint6
return QRenderRule();
quint64 stateMask = 0;
- const QVector<StyleRule> rules = styleRules(obj);
- for (int i = 0; i < rules.count(); i++) {
+ const QList<StyleRule> rules = styleRules(obj);
+ for (int i = 0; i < rules.size(); i++) {
const Selector& selector = rules.at(i).selectors.at(0);
quint64 negated = 0;
stateMask |= selector.pseudoClass(&negated);
@@ -1818,14 +1881,14 @@ QRenderRule QStyleSheetStyle::renderRule(const QObject *obj, int element, quint6
cacheIt = cache.constFind(state & stateMask);
if (cacheIt != cache.constEnd()) {
- const QRenderRule &newRule = cacheIt.value();
+ QRenderRule newRule = cacheIt.value();
cache[state] = newRule;
return newRule;
}
- const QString part = QLatin1String(knownPseudoElements[element].name);
- QVector<Declaration> decls = declarations(rules, part, state);
+ const QString part = QLatin1StringView(knownPseudoElements[element].name);
+ QList<Declaration> decls = declarations(rules, part, state);
QRenderRule newRule(decls, obj);
cache[state] = newRule;
if ((state & stateMask) != state)
@@ -1874,7 +1937,7 @@ QRenderRule QStyleSheetStyle::renderRule(const QObject *obj, const QStyleOption
break;
case PseudoElement_ToolButtonMenu:
case PseudoElement_ToolButtonMenuArrow:
- case PseudoElement_ToolButtonDownArrow:
+ case PseudoElement_ToolButtonMenuIndicator:
state |= complex->state & QStyle::State_MouseOver;
if (complex->state & QStyle::State_Sunken ||
complex->activeSubControls & QStyle::SC_ToolButtonMenu)
@@ -2085,6 +2148,14 @@ QRenderRule QStyleSheetStyle::renderRule(const QObject *obj, const QStyleOption
}
#endif
+#if QT_CONFIG(textedit)
+ else if (const QPlainTextEdit *edit = qobject_cast<const QPlainTextEdit *>(obj)) {
+ extraClass |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
+ }
+ else if (const QTextEdit *edit = qobject_cast<const QTextEdit *>(obj)) {
+ extraClass |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
+ }
+#endif
#if QT_CONFIG(lineedit)
// LineEdit sets Sunken flag to indicate Sunken frame (argh)
if (const QLineEdit *lineEdit = qobject_cast<const QLineEdit *>(obj)) {
@@ -2115,16 +2186,15 @@ bool QStyleSheetStyle::hasStyleRule(const QObject *obj, int part) const
if (!initObject(obj))
return false;
-
- const QVector<StyleRule> &rules = styleRules(obj);
+ const QList<StyleRule> &rules = styleRules(obj);
if (part == PseudoElement_None) {
bool result = obj && !rules.isEmpty();
cache[part] = result;
return result;
}
- QString pseudoElement = QLatin1String(knownPseudoElements[part].name);
- for (int i = 0; i < rules.count(); i++) {
+ auto pseudoElement = QLatin1StringView(knownPseudoElements[part].name);
+ for (int i = 0; i < rules.size(); i++) {
const Selector& selector = rules.at(i).selectors.at(0);
if (pseudoElement.compare(selector.pseudoElement(), Qt::CaseInsensitive) == 0) {
cache[part] = true;
@@ -2156,7 +2226,7 @@ static Origin defaultOrigin(int pe)
case PseudoElement_SpinBoxDownButton:
case PseudoElement_PushButtonMenuIndicator:
case PseudoElement_ComboBoxDropDown:
- case PseudoElement_ToolButtonDownArrow:
+ case PseudoElement_ToolButtonMenuIndicator:
case PseudoElement_MenuCheckMark:
case PseudoElement_MenuIcon:
case PseudoElement_MenuRightArrow:
@@ -2197,7 +2267,7 @@ static Qt::Alignment defaultPosition(int pe)
case PseudoElement_ScrollBarLast:
case PseudoElement_SpinBoxDownButton:
case PseudoElement_PushButtonMenuIndicator:
- case PseudoElement_ToolButtonDownArrow:
+ case PseudoElement_ToolButtonMenuIndicator:
return Qt::AlignRight | Qt::AlignBottom;
case PseudoElement_ScrollBarSubLine:
@@ -2217,6 +2287,9 @@ static Qt::Alignment defaultPosition(int pe)
case PseudoElement_SpinBoxDownArrow:
case PseudoElement_ComboBoxArrow:
case PseudoElement_DownArrow:
+ case PseudoElement_UpArrow:
+ case PseudoElement_LeftArrow:
+ case PseudoElement_RightArrow:
case PseudoElement_ToolButtonMenuArrow:
case PseudoElement_SliderGroove:
return Qt::AlignCenter;
@@ -2272,8 +2345,11 @@ QSize QStyleSheetStyle::defaultSize(const QWidget *w, QSize sz, const QRect& rec
case PseudoElement_ComboBoxArrow:
case PseudoElement_DownArrow:
+ case PseudoElement_UpArrow:
+ case PseudoElement_LeftArrow:
+ case PseudoElement_RightArrow:
case PseudoElement_ToolButtonMenuArrow:
- case PseudoElement_ToolButtonDownArrow:
+ case PseudoElement_ToolButtonMenuIndicator:
case PseudoElement_MenuRightArrow:
if (sz.width() == -1)
sz.setWidth(13);
@@ -2425,11 +2501,12 @@ static QWidget *embeddedWidget(QWidget *w)
}
/** \internal
- in case w is an embedded widget, return the container widget
- (i.e, the widget for which the rules actualy apply)
- (exemple, if w is a lineedit embedded in a combobox, return the combobox)
+ Returns the widget whose style rules apply to \a w.
+
+ When \a w is an embedded widget, this is the container widget.
+ For example, if w is a line edit embedded in a combobox, this returns the combobox.
+ When \a w is not embedded, this function return \a w itself.
- if w is not embedded, return w itself
*/
static QWidget *containerWidget(const QWidget *w)
{
@@ -2511,7 +2588,15 @@ static quint64 extendedPseudoClass(const QWidget *w)
pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
} else
#endif
- { } // required for the above ifdef'ery to work
+#if QT_CONFIG(textedit)
+ if (const QTextEdit *edit = qobject_cast<const QTextEdit *>(w)) {
+ pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
+ } else
+ if (const QPlainTextEdit *edit = qobject_cast<const QPlainTextEdit *>(w)) {
+ pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
+ } else
+#endif
+ {}
return pc;
}
@@ -2575,30 +2660,29 @@ void QStyleSheetStyle::setProperties(QWidget *w)
// Set value for each property in the order of property final occurrence
// since properties interact.
- const QVector<Declaration> decls = declarations(styleRules(w), QString());
- QVector<int> finals; // indices in reverse order of each property's final occurrence
+ const QList<Declaration> decls = declarations(styleRules(w), QString());
+ QList<int> finals; // indices in reverse order of each property's final occurrence
{
// scan decls for final occurrence of each "qproperty"
- QSet<const QString> propertySet;
- for (int i = decls.count() - 1; i >= 0; --i) {
+ QDuplicateTracker<QString> propertySet(decls.size());
+ for (int i = decls.size() - 1; i >= 0; --i) {
const QString property = decls.at(i).d->property;
- if (!property.startsWith(QLatin1String("qproperty-"), Qt::CaseInsensitive))
+ if (!property.startsWith("qproperty-"_L1, Qt::CaseInsensitive))
continue;
- if (!propertySet.contains(property)) {
- propertySet.insert(property);
+ if (!propertySet.hasSeen(property))
finals.append(i);
- }
}
}
- for (int i = finals.count() - 1; i >= 0; --i) {
+ for (int i = finals.size() - 1; i >= 0; --i) {
const Declaration &decl = decls.at(finals[i]);
- QString property = decl.d->property;
- property.remove(0, 10); // strip "qproperty-"
+ QStringView property = decl.d->property;
+ property = property.mid(10); // strip "qproperty-"
+ const auto propertyL1 = property.toLatin1();
const QMetaObject *metaObject = w->metaObject();
- int index = metaObject->indexOfProperty(property.toLatin1());
+ int index = metaObject->indexOfProperty(propertyL1);
if (Q_UNLIKELY(index == -1)) {
qWarning() << w << " does not have a property named " << property;
continue;
@@ -2610,22 +2694,25 @@ void QStyleSheetStyle::setProperties(QWidget *w)
}
QVariant v;
- const QVariant value = w->property(property.toLatin1());
- switch (value.type()) {
- case QVariant::Icon: v = decl.iconValue(); break;
- case QVariant::Image: v = QImage(decl.uriValue()); break;
- case QVariant::Pixmap: v = QPixmap(decl.uriValue()); break;
- case QVariant::Rect: v = decl.rectValue(); break;
- case QVariant::Size: v = decl.sizeValue(); break;
- case QVariant::Color: v = decl.colorValue(); break;
- case QVariant::Brush: v = decl.brushValue(); break;
+ const QVariant value = w->property(propertyL1);
+ switch (value.userType()) {
+ case QMetaType::QIcon: v = decl.iconValue(); break;
+ case QMetaType::QImage: v = QImage(decl.uriValue()); break;
+ case QMetaType::QPixmap: v = QPixmap(decl.uriValue()); break;
+ case QMetaType::QRect: v = decl.rectValue(); break;
+ case QMetaType::QSize: v = decl.sizeValue(); break;
+ case QMetaType::QColor: v = decl.colorValue(); break;
+ case QMetaType::QBrush: v = decl.brushValue(); break;
#ifndef QT_NO_SHORTCUT
- case QVariant::KeySequence: v = QKeySequence(decl.d->values.at(0).variant.toString()); break;
+ case QMetaType::QKeySequence: v = QKeySequence(decl.d->values.at(0).variant.toString()); break;
#endif
default: v = decl.d->values.at(0).variant; break;
}
- w->setProperty(property.toLatin1(), v);
+ if (propertyL1 == QByteArrayView("styleSheet") && value == v)
+ continue;
+
+ w->setProperty(propertyL1, v);
}
}
@@ -2663,13 +2750,13 @@ void QStyleSheetStyle::setPalette(QWidget *w)
rule.configurePalette(&p, map[i].group, ew, ew != w);
}
- if (!useStyleSheetPropagationInWidgetStyles || p.resolve() != 0) {
+ if (!useStyleSheetPropagationInWidgetStyles || p.resolveMask() != 0) {
QPalette wp = w->palette();
- styleSheetCaches->customPaletteWidgets.insert(w, {wp, p.resolve()});
+ styleSheetCaches->customPaletteWidgets.insert(w, {wp, p.resolveMask()});
if (useStyleSheetPropagationInWidgetStyles) {
p = p.resolve(wp);
- p.resolve(p.resolve() | wp.resolve());
+ p.setResolveMask(p.resolveMask() | wp.resolveMask());
}
w->setPalette(p);
@@ -2745,7 +2832,7 @@ static void updateObjects(const QList<const QObject *>& objects)
QCoreApplication::sendEvent(widget, &event);
QList<const QObject *> children;
children.reserve(widget->children().size() + 1);
- for (auto child: qAsConst(widget->children()))
+ for (auto child: std::as_const(widget->children()))
children.append(child);
updateObjects(children);
}
@@ -2813,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;
}
@@ -2827,7 +2916,7 @@ void QStyleSheetStyle::polish(QWidget *w)
if (styleSheetCaches->styleRulesCache.contains(w)) {
// the widget accessed its style pointer before polish (or repolish)
- // (exemple: the QAbstractSpinBox constructor ask for the stylehint)
+ // (example: the QAbstractSpinBox constructor ask for the stylehint)
styleSheetCaches->styleRulesCache.remove(w);
styleSheetCaches->hasStyleRuleCache.remove(w);
styleSheetCaches->renderRulesCache.remove(w);
@@ -2839,14 +2928,15 @@ void QStyleSheetStyle::polish(QWidget *w)
setPalette(w);
//set the WA_Hover attribute if one of the selector depends of the hover state
- QVector<StyleRule> rules = styleRules(w);
- for (int i = 0; i < rules.count(); i++) {
+ QList<StyleRule> rules = styleRules(w);
+ for (int i = 0; i < rules.size(); i++) {
const Selector& selector = rules.at(i).selectors.at(0);
quint64 negated = 0;
quint64 cssClass = selector.pseudoClass(&negated);
if ( cssClass & PseudoClass_Hover || negated & PseudoClass_Hover) {
w->setAttribute(Qt::WA_Hover);
embeddedWidget(w)->setAttribute(Qt::WA_Hover);
+ embeddedWidget(w)->setMouseTracking(true);
}
}
@@ -2856,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
@@ -2906,6 +2996,12 @@ void QStyleSheetStyle::polish(QWidget *w)
if (!rule.hasBackground() || rule.background()->isTransparent() || rule.hasBox()
|| (!rule.hasNativeBorder() && !rule.border()->isOpaque()))
w->setAttribute(Qt::WA_OpaquePaintEvent, false);
+ if (rule.hasBox() || !rule.hasNativeBorder()
+#if QT_CONFIG(pushbutton)
+ || (qobject_cast<QPushButton *>(w))
+#endif
+ )
+ w->setAttribute(Qt::WA_MacShowFocusRect, false);
}
}
@@ -2923,7 +3019,7 @@ void QStyleSheetStyle::repolish(QWidget *w)
{
QList<const QObject *> children;
children.reserve(w->children().size() + 1);
- for (auto child: qAsConst(w->children()))
+ for (auto child: std::as_const(w->children()))
children.append(child);
children.append(w);
styleSheetCaches->styleSheetCache.remove(w);
@@ -2956,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);
@@ -2978,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
{
@@ -3191,8 +3277,39 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
rule.configurePalette(&toolOpt.palette, QPalette::ButtonText, QPalette::Button);
toolOpt.font = rule.font.resolve(toolOpt.font);
toolOpt.rect = rule.borderRect(opt->rect);
- bool customArrow = (tool->features & (QStyleOptionToolButton::HasMenu | QStyleOptionToolButton::MenuButtonPopup));
- bool customDropDown = tool->features & QStyleOptionToolButton::MenuButtonPopup;
+ const auto customArrowElement = [tool]{
+ switch (tool->arrowType) {
+ case Qt::DownArrow: return PseudoElement_DownArrow;
+ case Qt::UpArrow: return PseudoElement_UpArrow;
+ case Qt::LeftArrow: return PseudoElement_LeftArrow;
+ case Qt::RightArrow: return PseudoElement_RightArrow;
+ default: break;
+ }
+ return PseudoElement_None;
+ };
+ // if arrow/menu/indicators are requested, either draw them using the available rule,
+ // or let the base style draw them; but not both
+ const bool drawArrow = tool->features & QStyleOptionToolButton::Arrow;
+ bool customArrow = drawArrow && hasStyleRule(w, customArrowElement());
+ if (customArrow) {
+ toolOpt.features &= ~QStyleOptionToolButton::Arrow;
+ toolOpt.text = QString(); // we need to draw the arrow and the text ourselves
+ }
+ bool drawDropDown = tool->features & QStyleOptionToolButton::MenuButtonPopup;
+ bool customDropDown = drawDropDown && hasStyleRule(w, PseudoElement_ToolButtonMenu);
+ bool customDropDownArrow = false;
+ bool drawMenuIndicator = tool->features & QStyleOptionToolButton::HasMenu;
+ if (customDropDown) {
+ toolOpt.subControls &= ~QStyle::SC_ToolButtonMenu;
+ customDropDownArrow = hasStyleRule(w, PseudoElement_ToolButtonMenuArrow);
+ if (customDropDownArrow)
+ toolOpt.features &= ~(QStyleOptionToolButton::Menu | QStyleOptionToolButton::HasMenu);
+ }
+ const bool customMenuIndicator = (!drawDropDown && drawMenuIndicator)
+ && hasStyleRule(w, PseudoElement_ToolButtonMenuIndicator);
+ if (customMenuIndicator)
+ toolOpt.features &= ~QStyleOptionToolButton::HasMenu;
+
if (rule.hasNativeBorder()) {
if (tool->subControls & SC_ToolButton) {
//in some case (eg. the button is "auto raised") the style doesn't draw the background
@@ -3206,21 +3323,23 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
if (!(bflags & (State_Sunken | State_On | State_Raised)))
rule.drawBackground(p, toolOpt.rect);
}
- customArrow = customArrow && hasStyleRule(w, PseudoElement_ToolButtonDownArrow);
- if (customArrow)
- toolOpt.features &= ~QStyleOptionToolButton::HasMenu;
- customDropDown = customDropDown && hasStyleRule(w, PseudoElement_ToolButtonMenu);
- if (customDropDown)
- toolOpt.subControls &= ~QStyle::SC_ToolButtonMenu;
-
- if (rule.baseStyleCanDraw() && !(tool->features & QStyleOptionToolButton::Arrow)) {
- baseStyle()->drawComplexControl(cc, &toolOpt, p, w);
- } else {
- QWindowsStyle::drawComplexControl(cc, &toolOpt, p, w);
- }
- if (!customArrow && !customDropDown)
- return;
+ QStyleOptionToolButton nativeToolOpt(toolOpt);
+ // don't draw natively if we have a custom rule for menu indicators and/or buttons
+ if (customMenuIndicator)
+ nativeToolOpt.features &= ~(QStyleOptionToolButton::Menu | QStyleOptionToolButton::HasMenu);
+ if (customDropDown || customDropDownArrow)
+ nativeToolOpt.features &= ~(QStyleOptionToolButton::Menu | QStyleOptionToolButton::HasMenu | QStyleOptionToolButton::MenuButtonPopup);
+ // Let base or windows style draw the button, which will include the menu-button
+ if (rule.baseStyleCanDraw() && !(tool->features & QStyleOptionToolButton::Arrow))
+ baseStyle()->drawComplexControl(cc, &nativeToolOpt, p, w);
+ else
+ QWindowsStyle::drawComplexControl(cc, &nativeToolOpt, p, w);
+ // if we did draw natively, don't draw custom
+ if (nativeToolOpt.features & (QStyleOptionToolButton::Menu | QStyleOptionToolButton::HasMenu))
+ drawMenuIndicator = false;
+ if (nativeToolOpt.features & QStyleOptionToolButton::MenuButtonPopup && !customDropDownArrow)
+ drawDropDown = false;
} else {
rule.drawRule(p, opt->rect);
toolOpt.rect = rule.contentsRect(opt->rect);
@@ -3229,33 +3348,78 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
drawControl(CE_ToolButtonLabel, &toolOpt, p, w);
}
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
- QRect r = subControlRect(CC_ToolButton, opt, QStyle::SC_ToolButtonMenu, w);
- if (customDropDown) {
+ const QRect cr = toolOpt.rect;
+ // Draw DropDownButton unless drawn before
+ if (drawDropDown) {
if (opt->subControls & QStyle::SC_ToolButtonMenu) {
+ QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
+ QRect menuButtonRect = subControlRect(CC_ToolButton, opt, QStyle::SC_ToolButtonMenu, w);
if (subRule.hasDrawable()) {
- subRule.drawRule(p, r);
+ subRule.drawRule(p, menuButtonRect);
} else {
- toolOpt.rect = r;
+ toolOpt.rect = menuButtonRect;
baseStyle()->drawPrimitive(PE_IndicatorButtonDropDown, &toolOpt, p, w);
}
+
+ if (customDropDownArrow || drawMenuIndicator) {
+ QRenderRule arrowRule = renderRule(w, opt, PseudoElement_ToolButtonMenuArrow);
+ QRect arrowRect = arrowRule.hasGeometry()
+ ? positionRect(w, arrowRule, PseudoElement_ToolButtonMenuArrow, menuButtonRect, toolOpt.direction)
+ : arrowRule.contentsRect(menuButtonRect);
+ if (arrowRule.hasDrawable()) {
+ arrowRule.drawRule(p, arrowRect);
+ } else {
+ toolOpt.rect = arrowRect;
+ baseStyle()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &toolOpt, p, w);
+ }
+ }
}
- }
+ } else if (drawMenuIndicator) {
+ QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenuIndicator);
- if (customArrow) {
- QRenderRule subRule2 = customDropDown ? renderRule(w, opt, PseudoElement_ToolButtonMenuArrow)
- : renderRule(w, opt, PseudoElement_ToolButtonDownArrow);
- QRect r2 = customDropDown
- ? positionRect(w, subRule, subRule2, PseudoElement_ToolButtonMenuArrow, r, opt->direction)
- : positionRect(w, rule, subRule2, PseudoElement_ToolButtonDownArrow, opt->rect, opt->direction);
- if (subRule2.hasDrawable()) {
- subRule2.drawRule(p, r2);
+ // content padding does not impact the indicator, so use the original rect to
+ // calculate position of the sub element within the toplevel rule
+ QRect r = positionRect(w, rule, subRule, PseudoElement_ToolButtonMenuIndicator, opt->rect, toolOpt.direction);
+ if (subRule.hasDrawable()) {
+ subRule.drawRule(p, r);
} else {
- toolOpt.rect = r2;
+ toolOpt.rect = r;
baseStyle()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &toolOpt, p, w);
}
}
+ toolOpt.rect = cr;
+
+ // If we don't have a custom arrow, then the arrow will have been rendered
+ // already by the base style when drawing the label.
+ if (customArrow) {
+ const auto arrowElement = customArrowElement();
+ QRenderRule subRule = renderRule(w, opt, arrowElement);
+ QRect arrowRect = subRule.hasGeometry() ? positionRect(w, subRule, arrowElement, toolOpt.rect, toolOpt.direction)
+ : subRule.contentsRect(toolOpt.rect);
+ switch (toolOpt.toolButtonStyle) {
+ case Qt::ToolButtonIconOnly:
+ break;
+ case Qt::ToolButtonTextOnly:
+ case Qt::ToolButtonTextBesideIcon:
+ case Qt::ToolButtonTextUnderIcon: {
+ // The base style needs to lay out the contents and will render the styled
+ // arrow icons, unless the geometry is defined in the style sheet.
+ toolOpt.text = tool->text;
+ if (!subRule.hasGeometry())
+ toolOpt.features |= QStyleOptionToolButton::Arrow;
+ drawControl(CE_ToolButtonLabel, &toolOpt, p, w);
+ if (!subRule.hasGeometry())
+ return;
+ break;
+ }
+ case Qt::ToolButtonFollowStyle:
+ // QToolButton handles this, so must never happen
+ Q_ASSERT(false);
+ break;
+ }
+ subRule.drawRule(p, arrowRect);
+ }
return;
}
break;
@@ -3337,14 +3501,14 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
if (hasStyleRule(w, PseudoElement_MdiCloseButton)
|| hasStyleRule(w, PseudoElement_MdiNormalButton)
|| hasStyleRule(w, PseudoElement_MdiMinButton)) {
- QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
+ QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
if (layout.isEmpty())
- layout = subControlLayout(QLatin1String("mNX"));
+ layout = subControlLayout("mNX");
QStyleOptionComplex optCopy(*opt);
optCopy.subControls = { };
- for (int i = 0; i < layout.count(); 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;
@@ -3375,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];
@@ -3385,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);
@@ -3396,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);
}
}
@@ -3406,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,
@@ -3423,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);
}
@@ -3447,6 +3611,37 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
baseStyle()->drawComplexControl(cc, opt, p, w);
}
+void QStyleSheetStyle::renderMenuItemIcon(const QStyleOptionMenuItem *mi, QPainter *p, const QWidget *w,
+ const QRect &rect, QRenderRule &subRule) const
+{
+ const QIcon::Mode mode = mi->state & QStyle::State_Enabled
+ ? (mi->state & QStyle::State_Selected ? QIcon::Active : QIcon::Normal)
+ : QIcon::Disabled;
+ const bool checked = mi->checkType != QStyleOptionMenuItem::NotCheckable && mi->checked;
+ 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();
+ QRenderRule iconRule = renderRule(w, mi, PseudoElement_MenuIcon);
+ if (!iconRule.hasGeometry()) {
+ iconRule.geo = new QStyleSheetGeometryData(pixw, pixh, pixw, pixh, -1, -1);
+ } else {
+ iconRule.geo->width = pixw;
+ iconRule.geo->height = pixh;
+ }
+ QRect iconRect = positionRect(w, subRule, iconRule, PseudoElement_MenuIcon, rect, mi->direction);
+ if (mi->direction == Qt::LeftToRight)
+ iconRect.moveLeft(iconRect.left());
+ else
+ iconRect.moveRight(iconRect.right());
+ iconRule.drawRule(p, iconRect);
+ QRect pmr(0, 0, pixw, pixh);
+ pmr.moveCenter(iconRect.center());
+ p->drawPixmap(pmr.topLeft(), pixmap);
+}
+
void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p,
const QWidget *w) const
{
@@ -3511,7 +3706,8 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
if (btn->features & QStyleOptionButton::HasMenu) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_PushButtonMenuIndicator);
- QRect ir = positionRect(w, rule, subRule, PseudoElement_PushButtonMenuIndicator, opt->rect, opt->direction);
+ QRect ir = positionRect(w, rule, subRule, PseudoElement_PushButtonMenuIndicator,
+ baseStyle()->subElementRect(SE_PushButtonBevel, btn, w), opt->direction);
if (subRule.hasDrawable()) {
subRule.drawRule(p, ir);
} else {
@@ -3536,7 +3732,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
QRect textRect = button->rect;
const uint horizontalAlignMask = Qt::AlignHCenter | Qt::AlignLeft | Qt::AlignRight;
- const uint verticalAlignMask = Qt::AlignVCenter | Qt::AlignTop | Qt::AlignLeft;
+ const uint verticalAlignMask = Qt::AlignVCenter | Qt::AlignTop | Qt::AlignBottom;
if (rule.hasPosition() && rule.position()->textAlignment != 0) {
Qt::Alignment textAlignment = rule.position()->textAlignment;
@@ -3559,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;
@@ -3726,42 +3923,18 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
}
mi.palette.setBrush(QPalette::HighlightedText, mi.palette.brush(QPalette::ButtonText));
- bool checkable = mi.checkType != QStyleOptionMenuItem::NotCheckable;
- bool checked = checkable ? mi.checked : false;
-
- bool dis = !(opt->state & QStyle::State_Enabled),
- act = opt->state & QStyle::State_Selected;
-
int textRectOffset = m->maxIconWidth;
if (!mi.icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
- if (act && !dis)
- mode = QIcon::Active;
- const QPixmap pixmap(mi.icon.pixmap(pixelMetric(PM_SmallIconSize), mode, checked ? QIcon::On : QIcon::Off));
- const int pixw = pixmap.width() / pixmap.devicePixelRatio();
- const int pixh = pixmap.height() / pixmap.devicePixelRatio();
- QRenderRule iconRule = renderRule(w, opt, PseudoElement_MenuIcon);
- if (!iconRule.hasGeometry()) {
- iconRule.geo = new QStyleSheetGeometryData(pixw, pixh, pixw, pixh, -1, -1);
- } else {
- iconRule.geo->width = pixw;
- iconRule.geo->height = pixh;
- }
- QRect iconRect = positionRect(w, subRule, iconRule, PseudoElement_MenuIcon, opt->rect, opt->direction);
- if (opt->direction == Qt::LeftToRight)
- iconRect.moveLeft(iconRect.left());
- else
- iconRect.moveRight(iconRect.right());
- iconRule.drawRule(p, iconRect);
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(iconRect.center());
- p->drawPixmap(pmr.topLeft(), pixmap);
- } else if (checkable) {
- QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
+ renderMenuItemIcon(&mi, p, w, opt->rect, subRule);
+ } else if (mi.menuHasCheckableItems) {
+ const bool checkable = mi.checkType != QStyleOptionMenuItem::NotCheckable;
+ const bool checked = checkable ? mi.checked : false;
+
+ const QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
const QRect cmRect = positionRect(w, subRule, subSubRule, PseudoElement_MenuCheckMark, opt->rect, opt->direction);
- if (subSubRule.hasDrawable() || checked) {
+ if (checkable && (subSubRule.hasDrawable() || checked)) {
QStyleOptionMenuItem newMi = mi;
- if (!dis)
+ if (opt->state & QStyle::State_Enabled)
newMi.state |= State_Enabled;
if (mi.checked)
newMi.state |= State_On;
@@ -3773,16 +3946,16 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
QRect textRect = subRule.contentsRect(opt->rect);
textRect.setLeft(textRect.left() + textRectOffset);
- textRect.setWidth(textRect.width() - mi.tabWidth);
+ textRect.setWidth(textRect.width() - mi.reservedShortcutWidth);
const QRect vTextRect = visualRect(opt->direction, m->rect, textRect);
- QStringRef s(&mi.text);
+ QStringView s(mi.text);
p->setPen(mi.palette.buttonText().color());
if (!s.isEmpty()) {
int text_flags = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
if (!styleHint(SH_UnderlineShortcut, &mi, w))
text_flags |= Qt::TextHideMnemonic;
- int t = s.indexOf(QLatin1Char('\t'));
+ qsizetype t = s.indexOf(u'\t');
if (t >= 0) {
QRect vShortcutRect = visualRect(opt->direction, mi.rect,
QRect(textRect.topRight(), QPoint(mi.rect.right(), textRect.bottom())));
@@ -3798,11 +3971,22 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
mi.rect = positionRect(w, subRule, subRule2, PseudoElement_MenuRightArrow, opt->rect, mi.direction);
drawPrimitive(arrow, &mi, p, w);
}
+ } else if (!mi.icon.isNull() && hasStyleRule(w, PseudoElement_MenuIcon)) {
+ // we wouldn't be here if the item itself would be styled, so now we only want
+ // the text from the default style, and then draw the icon ourselves.
+ QStyleOptionMenuItem newMi = mi;
+ newMi.icon = {};
+ newMi.checkType = QStyleOptionMenuItem::NotCheckable;
+ if (rule.baseStyleCanDraw() && subRule.baseStyleCanDraw())
+ baseStyle()->drawControl(ce, &newMi, p, w);
+ else
+ ParentStyle::drawControl(ce, &newMi, p, w);
+ renderMenuItemIcon(&mi, p, w, opt->rect, subRule);
} else if (hasStyleRule(w, PseudoElement_MenuCheckMark) || hasStyleRule(w, PseudoElement_MenuRightArrow)) {
QWindowsStyle::drawControl(ce, &mi, p, w);
if (mi.checkType != QStyleOptionMenuItem::NotCheckable && !mi.checked) {
// We have a style defined, but QWindowsStyle won't draw anything if not checked.
- // So we mimick what QWindowsStyle would do.
+ // So we mimic what QWindowsStyle would do.
int checkcol = qMax<int>(mi.maxIconWidth, QWindowsStylePrivate::windowsCheckMarkWidth);
QRect vCheckRect = visualRect(opt->direction, mi.rect, QRect(mi.rect.x(), mi.rect.y(), checkcol, mi.rect.height()));
if (mi.state.testFlag(State_Enabled) && mi.state.testFlag(State_Selected)) {
@@ -3874,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,
@@ -3890,7 +4075,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
if (!cb->currentText.isEmpty() && !cb->editable) {
QPalette styledPalette(cb->palette);
rule.configurePalette(&styledPalette, QPalette::Text, QPalette::Base);
- drawItemText(p, editRect.adjusted(0, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, styledPalette,
+ drawItemText(p, editRect.adjusted(0, 0, 0, 0), cb->textAlignment, styledPalette,
cb->state & State_Enabled, cb->currentText, QPalette::Text);
}
p->restore();
@@ -3905,7 +4090,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
ParentStyle::drawControl(ce, opt, p, w);
return;
}
- if(hasStyleRule(w, PseudoElement_HeaderViewSection)) {
+ if (hasStyleRule(w, PseudoElement_HeaderViewSection)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
if (!subRule.hasNativeBorder() || !subRule.baseStyleCanDraw()
|| subRule.hasBackground() || subRule.hasPalette() || subRule.hasFont || subRule.hasBorder()) {
@@ -3935,8 +4120,23 @@ 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)) {
+ 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) {
QFont oldFont = p->font();
@@ -3977,7 +4177,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
qint64 minimum = qint64(pb->minimum);
qint64 maximum = qint64(pb->maximum);
qint64 progress = qint64(pb->progress);
- bool vertical = (pb->orientation == Qt::Vertical);
+ bool vertical = !(pb->state & QStyle::State_Horizontal);
bool inverted = pb->invertedAppearance;
QTransform m;
@@ -4035,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();
@@ -4075,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();
@@ -4164,15 +4364,47 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
case CE_ItemViewItem:
if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
- if (subRule.hasDrawable() || hasStyleRule(w, PseudoElement_Indicator)) {
- QStyleOptionViewItem optCopy(*vopt);
+ QStyleOptionViewItem optCopy(*vopt);
+ if (subRule.hasDrawable()) {
subRule.configurePalette(&optCopy.palette, vopt->state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text,
vopt->state & QStyle::State_Selected ? QPalette::Highlight : QPalette::Base);
QWindowsStyle::drawControl(ce, &optCopy, p, w);
} else {
- QStyleOptionViewItem voptCopy(*vopt);
- subRule.configurePalette(&voptCopy.palette, QPalette::Text, QPalette::NoRole);
- baseStyle()->drawControl(ce, &voptCopy, p, w);
+ p->save();
+ if (hasStyleRule(w, PseudoElement_Indicator)) {
+ // there is a rule for the indicator, but no rule for the item itself (otherwise
+ // the previous path would have been taken); only draw the indicator using the
+ // rule (via QWindows/QCommonStyle), then let the base style handle the rest.
+ QStyleOptionViewItem optIndicator(*vopt);
+ subRule.configurePalette(&optIndicator.palette,
+ vopt->state & QStyle::State_Selected
+ ? QPalette::HighlightedText
+ : QPalette::Text,
+ vopt->state & QStyle::State_Selected
+ ? QPalette::Highlight
+ : QPalette::Base);
+ // 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,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 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))
+ - crStyle.united(crBase);
+ p->setClipRegion(clipRegion);
+ }
+ subRule.configurePalette(&optCopy.palette, QPalette::Text, QPalette::NoRole);
+ baseStyle()->drawControl(ce, &optCopy, p, w);
+ p->restore();
}
return;
}
@@ -4190,6 +4422,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
case CE_TabBarTabLabel:
case CE_TabBarTabShape:
if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
+ const auto foregroundRole = w ? w->foregroundRole() : QPalette::WindowText;
QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
QRect r = positionRect(w, subRule, PseudoElement_TabBarTab, opt->rect, opt->direction);
if (ce == CE_TabBarTabShape && subRule.hasDrawable() && tab->shape < QTabBar::TriangularNorth) {
@@ -4197,7 +4430,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
return;
}
QStyleOptionTab tabCopy(*tab);
- subRule.configurePalette(&tabCopy.palette, QPalette::WindowText, QPalette::Base);
+ subRule.configurePalette(&tabCopy.palette, foregroundRole, QPalette::Base);
QFont oldFont = p->font();
if (subRule.hasFont)
p->setFont(subRule.font.resolve(p->font()));
@@ -4255,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);
@@ -4417,14 +4650,16 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op
case PE_PanelLineEdit:
if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
-#if QT_CONFIG(spinbox)
- if (w && qobject_cast<const QAbstractSpinBox *>(w->parentWidget())) {
- QRenderRule spinboxRule = renderRule(w->parentWidget(), opt);
- if (!spinboxRule.hasNativeBorder() || !spinboxRule.baseStyleCanDraw())
- return;
- rule = spinboxRule;
+ // Fall back to container widget's render rule
+ if (w) {
+ if (QWidget *container = containerWidget(w); container != w) {
+ QRenderRule containerRule = renderRule(container, opt);
+ if (!containerRule.hasNativeBorder() || !containerRule.baseStyleCanDraw())
+ return;
+ rule = containerRule;
+ }
}
-#endif
+
if (rule.hasNativeBorder()) {
QStyleOptionFrame frmOpt(*frm);
rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
@@ -4473,7 +4708,7 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op
Q_FALLTHROUGH();
case PE_PanelMenu:
case PE_PanelStatusBar:
- if(rule.hasDrawable()) {
+ if (rule.hasDrawable()) {
rule.drawRule(p, opt->rect);
return;
}
@@ -4533,10 +4768,7 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op
if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TreeViewBranch);
if (subRule.hasDrawable()) {
- if ((vopt->state & QStyle::State_Selected) && vopt->showDecorationSelected)
- p->fillRect(vopt->rect, vopt->palette.highlight());
- else if (vopt->features & QStyleOptionViewItem::Alternate)
- p->fillRect(vopt->rect, vopt->palette.alternateBase());
+ proxy()->drawPrimitive(PE_PanelItemViewRow, vopt, p, w);
subRule.drawRule(p, opt->rect);
} else {
baseStyle()->drawPrimitive(pe, vopt, p, w);
@@ -4604,6 +4836,17 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op
pseudoElement = PseudoElement_DockWidgetSeparator;
break;
+ case PE_PanelItemViewRow:
+ // For compatibility reasons, QTreeView draws different parts of
+ // the background of an item row separately, before calling the
+ // delegate to draw the item. The row background of an item is
+ // however not separately styleable through a style sheet, but
+ // only indirectly through the background of the item. To get the
+ // same background for all parts drawn by QTreeView, we have to
+ // use the background rule for the item here.
+ if (renderRule(w, opt, PseudoElement_ViewItem).hasBackground())
+ pseudoElement = PseudoElement_ViewItem;
+ break;
case PE_PanelItemViewItem:
pseudoElement = PseudoElement_ViewItem;
break;
@@ -4630,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:
@@ -4648,7 +4892,7 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op
}
if (baseStyle()->property("_q_styleSheetRealCloseButton").toBool())
- baseStyle()->setProperty("_q_styleSheetRealCloseButton", QVariant(QVariant::Invalid));
+ baseStyle()->setProperty("_q_styleSheetRealCloseButton", QVariant());
}
QPixmap QStyleSheetStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap& pixmap,
@@ -4731,8 +4975,19 @@ int QStyleSheetStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const
case PM_MenuButtonIndicator:
#if QT_CONFIG(toolbutton)
// QToolButton adds this directly to the width
- if (qobject_cast<const QToolButton *>(w) && (rule.hasBox() || !rule.hasNativeBorder()))
- return 0;
+ if (qobject_cast<const QToolButton *>(w)) {
+ if (rule.hasBox() || !rule.hasNativeBorder())
+ return 0;
+ if (const auto *tbOpt = qstyleoption_cast<const QStyleOptionToolButton*>(opt)) {
+ if (tbOpt->features & QStyleOptionToolButton::MenuButtonPopup)
+ subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
+ else
+ subRule = renderRule(w, opt, PseudoElement_ToolButtonMenuIndicator);
+ if (subRule.hasContentsSize())
+ return subRule.size().width();
+ }
+ break;
+ }
#endif
subRule = renderRule(w, opt, PseudoElement_PushButtonMenuIndicator);
if (subRule.hasContentsSize())
@@ -4874,11 +5129,17 @@ int QStyleSheetStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const
break;
case PM_ScrollView_ScrollBarSpacing:
- if(!rule.hasNativeBorder() || rule.hasBox())
+ if (!rule.hasNativeBorder() || rule.hasBox())
+ return 0;
+ break;
+
+ case PM_ScrollView_ScrollBarOverlap:
+ if (!proxy()->styleHint(SH_ScrollBar_Transient, opt, w))
return 0;
break;
#endif // QT_CONFIG(scrollbar)
+
case PM_ProgressBarChunkWidth:
subRule = renderRule(w, opt, PseudoElement_ProgressBarChunk);
if (subRule.hasContentsSize()) {
@@ -4951,9 +5212,8 @@ int QStyleSheetStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const
case PM_MessageBoxIconSize:
case PM_ButtonIconSize:
case PM_SmallIconSize:
- if (rule.hasStyleHint(QLatin1String("icon-size"))) {
- return rule.styleHint(QLatin1String("icon-size")).toSize().width();
- }
+ if (rule.hasStyleHint("icon-size"_L1))
+ return rule.styleHint("icon-size"_L1).toSize().width();
break;
case PM_DockWidgetTitleMargin: {
@@ -5041,7 +5301,7 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
case CT_ComboBox:
case CT_PushButton:
if (rule.hasBox() || !rule.hasNativeBorder()) {
- if(ct == CT_ComboBox) {
+ if (ct == CT_ComboBox) {
//add some space for the drop down.
QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
QRect comboRect = positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown, opt->rect, opt->direction);
@@ -5085,8 +5345,17 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
}
return subRule.size(sz);
}
- return subRule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
- : QWindowsStyle::sizeFromContents(ct, opt, sz, w);
+ sz = subRule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
+ : QWindowsStyle::sizeFromContents(ct, opt, sz, w);
+ if (hasStyleRule(w, PseudoElement_HeaderViewDownArrow)
+ || hasStyleRule(w, PseudoElement_HeaderViewUpArrow)) {
+ const QRect arrowRect = subElementRect(SE_HeaderArrow, opt, w);
+ if (hdr->orientation == Qt::Horizontal)
+ sz.rwidth() += arrowRect.width();
+ else
+ sz.rheight() += arrowRect.height();
+ }
+ return sz;
}
}
break;
@@ -5137,20 +5406,21 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
}
if ((pe == PseudoElement_Item) && (subRule.hasBox() || subRule.hasBorder() || subRule.hasFont)) {
QSize sz(csz);
- if (mi->text.contains(QLatin1Char('\t')))
+ if (mi->text.contains(u'\t'))
sz.rwidth() += 12; //as in QCommonStyle
- bool checkable = mi->checkType != QStyleOptionMenuItem::NotCheckable;
if (!mi->icon.isNull()) {
const int pmSmall = pixelMetric(PM_SmallIconSize);
const QSize pmSize = mi->icon.actualSize(QSize(pmSmall, pmSmall));
- sz.rwidth() += pmSize.width() + 4;
- } else if (checkable) {
+ sz.rwidth() += std::max(mi->maxIconWidth, pmSize.width()) + 4;
+ } else if (mi->menuHasCheckableItems) {
QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
QRect checkmarkRect = positionRect(w, subRule, subSubRule, PseudoElement_MenuCheckMark, opt->rect, opt->direction);
sz.rwidth() += std::max(mi->maxIconWidth, checkmarkRect.width()) + 4;
+ } else {
+ sz.rwidth() += mi->maxIconWidth;
}
if (subRule.hasFont) {
- QFontMetrics fm(subRule.font);
+ QFontMetrics fm(subRule.font.resolve(mi->font));
const QRect r = fm.boundingRect(QRect(), Qt::TextSingleLine | Qt::TextShowMnemonic, mi->text);
sz = sz.expandedTo(r.size());
}
@@ -5183,15 +5453,38 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
#if QT_CONFIG(tabbar)
case CT_TabBarTab: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
- if (subRule.hasBox() || !subRule.hasNativeBorder()) {
+ if (subRule.hasBox() || !subRule.hasNativeBorder() || subRule.hasFont) {
int spaceForIcon = 0;
bool vertical = false;
+ QString text;
if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
if (!tab->icon.isNull())
spaceForIcon = 6 /* icon offset */ + 4 /* spacing */ + 2 /* magic */; // ###: hardcoded to match with common style
vertical = verticalTabs(tab->shape);
+ text = tab->text;
+ }
+ if (subRule.hasBox() || !subRule.hasNativeBorder())
+ sz = csz + QSize(vertical ? 0 : spaceForIcon, vertical ? spaceForIcon : 0);
+ if (subRule.hasFont) {
+ // first we remove the space needed for the text using the default font
+ const QSize oldTextSize = opt->fontMetrics.size(Qt::TextShowMnemonic, text);
+ (vertical ? sz.rheight() : sz.rwidth()) -= oldTextSize.width();
+
+ // then we add the space needed when using the rule font to the relevant
+ // dimension, and constraint the other dimension to the maximum to make
+ // sure we don't grow, but also don't clip icons or buttons.
+ const QFont ruleFont = subRule.font.resolve(w->font());
+ const QFontMetrics fm(ruleFont);
+ const QSize textSize = fm.size(Qt::TextShowMnemonic, text);
+ if (vertical) {
+ sz.rheight() += textSize.width();
+ sz.rwidth() = qMax(textSize.height(), sz.width());
+ } else {
+ sz.rwidth() += textSize.width();
+ sz.rheight() = qMax(textSize.height(), sz.height());
+ }
}
- sz = csz + QSize(vertical ? 0 : spaceForIcon, vertical ? spaceForIcon : 0);
+
return subRule.boxSize(subRule.adjustSize(sz));
}
sz = subRule.adjustSize(csz);
@@ -5206,13 +5499,13 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
&& !hasStyleRule(w, PseudoElement_MdiMinButton))
break;
- QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
+ QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
if (layout.isEmpty())
- layout = subControlLayout(QLatin1String("mNX"));
+ layout = subControlLayout("mNX");
int width = 0, height = 0;
- for (int i = 0; i < layout.count(); 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;
@@ -5250,64 +5543,65 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
/*!
\internal
*/
-static QLatin1String propertyNameForStandardPixmap(QStyle::StandardPixmap sp)
+static QLatin1StringView propertyNameForStandardPixmap(QStyle::StandardPixmap sp)
{
switch (sp) {
- case QStyle::SP_TitleBarMenuButton: return QLatin1String("titlebar-menu-icon");
- case QStyle::SP_TitleBarMinButton: return QLatin1String("titlebar-minimize-icon");
- case QStyle::SP_TitleBarMaxButton: return QLatin1String("titlebar-maximize-icon");
- case QStyle::SP_TitleBarCloseButton: return QLatin1String("titlebar-close-icon");
- case QStyle::SP_TitleBarNormalButton: return QLatin1String("titlebar-normal-icon");
- case QStyle::SP_TitleBarShadeButton: return QLatin1String("titlebar-shade-icon");
- case QStyle::SP_TitleBarUnshadeButton: return QLatin1String("titlebar-unshade-icon");
- case QStyle::SP_TitleBarContextHelpButton: return QLatin1String("titlebar-contexthelp-icon");
- case QStyle::SP_DockWidgetCloseButton: return QLatin1String("dockwidget-close-icon");
- case QStyle::SP_MessageBoxInformation: return QLatin1String("messagebox-information-icon");
- case QStyle::SP_MessageBoxWarning: return QLatin1String("messagebox-warning-icon");
- case QStyle::SP_MessageBoxCritical: return QLatin1String("messagebox-critical-icon");
- case QStyle::SP_MessageBoxQuestion: return QLatin1String("messagebox-question-icon");
- case QStyle::SP_DesktopIcon: return QLatin1String("desktop-icon");
- case QStyle::SP_TrashIcon: return QLatin1String("trash-icon");
- case QStyle::SP_ComputerIcon: return QLatin1String("computer-icon");
- case QStyle::SP_DriveFDIcon: return QLatin1String("floppy-icon");
- case QStyle::SP_DriveHDIcon: return QLatin1String("harddisk-icon");
- case QStyle::SP_DriveCDIcon: return QLatin1String("cd-icon");
- case QStyle::SP_DriveDVDIcon: return QLatin1String("dvd-icon");
- case QStyle::SP_DriveNetIcon: return QLatin1String("network-icon");
- case QStyle::SP_DirOpenIcon: return QLatin1String("directory-open-icon");
- case QStyle::SP_DirClosedIcon: return QLatin1String("directory-closed-icon");
- case QStyle::SP_DirLinkIcon: return QLatin1String("directory-link-icon");
- case QStyle::SP_FileIcon: return QLatin1String("file-icon");
- case QStyle::SP_FileLinkIcon: return QLatin1String("file-link-icon");
- case QStyle::SP_FileDialogStart: return QLatin1String("filedialog-start-icon");
- case QStyle::SP_FileDialogEnd: return QLatin1String("filedialog-end-icon");
- case QStyle::SP_FileDialogToParent: return QLatin1String("filedialog-parent-directory-icon");
- case QStyle::SP_FileDialogNewFolder: return QLatin1String("filedialog-new-directory-icon");
- case QStyle::SP_FileDialogDetailedView: return QLatin1String("filedialog-detailedview-icon");
- case QStyle::SP_FileDialogInfoView: return QLatin1String("filedialog-infoview-icon");
- case QStyle::SP_FileDialogContentsView: return QLatin1String("filedialog-contentsview-icon");
- case QStyle::SP_FileDialogListView: return QLatin1String("filedialog-listview-icon");
- case QStyle::SP_FileDialogBack: return QLatin1String("filedialog-backward-icon");
- case QStyle::SP_DirIcon: return QLatin1String("directory-icon");
- case QStyle::SP_DialogOkButton: return QLatin1String("dialog-ok-icon");
- case QStyle::SP_DialogCancelButton: return QLatin1String("dialog-cancel-icon");
- case QStyle::SP_DialogHelpButton: return QLatin1String("dialog-help-icon");
- case QStyle::SP_DialogOpenButton: return QLatin1String("dialog-open-icon");
- case QStyle::SP_DialogSaveButton: return QLatin1String("dialog-save-icon");
- case QStyle::SP_DialogCloseButton: return QLatin1String("dialog-close-icon");
- case QStyle::SP_DialogApplyButton: return QLatin1String("dialog-apply-icon");
- case QStyle::SP_DialogResetButton: return QLatin1String("dialog-reset-icon");
- case QStyle::SP_DialogDiscardButton: return QLatin1String("dialog-discard-icon");
- case QStyle::SP_DialogYesButton: return QLatin1String("dialog-yes-icon");
- case QStyle::SP_DialogNoButton: return QLatin1String("dialog-no-icon");
- case QStyle::SP_ArrowUp: return QLatin1String("uparrow-icon");
- case QStyle::SP_ArrowDown: return QLatin1String("downarrow-icon");
- case QStyle::SP_ArrowLeft: return QLatin1String("leftarrow-icon");
- case QStyle::SP_ArrowRight: return QLatin1String("rightarrow-icon");
- case QStyle::SP_ArrowBack: return QLatin1String("backward-icon");
- case QStyle::SP_ArrowForward: return QLatin1String("forward-icon");
- case QStyle::SP_DirHomeIcon: return QLatin1String("home-icon");
- default: return QLatin1String("");
+ case QStyle::SP_TitleBarMenuButton: return "titlebar-menu-icon"_L1;
+ case QStyle::SP_TitleBarMinButton: return "titlebar-minimize-icon"_L1;
+ case QStyle::SP_TitleBarMaxButton: return "titlebar-maximize-icon"_L1;
+ case QStyle::SP_TitleBarCloseButton: return "titlebar-close-icon"_L1;
+ case QStyle::SP_TitleBarNormalButton: return "titlebar-normal-icon"_L1;
+ case QStyle::SP_TitleBarShadeButton: return "titlebar-shade-icon"_L1;
+ case QStyle::SP_TitleBarUnshadeButton: return "titlebar-unshade-icon"_L1;
+ case QStyle::SP_TitleBarContextHelpButton: return "titlebar-contexthelp-icon"_L1;
+ case QStyle::SP_DockWidgetCloseButton: return "dockwidget-close-icon"_L1;
+ case QStyle::SP_MessageBoxInformation: return "messagebox-information-icon"_L1;
+ case QStyle::SP_MessageBoxWarning: return "messagebox-warning-icon"_L1;
+ case QStyle::SP_MessageBoxCritical: return "messagebox-critical-icon"_L1;
+ case QStyle::SP_MessageBoxQuestion: return "messagebox-question-icon"_L1;
+ case QStyle::SP_DesktopIcon: return "desktop-icon"_L1;
+ case QStyle::SP_TrashIcon: return "trash-icon"_L1;
+ case QStyle::SP_ComputerIcon: return "computer-icon"_L1;
+ case QStyle::SP_DriveFDIcon: return "floppy-icon"_L1;
+ case QStyle::SP_DriveHDIcon: return "harddisk-icon"_L1;
+ case QStyle::SP_DriveCDIcon: return "cd-icon"_L1;
+ case QStyle::SP_DriveDVDIcon: return "dvd-icon"_L1;
+ case QStyle::SP_DriveNetIcon: return "network-icon"_L1;
+ case QStyle::SP_DirOpenIcon: return "directory-open-icon"_L1;
+ case QStyle::SP_DirClosedIcon: return "directory-closed-icon"_L1;
+ case QStyle::SP_DirLinkIcon: return "directory-link-icon"_L1;
+ case QStyle::SP_FileIcon: return "file-icon"_L1;
+ case QStyle::SP_FileLinkIcon: return "file-link-icon"_L1;
+ case QStyle::SP_FileDialogStart: return "filedialog-start-icon"_L1;
+ case QStyle::SP_FileDialogEnd: return "filedialog-end-icon"_L1;
+ case QStyle::SP_FileDialogToParent: return "filedialog-parent-directory-icon"_L1;
+ case QStyle::SP_FileDialogNewFolder: return "filedialog-new-directory-icon"_L1;
+ case QStyle::SP_FileDialogDetailedView: return "filedialog-detailedview-icon"_L1;
+ case QStyle::SP_FileDialogInfoView: return "filedialog-infoview-icon"_L1;
+ case QStyle::SP_FileDialogContentsView: return "filedialog-contentsview-icon"_L1;
+ case QStyle::SP_FileDialogListView: return "filedialog-listview-icon"_L1;
+ case QStyle::SP_FileDialogBack: return "filedialog-backward-icon"_L1;
+ case QStyle::SP_DirIcon: return "directory-icon"_L1;
+ case QStyle::SP_DialogOkButton: return "dialog-ok-icon"_L1;
+ case QStyle::SP_DialogCancelButton: return "dialog-cancel-icon"_L1;
+ case QStyle::SP_DialogHelpButton: return "dialog-help-icon"_L1;
+ case QStyle::SP_DialogOpenButton: return "dialog-open-icon"_L1;
+ case QStyle::SP_DialogSaveButton: return "dialog-save-icon"_L1;
+ case QStyle::SP_DialogCloseButton: return "dialog-close-icon"_L1;
+ case QStyle::SP_DialogApplyButton: return "dialog-apply-icon"_L1;
+ case QStyle::SP_DialogResetButton: return "dialog-reset-icon"_L1;
+ case QStyle::SP_DialogDiscardButton: return "dialog-discard-icon"_L1;
+ case QStyle::SP_DialogYesButton: return "dialog-yes-icon"_L1;
+ case QStyle::SP_DialogNoButton: return "dialog-no-icon"_L1;
+ case QStyle::SP_ArrowUp: return "uparrow-icon"_L1;
+ case QStyle::SP_ArrowDown: return "downarrow-icon"_L1;
+ case QStyle::SP_ArrowLeft: return "leftarrow-icon"_L1;
+ case QStyle::SP_ArrowRight: return "rightarrow-icon"_L1;
+ case QStyle::SP_ArrowBack: return "backward-icon"_L1;
+ case QStyle::SP_ArrowForward: return "forward-icon"_L1;
+ case QStyle::SP_DirHomeIcon: return "home-icon"_L1;
+ case QStyle::SP_LineEditClearButton: return "lineedit-clear-button-icon"_L1;
+ default: return ""_L1;
}
}
@@ -5338,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);
@@ -5363,25 +5658,25 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi
QRenderRule rule = renderRule(w, opt);
QString s;
switch (sh) {
- case SH_LineEdit_PasswordCharacter: s = QLatin1String("lineedit-password-character"); break;
- case SH_LineEdit_PasswordMaskDelay: s = QLatin1String("lineedit-password-mask-delay"); break;
- case SH_DitherDisabledText: s = QLatin1String("dither-disabled-text"); break;
- case SH_EtchDisabledText: s = QLatin1String("etch-disabled-text"); break;
- case SH_ItemView_ActivateItemOnSingleClick: s = QLatin1String("activate-on-singleclick"); break;
- case SH_ItemView_ShowDecorationSelected: s = QLatin1String("show-decoration-selected"); break;
- case SH_Table_GridLineColor: s = QLatin1String("gridline-color"); break;
- case SH_DialogButtonLayout: s = QLatin1String("button-layout"); break;
- case SH_ToolTipLabel_Opacity: s = QLatin1String("opacity"); break;
- case SH_ComboBox_Popup: s = QLatin1String("combobox-popup"); break;
- case SH_ComboBox_ListMouseTracking: s = QLatin1String("combobox-list-mousetracking"); break;
- case SH_MenuBar_AltKeyNavigation: s = QLatin1String("menubar-altkey-navigation"); break;
- case SH_Menu_Scrollable: s = QLatin1String("menu-scrollable"); break;
- case SH_DrawMenuBarSeparator: s = QLatin1String("menubar-separator"); break;
- case SH_MenuBar_MouseTracking: s = QLatin1String("mouse-tracking"); break;
- case SH_SpinBox_ClickAutoRepeatRate: s = QLatin1String("spinbox-click-autorepeat-rate"); break;
- case SH_SpinControls_DisableOnBounds: s = QLatin1String("spincontrol-disable-on-bounds"); break;
- case SH_MessageBox_TextInteractionFlags: s = QLatin1String("messagebox-text-interaction-flags"); break;
- case SH_ToolButton_PopupDelay: s = QLatin1String("toolbutton-popup-delay"); break;
+ case SH_LineEdit_PasswordCharacter: s = "lineedit-password-character"_L1; break;
+ case SH_LineEdit_PasswordMaskDelay: s = "lineedit-password-mask-delay"_L1; break;
+ case SH_DitherDisabledText: s = "dither-disabled-text"_L1; break;
+ case SH_EtchDisabledText: s = "etch-disabled-text"_L1; break;
+ case SH_ItemView_ActivateItemOnSingleClick: s = "activate-on-singleclick"_L1; break;
+ case SH_ItemView_ShowDecorationSelected: s = "show-decoration-selected"_L1; break;
+ case SH_Table_GridLineColor: s = "gridline-color"_L1; break;
+ case SH_DialogButtonLayout: s = "button-layout"_L1; break;
+ case SH_ToolTipLabel_Opacity: s = "opacity"_L1; break;
+ case SH_ComboBox_Popup: s = "combobox-popup"_L1; break;
+ case SH_ComboBox_ListMouseTracking: s = "combobox-list-mousetracking"_L1; break;
+ case SH_MenuBar_AltKeyNavigation: s = "menubar-altkey-navigation"_L1; break;
+ case SH_Menu_Scrollable: s = "menu-scrollable"_L1; break;
+ case SH_DrawMenuBarSeparator: s = "menubar-separator"_L1; break;
+ case SH_MenuBar_MouseTracking: s = "mouse-tracking"_L1; break;
+ case SH_SpinBox_ClickAutoRepeatRate: s = "spinbox-click-autorepeat-rate"_L1; break;
+ case SH_SpinControls_DisableOnBounds: s = "spincontrol-disable-on-bounds"_L1; break;
+ case SH_MessageBox_TextInteractionFlags: s = "messagebox-text-interaction-flags"_L1; break;
+ case SH_ToolButton_PopupDelay: s = "toolbutton-popup-delay"_L1; break;
case SH_ToolBox_SelectedPageTitleBold:
if (renderRule(w, opt, PseudoElement_ToolBoxTab).hasFont)
return 0;
@@ -5390,12 +5685,12 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi
if (rule.hasPalette() && rule.palette()->foreground.style() != Qt::NoBrush)
return rule.palette()->foreground.color().rgba();
break;
- case SH_ScrollView_FrameOnlyAroundContents: s = QLatin1String("scrollview-frame-around-contents"); break;
- case SH_ScrollBar_ContextMenu: s = QLatin1String("scrollbar-contextmenu"); break;
- case SH_ScrollBar_LeftClickAbsolutePosition: s = QLatin1String("scrollbar-leftclick-absolute-position"); break;
- case SH_ScrollBar_MiddleClickAbsolutePosition: s = QLatin1String("scrollbar-middleclick-absolute-position"); break;
- case SH_ScrollBar_RollBetweenButtons: s = QLatin1String("scrollbar-roll-between-buttons"); break;
- case SH_ScrollBar_ScrollWhenPointerLeavesControl: s = QLatin1String("scrollbar-scroll-when-pointer-leaves-control"); break;
+ case SH_ScrollView_FrameOnlyAroundContents: s = "scrollview-frame-around-contents"_L1; break;
+ case SH_ScrollBar_ContextMenu: s = "scrollbar-contextmenu"_L1; break;
+ case SH_ScrollBar_LeftClickAbsolutePosition: s = "scrollbar-leftclick-absolute-position"_L1; break;
+ case SH_ScrollBar_MiddleClickAbsolutePosition: s = "scrollbar-middleclick-absolute-position"_L1; break;
+ case SH_ScrollBar_RollBetweenButtons: s = "scrollbar-roll-between-buttons"_L1; break;
+ case SH_ScrollBar_ScrollWhenPointerLeavesControl: s = "scrollbar-scroll-when-pointer-leaves-control"_L1; break;
case SH_TabBar_Alignment:
#if QT_CONFIG(tabwidget)
if (qobject_cast<const QTabWidget *>(w)) {
@@ -5404,7 +5699,7 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi
return rule.position()->position;
}
#endif // QT_CONFIG(tabwidget)
- s = QLatin1String("alignment");
+ s = "alignment"_L1;
break;
#if QT_CONFIG(tabbar)
case SH_TabBar_CloseButtonPosition:
@@ -5418,8 +5713,8 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi
}
break;
#endif
- case SH_TabBar_ElideMode: s = QLatin1String("tabbar-elide-mode"); break;
- case SH_TabBar_PreferNoArrows: s = QLatin1String("tabbar-prefer-no-arrows"); break;
+ case SH_TabBar_ElideMode: s = "tabbar-elide-mode"_L1; break;
+ case SH_TabBar_PreferNoArrows: s = "tabbar-prefer-no-arrows"_L1; break;
case SH_ComboBox_PopupFrameStyle:
#if QT_CONFIG(combobox)
if (qobject_cast<const QComboBox *>(w)) {
@@ -5433,8 +5728,8 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi
}
#endif // QT_CONFIG(combobox)
break;
- case SH_DialogButtonBox_ButtonsHaveIcons: s = QLatin1String("dialogbuttonbox-buttons-have-icons"); break;
- case SH_Workspace_FillSpaceOnMaximize: s = QLatin1String("mdi-fill-space-on-maximize"); break;
+ case SH_DialogButtonBox_ButtonsHaveIcons: s = "dialogbuttonbox-buttons-have-icons"_L1; break;
+ case SH_Workspace_FillSpaceOnMaximize: s = "mdi-fill-space-on-maximize"_L1; break;
case SH_TitleBar_NoBorder:
if (rule.hasBorder())
return !rule.border()->borders[LeftEdge];
@@ -5445,10 +5740,14 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi
return 1;
break;
}
- case SH_ItemView_ArrowKeysNavigateIntoChildren: s = QLatin1String("arrow-keys-navigate-into-children"); break;
- case SH_ItemView_PaintAlternatingRowColorsForEmptyArea: s = QLatin1String("paint-alternating-row-colors-for-empty-area"); break;
- case SH_TitleBar_ShowToolTipsOnButtons: s = QLatin1String("titlebar-show-tooltips-on-buttons"); break;
- case SH_Widget_Animation_Duration: s = QLatin1String("widget-animation-duration"); break;
+ case SH_ItemView_ArrowKeysNavigateIntoChildren: s = "arrow-keys-navigate-into-children"_L1; break;
+ case SH_ItemView_PaintAlternatingRowColorsForEmptyArea: s = "paint-alternating-row-colors-for-empty-area"_L1; break;
+ 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() || rule.hasDrawable())
+ return 0;
+ break;
default: break;
}
if (!s.isEmpty() && rule.hasStyleHint(s)) {
@@ -5767,14 +6066,14 @@ QRect QStyleSheetStyle::subControlRect(ComplexControl cc, const QStyleOptionComp
if (hasStyleRule(w, PseudoElement_MdiCloseButton)
|| hasStyleRule(w, PseudoElement_MdiNormalButton)
|| hasStyleRule(w, PseudoElement_MdiMinButton)) {
- QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
+ QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
if (layout.isEmpty())
- layout = subControlLayout(QLatin1String("mNX"));
+ layout = subControlLayout("mNX");
int x = 0, width = 0;
QRenderRule subRule;
- for (int i = 0; i < layout.count(); 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;
@@ -5820,10 +6119,21 @@ QRect QStyleSheetStyle::subElementRect(SubElement se, const QStyleOption *opt, c
switch (se) {
case SE_PushButtonContents:
+ case SE_PushButtonBevel:
case SE_PushButtonFocusRect:
if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if (rule.hasBox() || !rule.hasNativeBorder())
- return visualRect(opt->direction, opt->rect, rule.contentsRect(opt->rect));
+ if (btn->features & QStyleOptionButton::HasMenu
+ && hasStyleRule(w, PseudoElement_PushButtonMenuIndicator)) {
+ QStyleOptionButton btnOpt(*btn);
+ btnOpt.features &= ~QStyleOptionButton::HasMenu;
+ return rule.baseStyleCanDraw() ? baseStyle()->subElementRect(se, &btnOpt, w)
+ : QWindowsStyle::subElementRect(se, &btnOpt, w);
+ }
+ if (rule.hasBox() || !rule.hasNativeBorder()) {
+ return visualRect(opt->direction, opt->rect, se == SE_PushButtonBevel
+ ? rule.borderRect(opt->rect)
+ : rule.contentsRect(opt->rect));
+ }
return rule.baseStyleCanDraw() ? baseStyle()->subElementRect(se, btn, w)
: QWindowsStyle::subElementRect(se, btn, w);
}
@@ -5919,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;
@@ -6009,13 +6333,17 @@ QRect QStyleSheetStyle::subElementRect(SubElement se, const QStyleOption *opt, c
case SE_TabBarTabLeftButton:
case SE_TabBarTabRightButton: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
- if (subRule.hasBox() || !subRule.hasNativeBorder()) {
+ if (subRule.hasBox() || !subRule.hasNativeBorder() || subRule.hasFont) {
if (se == SE_TabBarTabText) {
- if (const QStyleOptionTabV4 *tab = qstyleoption_cast<const QStyleOptionTabV4 *>(opt)) {
+ if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
const QTabBar *bar = qobject_cast<const QTabBar *>(w);
const QRect optRect = bar && tab->tabIndex != -1 ? bar->tabRect(tab->tabIndex) : opt->rect;
const QRect r = positionRect(w, subRule, PseudoElement_TabBarTab, optRect, opt->direction);
- QStyleOptionTabV4 tabCopy(*tab);
+ QStyleOptionTab tabCopy(*tab);
+ if (subRule.hasFont) {
+ const QFont ruleFont = w ? subRule.font.resolve(w->font()) : subRule.font;
+ tabCopy.fontMetrics = QFontMetrics(ruleFont);
+ }
tabCopy.rect = subRule.contentsRect(r);
return ParentStyle::subElementRect(se, &tabCopy, w);
}
@@ -6044,7 +6372,7 @@ QRect QStyleSheetStyle::subElementRect(SubElement se, const QStyleOption *opt, c
#endif // QT_CONFIG(toolbar)
// On mac we make pixel adjustments to layouts which are not
- // desireable when you have custom style sheets on them
+ // desirable when you have custom style sheets on them
case SE_CheckBoxLayoutItem:
case SE_ComboBoxLayoutItem:
case SE_DateTimeEditLayoutItem:
@@ -6078,7 +6406,7 @@ void QStyleSheetStyle::updateStyleSheetFont(QWidget* w) const
{
// Qt's fontDialog relies on the font of the sample edit for its selection,
// we should never override it.
- if (w->objectName() == QLatin1String("qt_fontDialog_sampleEdit"))
+ if (w->objectName() == "qt_fontDialog_sampleEdit"_L1)
return;
QWidget *container = containerWidget(w);
@@ -6091,18 +6419,18 @@ void QStyleSheetStyle::updateStyleSheetFont(QWidget* w) const
if (useStyleSheetPropagationInWidgetStyles) {
unsetStyleSheetFont(w);
- if (rule.font.resolve()) {
+ if (rule.font.resolveMask()) {
QFont wf = w->d_func()->localFont();
- styleSheetCaches->customFontWidgets.insert(w, {wf, rule.font.resolve()});
+ styleSheetCaches->customFontWidgets.insert(w, {wf, rule.font.resolveMask()});
QFont font = rule.font.resolve(wf);
- font.resolve(wf.resolve() | rule.font.resolve());
+ font.setResolveMask(wf.resolveMask() | rule.font.resolveMask());
w->setFont(font);
}
} else {
QFont wf = w->d_func()->localFont();
QFont font = rule.font.resolve(wf);
- font.resolve(wf.resolve() | rule.font.resolve());
+ font.setResolveMask(wf.resolveMask() | rule.font.resolveMask());
if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
&& isNaturalChild(w) && qobject_cast<QWidget *>(w->parent())) {
@@ -6110,11 +6438,11 @@ void QStyleSheetStyle::updateStyleSheetFont(QWidget* w) const
font = font.resolve(static_cast<QWidget *>(w->parent())->font());
}
- if (wf.resolve() == font.resolve() && wf == font)
+ if (wf.resolveMask() == font.resolveMask() && wf == font)
return;
w->data->fnt = font;
- w->d_func()->directFontResolveMask = font.resolve();
+ w->d_func()->directFontResolveMask = font.resolveMask();
QEvent e(QEvent::FontChange);
QCoreApplication::sendEvent(w, &e);
@@ -6128,7 +6456,7 @@ void QStyleSheetStyle::saveWidgetFont(QWidget* w, const QFont& font) const
void QStyleSheetStyle::clearWidgetFont(QWidget* w) const
{
- w->setProperty("_q_styleSheetWidgetFont", QVariant(QVariant::Invalid));
+ w->setProperty("_q_styleSheetWidgetFont", QVariant());
}
// Polish palette that should be used for a particular widget, with particular states
@@ -6176,7 +6504,7 @@ Qt::Alignment QStyleSheetStyle::resolveAlignment(Qt::LayoutDirection layDir, Qt:
// (and hence has the correct object name).
bool QStyleSheetStyle::isNaturalChild(const QObject *obj)
{
- if (obj->objectName().startsWith(QLatin1String("qt_")))
+ if (obj->objectName().startsWith("qt_"_L1))
return true;
return false;
@@ -6184,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 1cb1adb2db..e50e18f291 100644
--- a/src/widgets/styles/qstylesheetstyle_default.cpp
+++ b/src/widgets/styles/qstylesheetstyle_default.cpp
@@ -1,59 +1,26 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/* This is the default Qt style sheet.
IMPORTANT: This style sheet is primarily meant for defining feature
- capablities of styles. Do NOT add default styling rules here. When in
+ capabilities of styles. Do NOT add default styling rules here. When in
doubt ask the stylesheet maintainer.
The stylesheet in here used to be in a CSS file, but was moved here to
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
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
using namespace QCss;
// This is the class name of the selector.
@@ -116,7 +83,7 @@ using namespace QCss;
// found among the Value_* constants, in which case the second should be that
// constant. Otherwise the first parameter is Value::Identifier and the second
// is a string.
-// Adding more values is the same as seperating by spaces in CSS.
+// Adding more values is the same as separating by spaces in CSS.
// Ex. border: 2px solid black;
// ^ ^ ^
@@ -164,20 +131,20 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-qt-style-features: background-color;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QLineEdit"));
+ SET_ELEMENT_NAME("QLineEdit"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Base);
ADD_DECLARATION;
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -187,13 +154,13 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
border: none;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QLineEdit"));
- ADD_PSEUDO(QLatin1String("no-frame"), PseudoClass_Frameless);
+ SET_ELEMENT_NAME("QLineEdit"_L1);
+ ADD_PSEUDO("no-frame"_L1, PseudoClass_Frameless);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_None);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -203,12 +170,12 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
border: native;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QFrame"));
+ SET_ELEMENT_NAME("QFrame"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -219,20 +186,20 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
border-image: none;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QLabel"));
+ SET_ELEMENT_NAME("QLabel"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_ELEMENT_NAME(QLatin1String("QToolBox"));
+ SET_ELEMENT_NAME("QToolBox"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("background"), Background);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
+ SET_PROPERTY("background"_L1, Background);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_None);
ADD_DECLARATION;
- SET_PROPERTY(QLatin1String("border-image"), BorderImage);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
+ SET_PROPERTY("border-image"_L1, BorderImage);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_None);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -242,12 +209,12 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
border: native;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QGroupBox"));
+ SET_ELEMENT_NAME("QGroupBox"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -259,16 +226,16 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
border: native;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QToolTip"));
+ SET_ELEMENT_NAME("QToolTip"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Window);
ADD_DECLARATION;
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -279,21 +246,21 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-qt-style-features: background-color; //only for not pixmap based styles
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QPushButton"));
+ SET_ELEMENT_NAME("QPushButton"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_ELEMENT_NAME(QLatin1String("QToolButton"));
+ SET_ELEMENT_NAME("QToolButton"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("border-style"), BorderStyles);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border-style"_L1, BorderStyles);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
if (!styleIsPixmapBased) {
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
}
@@ -309,23 +276,23 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QComboBox"));
+ SET_ELEMENT_NAME("QComboBox"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
if (!styleIsPixmapBased) {
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-gradient"));
+ SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-gradient"));
ADD_DECLARATION;
}
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Base);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -339,13 +306,13 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
}*/
if (baseStyle()->inherits("QPlastiqueStyle") || baseStyle()->inherits("QCleanlooksStyle") || baseStyle()->inherits("QFusionStyle"))
{
- SET_ELEMENT_NAME(QLatin1String("QComboBox"));
- ADD_ATTRIBUTE_SELECTOR(QLatin1String("readOnly"), QLatin1String("true"), AttributeSelector::MatchEqual);
+ SET_ELEMENT_NAME("QComboBox"_L1);
+ ADD_ATTRIBUTE_SELECTOR("readOnly"_L1, "true"_L1, AttributeSelector::MatchEqual);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Button);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Button);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -357,20 +324,20 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-qt-background-role: base;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QAbstractSpinBox"));
+ SET_ELEMENT_NAME("QAbstractSpinBox"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Base);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -380,12 +347,12 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-qt-background-role: window;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QMenu"));
+ SET_ELEMENT_NAME("QMenu"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Window);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -394,13 +361,13 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-qt-style-features: background-color;
}*/
if (!styleIsPixmapBased) {
- SET_ELEMENT_NAME(QLatin1String("QMenu"));
- ADD_PSEUDO(QLatin1String("item"), PseudoClass_Unknown);
+ SET_ELEMENT_NAME("QMenu"_L1);
+ ADD_PSEUDO("item"_L1, PseudoClass_Unknown);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -410,12 +377,12 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-qt-background-role: window;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QHeaderView"));
+ SET_ELEMENT_NAME("QHeaderView"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Window);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -427,28 +394,28 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
border: native;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QTableCornerButton"));
- ADD_PSEUDO(QLatin1String("section"), PseudoClass_Unknown);
+ SET_ELEMENT_NAME("QTableCornerButton"_L1);
+ ADD_PSEUDO("section"_L1, PseudoClass_Unknown);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_ELEMENT_NAME(QLatin1String("QHeaderView"));
- ADD_PSEUDO(QLatin1String("section"), PseudoClass_Unknown);
+ SET_ELEMENT_NAME("QHeaderView"_L1);
+ ADD_PSEUDO("section"_L1, PseudoClass_Unknown);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Button);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Button);
ADD_DECLARATION;
if (!styleIsPixmapBased) {
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
+ SET_PROPERTY("-qt-style-features"_L1, QtStyleFeatures);
+ ADD_VALUE(QCss::Value::Identifier, QString::fromLatin1("background-color"));
ADD_DECLARATION;
}
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -458,12 +425,12 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-qt-background-role: base;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QProgressBar"));
+ SET_ELEMENT_NAME("QProgressBar"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Base);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -473,12 +440,12 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-qt-background-role: window;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QScrollBar"));
+ SET_ELEMENT_NAME("QScrollBar"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
+ SET_PROPERTY("-qt-background-role"_L1, QtBackgroundRole);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Window);
ADD_DECLARATION;
ADD_STYLE_RULE;
@@ -488,12 +455,12 @@ StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
border: native;
}*/
{
- SET_ELEMENT_NAME(QLatin1String("QDockWidget"));
+ SET_ELEMENT_NAME("QDockWidget"_L1);
ADD_BASIC_SELECTOR;
ADD_SELECTOR;
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
+ SET_PROPERTY("border"_L1, Border);
+ ADD_VALUE(QCss::Value::KnownIdentifier, Value_Native);
ADD_DECLARATION;
ADD_STYLE_RULE;
diff --git a/src/widgets/styles/qstylesheetstyle_p.h b/src/widgets/styles/qstylesheetstyle_p.h
index 81c532bf6a..95d9db19c9 100644
--- a/src/widgets/styles/qstylesheetstyle_p.h
+++ b/src/widgets/styles/qstylesheetstyle_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTYLESHEETSTYLE_P_H
#define QSTYLESHEETSTYLE_P_H
@@ -45,14 +9,14 @@
#ifndef QT_NO_STYLE_STYLESHEET
+#include "QtWidgets/qapplication.h"
#include "QtWidgets/qstyleoption.h"
#include "QtCore/qhash.h"
-#include "QtGui/qevent.h"
-#include "QtCore/qvector.h"
+#include "QtCore/qlist.h"
#include "QtCore/qset.h"
-#include "QtWidgets/qapplication.h"
-#include "private/qcssparser_p.h"
#include "QtGui/qbrush.h"
+#include "QtGui/qevent.h"
+#include "private/qcssparser_p.h"
QT_BEGIN_NAMESPACE
@@ -158,7 +122,7 @@ private:
void setProperties(QWidget *);
void setGeometry(QWidget *);
void unsetStyleSheetFont(QWidget *) const;
- QVector<QCss::StyleRule> styleRules(const QObject *obj) const;
+ QList<QCss::StyleRule> styleRules(const QObject *obj) const;
bool hasStyleRule(const QObject *obj, int part) const;
QHash<QStyle::SubControl, QRect> titleBarLayout(const QWidget *w, const QStyleOptionTitleBar *tb) const;
@@ -169,6 +133,8 @@ private:
static bool isNaturalChild(const QObject *obj);
static QPixmap loadPixmap(const QString &fileName, const QObject *context);
bool initObject(const QObject *obj) const;
+ void renderMenuItemIcon(const QStyleOptionMenuItem *mi, QPainter *p, const QWidget *w,
+ const QRect &rect, QRenderRule &subRule) const;
public:
static int numinstances;
@@ -184,7 +150,7 @@ public Q_SLOTS:
void objectDestroyed(QObject *);
void styleDestroyed(QObject *);
public:
- QHash<const QObject *, QVector<QCss::StyleRule> > styleRulesCache;
+ QHash<const QObject *, QList<QCss::StyleRule>> styleRulesCache;
QHash<const QObject *, QHash<int, bool> > hasStyleRuleCache;
typedef QHash<int, QHash<quint64, QRenderRule> > QRenderRules;
QHash<const QObject *, QRenderRules> renderRulesCache;
@@ -194,7 +160,7 @@ public:
template <typename T>
struct Tampered {
T oldWidgetValue;
- decltype(std::declval<T>().resolve()) resolveMask;
+ decltype(std::declval<T>().resolveMask()) resolveMask;
// only call this function on an rvalue *this (it mangles oldWidgetValue)
T reverted(T current)
@@ -202,10 +168,10 @@ public:
&&
#endif
{
- oldWidgetValue.resolve(oldWidgetValue.resolve() & resolveMask);
- current.resolve(current.resolve() & ~resolveMask);
+ oldWidgetValue.setResolveMask(oldWidgetValue.resolveMask() & resolveMask);
+ current.setResolveMask(current.resolveMask() & ~resolveMask);
current.resolve(oldWidgetValue);
- current.resolve(current.resolve() | oldWidgetValue.resolve());
+ current.setResolveMask(current.resolveMask() | oldWidgetValue.resolveMask());
return current;
}
};
@@ -214,7 +180,7 @@ public:
};
template <typename T>
class QTypeInfo<QStyleSheetStyleCaches::Tampered<T>>
- : QTypeInfoMerger<QStyleSheetStyleCaches::Tampered<T>, T> {};
+ : public QTypeInfoMerger<QStyleSheetStyleCaches::Tampered<T>, T> {};
// Returns a QStyleSheet from the given style.
diff --git a/src/widgets/styles/qwindowsstyle.cpp b/src/widgets/styles/qwindowsstyle.cpp
index 8496a2c223..bae182b467 100644
--- a/src/widgets/styles/qwindowsstyle.cpp
+++ b/src/widgets/styles/qwindowsstyle.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qwindowsstyle_p.h"
#include "qwindowsstyle_p_p.h"
@@ -78,12 +42,14 @@
#endif
#include <private/qmath_p.h>
#include <qmath.h>
+#include <QtGui/qpainterpath.h>
#include <QtGui/qscreen.h>
#include <QtGui/qwindow.h>
#include <qpa/qplatformtheme.h>
#include <qpa/qplatformscreen.h>
#include <private/qguiapplication_p.h>
#include <private/qhighdpiscaling_p.h>
+#include <qpa/qplatformintegration.h>
#include <private/qwidget_p.h>
#include <private/qstylehelper_p.h>
@@ -122,11 +88,6 @@ enum QSliderDirection { SlUp, SlDown, SlLeft, SlRight };
QWindowsStylePrivate::QWindowsStylePrivate() = default;
-qreal QWindowsStylePrivate::appDevicePixelRatio()
-{
- return qApp->devicePixelRatio();
-}
-
// Returns \c true if the toplevel parent of \a widget has seen the Alt-key
bool QWindowsStylePrivate::hasSeenAlt(const QWidget *widget) const
{
@@ -151,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.erase(std::remove_if(l.begin(), l.end(), ignorable), l.end());
// 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:
@@ -173,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;
@@ -249,8 +211,8 @@ void QWindowsStyle::polish(QApplication *app)
d->inactiveCaptionColor = d->inactiveGradientCaptionColor;
d->inactiveCaptionText = palette.window().color();
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) //fetch native title bar colors
- if(app->desktopSettingsAware()){
+#if defined(Q_OS_WIN) //fetch native title bar colors
+ if (app->desktopSettingsAware()){
DWORD activeCaption = GetSysColor(COLOR_ACTIVECAPTION);
DWORD gradientActiveCaption = GetSysColor(COLOR_GRADIENTACTIVECAPTION);
DWORD inactiveCaption = GetSysColor(COLOR_INACTIVECAPTION);
@@ -294,34 +256,39 @@ void QWindowsStyle::polish(QPalette &pal)
int QWindowsStylePrivate::pixelMetricFromSystemDp(QStyle::PixelMetric pm, const QStyleOption *, const QWidget *widget)
{
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+#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;
}
-#else // Q_OS_WIN && !Q_OS_WINRT
+#else // Q_OS_WIN
Q_UNUSED(pm);
Q_UNUSED(widget);
#endif
@@ -388,22 +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)
{
- qreal result = qreal(1) / QWindowsStylePrivate::devicePixelRatio(widget);
- 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));
}
/*!
@@ -413,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)
@@ -423,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;
@@ -463,7 +418,7 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW
break;
case PM_SplitterWidth:
- ret = qMax(int(QStyleHelper::dpiScaled(4, opt)), QApplication::globalStrut().width());
+ ret = QStyleHelper::dpiScaled(4, opt);
break;
default:
@@ -480,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) && !defined(Q_OS_WINRT)
- 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 && !Q_OS_WINRT
return QCommonStyle::standardPixmap(standardPixmap, opt, widget);
}
@@ -530,7 +445,14 @@ int QWindowsStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWid
int ret = 0;
switch (hint) {
- case SH_EtchDisabledText:
+ 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:
@@ -557,7 +479,7 @@ int QWindowsStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWid
ret = 0;
break;
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) // Option not used on WinRT -> common style
+#if defined(Q_OS_WIN)
case SH_UnderlineShortcut:
{
ret = 1;
@@ -585,23 +507,23 @@ int QWindowsStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWid
ret = 1;
}
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (!ret && opt && opt->type == QStyleOption::SO_MenuItem
&& QStyleHelper::isInstanceOf(opt->styleObject, QAccessible::MenuItem)
&& opt->styleObject->property("_q_showUnderlined").toBool())
ret = 1;
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
break;
}
-#endif // Q_OS_WIN && !Q_OS_WINRT
+#endif // Q_OS_WIN
case SH_Menu_SubMenuSloppyCloseTimeout:
case SH_Menu_SubMenuPopupDelay: {
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+#if defined(Q_OS_WIN)
DWORD delay;
if (SystemParametersInfo(SPI_GETMENUSHOWDELAY, 0, &delay, 0))
ret = delay;
else
-#endif // Q_OS_WIN && !Q_OS_WINRT
+#endif // Q_OS_WIN
ret = 400;
break;
}
@@ -611,7 +533,7 @@ int QWindowsStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWid
ret = 0;
if (rbOpt->shape == QRubberBand::Rectangle) {
ret = true;
- if(QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(returnData)) {
+ if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(returnData)) {
mask->region = opt->rect;
int size = 1;
if (widget && widget->isWindow())
@@ -654,7 +576,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
QRect rect = opt->rect;
const int margin = 2;
QPen oldPen = p->pen();
- if(opt->state & State_Horizontal){
+ if (opt->state & State_Horizontal){
const int offset = rect.width()/2;
p->setPen(QPen(opt->palette.dark().color()));
p->drawLine(rect.bottomLeft().x() + offset,
@@ -739,7 +661,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
if (opt->state & (State_Raised | State_Sunken | State_On)) {
if (opt->state & State_AutoRaise) {
- if(opt->state & (State_Enabled | State_Sunken | State_On)){
+ if (opt->state & (State_Enabled | State_Sunken | State_On)){
if (panel)
qDrawShadePanel(p, opt->rect, opt->palette,
opt->state & (State_Sunken | State_On), 1, &fill);
@@ -834,10 +756,10 @@ 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() + 3.5 * scaleh, opt->rect.y() + 5.5 * scalev };
+ points[0] = { opt->rect.x() + qreal(3.5) * scaleh, opt->rect.y() + qreal(5.5) * scalev };
points[1] = { points[0].x(), points[0].y() + 2 * scalev };
points[2] = { points[1].x() + 2 * scaleh, points[1].y() + 2 * scalev };
points[3] = { points[2].x() + 4 * scaleh, points[2].y() - 4 * scalev };
@@ -845,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();
@@ -1006,7 +928,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
{
bool vertical = false, inverted = false;
if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- vertical = pb->orientation == Qt::Vertical;
+ vertical = !(pb->state & QStyle::State_Horizontal);
inverted = pb->invertedAppearance;
}
@@ -1091,7 +1013,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
int x, y, w, h;
menuitem->rect.getRect(&x, &y, &w, &h);
- int tab = menuitem->tabWidth;
+ int tab = menuitem->reservedShortcutWidth;
bool dis = !(menuitem->state & State_Enabled);
bool checked = menuitem->checkType != QStyleOptionMenuItem::NotCheckable
? menuitem->checked : false;
@@ -1138,9 +1060,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
pixmap = menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, opt, widget), mode, QIcon::On);
else
pixmap = menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, opt, widget), mode);
- const int pixw = pixmap.width() / pixmap.devicePixelRatio();
- const int pixh = pixmap.height() / pixmap.devicePixelRatio();
- QRect pmr(0, 0, pixw, pixh);
+ QRect pmr(QPoint(0, 0), pixmap.deviceIndependentSize().toSize());
pmr.moveCenter(vCheckRect.center());
p->setPen(menuitem->palette.text().color());
p->drawPixmap(pmr.topLeft(), pixmap);
@@ -1150,7 +1070,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
if (!dis)
newMi.state |= State_Enabled;
if (act)
- newMi.state |= State_On;
+ newMi.state |= State_On | State_Selected;
newMi.rect = visualRect(opt->direction, menuitem->rect, QRect(menuitem->rect.x() + QWindowsStylePrivate::windowsItemFrame,
menuitem->rect.y() + QWindowsStylePrivate::windowsItemFrame,
checkcol - 2 * QWindowsStylePrivate::windowsItemFrame,
@@ -1170,10 +1090,10 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
QRect textRect(xpos, y + QWindowsStylePrivate::windowsItemVMargin,
w - xm - QWindowsStylePrivate::windowsRightBorder - tab + 1, h - 2 * QWindowsStylePrivate::windowsItemVMargin);
QRect vTextRect = visualRect(opt->direction, menuitem->rect, textRect);
- QStringRef s(&menuitem->text);
+ QStringView s(menuitem->text);
if (!s.isEmpty()) { // draw text
p->save();
- int t = s.indexOf(QLatin1Char('\t'));
+ qsizetype t = s.indexOf(u'\t');
int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
if (!proxy()->styleHint(SH_UnderlineShortcut, menuitem, widget))
text_flags |= Qt::TextHideMnemonic;
@@ -1599,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){
@@ -1672,10 +1589,10 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
if (!rect.isValid())
return;
- const bool vertical = pb->orientation == Qt::Vertical;
+ const bool vertical = !(pb->state & QStyle::State_Horizontal);
const bool inverted = pb->invertedAppearance;
- QMatrix m;
+ QTransform m;
if (vertical) {
rect = QRect(rect.y(), rect.x(), rect.height(), rect.width()); // flip width and height
m.rotate(90);
@@ -1714,7 +1631,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
int myHeight = pbBits.rect.height();
int chunksToDraw = chunksInRow;
- if(step > chunkCount - 5)chunksToDraw = (chunkCount - step);
+ if (step > chunkCount - 5)chunksToDraw = (chunkCount - step);
p->save();
p->setClipRect(m.mapRect(QRectF(rect)).toRect());
@@ -1728,7 +1645,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
x += reverse ? -unit_width : unit_width;
}
//Draw wrap-around chunks
- if( step > chunkCount-5){
+ if ( step > chunkCount-5){
x0 = reverse ? rect.left() + rect.width() - unit_width : rect.left() ;
x = 0;
int chunksToDraw = step - (chunkCount - chunksInRow);
@@ -1815,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);
@@ -1978,51 +1895,46 @@ 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;
}
QBrush oldBrush = p->brush();
- bool oldQt4CompatiblePainting = p->testRenderHint(QPainter::Qt4CompatiblePainting);
p->setPen(Qt::NoPen);
p->setBrush(handleBrush);
- p->setRenderHint(QPainter::Qt4CompatiblePainting);
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);
@@ -2101,7 +2013,6 @@ void QWindowsStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComp
p->drawLine(x2, y2-1, x2+d, y2-1-d);
break;
}
- p->setRenderHint(QPainter::Qt4CompatiblePainting, oldQt4CompatiblePainting);
}
}
break;
@@ -2119,7 +2030,7 @@ void QWindowsStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComp
#if QT_CONFIG(combobox)
case CC_ComboBox:
if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- QBrush editBrush = cmb->palette.brush(QPalette::Base);
+ QBrush editBrush = cmb->palette.brush(QPalette::Button);
if ((cmb->subControls & SC_ComboBoxFrame)) {
if (cmb->frame) {
QPalette shadePal = opt->palette;
@@ -2304,12 +2215,11 @@ QSize QWindowsStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
int minwidth = int(QStyleHelper::dpiScaled(75, dpi));
int minheight = int(QStyleHelper::dpiScaled(23, dpi));
-#ifndef QT_QWS_SMALL_PUSHBUTTON
if (w < minwidth + defwidth && !btn->text.isEmpty())
w = minwidth + defwidth;
if (h < minheight + defwidth)
h = minheight + defwidth;
-#endif
+
sz = QSize(w, h);
}
break;
@@ -2335,7 +2245,7 @@ QSize QWindowsStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
}
int maxpmw = mi->maxIconWidth;
int tabSpacing = 20;
- if (mi->text.contains(QLatin1Char('\t')))
+ if (mi->text.contains(u'\t'))
w += tabSpacing;
else if (mi->menuItemType == QStyleOptionMenuItem::SubMenu)
w += 2 * QWindowsStylePrivate::windowsArrowHMargin;
diff --git a/src/widgets/styles/qwindowsstyle_p.h b/src/widgets/styles/qwindowsstyle_p.h
index b5f0bd68a1..2c2ca0c76b 100644
--- a/src/widgets/styles/qwindowsstyle_p.h
+++ b/src/widgets/styles/qwindowsstyle_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWINDOWSSTYLE_P_H
#define QWINDOWSSTYLE_P_H
diff --git a/src/widgets/styles/qwindowsstyle_p_p.h b/src/widgets/styles/qwindowsstyle_p_p.h
index 4f6ffcefc2..dce60cbf8d 100644
--- a/src/widgets/styles/qwindowsstyle_p_p.h
+++ b/src/widgets/styles/qwindowsstyle_p_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWINDOWSSTYLE_P_P_H
#define QWINDOWSSTYLE_P_P_H
@@ -60,8 +24,6 @@
QT_BEGIN_NAMESPACE
-class QTime;
-
class Q_WIDGETS_EXPORT QWindowsStylePrivate : public QCommonStylePrivate
{
Q_DECLARE_PUBLIC(QWindowsStyle)
@@ -71,15 +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->devicePixelRatioF() : QWindowsStylePrivate::appDevicePixelRatio(); }
static qreal nativeMetricScaleFactor(const QWidget *widget = nullptr);
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;
@@ -96,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/styles/styles.pri b/src/widgets/styles/styles.pri
deleted file mode 100644
index be535c1846..0000000000
--- a/src/widgets/styles/styles.pri
+++ /dev/null
@@ -1,49 +0,0 @@
-# Qt styles module
-
-HEADERS += \
- styles/qdrawutil.h \
- styles/qstyle.h \
- styles/qstylefactory.h \
- styles/qstyleoption.h \
- styles/qstyleplugin.h \
- styles/qcommonstylepixmaps_p.h \
- styles/qcommonstyle.h \
- styles/qstylehelper_p.h \
- styles/qproxystyle.h \
- styles/qproxystyle_p.h \
- styles/qcommonstyle_p.h \
- styles/qstylepainter.h \
- styles/qstylesheetstyle_p.h \
- styles/qpixmapstyle_p.h \
- styles/qpixmapstyle_p_p.h
-
-SOURCES += \
- styles/qdrawutil.cpp \
- styles/qstyle.cpp \
- styles/qstylefactory.cpp \
- styles/qstyleoption.cpp \
- styles/qstyleplugin.cpp \
- styles/qstylehelper.cpp \
- styles/qcommonstyle.cpp \
- styles/qproxystyle.cpp \
- styles/qstylepainter.cpp \
- styles/qstylesheetstyle.cpp \
- styles/qstylesheetstyle_default.cpp \
- styles/qpixmapstyle.cpp
-
-RESOURCES += styles/qstyle.qrc
-
-qtConfig(animation) {
- HEADERS += styles/qstyleanimation_p.h
- SOURCES += styles/qstyleanimation.cpp
-}
-
-qtConfig(style-windows) {
- HEADERS += styles/qwindowsstyle_p.h styles/qwindowsstyle_p_p.h
- SOURCES += styles/qwindowsstyle.cpp
-}
-
-qtConfig(style-fusion) {
- HEADERS += styles/qfusionstyle_p.h styles/qfusionstyle_p_p.h
- SOURCES += styles/qfusionstyle.cpp
-}
diff --git a/src/widgets/util/qcolormap.cpp b/src/widgets/util/qcolormap.cpp
index 57e61690e9..08f892b109 100644
--- a/src/widgets/util/qcolormap.cpp
+++ b/src/widgets/util/qcolormap.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qcolormap.h"
#include "qcolor.h"
@@ -175,12 +139,6 @@ uint QColormap::pixel(const QColor &color) const
const int green_mask = 0x00ff00;
const int blue_mask = 0x0000ff;
const int tg = g << green_shift;
-#ifdef QT_QWS_DEPTH_32_BGR
- if (qt_screen->pixelType() == QScreen::BGRPixel) {
- const int tb = b << red_shift;
- return 0xff000000 | (r & blue_mask) | (tg & green_mask) | (tb & red_mask);
- }
-#endif
const int tr = r << red_shift;
return 0xff000000 | (b & blue_mask) | (tg & green_mask) | (tr & red_mask);
}
@@ -202,13 +160,6 @@ const QColor QColormap::colorAt(uint pixel) const
const int red_mask = 0xff0000;
const int green_mask = 0x00ff00;
const int blue_mask = 0x0000ff;
-#ifdef QT_QWS_DEPTH_32_BGR
- if (qt_screen->pixelType() == QScreen::BGRPixel) {
- return QColor((pixel & blue_mask),
- (pixel & green_mask) >> green_shift,
- (pixel & red_mask) >> red_shift);
- }
-#endif
return QColor((pixel & red_mask) >> red_shift,
(pixel & green_mask) >> green_shift,
(pixel & blue_mask));
@@ -220,9 +171,9 @@ const QColor QColormap::colorAt(uint pixel) const
return QColor();
}
-const QVector<QColor> QColormap::colormap() const
+const QList<QColor> QColormap::colormap() const
{
- return QVector<QColor>();
+ return QList<QColor>();
}
QColormap &QColormap::operator=(const QColormap &colormap)
diff --git a/src/widgets/util/qcolormap.h b/src/widgets/util/qcolormap.h
index 8e652d8154..3a187e1191 100644
--- a/src/widgets/util/qcolormap.h
+++ b/src/widgets/util/qcolormap.h
@@ -1,50 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOLORMAP_H
#define QCOLORMAP_H
#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtCore/qatomic.h>
#include <QtGui/qrgb.h>
-#include <QtCore/qvector.h>
#include <QtGui/qwindowdefs.h>
+#include <QtCore/qatomic.h>
+#include <QtCore/qlist.h>
QT_BEGIN_NAMESPACE
@@ -75,7 +39,7 @@ public:
uint pixel(const QColor &color) const;
const QColor colorAt(uint pixel) const;
- const QVector<QColor> colormap() const;
+ const QList<QColor> colormap() const;
private:
QColormap();
diff --git a/src/widgets/util/qcolormap.qdoc b/src/widgets/util/qcolormap.qdoc
index 2e1c7c504b..d976a369f0 100644
--- a/src/widgets/util/qcolormap.qdoc
+++ b/src/widgets/util/qcolormap.qdoc
@@ -1,29 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\class QColormap
@@ -42,11 +18,11 @@
\value Direct Pixel values are derived directly from the RGB
values, also known as "True Color."
- \value Indexed Pixel values represent indexes into a vector of
+ \value Indexed Pixel values represent indexes into a list of
available colors, i.e. QColormap uses the index of the color that
most closely matches an RGB value.
- \value Gray Similar to \c Indexed, pixel values represent a vector
+ \value Gray Similar to \c Indexed, pixel values represent a list
of available gray tones. QColormap uses the index of the gray
tone that most closely matches the computed gray tone of an RGB
value.
@@ -113,11 +89,11 @@
*/
/*!
- \fn const QVector<QColor> QColormap::colormap() const
+ \fn const QList<QColor> QColormap::colormap() const
- Returns a vector of colors which represents the devices colormap
+ Returns a list of colors which represents the devices colormap
for \c Indexed and \c Gray modes. This function returns an empty
- vector for \c Direct mode.
+ list for \c Direct mode.
\sa size()
*/
diff --git a/src/widgets/util/qcompleter.cpp b/src/widgets/util/qcompleter.cpp
index 72fa557790..394a968aad 100644
--- a/src/widgets/util/qcompleter.cpp
+++ b/src/widgets/util/qcompleter.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QCompleter
@@ -148,11 +112,8 @@
#if QT_CONFIG(stringlistmodel)
#include "QtCore/qstringlistmodel.h"
#endif
-#if QT_CONFIG(dirmodel)
-#include "QtWidgets/qdirmodel.h"
-#endif
#if QT_CONFIG(filesystemmodel)
-#include "QtWidgets/qfilesystemmodel.h"
+#include "QtGui/qfilesystemmodel.h"
#endif
#include "QtWidgets/qheaderview.h"
#if QT_CONFIG(listview)
@@ -160,9 +121,8 @@
#endif
#include "QtWidgets/qapplication.h"
#include "QtGui/qevent.h"
-#include "QtWidgets/qdesktopwidget.h"
#include <private/qapplication_p.h>
-#include <private/qdesktopwidget_p.h>
+#include <private/qwidget_p.h>
#if QT_CONFIG(lineedit)
#include "QtWidgets/qlineedit.h"
#endif
@@ -170,6 +130,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
QCompletionModel::QCompletionModel(QCompleterPrivate *c, QObject *parent)
: QAbstractProxyModel(*new QCompletionModelPrivate, parent),
c(c), showAll(false)
@@ -364,7 +326,7 @@ int QCompletionModel::rowCount(const QModelIndex &parent) const
if (showAll) {
// Show all items below current parent, even if we have no valid matches
- if (engine->curParts.count() != 1 && !engine->matchCount()
+ if (engine->curParts.size() != 1 && !engine->matchCount()
&& !engine->curParent.isValid())
return 0;
return d->model->rowCount(engine->curParent);
@@ -449,7 +411,7 @@ void QCompletionEngine::filter(const QStringList& parts)
return;
QModelIndex parent;
- for (int i = 0; i < curParts.count() - 1; i++) {
+ for (int i = 0; i < curParts.size() - 1; i++) {
QString part = curParts.at(i);
int emi = filter(part, parent, -1).exactMatchIndex;
if (emi == -1)
@@ -470,22 +432,16 @@ void QCompletionEngine::filter(const QStringList& parts)
QMatchData QCompletionEngine::filterHistory()
{
QAbstractItemModel *source = c->proxy->sourceModel();
- if (curParts.count() <= 1 || c->proxy->showAll || !source)
+ if (curParts.size() <= 1 || c->proxy->showAll || !source)
return QMatchData();
-#if QT_CONFIG(dirmodel) && QT_DEPRECATED_SINCE(5, 15)
- const bool isDirModel = (qobject_cast<QDirModel *>(source) != nullptr);
-#else
- const bool isDirModel = false;
-#endif
- Q_UNUSED(isDirModel)
#if QT_CONFIG(filesystemmodel)
const bool isFsModel = (qobject_cast<QFileSystemModel *>(source) != nullptr);
#else
const bool isFsModel = false;
#endif
- Q_UNUSED(isFsModel)
- QVector<int> v;
+ Q_UNUSED(isFsModel);
+ QList<int> v;
QIndexMapper im(v);
QMatchData m(im, -1, true);
@@ -493,7 +449,7 @@ QMatchData QCompletionEngine::filterHistory()
QString str = source->index(i, c->column).data().toString();
if (str.startsWith(c->prefix, c->cs)
#if !defined(Q_OS_WIN)
- && ((!isFsModel && !isDirModel) || QDir::toNativeSeparators(str) != QDir::separator())
+ && (!isFsModel || QDir::toNativeSeparators(str) != QDir::separator())
#endif
)
m.indices.append(i);
@@ -560,7 +516,7 @@ void QCompletionEngine::saveInCache(QString part, const QModelIndex& parent, con
QMap<QModelIndex, CacheItem>::iterator it1 = cache.begin();
while (it1 != cache.end()) {
CacheItem& ci = it1.value();
- int sz = ci.count()/2;
+ int sz = ci.size()/2;
QMap<QString, QMatchData>::iterator it2 = ci.begin();
int i = 0;
while (it2 != ci.end() && i < sz) {
@@ -568,7 +524,7 @@ void QCompletionEngine::saveInCache(QString part, const QModelIndex& parent, con
it2 = ci.erase(it2);
i++;
}
- if (ci.count() == 0) {
+ if (ci.size() == 0) {
it1 = cache.erase(it1);
} else {
++it1;
@@ -597,7 +553,8 @@ QIndexMapper QSortedModelEngine::indexHint(QString part, const QModelIndex& pare
const CacheItem::const_iterator it = map.lowerBound(part);
// look backward for first valid hint
- for(CacheItem::const_iterator it1 = it; it1-- != map.constBegin();) {
+ for (CacheItem::const_iterator it1 = it; it1 != map.constBegin();) {
+ --it1;
const QMatchData& value = it1.value();
if (value.isValid()) {
if (order == Qt::AscendingOrder) {
@@ -757,7 +714,7 @@ int QUnsortedModelEngine::buildIndices(const QString& str, const QModelIndex& pa
case Qt::MatchExactly:
case Qt::MatchFixedString:
case Qt::MatchCaseSensitive:
- case Qt::MatchRegExp:
+ case Qt::MatchRegularExpression:
case Qt::MatchWildcard:
case Qt::MatchWrap:
case Qt::MatchRecursive:
@@ -793,7 +750,7 @@ QMatchData QUnsortedModelEngine::filter(const QString& part, const QModelIndex&
{
QMatchData hint;
- QVector<int> v;
+ QList<int> v;
QIndexMapper im(v);
QMatchData m(im, -1, true);
@@ -883,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);
}
@@ -903,13 +860,6 @@ void QCompleterPrivate::_q_complete(QModelIndex index, bool highlighted)
QModelIndex si = proxy->mapToSource(index);
si = si.sibling(si.row(), column); // for clicked()
completion = q->pathFromIndex(si);
-#if QT_CONFIG(dirmodel) && QT_DEPRECATED_SINCE(5, 15)
- // add a trailing separator in inline
- if (mode == QCompleter::InlineCompletion) {
- if (qobject_cast<QDirModel *>(proxy->sourceModel()) && QFileInfo(completion).isDir())
- completion += QDir::separator();
- }
-#endif
#if QT_CONFIG(filesystemmodel)
// add a trailing separator in inline
if (mode == QCompleter::InlineCompletion) {
@@ -937,7 +887,7 @@ void QCompleterPrivate::_q_autoResizePopup()
void QCompleterPrivate::showPopup(const QRect& rect)
{
- const QRect screen = QDesktopWidgetPrivate::availableGeometry(widget);
+ const QRect screen = widget->screen()->availableGeometry();
Qt::LayoutDirection dir = widget->layoutDirection();
QPoint pos;
int rh, w;
@@ -999,9 +949,9 @@ static bool completeOnLoaded(const QFileSystemModel *model,
if (prefixSize == pathSize)
return path.compare(prefix, caseSensitivity) == 0 && isRoot(model, path);
// The user is typing something within that directory and is not in a subdirectory yet.
- const auto separator = QLatin1Char('/');
+ const auto separator = u'/';
return prefix.startsWith(path, caseSensitivity) && prefix.at(pathSize) == separator
- && !prefix.rightRef(prefixSize - pathSize - 1).contains(separator);
+ && !QStringView{prefix}.right(prefixSize - pathSize - 1).contains(separator);
}
void QCompleterPrivate::_q_fileSystemModelDirectoryLoaded(const QString &path)
@@ -1116,6 +1066,8 @@ void QCompleter::setModel(QAbstractItemModel *model)
{
Q_D(QCompleter);
QAbstractItemModel *oldModel = d->proxy->sourceModel();
+ if (oldModel == model)
+ return;
#if QT_CONFIG(filesystemmodel)
if (qobject_cast<const QFileSystemModel *>(oldModel))
setCompletionRole(Qt::EditRole); // QTBUG-54642, clear FileNameRole set by QFileSystemModel
@@ -1125,15 +1077,6 @@ void QCompleter::setModel(QAbstractItemModel *model)
setPopup(d->popup); // set the model and make new connections
if (oldModel && oldModel->QObject::parent() == this)
delete oldModel;
-#if QT_CONFIG(dirmodel) && QT_DEPRECATED_SINCE(5, 15)
- if (qobject_cast<QDirModel *>(model)) {
-#if defined(Q_OS_WIN)
- setCaseSensitivity(Qt::CaseInsensitive);
-#else
- setCaseSensitivity(Qt::CaseSensitive);
-#endif
- }
-#endif // QT_CONFIG(dirmodel)
#if QT_CONFIG(filesystemmodel)
QFileSystemModel *fsModel = qobject_cast<QFileSystemModel *>(model);
if (fsModel) {
@@ -1204,7 +1147,7 @@ QCompleter::CompletionMode QCompleter::completionMode() const
/*!
\property QCompleter::filterMode
- \brief how the filtering is performed
+ \brief This property controls how filtering is performed.
\since 5.2
If filterMode is set to Qt::MatchStartsWith, only those entries that start
@@ -1212,11 +1155,14 @@ QCompleter::CompletionMode QCompleter::completionMode() const
the entries that contain the typed characters, and Qt::MatchEndsWith the
ones that end with the typed characters.
- Currently, only these three modes are implemented. Setting filterMode to
- any other Qt::MatchFlag will issue a warning, and no action will be
- performed.
+ Setting filterMode to any other Qt::MatchFlag will issue a warning, and no
+ action will be performed. Because of this, the \c Qt::MatchCaseSensitive
+ flag has no effect. Use the \l caseSensitivity property to control case
+ sensitivity.
The default mode is Qt::MatchStartsWith.
+
+ \sa caseSensitivity
*/
void QCompleter::setFilterMode(Qt::MatchFlags filterMode)
@@ -1261,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;
}
/*!
@@ -1354,6 +1305,7 @@ bool QCompleter::eventFilter(QObject *o, QEvent *e)
if (o != d->popup)
return QObject::eventFilter(o, e);
+ Q_ASSERT(d->popup);
switch (e->type()) {
case QEvent::KeyPress: {
QKeyEvent *ke = static_cast<QKeyEvent *>(e);
@@ -1743,9 +1695,9 @@ void QCompleter::setMaxVisibleItems(int maxItems)
\property QCompleter::caseSensitivity
\brief the case sensitivity of the matching
- The default is Qt::CaseSensitive.
+ The default value is \c Qt::CaseSensitive.
- \sa completionColumn, completionRole, modelSorting
+ \sa completionColumn, completionRole, modelSorting, filterMode
*/
void QCompleter::setCaseSensitivity(Qt::CaseSensitivity cs)
{
@@ -1844,26 +1796,19 @@ QString QCompleter::pathFromIndex(const QModelIndex& index) const
QAbstractItemModel *sourceModel = d->proxy->sourceModel();
if (!sourceModel)
return QString();
- bool isDirModel = false;
bool isFsModel = false;
-#if QT_CONFIG(dirmodel) && QT_DEPRECATED_SINCE(5, 15)
- isDirModel = qobject_cast<QDirModel *>(d->proxy->sourceModel()) != nullptr;
-#endif
#if QT_CONFIG(filesystemmodel)
isFsModel = qobject_cast<QFileSystemModel *>(d->proxy->sourceModel()) != nullptr;
#endif
- if (!isDirModel && !isFsModel)
+ if (!isFsModel)
return sourceModel->data(index, d->role).toString();
QModelIndex idx = index;
QStringList list;
do {
QString t;
- if (isDirModel)
- t = sourceModel->data(idx, Qt::EditRole).toString();
#if QT_CONFIG(filesystemmodel)
- else
- t = sourceModel->data(idx, QFileSystemModel::FileNameRole).toString();
+ t = sourceModel->data(idx, QFileSystemModel::FileNameRole).toString();
#endif
list.prepend(t);
QModelIndex parent = idx.parent();
@@ -1871,7 +1816,7 @@ QString QCompleter::pathFromIndex(const QModelIndex& index) const
} while (idx.isValid());
#if !defined(Q_OS_WIN)
- if (list.count() == 1) // only the separator or some other text
+ if (list.size() == 1) // only the separator or some other text
return list[0];
list[0].clear() ; // the join below will provide the separator
#endif
@@ -1893,27 +1838,20 @@ QString QCompleter::pathFromIndex(const QModelIndex& index) const
*/
QStringList QCompleter::splitPath(const QString& path) const
{
- bool isDirModel = false;
bool isFsModel = false;
-#if QT_CONFIG(dirmodel) && QT_DEPRECATED_SINCE(5, 15)
- Q_D(const QCompleter);
- isDirModel = qobject_cast<QDirModel *>(d->proxy->sourceModel()) != nullptr;
-#endif
#if QT_CONFIG(filesystemmodel)
-#if !QT_CONFIG(dirmodel)
Q_D(const QCompleter);
-#endif
isFsModel = qobject_cast<QFileSystemModel *>(d->proxy->sourceModel()) != nullptr;
#endif
- if ((!isDirModel && !isFsModel) || path.isEmpty())
+ if (!isFsModel || path.isEmpty())
return QStringList(completionPrefix());
QString pathCopy = QDir::toNativeSeparators(path);
#if defined(Q_OS_WIN)
- if (pathCopy == QLatin1String("\\") || pathCopy == QLatin1String("\\\\"))
+ if (pathCopy == "\\"_L1 || pathCopy == "\\\\"_L1)
return QStringList(pathCopy);
- const bool startsWithDoubleSlash = pathCopy.startsWith(QLatin1String("\\\\"));
+ const bool startsWithDoubleSlash = pathCopy.startsWith("\\\\"_L1);
if (startsWithDoubleSlash)
pathCopy = pathCopy.mid(2);
#endif
@@ -1923,10 +1861,10 @@ QStringList QCompleter::splitPath(const QString& path) const
#if defined(Q_OS_WIN)
if (startsWithDoubleSlash)
- parts[0].prepend(QLatin1String("\\\\"));
+ parts[0].prepend("\\\\"_L1);
#else
if (pathCopy[0] == sep) // readd the "/" at the beginning as the split removed it
- parts[0] = QLatin1Char('/');
+ parts[0] = u'/';
#endif
return parts;
diff --git a/src/widgets/util/qcompleter.h b/src/widgets/util/qcompleter.h
index 5448fc313c..9d20c9ae09 100644
--- a/src/widgets/util/qcompleter.h
+++ b/src/widgets/util/qcompleter.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOMPLETER_H
#define QCOMPLETER_H
diff --git a/src/widgets/util/qcompleter_p.h b/src/widgets/util/qcompleter_p.h
index a52e63a6e2..a88996f180 100644
--- a/src/widgets/util/qcompleter_p.h
+++ b/src/widgets/util/qcompleter_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOMPLETER_P_H
#define QCOMPLETER_P_H
@@ -57,10 +21,13 @@
#include "QtWidgets/qabstractitemview.h"
#include "QtCore/qabstractproxymodel.h"
+#include "QtCore/qmap.h"
#include "qcompleter.h"
-#include "QtWidgets/qitemdelegate.h"
+#include "qstyleditemdelegate.h"
#include "QtGui/qpainter.h"
+
#include "private/qabstractproxymodel_p.h"
+#include <QtCore/qpointer.h>
QT_REQUIRE_CONFIG(completer);
@@ -111,9 +78,9 @@ class QIndexMapper
public:
QIndexMapper() : v(false), f(0), t(-1) { }
QIndexMapper(int f, int t) : v(false), f(f), t(t) { }
- QIndexMapper(const QVector<int> &vec) : v(true), vector(vec), f(-1), t(-1) { }
+ QIndexMapper(const QList<int> &vec) : v(true), vector(vec), f(-1), t(-1) { }
- inline int count() const { return v ? vector.count() : t - f + 1; }
+ inline int count() const { return v ? vector.size() : t - f + 1; }
inline int operator[] (int index) const { return v ? vector[index] : f + index; }
inline int indexOf(int x) const { return v ? vector.indexOf(x) : ((t < f) ? -1 : x - f); }
inline bool isValid() const { return !isEmpty(); }
@@ -123,11 +90,11 @@ public:
inline int last() const { return v ? vector.last() : t; }
inline int from() const { Q_ASSERT(!v); return f; }
inline int to() const { Q_ASSERT(!v); return t; }
- inline int cost() const { return vector.count()+2; }
+ inline int cost() const { return vector.size()+2; }
private:
bool v;
- QVector<int> vector;
+ QList<int> vector;
int f, t;
};
@@ -194,18 +161,17 @@ private:
const QIndexMapper& iv, QMatchData* m);
};
-// ### Qt6: QStyledItemDelegate
-class QCompleterItemDelegate : public QItemDelegate
+class QCompleterItemDelegate : public QStyledItemDelegate
{
public:
QCompleterItemDelegate(QAbstractItemView *view)
- : QItemDelegate(view), view(view) { }
+ : QStyledItemDelegate(view), view(view) { }
void paint(QPainter *p, const QStyleOptionViewItem& opt, const QModelIndex& idx) const override {
QStyleOptionViewItem optCopy = opt;
optCopy.showDecorationSelected = true;
if (view->currentIndex() == idx)
optCopy.state |= QStyle::State_HasFocus;
- QItemDelegate::paint(p, optCopy, idx);
+ QStyledItemDelegate::paint(p, optCopy, idx);
}
private:
diff --git a/src/widgets/util/qflickgesture.cpp b/src/widgets/util/qflickgesture.cpp
index 064be873b9..f4198daa77 100644
--- a/src/widgets/util/qflickgesture.cpp
+++ b/src/widgets/util/qflickgesture.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgesture.h"
#include "qapplication.h"
@@ -48,7 +12,7 @@
#include "qgraphicsview.h"
#endif
#include "qscroller.h"
-#include <QtGui/qtouchdevice.h>
+#include <QtGui/qpointingdevice.h>
#include "private/qapplication_p.h"
#include "private/qevent_p.h"
#include "private/qflickgesture_p.h"
@@ -74,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->windowPos(), me->screenPos(),
- 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:
@@ -159,7 +99,7 @@ public:
if (!pressDelayEvent) {
pressDelayEvent.reset(copyMouseEvent(e));
pressDelayTimer = startTimer(delay);
- mouseTarget = QApplication::widgetAt(pressDelayEvent->globalPos());
+ mouseTarget = QApplication::widgetAt(pressDelayEvent->globalPosition().toPoint());
mouseButton = pressDelayEvent->button();
mouseEventSource = pressDelayEvent->source();
qFGDebug("QFG: consuming/delaying mouse press");
@@ -191,7 +131,7 @@ public:
result = true; // consume this event
} else if (mouseTarget && scrollerIsActive) {
- // we grabbed the mouse expicitly when the scroller became active, so undo that now
+ // we grabbed the mouse explicitly when the scroller became active, so undo that now
sendMouseEvent(nullptr, UngrabMouseBefore);
}
pressDelayEvent.reset(nullptr);
@@ -213,7 +153,7 @@ public:
mouseTarget = nullptr;
}
- void scrollerBecameActive()
+ void scrollerBecameActive(Qt::KeyboardModifiers eventModifiers, Qt::MouseButtons eventButtons)
{
if (pressDelayEvent) {
// we still haven't even sent the press, so just throw it away now
@@ -226,28 +166,12 @@ 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;
QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway, farFarAway,
- mouseButton, QGuiApplication::mouseButtons() & ~mouseButton,
- QGuiApplication::keyboardModifiers(), mouseEventSource);
+ mouseButton, eventButtons & ~mouseButton,
+ eventModifiers, mouseEventSource);
sendMouseEvent(&re, RegrabMouseAfterwards);
// don't clear the mouseTarget just yet, since we need to explicitly ungrab the mouse on release!
}
@@ -297,9 +221,11 @@ protected:
#endif // QT_CONFIG(graphicsview)
if (me) {
- QMouseEvent copy(me->type(), mouseTarget->mapFromGlobal(me->globalPos()),
- mouseTarget->topLevelWidget()->mapFromGlobal(me->globalPos()), me->screenPos(),
- me->button(), me->buttons(), me->modifiers(), me->source());
+ QMouseEvent copy(me->type(), mouseTarget->mapFromGlobal(me->globalPosition()),
+ 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);
}
@@ -398,7 +324,7 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
{
Q_UNUSED(watched);
- static QElapsedTimer monotonicTimer;
+ Q_CONSTINIT static QElapsedTimer monotonicTimer;
if (!monotonicTimer.isValid())
monotonicTimer.start();
@@ -429,6 +355,8 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
// qFGDebug() << "FlickGesture "<<state<<"watched:"<<watched<<"receiver"<<d->receiver<<"event"<<event->type()<<"button"<<button;
+ Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier;
+ Qt::MouseButtons mouseButtons = Qt::NoButton;
switch (event->type()) {
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
@@ -437,7 +365,9 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
return Ignore;
if (button != Qt::NoButton) {
me = static_cast<const QMouseEvent *>(event);
- globalPos = me->globalPos();
+ keyboardModifiers = me->modifiers();
+ mouseButtons = me->buttons();
+ globalPos = me->globalPosition().toPoint();
}
break;
#if QT_CONFIG(graphicsview)
@@ -448,6 +378,8 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
return Ignore;
if (button != Qt::NoButton) {
gsme = static_cast<const QGraphicsSceneMouseEvent *>(event);
+ keyboardModifiers = gsme->modifiers();
+ mouseButtons = gsme->buttons();
globalPos = gsme->screenPos();
}
break;
@@ -457,8 +389,9 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
case QEvent::TouchUpdate:
if (button == Qt::NoButton) {
te = static_cast<const QTouchEvent *>(event);
- if (!te->touchPoints().isEmpty())
- globalPos = te->touchPoints().at(0).screenPos().toPoint();
+ keyboardModifiers = te->modifiers();
+ if (!te->points().isEmpty())
+ globalPos = te->points().at(0).globalPosition().toPoint();
}
break;
@@ -492,7 +425,7 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
switch (event->type()) {
case QEvent::MouseButtonPress:
if (me && me->button() == button && me->buttons() == button) {
- point = me->globalPos();
+ point = me->globalPosition().toPoint();
inputType = QScroller::InputPress;
} else if (me) {
scroller->stop();
@@ -501,13 +434,13 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
break;
case QEvent::MouseButtonRelease:
if (me && me->button() == button) {
- point = me->globalPos();
+ point = me->globalPosition().toPoint();
inputType = QScroller::InputRelease;
}
break;
case QEvent::MouseMove:
if (me && me->buttons() == button) {
- point = me->globalPos();
+ point = me->globalPosition().toPoint();
inputType = QScroller::InputMove;
}
break;
@@ -547,18 +480,18 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
if (!inputType)
inputType = QScroller::InputMove;
- if (te->device()->type() == QTouchDevice::TouchPad) {
- if (te->touchPoints().count() != 2) // 2 fingers on pad
+ if (te->pointingDevice()->type() == QInputDevice::DeviceType::TouchPad) {
+ if (te->points().size() != 2) // 2 fingers on pad
return Ignore;
- point = te->touchPoints().at(0).startScenePos() +
- ((te->touchPoints().at(0).scenePos() - te->touchPoints().at(0).startScenePos()) +
- (te->touchPoints().at(1).scenePos() - te->touchPoints().at(1).startScenePos())) / 2;
+ point = te->points().at(0).scenePressPosition() +
+ ((te->points().at(0).scenePosition() - te->points().at(0).scenePressPosition()) +
+ (te->points().at(1).scenePosition() - te->points().at(1).scenePressPosition())) / 2;
} else { // TouchScreen
- if (te->touchPoints().count() != 1) // 1 finger on screen
+ if (te->points().size() != 1) // 1 finger on screen
return Ignore;
- point = te->touchPoints().at(0).scenePos();
+ point = te->points().at(0).scenePosition();
}
break;
@@ -634,7 +567,7 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
#endif
) {
if (!scrollerWasDragging && !scrollerWasScrolling && scrollerIsActive)
- PressDelayHandler::instance()->scrollerBecameActive();
+ PressDelayHandler::instance()->scrollerBecameActive(keyboardModifiers, mouseButtons);
else if (scrollerWasScrolling && (scroller->state() == QScroller::Dragging || scroller->state() == QScroller::Inactive))
PressDelayHandler::instance()->scrollerWasIntercepted();
}
diff --git a/src/widgets/util/qflickgesture_p.h b/src/widgets/util/qflickgesture_p.h
index 0b47516047..e8306b77e8 100644
--- a/src/widgets/util/qflickgesture_p.h
+++ b/src/widgets/util/qflickgesture_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFLICKGESTURE_P_H
#define QFLICKGESTURE_P_H
@@ -56,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 fec373d45c..1192a0be60 100644
--- a/src/widgets/util/qscroller.cpp
+++ b/src/widgets/util/qscroller.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qevent.h"
#include "qwidget.h"
@@ -57,29 +21,22 @@
#include <QGraphicsScene>
#include <QGraphicsView>
#endif
-#include <QDesktopWidget>
-#include <private/qdesktopwidget_p.h>
#include <QVector2D>
#include <QtCore/qmath.h>
#include <QtGui/qevent.h>
#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;
@@ -87,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
@@ -158,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;
}
@@ -170,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))
@@ -262,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.
- Several examples in the \c scroller examples directory show how QScroller,
- QScrollEvent and the scroller gesture can be used.
-
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
@@ -612,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;
@@ -688,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;
@@ -752,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;
@@ -981,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;
@@ -1050,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))
@@ -1065,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())))
@@ -1073,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;
@@ -1110,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;
}
@@ -1196,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);
@@ -1205,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();
@@ -1213,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
@@ -1248,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) ||
@@ -1262,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;
}
@@ -1271,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))
@@ -1281,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)
@@ -1305,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;
}
@@ -1331,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);
}
@@ -1376,7 +1360,7 @@ void QScrollerPrivate::createScrollingSegments(const QPointF &v,
// v(t) = deltaTime * a * 0.5 * differentialForProgress(t / deltaTime)
// v(0) = vrelease
// v(deltaTime) = 0
- // deltaTime = (2 * vrelease) / (a * differntial(0))
+ // deltaTime = (2 * vrelease) / (a * differential(0))
// pos(t) = integrate(v(t)dt)
// pos(t) = vrelease * t - 0.5 * a * t * t
@@ -1384,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);
@@ -1403,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;
@@ -1420,10 +1407,10 @@ bool QScrollerPrivate::prepareScrolling(const QPointF &position)
// - check if the content position was moved
if (contentDelta != QPointF(0, 0)) {
// need to correct all segments
- for (int i = 0; i < xSegments.count(); i++)
+ for (int i = 0; i < xSegments.size(); i++)
xSegments[i].startPos -= contentDelta.x();
- for (int i = 0; i < ySegments.count(); i++)
+ for (int i = 0; i < ySegments.size(); i++)
ySegments[i].startPos -= contentDelta.y();
}
@@ -1462,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);
@@ -1489,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;
}
@@ -1589,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);
@@ -1634,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);
@@ -1646,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())
@@ -1681,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:
@@ -1759,10 +1740,9 @@ 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 oldClampedPos = clampToRect(oldPos, contentPosRange);
QPointF newClampedPos = clampToRect(newPos, contentPosRange);
// --- handle overshooting and stop if the coordinate is going back inside the normal area
@@ -1777,21 +1757,17 @@ void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos)
bool canOvershootX = !noOvershootX && (alwaysOvershootX || contentPosRange.width());
bool canOvershootY = !noOvershootY && (alwaysOvershootY || contentPosRange.height());
- qreal oldOvershootX = (canOvershootX) ? oldPos.x() - oldClampedPos.x() : 0;
- qreal oldOvershootY = (canOvershootY) ? oldPos.y() - oldClampedPos.y() : 0;
-
qreal newOvershootX = (canOvershootX) ? newPos.x() - newClampedPos.x() : 0;
qreal newOvershootY = (canOvershootY) ? newPos.y() - newClampedPos.y() : 0;
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) {
- oldOvershootX *= sp->overshootDragResistanceFactor;
- oldOvershootY *= sp->overshootDragResistanceFactor;
newOvershootX *= sp->overshootDragResistanceFactor;
newOvershootY *= sp->overshootDragResistanceFactor;
}
@@ -1809,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;
}
@@ -1850,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);
@@ -1858,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
@@ -1993,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/qscroller.h b/src/widgets/util/qscroller.h
index ca8d059f50..a9f31218a4 100644
--- a/src/widgets/util/qscroller.h
+++ b/src/widgets/util/qscroller.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSCROLLER_H
#define QSCROLLER_H
@@ -62,7 +26,8 @@ class Q_WIDGETS_EXPORT QScroller : public QObject
{
Q_OBJECT
Q_PROPERTY(State state READ state NOTIFY stateChanged)
- Q_PROPERTY(QScrollerProperties scrollerProperties READ scrollerProperties WRITE setScrollerProperties NOTIFY scrollerPropertiesChanged)
+ Q_PROPERTY(QScrollerProperties scrollerProperties READ scrollerProperties
+ WRITE setScrollerProperties NOTIFY scrollerPropertiesChanged)
public:
enum State
diff --git a/src/widgets/util/qscroller_p.h b/src/widgets/util/qscroller_p.h
index 13e2032a5c..aadf58704d 100644
--- a/src/widgets/util/qscroller_p.h
+++ b/src/widgets/util/qscroller_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSCROLLER_P_H
#define QSCROLLER_P_H
diff --git a/src/widgets/util/qscrollerproperties.cpp b/src/widgets/util/qscrollerproperties.cpp
index be763f182e..ff8b695f61 100644
--- a/src/widgets/util/qscrollerproperties.cpp
+++ b/src/widgets/util/qscrollerproperties.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QPointer>
#include <QObject>
@@ -46,6 +10,11 @@
QT_BEGIN_NAMESPACE
+QT_IMPL_METATYPE_EXTERN_TAGGED(QScrollerProperties::OvershootPolicy,
+ QScrollerProperties__OvershootPolicy)
+QT_IMPL_METATYPE_EXTERN_TAGGED(QScrollerProperties::FrameRates,
+ QScrollerProperties__FrameRates)
+
static QScrollerPropertiesPrivate *userDefaults = nullptr;
static QScrollerPropertiesPrivate *systemDefaults = nullptr;
@@ -347,13 +316,13 @@ void QScrollerProperties::setScrollMetric(ScrollMetric metric, const QVariant &v
\value AcceleratingFlickSpeedupFactor The current speed is multiplied by this number if an
accelerating flick is detected. Should be \c{>= 1}.
- \value SnapPositionRatio This is the distance that the user must drag the area beween two snap
+ \value SnapPositionRatio This is the distance that the user must drag the area between two snap
points in order to snap it to the next position. \c{0.33} means that the scroll must only
reach one third of the distance between two snap points to snap to the next one. The ratio must
be between \c 0 and \c 1.
\value SnapTime This is the time factor for the scrolling curve. A lower value means that the
- scrolling will take longer. The scrolling distance is independet of this value.
+ scrolling will take longer. The scrolling distance is independent of this value.
\value OvershootDragResistanceFactor This value is the factor between the mouse dragging and
the actual scroll area movement (during overshoot). The factor must be between \c 0 and \c 1.
diff --git a/src/widgets/util/qscrollerproperties.h b/src/widgets/util/qscrollerproperties.h
index 2fc1a5dc18..ad301a6ad6 100644
--- a/src/widgets/util/qscrollerproperties.h
+++ b/src/widgets/util/qscrollerproperties.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSCROLLERPROPERTIES_H
#define QSCROLLERPROPERTIES_H
@@ -130,7 +94,9 @@ private:
QT_END_NAMESPACE
-Q_DECLARE_METATYPE(QScrollerProperties::OvershootPolicy)
-Q_DECLARE_METATYPE(QScrollerProperties::FrameRates)
+QT_DECL_METATYPE_EXTERN_TAGGED(QScrollerProperties::OvershootPolicy,
+ QScrollerProperties__OvershootPolicy, Q_WIDGETS_EXPORT)
+QT_DECL_METATYPE_EXTERN_TAGGED(QScrollerProperties::FrameRates,
+ QScrollerProperties__FrameRates, Q_WIDGETS_EXPORT)
#endif // QSCROLLERPROPERTIES_H
diff --git a/src/widgets/util/qscrollerproperties_p.h b/src/widgets/util/qscrollerproperties_p.h
index 7965171321..1ff5de3f11 100644
--- a/src/widgets/util/qscrollerproperties_p.h
+++ b/src/widgets/util/qscrollerproperties_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSCROLLERPROPERTIES_P_H
#define QSCROLLERPROPERTIES_P_H
diff --git a/src/widgets/util/qsystemtrayicon.cpp b/src/widgets/util/qsystemtrayicon.cpp
index ee52139913..2a55f014e1 100644
--- a/src/widgets/util/qsystemtrayicon.cpp
+++ b/src/widgets/util/qsystemtrayicon.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qsystemtrayicon.h"
#include "qsystemtrayicon_p.h"
@@ -60,8 +24,6 @@
#include "qstyle.h"
#include "qgridlayout.h"
#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
#include "qbitmap.h"
#include <private/qhighdpiscaling_p.h>
@@ -99,18 +61,18 @@ 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:
\list
\li All supported versions of Windows.
- \li All window managers and independent tray implementations for X11 that implement the
- \l{http://standards.freedesktop.org/systemtray-spec/systemtray-spec-0.2.html freedesktop.org}
- XEmbed system tray specification.
- \li All X11 desktop environments that implement the D-Bus
+ \li All Linux desktop environments that implement the D-Bus
\l{http://www.freedesktop.org/wiki/Specifications/StatusNotifierItem/StatusNotifierItem}
- specification, including recent versions of KDE and Unity.
+ {StatusNotifierItem specification}, including KDE, Gnome, Xfce, LXQt, and DDE.
+ \li All window managers and independent tray implementations for X11 that implement the
+ \l{http://standards.freedesktop.org/systemtray-spec/systemtray-spec-0.2.html}
+ {freedesktop.org XEmbed system tray specification}.
\li All supported versions of \macos.
\endlist
@@ -130,9 +92,11 @@ static QIcon messageIcon2qIcon(QSystemTrayIcon::MessageIcon icon)
Only on X11, when a tooltip is requested, the QSystemTrayIcon receives a QHelpEvent
of type QEvent::ToolTip. Additionally, the QSystemTrayIcon receives wheel events of
- type QEvent::Wheel. These are not supported on any other platform.
+ type QEvent::Wheel. These are not supported on any other platform. Note: Since GNOME
+ Shell version 3.26, not all QSystemTrayIcon::ActivationReason are supported by the
+ system without shell extensions installed.
- \sa QDesktopServices, QDesktopWidget, {Desktop Integration}, {System Tray Icon Example}
+ \sa QDesktopServices, {Desktop Integration}, {System Tray Icon Example}
*/
/*!
@@ -190,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 currenly 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.
@@ -201,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,
@@ -533,7 +498,7 @@ QBalloonTip::QBalloonTip(const QIcon &icon, const QString &title,
msgLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft);
// smart size for the message label
- int limit = QDesktopWidgetPrivate::availableGeometry(msgLabel).size().width() / 3;
+ int limit = QWidgetPrivate::availableScreenGeometry(msgLabel).width() / 3;
if (msgLabel->sizeHint().width() > limit) {
msgLabel->setWordWrap(true);
if (msgLabel->sizeHint().width() > limit) {
@@ -600,12 +565,15 @@ void QBalloonTip::resizeEvent(QResizeEvent *ev)
void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
{
this->showArrow = showArrow;
- QRect scr = QDesktopWidgetPrivate::screenGeometry(pos);
+ QScreen *screen = QGuiApplication::screenAt(pos);
+ if (!screen)
+ screen = QGuiApplication::primaryScreen();
+ QRect screenRect = screen->geometry();
QSize sh = sizeHint();
const int border = 1;
const int ah = 18, ao = 18, aw = 18, rc = 7;
- bool arrowAtTop = (pos.y() + sh.height() + ah < scr.height());
- bool arrowAtLeft = (pos.x() + sh.width() - ao < scr.width());
+ bool arrowAtTop = (pos.y() + sh.height() + ah < screenRect.height());
+ bool arrowAtLeft = (pos.x() + sh.width() - ao < screenRect.width());
setContentsMargins(border + 3, border + (arrowAtTop ? ah : 0) + 2, border + 3, border + (arrowAtTop ? 0 : ah) + 2);
updateGeometry();
sh = sizeHint();
@@ -631,14 +599,14 @@ void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
path.lineTo(ml + ao, mt - ah);
path.lineTo(ml + ao + aw, mt);
}
- move(qMax(pos.x() - ao, scr.left() + 2), pos.y());
+ move(qMax(pos.x() - ao, screenRect.left() + 2), pos.y());
} else if (arrowAtTop && !arrowAtLeft) {
if (showArrow) {
path.lineTo(mr - ao - aw, mt);
path.lineTo(mr - ao, mt - ah);
path.lineTo(mr - ao, mt);
}
- move(qMin(pos.x() - sh.width() + ao, scr.right() - sh.width() - 2), pos.y());
+ move(qMin(pos.x() - sh.width() + ao, screenRect.right() - sh.width() - 2), pos.y());
}
path.lineTo(mr - rc, mt);
path.arcTo(QRect(mr - rc*2, mt, rc*2, rc*2), 90, -90);
@@ -650,7 +618,7 @@ void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
path.lineTo(mr - ao, mb + ah);
path.lineTo(mr - ao - aw, mb);
}
- move(qMin(pos.x() - sh.width() + ao, scr.right() - sh.width() - 2),
+ move(qMin(pos.x() - sh.width() + ao, screenRect.right() - sh.width() - 2),
pos.y() - sh.height());
} else if (!arrowAtTop && arrowAtLeft) {
if (showArrow) {
@@ -658,7 +626,7 @@ void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
path.lineTo(ao, mb + ah);
path.lineTo(ao, mb);
}
- move(qMax(pos.x() - ao, scr.x() + 2), pos.y() - sh.height());
+ move(qMax(pos.x() - ao, screenRect.x() + 2), pos.y() - sh.height());
}
path.lineTo(ml + rc, mb);
path.arcTo(QRect(ml, mb - rc*2, rc*2, rc*2), -90, -90);
@@ -689,7 +657,7 @@ void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
void QBalloonTip::mousePressEvent(QMouseEvent *e)
{
close();
- if(e->button() == Qt::LeftButton)
+ if (e->button() == Qt::LeftButton)
emit trayIcon->messageClicked();
}
@@ -746,7 +714,7 @@ void QSystemTrayIconPrivate::addPlatformMenu(QMenu *menu) const
if (platformMenu)
menu->setPlatformMenu(platformMenu);
#else
- Q_UNUSED(menu)
+ Q_UNUSED(menu);
#endif // QT_CONFIG(menu)
}
diff --git a/src/widgets/util/qsystemtrayicon.h b/src/widgets/util/qsystemtrayicon.h
index e4652b742c..0a77ba03b7 100644
--- a/src/widgets/util/qsystemtrayicon.h
+++ b/src/widgets/util/qsystemtrayicon.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSYSTEMTRAYICON_H
#define QSYSTEMTRAYICON_H
diff --git a/src/widgets/util/qsystemtrayicon_p.h b/src/widgets/util/qsystemtrayicon_p.h
index e31532ea19..5f9509df4d 100644
--- a/src/widgets/util/qsystemtrayicon_p.h
+++ b/src/widgets/util/qsystemtrayicon_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSYSTEMTRAYICON_P_H
#define QSYSTEMTRAYICON_P_H
diff --git a/src/widgets/util/qsystemtrayicon_qpa.cpp b/src/widgets/util/qsystemtrayicon_qpa.cpp
index f2b0819132..63b24873db 100644
--- a/src/widgets/util/qsystemtrayicon_qpa.cpp
+++ b/src/widgets/util/qsystemtrayicon_qpa.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qsystemtrayicon_p.h"
@@ -53,7 +17,7 @@ QT_BEGIN_NAMESPACE
QSystemTrayIconPrivate::QSystemTrayIconPrivate()
: qpa_sys(QGuiApplicationPrivate::platformTheme()->createPlatformSystemTrayIcon())
- , visible(false)
+ , visible(false), trayWatcher(nullptr)
{
}
@@ -95,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/util/qsystemtrayicon_x11.cpp b/src/widgets/util/qsystemtrayicon_x11.cpp
index 86c11f98ed..2983dc6646 100644
--- a/src/widgets/util/qsystemtrayicon_x11.cpp
+++ b/src/widgets/util/qsystemtrayicon_x11.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtwidgetsglobal.h"
#if QT_CONFIG(label)
@@ -66,6 +30,8 @@
#ifndef QT_NO_SYSTEMTRAYICON
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
static inline unsigned long locateSystemTray()
{
return (unsigned long)QGuiApplication::platformNativeInterface()->nativeResourceForScreen(QByteArrayLiteral("traywindow"), QGuiApplication::primaryScreen());
@@ -120,12 +86,12 @@ QRect QSystemTrayIconSys::globalGeometry() const
void QSystemTrayIconSys::mousePressEvent(QMouseEvent *ev)
{
- QPoint globalPos = ev->globalPos();
+ QPoint globalPos = ev->globalPosition().toPoint();
#ifndef QT_NO_CONTEXTMENU
if (ev->button() == Qt::RightButton && q->contextMenu())
q->contextMenu()->popup(globalPos);
#else
- Q_UNUSED(globalPos)
+ Q_UNUSED(globalPos);
#endif // QT_NO_CONTEXTMENU
if (QBalloonTip::isBalloonVisible()) {
@@ -137,7 +103,7 @@ void QSystemTrayIconSys::mousePressEvent(QMouseEvent *ev)
emit q->activated(QSystemTrayIcon::Trigger);
else if (ev->button() == Qt::RightButton)
emit q->activated(QSystemTrayIcon::Context);
- else if (ev->button() == Qt::MidButton)
+ else if (ev->button() == Qt::MiddleButton)
emit q->activated(QSystemTrayIcon::MiddleClick);
}
@@ -308,7 +274,7 @@ void QSystemTrayIconPrivate::updateToolTip_sys()
}
if (!sys)
return;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
sys->setToolTip(toolTip);
#endif
}
@@ -321,7 +287,7 @@ bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
// no QPlatformSystemTrayIcon so fall back to default xcb platform behavior
const QString platform = QGuiApplication::platformName();
- if (platform.compare(QLatin1String("xcb"), Qt::CaseInsensitive) == 0)
+ if (platform.compare("xcb"_L1, Qt::CaseInsensitive) == 0)
return locateSystemTray();
return false;
}
diff --git a/src/widgets/util/qundogroup.cpp b/src/widgets/util/qundogroup.cpp
deleted file mode 100644
index ae439743bc..0000000000
--- a/src/widgets/util/qundogroup.cpp
+++ /dev/null
@@ -1,502 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qundogroup.h"
-#include "qundostack.h"
-#include "qundostack_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QUndoGroupPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QUndoGroup)
-public:
- QUndoGroupPrivate() : active(nullptr) {}
-
- QUndoStack *active;
- QList<QUndoStack*> stack_list;
-};
-
-/*!
- \class QUndoGroup
- \brief The QUndoGroup class is a group of QUndoStack objects.
- \since 4.2
- \inmodule QtWidgets
-
- For an overview of the Qt's undo framework, see the
- \l{qundo.html}{overview}.
-
- An application often has multiple undo stacks, one for each opened document. At the
- same time, an application usually has one undo action and one redo action, which
- triggers undo or redo in the active document.
-
- QUndoGroup is a group of QUndoStack objects, one of which may be active. It has
- an undo() and redo() slot, which calls QUndoStack::undo() and QUndoStack::redo()
- for the active stack. It also has the functions createUndoAction() and createRedoAction().
- The actions returned by these functions behave in the same way as those returned by
- QUndoStack::createUndoAction() and QUndoStack::createRedoAction() of the active
- stack.
-
- Stacks are added to a group with addStack() and removed with removeStack(). A stack
- is implicitly added to a group when it is created with the group as its parent
- QObject.
-
- It is the programmer's responsibility to specify which stack is active by
- calling QUndoStack::setActive(), usually when the associated document window receives focus.
- The active stack may also be set with setActiveStack(), and is returned by activeStack().
-
- When a stack is added to a group using addStack(), the group does not take ownership
- of the stack. This means the stack has to be deleted separately from the group. When
- a stack is deleted, it is automatically removed from a group. A stack may belong to
- only one group. Adding it to another group will cause it to be removed from the previous
- group.
-
- A QUndoGroup is also useful in conjunction with QUndoView. If a QUndoView is
- set to watch a group using QUndoView::setGroup(), it will update itself to display
- the active stack.
-*/
-
-/*!
- Creates an empty QUndoGroup object with parent \a parent.
-
- \sa addStack()
-*/
-
-QUndoGroup::QUndoGroup(QObject *parent)
- : QObject(*new QUndoGroupPrivate(), parent)
-{
-}
-
-/*!
- Destroys the QUndoGroup.
-*/
-QUndoGroup::~QUndoGroup()
-{
- // Ensure all QUndoStacks no longer refer to this group.
- Q_D(QUndoGroup);
- QList<QUndoStack *>::iterator it = d->stack_list.begin();
- QList<QUndoStack *>::iterator end = d->stack_list.end();
- while (it != end) {
- (*it)->d_func()->group = nullptr;
- ++it;
- }
-}
-
-/*!
- Adds \a stack to this group. The group does not take ownership of the stack. Another
- way of adding a stack to a group is by specifying the group as the stack's parent
- QObject in QUndoStack::QUndoStack(). In this case, the stack is deleted when the
- group is deleted, in the usual manner of QObjects.
-
- \sa removeStack(), stacks(), QUndoStack::QUndoStack()
-*/
-
-void QUndoGroup::addStack(QUndoStack *stack)
-{
- Q_D(QUndoGroup);
-
- if (d->stack_list.contains(stack))
- return;
- d->stack_list.append(stack);
-
- if (QUndoGroup *other = stack->d_func()->group)
- other->removeStack(stack);
- stack->d_func()->group = this;
-}
-
-/*!
- Removes \a stack from this group. If the stack was the active stack in the group,
- the active stack becomes 0.
-
- \sa addStack(), stacks(), QUndoStack::~QUndoStack()
-*/
-
-void QUndoGroup::removeStack(QUndoStack *stack)
-{
- Q_D(QUndoGroup);
-
- if (d->stack_list.removeAll(stack) == 0)
- return;
- if (stack == d->active)
- setActiveStack(nullptr);
- stack->d_func()->group = nullptr;
-}
-
-/*!
- Returns a list of stacks in this group.
-
- \sa addStack(), removeStack()
-*/
-
-QList<QUndoStack*> QUndoGroup::stacks() const
-{
- Q_D(const QUndoGroup);
- return d->stack_list;
-}
-
-/*!
- Sets the active stack of this group to \a stack.
-
- If the stack is not a member of this group, this function does nothing.
-
- Synonymous with calling QUndoStack::setActive() on \a stack.
-
- The actions returned by createUndoAction() and createRedoAction() will now behave
- in the same way as those returned by \a stack's QUndoStack::createUndoAction()
- and QUndoStack::createRedoAction().
-
- \sa QUndoStack::setActive(), activeStack()
-*/
-
-void QUndoGroup::setActiveStack(QUndoStack *stack)
-{
- Q_D(QUndoGroup);
- if (d->active == stack)
- return;
-
- if (d->active != nullptr) {
- disconnect(d->active, SIGNAL(canUndoChanged(bool)),
- this, SIGNAL(canUndoChanged(bool)));
- disconnect(d->active, SIGNAL(undoTextChanged(QString)),
- this, SIGNAL(undoTextChanged(QString)));
- disconnect(d->active, SIGNAL(canRedoChanged(bool)),
- this, SIGNAL(canRedoChanged(bool)));
- disconnect(d->active, SIGNAL(redoTextChanged(QString)),
- this, SIGNAL(redoTextChanged(QString)));
- disconnect(d->active, SIGNAL(indexChanged(int)),
- this, SIGNAL(indexChanged(int)));
- disconnect(d->active, SIGNAL(cleanChanged(bool)),
- this, SIGNAL(cleanChanged(bool)));
- }
-
- d->active = stack;
-
- if (d->active == nullptr) {
- emit canUndoChanged(false);
- emit undoTextChanged(QString());
- emit canRedoChanged(false);
- emit redoTextChanged(QString());
- emit cleanChanged(true);
- emit indexChanged(0);
- } else {
- connect(d->active, SIGNAL(canUndoChanged(bool)),
- this, SIGNAL(canUndoChanged(bool)));
- connect(d->active, SIGNAL(undoTextChanged(QString)),
- this, SIGNAL(undoTextChanged(QString)));
- connect(d->active, SIGNAL(canRedoChanged(bool)),
- this, SIGNAL(canRedoChanged(bool)));
- connect(d->active, SIGNAL(redoTextChanged(QString)),
- this, SIGNAL(redoTextChanged(QString)));
- connect(d->active, SIGNAL(indexChanged(int)),
- this, SIGNAL(indexChanged(int)));
- connect(d->active, SIGNAL(cleanChanged(bool)),
- this, SIGNAL(cleanChanged(bool)));
- emit canUndoChanged(d->active->canUndo());
- emit undoTextChanged(d->active->undoText());
- emit canRedoChanged(d->active->canRedo());
- emit redoTextChanged(d->active->redoText());
- emit cleanChanged(d->active->isClean());
- emit indexChanged(d->active->index());
- }
-
- emit activeStackChanged(d->active);
-}
-
-/*!
- Returns the active stack of this group.
-
- If none of the stacks are active, or if the group is empty, this function
- returns \nullptr.
-
- \sa setActiveStack(), QUndoStack::setActive()
-*/
-
-QUndoStack *QUndoGroup::activeStack() const
-{
- Q_D(const QUndoGroup);
- return d->active;
-}
-
-/*!
- Calls QUndoStack::undo() on the active stack.
-
- If none of the stacks are active, or if the group is empty, this function
- does nothing.
-
- \sa redo(), canUndo(), setActiveStack()
-*/
-
-void QUndoGroup::undo()
-{
- Q_D(QUndoGroup);
- if (d->active != nullptr)
- d->active->undo();
-}
-
-/*!
- Calls QUndoStack::redo() on the active stack.
-
- If none of the stacks are active, or if the group is empty, this function
- does nothing.
-
- \sa undo(), canRedo(), setActiveStack()
-*/
-
-
-void QUndoGroup::redo()
-{
- Q_D(QUndoGroup);
- if (d->active != nullptr)
- d->active->redo();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::canUndo().
-
- If none of the stacks are active, or if the group is empty, this function
- returns \c false.
-
- \sa canRedo(), setActiveStack()
-*/
-
-bool QUndoGroup::canUndo() const
-{
- Q_D(const QUndoGroup);
- return d->active != nullptr && d->active->canUndo();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::canRedo().
-
- If none of the stacks are active, or if the group is empty, this function
- returns \c false.
-
- \sa canUndo(), setActiveStack()
-*/
-
-bool QUndoGroup::canRedo() const
-{
- Q_D(const QUndoGroup);
- return d->active != nullptr && d->active->canRedo();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::undoText().
-
- If none of the stacks are active, or if the group is empty, this function
- returns an empty string.
-
- \sa redoText(), setActiveStack()
-*/
-
-QString QUndoGroup::undoText() const
-{
- Q_D(const QUndoGroup);
- return d->active == nullptr ? QString() : d->active->undoText();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::redoText().
-
- If none of the stacks are active, or if the group is empty, this function
- returns an empty string.
-
- \sa undoText(), setActiveStack()
-*/
-
-QString QUndoGroup::redoText() const
-{
- Q_D(const QUndoGroup);
- return d->active == nullptr ? QString() : d->active->redoText();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::isClean().
-
- If none of the stacks are active, or if the group is empty, this function
- returns \c true.
-
- \sa setActiveStack()
-*/
-
-bool QUndoGroup::isClean() const
-{
- Q_D(const QUndoGroup);
- return d->active == nullptr || d->active->isClean();
-}
-
-#ifndef QT_NO_ACTION
-
-/*!
- Creates an undo QAction object with parent \a parent.
-
- Triggering this action will cause a call to QUndoStack::undo() on the active stack.
- The text of this action will always be the text of the command which will be undone
- in the next call to undo(), prefixed by \a prefix. If there is no command available
- for undo, if the group is empty or if none of the stacks are active, this action will
- be disabled.
-
- If \a prefix is empty, the default template "Undo %1" is used instead of prefix.
- Before Qt 4.8, the prefix "Undo" was used by default.
-
- \sa createRedoAction(), canUndo(), QUndoCommand::text()
-*/
-
-QAction *QUndoGroup::createUndoAction(QObject *parent, const QString &prefix) const
-{
- QUndoAction *result = new QUndoAction(prefix, parent);
- if (prefix.isEmpty())
- result->setTextFormat(tr("Undo %1"), tr("Undo", "Default text for undo action"));
-
- result->setEnabled(canUndo());
- result->setPrefixedText(undoText());
- connect(this, SIGNAL(canUndoChanged(bool)),
- result, SLOT(setEnabled(bool)));
- connect(this, SIGNAL(undoTextChanged(QString)),
- result, SLOT(setPrefixedText(QString)));
- connect(result, SIGNAL(triggered()), this, SLOT(undo()));
- return result;
-}
-
-/*!
- Creates an redo QAction object with parent \a parent.
-
- Triggering this action will cause a call to QUndoStack::redo() on the active stack.
- The text of this action will always be the text of the command which will be redone
- in the next call to redo(), prefixed by \a prefix. If there is no command available
- for redo, if the group is empty or if none of the stacks are active, this action will
- be disabled.
-
- If \a prefix is empty, the default template "Redo %1" is used instead of prefix.
- Before Qt 4.8, the prefix "Redo" was used by default.
-
- \sa createUndoAction(), canRedo(), QUndoCommand::text()
-*/
-
-QAction *QUndoGroup::createRedoAction(QObject *parent, const QString &prefix) const
-{
- QUndoAction *result = new QUndoAction(prefix, parent);
- if (prefix.isEmpty())
- result->setTextFormat(tr("Redo %1"), tr("Redo", "Default text for redo action"));
-
- result->setEnabled(canRedo());
- result->setPrefixedText(redoText());
- connect(this, SIGNAL(canRedoChanged(bool)),
- result, SLOT(setEnabled(bool)));
- connect(this, SIGNAL(redoTextChanged(QString)),
- result, SLOT(setPrefixedText(QString)));
- connect(result, SIGNAL(triggered()), this, SLOT(redo()));
- return result;
-}
-
-#endif // QT_NO_ACTION
-
-/*! \fn void QUndoGroup::activeStackChanged(QUndoStack *stack)
-
- This signal is emitted whenever the active stack of the group changes. This can happen
- when setActiveStack() or QUndoStack::setActive() is called, or when the active stack
- is removed form the group. \a stack is the new active stack. If no stack is active,
- \a stack is 0.
-
- \sa setActiveStack(), QUndoStack::setActive()
-*/
-
-/*! \fn void QUndoGroup::indexChanged(int idx)
-
- This signal is emitted whenever the active stack emits QUndoStack::indexChanged()
- or the active stack changes.
-
- \a idx is the new current index, or 0 if the active stack is 0.
-
- \sa QUndoStack::indexChanged(), setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::cleanChanged(bool clean)
-
- This signal is emitted whenever the active stack emits QUndoStack::cleanChanged()
- or the active stack changes.
-
- \a clean is the new state, or true if the active stack is 0.
-
- \sa QUndoStack::cleanChanged(), setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::canUndoChanged(bool canUndo)
-
- This signal is emitted whenever the active stack emits QUndoStack::canUndoChanged()
- or the active stack changes.
-
- \a canUndo is the new state, or false if the active stack is 0.
-
- \sa QUndoStack::canUndoChanged(), setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::canRedoChanged(bool canRedo)
-
- This signal is emitted whenever the active stack emits QUndoStack::canRedoChanged()
- or the active stack changes.
-
- \a canRedo is the new state, or false if the active stack is 0.
-
- \sa QUndoStack::canRedoChanged(), setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::undoTextChanged(const QString &undoText)
-
- This signal is emitted whenever the active stack emits QUndoStack::undoTextChanged()
- or the active stack changes.
-
- \a undoText is the new state, or an empty string if the active stack is 0.
-
- \sa QUndoStack::undoTextChanged(), setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::redoTextChanged(const QString &redoText)
-
- This signal is emitted whenever the active stack emits QUndoStack::redoTextChanged()
- or the active stack changes.
-
- \a redoText is the new state, or an empty string if the active stack is 0.
-
- \sa QUndoStack::redoTextChanged(), setActiveStack()
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qundogroup.cpp"
diff --git a/src/widgets/util/qundogroup.h b/src/widgets/util/qundogroup.h
index 1845f7e057..379e03d5b1 100644
--- a/src/widgets/util/qundogroup.h
+++ b/src/widgets/util/qundogroup.h
@@ -1,101 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QUNDOGROUP_H
-#define QUNDOGROUP_H
+#if 0
+// syncqt: header is already part of QtGui/QtGui
+#pragma qt_no_master_include
+#endif
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtCore/qobject.h>
-#include <QtCore/qstring.h>
-
-QT_REQUIRE_CONFIG(undogroup);
+#include <QtGui/QUndoGroup>
QT_BEGIN_NAMESPACE
-
-class QUndoGroupPrivate;
-class QUndoStack;
-class QAction;
-
-class Q_WIDGETS_EXPORT QUndoGroup : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QUndoGroup)
-
-public:
- explicit QUndoGroup(QObject *parent = nullptr);
- ~QUndoGroup();
-
- void addStack(QUndoStack *stack);
- void removeStack(QUndoStack *stack);
- QList<QUndoStack*> stacks() const;
- QUndoStack *activeStack() const;
-
-#ifndef QT_NO_ACTION
- QAction *createUndoAction(QObject *parent,
- const QString &prefix = QString()) const;
- QAction *createRedoAction(QObject *parent,
- const QString &prefix = QString()) const;
-#endif // QT_NO_ACTION
- bool canUndo() const;
- bool canRedo() const;
- QString undoText() const;
- QString redoText() const;
- bool isClean() const;
-
-public Q_SLOTS:
- void undo();
- void redo();
- void setActiveStack(QUndoStack *stack);
-
-Q_SIGNALS:
- void activeStackChanged(QUndoStack *stack);
- void indexChanged(int idx);
- void cleanChanged(bool clean);
- void canUndoChanged(bool canUndo);
- void canRedoChanged(bool canRedo);
- void undoTextChanged(const QString &undoText);
- void redoTextChanged(const QString &redoText);
-
-private:
- Q_DISABLE_COPY(QUndoGroup)
-};
-
QT_END_NAMESPACE
-
-#endif // QUNDOGROUP_H
diff --git a/src/widgets/util/qundostack.cpp b/src/widgets/util/qundostack.cpp
deleted file mode 100644
index 8974f11a13..0000000000
--- a/src/widgets/util/qundostack.cpp
+++ /dev/null
@@ -1,1388 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtCore/qdebug.h>
-#include "qundostack.h"
-#if QT_CONFIG(undogroup)
-#include "qundogroup.h"
-#endif
-#include "qundostack_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QUndoCommand
- \brief The QUndoCommand class is the base class of all commands stored on a QUndoStack.
- \since 4.2
-
- \inmodule QtWidgets
-
- For an overview of Qt's Undo Framework, see the
- \l{Overview of Qt's Undo Framework}{overview document}.
-
- A QUndoCommand represents a single editing action on a document; for example,
- inserting or deleting a block of text in a text editor. QUndoCommand can apply
- a change to the document with redo() and undo the change with undo(). The
- implementations for these functions must be provided in a derived class.
-
- \snippet code/src_gui_util_qundostack.cpp 0
-
- A QUndoCommand has an associated text(). This is a short string
- describing what the command does. It is used to update the text
- properties of the stack's undo and redo actions; see
- QUndoStack::createUndoAction() and QUndoStack::createRedoAction().
-
- QUndoCommand objects are owned by the stack they were pushed on.
- QUndoStack deletes a command if it has been undone and a new command is pushed. For example:
-
-\snippet code/src_gui_util_qundostack.cpp 1
-
- In effect, when a command is pushed, it becomes the top-most command
- on the stack.
-
- To support command compression, QUndoCommand has an id() and the virtual function
- mergeWith(). These functions are used by QUndoStack::push().
-
- To support command macros, a QUndoCommand object can have any number of child
- commands. Undoing or redoing the parent command will cause the child
- commands to be undone or redone. A command can be assigned
- to a parent explicitly in the constructor. In this case, the command
- will be owned by the parent.
-
- The parent in this case is usually an empty command, in that it doesn't
- provide its own implementation of undo() and redo(). Instead, it uses
- the base implementations of these functions, which simply call undo() or
- redo() on all its children. The parent should, however, have a meaningful
- text().
-
- \snippet code/src_gui_util_qundostack.cpp 2
-
- Another way to create macros is to use the convenience functions
- QUndoStack::beginMacro() and QUndoStack::endMacro().
-
- \sa QUndoStack
-*/
-
-/*!
- Constructs a QUndoCommand object with the given \a parent and \a text.
-
- If \a parent is not \nullptr, this command is appended to parent's
- child list. The parent command then owns this command and will delete
- it in its destructor.
-
- \sa ~QUndoCommand()
-*/
-
-QUndoCommand::QUndoCommand(const QString &text, QUndoCommand *parent)
- : QUndoCommand(parent)
-{
- setText(text);
-}
-
-/*!
- Constructs a QUndoCommand object with parent \a parent.
-
- If \a parent is not \nullptr, this command is appended to parent's
- child list. The parent command then owns this command and will delete
- it in its destructor.
-
- \sa ~QUndoCommand()
-*/
-
-QUndoCommand::QUndoCommand(QUndoCommand *parent)
-{
- d = new QUndoCommandPrivate;
- if (parent != nullptr)
- parent->d->child_list.append(this);
-}
-
-/*!
- Destroys the QUndoCommand object and all child commands.
-
- \sa QUndoCommand()
-*/
-
-QUndoCommand::~QUndoCommand()
-{
- qDeleteAll(d->child_list);
- delete d;
-}
-
-/*!
- \since 5.9
-
- Returns whether the command is obsolete.
-
- The boolean is used for the automatic removal of commands that are not necessary in the
- stack anymore. The isObsolete function is checked in the functions QUndoStack::push(),
- QUndoStack::undo(), QUndoStack::redo(), and QUndoStack::setIndex().
-
- \sa setObsolete(), mergeWith(), QUndoStack::push(), QUndoStack::undo(), QUndoStack::redo()
-*/
-
-bool QUndoCommand::isObsolete() const
-{
- return d->obsolete;
-}
-
-/*!
- \since 5.9
-
- Sets whether the command is obsolete to \a obsolete.
-
- \sa isObsolete(), mergeWith(), QUndoStack::push(), QUndoStack::undo(), QUndoStack::redo()
-*/
-
-void QUndoCommand::setObsolete(bool obsolete)
-{
- d->obsolete = obsolete;
-}
-
-/*!
- Returns the ID of this command.
-
- A command ID is used in command compression. It must be an integer unique to
- this command's class, or -1 if the command doesn't support compression.
-
- If the command supports compression this function must be overridden in the
- derived class to return the correct ID. The base implementation returns -1.
-
- QUndoStack::push() will only try to merge two commands if they have the
- same ID, and the ID is not -1.
-
- \sa mergeWith(), QUndoStack::push()
-*/
-
-int QUndoCommand::id() const
-{
- return -1;
-}
-
-/*!
- Attempts to merge this command with \a command. Returns \c true on
- success; otherwise returns \c false.
-
- If this function returns \c true, calling this command's redo() must have the same
- effect as redoing both this command and \a command.
- Similarly, calling this command's undo() must have the same effect as undoing
- \a command and this command.
-
- QUndoStack will only try to merge two commands if they have the same id, and
- the id is not -1.
-
- The default implementation returns \c false.
-
- \snippet code/src_gui_util_qundostack.cpp 3
-
- \sa id(), QUndoStack::push()
-*/
-
-bool QUndoCommand::mergeWith(const QUndoCommand *command)
-{
- Q_UNUSED(command);
- return false;
-}
-
-/*!
- Applies a change to the document. This function must be implemented in
- the derived class. Calling QUndoStack::push(),
- QUndoStack::undo() or QUndoStack::redo() from this function leads to
- undefined beahavior.
-
- The default implementation calls redo() on all child commands.
-
- \sa undo()
-*/
-
-void QUndoCommand::redo()
-{
- for (int i = 0; i < d->child_list.size(); ++i)
- d->child_list.at(i)->redo();
-}
-
-/*!
- Reverts a change to the document. After undo() is called, the state of
- the document should be the same as before redo() was called. This function must
- be implemented in the derived class. Calling QUndoStack::push(),
- QUndoStack::undo() or QUndoStack::redo() from this function leads to
- undefined beahavior.
-
- The default implementation calls undo() on all child commands in reverse order.
-
- \sa redo()
-*/
-
-void QUndoCommand::undo()
-{
- for (int i = d->child_list.size() - 1; i >= 0; --i)
- d->child_list.at(i)->undo();
-}
-
-/*!
- Returns a short text string describing what this command does; for example,
- "insert text".
-
- The text is used for names of items in QUndoView.
-
- \sa actionText(), setText(), QUndoStack::createUndoAction(), QUndoStack::createRedoAction()
-*/
-
-QString QUndoCommand::text() const
-{
- return d->text;
-}
-
-/*!
- \since 4.8
-
- Returns a short text string describing what this command does; for example,
- "insert text".
-
- The text is used when the text properties of the stack's undo and redo
- actions are updated.
-
- \sa text(), setText(), QUndoStack::createUndoAction(), QUndoStack::createRedoAction()
-*/
-
-QString QUndoCommand::actionText() const
-{
- return d->actionText;
-}
-
-/*!
- Sets the command's text to be the \a text specified.
-
- The specified text should be a short user-readable string describing what this
- command does.
-
- If you need to have two different strings for text() and actionText(), separate
- them with "\\n" and pass into this function. Even if you do not use this feature
- for English strings during development, you can still let translators use two
- different strings in order to match specific languages' needs.
- The described feature and the function actionText() are available since Qt 4.8.
-
- \sa text(), actionText(), QUndoStack::createUndoAction(), QUndoStack::createRedoAction()
-*/
-
-void QUndoCommand::setText(const QString &text)
-{
- int cdpos = text.indexOf(QLatin1Char('\n'));
- if (cdpos > 0) {
- d->text = text.left(cdpos);
- d->actionText = text.mid(cdpos + 1);
- } else {
- d->text = text;
- d->actionText = text;
- }
-}
-
-/*!
- \since 4.4
-
- Returns the number of child commands in this command.
-
- \sa child()
-*/
-
-int QUndoCommand::childCount() const
-{
- return d->child_list.count();
-}
-
-/*!
- \since 4.4
-
- Returns the child command at \a index.
-
- \sa childCount(), QUndoStack::command()
-*/
-
-const QUndoCommand *QUndoCommand::child(int index) const
-{
- if (index < 0 || index >= d->child_list.count())
- return nullptr;
- return d->child_list.at(index);
-}
-
-#if QT_CONFIG(undostack)
-
-/*!
- \class QUndoStack
- \brief The QUndoStack class is a stack of QUndoCommand objects.
- \since 4.2
-
- \inmodule QtWidgets
-
- For an overview of Qt's Undo Framework, see the
- \l{Overview of Qt's Undo Framework}{overview document}.
-
- An undo stack maintains a stack of commands that have been applied to a
- document.
-
- New commands are pushed on the stack using push(). Commands can be
- undone and redone using undo() and redo(), or by triggering the
- actions returned by createUndoAction() and createRedoAction().
-
- QUndoStack keeps track of the \a current command. This is the command
- which will be executed by the next call to redo(). The index of this
- command is returned by index(). The state of the edited object can be
- rolled forward or back using setIndex(). If the top-most command on the
- stack has already been redone, index() is equal to count().
-
- QUndoStack provides support for undo and redo actions, command
- compression, command macros, and supports the concept of a
- \e{clean state}.
-
- \section1 Undo and Redo Actions
-
- QUndoStack provides convenient undo and redo QAction objects, which
- can be inserted into a menu or a toolbar. When commands are undone or
- redone, QUndoStack updates the text properties of these actions
- to reflect what change they will trigger. The actions are also disabled
- when no command is available for undo or redo. These actions
- are returned by QUndoStack::createUndoAction() and QUndoStack::createRedoAction().
-
- \section1 Command Compression and Macros
-
- Command compression is useful when several commands can be compressed
- into a single command that can be undone and redone in a single operation.
- For example, when a user types a character in a text editor, a new command
- is created. This command inserts the character into the document at the
- cursor position. However, it is more convenient for the user to be able
- to undo or redo typing of whole words, sentences, or paragraphs.
- Command compression allows these single-character commands to be merged
- into a single command which inserts or deletes sections of text.
- For more information, see QUndoCommand::mergeWith() and push().
-
- A command macro is a sequence of commands, all of which are undone and
- redone in one go. Command macros are created by giving a command a list
- of child commands.
- Undoing or redoing the parent command will cause the child commands to
- be undone or redone. Command macros may be created explicitly
- by specifying a parent in the QUndoCommand constructor, or by using the
- convenience functions beginMacro() and endMacro().
-
- Although command compression and macros appear to have the same effect to the
- user, they often have different uses in an application. Commands that
- perform small changes to a document may be usefully compressed if there is
- no need to individually record them, and if only larger changes are relevant
- to the user.
- However, for commands that need to be recorded individually, or those that
- cannot be compressed, it is useful to use macros to provide a more convenient
- user experience while maintaining a record of each command.
-
- \section1 Clean State
-
- QUndoStack supports the concept of a clean state. When the
- document is saved to disk, the stack can be marked as clean using
- setClean(). Whenever the stack returns to this state through undoing and
- redoing commands, it emits the signal cleanChanged(). This signal
- is also emitted when the stack leaves the clean state. This signal is
- usually used to enable and disable the save actions in the application,
- and to update the document's title to reflect that it contains unsaved
- changes.
-
- \section1 Obsolete Commands
-
- QUndoStack is able to delete commands from the stack if the command is no
- longer needed. One example may be to delete a command when two commands are
- merged together in such a way that the merged command has no function. This
- can be seen with move commands where the user moves their mouse to one part
- of the screen and then moves it to the original position. The merged command
- results in a mouse movement of 0. This command can be deleted since it serves
- no purpose. Another example is with networking commands that fail due to connection
- issues. In this case, the command is to be removed from the stack because the redo()
- and undo() functions have no function since there was connection issues.
-
- A command can be marked obsolete with the QUndoCommand::setObsolete() function.
- The QUndoCommand::isObsolete() flag is checked in QUndoStack::push(),
- QUndoStack::undo(), QUndoStack::redo(), and QUndoStack::setIndex() after calling
- QUndoCommand::undo(), QUndoCommand::redo() and QUndoCommand:mergeWith() where
- applicable.
-
- If a command is set obsolete and the clean index is greater than or equal to the
- current command index, then the clean index will be reset when the command is
- deleted from the stack.
-
- \sa QUndoCommand, QUndoView
-*/
-
-#if QT_CONFIG(action)
-
-QUndoAction::QUndoAction(const QString &prefix, QObject *parent)
- : QAction(parent)
-{
- m_prefix = prefix;
-}
-
-void QUndoAction::setPrefixedText(const QString &text)
-{
- if (m_defaultText.isEmpty()) {
- QString s = m_prefix;
- if (!m_prefix.isEmpty() && !text.isEmpty())
- s.append(QLatin1Char(' '));
- s.append(text);
- setText(s);
- } else {
- if (text.isEmpty())
- setText(m_defaultText);
- else
- setText(m_prefix.arg(text));
- }
-}
-
-void QUndoAction::setTextFormat(const QString &textFormat, const QString &defaultText)
-{
- m_prefix = textFormat;
- m_defaultText = defaultText;
-}
-
-#endif // QT_CONFIG(action)
-
-/*! \internal
- Sets the current index to \a idx, emitting appropriate signals. If \a clean is true,
- makes \a idx the clean index as well.
-*/
-
-void QUndoStackPrivate::setIndex(int idx, bool clean)
-{
- Q_Q(QUndoStack);
-
- bool was_clean = index == clean_index;
-
- if (idx != index) {
- index = idx;
- emit q->indexChanged(index);
- emit q->canUndoChanged(q->canUndo());
- emit q->undoTextChanged(q->undoText());
- emit q->canRedoChanged(q->canRedo());
- emit q->redoTextChanged(q->redoText());
- }
-
- if (clean)
- clean_index = index;
-
- bool is_clean = index == clean_index;
- if (is_clean != was_clean)
- emit q->cleanChanged(is_clean);
-}
-
-/*! \internal
- If the number of commands on the stack exceedes the undo limit, deletes commands from
- the bottom of the stack.
-
- Returns \c true if commands were deleted.
-*/
-
-bool QUndoStackPrivate::checkUndoLimit()
-{
- if (undo_limit <= 0 || !macro_stack.isEmpty() || undo_limit >= command_list.count())
- return false;
-
- int del_count = command_list.count() - undo_limit;
-
- for (int i = 0; i < del_count; ++i)
- delete command_list.takeFirst();
-
- index -= del_count;
- if (clean_index != -1) {
- if (clean_index < del_count)
- clean_index = -1; // we've deleted the clean command
- else
- clean_index -= del_count;
- }
-
- return true;
-}
-
-/*!
- Constructs an empty undo stack with the parent \a parent. The
- stack will initially be in the clean state. If \a parent is a
- QUndoGroup object, the stack is automatically added to the group.
-
- \sa push()
-*/
-
-QUndoStack::QUndoStack(QObject *parent)
- : QObject(*(new QUndoStackPrivate), parent)
-{
-#if QT_CONFIG(undogroup)
- if (QUndoGroup *group = qobject_cast<QUndoGroup*>(parent))
- group->addStack(this);
-#endif
-}
-
-/*!
- Destroys the undo stack, deleting any commands that are on it. If the
- stack is in a QUndoGroup, the stack is automatically removed from the group.
-
- \sa QUndoStack()
-*/
-
-QUndoStack::~QUndoStack()
-{
-#if QT_CONFIG(undogroup)
- Q_D(QUndoStack);
- if (d->group != nullptr)
- d->group->removeStack(this);
-#endif
- clear();
-}
-
-/*!
- Clears the command stack by deleting all commands on it, and returns the stack
- to the clean state.
-
- Commands are not undone or redone; the state of the edited object remains
- unchanged.
-
- This function is usually used when the contents of the document are
- abandoned.
-
- \sa QUndoStack()
-*/
-
-void QUndoStack::clear()
-{
- Q_D(QUndoStack);
-
- if (d->command_list.isEmpty())
- return;
-
- bool was_clean = isClean();
-
- d->macro_stack.clear();
- qDeleteAll(d->command_list);
- d->command_list.clear();
-
- d->index = 0;
- d->clean_index = 0;
-
- emit indexChanged(0);
- emit canUndoChanged(false);
- emit undoTextChanged(QString());
- emit canRedoChanged(false);
- emit redoTextChanged(QString());
-
- if (!was_clean)
- emit cleanChanged(true);
-}
-
-/*!
- Pushes \a cmd on the stack or merges it with the most recently executed command.
- In either case, executes \a cmd by calling its redo() function.
-
- If \a cmd's id is not -1, and if the id is the same as that of the
- most recently executed command, QUndoStack will attempt to merge the two
- commands by calling QUndoCommand::mergeWith() on the most recently executed
- command. If QUndoCommand::mergeWith() returns \c true, \a cmd is deleted.
-
- After calling QUndoCommand::redo() and, if applicable, QUndoCommand::mergeWith(),
- QUndoCommand::isObsolete() will be called for \a cmd or the merged command.
- If QUndoCommand::isObsolete() returns \c true, then \a cmd or the merged command
- will be deleted from the stack.
-
- In all other cases \a cmd is simply pushed on the stack.
-
- If commands were undone before \a cmd was pushed, the current command and
- all commands above it are deleted. Hence \a cmd always ends up being the
- top-most on the stack.
-
- Once a command is pushed, the stack takes ownership of it. There
- are no getters to return the command, since modifying it after it has
- been executed will almost always lead to corruption of the document's
- state.
-
- \sa QUndoCommand::id(), QUndoCommand::mergeWith()
-*/
-
-void QUndoStack::push(QUndoCommand *cmd)
-{
- Q_D(QUndoStack);
- if (!cmd->isObsolete())
- cmd->redo();
-
- bool macro = !d->macro_stack.isEmpty();
-
- QUndoCommand *cur = nullptr;
- if (macro) {
- QUndoCommand *macro_cmd = d->macro_stack.constLast();
- if (!macro_cmd->d->child_list.isEmpty())
- cur = macro_cmd->d->child_list.constLast();
- } else {
- if (d->index > 0)
- cur = d->command_list.at(d->index - 1);
- while (d->index < d->command_list.size())
- delete d->command_list.takeLast();
- if (d->clean_index > d->index)
- d->clean_index = -1; // we've deleted the clean state
- }
-
- bool try_merge = cur != nullptr
- && cur->id() != -1
- && cur->id() == cmd->id()
- && (macro || d->index != d->clean_index);
-
- if (try_merge && cur->mergeWith(cmd)) {
- delete cmd;
-
- if (macro) {
- if (cur->isObsolete())
- delete d->macro_stack.constLast()->d->child_list.takeLast();
- } else {
- if (cur->isObsolete()) {
- delete d->command_list.takeLast();
-
- d->setIndex(d->index - 1, false);
- } else {
- emit indexChanged(d->index);
- emit canUndoChanged(canUndo());
- emit undoTextChanged(undoText());
- emit canRedoChanged(canRedo());
- emit redoTextChanged(redoText());
- }
- }
- } else if (cmd->isObsolete()) {
- delete cmd; // command should be deleted and NOT added to the stack
- } else {
- if (macro) {
- d->macro_stack.constLast()->d->child_list.append(cmd);
- } else {
- d->command_list.append(cmd);
- d->checkUndoLimit();
- d->setIndex(d->index + 1, false);
- }
- }
-}
-
-/*!
- Marks the stack as clean and emits cleanChanged() if the stack was
- not already clean.
-
- This is typically called when a document is saved, for example.
-
- Whenever the stack returns to this state through the use of undo/redo
- commands, it emits the signal cleanChanged(). This signal is also
- emitted when the stack leaves the clean state.
-
- \sa isClean(), resetClean(), cleanIndex()
-*/
-
-void QUndoStack::setClean()
-{
- Q_D(QUndoStack);
- if (Q_UNLIKELY(!d->macro_stack.isEmpty())) {
- qWarning("QUndoStack::setClean(): cannot set clean in the middle of a macro");
- return;
- }
-
- d->setIndex(d->index, true);
-}
-
-/*!
- \since 5.8
-
- Leaves the clean state and emits cleanChanged() if the stack was clean.
- This method resets the clean index to -1.
-
- This is typically called in the following cases, when a document has been:
- \list
- \li created basing on some template and has not been saved,
- so no filename has been associated with the document yet.
- \li restored from a backup file.
- \li changed outside of the editor and the user did not reload it.
- \endlist
-
- \sa isClean(), setClean(), cleanIndex()
-*/
-
-void QUndoStack::resetClean()
-{
- Q_D(QUndoStack);
- const bool was_clean = isClean();
- d->clean_index = -1;
- if (was_clean)
- emit cleanChanged(false);
-}
-
-/*!
- \since 5.12
- \property QUndoStack::clean
- \brief the clean status of this stack.
-
- This property indicates whether or not the stack is clean. For example, a
- stack is clean when a document has been saved.
-
- \sa isClean(), setClean(), resetClean(), cleanIndex()
-*/
-
-/*!
- If the stack is in the clean state, returns \c true; otherwise returns \c false.
-
- \sa setClean(), cleanIndex()
-*/
-
-bool QUndoStack::isClean() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return false;
- return d->clean_index == d->index;
-}
-
-/*!
- Returns the clean index. This is the index at which setClean() was called.
-
- A stack may not have a clean index. This happens if a document is saved,
- some commands are undone, then a new command is pushed. Since
- push() deletes all the undone commands before pushing the new command, the stack
- can't return to the clean state again. In this case, this function returns -1.
- The -1 may also be returned after an explicit call to resetClean().
-
- \sa isClean(), setClean()
-*/
-
-int QUndoStack::cleanIndex() const
-{
- Q_D(const QUndoStack);
- return d->clean_index;
-}
-
-/*!
- Undoes the command below the current command by calling QUndoCommand::undo().
- Decrements the current command index.
-
- If the stack is empty, or if the bottom command on the stack has already been
- undone, this function does nothing.
-
- After the command is undone, if QUndoCommand::isObsolete() returns \c true,
- then the command will be deleted from the stack. Additionally, if the clean
- index is greater than or equal to the current command index, then the clean
- index is reset.
-
- \sa redo(), index()
-*/
-
-void QUndoStack::undo()
-{
- Q_D(QUndoStack);
- if (d->index == 0)
- return;
-
- if (Q_UNLIKELY(!d->macro_stack.isEmpty())) {
- qWarning("QUndoStack::undo(): cannot undo in the middle of a macro");
- return;
- }
-
- int idx = d->index - 1;
- QUndoCommand *cmd = d->command_list.at(idx);
-
- if (!cmd->isObsolete())
- cmd->undo();
-
- if (cmd->isObsolete()) { // A separate check is done b/c the undo command may set obsolete flag
- delete d->command_list.takeAt(idx);
-
- if (d->clean_index > idx)
- resetClean();
- }
-
- d->setIndex(idx, false);
-}
-
-/*!
- Redoes the current command by calling QUndoCommand::redo(). Increments the current
- command index.
-
- If the stack is empty, or if the top command on the stack has already been
- redone, this function does nothing.
-
- If QUndoCommand::isObsolete() returns true for the current command, then
- the command will be deleted from the stack. Additionally, if the clean
- index is greater than or equal to the current command index, then the clean
- index is reset.
-
- \sa undo(), index()
-*/
-
-void QUndoStack::redo()
-{
- Q_D(QUndoStack);
- if (d->index == d->command_list.size())
- return;
-
- if (Q_UNLIKELY(!d->macro_stack.isEmpty())) {
- qWarning("QUndoStack::redo(): cannot redo in the middle of a macro");
- return;
- }
-
- int idx = d->index;
- QUndoCommand *cmd = d->command_list.at(idx);
-
- if (!cmd->isObsolete())
- cmd->redo(); // A separate check is done b/c the undo command may set obsolete flag
-
- if (cmd->isObsolete()) {
- delete d->command_list.takeAt(idx);
-
- if (d->clean_index > idx)
- resetClean();
- } else {
- d->setIndex(d->index + 1, false);
- }
-}
-
-/*!
- Returns the number of commands on the stack. Macro commands are counted as
- one command.
-
- \sa index(), setIndex(), command()
-*/
-
-int QUndoStack::count() const
-{
- Q_D(const QUndoStack);
- return d->command_list.size();
-}
-
-/*!
- Returns the index of the current command. This is the command that will be
- executed on the next call to redo(). It is not always the top-most command
- on the stack, since a number of commands may have been undone.
-
- \sa undo(), redo(), count()
-*/
-
-int QUndoStack::index() const
-{
- Q_D(const QUndoStack);
- return d->index;
-}
-
-/*!
- Repeatedly calls undo() or redo() until the current command index reaches
- \a idx. This function can be used to roll the state of the document forwards
- of backwards. indexChanged() is emitted only once.
-
- \sa index(), count(), undo(), redo()
-*/
-
-void QUndoStack::setIndex(int idx)
-{
- Q_D(QUndoStack);
- if (Q_UNLIKELY(!d->macro_stack.isEmpty())) {
- qWarning("QUndoStack::setIndex(): cannot set index in the middle of a macro");
- return;
- }
-
- if (idx < 0)
- idx = 0;
- else if (idx > d->command_list.size())
- idx = d->command_list.size();
-
- int i = d->index;
- while (i < idx) {
- QUndoCommand *cmd = d->command_list.at(i);
-
- if (!cmd->isObsolete())
- cmd->redo(); // A separate check is done b/c the undo command may set obsolete flag
-
- if (cmd->isObsolete()) {
- delete d->command_list.takeAt(i);
-
- if (d->clean_index > i)
- resetClean();
-
- idx--; // Subtract from idx because we removed a command
- } else {
- i++;
- }
- }
-
- while (i > idx) {
- QUndoCommand *cmd = d->command_list.at(--i);
-
- cmd->undo();
- if (cmd->isObsolete()) {
- delete d->command_list.takeAt(i);
-
- if (d->clean_index > i)
- resetClean();
- }
- }
-
- d->setIndex(idx, false);
-}
-
-/*!
- \since 5.12
- \property QUndoStack::canUndo
- \brief whether this stack can undo.
-
- This property indicates whether or not there is a command that can be
- undone.
-
- \sa canUndo(), index(), canRedo()
-*/
-
-/*!
- Returns \c true if there is a command available for undo; otherwise returns \c false.
-
- This function returns \c false if the stack is empty, or if the bottom command
- on the stack has already been undone.
-
- Synonymous with index() == 0.
-
- \sa index(), canRedo()
-*/
-
-bool QUndoStack::canUndo() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return false;
- return d->index > 0;
-}
-
-/*!
- \since 5.12
- \property QUndoStack::canRedo
- \brief whether this stack can redo.
-
- This property indicates whether or not there is a command that can be
- redone.
-
- \sa canRedo(), index(), canUndo()
-*/
-
-/*!
- Returns \c true if there is a command available for redo; otherwise returns \c false.
-
- This function returns \c false if the stack is empty or if the top command
- on the stack has already been redone.
-
- Synonymous with index() == count().
-
- \sa index(), canUndo()
-*/
-
-bool QUndoStack::canRedo() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return false;
- return d->index < d->command_list.size();
-}
-
-/*!
- \since 5.12
- \property QUndoStack::undoText
- \brief the undo text of the next command that is undone.
-
- This property holds the text of the command which will be undone in the
- next call to undo().
-
- \sa undoText(), QUndoCommand::actionText(), redoText()
-*/
-
-/*!
- Returns the text of the command which will be undone in the next call to undo().
-
- \sa QUndoCommand::actionText(), redoText()
-*/
-
-QString QUndoStack::undoText() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return QString();
- if (d->index > 0)
- return d->command_list.at(d->index - 1)->actionText();
- return QString();
-}
-
-/*!
- \since 5.12
- \property QUndoStack::redoText
- \brief the redo text of the next command that is redone.
-
- This property holds the text of the command which will be redone in the
- next call to redo().
-
- \sa redoText(), QUndoCommand::actionText(), undoText()
-*/
-
-/*!
- Returns the text of the command which will be redone in the next call to redo().
-
- \sa QUndoCommand::actionText(), undoText()
-*/
-
-QString QUndoStack::redoText() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return QString();
- if (d->index < d->command_list.size())
- return d->command_list.at(d->index)->actionText();
- return QString();
-}
-
-#ifndef QT_NO_ACTION
-
-/*!
- Creates an undo QAction object with the given \a parent.
-
- Triggering this action will cause a call to undo(). The text of this action
- is the text of the command which will be undone in the next call to undo(),
- prefixed by the specified \a prefix. If there is no command available for undo,
- this action will be disabled.
-
- If \a prefix is empty, the default template "Undo %1" is used instead of prefix.
- Before Qt 4.8, the prefix "Undo" was used by default.
-
- \sa createRedoAction(), canUndo(), QUndoCommand::text()
-*/
-
-QAction *QUndoStack::createUndoAction(QObject *parent, const QString &prefix) const
-{
- QUndoAction *result = new QUndoAction(prefix, parent);
- if (prefix.isEmpty())
- result->setTextFormat(tr("Undo %1"), tr("Undo", "Default text for undo action"));
-
- result->setEnabled(canUndo());
- result->setPrefixedText(undoText());
- connect(this, SIGNAL(canUndoChanged(bool)),
- result, SLOT(setEnabled(bool)));
- connect(this, SIGNAL(undoTextChanged(QString)),
- result, SLOT(setPrefixedText(QString)));
- connect(result, SIGNAL(triggered()), this, SLOT(undo()));
- return result;
-}
-
-/*!
- Creates an redo QAction object with the given \a parent.
-
- Triggering this action will cause a call to redo(). The text of this action
- is the text of the command which will be redone in the next call to redo(),
- prefixed by the specified \a prefix. If there is no command available for redo,
- this action will be disabled.
-
- If \a prefix is empty, the default template "Redo %1" is used instead of prefix.
- Before Qt 4.8, the prefix "Redo" was used by default.
-
- \sa createUndoAction(), canRedo(), QUndoCommand::text()
-*/
-
-QAction *QUndoStack::createRedoAction(QObject *parent, const QString &prefix) const
-{
- QUndoAction *result = new QUndoAction(prefix, parent);
- if (prefix.isEmpty())
- result->setTextFormat(tr("Redo %1"), tr("Redo", "Default text for redo action"));
-
- result->setEnabled(canRedo());
- result->setPrefixedText(redoText());
- connect(this, SIGNAL(canRedoChanged(bool)),
- result, SLOT(setEnabled(bool)));
- connect(this, SIGNAL(redoTextChanged(QString)),
- result, SLOT(setPrefixedText(QString)));
- connect(result, SIGNAL(triggered()), this, SLOT(redo()));
- return result;
-}
-
-#endif // QT_NO_ACTION
-
-/*!
- Begins composition of a macro command with the given \a text description.
-
- An empty command described by the specified \a text is pushed on the stack.
- Any subsequent commands pushed on the stack will be appended to the empty
- command's children until endMacro() is called.
-
- Calls to beginMacro() and endMacro() may be nested, but every call to
- beginMacro() must have a matching call to endMacro().
-
- While a macro is being composed, the stack is disabled. This means that:
- \list
- \li indexChanged() and cleanChanged() are not emitted,
- \li canUndo() and canRedo() return false,
- \li calling undo() or redo() has no effect,
- \li the undo/redo actions are disabled.
- \endlist
-
- The stack becomes enabled and appropriate signals are emitted when endMacro()
- is called for the outermost macro.
-
- \snippet code/src_gui_util_qundostack.cpp 4
-
- This code is equivalent to:
-
- \snippet code/src_gui_util_qundostack.cpp 5
-
- \sa endMacro()
-*/
-
-void QUndoStack::beginMacro(const QString &text)
-{
- Q_D(QUndoStack);
- QUndoCommand *cmd = new QUndoCommand();
- cmd->setText(text);
-
- if (d->macro_stack.isEmpty()) {
- while (d->index < d->command_list.size())
- delete d->command_list.takeLast();
- if (d->clean_index > d->index)
- d->clean_index = -1; // we've deleted the clean state
- d->command_list.append(cmd);
- } else {
- d->macro_stack.constLast()->d->child_list.append(cmd);
- }
- d->macro_stack.append(cmd);
-
- if (d->macro_stack.count() == 1) {
- emit canUndoChanged(false);
- emit undoTextChanged(QString());
- emit canRedoChanged(false);
- emit redoTextChanged(QString());
- }
-}
-
-/*!
- Ends composition of a macro command.
-
- If this is the outermost macro in a set nested macros, this function emits
- indexChanged() once for the entire macro command.
-
- \sa beginMacro()
-*/
-
-void QUndoStack::endMacro()
-{
- Q_D(QUndoStack);
- if (Q_UNLIKELY(d->macro_stack.isEmpty())) {
- qWarning("QUndoStack::endMacro(): no matching beginMacro()");
- return;
- }
-
- d->macro_stack.removeLast();
-
- if (d->macro_stack.isEmpty()) {
- d->checkUndoLimit();
- d->setIndex(d->index + 1, false);
- }
-}
-
-/*!
- \since 4.4
-
- Returns a const pointer to the command at \a index.
-
- This function returns a const pointer, because modifying a command,
- once it has been pushed onto the stack and executed, almost always
- causes corruption of the state of the document, if the command is
- later undone or redone.
-
- \sa QUndoCommand::child()
-*/
-const QUndoCommand *QUndoStack::command(int index) const
-{
- Q_D(const QUndoStack);
-
- if (index < 0 || index >= d->command_list.count())
- return nullptr;
- return d->command_list.at(index);
-}
-
-/*!
- Returns the text of the command at index \a idx.
-
- \sa beginMacro()
-*/
-
-QString QUndoStack::text(int idx) const
-{
- Q_D(const QUndoStack);
-
- if (idx < 0 || idx >= d->command_list.size())
- return QString();
- return d->command_list.at(idx)->text();
-}
-
-/*!
- \property QUndoStack::undoLimit
- \brief the maximum number of commands on this stack.
- \since 4.3
-
- When the number of commands on a stack exceedes the stack's undoLimit, commands are
- deleted from the bottom of the stack. Macro commands (commands with child commands)
- are treated as one command. The default value is 0, which means that there is no
- limit.
-
- This property may only be set when the undo stack is empty, since setting it on a
- non-empty stack might delete the command at the current index. Calling setUndoLimit()
- on a non-empty stack prints a warning and does nothing.
-*/
-
-void QUndoStack::setUndoLimit(int limit)
-{
- Q_D(QUndoStack);
-
- if (Q_UNLIKELY(!d->command_list.isEmpty())) {
- qWarning("QUndoStack::setUndoLimit(): an undo limit can only be set when the stack is empty");
- return;
- }
-
- if (limit == d->undo_limit)
- return;
- d->undo_limit = limit;
- d->checkUndoLimit();
-}
-
-int QUndoStack::undoLimit() const
-{
- Q_D(const QUndoStack);
-
- return d->undo_limit;
-}
-
-/*!
- \property QUndoStack::active
- \brief the active status of this stack.
-
- An application often has multiple undo stacks, one for each opened document. The active
- stack is the one associated with the currently active document. If the stack belongs
- to a QUndoGroup, calls to QUndoGroup::undo() or QUndoGroup::redo() will be forwarded
- to this stack when it is active. If the QUndoGroup is watched by a QUndoView, the view
- will display the contents of this stack when it is active. If the stack does not belong to
- a QUndoGroup, making it active has no effect.
-
- It is the programmer's responsibility to specify which stack is active by
- calling setActive(), usually when the associated document window receives focus.
-
- \sa QUndoGroup
-*/
-
-void QUndoStack::setActive(bool active)
-{
-#if !QT_CONFIG(undogroup)
- Q_UNUSED(active);
-#else
- Q_D(QUndoStack);
-
- if (d->group != nullptr) {
- if (active)
- d->group->setActiveStack(this);
- else if (d->group->activeStack() == this)
- d->group->setActiveStack(nullptr);
- }
-#endif
-}
-
-bool QUndoStack::isActive() const
-{
-#if !QT_CONFIG(undogroup)
- return true;
-#else
- Q_D(const QUndoStack);
- return d->group == nullptr || d->group->activeStack() == this;
-#endif
-}
-
-/*!
- \fn void QUndoStack::indexChanged(int idx)
-
- This signal is emitted whenever a command modifies the state of the document.
- This happens when a command is undone or redone. When a macro
- command is undone or redone, or setIndex() is called, this signal
- is emitted only once.
-
- \a idx specifies the index of the current command, ie. the command which will be
- executed on the next call to redo().
-
- \sa index(), setIndex()
-*/
-
-/*!
- \fn void QUndoStack::cleanChanged(bool clean)
-
- This signal is emitted whenever the stack enters or leaves the clean state.
- If \a clean is true, the stack is in a clean state; otherwise this signal
- indicates that it has left the clean state.
-
- \sa isClean(), setClean()
-*/
-
-/*!
- \fn void QUndoStack::undoTextChanged(const QString &undoText)
-
- This signal is emitted whenever the value of undoText() changes. It is
- used to update the text property of the undo action returned by createUndoAction().
- \a undoText specifies the new text.
-*/
-
-/*!
- \fn void QUndoStack::canUndoChanged(bool canUndo)
-
- This signal is emitted whenever the value of canUndo() changes. It is
- used to enable or disable the undo action returned by createUndoAction().
- \a canUndo specifies the new value.
-*/
-
-/*!
- \fn void QUndoStack::redoTextChanged(const QString &redoText)
-
- This signal is emitted whenever the value of redoText() changes. It is
- used to update the text property of the redo action returned by createRedoAction().
- \a redoText specifies the new text.
-*/
-
-/*!
- \fn void QUndoStack::canRedoChanged(bool canRedo)
-
- This signal is emitted whenever the value of canRedo() changes. It is
- used to enable or disable the redo action returned by createRedoAction().
- \a canRedo specifies the new value.
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qundostack.cpp"
-#include "moc_qundostack_p.cpp"
-
-#endif // QT_CONFIG(undostack)
diff --git a/src/widgets/util/qundostack.h b/src/widgets/util/qundostack.h
index b5716b2e9b..c291303803 100644
--- a/src/widgets/util/qundostack.h
+++ b/src/widgets/util/qundostack.h
@@ -1,159 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QUNDOSTACK_H
-#define QUNDOSTACK_H
+#if 0
+// syncqt: header is already part of QtGui/QtGui
+#pragma qt_no_master_include
+#endif
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtCore/qobject.h>
-#include <QtCore/qstring.h>
-
-QT_REQUIRE_CONFIG(undocommand);
+#include <QtGui/QUndoStack>
QT_BEGIN_NAMESPACE
-
-class QAction;
-class QUndoCommandPrivate;
-class QUndoStackPrivate;
-
-class Q_WIDGETS_EXPORT QUndoCommand
-{
- QUndoCommandPrivate *d;
-
-public:
- explicit QUndoCommand(QUndoCommand *parent = nullptr);
- explicit QUndoCommand(const QString &text, QUndoCommand *parent = nullptr);
- virtual ~QUndoCommand();
-
- virtual void undo();
- virtual void redo();
-
- QString text() const;
- QString actionText() const;
- void setText(const QString &text);
-
- bool isObsolete() const;
- void setObsolete(bool obsolete);
-
- virtual int id() const;
- virtual bool mergeWith(const QUndoCommand *other);
-
- int childCount() const;
- const QUndoCommand *child(int index) const;
-
-private:
- Q_DISABLE_COPY(QUndoCommand)
- friend class QUndoStack;
-};
-
-#if QT_CONFIG(undostack)
-
-class Q_WIDGETS_EXPORT QUndoStack : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QUndoStack)
- Q_PROPERTY(bool active READ isActive WRITE setActive)
- Q_PROPERTY(int undoLimit READ undoLimit WRITE setUndoLimit)
- Q_PROPERTY(bool canUndo READ canUndo NOTIFY canUndoChanged)
- Q_PROPERTY(bool canRedo READ canRedo NOTIFY canRedoChanged)
- Q_PROPERTY(QString undoText READ undoText NOTIFY undoTextChanged)
- Q_PROPERTY(QString redoText READ redoText NOTIFY redoTextChanged)
- Q_PROPERTY(bool clean READ isClean NOTIFY cleanChanged)
-
-public:
- explicit QUndoStack(QObject *parent = nullptr);
- ~QUndoStack();
- void clear();
-
- void push(QUndoCommand *cmd);
-
- bool canUndo() const;
- bool canRedo() const;
- QString undoText() const;
- QString redoText() const;
-
- int count() const;
- int index() const;
- QString text(int idx) const;
-
-#ifndef QT_NO_ACTION
- QAction *createUndoAction(QObject *parent,
- const QString &prefix = QString()) const;
- QAction *createRedoAction(QObject *parent,
- const QString &prefix = QString()) const;
-#endif // QT_NO_ACTION
-
- bool isActive() const;
- bool isClean() const;
- int cleanIndex() const;
-
- void beginMacro(const QString &text);
- void endMacro();
-
- void setUndoLimit(int limit);
- int undoLimit() const;
-
- const QUndoCommand *command(int index) const;
-
-public Q_SLOTS:
- void setClean();
- void resetClean();
- void setIndex(int idx);
- void undo();
- void redo();
- void setActive(bool active = true);
-
-Q_SIGNALS:
- void indexChanged(int idx);
- void cleanChanged(bool clean);
- void canUndoChanged(bool canUndo);
- void canRedoChanged(bool canRedo);
- void undoTextChanged(const QString &undoText);
- void redoTextChanged(const QString &redoText);
-
-private:
- Q_DISABLE_COPY(QUndoStack)
- friend class QUndoGroup;
-};
-
-#endif // QT_CONFIG(undostack)
-
QT_END_NAMESPACE
-
-#endif // QUNDOSTACK_H
diff --git a/src/widgets/util/qundostack_p.h b/src/widgets/util/qundostack_p.h
deleted file mode 100644
index c44cdd6603..0000000000
--- a/src/widgets/util/qundostack_p.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QUNDOSTACK_P_H
-#define QUNDOSTACK_P_H
-
-#include <QtWidgets/private/qtwidgetsglobal_p.h>
-#include <private/qobject_p.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qstring.h>
-#if QT_CONFIG(action)
-# include <QtWidgets/qaction.h>
-#endif
-
-#include "qundostack.h"
-
-QT_BEGIN_NAMESPACE
-class QUndoCommand;
-class QUndoGroup;
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of qapplication_*.cpp, qwidget*.cpp and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-class QUndoCommandPrivate
-{
-public:
- QUndoCommandPrivate() : id(-1), obsolete(false) {}
- QList<QUndoCommand*> child_list;
- QString text;
- QString actionText;
- int id;
- bool obsolete;
-};
-
-#if QT_CONFIG(undostack)
-
-class QUndoStackPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QUndoStack)
-public:
- QUndoStackPrivate() : index(0), clean_index(0), group(nullptr), undo_limit(0) {}
-
- QList<QUndoCommand*> command_list;
- QList<QUndoCommand*> macro_stack;
- int index;
- int clean_index;
- QUndoGroup *group;
- int undo_limit;
-
- void setIndex(int idx, bool clean);
- bool checkUndoLimit();
-};
-
-#ifndef QT_NO_ACTION
-class QUndoAction : public QAction
-{
- Q_OBJECT
-public:
- explicit QUndoAction(const QString &prefix, QObject *parent = nullptr);
- void setTextFormat(const QString &textFormat, const QString &defaultText);
-public Q_SLOTS:
- void setPrefixedText(const QString &text);
-private:
- QString m_prefix;
- QString m_defaultText;
-};
-#endif // QT_NO_ACTION
-
-QT_END_NAMESPACE
-#endif // QT_CONFIG(undostack)
-#endif // QUNDOSTACK_P_H
diff --git a/src/widgets/util/qundoview.cpp b/src/widgets/util/qundoview.cpp
index 9ca83a1da2..9c78c6d075 100644
--- a/src/widgets/util/qundoview.cpp
+++ b/src/widgets/util/qundoview.cpp
@@ -1,48 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qundostack.h"
+// 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 "qundoview.h"
#if QT_CONFIG(undogroup)
-#include "qundogroup.h"
+#include <QtGui/qundogroup.h>
#endif
+#include <QtGui/qundostack.h>
#include <QtCore/qabstractitemmodel.h>
#include <QtCore/qpointer.h>
#include <QtGui/qicon.h>
@@ -358,8 +322,8 @@ QUndoStack *QUndoView::stack() const
}
/*!
- Sets the stack displayed by this view to \a stack. If \a stack is 0, the view
- will be empty.
+ Sets the stack displayed by this view to \a stack. If \a stack is \nullptr,
+ the view will be empty.
If the view was previously looking at a QUndoGroup, the group is set to \nullptr.
@@ -378,10 +342,10 @@ void QUndoView::setStack(QUndoStack *stack)
#if QT_CONFIG(undogroup)
/*!
- Sets the group displayed by this view to \a group. If \a group is 0, the view will
- be empty.
+ Sets the group displayed by this view to \a group. If \a group is \nullptr,
+ the view will be empty.
- The view will update itself autmiatically whenever the active stack of the group changes.
+ The view will update itself automatically whenever the active stack of the group changes.
\sa group(), setStack()
*/
diff --git a/src/widgets/util/qundoview.h b/src/widgets/util/qundoview.h
index 403f05d2e4..2d011b961c 100644
--- a/src/widgets/util/qundoview.h
+++ b/src/widgets/util/qundoview.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QUNDOVIEW_H
#define QUNDOVIEW_H
diff --git a/src/widgets/util/util.pri b/src/widgets/util/util.pri
deleted file mode 100644
index 363291528e..0000000000
--- a/src/widgets/util/util.pri
+++ /dev/null
@@ -1,56 +0,0 @@
-# Qt util module
-
-HEADERS += \
- util/qsystemtrayicon.h \
- util/qcolormap.h \
- util/qsystemtrayicon_p.h
-
-SOURCES += \
- util/qsystemtrayicon.cpp \
- util/qcolormap.cpp
-
-qtConfig(completer) {
- HEADERS += \
- util/qcompleter.h \
- util/qcompleter_p.h
-
- SOURCES += util/qcompleter.cpp
-}
-
-qtConfig(scroller) {
- HEADERS += \
- util/qscroller.h \
- util/qscroller_p.h \
- util/qscrollerproperties.h \
- util/qscrollerproperties_p.h \
- util/qflickgesture_p.h
-
- SOURCES += \
- util/qscroller.cpp \
- util/qscrollerproperties.cpp \
- util/qflickgesture.cpp \
-}
-
-qtConfig(undocommand) {
- HEADERS += \
- util/qundostack.h \
- util/qundostack_p.h
-
- SOURCES += util/qundostack.cpp
-}
-
-qtConfig(undogroup) {
- HEADERS += util/qundogroup.h
- SOURCES += util/qundogroup.cpp
-}
-
-qtConfig(undoview) {
- HEADERS += util/qundoview.h
- SOURCES += util/qundoview.cpp
-}
-
-qtConfig(xcb) {
- SOURCES += util/qsystemtrayicon_x11.cpp
-} else {
- SOURCES += util/qsystemtrayicon_qpa.cpp
-}
diff --git a/src/widgets/widgets.pro b/src/widgets/widgets.pro
deleted file mode 100644
index 2d5ba05d40..0000000000
--- a/src/widgets/widgets.pro
+++ /dev/null
@@ -1,49 +0,0 @@
-TARGET = QtWidgets
-QT = core-private gui-private
-MODULE_CONFIG = uic
-
-CONFIG += $$MODULE_CONFIG
-DEFINES += QT_NO_USING_NAMESPACE
-msvc:equals(QT_ARCH, i386): QMAKE_LFLAGS += /BASE:0x65000000
-
-TRACEPOINT_PROVIDER = $$PWD/qtwidgets.tracepoints
-CONFIG += qt_tracepoints
-
-QMAKE_DOCS = $$PWD/doc/qtwidgets.qdocconf
-
-#platforms
-mac:include(kernel/mac.pri)
-win32:include(kernel/win.pri)
-
-#modules
-include(kernel/kernel.pri)
-include(styles/styles.pri)
-include(widgets/widgets.pri)
-include(dialogs/dialogs.pri)
-include(accessible/accessible.pri)
-include(itemviews/itemviews.pri)
-include(graphicsview/graphicsview.pri)
-include(util/util.pri)
-include(statemachine/statemachine.pri)
-
-qtConfig(graphicseffect) {
- include(effects/effects.pri)
-}
-
-QMAKE_LIBS += $$QMAKE_LIBS_GUI
-
-QMAKE_DYNAMIC_LIST_FILE = $$PWD/QtWidgets.dynlist
-
-# Code coverage with TestCocoon
-# The following is required as extra compilers use $$QMAKE_CXX instead of $(CXX).
-# Without this, testcocoon.prf is read only after $$QMAKE_CXX is used by the
-# extra compilers.
-testcocoon {
- load(testcocoon)
-}
-
-MODULE_PLUGIN_TYPES += \
- styles
-load(qt_module)
-
-CONFIG += metatypes install_metatypes
diff --git a/src/widgets/widgets/qabstractbutton.cpp b/src/widgets/widgets/qabstractbutton.cpp
index 29d28847f3..3a5fbe1b90 100644
--- a/src/widgets/widgets/qabstractbutton.cpp
+++ b/src/widgets/widgets/qabstractbutton.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 "private/qabstractbutton_p.h"
@@ -44,17 +8,20 @@
#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"
#include "qapplication.h"
#include "qstyle.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
+#include <qpa/qplatformtheme.h>
+
+#include <QtCore/qpointer.h>
#include <algorithm>
@@ -190,7 +157,9 @@ QList<QAbstractButton *>QAbstractButtonPrivate::queryButtonList() const
return group->d_func()->buttonList;
#endif
- QList<QAbstractButton*>candidates = parent->findChildren<QAbstractButton *>();
+ if (!parent)
+ return {};
+ QList<QAbstractButton *> candidates = parent->findChildren<QAbstractButton *>();
if (autoExclusive) {
auto isNoMemberOfMyAutoExclusiveGroup = [](QAbstractButton *candidate) {
return !candidate->autoExclusive()
@@ -199,9 +168,7 @@ QList<QAbstractButton *>QAbstractButtonPrivate::queryButtonList() const
#endif
;
};
- candidates.erase(std::remove_if(candidates.begin(), candidates.end(),
- isNoMemberOfMyAutoExclusiveGroup),
- candidates.end());
+ candidates.removeIf(isNoMemberOfMyAutoExclusiveGroup);
}
return candidates;
}
@@ -215,10 +182,10 @@ QAbstractButton *QAbstractButtonPrivate::queryCheckedButton() const
Q_Q(const QAbstractButton);
QList<QAbstractButton *> buttonList = queryButtonList();
- if (!autoExclusive || buttonList.count() == 1) // no group
+ if (!autoExclusive || buttonList.size() == 1) // no group
return nullptr;
- for (int i = 0; i < buttonList.count(); ++i) {
+ for (int i = 0; i < buttonList.size(); ++i) {
QAbstractButton *b = buttonList.at(i);
if (b->d_func()->checked && b != q)
return b;
@@ -245,7 +212,7 @@ void QAbstractButtonPrivate::notifyChecked()
void QAbstractButtonPrivate::moveFocus(int key)
{
- QList<QAbstractButton *> buttonList = queryButtonList();;
+ QList<QAbstractButton *> buttonList = queryButtonList();
#if QT_CONFIG(buttongroup)
bool exclusive = group ? group->d_func()->exclusive : autoExclusive;
#else
@@ -262,10 +229,10 @@ void QAbstractButtonPrivate::moveFocus(int key)
QPoint goal = target.center();
uint focus_flag = qt_tab_all_widgets() ? Qt::TabFocus : Qt::StrongFocus;
- for (int i = 0; i < buttonList.count(); ++i) {
+ for (int i = 0; i < buttonList.size(); ++i) {
QAbstractButton *button = buttonList.at(i);
if (button != f && button->window() == f->window() && button->isEnabled() && !button->isHidden() &&
- (autoExclusive || (button->focusPolicy() & focus_flag) == focus_flag)) {
+ (exclusive || (button->focusPolicy() & focus_flag) == focus_flag)) {
QRect buttonRect = button->rect().translated(button->mapToGlobal(QPoint(0,0)));
QPoint p = buttonRect.center();
@@ -345,7 +312,7 @@ void QAbstractButtonPrivate::fixFocusPolicy()
return;
QList<QAbstractButton *> buttonList = queryButtonList();
- for (int i = 0; i < buttonList.count(); ++i) {
+ for (int i = 0; i < buttonList.size(); ++i) {
QAbstractButton *b = buttonList.at(i);
if (!b->isCheckable())
continue;
@@ -414,7 +381,7 @@ void QAbstractButtonPrivate::emitClicked()
emit q->clicked(checked);
#if QT_CONFIG(buttongroup)
if (guard && group) {
- emit group->buttonClicked(group->id(q));
+ emit group->idClicked(group->id(q));
if (guard && group)
emit group->buttonClicked(q);
}
@@ -428,7 +395,7 @@ void QAbstractButtonPrivate::emitPressed()
emit q->pressed();
#if QT_CONFIG(buttongroup)
if (guard && group) {
- emit group->buttonPressed(group->id(q));
+ emit group->idPressed(group->id(q));
if (guard && group)
emit group->buttonPressed(q);
}
@@ -442,7 +409,7 @@ void QAbstractButtonPrivate::emitReleased()
emit q->released();
#if QT_CONFIG(buttongroup)
if (guard && group) {
- emit group->buttonReleased(group->id(q));
+ emit group->idReleased(group->id(q));
if (guard && group)
emit group->buttonReleased(q);
}
@@ -456,7 +423,7 @@ void QAbstractButtonPrivate::emitToggled(bool checked)
emit q->toggled(checked);
#if QT_CONFIG(buttongroup)
if (guard && group) {
- emit group->buttonToggled(group->id(q), checked);
+ emit group->idToggled(group->id(q), checked);
if (guard && group)
emit group->buttonToggled(q, checked);
}
@@ -525,7 +492,7 @@ void QAbstractButton::setText(const QString &text)
d->sizeHint = QSize();
update();
updateGeometry();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleEvent event(this, QAccessible::NameChanged);
QAccessible::updateAccessibility(&event);
#endif
@@ -648,12 +615,13 @@ void QAbstractButton::setChecked(bool checked)
if (guard)
d->emitToggled(checked);
-
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::State s;
- s.checked = true;
- QAccessibleStateChangeEvent event(this, s);
- QAccessible::updateAccessibility(&event);
+#if QT_CONFIG(accessibility)
+ if (guard) {
+ QAccessible::State s;
+ s.checked = true;
+ QAccessibleStateChangeEvent event(this, s);
+ QAccessible::updateAccessibility(&event);
+ }
#endif
}
@@ -818,7 +786,7 @@ QButtonGroup *QAbstractButton::group() const
/*!
Performs an animated click: the button is pressed immediately, and
-released \a msec milliseconds later (the default is 100 ms).
+released 100ms later.
Calling this function again before the button is released resets
the release timer.
@@ -829,7 +797,7 @@ This function does nothing if the button is \l{setEnabled()}{disabled.}
\sa click()
*/
-void QAbstractButton::animateClick(int msec)
+void QAbstractButton::animateClick()
{
if (!isEnabled())
return;
@@ -840,7 +808,7 @@ void QAbstractButton::animateClick(int msec)
repaint();
if (!d->animateTimer.isActive())
d->emitPressed();
- d->animateTimer.start(msec, this);
+ d->animateTimer.start(100, this);
}
/*!
@@ -939,9 +907,6 @@ bool QAbstractButton::event(QEvent *e)
case QEvent::HoverEnter:
case QEvent::HoverLeave:
case QEvent::ContextMenu:
-#if QT_CONFIG(wheelevent)
- case QEvent::Wheel:
-#endif
return true;
default:
break;
@@ -976,7 +941,7 @@ void QAbstractButton::mousePressEvent(QMouseEvent *e)
e->ignore();
return;
}
- if (hitButton(e->pos())) {
+ if (hitButton(e->position().toPoint())) {
setDown(true);
d->pressed = true;
repaint();
@@ -1006,7 +971,7 @@ void QAbstractButton::mouseReleaseEvent(QMouseEvent *e)
return;
}
- if (hitButton(e->pos())) {
+ if (hitButton(e->position().toPoint())) {
d->repeatTimer.stop();
d->click();
e->accept();
@@ -1025,7 +990,7 @@ void QAbstractButton::mouseMoveEvent(QMouseEvent *e)
return;
}
- if (hitButton(e->pos()) != d->down) {
+ if (hitButton(e->position().toPoint()) != d->down) {
setDown(!d->down);
repaint();
if (d->down)
@@ -1033,7 +998,7 @@ void QAbstractButton::mouseMoveEvent(QMouseEvent *e)
else
d->emitReleased();
e->accept();
- } else if (!hitButton(e->pos())) {
+ } else if (!hitButton(e->position().toPoint())) {
e->ignore();
}
}
@@ -1043,19 +1008,19 @@ void QAbstractButton::keyPressEvent(QKeyEvent *e)
{
Q_D(QAbstractButton);
bool next = true;
- switch (e->key()) {
- case Qt::Key_Enter:
- case Qt::Key_Return:
- e->ignore();
- break;
- case Qt::Key_Select:
- case Qt::Key_Space:
- if (!e->isAutoRepeat()) {
- setDown(true);
- repaint();
- d->emitPressed();
- }
- break;
+
+ const auto key = e->key();
+ const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()
+ ->themeHint(QPlatformTheme::ButtonPressKeys)
+ .value<QList<Qt::Key>>();
+ if (buttonPressKeys.contains(key) && !e->isAutoRepeat()) {
+ setDown(true);
+ repaint();
+ d->emitPressed();
+ return;
+ }
+
+ switch (key) {
case Qt::Key_Up:
next = false;
Q_FALLTHROUGH();
@@ -1085,7 +1050,7 @@ void QAbstractButton::keyPressEvent(QKeyEvent *e)
// cleaned up when fixing task 194373. It's here to ensure that we
// keep compatibility outside QAbstractItemView.
d->moveFocus(e->key());
- if (hasFocus()) // nothing happend, propagate
+ if (hasFocus()) // nothing happened, propagate
e->ignore();
} else {
// Prefer parent widget, use this if parent is absent
@@ -1120,15 +1085,15 @@ void QAbstractButton::keyReleaseEvent(QKeyEvent *e)
if (!e->isAutoRepeat())
d->repeatTimer.stop();
- switch (e->key()) {
- case Qt::Key_Select:
- case Qt::Key_Space:
- if (!e->isAutoRepeat() && d->down)
- d->click();
- break;
- default:
- e->ignore();
+ const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()
+ ->themeHint(QPlatformTheme::ButtonPressKeys)
+ .value<QList<Qt::Key>>();
+ if (buttonPressKeys.contains(e->key()) && !e->isAutoRepeat() && d->down) {
+ d->click();
+ return;
}
+
+ e->ignore();
}
/*!\reimp
diff --git a/src/widgets/widgets/qabstractbutton.h b/src/widgets/widgets/qabstractbutton.h
index d44da2f4f3..7a1e55abdd 100644
--- a/src/widgets/widgets/qabstractbutton.h
+++ b/src/widgets/widgets/qabstractbutton.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTBUTTON_H
#define QABSTRACTBUTTON_H
@@ -116,7 +80,7 @@ public:
public Q_SLOTS:
void setIconSize(const QSize &size);
- void animateClick(int msec = 100);
+ void animateClick();
void click();
void toggle();
void setChecked(bool);
diff --git a/src/widgets/widgets/qabstractbutton_p.h b/src/widgets/widgets/qabstractbutton_p.h
index 39e2e399a7..6b6d5a2167 100644
--- a/src/widgets/widgets/qabstractbutton_p.h
+++ b/src/widgets/widgets/qabstractbutton_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTBUTTON_P_H
#define QABSTRACTBUTTON_P_H
diff --git a/src/widgets/widgets/qabstractscrollarea.cpp b/src/widgets/widgets/qabstractscrollarea.cpp
index 320b3bf7ef..f6f8e8b795 100644
--- a/src/widgets/widgets/qabstractscrollarea.cpp
+++ b/src/widgets/widgets/qabstractscrollarea.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qabstractscrollarea.h"
@@ -68,6 +32,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
\class QAbstractScrollArea
\brief The QAbstractScrollArea widget provides a scrolling area with
@@ -127,13 +93,13 @@ QT_BEGIN_NAMESPACE
QWidget::move(). When the area contents or the viewport size
changes, we do the following:
- \snippet myscrollarea.cpp 1
+ \snippet myscrollarea/myscrollarea.cpp 1
When the scroll bars change value, we need to update the widget
position, i.e., find the part of the widget that is to be drawn in
the viewport:
- \snippet myscrollarea.cpp 0
+ \snippet myscrollarea/myscrollarea.cpp 0
In order to track scroll bar movements, reimplement the virtual
function scrollContentsBy(). In order to fine-tune scrolling
@@ -202,7 +168,7 @@ void QAbstractScrollAreaScrollBarContainer::addWidget(QWidget *widget, LogicalPo
}
/*! \internal
- Retuns a list of scroll bar widgets for the given position. The scroll bar
+ Returns a list of scroll-bar widgets for the given position. The scroll bar
itself is not returned.
*/
QWidgetList QAbstractScrollAreaScrollBarContainer::widgets(LogicalPosition position)
@@ -282,11 +248,11 @@ void QAbstractScrollAreaPrivate::init()
{
Q_Q(QAbstractScrollArea);
viewport = new QWidget(q);
- viewport->setObjectName(QLatin1String("qt_scrollarea_viewport"));
+ viewport->setObjectName("qt_scrollarea_viewport"_L1);
viewport->setBackgroundRole(QPalette::Base);
viewport->setAutoFillBackground(true);
scrollBarContainers[Qt::Horizontal] = new QAbstractScrollAreaScrollBarContainer(Qt::Horizontal, q);
- scrollBarContainers[Qt::Horizontal]->setObjectName(QLatin1String("qt_scrollarea_hcontainer"));
+ scrollBarContainers[Qt::Horizontal]->setObjectName("qt_scrollarea_hcontainer"_L1);
hbar = scrollBarContainers[Qt::Horizontal]->scrollBar;
hbar->setRange(0,0);
scrollBarContainers[Qt::Horizontal]->setVisible(false);
@@ -294,7 +260,7 @@ void QAbstractScrollAreaPrivate::init()
QObject::connect(hbar, SIGNAL(valueChanged(int)), q, SLOT(_q_hslide(int)));
QObject::connect(hbar, SIGNAL(rangeChanged(int,int)), q, SLOT(_q_showOrHideScrollBars()), Qt::QueuedConnection);
scrollBarContainers[Qt::Vertical] = new QAbstractScrollAreaScrollBarContainer(Qt::Vertical, q);
- scrollBarContainers[Qt::Vertical]->setObjectName(QLatin1String("qt_scrollarea_vcontainer"));
+ scrollBarContainers[Qt::Vertical]->setObjectName("qt_scrollarea_vcontainer"_L1);
vbar = scrollBarContainers[Qt::Vertical]->scrollBar;
vbar->setRange(0,0);
scrollBarContainers[Qt::Vertical]->setVisible(false);
@@ -308,7 +274,7 @@ void QAbstractScrollAreaPrivate::init()
q->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
q->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
layoutChildren();
-#ifndef Q_OS_OSX
+#ifndef Q_OS_MACOS
# ifndef QT_NO_GESTURES
viewport->grabGesture(Qt::PanGesture);
# endif
@@ -329,21 +295,24 @@ 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.init(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);
+ opt.initFrom(q);
const int hsbExt = hbar->sizeHint().height();
const int vsbExt = vbar->sizeHint().width();
@@ -402,7 +371,7 @@ void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrol
#if QT_CONFIG(itemviews)
if ((vscrollOverlap > 0 && needv) || (hscrollOverlap > 0 && needh)) {
const QList<QHeaderView *> headers = q->findChildren<QHeaderView*>();
- if (headers.count() <= 2) {
+ if (headers.size() <= 2) {
for (const QHeaderView *header : headers) {
const QRect geo = header->geometry();
if (header->orientation() == Qt::Vertical && header->isVisible() && QStyle::visualRect(opt.direction, opt.rect, geo).left() <= opt.rect.width() / 2)
@@ -442,8 +411,10 @@ void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrol
viewportRect.adjust(right, top, -left, -bottom);
else
viewportRect.adjust(left, top, -right, -bottom);
+ viewportRect = QStyle::visualRect(opt.direction, opt.rect, viewportRect);
+ viewportRect.translate(-overshoot);
+ viewport->setGeometry(viewportRect); // resize the viewport last
- viewport->setGeometry(QStyle::visualRect(opt.direction, opt.rect, viewportRect)); // resize the viewport last
*needHorizontalScrollbar = needh;
*needVerticalScrollbar = needv;
}
@@ -512,8 +483,8 @@ QAbstractScrollArea::~QAbstractScrollArea()
Sets the viewport to be the given \a widget.
The QAbstractScrollArea will take ownership of the given \a widget.
- If \a widget is 0, QAbstractScrollArea will assign a new QWidget instance
- for the viewport.
+ If \a widget is \nullptr, QAbstractScrollArea will assign a new QWidget
+ instance for the viewport.
\sa viewport()
*/
@@ -564,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;
}
@@ -720,7 +689,7 @@ QWidget *QAbstractScrollArea::cornerWidget() const
You will probably also want to set at least one of the scroll bar
modes to \c AlwaysOn.
- Passing 0 shows no widget in the corner.
+ Passing \nullptr shows no widget in the corner.
Any previous corner widget is hidden.
@@ -836,7 +805,7 @@ QWidgetList QAbstractScrollArea::scrollBarWidgets(Qt::Alignment alignment)
/*!
Sets the margins around the scrolling area to \a left, \a top, \a
right and \a bottom. This is useful for applications such as
- spreadsheets with "locked" rows and columns. The marginal space is
+ spreadsheets with "locked" rows and columns. The marginal space
is left blank; put widgets in the unused area.
Note that this function is frequently called by QTreeView and
@@ -1131,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()
*/
@@ -1361,38 +1330,27 @@ void QAbstractScrollArea::scrollContentsBy(int, int)
viewport()->update();
}
-bool QAbstractScrollAreaPrivate::canStartScrollingAt( const QPoint &startPos )
+bool QAbstractScrollAreaPrivate::canStartScrollingAt(const QPoint &startPos) const
{
- Q_Q(QAbstractScrollArea);
-
-#if QT_CONFIG(graphicsview)
- // don't start scrolling when a drag mode has been set.
- // don't start scrolling on a movable item.
- if (QGraphicsView *view = qobject_cast<QGraphicsView *>(q)) {
- if (view->dragMode() != QGraphicsView::NoDrag)
- return false;
-
- QGraphicsItem *childItem = view->itemAt(startPos);
-
- if (childItem && (childItem->flags() & QGraphicsItem::ItemIsMovable))
- return false;
- }
-#endif
+ Q_Q(const QAbstractScrollArea);
// don't start scrolling on a QAbstractSlider
- if (qobject_cast<QAbstractSlider *>(q->viewport()->childAt(startPos))) {
+ if (qobject_cast<QAbstractSlider *>(q->viewport()->childAt(startPos)))
return false;
- }
return true;
}
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();
}
@@ -1473,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();
@@ -1505,7 +1463,7 @@ QSize QAbstractScrollArea::viewportSizeHint() const
/*!
\since 5.2
\property QAbstractScrollArea::sizeAdjustPolicy
- This property holds the policy describing how the size of the scroll area changes when the
+ \brief the policy describing how the size of the scroll area changes when the
size of the viewport changes.
The default policy is QAbstractScrollArea::AdjustIgnored.
diff --git a/src/widgets/widgets/qabstractscrollarea.h b/src/widgets/widgets/qabstractscrollarea.h
index 6d0d8fa6e6..33f4b76444 100644
--- a/src/widgets/widgets/qabstractscrollarea.h
+++ b/src/widgets/widgets/qabstractscrollarea.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTSCROLLAREA_H
#define QABSTRACTSCROLLAREA_H
@@ -56,8 +20,10 @@ class Q_WIDGETS_EXPORT QAbstractScrollArea : public QFrame
{
Q_OBJECT
- Q_PROPERTY(Qt::ScrollBarPolicy verticalScrollBarPolicy READ verticalScrollBarPolicy WRITE setVerticalScrollBarPolicy)
- Q_PROPERTY(Qt::ScrollBarPolicy horizontalScrollBarPolicy READ horizontalScrollBarPolicy WRITE setHorizontalScrollBarPolicy)
+ Q_PROPERTY(Qt::ScrollBarPolicy verticalScrollBarPolicy READ verticalScrollBarPolicy
+ WRITE setVerticalScrollBarPolicy)
+ Q_PROPERTY(Qt::ScrollBarPolicy horizontalScrollBarPolicy READ horizontalScrollBarPolicy
+ WRITE setHorizontalScrollBarPolicy)
Q_PROPERTY(SizeAdjustPolicy sizeAdjustPolicy READ sizeAdjustPolicy WRITE setSizeAdjustPolicy)
public:
diff --git a/src/widgets/widgets/qabstractscrollarea_p.h b/src/widgets/widgets/qabstractscrollarea_p.h
index 6d78b9db6d..7224d489ce 100644
--- a/src/widgets/widgets/qabstractscrollarea_p.h
+++ b/src/widgets/widgets/qabstractscrollarea_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTSCROLLAREA_P_H
#define QABSTRACTSCROLLAREA_P_H
@@ -54,6 +18,7 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "private/qframe_p.h"
#include "qabstractscrollarea.h"
+#include <QtGui/private/qgridlayoutengine_p.h>
QT_BEGIN_NAMESPACE
@@ -62,8 +27,7 @@ QT_BEGIN_NAMESPACE
class QScrollBar;
class QAbstractScrollAreaScrollBarContainer;
-// ### Qt 6: is the export still needed? If not, unexport QFramePrivate, too.
-class Q_WIDGETS_EXPORT QAbstractScrollAreaPrivate: public QFramePrivate
+class Q_AUTOTEST_EXPORT QAbstractScrollAreaPrivate: public QFramePrivate
{
Q_DECLARE_PUBLIC(QAbstractScrollArea)
@@ -73,7 +37,7 @@ public:
void replaceScrollBar(QScrollBar *scrollBar, Qt::Orientation orientation);
- QAbstractScrollAreaScrollBarContainer *scrollBarContainers[Qt::Vertical + 1];
+ QHVContainer<QAbstractScrollAreaScrollBarContainer *> scrollBarContainers;
QScrollBar *hbar, *vbar;
Qt::ScrollBarPolicy vbarpolicy, hbarpolicy;
@@ -94,9 +58,8 @@ public:
void init();
void layoutChildren();
void layoutChildren_helper(bool *needHorizontalScrollbar, bool *needVerticalScrollbar);
- // ### Fix for 4.4, talk to Bjoern E or Girish.
virtual void scrollBarPolicyChanged(Qt::Orientation, Qt::ScrollBarPolicy) {}
- bool canStartScrollingAt( const QPoint &startPos );
+ virtual bool canStartScrollingAt( const QPoint &startPos ) const;
void flashScrollBars();
void setScrollBarTransient(QScrollBar *scrollBar, bool transient);
@@ -117,7 +80,7 @@ class QAbstractScrollAreaFilter : public QObject
Q_OBJECT
public:
QAbstractScrollAreaFilter(QAbstractScrollAreaPrivate *p) : d(p)
- { setObjectName(QLatin1String("qt_abstractscrollarea_filter")); }
+ { setObjectName(QLatin1StringView("qt_abstractscrollarea_filter")); }
bool eventFilter(QObject *o, QEvent *e) override
{ return (o == d->viewport ? d->viewportEvent(e) : false); }
private:
diff --git a/src/widgets/widgets/qabstractslider.cpp b/src/widgets/widgets/qabstractslider.cpp
index a0611565b8..4e65fbac88 100644
--- a/src/widgets/widgets/qabstractslider.cpp
+++ b/src/widgets/widgets/qabstractslider.cpp
@@ -1,48 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <qapplication.h>
#include "qabstractslider.h"
#include "qevent.h"
#include "qabstractslider_p.h"
#include "qdebug.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
#include <limits.h>
@@ -107,7 +71,7 @@ QT_BEGIN_NAMESPACE
\row \li \l sliderReleased()
\li the user releases the slider.
\row \li \l actionTriggered()
- \li a slider action was triggerd.
+ \li a slider action was triggered.
\row \li \l rangeChanged()
\li a the range has changed.
\endtable
@@ -534,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);
}
-#ifndef QT_NO_ACCESSIBILITY
+#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/qabstractslider.h b/src/widgets/widgets/qabstractslider.h
index 7791d30d10..fa2261fda1 100644
--- a/src/widgets/widgets/qabstractslider.h
+++ b/src/widgets/widgets/qabstractslider.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTSLIDER_H
#define QABSTRACTSLIDER_H
diff --git a/src/widgets/widgets/qabstractslider_p.h b/src/widgets/widgets/qabstractslider_p.h
index 1b8c76c7ec..db4294e198 100644
--- a/src/widgets/widgets/qabstractslider_p.h
+++ b/src/widgets/widgets/qabstractslider_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTSLIDER_P_H
#define QABSTRACTSLIDER_P_H
diff --git a/src/widgets/widgets/qabstractspinbox.cpp b/src/widgets/widgets/qabstractspinbox.cpp
index 6a0d2f5019..f377275d23 100644
--- a/src/widgets/widgets/qabstractspinbox.cpp
+++ b/src/widgets/widgets/qabstractspinbox.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <private/qabstractspinbox_p.h>
@@ -58,10 +22,11 @@
#include <qpalette.h>
#include <qstylepainter.h>
#include <qdebug.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
# include <qaccessible.h>
#endif
+#include <QtCore/qpointer.h>
//#define QABSTRACTSPINBOX_QSBDEBUG
#ifdef QABSTRACTSPINBOX_QSBDEBUG
@@ -72,6 +37,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
\class QAbstractSpinBox
\brief The QAbstractSpinBox class provides a spinbox and a line edit to
@@ -420,7 +387,7 @@ bool QAbstractSpinBox::isAccelerated() const
\since 5.3
- This property holds whether a thousands separator is enabled. By default this
+ \brief whether a thousands separator is enabled. By default this
property is false.
*/
bool QAbstractSpinBox::isGroupSeparatorShown() const
@@ -570,7 +537,7 @@ void QAbstractSpinBox::clear()
QAbstractSpinBox::StepEnabled QAbstractSpinBox::stepEnabled() const
{
Q_D(const QAbstractSpinBox);
- if (d->readOnly || d->type == QVariant::Invalid)
+ if (d->readOnly || d->type == QMetaType::UnknownType)
return StepNone;
if (d->wrapping)
return StepEnabled(StepUpEnabled | StepDownEnabled);
@@ -671,7 +638,8 @@ void QAbstractSpinBox::stepBy(int steps)
} else if (e == AlwaysEmit) {
d->emitSignals(e, old);
}
- selectAll();
+ if (style()->styleHint(QStyle::SH_SpinBox_SelectOnStep, nullptr, this, nullptr))
+ selectAll();
}
/*!
@@ -723,15 +691,15 @@ void QAbstractSpinBox::setLineEdit(QLineEdit *lineEdit)
d->edit->setFocusProxy(this);
d->edit->setAcceptDrops(false);
- if (d->type != QVariant::Invalid) {
- 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()));
+ if (d->type != QMetaType::UnknownType) {
+ 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);
@@ -795,7 +763,7 @@ bool QAbstractSpinBox::event(QEvent *event)
case QEvent::HoverEnter:
case QEvent::HoverLeave:
case QEvent::HoverMove:
- d->updateHoverControl(static_cast<const QHoverEvent *>(event)->pos());
+ d->updateHoverControl(static_cast<const QHoverEvent *>(event)->position().toPoint());
break;
case QEvent::ShortcutOverride:
if (d->edit->event(event))
@@ -905,7 +873,7 @@ QSize QAbstractSpinBox::sizeHint() const
int h = d->edit->sizeHint().height();
int w = 0;
QString s;
- QString fixedContent = d->prefix + d->suffix + QLatin1Char(' ');
+ QString fixedContent = d->prefix + d->suffix + u' ';
s = d->textFromValue(d->minimum);
s.truncate(18);
s += fixedContent;
@@ -924,8 +892,7 @@ QSize QAbstractSpinBox::sizeHint() const
QStyleOptionSpinBox opt;
initStyleOption(&opt);
QSize hint(w, h);
- d->cachedSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
- .expandedTo(QApplication::globalStrut());
+ d->cachedSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this);
}
return d->cachedSizeHint;
}
@@ -946,7 +913,7 @@ QSize QAbstractSpinBox::minimumSizeHint() const
int w = 0;
QString s;
- QString fixedContent = d->prefix + QLatin1Char(' ');
+ QString fixedContent = d->prefix + u' ';
s = d->textFromValue(d->minimum);
s.truncate(18);
s += fixedContent;
@@ -966,8 +933,7 @@ QSize QAbstractSpinBox::minimumSizeHint() const
initStyleOption(&opt);
QSize hint(w, h);
- d->cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
- .expandedTo(QApplication::globalStrut());
+ d->cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this);
}
return d->cachedMinimumSizeHint;
}
@@ -1012,6 +978,8 @@ void QAbstractSpinBox::keyPressEvent(QKeyEvent *event)
{
Q_D(QAbstractSpinBox);
+ d->keyboardModifiers = event->modifiers();
+
if (!event->text().isEmpty() && d->edit->cursorPosition() < d->prefix.size())
d->edit->setCursorPosition(d->prefix.size());
@@ -1048,12 +1016,12 @@ void QAbstractSpinBox::keyPressEvent(QKeyEvent *event)
}
if (d->spinClickTimerId == -1)
stepBy(steps);
- if(event->isAutoRepeat() && !isPgUpOrDown) {
- if(d->spinClickThresholdTimerId == -1 && d->spinClickTimerId == -1) {
+ if (event->isAutoRepeat() && !isPgUpOrDown) {
+ if (d->spinClickThresholdTimerId == -1 && d->spinClickTimerId == -1) {
d->updateState(up, true);
}
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(this, d->value);
QAccessible::updateAccessibility(&event);
#endif
@@ -1095,7 +1063,7 @@ void QAbstractSpinBox::keyPressEvent(QKeyEvent *event)
case Qt::Key_U:
if (event->modifiers() & Qt::ControlModifier
- && QGuiApplication::platformName() == QLatin1String("xcb")) { // only X11
+ && QGuiApplication::platformName() == "xcb"_L1) { // only X11
event->accept();
if (!isReadOnly())
clear();
@@ -1152,6 +1120,7 @@ void QAbstractSpinBox::keyReleaseEvent(QKeyEvent *event)
{
Q_D(QAbstractSpinBox);
+ d->keyboardModifiers = event->modifiers();
if (d->buttonState & Keyboard && !event->isAutoRepeat()) {
d->reset();
} else {
@@ -1268,7 +1237,7 @@ void QAbstractSpinBox::timerEvent(QTimerEvent *event)
killTimer(d->spinClickThresholdTimerId);
d->spinClickThresholdTimerId = -1;
d->effectiveSpinRepeatRate = d->buttonState & Keyboard
- ? QGuiApplication::styleHints()->keyboardAutoRepeatRate()
+ ? QGuiApplication::styleHints()->keyboardAutoRepeatRateF()
: d->spinClickTimerInterval;
d->spinClickTimerId = startTimer(d->effectiveSpinRepeatRate);
doStep = true;
@@ -1284,7 +1253,7 @@ void QAbstractSpinBox::timerEvent(QTimerEvent *event)
}
if (doStep) {
- const bool increaseStepRate = QGuiApplication::keyboardModifiers() & d->stepModifier;
+ const bool increaseStepRate = d->keyboardModifiers & d->stepModifier;
const StepEnabled st = stepEnabled();
if (d->buttonState & Up) {
if (!(st & StepUpEnabled)) {
@@ -1361,7 +1330,8 @@ void QAbstractSpinBox::mouseMoveEvent(QMouseEvent *event)
{
Q_D(QAbstractSpinBox);
- d->updateHoverControl(event->pos());
+ d->keyboardModifiers = event->modifiers();
+ d->updateHoverControl(event->position().toPoint());
// If we have a timer ID, update the state
if (d->spinClickTimerId != -1 && d->buttonSymbols != NoButtons) {
@@ -1384,11 +1354,12 @@ void QAbstractSpinBox::mousePressEvent(QMouseEvent *event)
{
Q_D(QAbstractSpinBox);
+ d->keyboardModifiers = event->modifiers();
if (event->button() != Qt::LeftButton || d->buttonState != None) {
return;
}
- d->updateHoverControl(event->pos());
+ d->updateHoverControl(event->position().toPoint());
event->accept();
const StepEnabled se = (d->buttonSymbols == NoButtons) ? StepEnabled(StepNone) : stepEnabled();
@@ -1408,6 +1379,7 @@ void QAbstractSpinBox::mouseReleaseEvent(QMouseEvent *event)
{
Q_D(QAbstractSpinBox);
+ d->keyboardModifiers = event->modifiers();
if ((d->buttonState & Mouse) != 0)
d->reset();
event->accept();
@@ -1421,15 +1393,9 @@ void QAbstractSpinBox::mouseReleaseEvent(QMouseEvent *event)
*/
QAbstractSpinBoxPrivate::QAbstractSpinBoxPrivate()
- : edit(nullptr), type(QVariant::Invalid), spinClickTimerId(-1),
- spinClickTimerInterval(100), spinClickThresholdTimerId(-1), spinClickThresholdTimerInterval(-1),
- effectiveSpinRepeatRate(1), buttonState(None), cachedText(QLatin1String("\x01")),
- cachedState(QValidator::Invalid), pendingEmit(false), readOnly(false), wrapping(false),
- ignoreCursorPositionChanged(false), frame(true), accelerate(false), keyboardTracking(true),
- cleared(false), ignoreUpdateEdit(false), correctionMode(QAbstractSpinBox::CorrectToPreviousValue),
- stepModifier(Qt::ControlModifier), acceleration(0), hoverControl(QStyle::SC_None),
- buttonSymbols(QAbstractSpinBox::UpDownArrows), validator(nullptr), showGroupSeparator(0),
- wheelDeltaRemainder(0)
+ : pendingEmit(false), readOnly(false), wrapping(false),
+ ignoreCursorPositionChanged(false), frame(true), accelerate(false), keyboardTracking(true),
+ cleared(false), ignoreUpdateEdit(false), showGroupSeparator(false)
{
}
@@ -1484,7 +1450,7 @@ QStyle::SubControl QAbstractSpinBoxPrivate::newHoverControl(const QPoint &pos)
QString QAbstractSpinBoxPrivate::stripped(const QString &t, int *pos) const
{
- QStringRef text(&t);
+ QStringView text(t);
if (specialValueText.size() == 0 || text != specialValueText) {
int from = 0;
int size = text.size();
@@ -1545,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);
@@ -1575,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;
@@ -1626,11 +1592,13 @@ void QAbstractSpinBoxPrivate::init()
Q_Q(QAbstractSpinBox);
q->setLineEdit(new QLineEdit(q));
- edit->setObjectName(QLatin1String("qt_spinbox_lineedit"));
+ edit->setObjectName("qt_spinbox_lineedit"_L1);
validator = new QSpinBoxValidator(q, this);
edit->setValidator(validator);
QStyleOptionSpinBox opt;
+ // ### This is called from the ctor and thus we shouldn't call initStyleOption yet
+ // ### as we only call the base class implementation of initStyleOption called.
q->initStyleOption(&opt);
spinClickTimerInterval = q->style()->styleHint(QStyle::SH_SpinBox_ClickAutoRepeatRate, &opt, q);
spinClickThresholdTimerInterval = q->style()->styleHint(QStyle::SH_SpinBox_ClickAutoRepeatThreshold, &opt, q);
@@ -1678,13 +1646,13 @@ void QAbstractSpinBoxPrivate::updateState(bool up, bool fromKeyboard /* = false
reset();
if (q && (q->stepEnabled() & (up ? QAbstractSpinBox::StepUpEnabled
: QAbstractSpinBox::StepDownEnabled))) {
- spinClickThresholdTimerId = q->startTimer(spinClickThresholdTimerInterval);
buttonState = (up ? Up : Down) | (fromKeyboard ? Keyboard : Mouse);
int steps = up ? 1 : -1;
- if (QGuiApplication::keyboardModifiers() & stepModifier)
+ if (keyboardModifiers & stepModifier)
steps *= 10;
q->stepBy(steps);
-#ifndef QT_NO_ACCESSIBILITY
+ spinClickThresholdTimerId = q->startTimer(spinClickThresholdTimerInterval);
+#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(q, value);
QAccessible::updateAccessibility(&event);
#endif
@@ -1805,7 +1773,7 @@ void QAbstractSpinBoxPrivate::setValue(const QVariant &val, EmitPolicy ep,
void QAbstractSpinBoxPrivate::updateEdit()
{
Q_Q(QAbstractSpinBox);
- if (type == QVariant::Invalid)
+ if (type == QMetaType::UnknownType)
return;
const QString newText = specialValue() ? specialValueText : prefix + textFromValue(value) + suffix;
if (newText == edit->displayText() || cleared)
@@ -1865,8 +1833,8 @@ QVariant QAbstractSpinBoxPrivate::getZeroVariant() const
{
QVariant ret;
switch (type) {
- case QVariant::Int: ret = QVariant((int)0); break;
- case QVariant::Double: ret = QVariant((double)0.0); break;
+ case QMetaType::Int: ret = QVariant(0); break;
+ case QMetaType::Double: ret = QVariant(0.0); break;
default: break;
}
return ret;
@@ -1913,7 +1881,7 @@ QVariant QAbstractSpinBoxPrivate::valueFromText(const QString &) const
void QAbstractSpinBoxPrivate::interpret(EmitPolicy ep)
{
Q_Q(QAbstractSpinBox);
- if (type == QVariant::Invalid || cleared)
+ if (type == QMetaType::UnknownType || cleared)
return;
QVariant v = getZeroVariant();
@@ -1954,7 +1922,7 @@ void QAbstractSpinBoxPrivate::clearCache() const
QVariant QAbstractSpinBoxPrivate::calculateAdaptiveDecimalStep(int steps) const
{
- Q_UNUSED(steps)
+ Q_UNUSED(steps);
return singleStep;
}
@@ -1968,7 +1936,7 @@ QVariant QAbstractSpinBoxPrivate::calculateAdaptiveDecimalStep(int steps) const
QSpinBoxValidator::QSpinBoxValidator(QAbstractSpinBox *qp, QAbstractSpinBoxPrivate *dp)
: QValidator(qp), qptr(qp), dptr(dp)
{
- setObjectName(QLatin1String("qt_spinboxvalidator"));
+ setObjectName("qt_spinboxvalidator"_L1);
}
/*!
@@ -1985,7 +1953,7 @@ QValidator::State QSpinBoxValidator::validate(QString &input, int &pos) const
if (!dptr->prefix.isEmpty() && !input.startsWith(dptr->prefix)) {
input.prepend(dptr->prefix);
- pos += dptr->prefix.length();
+ pos += dptr->prefix.size();
}
if (!dptr->suffix.isEmpty() && !input.endsWith(dptr->suffix))
@@ -2013,11 +1981,11 @@ void QSpinBoxValidator::fixup(QString &input) const
QVariant operator+(const QVariant &arg1, const QVariant &arg2)
{
QVariant ret;
- if (Q_UNLIKELY(arg1.type() != arg2.type()))
+ if (Q_UNLIKELY(arg1.userType() != arg2.userType()))
qWarning("QAbstractSpinBox: Internal error: Different types (%s vs %s) (%s:%d)",
arg1.typeName(), arg2.typeName(), __FILE__, __LINE__);
- switch (arg1.type()) {
- case QVariant::Int: {
+ switch (arg1.userType()) {
+ case QMetaType::Int: {
const int int1 = arg1.toInt();
const int int2 = arg2.toInt();
if (int1 > 0 && (int2 >= INT_MAX - int1)) {
@@ -2031,9 +1999,9 @@ QVariant operator+(const QVariant &arg1, const QVariant &arg2)
}
break;
}
- case QVariant::Double: ret = QVariant(arg1.toDouble() + arg2.toDouble()); break;
+ case QMetaType::Double: ret = QVariant(arg1.toDouble() + arg2.toDouble()); break;
#if QT_CONFIG(datetimeparser)
- case QVariant::DateTime: {
+ case QMetaType::QDateTime: {
QDateTime a2 = arg2.toDateTime();
QDateTime a1 = arg1.toDateTime().addDays(QDATETIMEEDIT_DATE_MIN.daysTo(a2.date()));
a1.setTime(a1.time().addMSecs(a2.time().msecsSinceStartOfDay()));
@@ -2055,13 +2023,13 @@ QVariant operator+(const QVariant &arg1, const QVariant &arg2)
QVariant operator-(const QVariant &arg1, const QVariant &arg2)
{
QVariant ret;
- if (Q_UNLIKELY(arg1.type() != arg2.type()))
+ if (Q_UNLIKELY(arg1.userType() != arg2.userType()))
qWarning("QAbstractSpinBox: Internal error: Different types (%s vs %s) (%s:%d)",
arg1.typeName(), arg2.typeName(), __FILE__, __LINE__);
- switch (arg1.type()) {
- case QVariant::Int: ret = QVariant(arg1.toInt() - arg2.toInt()); break;
- case QVariant::Double: ret = QVariant(arg1.toDouble() - arg2.toDouble()); break;
- case QVariant::DateTime: {
+ switch (arg1.userType()) {
+ case QMetaType::Int: ret = QVariant(arg1.toInt() - arg2.toInt()); break;
+ case QMetaType::Double: ret = QVariant(arg1.toDouble() - arg2.toDouble()); break;
+ case QMetaType::QDateTime: {
QDateTime a1 = arg1.toDateTime();
QDateTime a2 = arg2.toDateTime();
int days = a2.daysTo(a1);
@@ -2075,6 +2043,7 @@ QVariant operator-(const QVariant &arg1, const QVariant &arg2)
dt.setTime(dt.time().addMSecs(msecs));
ret = QVariant(dt);
}
+ break;
}
default: break;
}
@@ -2090,13 +2059,13 @@ QVariant operator*(const QVariant &arg1, double multiplier)
{
QVariant ret;
- switch (arg1.type()) {
- case QVariant::Int:
+ switch (arg1.userType()) {
+ case QMetaType::Int:
ret = static_cast<int>(qBound<double>(INT_MIN, arg1.toInt() * multiplier, INT_MAX));
break;
- case QVariant::Double: ret = QVariant(arg1.toDouble() * multiplier); break;
+ case QMetaType::Double: ret = QVariant(arg1.toDouble() * multiplier); break;
#if QT_CONFIG(datetimeparser)
- case QVariant::DateTime: {
+ case QMetaType::QDateTime: {
double days = QDATETIMEEDIT_DATE_MIN.daysTo(arg1.toDateTime().date()) * multiplier;
const qint64 daysInt = qint64(days);
days -= daysInt;
@@ -2119,17 +2088,17 @@ double operator/(const QVariant &arg1, const QVariant &arg2)
double a1 = 0;
double a2 = 0;
- switch (arg1.type()) {
- case QVariant::Int:
+ switch (arg1.userType()) {
+ case QMetaType::Int:
a1 = (double)arg1.toInt();
a2 = (double)arg2.toInt();
break;
- case QVariant::Double:
+ case QMetaType::Double:
a1 = arg1.toDouble();
a2 = arg2.toDouble();
break;
#if QT_CONFIG(datetimeparser)
- case QVariant::DateTime:
+ case QMetaType::QDateTime:
a1 = QDATETIMEEDIT_DATE_MIN.daysTo(arg1.toDate());
a2 = QDATETIMEEDIT_DATE_MIN.daysTo(arg2.toDate());
a1 += arg1.toDateTime().time().msecsSinceStartOfDay() / (36e5 * 24);
@@ -2144,9 +2113,9 @@ double operator/(const QVariant &arg1, const QVariant &arg2)
int QAbstractSpinBoxPrivate::variantCompare(const QVariant &arg1, const QVariant &arg2)
{
- switch (arg2.type()) {
- case QVariant::Date:
- Q_ASSERT_X(arg1.type() == QVariant::Date, "QAbstractSpinBoxPrivate::variantCompare",
+ switch (arg2.userType()) {
+ case QMetaType::QDate:
+ Q_ASSERT_X(arg1.userType() == QMetaType::QDate, "QAbstractSpinBoxPrivate::variantCompare",
qPrintable(QString::fromLatin1("Internal error 1 (%1)").
arg(QString::fromLatin1(arg1.typeName()))));
if (arg1.toDate() == arg2.toDate()) {
@@ -2156,8 +2125,8 @@ int QAbstractSpinBoxPrivate::variantCompare(const QVariant &arg1, const QVariant
} else {
return 1;
}
- case QVariant::Time:
- Q_ASSERT_X(arg1.type() == QVariant::Time, "QAbstractSpinBoxPrivate::variantCompare",
+ case QMetaType::QTime:
+ Q_ASSERT_X(arg1.userType() == QMetaType::QTime, "QAbstractSpinBoxPrivate::variantCompare",
qPrintable(QString::fromLatin1("Internal error 2 (%1)").
arg(QString::fromLatin1(arg1.typeName()))));
if (arg1.toTime() == arg2.toTime()) {
@@ -2169,7 +2138,7 @@ int QAbstractSpinBoxPrivate::variantCompare(const QVariant &arg1, const QVariant
}
- case QVariant::DateTime:
+ case QMetaType::QDateTime:
if (arg1.toDateTime() == arg2.toDateTime()) {
return 0;
} else if (arg1.toDateTime() < arg2.toDateTime()) {
@@ -2177,7 +2146,7 @@ int QAbstractSpinBoxPrivate::variantCompare(const QVariant &arg1, const QVariant
} else {
return 1;
}
- case QVariant::Int:
+ case QMetaType::Int:
if (arg1.toInt() == arg2.toInt()) {
return 0;
} else if (arg1.toInt() < arg2.toInt()) {
@@ -2185,7 +2154,7 @@ int QAbstractSpinBoxPrivate::variantCompare(const QVariant &arg1, const QVariant
} else {
return 1;
}
- case QVariant::Double:
+ case QMetaType::Double:
if (arg1.toDouble() == arg2.toDouble()) {
return 0;
} else if (arg1.toDouble() < arg2.toDouble()) {
@@ -2193,8 +2162,8 @@ int QAbstractSpinBoxPrivate::variantCompare(const QVariant &arg1, const QVariant
} else {
return 1;
}
- case QVariant::Invalid:
- if (arg2.type() == QVariant::Invalid)
+ case QMetaType::UnknownType:
+ if (arg2.userType() == QMetaType::UnknownType)
return 0;
Q_FALLTHROUGH();
default:
diff --git a/src/widgets/widgets/qabstractspinbox.h b/src/widgets/widgets/qabstractspinbox.h
index 87d46c7326..91d3dcb8fc 100644
--- a/src/widgets/widgets/qabstractspinbox.h
+++ b/src/widgets/widgets/qabstractspinbox.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTSPINBOX_H
#define QABSTRACTSPINBOX_H
@@ -160,7 +124,7 @@ protected:
void timerEvent(QTimerEvent *event) override;
void paintEvent(QPaintEvent *event) override;
void showEvent(QShowEvent *event) override;
- void initStyleOption(QStyleOptionSpinBox *option) const;
+ virtual void initStyleOption(QStyleOptionSpinBox *option) const;
QLineEdit *lineEdit() const;
void setLineEdit(QLineEdit *edit);
@@ -172,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 ad169fde19..4252a01423 100644
--- a/src/widgets/widgets/qabstractspinbox_p.h
+++ b/src/widgets/widgets/qabstractspinbox_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QABSTRACTSPINBOX_P_H
#define QABSTRACTSPINBOX_P_H
@@ -110,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);
@@ -124,17 +88,32 @@ public:
virtual QVariant calculateAdaptiveDecimalStep(int steps) const;
- QLineEdit *edit;
QString prefix, suffix, specialValueText;
QVariant value, minimum, maximum, singleStep;
- QVariant::Type type;
- int spinClickTimerId, spinClickTimerInterval, spinClickThresholdTimerId, spinClickThresholdTimerInterval;
- int effectiveSpinRepeatRate;
- uint buttonState;
- mutable QString cachedText;
+ QRect hoverRect;
+
+ mutable QString cachedText = { u'\x01' };
mutable QVariant cachedValue;
- mutable QValidator::State cachedState;
mutable QSize cachedSizeHint, cachedMinimumSizeHint;
+ QLineEdit *edit = nullptr;
+ QSpinBoxValidator *validator = nullptr;
+ QMetaType::Type type = QMetaType::UnknownType;
+ int spinClickTimerId = -1;
+ int spinClickTimerInterval = 100;
+ int spinClickThresholdTimerId = -1;
+ int spinClickThresholdTimerInterval = -1;
+ qreal effectiveSpinRepeatRate = 1;
+ int acceleration = 0;
+ int wheelDeltaRemainder = 0;
+
+ Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier;
+ Qt::KeyboardModifier stepModifier = Qt::ControlModifier;
+ QAbstractSpinBox::CorrectionMode correctionMode = QAbstractSpinBox::CorrectToPreviousValue;
+ QAbstractSpinBox::StepType stepType = QAbstractSpinBox::StepType::DefaultStepType;
+ QAbstractSpinBox::ButtonSymbols buttonSymbols = QAbstractSpinBox::UpDownArrows;
+ QStyle::SubControl hoverControl = QStyle::SC_None;
+ mutable QValidator::State cachedState = QValidator::Invalid;
+ uint buttonState = None;
uint pendingEmit : 1;
uint readOnly : 1;
uint wrapping : 1;
@@ -144,16 +123,7 @@ public:
uint keyboardTracking : 1;
uint cleared : 1;
uint ignoreUpdateEdit : 1;
- QAbstractSpinBox::CorrectionMode correctionMode;
- QAbstractSpinBox::StepType stepType = QAbstractSpinBox::StepType::DefaultStepType;
- Qt::KeyboardModifier stepModifier = Qt::ControlModifier;
- int acceleration;
- QStyle::SubControl hoverControl;
- QRect hoverRect;
- QAbstractSpinBox::ButtonSymbols buttonSymbols;
- QSpinBoxValidator *validator;
uint showGroupSeparator : 1;
- int wheelDeltaRemainder;
};
class QSpinBoxValidator : public QValidator
diff --git a/src/widgets/widgets/qbuttongroup.cpp b/src/widgets/widgets/qbuttongroup.cpp
index c3fd37d8e9..079ef45e90 100644
--- a/src/widgets/widgets/qbuttongroup.cpp
+++ b/src/widgets/widgets/qbuttongroup.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 "private/qbuttongroup_p.h"
@@ -50,7 +14,7 @@ void QButtonGroupPrivate::detectCheckedButton()
checkedButton = nullptr;
if (exclusive)
return;
- for (int i = 0; i < buttonList.count(); i++) {
+ for (int i = 0; i < buttonList.size(); i++) {
if (buttonList.at(i) != previous && buttonList.at(i)->isChecked()) {
checkedButton = buttonList.at(i);
return;
@@ -93,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.
@@ -118,7 +82,7 @@ QButtonGroup::QButtonGroup(QObject *parent)
QButtonGroup::~QButtonGroup()
{
Q_D(QButtonGroup);
- for (int i = 0; i < d->buttonList.count(); ++i)
+ for (int i = 0; i < d->buttonList.size(); ++i)
d->buttonList.at(i)->d_func()->group = nullptr;
}
@@ -163,7 +127,8 @@ void QButtonGroup::setExclusive(bool exclusive)
*/
/*!
- \fn void QButtonGroup::buttonClicked(int id)
+ \fn void QButtonGroup::idClicked(int id)
+ \since 5.15
This signal is emitted when a button with the given \a id is
clicked.
@@ -181,8 +146,8 @@ void QButtonGroup::setExclusive(bool exclusive)
*/
/*!
- \fn void QButtonGroup::buttonPressed(int id)
- \since 4.2
+ \fn void QButtonGroup::idPressed(int id)
+ \since 5.15
This signal is emitted when a button with the given \a id is
pressed down.
@@ -200,8 +165,8 @@ void QButtonGroup::setExclusive(bool exclusive)
*/
/*!
- \fn void QButtonGroup::buttonReleased(int id)
- \since 4.2
+ \fn void QButtonGroup::idReleased(int id)
+ \since 5.15
This signal is emitted when a button with the given \a id is
released.
@@ -220,8 +185,8 @@ void QButtonGroup::setExclusive(bool exclusive)
*/
/*!
- \fn void QButtonGroup::buttonToggled(int id, bool checked)
- \since 5.2
+ \fn void QButtonGroup::idToggled(int id, bool checked)
+ \since 5.15
This signal is emitted when a button with the given \a id is toggled.
\a checked is true if the button is checked, or false if the button is unchecked.
@@ -229,7 +194,6 @@ void QButtonGroup::setExclusive(bool exclusive)
\sa QAbstractButton::toggled()
*/
-
/*!
Adds the given \a button to the button group. If \a id is -1,
an id will be assigned to the button.
diff --git a/src/widgets/widgets/qbuttongroup.h b/src/widgets/widgets/qbuttongroup.h
index fec94ccb3e..2a399e5325 100644
--- a/src/widgets/widgets/qbuttongroup.h
+++ b/src/widgets/widgets/qbuttongroup.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QBUTTONGROUP_H
#define QBUTTONGROUP_H
@@ -78,13 +42,13 @@ public:
Q_SIGNALS:
void buttonClicked(QAbstractButton *);
- void buttonClicked(int);
void buttonPressed(QAbstractButton *);
- void buttonPressed(int);
void buttonReleased(QAbstractButton *);
- void buttonReleased(int);
void buttonToggled(QAbstractButton *, bool);
- void buttonToggled(int, bool);
+ void idClicked(int);
+ void idPressed(int);
+ void idReleased(int);
+ void idToggled(int, bool);
private:
Q_DISABLE_COPY(QButtonGroup)
diff --git a/src/widgets/widgets/qbuttongroup_p.h b/src/widgets/widgets/qbuttongroup_p.h
index 148f572373..ffeab3fc0b 100644
--- a/src/widgets/widgets/qbuttongroup_p.h
+++ b/src/widgets/widgets/qbuttongroup_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2017 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 QBUTTONGROUP_P_H
#define QBUTTONGROUP_P_H
diff --git a/src/widgets/widgets/qcalendarwidget.cpp b/src/widgets/widgets/qcalendarwidget.cpp
index fe1133c6c7..034127b4f3 100644
--- a/src/widgets/widgets/qcalendarwidget.cpp
+++ b/src/widgets/widgets/qcalendarwidget.cpp
@@ -1,46 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 "qcalendarwidget.h"
#include <qabstractitemmodel.h>
-#include <qitemdelegate.h>
+#include <qstyleditemdelegate.h>
#include <qdatetime.h>
#include <qtableview.h>
#include <qlayout.h>
@@ -63,6 +27,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
enum {
RowCount = 6,
ColumnCount = 7,
@@ -71,13 +37,13 @@ enum {
MinimumDayOffset = 1
};
-namespace {
-
static QString formatNumber(int number, int fieldWidth)
{
- return QString::number(number).rightJustified(fieldWidth, QLatin1Char('0'));
+ return QString::number(number).rightJustified(fieldWidth, u'0');
}
+namespace QtPrivate {
+
class QCalendarDateSectionValidator
{
public:
@@ -105,9 +71,9 @@ protected:
QString QCalendarDateSectionValidator::highlightString(const QString &str, int pos)
{
if (pos == 0)
- return QLatin1String("<b>") + str + QLatin1String("</b>");
- int startPos = str.length() - pos;
- return str.midRef(0, startPos) + QLatin1String("<b>") + str.midRef(startPos, pos) + QLatin1String("</b>");
+ return "<b>"_L1 + str + "</b>"_L1;
+ int startPos = str.size() - pos;
+ return QStringView{str}.mid(0, startPos) + "<b>"_L1 + QStringView{str}.mid(startPos, pos) + "</b>"_L1;
}
@@ -186,7 +152,7 @@ QDate QCalendarDayValidator::applyToDate(QDate date, QCalendar cal) const
auto parts = cal.partsFromDate(date);
if (!parts.isValid())
return QDate();
- parts.day = qMin(qMax(1, m_day), cal.daysInMonth(parts.year, parts.month));
+ parts.day = qMin(qMax(1, m_day), cal.daysInMonth(parts.month, parts.year));
return cal.dateFromParts(parts);
}
@@ -292,7 +258,7 @@ QDate QCalendarMonthValidator::applyToDate(QDate date, QCalendar cal) const
if (!parts.isValid())
return QDate();
parts.month = qMin(qMax(1, m_month), cal.monthsInYear(parts.year));
- parts.day = qMin(parts.day, cal.daysInMonth(parts.year, m_month)); // m_month or parts.month ?
+ parts.day = qMin(parts.day, cal.daysInMonth(m_month, parts.year)); // m_month or parts.month ?
return cal.dateFromParts(parts);
}
@@ -401,7 +367,7 @@ QDate QCalendarYearValidator::applyToDate(QDate date, QCalendar cal) const
return QDate();
// This widget does not support negative years (some calendars may support)
parts.year = qMax(1, m_year);
- parts.day = qMin(parts.day, cal.daysInMonth(parts.year, parts.month));
+ parts.day = qMin(parts.day, cal.daysInMonth(parts.month, parts.year));
return cal.dateFromParts(parts);
}
@@ -426,15 +392,17 @@ QString QCalendarYearValidator::text(QDate date, QCalendar cal, int repeat) cons
///////////////////////////////////
struct SectionToken {
- Q_DECL_CONSTEXPR SectionToken(QCalendarDateSectionValidator *v, int rep)
+ constexpr SectionToken(QCalendarDateSectionValidator *v, int rep)
: validator(v), repeat(rep) {}
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
{
@@ -544,11 +512,11 @@ void QCalendarDateValidator::setFormat(const QString &format)
clear();
int pos = 0;
- const QLatin1Char quote('\'');
+ const auto quote = u'\'';
bool quoting = false;
QString separator;
while (pos < format.size()) {
- const QStringRef mid = format.midRef(pos);
+ const QStringView mid = QStringView{format}.mid(pos);
int offset = 1;
if (mid.startsWith(quote)) {
@@ -560,13 +528,13 @@ void QCalendarDateValidator::setFormat(const QString &format)
quoting = false;
} else {
QCalendarDateSectionValidator *validator = nullptr;
- if (nextChar == QLatin1Char('d')) {
+ if (nextChar == u'd') {
offset = qMin(4, countRepeat(format, pos));
validator = &m_dayValidator;
- } else if (nextChar == QLatin1Char('M')) {
+ } else if (nextChar == u'M') {
offset = qMin(4, countRepeat(format, pos));
validator = &m_monthValidator;
- } else if (nextChar == QLatin1Char('y')) {
+ } else if (nextChar == u'y') {
offset = qMin(4, countRepeat(format, pos));
validator = &m_yearValidator;
} else {
@@ -761,8 +729,8 @@ bool QCalendarTextNavigator::eventFilter(QObject *o, QEvent *e)
{
if (m_widget) {
if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) {
- QKeyEvent* ke = (QKeyEvent*)e;
- if ((ke->text().length() > 0 && ke->text().at(0).isPrint()) || m_dateFrame) {
+ 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();
emit editingFinished();
@@ -826,27 +794,23 @@ class StaticDayOfWeekAssociativeArray {
bool contained[7];
T data[7];
- static Q_DECL_CONSTEXPR int day2idx(Qt::DayOfWeek day) noexcept { return int(day) - 1; } // alt: day % 7
+ static constexpr int day2idx(Qt::DayOfWeek day) noexcept { return int(day) - 1; } // alt: day % 7
public:
- Q_DECL_CONSTEXPR StaticDayOfWeekAssociativeArray() noexcept(noexcept(T()))
-#ifdef Q_COMPILER_CONSTEXPR
+ constexpr StaticDayOfWeekAssociativeArray() noexcept(noexcept(T()))
: contained{}, data{} // arrays require uniform initialization
-#else
- : contained(), data()
-#endif
{}
- Q_DECL_CONSTEXPR bool contains(Qt::DayOfWeek day) const noexcept { return contained[day2idx(day)]; }
- Q_DECL_CONSTEXPR const T &value(Qt::DayOfWeek day) const noexcept { return data[day2idx(day)]; }
+ constexpr bool contains(Qt::DayOfWeek day) const noexcept { return contained[day2idx(day)]; }
+ constexpr const T &value(Qt::DayOfWeek day) const noexcept { return data[day2idx(day)]; }
- Q_DECL_RELAXED_CONSTEXPR T &operator[](Qt::DayOfWeek day) noexcept
+ constexpr T &operator[](Qt::DayOfWeek day) noexcept
{
const int idx = day2idx(day);
contained[idx] = true;
return data[idx];
}
- Q_DECL_RELAXED_CONSTEXPR void insert(Qt::DayOfWeek day, T v) noexcept
+ constexpr void insert(Qt::DayOfWeek day, T v) noexcept
{
operator[](day).swap(v);
}
@@ -860,38 +824,23 @@ class QCalendarModel : public QAbstractTableModel
public:
QCalendarModel(QObject *parent = nullptr);
- int rowCount(const QModelIndex &) const override
- { return RowCount + m_firstRow; }
- int columnCount(const QModelIndex &) const override
- { return ColumnCount + m_firstColumn; }
- QVariant data(const QModelIndex &index, int role) const override;
- Qt::ItemFlags flags(const QModelIndex &index) const override;
-
- bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override
- {
- beginInsertRows(parent, row, row + count - 1);
- endInsertRows();
- return true;
- }
- bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex()) override
- {
- beginInsertColumns(parent, column, column + count - 1);
- endInsertColumns();
- return true;
- }
- bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override
+ int rowCount(const QModelIndex &parent) const override
{
- beginRemoveRows(parent, row, row + count - 1);
- endRemoveRows();
- return true;
+ if (parent.isValid())
+ return 0;
+ return RowCount + m_firstRow;
}
- bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex()) override
+
+ int columnCount(const QModelIndex &parent) const override
{
- beginRemoveColumns(parent, column, column + count - 1);
- endRemoveColumns();
- return true;
+ if (parent.isValid())
+ return 0;
+ return ColumnCount + m_firstColumn;
}
+ QVariant data(const QModelIndex &index, int role) const override;
+ Qt::ItemFlags flags(const QModelIndex &index) const override;
+
void showMonth(int year, int month);
void setDate(QDate d);
@@ -955,7 +904,7 @@ public:
void internalUpdate() { updateGeometries(); }
void setReadOnly(bool enable);
- virtual void keyboardSearch(const QString & search) override { Q_UNUSED(search) }
+ virtual void keyboardSearch(const QString &) override {}
signals:
void showDate(QDate date);
@@ -1130,16 +1079,17 @@ QTextCharFormat QCalendarModel::formatForCell(int row, int col) const
{
QPalette pal;
QPalette::ColorGroup cg = QPalette::Active;
+ QTextCharFormat format;
+
if (m_view) {
pal = m_view->palette();
if (!m_view->isEnabled())
cg = QPalette::Disabled;
else if (!m_view->isActiveWindow())
cg = QPalette::Inactive;
+ format.setFont(m_view->font());
}
- QTextCharFormat format;
- format.setFont(m_view->font());
bool header = (m_weekNumbersShown && col == HeaderColumn)
|| (m_horizontalHeaderFormat != QCalendarWidget::NoHorizontalHeader && row == HeaderRow);
format.setBackground(pal.brush(cg, header ? QPalette::AlternateBase : QPalette::Base));
@@ -1157,7 +1107,7 @@ QTextCharFormat QCalendarModel::formatForCell(int row, int col) const
if (!header) {
QDate date = dateForCell(row, col);
format.merge(m_dateFormats.value(date));
- if(date < m_minimumDate || date > m_maximumDate)
+ if (date < m_minimumDate || date > m_maximumDate)
format.setBackground(pal.brush(cg, QPalette::Window));
if (m_shownMonth != date.month(m_calendar))
format.setForeground(pal.brush(QPalette::Disabled, QPalette::Text));
@@ -1173,7 +1123,7 @@ QVariant QCalendarModel::data(const QModelIndex &index, int role) const
int row = index.row();
int column = index.column();
- if(role == Qt::DisplayRole) {
+ if (role == Qt::DisplayRole) {
if (m_weekNumbersShown && column == HeaderColumn
&& row >= m_firstRow && row < m_firstRow + RowCount) {
QDate date = dateForCell(row, columnForDayOfWeek(Qt::Monday));
@@ -1303,11 +1253,13 @@ void QCalendarModel::setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeader
int oldFormat = m_horizontalHeaderFormat;
m_horizontalHeaderFormat = format;
if (oldFormat == QCalendarWidget::NoHorizontalHeader) {
+ beginInsertRows(QModelIndex(), 0, 0);
m_firstRow = 1;
- insertRow(0);
+ endInsertRows();
} else if (m_horizontalHeaderFormat == QCalendarWidget::NoHorizontalHeader) {
+ beginRemoveRows(QModelIndex(), 0, 0);
m_firstRow = 0;
- removeRow(0);
+ endRemoveRows();
}
internalUpdate();
}
@@ -1338,11 +1290,13 @@ void QCalendarModel::setWeekNumbersShown(bool show)
m_weekNumbersShown = show;
if (show) {
+ beginInsertColumns(QModelIndex(), 0, 0);
m_firstColumn = 1;
- insertColumn(0);
+ endInsertColumns();
} else {
+ beginRemoveColumns(QModelIndex(), 0, 0);
m_firstColumn = 0;
- removeColumn(0);
+ endRemoveColumns();
}
internalUpdate();
}
@@ -1397,7 +1351,7 @@ QModelIndex QCalendarView::moveCursor(CursorAction cursorAction, Qt::KeyboardMod
case QAbstractItemView::MoveEnd: {
auto parts = cal.partsFromDate(currentDate);
if (parts.isValid()) {
- parts.day = cal.daysInMonth(parts.year, parts.month);
+ parts.day = cal.daysInMonth(parts.month, parts.year);
currentDate = cal.dateFromParts(parts);
}
}
@@ -1485,7 +1439,7 @@ QDate QCalendarView::handleMouseEvent(QMouseEvent *event)
if (!calendarModel)
return QDate();
- QPoint pos = event->pos();
+ QPoint pos = event->position().toPoint();
QModelIndex index = indexAt(pos);
QDate date = calendarModel->dateForCell(index.row(), index.column());
if (date.isValid() && date >= calendarModel->m_minimumDate
@@ -1594,13 +1548,12 @@ void QCalendarView::mouseReleaseEvent(QMouseEvent *event)
}
}
-// ### Qt6: QStyledItemDelegate
-class QCalendarDelegate : public QItemDelegate
+class QCalendarDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
QCalendarDelegate(QCalendarWidgetPrivate *w, QObject *parent = nullptr)
- : QItemDelegate(parent), calendarWidgetPrivate(w)
+ : QStyledItemDelegate(parent), calendarWidgetPrivate(w)
{ }
virtual void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
@@ -1621,7 +1574,7 @@ public:
protected:
void paintEvent(QPaintEvent *e) override
{
- Q_UNUSED(e)
+ Q_UNUSED(e);
QStyleOptionToolButton opt;
initStyleOption(&opt);
@@ -1655,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
{
@@ -1717,7 +1683,7 @@ void QCalendarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt
QRect rect = option.rect;
calendarWidgetPrivate->paintCell(painter, rect, date);
} else {
- QItemDelegate::paint(painter, option, index);
+ QStyledItemDelegate::paint(painter, option, index);
}
}
@@ -1728,7 +1694,7 @@ void QCalendarDelegate::paintCell(QPainter *painter, const QRect &rect, QDate da
int col = -1;
calendarWidgetPrivate->m_model->cellForDate(date, &row, &col);
QModelIndex idx = calendarWidgetPrivate->m_model->index(row, col);
- QItemDelegate::paint(painter, storedOption, idx);
+ QStyledItemDelegate::paint(painter, storedOption, idx);
}
QCalendarWidgetPrivate::QCalendarWidgetPrivate()
@@ -1773,7 +1739,7 @@ void QCalendarWidgetPrivate::createNavigationBar(QWidget *widget)
{
Q_Q(QCalendarWidget);
navBarBackground = new QWidget(widget);
- navBarBackground->setObjectName(QLatin1String("qt_calendar_navigationbar"));
+ navBarBackground->setObjectName("qt_calendar_navigationbar"_L1);
navBarBackground->setAutoFillBackground(true);
navBarBackground->setBackgroundRole(QPalette::Highlight);
@@ -1834,11 +1800,11 @@ void QCalendarWidgetPrivate::createNavigationBar(QWidget *widget)
monthButton->setFocusPolicy(Qt::NoFocus);
//set names for the header controls.
- prevMonth->setObjectName(QLatin1String("qt_calendar_prevmonth"));
- nextMonth->setObjectName(QLatin1String("qt_calendar_nextmonth"));
- monthButton->setObjectName(QLatin1String("qt_calendar_monthbutton"));
- yearButton->setObjectName(QLatin1String("qt_calendar_yearbutton"));
- yearEdit->setObjectName(QLatin1String("qt_calendar_yearedit"));
+ prevMonth->setObjectName("qt_calendar_prevmonth"_L1);
+ nextMonth->setObjectName("qt_calendar_nextmonth"_L1);
+ monthButton->setObjectName("qt_calendar_monthbutton"_L1);
+ yearButton->setObjectName("qt_calendar_yearbutton"_L1);
+ yearEdit->setObjectName("qt_calendar_yearedit"_L1);
updateMonthMenu();
showMonth(m_model->m_date.year(m_model->m_calendar), m_model->m_date.month(m_model->m_calendar));
@@ -1939,7 +1905,6 @@ void QCalendarWidgetPrivate::_q_nextMonthClicked()
void QCalendarWidgetPrivate::_q_yearEditingFinished()
{
Q_Q(QCalendarWidget);
- yearButton->setText(q->locale().toString(yearEdit->value()));
yearEdit->hide();
q->setFocusPolicy(oldFocusPolicy);
qApp->removeEventFilter(q);
@@ -1948,6 +1913,7 @@ void QCalendarWidgetPrivate::_q_yearEditingFinished()
QDate currentDate = getCurrentDate();
int newYear = q->locale().toInt(yearEdit->text());
currentDate = currentDate.addYears(newYear - currentDate.year(m_model->m_calendar), m_model->m_calendar);
+ yearButton->setText(q->locale().toString(currentDate, u"yyyy", m_model->m_calendar));
updateCurrentPage(currentDate);
}
@@ -2150,7 +2116,7 @@ QCalendarWidget::QCalendarWidget(QWidget *parent)
d->m_model->m_dayFormats.insert(Qt::Saturday, fmt);
d->m_model->m_dayFormats.insert(Qt::Sunday, fmt);
d->m_view = new QCalendarView(this);
- d->m_view->setObjectName(QLatin1String("qt_calendar_calendarview"));
+ d->m_view->setObjectName("qt_calendar_calendarview"_L1);
d->m_view->setModel(d->m_model);
d->m_model->setView(d->m_view);
d->m_view->setSelectionBehavior(QAbstractItemView::SelectItems);
@@ -2232,7 +2198,9 @@ QSize QCalendarWidget::minimumSizeHint() const
int rows = 7;
int cols = 8;
- const int marginH = (style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1) * 2;
+ QStyleOption option;
+ option.initFrom(this);
+ const int marginH = (style()->pixelMetric(QStyle::PM_FocusFrameHMargin, &option, this) + 1) * 2;
if (horizontalHeaderFormat() == QCalendarWidget::NoHorizontalHeader) {
rows = 6;
@@ -2291,7 +2259,7 @@ QSize QCalendarWidget::minimumSizeHint() const
headerW += monthW + buttonDecoMargin;
fm = d->yearButton->fontMetrics();
- headerW += fm.boundingRect(QLatin1String("5555")).width() + buttonDecoMargin;
+ headerW += fm.boundingRect("5555"_L1).width() + buttonDecoMargin;
headerSize = QSize(headerW, headerH);
}
@@ -2309,7 +2277,7 @@ QSize QCalendarWidget::minimumSizeHint() const
Paints the cell specified by the given \a date, using the given \a painter and \a rect.
*/
-void QCalendarWidget::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
+void QCalendarWidget::paintCell(QPainter *painter, const QRect &rect, QDate date) const
{
Q_D(const QCalendarWidget);
d->m_delegate->paintCell(painter, rect, date);
@@ -2332,7 +2300,7 @@ QDate QCalendarWidget::selectedDate() const
return d->m_model->m_date;
}
-void QCalendarWidget::setSelectedDate(const QDate &date)
+void QCalendarWidget::setSelectedDate(QDate date)
{
Q_D(QCalendarWidget);
if (d->m_model->m_date == date && date == d->getCurrentDate())
@@ -2393,7 +2361,7 @@ void QCalendarWidget::setCurrentPage(int year, int month)
QDate currentDate = d->getCurrentDate();
QCalendar cal = d->m_model->m_calendar;
int day = currentDate.day(cal);
- int daysInMonths = cal.daysInMonth(year, month);
+ int daysInMonths = cal.daysInMonth(month, year);
if (day > daysInMonths)
day = daysInMonths;
@@ -2524,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()
*/
@@ -2541,7 +2509,7 @@ QDate QCalendarWidget::minimumDate() const
return d->m_model->m_minimumDate;
}
-void QCalendarWidget::setMinimumDate(const QDate &date)
+void QCalendarWidget::setMinimumDate(QDate date)
{
Q_D(QCalendarWidget);
if (!date.isValid() || d->m_model->m_minimumDate == date)
@@ -2560,6 +2528,11 @@ void QCalendarWidget::setMinimumDate(const QDate &date)
}
}
+void QCalendarWidget::clearMinimumDate()
+{
+ setMinimumDate(QDate::fromJulianDay(1));
+}
+
/*!
\property QCalendarWidget::maximumDate
\brief the maximum date of the currently specified date range.
@@ -2575,14 +2548,14 @@ void QCalendarWidget::setMinimumDate(const 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()
*/
@@ -2592,7 +2565,7 @@ QDate QCalendarWidget::maximumDate() const
return d->m_model->m_maximumDate;
}
-void QCalendarWidget::setMaximumDate(const QDate &date)
+void QCalendarWidget::setMaximumDate(QDate date)
{
Q_D(QCalendarWidget);
if (!date.isValid() || d->m_model->m_maximumDate == date)
@@ -2611,6 +2584,11 @@ void QCalendarWidget::setMaximumDate(const QDate &date)
}
}
+void QCalendarWidget::clearMaximumDate()
+{
+ setMaximumDate(QDate(9999, 12, 31));
+}
+
/*!
Defines a date range by setting the minimumDate and maximumDate
properties.
@@ -2630,7 +2608,7 @@ void QCalendarWidget::setMaximumDate(const QDate &date)
\sa setMinimumDate(), setMaximumDate()
*/
-void QCalendarWidget::setDateRange(const QDate &min, const QDate &max)
+void QCalendarWidget::setDateRange(QDate min, QDate max)
{
Q_D(QCalendarWidget);
if (d->m_model->m_minimumDate == min && d->m_model->m_maximumDate == max)
@@ -2895,10 +2873,10 @@ 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(const QDate &date) const
+QTextCharFormat QCalendarWidget::dateTextFormat(QDate date) const
{
Q_D(const QCalendarWidget);
return d->m_model->m_dateFormats.value(date);
@@ -2909,7 +2887,7 @@ QTextCharFormat QCalendarWidget::dateTextFormat(const QDate &date) const
If \a date is null, all date formats are cleared.
*/
-void QCalendarWidget::setDateTextFormat(const QDate &date, const QTextCharFormat &format)
+void QCalendarWidget::setDateTextFormat(QDate date, const QTextCharFormat &format)
{
Q_D(QCalendarWidget);
if (date.isNull())
@@ -2961,7 +2939,7 @@ void QCalendarWidget::setDateEditEnabled(bool enable)
\since 4.3
If the calendar widget's \l{dateEditEnabled}{date edit is enabled}, this
- property specifies the amount of time (in millseconds) that the date edit
+ property specifies the amount of time (in milliseconds) that the date edit
remains open after the most recent user input. Once this time has elapsed,
the date specified in the date edit is accepted and the popup is closed.
@@ -2987,7 +2965,7 @@ void QCalendarWidget::setDateEditAcceptDelay(int delay)
\sa updateCells(), yearShown(), monthShown()
*/
-void QCalendarWidget::updateCell(const QDate &date)
+void QCalendarWidget::updateCell(QDate date)
{
if (Q_UNLIKELY(!date.isValid())) {
qWarning("QCalendarWidget::updateCell: Invalid date");
@@ -3046,7 +3024,7 @@ void QCalendarWidget::updateCells()
*/
/*!
- \fn void QCalendarWidget::activated(const QDate &date)
+ \fn void QCalendarWidget::activated(QDate date)
This signal is emitted whenever the user presses the Return or
Enter key or double-clicks a \a date in the calendar
@@ -3054,7 +3032,7 @@ void QCalendarWidget::updateCells()
*/
/*!
- \fn void QCalendarWidget::clicked(const QDate &date)
+ \fn void QCalendarWidget::clicked(QDate date)
This signal is emitted when a mouse button is clicked. The date
the mouse was clicked on is specified by \a date. The signal is
@@ -3121,6 +3099,7 @@ bool QCalendarWidget::event(QEvent *event)
case QEvent::StyleChange:
d->cachedSizeHint = QSize();
d->m_view->updateGeometry();
+ break;
default:
break;
}
@@ -3143,7 +3122,7 @@ bool QCalendarWidget::eventFilter(QObject *watched, QEvent *event)
if (!widget || widget->window() != tlw)
return QWidget::eventFilter(watched, event);
- QPoint mousePos = widget->mapTo(tlw, static_cast<QMouseEvent *>(event)->pos());
+ QPoint mousePos = widget->mapTo(tlw, static_cast<QMouseEvent *>(event)->position().toPoint());
QRect geom = QRect(d->yearEdit->mapTo(tlw, QPoint(0, 0)), d->yearEdit->size());
if (!geom.contains(mousePos)) {
event->accept();
@@ -3175,7 +3154,7 @@ void QCalendarWidget::resizeEvent(QResizeEvent * event)
// XXX Should really use a QWidgetStack for yearEdit and yearButton,
// XXX here we hide the year edit when the layout is likely to break
// XXX the manual positioning of the yearEdit over the yearButton.
- if(d->yearEdit->isVisible() && event->size().width() != event->oldSize().width())
+ if (d->yearEdit->isVisible() && event->size().width() != event->oldSize().width())
d->_q_yearEditingFinished();
QWidget::resizeEvent(event);
diff --git a/src/widgets/widgets/qcalendarwidget.h b/src/widgets/widgets/qcalendarwidget.h
index 08825a0ff3..034c95dd62 100644
--- a/src/widgets/widgets/qcalendarwidget.h
+++ b/src/widgets/widgets/qcalendarwidget.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QCALENDARWIDGET_H
#define QCALENDARWIDGET_H
@@ -57,13 +21,15 @@ 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)
- Q_PROPERTY(HorizontalHeaderFormat horizontalHeaderFormat READ horizontalHeaderFormat WRITE setHorizontalHeaderFormat)
- Q_PROPERTY(VerticalHeaderFormat verticalHeaderFormat READ verticalHeaderFormat WRITE setVerticalHeaderFormat)
+ Q_PROPERTY(HorizontalHeaderFormat horizontalHeaderFormat READ horizontalHeaderFormat
+ WRITE setHorizontalHeaderFormat)
+ Q_PROPERTY(VerticalHeaderFormat verticalHeaderFormat READ verticalHeaderFormat
+ WRITE setVerticalHeaderFormat)
Q_PROPERTY(bool navigationBarVisible READ isNavigationBarVisible WRITE setNavigationBarVisible)
Q_PROPERTY(bool dateEditEnabled READ isDateEditEnabled WRITE setDateEditEnabled)
Q_PROPERTY(int dateEditAcceptDelay READ dateEditAcceptDelay WRITE setDateEditAcceptDelay)
@@ -101,10 +67,12 @@ public:
int monthShown() const;
QDate minimumDate() const;
- void setMinimumDate(const QDate &date);
+ void setMinimumDate(QDate date);
+ void clearMinimumDate();
QDate maximumDate() const;
- void setMaximumDate(const QDate &date);
+ void setMaximumDate(QDate date);
+ void clearMaximumDate();
Qt::DayOfWeek firstDayOfWeek() const;
void setFirstDayOfWeek(Qt::DayOfWeek dayOfWeek);
@@ -131,8 +99,8 @@ public:
void setWeekdayTextFormat(Qt::DayOfWeek dayOfWeek, const QTextCharFormat &format);
QMap<QDate, QTextCharFormat> dateTextFormat() const;
- QTextCharFormat dateTextFormat(const QDate &date) const;
- void setDateTextFormat(const QDate &date, const QTextCharFormat &format);
+ QTextCharFormat dateTextFormat(QDate date) const;
+ void setDateTextFormat(QDate date, const QTextCharFormat &format);
bool isDateEditEnabled() const;
void setDateEditEnabled(bool enable);
@@ -147,13 +115,13 @@ protected:
void resizeEvent(QResizeEvent * event) override;
void keyPressEvent(QKeyEvent * event) override;
- virtual void paintCell(QPainter *painter, const QRect &rect, const QDate &date) const;
- void updateCell(const QDate &date);
+ virtual void paintCell(QPainter *painter, const QRect &rect, QDate date) const;
+ void updateCell(QDate date);
void updateCells();
public Q_SLOTS:
- void setSelectedDate(const QDate &date);
- void setDateRange(const QDate &min, const QDate &max);
+ void setSelectedDate(QDate date);
+ void setDateRange(QDate min, QDate max);
void setCurrentPage(int year, int month);
void setGridVisible(bool show);
void setNavigationBarVisible(bool visible);
@@ -166,17 +134,17 @@ public Q_SLOTS:
Q_SIGNALS:
void selectionChanged();
- void clicked(const QDate &date);
- void activated(const QDate &date);
+ void clicked(QDate date);
+ void activated(QDate date);
void currentPageChanged(int year, int month);
private:
Q_DECLARE_PRIVATE(QCalendarWidget)
Q_DISABLE_COPY(QCalendarWidget)
- Q_PRIVATE_SLOT(d_func(), void _q_slotShowDate(const QDate &date))
- Q_PRIVATE_SLOT(d_func(), void _q_slotChangeDate(const QDate &date))
- Q_PRIVATE_SLOT(d_func(), void _q_slotChangeDate(const QDate &date, bool changeMonth))
+ Q_PRIVATE_SLOT(d_func(), void _q_slotShowDate(QDate date))
+ Q_PRIVATE_SLOT(d_func(), void _q_slotChangeDate(QDate date))
+ Q_PRIVATE_SLOT(d_func(), void _q_slotChangeDate(QDate date, bool changeMonth))
Q_PRIVATE_SLOT(d_func(), void _q_editingFinished())
Q_PRIVATE_SLOT(d_func(), void _q_prevMonthClicked())
Q_PRIVATE_SLOT(d_func(), void _q_nextMonthClicked())
diff --git a/src/widgets/widgets/qcheckbox.cpp b/src/widgets/widgets/qcheckbox.cpp
index 81bfd3af35..88cd603d70 100644
--- a/src/widgets/widgets/qcheckbox.cpp
+++ b/src/widgets/widgets/qcheckbox.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qcheckbox.h"
#include "qapplication.h"
@@ -45,7 +9,7 @@
#include "qstyle.h"
#include "qstyleoption.h"
#include "qevent.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
@@ -64,7 +28,7 @@ public:
uint tristate : 1;
uint noChange : 1;
uint hovering : 1;
- uint publishedState : 2;
+ Qt::CheckState publishedState : 3;
void init();
};
@@ -95,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.
@@ -120,14 +84,21 @@ 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, {fowler}{GUI Design Handbook: Check Box}
+ \sa QAbstractButton, QRadioButton
*/
/*!
\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.
@@ -247,7 +218,7 @@ Qt::CheckState QCheckBox::checkState() const
void QCheckBox::setCheckState(Qt::CheckState state)
{
Q_D(QCheckBox);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
bool noChange = d->noChange;
#endif
if (state == Qt::PartiallyChecked) {
@@ -260,12 +231,17 @@ 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
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (noChange != d->noChange) {
QAccessible::State s;
s.checkStateMixed = true;
@@ -292,8 +268,7 @@ QSize QCheckBox::sizeHint() const
text()).size();
if (!opt.icon.isNull())
sz = QSize(sz.width() + opt.iconSize.width() + 4, qMax(sz.height(), opt.iconSize.height()));
- d->sizeHint = (style()->sizeFromContents(QStyle::CT_CheckBox, &opt, sz, this)
- .expandedTo(QApplication::globalStrut()));
+ d->sizeHint = style()->sizeFromContents(QStyle::CT_CheckBox, &opt, sz, this);
return d->sizeHint;
}
@@ -326,7 +301,7 @@ void QCheckBox::mouseMoveEvent(QMouseEvent *e)
if (testAttribute(Qt::WA_Hover)) {
bool hit = false;
if (underMouse())
- hit = hitButton(e->pos());
+ hit = hitButton(e->position().toPoint());
if (hit != d->hovering) {
update(rect());
@@ -356,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 80cb22b82e..de623b7b9e 100644
--- a/src/widgets/widgets/qcheckbox.h
+++ b/src/widgets/widgets/qcheckbox.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCHECKBOX_H
#define QCHECKBOX_H
@@ -72,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;
@@ -81,7 +49,7 @@ protected:
void nextCheckState() override;
void paintEvent(QPaintEvent *) override;
void mouseMoveEvent(QMouseEvent *) override;
- void initStyleOption(QStyleOptionButton *option) const;
+ virtual void initStyleOption(QStyleOptionButton *option) const;
private:
diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp
index d786c7ff83..1fe9a8d7be 100644
--- a/src/widgets/widgets/qcombobox.cpp
+++ b/src/widgets/widgets/qcombobox.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 "qcombobox.h"
@@ -44,13 +8,11 @@
#include <qpa/qplatformmenu.h>
#include <qlineedit.h>
#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <private/qdesktopwidget_p.h>
#include <qlistview.h>
#if QT_CONFIG(tableview)
#include <qtableview.h>
#endif
-#include <qitemdelegate.h>
+#include <qabstractitemdelegate.h>
#include <qmap.h>
#if QT_CONFIG(menu)
#include <qmenu.h>
@@ -83,24 +45,30 @@
# include <private/qeffects_p.h>
#endif
#include <private/qstyle_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
+#include <array>
+
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
QComboBoxPrivate::QComboBoxPrivate()
: QWidgetPrivate(),
shownOnce(false),
- autoCompletion(true),
duplicatesEnabled(false),
frame(true),
- inserting(false)
+ inserting(false),
+ hidingPopup(false)
{
}
QComboBoxPrivate::~QComboBoxPrivate()
{
+ disconnectModel();
#ifdef Q_OS_MAC
cleanupNativePopup();
#endif
@@ -144,11 +112,11 @@ QStyleOptionMenuItem QComboMenuDelegate::getStyleOption(const QStyleOptionViewIt
menuOption.menuItemType = QStyleOptionMenuItem::Normal;
QVariant variant = index.model()->data(index, Qt::DecorationRole);
- switch (variant.type()) {
- case QVariant::Icon:
+ switch (variant.userType()) {
+ case QMetaType::QIcon:
menuOption.icon = qvariant_cast<QIcon>(variant);
break;
- case QVariant::Color: {
+ case QMetaType::QColor: {
static QPixmap pixmap(option.decorationSize);
pixmap.fill(qvariant_cast<QColor>(variant));
menuOption.icon = pixmap;
@@ -161,9 +129,8 @@ QStyleOptionMenuItem QComboMenuDelegate::getStyleOption(const QStyleOptionViewIt
menuOption.palette.setBrush(QPalette::All, QPalette::Window,
qvariant_cast<QBrush>(index.data(Qt::BackgroundRole)));
}
- menuOption.text = index.model()->data(index, Qt::DisplayRole).toString()
- .replace(QLatin1Char('&'), QLatin1String("&&"));
- menuOption.tabWidth = 0;
+ menuOption.text = index.model()->data(index, Qt::DisplayRole).toString().replace(u'&', "&&"_L1);
+ menuOption.reservedShortcutWidth = 0;
menuOption.maxIconWidth = option.decorationSize.width() + 4;
menuOption.menuRect = option.rect;
menuOption.rect = option.rect;
@@ -237,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)
@@ -263,15 +230,6 @@ void QComboBoxPrivate::_q_completerActivated(const QModelIndex &index)
}
}
#endif
-
-# ifdef QT_KEYPAD_NAVIGATION
- if ( QApplicationPrivate::keypadNavigationEnabled()
- && q->isEditable()
- && q->completer()
- && q->completer()->completionMode() == QCompleter::UnfilteredPopupCompletion ) {
- q->setEditFocus(false);
- }
-# endif // QT_KEYPAD_NAVIGATION
}
#endif // QT_CONFIG(completer)
@@ -286,29 +244,48 @@ void QComboBoxPrivate::updateArrow(QStyle::StateFlag state)
q->update(q->rect());
}
-void QComboBoxPrivate::_q_modelReset()
+void QComboBoxPrivate::modelReset()
{
Q_Q(QComboBox);
if (lineEdit) {
lineEdit->setText(QString());
updateLineEditGeometry();
}
- if (currentIndex.row() != indexBeforeChange)
- _q_emitCurrentIndexChanged(currentIndex);
+ trySetValidIndex();
modelChanged();
q->update();
}
-void QComboBoxPrivate::_q_modelDestroyed()
+void QComboBoxPrivate::modelDestroyed()
{
model = QAbstractItemModelPrivate::staticEmptyModel();
}
-QRect QComboBoxPrivate::popupGeometry(int screen) const
+void QComboBoxPrivate::trySetValidIndex()
+{
+ Q_Q(QComboBox);
+ bool currentReset = false;
+
+ const int rowCount = q->count();
+ for (int pos = 0; pos < rowCount; ++pos) {
+ const QModelIndex idx(model->index(pos, modelColumn, root));
+ if (idx.flags() & Qt::ItemIsEnabled) {
+ setCurrentIndex(idx);
+ currentReset = true;
+ break;
+ }
+ }
+
+ if (!currentReset)
+ setCurrentIndex(QModelIndex());
+}
+
+QRect QComboBoxPrivate::popupGeometry(const QPoint &globalPosition) const
{
+ Q_Q(const QComboBox);
return QStylePrivate::useFullScreenForPopup()
- ? QDesktopWidgetPrivate::screenGeometry(screen)
- : QDesktopWidgetPrivate::availableGeometry(screen);
+ ? QWidgetPrivate::screenGeometry(q, globalPosition)
+ : QWidgetPrivate::availableScreenGeometry(q, globalPosition);
}
bool QComboBoxPrivate::updateHoverControl(const QPoint &pos)
@@ -382,7 +359,7 @@ QSize QComboBoxPrivate::recomputeSizeHint(QSize &sh) const
case QComboBox::AdjustToContents:
case QComboBox::AdjustToContentsOnFirstShow:
if (count == 0) {
- sh.rwidth() = 7 * fm.horizontalAdvance(QLatin1Char('x'));
+ sh.rwidth() = 7 * fm.horizontalAdvance(u'x');
} else {
for (int i = 0; i < count; ++i) {
if (!q->itemIcon(i).isNull()) {
@@ -394,10 +371,7 @@ QSize QComboBoxPrivate::recomputeSizeHint(QSize &sh) const
}
}
break;
- case QComboBox::AdjustToMinimumContentsLength:
- for (int i = 0; i < count && !hasIcon; ++i)
- hasIcon = !q->itemIcon(i).isNull();
- default:
+ case QComboBox::AdjustToMinimumContentsLengthWithIcon:
;
}
} else {
@@ -405,7 +379,7 @@ QSize QComboBoxPrivate::recomputeSizeHint(QSize &sh) const
hasIcon = !q->itemIcon(i).isNull();
}
if (minimumContentsLength > 0)
- sh.setWidth(qMax(sh.width(), minimumContentsLength * fm.horizontalAdvance(QLatin1Char('X')) + (hasIcon ? iconSize.width() + 4 : 0)));
+ sh.setWidth(qMax(sh.width(), minimumContentsLength * fm.horizontalAdvance(u'X') + (hasIcon ? iconSize.width() + 4 : 0)));
if (!placeholderText.isEmpty())
sh.setWidth(qMax(sh.width(), fm.boundingRect(placeholderText).width()));
@@ -421,7 +395,7 @@ QSize QComboBoxPrivate::recomputeSizeHint(QSize &sh) const
q->initStyleOption(&opt);
sh = q->style()->sizeFromContents(QStyle::CT_ComboBox, &opt, sh, q);
}
- return sh.expandedTo(QApplication::globalStrut());
+ return sh;
}
void QComboBoxPrivate::adjustComboBoxSize()
@@ -518,21 +492,27 @@ QComboBoxPrivateContainer::QComboBoxPrivateContainer(QAbstractItemView *itemView
setLineWidth(1);
}
- setFrameStyle(combo->style()->styleHint(QStyle::SH_ComboBox_PopupFrameStyle, &opt, combo));
-
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.
layout->insertSpacing(0, 0);
layout->addSpacing(0);
- updateTopBottomMargin();
+ updateStyleSettings();
+}
+
+QComboBoxPrivateContainer::~QComboBoxPrivateContainer()
+{
+ disconnect(view, &QAbstractItemView::destroyed,
+ this, &QComboBoxPrivateContainer::viewDestroyed);
}
void QComboBoxPrivateContainer::scrollItemView(int action)
@@ -615,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;
@@ -652,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,14 +695,20 @@ void QComboBoxPrivateContainer::updateTopBottomMargin()
boxLayout->invalidate();
}
+void QComboBoxPrivateContainer::updateStyleSettings()
+{
+ // add scroller arrows if style needs them
+ QStyleOptionComboBox opt = comboStyleOption();
+ view->setMouseTracking(combo->style()->styleHint(QStyle::SH_ComboBox_ListMouseTracking, &opt, combo) ||
+ combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo));
+ setFrameStyle(combo->style()->styleHint(QStyle::SH_ComboBox_PopupFrameStyle, &opt, combo));
+ updateTopBottomMargin();
+}
+
void QComboBoxPrivateContainer::changeEvent(QEvent *e)
{
- if (e->type() == QEvent::StyleChange) {
- QStyleOptionComboBox opt = comboStyleOption();
- view->setMouseTracking(combo->style()->styleHint(QStyle::SH_ComboBox_ListMouseTracking, &opt, combo) ||
- combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo));
- setFrameStyle(combo->style()->styleHint(QStyle::SH_ComboBox_PopupFrameStyle, &opt, combo));
- }
+ if (e->type() == QEvent::StyleChange)
+ updateStyleSettings();
QFrame::changeEvent(e);
}
@@ -739,8 +725,9 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_Select:
#endif
- if (view->currentIndex().isValid() && (view->currentIndex().flags() & Qt::ItemIsEnabled) ) {
+ if (view->currentIndex().isValid() && view->currentIndex().flags().testFlag(Qt::ItemIsEnabled)) {
combo->hidePopup();
+ keyEvent->accept();
emit itemSelected(view->currentIndex());
}
return true;
@@ -750,11 +737,13 @@ 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)) {
- combo->hidePopup();
+ if (keyEvent->matches(QKeySequence::Cancel) && isVisible()) {
+ keyEvent->accept();
return true;
}
#endif
@@ -766,10 +755,10 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
if (isVisible()) {
QMouseEvent *m = static_cast<QMouseEvent *>(e);
QWidget *widget = static_cast<QWidget *>(o);
- QPoint vector = widget->mapToGlobal(m->pos()) - initialClickPosition;
+ QPoint vector = widget->mapToGlobal(m->position().toPoint()) - initialClickPosition;
if (vector.manhattanLength() > 9 && blockMouseReleaseTimer.isActive())
blockMouseReleaseTimer.stop();
- QModelIndex indexUnderMouse = view->indexAt(m->pos());
+ QModelIndex indexUnderMouse = view->indexAt(m->position().toPoint());
if (indexUnderMouse.isValid()
&& !QComboBoxDelegate::isSeparator(indexUnderMouse)) {
view->setCurrentIndex(indexUnderMouse);
@@ -783,10 +772,10 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
bool ignoreEvent = maybeIgnoreMouseButtonRelease && popupTimer.elapsed() < QApplication::doubleClickInterval();
QMouseEvent *m = static_cast<QMouseEvent *>(e);
- if (isVisible() && view->rect().contains(m->pos()) && view->currentIndex().isValid()
+ if (isVisible() && view->rect().contains(m->position().toPoint()) && view->currentIndex().isValid()
&& !blockMouseReleaseTimer.isActive() && !ignoreEvent
- && (view->currentIndex().flags() & Qt::ItemIsEnabled)
- && (view->currentIndex().flags() & Qt::ItemIsSelectable)) {
+ && (view->currentIndex().flags().testFlag(Qt::ItemIsEnabled))
+ && (view->currentIndex().flags().testFlag(Qt::ItemIsSelectable))) {
combo->hidePopup();
emit itemSelected(view->currentIndex());
return true;
@@ -824,7 +813,7 @@ void QComboBoxPrivateContainer::mousePressEvent(QMouseEvent *e)
opt.subControls = QStyle::SC_All;
opt.activeSubControls = QStyle::SC_ComboBoxArrow;
QStyle::SubControl sc = combo->style()->hitTestComplexControl(QStyle::CC_ComboBox, &opt,
- combo->mapFromGlobal(e->globalPos()),
+ combo->mapFromGlobal(e->globalPosition().toPoint()),
combo);
if ((combo->isEditable() && sc == QStyle::SC_ComboBoxArrow)
|| (!combo->isEditable() && sc != QStyle::SC_None))
@@ -835,7 +824,7 @@ void QComboBoxPrivateContainer::mousePressEvent(QMouseEvent *e)
void QComboBoxPrivateContainer::mouseReleaseEvent(QMouseEvent *e)
{
Q_UNUSED(e);
- if (!blockMouseReleaseTimer.isActive()){
+ if (!blockMouseReleaseTimer.isActive()) {
combo->hidePopup();
emit resetButton();
}
@@ -876,8 +865,8 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
\value AdjustToContents The combobox will always adjust to the contents
\value AdjustToContentsOnFirstShow The combobox will adjust to its contents the first time it is shown.
- \value AdjustToMinimumContentsLength Use AdjustToContents or AdjustToContentsOnFirstShow instead.
- \value AdjustToMinimumContentsLengthWithIcon The combobox will adjust to \l minimumContentsLength plus space for an icon. For performance reasons use this policy on large models.
+ \value AdjustToMinimumContentsLengthWithIcon The combobox will adjust to \l minimumContentsLength plus space for an icon.
+ For performance reasons use this policy on large models.
*/
/*!
@@ -886,28 +875,19 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
This signal is sent when the user chooses an item in the combobox.
The item's \a index is passed. Note that this signal is sent even
when the choice is not changed. If you need to know when the
- choice actually changes, use signal currentIndexChanged().
-
+ choice actually changes, use signal currentIndexChanged() or
+ currentTextChanged().
*/
/*!
- \fn void QComboBox::activated(const QString &text)
-
- This signal is sent when the user chooses an item in the combobox.
- The item's \a text is passed. Note that this signal is sent even
- when the choice is not changed. If you need to know when the
- choice actually changes, use signal currentIndexChanged().
-
- \obsolete Use QComboBox::textActivated() instead
-*/
-/*!
\fn void QComboBox::textActivated(const QString &text)
\since 5.14
This signal is sent when the user chooses an item in the combobox.
The item's \a text is passed. Note that this signal is sent even
when the choice is not changed. If you need to know when the
- choice actually changes, use signal currentIndexChanged().
+ choice actually changes, use signal currentIndexChanged() or
+ currentTextChanged().
*/
/*!
@@ -918,14 +898,6 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
*/
/*!
- \fn void QComboBox::highlighted(const QString &text)
-
- This signal is sent when an item in the combobox popup list is
- highlighted by the user. The item's \a text is passed.
-
- \obsolete Use textHighlighted() instead
-*/
-/*!
\fn void QComboBox::textHighlighted(const QString &text)
\since 5.14
@@ -944,20 +916,14 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
*/
/*!
- \fn void QComboBox::currentIndexChanged(const QString &text)
- \since 4.1
-
- This signal is sent whenever the currentIndex in the combobox
- changes either through user interaction or programmatically. The
- item's \a text is passed.
-*/
-
-/*!
\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.
*/
/*!
@@ -981,41 +947,36 @@ QComboBox::QComboBox(QComboBoxPrivate &dd, QWidget *parent)
d->init();
}
-
/*!
\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 two signals emitted if the current item of a combobox
- changes, currentIndexChanged() and activated().
- currentIndexChanged() is 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
@@ -1038,27 +999,42 @@ 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,
- {fowler}{GUI Design Handbook: Combo Box, Drop-Down List Box}
+ \sa QLineEdit, QSpinBox, QRadioButton, QButtonGroup
*/
void QComboBoxPrivate::init()
{
Q_Q(QComboBox);
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
// On OS X, only line edits and list views always get tab focus. It's only
// when we enable full keyboard access that other controls can get tab focus.
// When it's not editable, a combobox looks like a button, and it behaves as
@@ -1086,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)
@@ -1124,17 +1103,17 @@ void QComboBoxPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIn
lineEdit->setText(text);
updateLineEditGeometry();
} else {
- emit q->currentTextChanged(text);
+ updateCurrentText(text);
}
q->update();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(q, text);
QAccessible::updateAccessibility(&event);
#endif
}
}
-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)
@@ -1149,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)
@@ -1174,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()) {
@@ -1185,7 +1181,7 @@ void QComboBoxPrivate::_q_rowsRemoved(const QModelIndex &parent, int /*start*/,
updateLineEditGeometry();
}
q->update();
- _q_emitCurrentIndexChanged(currentIndex);
+ emitCurrentIndexChanged(currentIndex);
}
}
@@ -1215,7 +1211,7 @@ void QComboBoxPrivate::updateViewContainerPaletteAndOpacity()
void QComboBoxPrivate::updateFocusPolicy()
{
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
Q_Q(QComboBox);
// See comment in QComboBoxPrivate::init()
@@ -1252,8 +1248,12 @@ void QComboBox::initStyleOption(QStyleOptionComboBox *option) const
option->activeSubControls = d->hoverControl;
}
option->currentText = currentText();
- if (d->currentIndex.isValid())
+ if (d->currentIndex.isValid()) {
option->currentIcon = d->itemIcon(d->currentIndex);
+ QVariant alignment = d->model->data(d->currentIndex, Qt::TextAlignmentRole);
+ if (alignment.isValid())
+ option->textAlignment = static_cast<Qt::Alignment>(alignment.toUInt());
+ }
option->iconSize = iconSize();
if (d->container && d->container->isVisible())
option->state |= QStyle::State_On;
@@ -1290,7 +1290,7 @@ Qt::MatchFlags QComboBoxPrivate::matchFlags() const
}
-void QComboBoxPrivate::_q_editingFinished()
+void QComboBoxPrivate::editingFinished()
{
Q_Q(QComboBox);
if (!lineEdit)
@@ -1322,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;
@@ -1370,7 +1370,7 @@ void QComboBoxPrivate::_q_returnPressed()
break;
case QComboBox::InsertAlphabetically:
index = 0;
- for (int i=0; i< q->count(); i++, index++ ) {
+ for (int i = 0; i < q->count(); ++i, ++index) {
if (text.toLower() < q->itemText(i).toLower())
break;
}
@@ -1386,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) {
@@ -1406,15 +1406,9 @@ void QComboBoxPrivate::emitActivated(const QModelIndex &index)
QString text(itemText(index));
emit q->activated(index.row());
emit q->textActivated(text);
-#if QT_DEPRECATED_SINCE(5, 15)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit q->activated(text);
-QT_WARNING_POP
-#endif
}
-void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
+void QComboBoxPrivate::emitHighlighted(const QModelIndex &index)
{
Q_Q(QComboBox);
if (!index.isValid())
@@ -1422,29 +1416,17 @@ void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
QString text(itemText(index));
emit q->highlighted(index.row());
emit q->textHighlighted(text);
-#if QT_DEPRECATED_SINCE(5, 15)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit q->highlighted(text);
-QT_WARNING_POP
-#endif
}
-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());
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_WARNING_PUSH
- QT_WARNING_DISABLE_DEPRECATED
- emit q->currentIndexChanged(text);
- QT_WARNING_POP
-#endif
// signal lineEdit.textChanged already connected to signal currentTextChanged, so don't emit double here
if (!lineEdit)
- emit q->currentTextChanged(text);
-#ifndef QT_NO_ACCESSIBILITY
+ updateCurrentText(text);
+#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(q, text);
QAccessible::updateAccessibility(&event);
#endif
@@ -1469,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;
}
/*!
@@ -1504,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.
*/
@@ -1516,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
@@ -1547,108 +1531,9 @@ int QComboBox::maxCount() const
return d->maxCount;
}
-#if QT_CONFIG(completer)
-#if QT_DEPRECATED_SINCE(5, 13)
-
-/*!
- \property QComboBox::autoCompletion
- \brief whether the combobox provides auto-completion for editable items
- \since 4.1
- \obsolete
-
- Use setCompleter() instead.
-
- By default, this property is \c true.
-
- \sa editable
-*/
-
-/*!
- \obsolete
-
- Use completer() instead.
-*/
-bool QComboBox::autoCompletion() const
-{
- Q_D(const QComboBox);
- return d->autoCompletion;
-}
-
-/*!
- \obsolete
-
- Use setCompleter() instead.
-*/
-void QComboBox::setAutoCompletion(bool enable)
-{
- Q_D(QComboBox);
-
-#ifdef QT_KEYPAD_NAVIGATION
- if (Q_UNLIKELY(QApplicationPrivate::keypadNavigationEnabled() && !enable && isEditable()))
- qWarning("QComboBox::setAutoCompletion: auto completion is mandatory when combo box editable");
-#endif
-
- d->autoCompletion = enable;
- if (!d->lineEdit)
- return;
- if (enable) {
- if (d->lineEdit->completer())
- return;
- d->completer = new QCompleter(d->model, d->lineEdit);
- connect(d->completer, SIGNAL(activated(QModelIndex)), this, SLOT(_q_completerActivated(QModelIndex)));
- d->completer->setCaseSensitivity(d->autoCompletionCaseSensitivity);
- d->completer->setCompletionMode(QCompleter::InlineCompletion);
- d->completer->setCompletionColumn(d->modelColumn);
- d->lineEdit->setCompleter(d->completer);
- d->completer->setWidget(this);
- } else {
- d->lineEdit->setCompleter(nullptr);
- }
-}
-
-/*!
- \property QComboBox::autoCompletionCaseSensitivity
- \brief whether string comparisons are case-sensitive or case-insensitive for auto-completion
- \obsolete
-
- By default, this property is Qt::CaseInsensitive.
-
- Use setCompleter() instead. Case sensitivity of the auto completion can be
- changed using QCompleter::setCaseSensitivity().
-
- \sa autoCompletion
-*/
-
-/*!
- \obsolete
-
- Use setCompleter() and QCompleter::setCaseSensitivity() instead.
-*/
-Qt::CaseSensitivity QComboBox::autoCompletionCaseSensitivity() const
-{
- Q_D(const QComboBox);
- return d->autoCompletionCaseSensitivity;
-}
-
-/*!
- \obsolete
-
- Use setCompleter() and QCompleter::setCaseSensitivity() instead.
-*/
-void QComboBox::setAutoCompletionCaseSensitivity(Qt::CaseSensitivity sensitivity)
-{
- Q_D(QComboBox);
- d->autoCompletionCaseSensitivity = sensitivity;
- if (d->lineEdit && d->lineEdit->completer())
- d->lineEdit->completer()->setCaseSensitivity(sensitivity);
-}
-#endif // QT_DEPRECATED_SINCE(5, 13)
-
-#endif // QT_CONFIG(completer)
-
/*!
\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.
@@ -1694,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.
@@ -1717,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.
@@ -1768,8 +1653,7 @@ void QComboBox::setMinimumContentsLength(int characters)
d->minimumContentsLength = characters;
if (d->sizeAdjustPolicy == AdjustToContents
- || d->sizeAdjustPolicy == AdjustToMinimumContentsLength
- || d->sizeAdjustPolicy == AdjustToMinimumContentsLengthWithIcon) {
+ || d->sizeAdjustPolicy == AdjustToMinimumContentsLengthWithIcon) {
d->sizeHint = QSize();
d->adjustComboBoxSize();
updateGeometry();
@@ -1809,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
@@ -1831,7 +1715,7 @@ void QComboBox::setPlaceholderText(const QString &placeholderText)
d->placeholderText = placeholderText;
if (currentIndex() == -1) {
- if (d->placeholderText.isEmpty() && currentIndex() == -1)
+ if (d->placeholderText.isEmpty())
setCurrentIndex(0);
else
update();
@@ -1848,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.
@@ -1887,8 +1771,10 @@ 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.type() == QVariant::Pixmap)
+ if (decoration.userType() == QMetaType::QPixmap)
return QIcon(qvariant_cast<QPixmap>(decoration));
else
return qvariant_cast<QIcon>(decoration);
@@ -1908,6 +1794,7 @@ void QComboBox::setEditable(bool editable)
view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}
QLineEdit *le = new QLineEdit(this);
+ le->setPalette(palette());
setLineEdit(le);
} else {
if (style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, this)) {
@@ -1932,6 +1819,9 @@ void QComboBox::setEditable(bool editable)
Sets the line \a edit to use instead of the current line edit widget.
The combo box takes ownership of the line edit.
+
+ \note Since the combobox's line edit owns the QCompleter, any previous
+ call to setCompleter() will no longer have any effect.
*/
void QComboBox::setLineEdit(QLineEdit *edit)
{
@@ -1953,38 +1843,42 @@ 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();
d->lineEdit->setFocusProxy(this);
d->lineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
-#if QT_DEPRECATED_SINCE(5, 13)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
+
#if QT_CONFIG(completer)
- setAutoCompletion(d->autoCompletion);
+ // create a default completer
+ if (!d->lineEdit->completer()) {
+ QCompleter *completer = new QCompleter(d->model, d->lineEdit);
+ completer->setCaseSensitivity(Qt::CaseInsensitive);
+ completer->setCompletionMode(QCompleter::InlineCompletion);
+ completer->setCompletionColumn(d->modelColumn);
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplicationPrivate::keypadNavigationEnabled()) {
// Editable combo boxes will have a completer that is set to UnfilteredPopupCompletion.
// This means that when the user enters edit mode they are immediately presented with a
// list of possible completions.
- setAutoCompletion(true);
- if (d->completer) {
- d->completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
- connect(d->completer, SIGNAL(activated(QModelIndex)), this, SLOT(_q_completerActivated()));
- }
- }
-#endif
+ if (QApplicationPrivate::keypadNavigationEnabled())
+ completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
#endif
-QT_WARNING_POP
+ // sets up connections
+ setCompleter(completer);
+ }
#endif
setAttribute(Qt::WA_InputMethodEnabled);
@@ -2044,12 +1938,13 @@ const QValidator *QComboBox::validator() const
\since 4.2
Sets the \a completer to use instead of the current completer.
- If \a completer is 0, auto completion is disabled.
+ If \a completer is \nullptr, auto completion is disabled.
By default, for an editable combo box, a QCompleter that
performs case insensitive inline completion is automatically created.
- \note The completer is removed when the \l editable property becomes \c false.
+ \note The completer is removed when the \l editable property becomes \c false,
+ or when the line edit is replaced by a call to setLineEdit().
Setting a completer on a QComboBox that is not editable will be ignored.
*/
void QComboBox::setCompleter(QCompleter *c)
@@ -2061,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);
}
}
@@ -2096,6 +1992,9 @@ QAbstractItemDelegate *QComboBox::itemDelegate() const
Sets the item \a delegate for the popup list view.
The combobox takes ownership of the delegate.
+ Any existing delegate will be removed, but not deleted. QComboBox
+ does not take ownership of \a delegate.
+
\warning You should not share the same instance of a delegate between comboboxes,
widget mappers or views. Doing so can cause incorrect or unintuitive editing behavior
since each view connected to a given delegate may receive the
@@ -2110,7 +2009,6 @@ void QComboBox::setItemDelegate(QAbstractItemDelegate *delegate)
qWarning("QComboBox::setItemDelegate: cannot set a 0 delegate");
return;
}
- delete view()->itemDelegate();
view()->setItemDelegate(delegate);
}
@@ -2132,7 +2030,10 @@ QAbstractItemModel *QComboBox::model() const
Sets the model to be \a model. \a model must not be \nullptr.
If you want to clear the contents of a model, call clear().
- \sa clear()
+ \note If the combobox is editable, then the \a model will also be
+ set on the completer of the line edit.
+
+ \sa clear() setCompleter()
*/
void QComboBox::setModel(QAbstractItemModel *model)
{
@@ -2147,74 +2048,61 @@ void QComboBox::setModel(QAbstractItemModel *model)
return;
#if QT_CONFIG(completer)
- if (d->lineEdit && d->lineEdit->completer()
- && d->lineEdit->completer() == d->completer)
+ 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());
- bool currentReset = false;
+ d->trySetValidIndex();
+ d->modelChanged();
+}
- const int rowCount = count();
- for (int pos=0; pos < rowCount; pos++) {
- if (d->model->index(pos, d->modelColumn, d->root).flags() & Qt::ItemIsEnabled) {
- setCurrentIndex(pos);
- currentReset = true;
- break;
- }
- }
+void QComboBoxPrivate::connectModel()
+{
+ if (!model)
+ return;
- if (!currentReset)
- setCurrentIndex(-1);
+ 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)
+ };
+}
- d->modelChanged();
+void QComboBoxPrivate::disconnectModel()
+{
+ for (auto &connection : modelConnections)
+ QObject::disconnect(connection);
}
/*!
@@ -2262,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);
}
@@ -2299,9 +2187,24 @@ void QComboBoxPrivate::setCurrentIndex(const QModelIndex &mi)
}
updateLineEditGeometry();
}
- if (indexChanged) {
+ // 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 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);
}
}
@@ -2324,10 +2227,9 @@ QString QComboBox::currentText() const
Q_D(const QComboBox);
if (d->lineEdit)
return d->lineEdit->text();
- else if (d->currentIndex.isValid())
+ if (d->currentIndex.isValid())
return d->itemText(d->currentIndex);
- else
- return d->placeholderText;
+ return {};
}
/*!
@@ -2366,7 +2268,7 @@ QIcon QComboBox::itemIcon(int index) const
/*!
Returns the data for the given \a role in the given \a index in the
- combobox, or QVariant::Invalid if there is no data for this role.
+ combobox, or an invalid QVariant if there is no data for this role.
*/
QVariant QComboBox::itemData(int index, int role) const
{
@@ -2431,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;
@@ -2458,7 +2360,7 @@ void QComboBox::insertItems(int index, const QStringList &list)
if (list.isEmpty())
return;
index = qBound(0, index, count());
- int insertCount = qMin(d->maxCount - index, list.count());
+ int insertCount = qMin(d->maxCount - index, list.size());
if (insertCount <= 0)
return;
// For the common case where we are using the built in QStandardItemModel
@@ -2479,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;
}
@@ -2589,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);
}
@@ -2622,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;
}
/*!
@@ -2650,7 +2556,7 @@ bool QComboBoxPrivate::showNativePopup()
int itemsCount = q->count();
m_platformMenu->setTag(quintptr(itemsCount));
- QPlatformMenuItem *currentItem = 0;
+ QPlatformMenuItem *currentItem = nullptr;
int currentIndex = q->currentIndex();
for (int i = 0; i < itemsCount; ++i) {
@@ -2659,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);
@@ -2682,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_OSX
- // 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(), Qt::LeftButton,
- Qt::MouseButtons(Qt::LeftButton), Qt::KeyboardModifiers());
- QCoreApplication::sendEvent(q, &mouseReleased);
+#ifdef Q_OS_MACOS
+ 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;
@@ -2728,30 +2639,17 @@ void QComboBox::showPopup()
return;
#endif // Q_OS_MAC
-#ifdef QT_KEYPAD_NAVIGATION
-#if QT_CONFIG(completer)
- if (QApplicationPrivate::keypadNavigationEnabled() && d->completer) {
- // editable combo box is line edit plus completer
- setEditFocus(true);
- d->completer->complete(); // show popup
- return;
- }
-#endif
-#endif
-
- // set current item and select it
- view()->selectionModel()->setCurrentIndex(d->currentIndex,
- QItemSelectionModel::ClearAndSelect);
QComboBoxPrivateContainer* container = d->viewContainer();
QRect listRect(style->subControlRect(QStyle::CC_ComboBox, &opt,
QStyle::SC_ComboBoxListBoxPopup, this));
- QRect screen = d->popupGeometry(QDesktopWidgetPrivate::screenNumber(this));
+ QRect screen = d->popupGeometry(mapToGlobal(listRect.topLeft()));
QPoint below = mapToGlobal(listRect.bottomLeft());
int belowHeight = screen.bottom() - below.y();
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;
@@ -2766,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;
@@ -2838,8 +2738,14 @@ void QComboBox::showPopup()
// Position horizontally.
listRect.moveLeft(above.x());
- // Position vertically so the curently selected item lines up
- // with the combo box.
+ // Position vertically so the currently selected item lines up
+ // 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());
@@ -2872,13 +2778,15 @@ void QComboBox::showPopup()
QGuiApplication::inputMethod()->reset();
}
- QScrollBar *sb = view()->horizontalScrollBar();
- Qt::ScrollBarPolicy policy = view()->horizontalScrollBarPolicy();
- bool needHorizontalScrollBar = (policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn)
- && sb->minimum() < sb->maximum();
- if (needHorizontalScrollBar) {
+ const QScrollBar *sb = view()->horizontalScrollBar();
+ const auto needHorizontalScrollBar = [this, sb]{
+ const Qt::ScrollBarPolicy policy = view()->horizontalScrollBarPolicy();
+ return (policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn)
+ && sb->minimum() < sb->maximum();
+ };
+ const bool neededHorizontalScrollBar = needHorizontalScrollBar();
+ if (neededHorizontalScrollBar)
listRect.adjust(0, 0, 0, sb->height());
- }
// Hide the scrollers here, so that the listrect gets the full height of the container
// If the scrollers are truly needed, the later call to container->updateScrollers()
@@ -2921,6 +2829,11 @@ void QComboBox::showPopup()
}
}
container->show();
+ if (!neededHorizontalScrollBar && needHorizontalScrollBar()) {
+ listRect.adjust(0, 0, 0, sb->height());
+ container->setGeometry(listRect);
+ }
+
container->updateScrollers();
view()->setFocus();
@@ -2934,10 +2847,6 @@ void QComboBox::showPopup()
#endif
container->update();
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplicationPrivate::keypadNavigationEnabled())
- view()->setEditFocus(true);
-#endif
if (startTimer) {
container->popupTimer.start();
container->maybeIgnoreMouseButtonRelease = true;
@@ -2957,60 +2866,64 @@ void QComboBox::showPopup()
void QComboBox::hidePopup()
{
Q_D(QComboBox);
- if (d->container && d->container->isVisible()) {
+ if (d->hidingPopup)
+ return;
+ d->hidingPopup = true;
+ // can't use QBoolBlocker on a bitfield
+ auto resetHidingPopup = qScopeGuard([d]{
+ d->hidingPopup = false;
+ });
+
+ if (!d->container || !d->container->isVisible())
+ return;
+
#if QT_CONFIG(effects)
- QSignalBlocker modelBlocker(d->model);
- QSignalBlocker viewBlocker(d->container->itemView());
- QSignalBlocker containerBlocker(d->container);
- // Flash selected/triggered item (if any).
- if (style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem)) {
- QItemSelectionModel *selectionModel = view() ? view()->selectionModel() : nullptr;
- if (selectionModel && selectionModel->hasSelection()) {
- QEventLoop eventLoop;
- const QItemSelection selection = selectionModel->selection();
-
- // Deselect item and wait 60 ms.
+ 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);
selectionModel->select(selection, QItemSelectionModel::Toggle);
- QTimer::singleShot(60, &eventLoop, SLOT(quit()));
- eventLoop.exec();
+ QTimer::singleShot(20, d->container, [d] {
+ d->doHidePopup();
+ });
+ });
+ });
+ } else
+#endif // QT_CONFIG(effects)
+ {
+ d->doHidePopup();
+ }
+}
- // Select item and wait 20 ms.
- selectionModel->select(selection, QItemSelectionModel::Toggle);
- QTimer::singleShot(20, &eventLoop, SLOT(quit()));
- eventLoop.exec();
- }
- }
+void QComboBoxPrivate::doHidePopup()
+{
+ if (container && container->isVisible())
+ container->hide();
- // Fade out.
- bool needFade = style()->styleHint(QStyle::SH_Menu_FadeOutOnHide);
- bool didFade = false;
- if (needFade) {
-#if defined(Q_OS_MAC)
- QPlatformNativeInterface *platformNativeInterface = QGuiApplication::platformNativeInterface();
- int at = platformNativeInterface->metaObject()->indexOfMethod("fadeWindow()");
- if (at != -1) {
- QMetaMethod windowFade = platformNativeInterface->metaObject()->method(at);
- windowFade.invoke(platformNativeInterface, Q_ARG(QWindow *, d->container->windowHandle()));
- didFade = true;
- }
+ resetButton();
+}
-#endif // Q_OS_MAC
- // Other platform implementations welcome :-)
- }
- containerBlocker.unblock();
- viewBlocker.unblock();
- modelBlocker.unblock();
+void QComboBoxPrivate::updateCurrentText(const QString &text)
+{
+ if (text == currentText)
+ return;
- if (!didFade)
-#endif // QT_CONFIG(effects)
- // Fade should implicitly hide as well ;-)
- d->container->hide();
- }
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplicationPrivate::keypadNavigationEnabled() && isEditable() && hasFocus())
- setEditFocus(true);
-#endif
- d->_q_resetButton();
+ currentText = text;
+ emit q_func()->currentTextChanged(text);
}
/*!
@@ -3023,7 +2936,7 @@ void QComboBox::clear()
{
Q_D(QComboBox);
d->model->removeRows(0, d->model->rowCount(d->root), d->root);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(this, QString());
QAccessible::updateAccessibility(&event);
#endif
@@ -3037,7 +2950,7 @@ void QComboBox::clearEditText()
Q_D(QComboBox);
if (d->lineEdit)
d->lineEdit->clear();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(this, QString());
QAccessible::updateAccessibility(&event);
#endif
@@ -3051,7 +2964,7 @@ void QComboBox::setEditText(const QString &text)
Q_D(QComboBox);
if (d->lineEdit)
d->lineEdit->setText(text);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(this, text);
QAccessible::updateAccessibility(&event);
#endif
@@ -3090,7 +3003,10 @@ void QComboBox::changeEvent(QEvent *e)
Q_D(QComboBox);
switch (e->type()) {
case QEvent::StyleChange:
+ if (d->container)
+ d->container->updateStyleSettings();
d->updateDelegate();
+
#ifdef Q_OS_MAC
case QEvent::MacSizeChange:
#endif
@@ -3101,7 +3017,7 @@ void QComboBox::changeEvent(QEvent *e)
d->updateLineEditGeometry();
d->setLayoutItemMargins(QStyle::SE_ComboBoxLayoutItem);
- if (e->type() == QEvent::MacSizeChange){
+ if (e->type() == QEvent::MacSizeChange) {
QPlatformTheme::Font f = QPlatformTheme::SystemFont;
if (testAttribute(Qt::WA_MacSmallSize))
f = QPlatformTheme::SmallFont;
@@ -3123,12 +3039,14 @@ void QComboBox::changeEvent(QEvent *e)
d->updateViewContainerPaletteAndOpacity();
break;
}
- case QEvent::FontChange:
+ case QEvent::FontChange: {
d->sizeHint = QSize(); // invalidate size hint
d->viewContainer()->setFont(font());
+ d->viewContainer()->itemView()->doItemsLayout();
if (d->lineEdit)
d->updateLineEditGeometry();
break;
+ }
default:
break;
}
@@ -3157,8 +3075,10 @@ void QComboBox::paintEvent(QPaintEvent *)
initStyleOption(&opt);
painter.drawComplexControl(QStyle::CC_ComboBox, opt);
- if (currentIndex() < 0)
- opt.palette.setBrush(QPalette::ButtonText, opt.palette.brush(QPalette::ButtonText).color().lighter());
+ if (currentIndex() < 0 && !placeholderText().isEmpty()) {
+ opt.palette.setBrush(QPalette::ButtonText, opt.palette.placeholderText());
+ opt.currentText = placeholderText();
+ }
// draw the icon and text
painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
@@ -3202,7 +3122,7 @@ bool QComboBox::event(QEvent *event)
case QEvent::HoverLeave:
case QEvent::HoverMove:
if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d->updateHoverControl(he->pos());
+ d->updateHoverControl(he->position().toPoint());
break;
case QEvent::ShortcutOverride:
if (d->lineEdit)
@@ -3210,9 +3130,7 @@ bool QComboBox::event(QEvent *event)
break;
#ifdef QT_KEYPAD_NAVIGATION
case QEvent::EnterEditFocus:
- if (!d->lineEdit)
- setEditFocus(false); // We never want edit focus if we are not editable
- else
+ if (d->lineEdit)
d->lineEdit->event(event); //so cursor starts
break;
case QEvent::LeaveEditFocus:
@@ -3241,7 +3159,7 @@ void QComboBoxPrivate::showPopupFromMouseEvent(QMouseEvent *e)
Q_Q(QComboBox);
QStyleOptionComboBox opt;
q->initStyleOption(&opt);
- QStyle::SubControl sc = q->style()->hitTestComplexControl(QStyle::CC_ComboBox, &opt, e->pos(), q);
+ QStyle::SubControl sc = q->style()->hitTestComplexControl(QStyle::CC_ComboBox, &opt, e->position().toPoint(), q);
if (e->button() == Qt::LeftButton
&& !(sc == QStyle::SC_None && e->type() == QEvent::MouseButtonRelease)
@@ -3252,14 +3170,17 @@ void QComboBoxPrivate::showPopupFromMouseEvent(QMouseEvent *e)
#ifdef QT_KEYPAD_NAVIGATION
//if the container already exists, then d->viewContainer() is safe to call
if (container) {
+#else
+ if (true) {
#endif
// We've restricted the next couple of lines, because by not calling
// viewContainer(), we avoid creating the QComboBoxPrivateContainer.
- viewContainer()->initialClickPosition = q->mapToGlobal(e->pos());
-#ifdef QT_KEYPAD_NAVIGATION
+ viewContainer()->initialClickPosition = q->mapToGlobal(e->position().toPoint());
}
-#endif
+ 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.
@@ -3311,7 +3232,23 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
Move move = NoMove;
int newIndex = currentIndex();
- switch (e->key()) {
+
+ bool pressLikeButton = !d->lineEdit;
+#ifdef QT_KEYPAD_NAVIGATION
+ pressLikeButton |= QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus();
+#endif
+ auto key = e->key();
+ if (pressLikeButton) {
+ const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()
+ ->themeHint(QPlatformTheme::ButtonPressKeys)
+ .value<QList<Qt::Key>>();
+ if (buttonPressKeys.contains(key)) {
+ showPopup();
+ return;
+ }
+ }
+
+ switch (key) {
case Qt::Key_Up:
if (e->modifiers() & Qt::ControlModifier)
break; // pass to line edit for auto completion
@@ -3353,12 +3290,6 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
return;
}
break;
- case Qt::Key_Space:
- if (!d->lineEdit) {
- showPopup();
- return;
- }
- break;
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Escape:
@@ -3366,13 +3297,6 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
e->ignore();
break;
#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
- if (QApplicationPrivate::keypadNavigationEnabled()
- && (!hasEditFocus() || !d->lineEdit)) {
- showPopup();
- return;
- }
- break;
case Qt::Key_Left:
case Qt::Key_Right:
if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus())
@@ -3383,14 +3307,22 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
if (!hasEditFocus() || !d->lineEdit)
e->ignore();
} else {
- e->ignore(); // let the surounding dialog have it
+ e->ignore(); // let the surrounding dialog have it
}
break;
#endif
default:
+#if QT_CONFIG(shortcut)
+ if (d->container && d->container->isVisible() && e->matches(QKeySequence::Cancel)) {
+ hidePopup();
+ e->accept();
+ }
+#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();
}
@@ -3588,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
@@ -3618,6 +3550,9 @@ void QComboBox::setFrame(bool enable)
default value).
By default, this property has a value of 0.
+
+ \note In an editable combobox, the visible column will also become
+ the \l{QCompleter::completionColumn}{completion column}.
*/
int QComboBox::modelColumn() const
{
@@ -3633,8 +3568,7 @@ void QComboBox::setModelColumn(int visibleColumn)
if (lv)
lv->setModelColumn(visibleColumn);
#if QT_CONFIG(completer)
- if (d->lineEdit && d->lineEdit->completer()
- && d->lineEdit->completer() == d->completer)
+ if (d->lineEdit && d->lineEdit->completer())
d->lineEdit->completer()->setCompletionColumn(visibleColumn);
#endif
setCurrentIndex(currentIndex()); //update the text to the text of the new column;
diff --git a/src/widgets/widgets/qcombobox.h b/src/widgets/widgets/qcombobox.h
index 1b80f90c74..1689d0fa1e 100644
--- a/src/widgets/widgets/qcombobox.h
+++ b/src/widgets/widgets/qcombobox.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QCOMBOBOX_H
#define QCOMBOBOX_H
@@ -62,7 +26,8 @@ class Q_WIDGETS_EXPORT QComboBox : public QWidget
Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
Q_PROPERTY(int count READ count)
- Q_PROPERTY(QString currentText READ currentText WRITE setCurrentText NOTIFY currentTextChanged USER true)
+ Q_PROPERTY(QString currentText READ currentText WRITE setCurrentText NOTIFY currentTextChanged
+ USER true)
Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
Q_PROPERTY(QVariant currentData READ currentData)
Q_PROPERTY(int maxVisibleItems READ maxVisibleItems WRITE setMaxVisibleItems)
@@ -72,14 +37,6 @@ class Q_WIDGETS_EXPORT QComboBox : public QWidget
Q_PROPERTY(int minimumContentsLength READ minimumContentsLength WRITE setMinimumContentsLength)
Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
Q_PROPERTY(QString placeholderText READ placeholderText WRITE setPlaceholderText)
-
-#if QT_CONFIG(completer)
-#if QT_DEPRECATED_SINCE(5, 13)
- Q_PROPERTY(bool autoCompletion READ autoCompletion WRITE setAutoCompletion DESIGNABLE false)
- Q_PROPERTY(Qt::CaseSensitivity autoCompletionCaseSensitivity READ autoCompletionCaseSensitivity WRITE setAutoCompletionCaseSensitivity DESIGNABLE false)
-#endif
-#endif // QT_CONFIG(completer)
-
Q_PROPERTY(bool duplicatesEnabled READ duplicatesEnabled WRITE setDuplicatesEnabled)
Q_PROPERTY(bool frame READ hasFrame WRITE setFrame)
Q_PROPERTY(int modelColumn READ modelColumn WRITE setModelColumn)
@@ -95,19 +52,6 @@ public:
void setMaxCount(int max);
int maxCount() const;
-#if QT_CONFIG(completer)
-#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X("Use completer() instead.")
- bool autoCompletion() const;
- QT_DEPRECATED_X("Use setCompleter() instead.")
- void setAutoCompletion(bool enable);
- QT_DEPRECATED_X("Use completer()->caseSensitivity() instead.")
- Qt::CaseSensitivity autoCompletionCaseSensitivity() const;
- QT_DEPRECATED_X("Use completer()->setCaseSensitivity() instead.")
- void setAutoCompletionCaseSensitivity(Qt::CaseSensitivity sensitivity);
-#endif
-#endif
-
bool duplicatesEnabled() const;
void setDuplicatesEnabled(bool enable);
@@ -137,7 +81,6 @@ public:
enum SizeAdjustPolicy {
AdjustToContents,
AdjustToContentsOnFirstShow,
- AdjustToMinimumContentsLength, // ### Qt 6: remove
AdjustToMinimumContentsLengthWithIcon
};
Q_ENUM(SizeAdjustPolicy)
@@ -231,14 +174,7 @@ Q_SIGNALS:
void highlighted(int index);
void textHighlighted(const QString &);
void currentIndexChanged(int index);
- void currentIndexChanged(const QString &);
void currentTextChanged(const QString &);
-#if QT_DEPRECATED_SINCE(5, 15)
- QT_DEPRECATED_VERSION_X(5, 15, "Use textActivated() instead")
- void activated(const QString &);
- QT_DEPRECATED_VERSION_X(5, 15, "Use textHighlighted() instead")
- void highlighted(const QString &);
-#endif
protected:
void focusInEvent(QFocusEvent *e) override;
@@ -259,7 +195,7 @@ protected:
void contextMenuEvent(QContextMenuEvent *e) override;
#endif // QT_NO_CONTEXTMENU
void inputMethodEvent(QInputMethodEvent *) override;
- void initStyleOption(QStyleOptionComboBox *option) const;
+ virtual void initStyleOption(QStyleOptionComboBox *option) const;
protected:
@@ -268,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 7a3fcf6e0f..723d637ae2 100644
--- a/src/widgets/widgets/qcombobox_p.h
+++ b/src/widgets/widgets/qcombobox_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOMBOBOX_P_H
#define QCOMBOBOX_P_H
@@ -56,14 +20,13 @@
#include "QtWidgets/qabstractslider.h"
#include "QtWidgets/qapplication.h"
-#include "QtWidgets/qitemdelegate.h"
+#include "QtWidgets/qstyleditemdelegate.h"
#include "QtGui/qstandarditemmodel.h"
#include "QtWidgets/qlineedit.h"
#include "QtWidgets/qlistview.h"
#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"
@@ -85,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
@@ -94,13 +61,12 @@ protected:
QListView::resizeEvent(event);
}
- QStyleOptionViewItem viewOptions() const override
+ void initViewItemOption(QStyleOptionViewItem *option) const override
{
- QStyleOptionViewItem option = QListView::viewOptions();
- option.showDecorationSelected = true;
+ QListView::initViewItemOption(option);
+ option->showDecorationSelected = true;
if (combo)
- option.font = combo->font();
- return option;
+ option->font = combo->font();
}
void paintEvent(QPaintEvent *e) override
@@ -118,7 +84,7 @@ protected:
menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
menuOpt.menuRect = e->rect();
menuOpt.maxIconWidth = 0;
- menuOpt.tabWidth = 0;
+ menuOpt.reservedShortcutWidth = 0;
QPainter p(viewport());
combo->style()->drawControl(QStyle::CE_MenuEmptyArea, &menuOpt, &p, this);
}
@@ -142,7 +108,7 @@ public:
setAttribute(Qt::WA_NoMousePropagation);
}
QSize sizeHint() const override {
- return QSize(20, style()->pixelMetric(QStyle::PM_MenuScrollerHeight));
+ return QSize(20, style()->pixelMetric(QStyle::PM_MenuScrollerHeight, nullptr, this));
}
protected:
@@ -155,7 +121,7 @@ protected:
fast = false;
}
- void enterEvent(QEvent *) override {
+ void enterEvent(QEnterEvent *) override {
startTimer();
}
@@ -178,8 +144,8 @@ protected:
void mouseMoveEvent(QMouseEvent *e) override
{
// Enable fast scrolling if the cursor is directly above or below the popup.
- const int mouseX = e->pos().x();
- const int mouseY = e->pos().y();
+ const int mouseX = e->position().toPoint().x();
+ const int mouseY = e->position().toPoint().y();
const bool horizontallyInside = pos().x() < mouseX && mouseX < rect().right() + 1;
const bool verticallyOutside = (sliderAction == QAbstractSlider::SliderSingleStepAdd) ?
rect().bottom() + 1 < mouseY : mouseY < pos().y();
@@ -190,11 +156,11 @@ protected:
void paintEvent(QPaintEvent *) override {
QPainter p(this);
QStyleOptionMenuItem menuOpt;
- menuOpt.init(this);
+ menuOpt.initFrom(this);
menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
menuOpt.menuRect = rect();
menuOpt.maxIconWidth = 0;
- menuOpt.tabWidth = 0;
+ menuOpt.reservedShortcutWidth = 0;
menuOpt.menuItemType = QStyleOptionMenuItem::Scroller;
if (sliderAction == QAbstractSlider::SliderSingleStepAdd)
menuOpt.state |= QStyle::State_DownArrow;
@@ -217,12 +183,14 @@ class Q_WIDGETS_EXPORT QComboBoxPrivateContainer : public QFrame
public:
QComboBoxPrivateContainer(QAbstractItemView *itemView, QComboBox *parent);
+ ~QComboBoxPrivateContainer();
QAbstractItemView *itemView() const;
void setItemView(QAbstractItemView *itemView);
int spacing() const;
int topMargin() const;
int bottomMargin() const { return topMargin(); }
void updateTopBottomMargin();
+ void updateStyleSettings();
QTimer blockMouseReleaseTimer;
QBasicTimer adjustSizeTimer;
@@ -294,17 +262,17 @@ private:
int pressedIndex;
};
-// ### Qt6: QStyledItemDelegate ?
-// Note that this class is intentionally not using QStyledItemDelegate
-// Vista does not use the new theme for combo boxes and there might
-// be other side effects from using the new class
-class Q_AUTOTEST_EXPORT QComboBoxDelegate : public QItemDelegate
-{ Q_OBJECT
+class Q_AUTOTEST_EXPORT QComboBoxDelegate : public QStyledItemDelegate
+{
+ Q_OBJECT
public:
- QComboBoxDelegate(QObject *parent, QComboBox *cmb) : QItemDelegate(parent), mCombo(cmb) {}
+ QComboBoxDelegate(QObject *parent, QComboBox *cmb)
+ : QStyledItemDelegate(parent), mCombo(cmb)
+ {}
static bool isSeparator(const QModelIndex &index) {
- return index.data(Qt::AccessibleDescriptionRole).toString() == QLatin1String("separator");
+ return index.data(Qt::AccessibleDescriptionRole).toString()
+ == QLatin1StringView("separator");
}
static void setSeparator(QAbstractItemModel *model, const QModelIndex &index) {
model->setData(index, QString::fromLatin1("separator"), Qt::AccessibleDescriptionRole);
@@ -325,7 +293,7 @@ protected:
opt.rect = rect;
mCombo->style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &opt, painter, mCombo);
} else {
- QItemDelegate::paint(painter, option, index);
+ QStyledItemDelegate::paint(painter, option, index);
}
}
@@ -335,7 +303,7 @@ protected:
int pm = mCombo->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, nullptr, mCombo);
return QSize(pm, pm);
}
- return QItemDelegate::sizeHint(option, index);
+ return QStyledItemDelegate::sizeHint(option, index);
}
private:
QComboBox *mCombo;
@@ -351,27 +319,29 @@ 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);
- QRect popupGeometry(int screen = -1) const;
+ void trySetValidIndex();
+ QRect popupGeometry(const QPoint &globalPos) const;
QStyle::SubControl newHoverControl(const QPoint &pos);
int computeWidthHint() const;
QSize recomputeSizeHint(QSize &sh) const;
@@ -387,6 +357,10 @@ public:
void updateViewContainerPaletteAndOpacity();
void updateFocusPolicy();
void showPopupFromMouseEvent(QMouseEvent *e);
+ void doHidePopup();
+ void updateCurrentText(const QString &text);
+ void connectModel();
+ void disconnectModel();
#ifdef Q_OS_MAC
void cleanupNativePopup();
@@ -403,18 +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
-#if QT_CONFIG(completer)
- QPointer<QCompleter> completer;
-#endif
QPersistentModelIndex currentIndex;
QPersistentModelIndex root;
QString placeholderText;
+ QString currentText;
QRect hoverRect;
QSize iconSize;
mutable QSize minimumSizeHint;
@@ -423,18 +396,17 @@ public:
QComboBox::SizeAdjustPolicy sizeAdjustPolicy = QComboBox::AdjustToContentsOnFirstShow;
QStyle::StateFlag arrowState = QStyle::State_None;
QStyle::SubControl hoverControl = QStyle::SC_None;
- Qt::CaseSensitivity autoCompletionCaseSensitivity = Qt::CaseInsensitive;
int minimumContentsLength = 0;
int indexBeforeChange = -1;
int maxVisibleItems = 10;
- int maxCount = std::numeric_limits<int>::max();
+ int maxCount = (std::numeric_limits<int>::max)();
int modelColumn = 0;
int placeholderIndex = -1;
bool shownOnce : 1;
- bool autoCompletion : 1;
bool duplicatesEnabled : 1;
bool frame : 1;
bool inserting : 1;
+ bool hidingPopup : 1;
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qcommandlinkbutton.cpp b/src/widgets/widgets/qcommandlinkbutton.cpp
index 2b9258fd91..5c7d2601d9 100644
--- a/src/widgets/widgets/qcommandlinkbutton.cpp
+++ b/src/widgets/widgets/qcommandlinkbutton.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qcommandlinkbutton.h"
#include "qstylepainter.h"
@@ -207,8 +171,8 @@ bool QCommandLinkButtonPrivate::usingVistaStyle() const
Q_Q(const QCommandLinkButton);
//### 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->style()->inherits("QWindowsVistaStyle")
- && !q->style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal);
+ return q->property("_qt_usingVistaStyle").toBool()
+ && q->style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, nullptr, q) == 0;
}
void QCommandLinkButtonPrivate::init()
@@ -216,6 +180,7 @@ void QCommandLinkButtonPrivate::init()
Q_Q(QCommandLinkButton);
QPushButtonPrivate::init();
q->setAttribute(Qt::WA_Hover);
+ q->setAttribute(Qt::WA_MacShowFocusRect, false);
QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Preferred, QSizePolicy::PushButton);
policy.setHeightForWidth(true);
@@ -224,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
@@ -264,6 +229,12 @@ QSize QCommandLinkButton::minimumSizeHint() const
return size;
}
+void QCommandLinkButton::initStyleOption(QStyleOptionButton *option) const
+{
+ QPushButton::initStyleOption(option);
+ option->features |= QStyleOptionButton::CommandLinkButton;
+}
+
/*!
Constructs a command link with no text and a \a parent.
*/
@@ -349,14 +320,14 @@ void QCommandLinkButton::paintEvent(QPaintEvent *)
QStyleOptionButton option;
initStyleOption(&option);
- //Enable command link appearance on Vista
- option.features |= QStyleOptionButton::CommandLinkButton;
option.text = QString();
option.icon = QIcon(); //we draw this ourselves
QSize pixmapSize = icon().actualSize(iconSize());
- int vOffset = isDown() ? style()->pixelMetric(QStyle::PM_ButtonShiftVertical) : 0;
- int hOffset = isDown() ? style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal) : 0;
+ const int vOffset = isDown()
+ ? style()->pixelMetric(QStyle::PM_ButtonShiftVertical, &option, this) : 0;
+ const int hOffset = isDown()
+ ? style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, &option, this) : 0;
//Draw icon
p.drawControl(QStyle::CE_PushButton, option);
@@ -368,9 +339,9 @@ void QCommandLinkButton::paintEvent(QPaintEvent *)
//Draw title
QColor textColor = palette().buttonText().color();
if (isEnabled() && d->usingVistaStyle()) {
- textColor = QColor(21, 28, 85);
+ textColor = option.palette.buttonText().color();
if (underMouse() && !isDown())
- textColor = QColor(7, 64, 229);
+ textColor = option.palette.brightText().color();
//A simple text color transition
d->currentColor = d->mergedColors(textColor, d->currentColor, 60);
option.palette.setColor(QPalette::ButtonText, d->currentColor);
diff --git a/src/widgets/widgets/qcommandlinkbutton.h b/src/widgets/widgets/qcommandlinkbutton.h
index 3d2dd5784d..7979b992f4 100644
--- a/src/widgets/widgets/qcommandlinkbutton.h
+++ b/src/widgets/widgets/qcommandlinkbutton.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QCOMMANDLINKBUTTON_H
#define QCOMMANDLINKBUTTON_H
@@ -66,15 +30,11 @@ public:
QString description() const;
void setDescription(const QString &description);
- // QTBUG-68722
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
-protected:
-#else
-public:
-#endif
QSize sizeHint() const override;
int heightForWidth(int) const override;
QSize minimumSizeHint() const override;
+ void initStyleOption(QStyleOptionButton *option) const override;
+
protected:
bool event(QEvent *e) override;
void paintEvent(QPaintEvent *) override;
diff --git a/src/widgets/widgets/qdatetimeedit.cpp b/src/widgets/widgets/qdatetimeedit.cpp
index e4abb89636..01e52b2fa6 100644
--- a/src/widgets/widgets/qdatetimeedit.cpp
+++ b/src/widgets/widgets/qdatetimeedit.cpp
@@ -1,49 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 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 <private/qapplication_p.h>
#include <private/qdatetimeedit_p.h>
#include <qabstractspinbox.h>
#include <qapplication.h>
#include <qdatetimeedit.h>
-#include <qdesktopwidget.h>
-#include <private/qdesktopwidget_p.h>
#include <qdebug.h>
#include <qevent.h>
#include <qlineedit.h>
@@ -53,9 +15,7 @@
#include <qlayout.h>
#include <qset.h>
#include <qstyle.h>
-#if QT_CONFIG(timezone)
-#include <QTimeZone>
-#endif
+#include <qstylepainter.h>
#include <algorithm>
@@ -70,6 +30,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
// --- QDateTimeEdit ---
/*!
@@ -106,6 +68,23 @@ QT_BEGIN_NAMESPACE
calendar pop-up by calling the setCalendarWidget() function. The existing
calendar widget can be retrieved with calendarWidget().
+ \section1 Keyboard Tracking
+
+ When \l{QAbstractSpinBox::keyboardTracking}{keyboard tracking} is enabled
+ (the default), every keystroke of editing a field triggers signals for value
+ changes.
+
+ When the allowed \l{QDateTimeEdit::setDateTimeRange}{range} is narrower than
+ some time interval whose end it straddles, keyboard tracking prevents the
+ user editing the date or time to access the later part of the interval. For
+ example, for a range from 29.04.2020 to 02.05.2020 and an initial date of
+ 30.04.2020, the user can change neither the month (May 30th is outside the
+ range) nor the day (April 2nd is outside the range).
+
+ When keyboard tracking is disabled, changes are only signalled when focus
+ leaves the text field after edits have modified the content. This allows the
+ user to edit via an invalid date-time to reach a valid one.
+
\sa QDateEdit, QTimeEdit, QDate, QTime
*/
@@ -130,20 +109,26 @@ QT_BEGIN_NAMESPACE
This signal is emitted whenever the date or time is changed. The
new date and time is passed in \a datetime.
+
+ \sa {Keyboard Tracking}
*/
/*!
- \fn void QDateTimeEdit::timeChanged(const QTime &time)
+ \fn void QDateTimeEdit::timeChanged(QTime time)
This signal is emitted whenever the time is changed. The new time
is passed in \a time.
+
+ \sa {Keyboard Tracking}
*/
/*!
- \fn void QDateTimeEdit::dateChanged(const QDate &date)
+ \fn void QDateTimeEdit::dateChanged(QDate date)
This signal is emitted whenever the date is changed. The new date
is passed in \a date.
+
+ \sa {Keyboard Tracking}
*/
@@ -171,13 +156,13 @@ QDateTimeEdit::QDateTimeEdit(const QDateTime &datetime, QWidget *parent)
}
/*!
- \fn QDateTimeEdit::QDateTimeEdit(const QDate &date, QWidget *parent)
+ \fn QDateTimeEdit::QDateTimeEdit(QDate date, QWidget *parent)
Constructs an empty date time editor with a \a parent.
The value is set to \a date.
*/
-QDateTimeEdit::QDateTimeEdit(const QDate &date, QWidget *parent)
+QDateTimeEdit::QDateTimeEdit(QDate date, QWidget *parent)
: QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
{
Q_D(QDateTimeEdit);
@@ -185,13 +170,13 @@ QDateTimeEdit::QDateTimeEdit(const QDate &date, QWidget *parent)
}
/*!
- \fn QDateTimeEdit::QDateTimeEdit(const QTime &time, QWidget *parent)
+ \fn QDateTimeEdit::QDateTimeEdit(QTime time, QWidget *parent)
Constructs an empty date time editor with a \a parent.
The value is set to \a time.
*/
-QDateTimeEdit::QDateTimeEdit(const QTime &time, QWidget *parent)
+QDateTimeEdit::QDateTimeEdit(QTime time, QWidget *parent)
: QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
{
Q_D(QDateTimeEdit);
@@ -201,9 +186,10 @@ QDateTimeEdit::QDateTimeEdit(const QTime &time, QWidget *parent)
/*!
\internal
*/
-
-QDateTimeEdit::QDateTimeEdit(const QVariant &var, QVariant::Type parserType, QWidget *parent)
- : QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
+QDateTimeEdit::QDateTimeEdit(const QVariant &var, QMetaType::Type parserType, QWidget *parent)
+ : QAbstractSpinBox(*new QDateTimeEditPrivate(parserType == QMetaType::QDateTime
+ ? QTimeZone::LocalTime : QTimeZone::UTC),
+ parent)
{
Q_D(QDateTimeEdit);
d->parserType = parserType;
@@ -221,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
@@ -233,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
@@ -246,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();
@@ -275,7 +261,7 @@ QDate QDateTimeEdit::date() const
return d->value.toDate();
}
-void QDateTimeEdit::setDate(const QDate &date)
+void QDateTimeEdit::setDate(QDate date)
{
Q_D(QDateTimeEdit);
if (date.isValid()) {
@@ -283,14 +269,10 @@ void QDateTimeEdit::setDate(const 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();
}
}
@@ -312,12 +294,12 @@ QTime QDateTimeEdit::time() const
return d->value.toTime();
}
-void QDateTimeEdit::setTime(const QTime &time)
+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);
}
}
@@ -348,14 +330,15 @@ void QDateTimeEdit::setCalendar(QCalendar calendar)
minimumTime properties to the date and time parts of this property,
respectively. When setting this property, the \l maximumDateTime is adjusted,
if necessary, to ensure that the range remains valid. Otherwise, changing this
- property preserves the \l minimumDateTime property.
+ property preserves the \l maximumDateTime property.
This property can only be set to a valid QDateTime value. The earliest
date-time that setMinimumDateTime() accepts is the start of 100 CE. The
property's default is the start of September 14, 1752 CE. This default can be
restored with clearMinimumDateTime().
- \sa maximumDateTime, minimumTime, minimumDate, setDateTimeRange(), QDateTime::isValid()
+ \sa maximumDateTime, minimumTime, minimumDate, setDateTimeRange(),
+ QDateTime::isValid(), {Keyboard Tracking}
*/
QDateTime QDateTimeEdit::minimumDateTime() const
@@ -373,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));
}
@@ -396,7 +379,8 @@ void QDateTimeEdit::setMinimumDateTime(const QDateTime &dt)
default for this property. This default can be restored with
clearMaximumDateTime().
- \sa minimumDateTime, maximumTime, maximumDate(), setDateTimeRange(), QDateTime::isValid()
+ \sa minimumDateTime, maximumTime, maximumDate(), setDateTimeRange(),
+ QDateTime::isValid(), {Keyboard Tracking}
*/
QDateTime QDateTimeEdit::maximumDateTime() const
@@ -414,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);
}
@@ -436,15 +420,20 @@ void QDateTimeEdit::setMaximumDateTime(const QDateTime &dt)
If either \a min or \a max is invalid, this function does nothing. If \a max
is less than \a min, \a min is used also as \a max.
- \sa minimumDateTime, maximumDateTime, setDateRange(), setTimeRange(), QDateTime::isValid()
+ If the range is narrower then a time interval whose end it spans, for example
+ a week that spans the end of a month, users can only edit the date-time to one
+ in the later part of the range if keyboard-tracking is disabled.
+
+ \sa minimumDateTime, maximumDateTime, setDateRange(), setTimeRange(),
+ QDateTime::isValid(), {Keyboard Tracking}
*/
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);
}
@@ -466,7 +455,8 @@ void QDateTimeEdit::setDateTimeRange(const QDateTime &min, const QDateTime &max)
default for this property is September 14, 1752 CE. This default can be
restored with clearMinimumDateTime().
- \sa maximumDate, minimumTime, minimumDateTime, setDateRange(), QDate::isValid()
+ \sa maximumDate, minimumTime, minimumDateTime, setDateRange(),
+ QDate::isValid(), {Keyboard Tracking}
*/
QDate QDateTimeEdit::minimumDate() const
@@ -475,12 +465,11 @@ QDate QDateTimeEdit::minimumDate() const
return d->minimum.toDate();
}
-void QDateTimeEdit::setMinimumDate(const QDate &min)
+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()
@@ -506,7 +495,8 @@ void QDateTimeEdit::clearMinimumDate()
default for this property. This default can be restored with
clearMaximumDateTime().
- \sa minimumDate, maximumTime, maximumDateTime, setDateRange(), QDate::isValid()
+ \sa minimumDate, maximumTime, maximumDateTime, setDateRange(),
+ QDate::isValid(), {Keyboard Tracking}
*/
QDate QDateTimeEdit::maximumDate() const
@@ -515,11 +505,11 @@ QDate QDateTimeEdit::maximumDate() const
return d->maximum.toDate();
}
-void QDateTimeEdit::setMaximumDate(const QDate &max)
+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()
@@ -543,7 +533,8 @@ void QDateTimeEdit::clearMaximumDate()
contains a time of 00:00:00 and 0 milliseconds. This default can be restored
with clearMinimumTime().
- \sa maximumTime, minimumDate, minimumDateTime, setTimeRange(), QTime::isValid()
+ \sa maximumTime, minimumDate, minimumDateTime, setTimeRange(),
+ QTime::isValid(), {Keyboard Tracking}
*/
QTime QDateTimeEdit::minimumTime() const
@@ -552,13 +543,11 @@ QTime QDateTimeEdit::minimumTime() const
return d->minimum.toTime();
}
-void QDateTimeEdit::setMinimumTime(const QTime &min)
+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()
@@ -582,7 +571,8 @@ void QDateTimeEdit::clearMinimumTime()
contains a time of 23:59:59 and 999 milliseconds. This default can be restored
with clearMaximumTime().
- \sa minimumTime, maximumDate, maximumDateTime, setTimeRange(), QTime::isValid()
+ \sa minimumTime, maximumDate, maximumDateTime, setTimeRange(),
+ QTime::isValid(), {Keyboard Tracking}
*/
QTime QDateTimeEdit::maximumTime() const
{
@@ -590,13 +580,11 @@ QTime QDateTimeEdit::maximumTime() const
return d->maximum.toTime();
}
-void QDateTimeEdit::setMaximumTime(const QTime &max)
+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()
@@ -623,15 +611,19 @@ void QDateTimeEdit::clearMaximumTime()
minimumTime property, the \l maximumTime property is set to the \l minimumTime
property. Otherwise, this preserves the \l maximumTime property.
- \sa minimumDate, maximumDate, setDateTimeRange(), QDate::isValid()
+ If the range is narrower then a time interval whose end it spans, for example
+ a week that spans the end of a month, users can only edit the date to one in
+ the later part of the range if keyboard-tracking is disabled.
+
+ \sa minimumDate, maximumDate, setDateTimeRange(), QDate::isValid(), {Keyboard Tracking}
*/
-void QDateTimeEdit::setDateRange(const QDate &min, const QDate &max)
+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()));
}
}
@@ -657,15 +649,20 @@ void QDateTimeEdit::setDateRange(const QDate &min, const QDate &max)
function preserves the \l minimumDate and \l maximumDate properties. If those
properties coincide and \a max is less than \a min, \a min is used as \a max.
- \sa minimumTime, maximumTime, setDateTimeRange(), QTime::isValid()
+ If the range is narrower then a time interval whose end it spans, for example
+ the interval from ten to an hour to ten past the same hour, users can only
+ edit the time to one in the later part of the range if keyboard-tracking is
+ disabled.
+
+ \sa minimumTime, maximumTime, setDateTimeRange(), QTime::isValid(), {Keyboard Tracking}
*/
-void QDateTimeEdit::setTimeRange(const QTime &min, const QTime &max)
+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));
}
}
@@ -675,7 +672,8 @@ void QDateTimeEdit::setTimeRange(const QTime &min, const QTime &max)
\brief The currently displayed fields of the date time edit.
Returns a bit set of the displayed sections for this format.
- \a setDisplayFormat(), displayFormat()
+
+ \sa setDisplayFormat(), displayFormat()
*/
QDateTimeEdit::Sections QDateTimeEdit::displayedSections() const
@@ -688,7 +686,6 @@ QDateTimeEdit::Sections QDateTimeEdit::displayedSections() const
\property QDateTimeEdit::currentSection
\brief The current section of the spinbox.
- \a setCurrentSection()
*/
QDateTimeEdit::Section QDateTimeEdit::currentSection() const
@@ -768,8 +765,7 @@ int QDateTimeEdit::sectionCount() const
the cursorPosition is 5, currentSectionIndex returns 1. If the
cursorPosition is 3, currentSectionIndex is 0, and so on.
- \a setCurrentSection()
- \sa currentSection()
+ \sa setCurrentSection(), currentSection()
*/
int QDateTimeEdit::currentSectionIndex() const
@@ -949,10 +945,10 @@ void QDateTimeEdit::setDisplayFormat(const QString &format)
}
} else if (dateShown && !timeShown) {
setTimeRange(QDATETIMEEDIT_TIME_MIN, QDATETIMEEDIT_TIME_MAX);
- d->value = QDateTime(d->value.toDate(), QTime(), d->spec);
+ d->value = d->value.toDate().startOfDay(d->timeZone);
}
d->updateEdit();
- d->_q_editorCursorPositionChanged(-1, 0);
+ d->editorCursorPositionChanged(-1, 0);
}
}
@@ -988,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();
}
}
@@ -1023,9 +1065,9 @@ QSize QDateTimeEdit::sizeHint() const
int h = d->edit->sizeHint().height();
int w = 0;
QString s;
- s = d->textFromValue(d->minimum) + QLatin1Char(' ');
+ s = d->textFromValue(d->minimum) + u' ';
w = qMax<int>(w, fm.horizontalAdvance(s));
- s = d->textFromValue(d->maximum) + QLatin1Char(' ');
+ s = d->textFromValue(d->maximum) + u' ';
w = qMax<int>(w, fm.horizontalAdvance(s));
if (d->specialValueText.size()) {
s = d->specialValueText;
@@ -1044,8 +1086,7 @@ QSize QDateTimeEdit::sizeHint() const
{
QStyleOptionSpinBox opt;
initStyleOption(&opt);
- d->cachedSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
- .expandedTo(QApplication::globalStrut());
+ d->cachedSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this);
}
d->cachedMinimumSizeHint = d->cachedSizeHint;
@@ -1257,9 +1298,9 @@ void QDateTimeEdit::focusInEvent(QFocusEvent *event)
{
Q_D(QDateTimeEdit);
QAbstractSpinBox::focusInEvent(event);
- QString *frm = nullptr;
const int oldPos = d->edit->cursorPosition();
if (!d->formatExplicitlySet) {
+ QString *frm = nullptr;
if (d->displayFormat == d->defaultTimeFormat) {
frm = &d->defaultTimeFormat;
} else if (d->displayFormat == d->defaultDateFormat) {
@@ -1290,6 +1331,7 @@ void QDateTimeEdit::focusInEvent(QFocusEvent *event)
case Qt::ActiveWindowFocusReason:
if (oldHasHadFocus)
return;
+ break;
case Qt::ShortcutFocusReason:
case Qt::TabFocusReason:
default:
@@ -1382,7 +1424,7 @@ void QDateTimeEdit::stepBy(int steps)
d->updateCache(d->value, d->displayText());
d->setSelected(d->currentSectionIndex);
- d->updateTimeSpec();
+ d->updateTimeZone();
}
/*!
@@ -1440,7 +1482,12 @@ void QDateTimeEdit::fixup(QString &input) const
QValidator::State state;
int copy = d->edit->cursorPosition();
- d->validateAndInterpret(input, copy, state, true);
+ QDateTime value = d->validateAndInterpret(input, copy, state, true);
+ // 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);
}
@@ -1464,7 +1511,7 @@ QDateTimeEdit::StepEnabled QDateTimeEdit::stepEnabled() const
if (d->wrapping)
return StepEnabled(StepUpEnabled | StepDownEnabled);
// 3 cases. date, time, datetime. each case look
- // at just the relavant component.
+ // at just the relevant component.
QVariant max, min, val;
if (!(d->sections & DateSections_Mask)) {
// time only, no date
@@ -1522,7 +1569,7 @@ void QDateTimeEdit::mousePressEvent(QMouseEvent *event)
QAbstractSpinBox::mousePressEvent(event);
return;
}
- d->updateHoverControl(event->pos());
+ d->updateHoverControl(event->position().toPoint());
if (d->hoverControl == QStyle::SC_ComboBoxArrow) {
event->accept();
if (d->readOnly) {
@@ -1570,7 +1617,7 @@ void QDateTimeEdit::mousePressEvent(QMouseEvent *event)
QTimeEdit::QTimeEdit(QWidget *parent)
- : QDateTimeEdit(QDATETIMEEDIT_TIME_MIN, QVariant::Time, parent)
+ : QDateTimeEdit(QDATETIMEEDIT_TIME_MIN, QMetaType::QTime, parent)
{
connect(this, &QTimeEdit::timeChanged, this, &QTimeEdit::userTimeChanged);
}
@@ -1580,8 +1627,8 @@ QTimeEdit::QTimeEdit(QWidget *parent)
to \a time.
*/
-QTimeEdit::QTimeEdit(const QTime &time, QWidget *parent)
- : QDateTimeEdit(time, QVariant::Time, parent)
+QTimeEdit::QTimeEdit(QTime time, QWidget *parent)
+ : QDateTimeEdit(time.isValid() ? time : QDATETIMEEDIT_TIME_MIN, QMetaType::QTime, parent)
{
connect(this, &QTimeEdit::timeChanged, this, &QTimeEdit::userTimeChanged);
}
@@ -1600,7 +1647,7 @@ QTimeEdit::~QTimeEdit()
*/
/*!
- \fn void QTimeEdit::userTimeChanged(const QTime &time)
+ \fn void QTimeEdit::userTimeChanged(QTime time)
This signal only exists to fully implement the time Q_PROPERTY on the class.
Normally timeChanged should be used instead.
@@ -1640,7 +1687,7 @@ QTimeEdit::~QTimeEdit()
*/
QDateEdit::QDateEdit(QWidget *parent)
- : QDateTimeEdit(QDATETIMEEDIT_DATE_INITIAL, QVariant::Date, parent)
+ : QDateTimeEdit(QDATETIMEEDIT_DATE_INITIAL, QMetaType::QDate, parent)
{
connect(this, &QDateEdit::dateChanged, this, &QDateEdit::userDateChanged);
}
@@ -1650,8 +1697,8 @@ QDateEdit::QDateEdit(QWidget *parent)
to \a date.
*/
-QDateEdit::QDateEdit(const QDate &date, QWidget *parent)
- : QDateTimeEdit(date, QVariant::Date, parent)
+QDateEdit::QDateEdit(QDate date, QWidget *parent)
+ : QDateTimeEdit(date.isValid() ? date : QDATETIMEEDIT_DATE_INITIAL, QMetaType::QDate, parent)
{
connect(this, &QDateEdit::dateChanged, this, &QDateEdit::userDateChanged);
}
@@ -1670,7 +1717,7 @@ QDateEdit::~QDateEdit()
*/
/*!
- \fn void QDateEdit::userDateChanged(const QDate &date)
+ \fn void QDateEdit::userDateChanged(QDate date)
This signal only exists to fully implement the date Q_PROPERTY on the class.
Normally dateChanged should be used instead.
@@ -1687,62 +1734,42 @@ QDateEdit::~QDateEdit()
*/
-QDateTimeEditPrivate::QDateTimeEditPrivate()
- : QDateTimeParser(QVariant::DateTime, QDateTimeParser::DateTimeEdit, QCalendar())
+QDateTimeEditPrivate::QDateTimeEditPrivate(const QTimeZone &zone)
+ : QDateTimeParser(QMetaType::QDateTime, QDateTimeParser::DateTimeEdit, QCalendar()),
+ timeZone(zone)
{
- hasHadFocus = false;
- formatExplicitlySet = false;
- cacheGuard = false;
fixday = true;
- type = QVariant::DateTime;
- sections = { };
- cachedDay = -1;
+ type = QMetaType::QDateTime;
currentSectionIndex = FirstSectionIndex;
first.pos = 0;
- calendarPopup = false;
- minimum = QDATETIMEEDIT_COMPAT_DATE_MIN.startOfDay();
- maximum = QDATETIMEEDIT_DATE_MAX.endOfDay();
- arrowState = QStyle::State_None;
- monthCalendar = nullptr;
+ minimum = QDATETIMEEDIT_COMPAT_DATE_MIN.startOfDay(timeZone);
+ maximum = QDATETIMEEDIT_DATE_MAX.endOfDay(timeZone);
readLocaleSettings();
+}
-#ifdef QT_KEYPAD_NAVIGATION
- focusOnButton = false;
-#endif
+QDateTime QDateTimeEditPrivate::convertTimeZone(const QDateTime &datetime)
+{
+ return datetime.toTimeZone(timeZone);
}
-QDateTime QDateTimeEditPrivate::convertTimeSpec(const QDateTime &datetime)
+QDateTime QDateTimeEditPrivate::dateTimeValue(QDate date, QTime time) const
{
- 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());
-#if QT_CONFIG(timezone)
- case Qt::TimeZone:
- return datetime.toTimeZone(value.toDateTime().timeZone());
-#endif
- }
- Q_UNREACHABLE();
+ return QDateTime(date, time, timeZone);
}
-// FIXME: architecturaly incompatible with OffsetFromUTC or TimeZone as spec (QTBUG-80417).
-void QDateTimeEditPrivate::updateTimeSpec()
+void QDateTimeEditPrivate::updateTimeZone()
{
- minimum = minimum.toDateTime().toTimeSpec(spec);
- maximum = maximum.toDateTime().toTimeSpec(spec);
- value = value.toDateTime().toTimeSpec(spec);
+ 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);
}
}
}
@@ -1777,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
@@ -1822,7 +1870,7 @@ int QDateTimeEditPrivate::sectionAt(int pos) const
const int textSize = text.size();
if (textSize - pos < separators.last().size() + 1) {
if (separators.last().size() == 0) {
- return sectionNodes.count() - 1;
+ return sectionNodes.size() - 1;
}
return (pos == textSize ? LastSectionIndex : NoSectionIndex);
}
@@ -1852,7 +1900,7 @@ int QDateTimeEditPrivate::closestSection(int pos, bool forward) const
const QString text = displayText();
if (text.size() - pos < separators.last().size() + 1)
- return forward ? LastSectionIndex : sectionNodes.size() - 1;
+ return forward ? LastSectionIndex : int(sectionNodes.size() - 1);
updateCache(value, text);
for (int i=0; i<sectionNodes.size(); ++i) {
@@ -1884,7 +1932,7 @@ int QDateTimeEditPrivate::nextPrevSection(int current, bool forward) const
switch (current) {
case FirstSectionIndex: return forward ? 0 : FirstSectionIndex;
- case LastSectionIndex: return (forward ? LastSectionIndex : sectionNodes.size() - 1);
+ case LastSectionIndex: return (forward ? LastSectionIndex : int(sectionNodes.size() - 1));
case NoSectionIndex: return FirstSectionIndex;
default: break;
}
@@ -1908,7 +1956,7 @@ int QDateTimeEditPrivate::nextPrevSection(int current, bool forward) const
void QDateTimeEditPrivate::clearSection(int index)
{
- const QLatin1Char space(' ');
+ const auto space = u' ';
int cursorPos = edit->cursorPosition();
const QSignalBlocker blocker(edit);
QString t = edit->text();
@@ -1985,8 +2033,18 @@ QDateTime QDateTimeEditPrivate::validateAndInterpret(QString &input, int &positi
return minimum.toDateTime();
}
}
+
StateNode tmp = parse(input, position, value.toDateTime(), fixup);
- input = tmp.input;
+ // Take note of any corrections imposed during parsing:
+ input = m_text;
+ // 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;
+
position += tmp.padded;
state = QValidator::State(int(tmp.state));
if (state == QValidator::Acceptable) {
@@ -2028,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);
}
@@ -2050,40 +2108,73 @@ QDateTime QDateTimeEditPrivate::stepBy(int sectionIndex, int steps, bool test) c
int pos = edit->cursorPosition();
const SectionNode sn = sectionNode(sectionIndex);
- int val;
// to make sure it behaves reasonably when typing something and then stepping in non-tracking mode
- if (!test && pendingEmit) {
- if (q->validate(str, pos) != QValidator::Acceptable) {
- v = value.toDateTime();
- } else {
- v = q->dateTimeFromText(str);
- }
- val = getDigit(v, sectionIndex);
- } else {
- val = getDigit(v, sectionIndex);
- }
-
- val += steps;
+ if (!test && pendingEmit && q->validate(str, pos) == QValidator::Acceptable)
+ v = q->dateTimeFromText(str);
+ int val = getDigit(v, sectionIndex);
const int min = absoluteMin(sectionIndex);
const int max = absoluteMax(sectionIndex, value.toDateTime());
- if (val < min) {
- val = (wrapping ? max - (min - val) + 1 : min);
- } else if (val > max) {
- val = (wrapping ? min + val - max - 1 : max);
+ if (sn.type & DayOfWeekSectionMask) {
+ // Must take locale's first day of week into account when *not*
+ // wrapping; min and max don't help us.
+#ifndef QT_ALWAYS_WRAP_WEEKDAY // (documentation, not an actual define)
+ if (!wrapping) {
+ /* It's not clear this is ever really a desirable behavior.
+
+ It refuses to step backwards from the first day of the week or
+ forwards from the day before, only allowing day-of-week stepping
+ from start to end of one week. That's strictly what non-wrapping
+ behavior must surely mean, when put in locale-neutral terms.
+
+ It is, however, likely that users would prefer the "more natural"
+ behavior of cycling through the week.
+ */
+ const int first = int(locale().firstDayOfWeek()); // Mon = 1 through 7 = Sun
+ val = qBound(val < first ? first - 7 : first,
+ val + steps,
+ val < first ? first - 1 : first + 6);
+ } else
+#endif
+ {
+ val += steps;
+ }
+
+ // Restore to range from 1 through 7:
+ val = val % 7;
+ if (val <= 0)
+ val += 7;
+ } else {
+ val += steps;
+ const int span = max - min + 1;
+ if (val < min)
+ val = wrapping ? val + span : min;
+ else if (val > max)
+ val = wrapping ? val - span : max;
}
const int oldDay = v.date().day(calendar);
- setDigit(v, sectionIndex, val);
+ /*
+ Stepping into a daylight saving time that doesn't exist (setDigit() is
+ 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) && 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
+ 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.
const QDateTime minimumDateTime = minimum.toDateTime();
const QDateTime maximumDateTime = maximum.toDateTime();
// changing one section should only modify that section, if possible
- if (sn.type != AmPmSection && (v < minimumDateTime || v > maximumDateTime)) {
+ if (sn.type != AmPmSection && !(sn.type & DayOfWeekSectionMask)
+ && (v < minimumDateTime || v > maximumDateTime)) {
const int localmin = getDigit(minimumDateTime, sectionIndex);
const int localmax = getDigit(maximumDateTime, sectionIndex);
@@ -2170,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);
}
/*!
@@ -2207,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;
@@ -2265,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())));
@@ -2348,7 +2438,7 @@ void QDateTimeEdit::paintEvent(QPaintEvent *event)
QStyleOptionComboBox optCombo;
- optCombo.init(this);
+ optCombo.initFrom(this);
optCombo.editable = true;
optCombo.frame = opt.frame;
optCombo.subControls = opt.subControls;
@@ -2358,8 +2448,8 @@ void QDateTimeEdit::paintEvent(QPaintEvent *event)
optCombo.state &= ~QStyle::State_Enabled;
}
- QPainter p(this);
- style()->drawComplexControl(QStyle::CC_ComboBox, &optCombo, &p, this);
+ QStylePainter p(this);
+ p.drawComplexControl(QStyle::CC_ComboBox, optCombo);
}
int QDateTimeEditPrivate::absoluteIndex(QDateTimeEdit::Section s, int index) const
@@ -2389,7 +2479,7 @@ void QDateTimeEditPrivate::interpret(EmitPolicy ep)
|| currentSectionIndex < 0
|| !(fieldInfo(currentSectionIndex) & AllowPartial))) {
setValue(value, ep);
- updateTimeSpec();
+ updateTimeZone();
} else {
QAbstractSpinBoxPrivate::interpret(ep);
}
@@ -2428,27 +2518,27 @@ void QDateTimeEdit::initStyleOption(QStyleOptionSpinBox *option) const
void QDateTimeEditPrivate::init(const QVariant &var)
{
Q_Q(QDateTimeEdit);
- switch (var.type()) {
- case QVariant::Date:
- value = var.toDate().startOfDay();
- updateTimeSpec();
+ switch (var.userType()) {
+ case QMetaType::QDate:
+ value = var.toDate().startOfDay(timeZone);
+ updateTimeZone();
q->setDisplayFormat(defaultDateFormat);
if (sectionNodes.isEmpty()) // ### safeguard for broken locale
- q->setDisplayFormat(QLatin1String("dd/MM/yyyy"));
+ q->setDisplayFormat("dd/MM/yyyy"_L1);
break;
- case QVariant::DateTime:
+ case QMetaType::QDateTime:
value = var;
- updateTimeSpec();
+ updateTimeZone();
q->setDisplayFormat(defaultDateTimeFormat);
if (sectionNodes.isEmpty()) // ### safeguard for broken locale
- q->setDisplayFormat(QLatin1String("dd/MM/yyyy hh:mm:ss"));
+ q->setDisplayFormat("dd/MM/yyyy hh:mm:ss"_L1);
break;
- case QVariant::Time:
- value = QDateTime(QDATETIMEEDIT_DATE_INITIAL, var.toTime());
- updateTimeSpec();
+ case QMetaType::QTime:
+ value = dateTimeValue(QDATETIMEEDIT_DATE_INITIAL, var.toTime());
+ updateTimeZone();
q->setDisplayFormat(defaultTimeFormat);
if (sectionNodes.isEmpty()) // ### safeguard for broken locale
- q->setDisplayFormat(QLatin1String("hh:mm:ss"));
+ q->setDisplayFormat("hh:mm:ss"_L1);
break;
default:
Q_ASSERT_X(0, "QDateTimeEditPrivate::init", "Internal error");
@@ -2496,7 +2586,7 @@ QStyle::SubControl QDateTimeEditPrivate::newHoverControl(const QPoint &pos)
Q_Q(QDateTimeEdit);
QStyleOptionComboBox optCombo;
- optCombo.init(q);
+ optCombo.initFrom(q);
optCombo.editable = true;
optCombo.subControls = QStyle::SC_All;
hoverControl = q->style()->hitTestComplexControl(QStyle::CC_ComboBox, &optCombo, pos, q);
@@ -2513,7 +2603,7 @@ void QDateTimeEditPrivate::updateEditFieldGeometry()
Q_Q(QDateTimeEdit);
QStyleOptionComboBox optCombo;
- optCombo.init(q);
+ optCombo.initFrom(q);
optCombo.editable = true;
optCombo.subControls = QStyle::SC_ComboBoxEditField;
edit->setGeometry(q->style()->subControlRect(QStyle::CC_ComboBox, &optCombo,
@@ -2522,8 +2612,8 @@ void QDateTimeEditPrivate::updateEditFieldGeometry()
QVariant QDateTimeEditPrivate::getZeroVariant() const
{
- Q_ASSERT(type == QVariant::DateTime);
- return QDateTime(QDATETIMEEDIT_DATE_INITIAL, QTime(), spec);
+ Q_ASSERT(type == QMetaType::QDateTime);
+ return QDATETIMEEDIT_DATE_INITIAL.startOfDay(timeZone);
}
void QDateTimeEditPrivate::setRange(const QVariant &min, const QVariant &max)
@@ -2552,7 +2642,7 @@ void QDateTimeEditPrivate::initCalendarPopup(QCalendarWidget *cw)
Q_Q(QDateTimeEdit);
if (!monthCalendar) {
monthCalendar = new QCalendarPopup(q, cw, calendar);
- monthCalendar->setObjectName(QLatin1String("qt_datetimedit_calendar"));
+ monthCalendar->setObjectName("qt_datetimedit_calendar"_L1);
QObject::connect(monthCalendar, SIGNAL(newDateSelected(QDate)), q, SLOT(setDate(QDate)));
QObject::connect(monthCalendar, SIGNAL(hidingCalendar(QDate)), q, SLOT(setDate(QDate)));
QObject::connect(monthCalendar, SIGNAL(activated(QDate)), q, SLOT(setDate(QDate)));
@@ -2572,28 +2662,31 @@ void QDateTimeEditPrivate::positionCalendarPopup()
pos = q->mapToGlobal(pos);
pos2 = q->mapToGlobal(pos2);
QSize size = monthCalendar->sizeHint();
- QRect screen = QDesktopWidgetPrivate::availableGeometry(pos);
+ QScreen *screen = QGuiApplication::screenAt(pos);
+ if (!screen)
+ screen = QGuiApplication::primaryScreen();
+ const QRect screenRect = screen->availableGeometry();
//handle popup falling "off screen"
if (q->layoutDirection() == Qt::RightToLeft) {
pos.setX(pos.x()-size.width());
pos2.setX(pos2.x()-size.width());
- if (pos.x() < screen.left())
- pos.setX(qMax(pos.x(), screen.left()));
- else if (pos.x()+size.width() > screen.right())
- pos.setX(qMax(pos.x()-size.width(), screen.right()-size.width()));
+ if (pos.x() < screenRect.left())
+ pos.setX(qMax(pos.x(), screenRect.left()));
+ else if (pos.x()+size.width() > screenRect.right())
+ pos.setX(qMax(pos.x()-size.width(), screenRect.right()-size.width()));
} else {
- if (pos.x()+size.width() > screen.right())
- pos.setX(screen.right()-size.width());
- pos.setX(qMax(pos.x(), screen.left()));
+ if (pos.x()+size.width() > screenRect.right())
+ pos.setX(screenRect.right()-size.width());
+ pos.setX(qMax(pos.x(), screenRect.left()));
}
- if (pos.y() + size.height() > screen.bottom())
+ if (pos.y() + size.height() > screenRect.bottom())
pos.setY(pos2.y() - size.height());
- else if (pos.y() < screen.top())
- pos.setY(screen.top());
- if (pos.y() < screen.top())
- pos.setY(screen.top());
- if (pos.y()+size.height() > screen.bottom())
- pos.setY(screen.bottom()-size.height());
+ else if (pos.y() < screenRect.top())
+ pos.setY(screenRect.top());
+ if (pos.y() < screenRect.top())
+ pos.setY(screenRect.top());
+ if (pos.y()+size.height() > screenRect.bottom())
+ pos.setY(screenRect.bottom()-size.height());
monthCalendar->move(pos);
}
@@ -2681,11 +2774,11 @@ void QCalendarPopup::mousePressEvent(QMouseEvent *event)
QDateTimeEdit *dateTime = qobject_cast<QDateTimeEdit *>(parentWidget());
if (dateTime) {
QStyleOptionComboBox opt;
- opt.init(dateTime);
+ opt.initFrom(dateTime);
QRect arrowRect = dateTime->style()->subControlRect(QStyle::CC_ComboBox, &opt,
QStyle::SC_ComboBoxArrow, dateTime);
arrowRect.moveTo(dateTime->mapToGlobal(arrowRect .topLeft()));
- if (arrowRect.contains(event->globalPos()) || rect().contains(event->pos()))
+ if (arrowRect.contains(event->globalPosition().toPoint()) || rect().contains(event->position().toPoint()))
setAttribute(Qt::WA_NoMouseReplay);
}
QWidget::mousePressEvent(event);
diff --git a/src/widgets/widgets/qdatetimeedit.h b/src/widgets/widgets/qdatetimeedit.h
index 03994675ae..f7c0dd7374 100644
--- a/src/widgets/widgets/qdatetimeedit.h
+++ b/src/widgets/widgets/qdatetimeedit.h
@@ -1,47 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QDATETIMEEDIT_H
#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>
@@ -61,8 +25,10 @@ class Q_WIDGETS_EXPORT QDateTimeEdit : public QAbstractSpinBox
Q_PROPERTY(QDateTime dateTime READ dateTime WRITE setDateTime NOTIFY dateTimeChanged USER true)
Q_PROPERTY(QDate date READ date WRITE setDate NOTIFY dateChanged)
Q_PROPERTY(QTime time READ time WRITE setTime NOTIFY timeChanged)
- Q_PROPERTY(QDateTime maximumDateTime READ maximumDateTime WRITE setMaximumDateTime RESET clearMaximumDateTime)
- Q_PROPERTY(QDateTime minimumDateTime READ minimumDateTime WRITE setMinimumDateTime RESET clearMinimumDateTime)
+ Q_PROPERTY(QDateTime maximumDateTime READ maximumDateTime WRITE setMaximumDateTime
+ RESET clearMaximumDateTime)
+ Q_PROPERTY(QDateTime minimumDateTime READ minimumDateTime WRITE setMinimumDateTime
+ RESET clearMinimumDateTime)
Q_PROPERTY(QDate maximumDate READ maximumDate WRITE setMaximumDate RESET clearMaximumDate)
Q_PROPERTY(QDate minimumDate READ minimumDate WRITE setMinimumDate RESET clearMinimumDate)
Q_PROPERTY(QTime maximumTime READ maximumTime WRITE setMaximumTime RESET clearMaximumTime)
@@ -73,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,
@@ -95,8 +64,8 @@ public:
explicit QDateTimeEdit(QWidget *parent = nullptr);
explicit QDateTimeEdit(const QDateTime &dt, QWidget *parent = nullptr);
- explicit QDateTimeEdit(const QDate &d, QWidget *parent = nullptr);
- explicit QDateTimeEdit(const QTime &t, QWidget *parent = nullptr);
+ explicit QDateTimeEdit(QDate d, QWidget *parent = nullptr);
+ explicit QDateTimeEdit(QTime t, QWidget *parent = nullptr);
~QDateTimeEdit();
QDateTime dateTime() const;
@@ -117,24 +86,24 @@ public:
void setDateTimeRange(const QDateTime &min, const QDateTime &max);
QDate minimumDate() const;
- void setMinimumDate(const QDate &min);
+ void setMinimumDate(QDate min);
void clearMinimumDate();
QDate maximumDate() const;
- void setMaximumDate(const QDate &max);
+ void setMaximumDate(QDate max);
void clearMaximumDate();
- void setDateRange(const QDate &min, const QDate &max);
+ void setDateRange(QDate min, QDate max);
QTime minimumTime() const;
- void setMinimumTime(const QTime &min);
+ void setMinimumTime(QTime min);
void clearMinimumTime();
QTime maximumTime() const;
- void setMaximumTime(const QTime &max);
+ void setMaximumTime(QTime max);
void clearMaximumTime();
- void setTimeRange(const QTime &min, const QTime &max);
+ void setTimeRange(QTime min, QTime max);
Sections displayedSections() const;
Section currentSection() const;
@@ -159,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;
@@ -170,13 +145,13 @@ public:
bool event(QEvent *event) override;
Q_SIGNALS:
void dateTimeChanged(const QDateTime &dateTime);
- void timeChanged(const QTime &time);
- void dateChanged(const QDate &date);
+ void timeChanged(QTime time);
+ void dateChanged(QDate date);
public Q_SLOTS:
void setDateTime(const QDateTime &dateTime);
- void setDate(const QDate &date);
- void setTime(const QTime &time);
+ void setDate(QDate date);
+ void setTime(QTime time);
protected:
void keyPressEvent(QKeyEvent *event) override;
@@ -193,9 +168,9 @@ protected:
StepEnabled stepEnabled() const override;
void mousePressEvent(QMouseEvent *event) override;
void paintEvent(QPaintEvent *event) override;
- void initStyleOption(QStyleOptionSpinBox *option) const;
+ void initStyleOption(QStyleOptionSpinBox *option) const override;
- QDateTimeEdit(const QVariant &val, QVariant::Type parserType, QWidget *parent = nullptr);
+ QDateTimeEdit(const QVariant &val, QMetaType::Type parserType, QWidget *parent = nullptr);
private:
Q_DECLARE_PRIVATE(QDateTimeEdit)
Q_DISABLE_COPY(QDateTimeEdit)
@@ -209,11 +184,11 @@ class Q_WIDGETS_EXPORT QTimeEdit : public QDateTimeEdit
Q_PROPERTY(QTime time READ time WRITE setTime NOTIFY userTimeChanged USER true)
public:
explicit QTimeEdit(QWidget *parent = nullptr);
- explicit QTimeEdit(const QTime &time, QWidget *parent = nullptr);
+ explicit QTimeEdit(QTime time, QWidget *parent = nullptr);
~QTimeEdit();
Q_SIGNALS:
- void userTimeChanged(const QTime &time);
+ void userTimeChanged(QTime time);
};
class Q_WIDGETS_EXPORT QDateEdit : public QDateTimeEdit
@@ -222,11 +197,11 @@ class Q_WIDGETS_EXPORT QDateEdit : public QDateTimeEdit
Q_PROPERTY(QDate date READ date WRITE setDate NOTIFY userDateChanged USER true)
public:
explicit QDateEdit(QWidget *parent = nullptr);
- explicit QDateEdit(const QDate &date, QWidget *parent = nullptr);
+ explicit QDateEdit(QDate date, QWidget *parent = nullptr);
~QDateEdit();
Q_SIGNALS:
- void userDateChanged(const QDate &date);
+ void userDateChanged(QDate date);
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QDateTimeEdit::Sections)
diff --git a/src/widgets/widgets/qdatetimeedit_p.h b/src/widgets/widgets/qdatetimeedit_p.h
index 0a4433846f..215ee75bfe 100644
--- a/src/widgets/widgets/qdatetimeedit_p.h
+++ b/src/widgets/widgets/qdatetimeedit_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 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 QDATETIMEEDIT_P_H
#define QDATETIMEEDIT_P_H
@@ -53,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"
@@ -62,6 +28,7 @@
#include "private/qdatetimeparser_p.h"
#include "qdebug.h"
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
@@ -70,7 +37,7 @@ class Q_AUTOTEST_EXPORT QDateTimeEditPrivate : public QAbstractSpinBoxPrivate, p
{
Q_DECLARE_PUBLIC(QDateTimeEdit)
public:
- QDateTimeEditPrivate();
+ QDateTimeEditPrivate(const QTimeZone &zone = QTimeZone::LocalTime);
void init(const QVariant &var);
void readLocaleSettings();
@@ -83,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;
@@ -94,8 +61,8 @@ public:
// Override QDateTimeParser:
QString displayText() const override { return edit->text(); }
- QDateTime getMinimum() const override { return minimum.toDateTime(); }
- QDateTime getMaximum() const override { return maximum.toDateTime(); }
+ 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; }
@@ -109,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);
@@ -126,18 +94,20 @@ public:
void initCalendarPopup(QCalendarWidget *cw = nullptr);
void positionCalendarPopup();
- QDateTimeEdit::Sections sections;
- mutable bool cacheGuard;
+ QDateTimeEdit::Sections sections = {};
+ mutable bool cacheGuard = false;
QString defaultDateFormat, defaultTimeFormat, defaultDateTimeFormat, unreversedFormat;
mutable QVariant conflictGuard;
- bool hasHadFocus, formatExplicitlySet, calendarPopup;
- QStyle::StateFlag arrowState;
- QCalendarPopup *monthCalendar;
+ bool hasHadFocus = false, formatExplicitlySet = false, calendarPopup = false;
+ QStyle::StateFlag arrowState = QStyle::State_None;
+ QCalendarPopup *monthCalendar = nullptr;
#ifdef QT_KEYPAD_NAVIGATION
- bool focusOnButton;
+ bool focusOnButton = false;
#endif
+
+ QTimeZone timeZone;
};
diff --git a/src/widgets/widgets/qdial.cpp b/src/widgets/widgets/qdial.cpp
index 25d57970bf..14e96f8dc3 100644
--- a/src/widgets/widgets/qdial.cpp
+++ b/src/widgets/widgets/qdial.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qdial.h"
@@ -52,7 +16,7 @@
#include <qslider.h>
#include <private/qabstractslider_p.h>
#include <private/qmath_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
#include <qmath.h>
@@ -94,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;
@@ -222,11 +188,11 @@ int QDialPrivate::valueFromPoint(const QPoint &p) const
If you are using the mouse wheel to adjust the dial, the increment
value is determined by the lesser value of
- \l{QApplication::wheelScrollLines()} {wheelScrollLines} multipled
+ \l{QApplication::wheelScrollLines()} {wheelScrollLines} multiplied
by \l {QAbstractSlider::singleStep} {singleStep}, and
\l {QAbstractSlider::pageStep} {pageStep}.
- \sa QScrollBar, QSpinBox, QSlider, {fowler}{GUI Design Handbook: Slider}, {Sliders Example}
+ \sa QScrollBar, QSpinBox, QSlider, {Sliders Example}
*/
/*!
@@ -280,7 +246,7 @@ void QDial::mousePressEvent(QMouseEvent *e)
return;
}
e->accept();
- setSliderPosition(d->valueFromPoint(e->pos()));
+ setSliderPosition(d->valueFromPoint(e->position().toPoint()));
// ### This isn't quite right,
// we should be doing a hit test and only setting this if it's
// the actual dial thingie (similar to what QSlider does), but we have no
@@ -302,7 +268,7 @@ void QDial::mouseReleaseEvent(QMouseEvent * e)
return;
}
e->accept();
- setValue(d->valueFromPoint(e->pos()));
+ setValue(d->valueFromPoint(e->position().toPoint()));
setSliderDown(false);
}
@@ -320,7 +286,7 @@ void QDial::mouseMoveEvent(QMouseEvent * e)
}
e->accept();
d->doNotEmit = true;
- setSliderPosition(d->valueFromPoint(e->pos()));
+ setSliderPosition(d->valueFromPoint(e->position().toPoint()));
d->doNotEmit = false;
}
@@ -370,12 +336,10 @@ bool QDial::wrapping() const
\property QDial::notchSize
\brief the current notch size
- The notch size is in range control units, not pixels, and if
- possible it is a multiple of singleStep() that results in an
+ The notch size is in range control units, not pixels, and is
+ calculated to be a multiple of singleStep() that results in an
on-screen notch size near notchTarget().
- By default, this property has a value of 1.
-
\sa notchTarget(), singleStep()
*/
@@ -383,21 +347,17 @@ int QDial::notchSize() const
{
Q_D(const QDial);
// radius of the arc
- int r = qMin(width(), height())/2;
+ qreal r = qMin(width(), height())/2.0;
// length of the whole arc
- int l = (int)(r * (d->wrapping ? 6 : 5) * Q_PI / 6);
+ int l = qRound(r * (d->wrapping ? 6.0 : 5.0) * Q_PI / 6.0);
// length of the arc from minValue() to minValue()+pageStep()
if (d->maximum > d->minimum + d->pageStep)
- l = (int)(0.5 + l * d->pageStep / (d->maximum - d->minimum));
+ l = qRound(l * d->pageStep / double(d->maximum - d->minimum));
// length of a singleStep arc
- l = l * d->singleStep / (d->pageStep ? d->pageStep : 1);
- if (l < 1)
- l = 1;
+ l = qMax(l * d->singleStep / (d->pageStep ? d->pageStep : 1), 1);
// how many times singleStep can be draw in d->target pixels
- l = (int)(0.5 + d->target / l);
- // we want notchSize() to be a non-zero multiple of lineStep()
- if (!l)
- l = 1;
+ l = qMax(qRound(d->target / l), 1);
+ // we want notchSize() to be a non-zero multiple of singleStep()
return d->singleStep * l;
}
@@ -464,7 +424,7 @@ QSize QDial::minimumSizeHint() const
QSize QDial::sizeHint() const
{
- return QSize(100, 100).expandedTo(QApplication::globalStrut());
+ return QSize(100, 100);
}
/*!
diff --git a/src/widgets/widgets/qdial.h b/src/widgets/widgets/qdial.h
index 1db1f9bb07..af08a41048 100644
--- a/src/widgets/widgets/qdial.h
+++ b/src/widgets/widgets/qdial.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDIAL_H
@@ -90,7 +54,7 @@ protected:
void mouseMoveEvent(QMouseEvent *me) override;
void sliderChange(SliderChange change) override;
- void initStyleOption(QStyleOptionSlider *option) const;
+ virtual void initStyleOption(QStyleOptionSlider *option) const;
private:
diff --git a/src/widgets/widgets/qdialogbuttonbox.cpp b/src/widgets/widgets/qdialogbuttonbox.cpp
index 2e12320bc3..30ace89fa8 100644
--- a/src/widgets/widgets/qdialogbuttonbox.cpp
+++ b/src/widgets/widgets/qdialogbuttonbox.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QtCore/qhash.h>
#include <QtWidgets/qpushbutton.h>
@@ -47,9 +11,12 @@
#include <private/qguiapplication_p.h>
#include <QtGui/qpa/qplatformdialoghelper.h>
#include <QtGui/qpa/qplatformtheme.h>
-#include <QtWidgets/qaction.h>
+#include <QtGui/qaction.h>
#include "qdialogbuttonbox.h"
+#include "qdialogbuttonbox_p.h"
+
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
@@ -89,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.
@@ -147,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()
@@ -213,7 +166,6 @@ void QDialogButtonBoxPrivate::initLayout()
void QDialogButtonBoxPrivate::resetLayout()
{
- //delete buttonLayout;
initLayout();
layoutButtons();
}
@@ -221,8 +173,8 @@ void QDialogButtonBoxPrivate::resetLayout()
void QDialogButtonBoxPrivate::addButtonsToLayout(const QList<QAbstractButton *> &buttonList,
bool reverse)
{
- int start = reverse ? buttonList.count() - 1 : 0;
- int end = reverse ? -1 : buttonList.count();
+ int start = reverse ? buttonList.size() - 1 : 0;
+ int end = reverse ? -1 : buttonList.size();
int step = reverse ? -1 : 1;
for (int i = start; i != end; i += step) {
@@ -237,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())
@@ -329,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);
}
}
@@ -347,7 +304,7 @@ void QDialogButtonBoxPrivate::layoutButtons()
}
QPushButton *QDialogButtonBoxPrivate::createButton(QDialogButtonBox::StandardButton sbutton,
- bool doLayout)
+ LayoutRule layoutRule)
{
Q_Q(QDialogButtonBox);
int icon = 0;
@@ -422,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())
@@ -432,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();
@@ -456,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);
}
}
@@ -518,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();
}
/*!
@@ -672,34 +647,45 @@ void QDialogButtonBox::clear()
d->standardButtonHash.clear();
for (int i = 0; i < NRoles; ++i) {
QList<QAbstractButton *> &list = d->buttonLists[i];
- while (list.count()) {
+ 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 j = 0; j < list.count(); ++j)
+ 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 0 or has not been added to the button box.
+ \l InvalidRole if \a button is \nullptr or has not been added to the button box.
\sa buttons(), addButton()
*/
@@ -708,12 +694,12 @@ QDialogButtonBox::ButtonRole QDialogButtonBox::buttonRole(QAbstractButton *butto
Q_D(const QDialogButtonBox);
for (int i = 0; i < NRoles; ++i) {
const QList<QAbstractButton *> &list = d->buttonLists[i];
- for (int j = 0; j < list.count(); ++j) {
+ for (int j = 0; j < list.size(); ++j) {
if (list.at(j) == button)
return ButtonRole(i);
}
}
- return InvalidRole;
+ return d->hiddenButtons.value(button, InvalidRole);
}
/*!
@@ -724,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.count(); ++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;
+ }
}
/*!
@@ -814,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);
@@ -856,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())) {
@@ -890,20 +894,51 @@ 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;
}
/*!
\property QDialogButtonBox::centerButtons
\brief whether the buttons in the button box are centered
- By default, this property is \c false. This behavior is appopriate
+ By default, this property is \c false. This behavior is appropriate
for most types of dialogs. A notable exception is message boxes
on most platforms (e.g. Windows), where the button box is
centered horizontally.
@@ -954,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 a9a1a3453d..d967494d0d 100644
--- a/src/widgets/widgets/qdialogbuttonbox.h
+++ b/src/widgets/widgets/qdialogbuttonbox.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDIALOGBUTTONBOX_H
#define QDIALOGBUTTONBOX_H
@@ -113,8 +77,7 @@ public:
MacLayout,
KdeLayout,
GnomeLayout,
- // MacModelessLayout,
- AndroidLayout = GnomeLayout + 2 // ### Qt 6: reorder
+ AndroidLayout
};
QDialogButtonBox(QWidget *parent = nullptr);
@@ -157,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 87f4519dd6..da0e987171 100644
--- a/src/widgets/widgets/qdockarealayout.cpp
+++ b/src/widgets/widgets/qdockarealayout.cpp
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "QtWidgets/qapplication.h"
#include "QtWidgets/qwidget.h"
@@ -44,8 +8,6 @@
#include "QtWidgets/qtabbar.h"
#endif
#include "QtWidgets/qstyle.h"
-#include "QtWidgets/qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
#include "QtWidgets/qapplication.h"
#include "QtCore/qvariant.h"
#include "qdockarealayout_p.h"
@@ -62,6 +24,8 @@
QT_BEGIN_NAMESPACE
+Q_LOGGING_CATEGORY(lcQpaDockWidgets, "qt.widgets.dockwidgets");
+
// qmainwindow.cpp
extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
@@ -127,7 +91,7 @@ bool QDockAreaLayoutItem::skip() const
return widgetItem->isEmpty();
if (subinfo != nullptr) {
- for (int i = 0; i < subinfo->item_list.count(); ++i) {
+ for (int i = 0; i < subinfo->item_list.size(); ++i) {
if (!subinfo->item_list.at(i).skip())
return false;
}
@@ -184,7 +148,11 @@ QSize QDockAreaLayoutItem::sizeHint() const
QDockAreaLayoutItem
&QDockAreaLayoutItem::operator = (const QDockAreaLayoutItem &other)
{
+ if (this == &other)
+ return *this;
+
widgetItem = other.widgetItem;
+ delete subinfo;
if (other.subinfo == nullptr)
subinfo = nullptr;
else
@@ -203,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
*/
@@ -544,7 +544,7 @@ void QDockAreaLayoutInfo::fitItems()
}
#endif
- QVector<QLayoutStruct> layout_struct_list(item_list.size()*2);
+ QList<QLayoutStruct> layout_struct_list(item_list.size() * 2);
int j = 0;
int size = pick(o, rect.size());
@@ -854,7 +854,7 @@ static inline int grow(QLayoutStruct &ls, int delta)
return ls.size - old_size;
}
-static int separatorMoveHelper(QVector<QLayoutStruct> &list, int index, int delta, int sep)
+static int separatorMoveHelper(QList<QLayoutStruct> &list, int index, int delta, int sep)
{
// adjust sizes
int pos = -1;
@@ -884,7 +884,7 @@ static int separatorMoveHelper(QVector<QLayoutStruct> &list, int index, int delt
delta = growlimit;
int d = 0;
- for (int i = index + 1; d < delta && i < list.count(); ++i)
+ for (int i = index + 1; d < delta && i < list.size(); ++i)
d += shrink(list[i], delta - d);
delta = d;
d = 0;
@@ -892,7 +892,7 @@ static int separatorMoveHelper(QVector<QLayoutStruct> &list, int index, int delt
d += grow(list[i], delta - d);
} else if (delta < 0) {
int growlimit = 0;
- for (int i = index + 1; i < list.count(); ++i) {
+ for (int i = index + 1; i < list.size(); ++i) {
const QLayoutStruct &ls = list.at(i);
if (ls.empty)
continue;
@@ -910,7 +910,7 @@ static int separatorMoveHelper(QVector<QLayoutStruct> &list, int index, int delt
d += shrink(list[i], -delta - d);
delta = -d;
d = 0;
- for (int i = index + 1; d < -delta && i < list.count(); ++i)
+ for (int i = index + 1; d < -delta && i < list.size(); ++i)
d += grow(list[i], -delta - d);
}
@@ -938,7 +938,7 @@ int QDockAreaLayoutInfo::separatorMove(int index, int delta)
Q_ASSERT(!tabbed);
#endif
- QVector<QLayoutStruct> list(item_list.size());
+ QList<QLayoutStruct> list(item_list.size());
for (int i = 0; i < list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
QLayoutStruct &ls = list[i];
@@ -981,12 +981,12 @@ void QDockAreaLayoutInfo::unnest(int index)
QDockAreaLayoutItem &item = item_list[index];
if (item.subinfo == nullptr)
return;
- if (item.subinfo->item_list.count() > 1)
+ if (item.subinfo->item_list.size() > 1)
return;
- if (item.subinfo->item_list.count() == 0) {
+ if (item.subinfo->item_list.size() == 0) {
item_list.removeAt(index);
- } else if (item.subinfo->item_list.count() == 1) {
+ } else if (item.subinfo->item_list.size() == 1) {
QDockAreaLayoutItem &child = item.subinfo->item_list.first();
if (child.widgetItem != nullptr) {
item.widgetItem = child.widgetItem;
@@ -1006,7 +1006,7 @@ void QDockAreaLayoutInfo::remove(const QList<int> &path)
{
Q_ASSERT(!path.isEmpty());
- if (path.count() > 1) {
+ if (path.size() > 1) {
const int index = path.first();
QDockAreaLayoutItem &item = item_list[index];
Q_ASSERT(item.subinfo != nullptr);
@@ -1018,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());
@@ -1026,7 +1034,7 @@ QLayoutItem *QDockAreaLayoutInfo::plug(const QList<int> &path)
if (index < 0)
index = -index - 1;
- if (path.count() > 1) {
+ if (path.size() > 1) {
QDockAreaLayoutItem &item = item_list[index];
Q_ASSERT(item.subinfo != nullptr);
return item.subinfo->plug(path.mid(1));
@@ -1045,7 +1053,7 @@ QLayoutItem *QDockAreaLayoutInfo::unplug(const QList<int> &path)
Q_ASSERT(!path.isEmpty());
const int index = path.first();
- if (path.count() > 1) {
+ if (path.size() > 1) {
QDockAreaLayoutItem &item = item_list[index];
Q_ASSERT(item.subinfo != nullptr);
return item.subinfo->unplug(path.mid(1));
@@ -1122,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());
@@ -1133,9 +1156,7 @@ bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWid
index = -index - 1;
}
-// dump(qDebug() << "insertGap() before:" << index << tabIndex, *this, QString());
-
- if (path.count() > 1) {
+ if (path.size() > 1) {
QDockAreaLayoutItem &item = item_list[index];
if (item.subinfo == nullptr
@@ -1217,12 +1238,14 @@ bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWid
break;
}
} else {
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.skip())
continue;
- Q_ASSERT(!(item.flags & QDockAreaLayoutItem::GapItem));
+ Q_ASSERT_X(!(item.flags & QDockAreaLayoutItem::GapItem),
+ "QDockAreaLayoutInfo::insertGap", "inserting two gaps after each other");
space += item.size - pick(o, item.minimumSize());
+ qCDebug(lcQpaDockWidgets) << "Item space:" << item.flags << this;
}
}
@@ -1247,15 +1270,14 @@ bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWid
// finally, insert the gap
item_list.insert(index, gap_item);
-
-// dump(qDebug() << "insertGap() after:" << index << tabIndex, *this, QString());
+ qCDebug(lcQpaDockWidgets) << "Insert gap after:" << index << this;
return true;
}
QDockAreaLayoutInfo *QDockAreaLayoutInfo::info(QWidget *widget)
{
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.skip())
continue;
@@ -1282,9 +1304,9 @@ QDockAreaLayoutInfo *QDockAreaLayoutInfo::info(const QList<int> &path)
int index = path.first();
if (index < 0)
index = -index - 1;
- if (index >= item_list.count())
+ if (index >= item_list.size())
return this;
- if (path.count() == 1 || item_list[index].subinfo == nullptr)
+ if (path.size() == 1 || item_list[index].subinfo == nullptr)
return this;
return item_list[index].subinfo->info(path.mid(1));
}
@@ -1339,7 +1361,7 @@ QRect QDockAreaLayoutInfo::itemRect(const QList<int> &path) const
Q_ASSERT(!path.isEmpty());
const int index = path.first();
- if (path.count() > 1) {
+ if (path.size() > 1) {
const QDockAreaLayoutItem &item = item_list.at(index);
Q_ASSERT(item.subinfo != nullptr);
return item.subinfo->itemRect(path.mid(1));
@@ -1372,7 +1394,7 @@ QRect QDockAreaLayoutInfo::separatorRect(const QList<int> &path) const
Q_ASSERT(!path.isEmpty());
const int index = path.first();
- if (path.count() > 1) {
+ if (path.size() > 1) {
const QDockAreaLayoutItem &item = item_list.at(index);
Q_ASSERT(item.subinfo != nullptr);
return item.subinfo->separatorRect(path.mid(1));
@@ -1597,7 +1619,7 @@ QRegion QDockAreaLayoutInfo::separatorRegion() const
return result;
#endif
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.skip())
@@ -1627,7 +1649,7 @@ void QDockAreaLayoutInfo::paintSeparators(QPainter *p, QWidget *widget,
return;
#endif
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.skip())
@@ -1712,7 +1734,7 @@ QDockAreaLayoutItem &QDockAreaLayoutInfo::item(const QList<int> &path)
{
Q_ASSERT(!path.isEmpty());
const int index = path.first();
- if (path.count() > 1) {
+ if (path.size() > 1) {
const QDockAreaLayoutItem &item = item_list[index];
Q_ASSERT(item.subinfo != nullptr);
return item.subinfo->item(path.mid(1));
@@ -1722,7 +1744,7 @@ QDockAreaLayoutItem &QDockAreaLayoutInfo::item(const QList<int> &path)
QLayoutItem *QDockAreaLayoutInfo::itemAt(int *x, int index) const
{
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.placeHolderItem != nullptr)
continue;
@@ -1739,7 +1761,7 @@ QLayoutItem *QDockAreaLayoutInfo::itemAt(int *x, int index) const
QLayoutItem *QDockAreaLayoutInfo::takeAt(int *x, int index)
{
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
QDockAreaLayoutItem &item = item_list[i];
if (item.placeHolderItem != nullptr)
continue;
@@ -1762,9 +1784,29 @@ 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.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
QDockAreaLayoutItem &item= item_list[i];
if (item.subinfo) {
item.subinfo->deleteAllLayoutItems();
@@ -1784,7 +1826,7 @@ void QDockAreaLayoutInfo::saveState(QDataStream &stream) const
// write the index in item_list of the widget that's currently on top.
quintptr id = currentTabId();
int index = -1;
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
if (tabId(item_list.at(i)) == id) {
index = i;
break;
@@ -1797,9 +1839,9 @@ void QDockAreaLayoutInfo::saveState(QDataStream &stream) const
stream << (uchar) SequenceMarker;
}
- stream << (uchar) o << item_list.count();
+ stream << (uchar) o << int(item_list.size());
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.widgetItem != nullptr) {
stream << (uchar) WidgetMarker;
@@ -1895,7 +1937,7 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*>
}
QDockWidget *widget = nullptr;
- for (int j = 0; j < widgets.count(); ++j) {
+ for (int j = 0; j < widgets.size(); ++j) {
if (widgets.at(j)->objectName() == name) {
widget = widgets.takeAt(j);
break;
@@ -1955,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) {
@@ -1981,7 +2024,7 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*>
}
#if QT_CONFIG(tabbar)
- if (!testing && tabbed && index >= 0 && index < item_list.count()) {
+ if (!testing && tabbed && index >= 0 && index < item_list.size()) {
updateTabBar();
setCurrentTabId(tabId(item_list.at(index)));
}
@@ -2001,7 +2044,7 @@ void QDockAreaLayoutInfo::updateSeparatorWidgets() const
}
int j = 0;
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.skip())
@@ -2020,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);
@@ -2040,7 +2089,6 @@ void QDockAreaLayoutInfo::updateSeparatorWidgets() const
separatorWidgets[k]->hide();
}
separatorWidgets.resize(j);
- Q_ASSERT(separatorWidgets.size() == j);
}
/*! \internal
@@ -2053,7 +2101,7 @@ void QDockAreaLayoutInfo::reparentWidgets(QWidget *parent)
if (tabBar)
tabBar->setParent(parent);
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.flags & QDockAreaLayoutItem::GapItem)
continue;
@@ -2093,7 +2141,7 @@ bool QDockAreaLayoutInfo::updateTabBar() const
const quintptr oldCurrentId = currentTabId();
int tab_idx = 0;
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.skip())
continue;
@@ -2109,7 +2157,7 @@ bool QDockAreaLayoutInfo::updateTabBar() const
quintptr id = tabId(item);
if (tab_idx == tabBar->count()) {
tabBar->insertTab(tab_idx, title);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
tabBar->setTabToolTip(tab_idx, title);
#endif
tabBar->setTabData(tab_idx, id);
@@ -2119,7 +2167,7 @@ bool QDockAreaLayoutInfo::updateTabBar() const
tabBar->removeTab(tab_idx);
else {
tabBar->insertTab(tab_idx, title);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
tabBar->setTabToolTip(tab_idx, title);
#endif
tabBar->setTabData(tab_idx, id);
@@ -2128,7 +2176,7 @@ bool QDockAreaLayoutInfo::updateTabBar() const
if (title != tabBar->tabText(tab_idx)) {
tabBar->setTabText(tab_idx, title);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
tabBar->setTabToolTip(tab_idx, title);
#endif
}
@@ -2158,7 +2206,7 @@ void QDockAreaLayoutInfo::setTabBarShape(int shape)
if (tabBar != nullptr)
tabBar->setShape(static_cast<QTabBar::Shape>(shape));
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
QDockAreaLayoutItem &item = item_list[i];
if (item.subinfo != nullptr)
item.subinfo->setTabBarShape(shape);
@@ -2190,7 +2238,7 @@ QSet<QTabBar*> QDockAreaLayoutInfo::usedTabBars() const
result.insert(tabBar);
}
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.subinfo != nullptr)
result += item.subinfo->usedTabBars();
@@ -2204,13 +2252,13 @@ QSet<QTabBar*> QDockAreaLayoutInfo::usedTabBars() const
QSet<QWidget*> QDockAreaLayoutInfo::usedSeparatorWidgets() const
{
QSet<QWidget*> result;
- const int numSeparatorWidgets = separatorWidgets.count();
+ const int numSeparatorWidgets = separatorWidgets.size();
result.reserve(numSeparatorWidgets);
for (int i = 0; i < numSeparatorWidgets; ++i)
result << separatorWidgets.at(i);
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
const QDockAreaLayoutItem &item = item_list.at(i);
if (item.subinfo != nullptr)
result += item.subinfo->usedSeparatorWidgets();
@@ -2257,7 +2305,7 @@ int QDockAreaLayoutInfo::tabIndexToListIndex(int tabIndex) const
{
Q_ASSERT(tabbed && tabBar);
quintptr data = qvariant_cast<quintptr>(tabBar->tabData(tabIndex));
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
if (tabId(item_list.at(i)) == data)
return i;
}
@@ -2427,23 +2475,7 @@ QList<int> QDockAreaLayout::gapIndex(const QPoint &pos, bool disallowTabs) const
const QDockAreaLayoutInfo &info = docks[i];
if (info.isEmpty()) {
- QRect r;
- switch (i) {
- case QInternal::LeftDock:
- r = QRect(rect.left(), rect.top(), EmptyDropAreaSize, rect.height());
- break;
- case QInternal::RightDock:
- r = QRect(rect.right() - EmptyDropAreaSize, rect.top(),
- EmptyDropAreaSize, rect.height());
- break;
- case QInternal::TopDock:
- r = QRect(rect.left(), rect.top(), rect.width(), EmptyDropAreaSize);
- break;
- case QInternal::BottomDock:
- r = QRect(rect.left(), rect.bottom() - EmptyDropAreaSize,
- rect.width(), EmptyDropAreaSize);
- break;
- }
+ const QRect r = gapRect(static_cast<QInternal::DockPosition>(i));
if (r.contains(pos)) {
if (opts & QMainWindow::ForceTabbedDocks && !info.item_list.isEmpty()) {
//in case of ForceTabbedDocks, we pass -1 in order to force the gap to be tabbed
@@ -2459,6 +2491,43 @@ QList<int> QDockAreaLayout::gapIndex(const QPoint &pos, bool disallowTabs) const
return QList<int>();
}
+QRect QDockAreaLayout::gapRect(QInternal::DockPosition dockPos) const
+{
+ Q_ASSERT_X(mainWindow, "QDockAreaLayout::gapRect", "Called without valid mainWindow pointer.");
+
+ // Determine gap size depending on MainWindow size (QTBUG-101657)
+ const QSize gapSize = (mainWindow->size()/2).boundedTo(QSize(EmptyDropAreaSize, EmptyDropAreaSize));
+
+ // Warn if main window is too small to create proper docks.
+ // Do not fail because this can be triggered by a user making MainWindow too small
+ if (mainWindow->height() < (2 * sep)) {
+ qCWarning(lcQpaDockWidgets,
+ "QDockAreaLayout::gapRect: Main window height %i is too small. Docking will not be possible.",
+ mainWindow->height());
+
+ }
+ if (mainWindow->width() < (2 * sep)) {
+ qCWarning(lcQpaDockWidgets,
+ "QDockAreaLayout::gapRect: Main window width %i is too small. Docking will not be possible.",
+ mainWindow->width());
+ }
+
+ // Calculate rectangle of requested dock
+ switch (dockPos) {
+ case QInternal::LeftDock:
+ return QRect(rect.left(), rect.top(), gapSize.width(), rect.height());
+ case QInternal::RightDock:
+ return QRect(rect.right() - gapSize.width(), rect.top(), gapSize.width(), rect.height());
+ case QInternal::TopDock:
+ return QRect(rect.left(), rect.top(), rect.width(), gapSize.height());
+ case QInternal::BottomDock:
+ return QRect(rect.left(), rect.bottom() - gapSize.height(), rect.width(), gapSize.height());
+ case QInternal::DockCount:
+ break;
+ }
+ return QRect();
+}
+
QList<int> QDockAreaLayout::findSeparator(const QPoint &pos) const
{
QList<int> result;
@@ -2500,7 +2569,7 @@ QDockAreaLayoutInfo *QDockAreaLayout::info(const QList<int> &path)
const int index = path.first();
Q_ASSERT(index >= 0 && index < QInternal::DockCount);
- if (path.count() == 1)
+ if (path.size() == 1)
return &docks[index];
return docks[index].info(path.mid(1));
@@ -2555,7 +2624,7 @@ QRect QDockAreaLayout::separatorRect(const QList<int> &path) const
const int index = path.first();
Q_ASSERT(index >= 0 && index < QInternal::DockCount);
- if (path.count() == 1)
+ if (path.size() == 1)
return separatorRect(index);
else
return docks[index].separatorRect(path.mid(1));
@@ -2605,7 +2674,7 @@ void QDockAreaLayout::removePlaceHolder(const QString &name)
if (!index.isEmpty())
remove(index);
const auto groups =
- mainWindow->findChildren<QDockWidgetGroupWindow *>(QString(), Qt::FindDirectChildrenOnly);
+ mainWindow->findChildren<QDockWidgetGroupWindow *>(Qt::FindDirectChildrenOnly);
for (QDockWidgetGroupWindow *dwgw : groups) {
index = dwgw->layoutInfo()->indexOfPlaceHolder(name);
if (!index.isEmpty()) {
@@ -2617,8 +2686,8 @@ void QDockAreaLayout::removePlaceHolder(const QString &name)
static inline int qMax(int i1, int i2, int i3) { return qMax(i1, qMax(i2, i3)); }
-void QDockAreaLayout::getGrid(QVector<QLayoutStruct> *_ver_struct_list,
- QVector<QLayoutStruct> *_hor_struct_list)
+void QDockAreaLayout::getGrid(QList<QLayoutStruct> *_ver_struct_list,
+ QList<QLayoutStruct> *_hor_struct_list)
{
QSize center_hint(0, 0);
QSize center_min(0, 0);
@@ -2671,7 +2740,7 @@ void QDockAreaLayout::getGrid(QVector<QLayoutStruct> *_ver_struct_list,
bottom_hint = bottom_hint.boundedTo(bottom_max).expandedTo(bottom_min);
if (_ver_struct_list != nullptr) {
- QVector<QLayoutStruct> &ver_struct_list = *_ver_struct_list;
+ QList<QLayoutStruct> &ver_struct_list = *_ver_struct_list;
ver_struct_list.resize(3);
// top --------------------------------------------------
@@ -2733,7 +2802,7 @@ void QDockAreaLayout::getGrid(QVector<QLayoutStruct> *_ver_struct_list,
}
if (_hor_struct_list != nullptr) {
- QVector<QLayoutStruct> &hor_struct_list = *_hor_struct_list;
+ QList<QLayoutStruct> &hor_struct_list = *_hor_struct_list;
hor_struct_list.resize(3);
// left --------------------------------------------------
@@ -2795,8 +2864,8 @@ void QDockAreaLayout::getGrid(QVector<QLayoutStruct> *_ver_struct_list,
}
}
-void QDockAreaLayout::setGrid(QVector<QLayoutStruct> *ver_struct_list,
- QVector<QLayoutStruct> *hor_struct_list)
+void QDockAreaLayout::setGrid(QList<QLayoutStruct> *ver_struct_list,
+ QList<QLayoutStruct> *hor_struct_list)
{
// top ---------------------------------------------------
@@ -2893,8 +2962,8 @@ void QDockAreaLayout::setGrid(QVector<QLayoutStruct> *ver_struct_list,
void QDockAreaLayout::fitLayout()
{
- QVector<QLayoutStruct> ver_struct_list(3);
- QVector<QLayoutStruct> hor_struct_list(3);
+ QList<QLayoutStruct> ver_struct_list(3);
+ QList<QLayoutStruct> hor_struct_list(3);
getGrid(&ver_struct_list, &hor_struct_list);
qGeomCalc(ver_struct_list, 0, 3, rect.top(), rect.height(), sep);
@@ -2912,7 +2981,8 @@ void QDockAreaLayout::clear()
centralWidgetRect = QRect();
}
-QSize QDockAreaLayout::sizeHint() const
+template<typename SizePMF, typename CenterPMF>
+QSize QDockAreaLayout::size_helper(SizePMF sizeFn, CenterPMF centerFn) const
{
int left_sep = 0;
int right_sep = 0;
@@ -2926,11 +2996,12 @@ QSize QDockAreaLayout::sizeHint() const
bottom_sep = docks[QInternal::BottomDock].isEmpty() ? 0 : sep;
}
- QSize left = docks[QInternal::LeftDock].sizeHint() + QSize(left_sep, 0);
- QSize right = docks[QInternal::RightDock].sizeHint() + QSize(right_sep, 0);
- QSize top = docks[QInternal::TopDock].sizeHint() + QSize(0, top_sep);
- QSize bottom = docks[QInternal::BottomDock].sizeHint() + QSize(0, bottom_sep);
- QSize center = centralWidgetItem == nullptr ? QSize(0, 0) : centralWidgetItem->sizeHint();
+ const QSize left = (docks[QInternal::LeftDock].*sizeFn)() + QSize(left_sep, 0);
+ const QSize right = (docks[QInternal::RightDock].*sizeFn)() + QSize(right_sep, 0);
+ const QSize top = (docks[QInternal::TopDock].*sizeFn)() + QSize(0, top_sep);
+ const QSize bottom = (docks[QInternal::BottomDock].*sizeFn)() + QSize(0, bottom_sep);
+ const QSize center = centralWidgetItem == nullptr
+ ? QSize(0, 0) : (centralWidgetItem->*centerFn)();
int row1 = top.width();
int row2 = left.width() + center.width() + right.width();
@@ -2962,54 +3033,24 @@ QSize QDockAreaLayout::sizeHint() const
return QSize(qMax(row1, row2, row3), qMax(col1, col2, col3));
}
-QSize QDockAreaLayout::minimumSize() const
+QSize QDockAreaLayout::sizeHint() const
{
- int left_sep = 0;
- int right_sep = 0;
- int top_sep = 0;
- int bottom_sep = 0;
-
- if (centralWidgetItem != nullptr) {
- left_sep = docks[QInternal::LeftDock].isEmpty() ? 0 : sep;
- right_sep = docks[QInternal::RightDock].isEmpty() ? 0 : sep;
- top_sep = docks[QInternal::TopDock].isEmpty() ? 0 : sep;
- bottom_sep = docks[QInternal::BottomDock].isEmpty() ? 0 : sep;
- }
-
- QSize left = docks[QInternal::LeftDock].minimumSize() + QSize(left_sep, 0);
- QSize right = docks[QInternal::RightDock].minimumSize() + QSize(right_sep, 0);
- QSize top = docks[QInternal::TopDock].minimumSize() + QSize(0, top_sep);
- QSize bottom = docks[QInternal::BottomDock].minimumSize() + QSize(0, bottom_sep);
- QSize center = centralWidgetItem == nullptr ? QSize(0, 0) : centralWidgetItem->minimumSize();
-
- int row1 = top.width();
- int row2 = left.width() + center.width() + right.width();
- int row3 = bottom.width();
- int col1 = left.height();
- int col2 = top.height() + center.height() + bottom.height();
- int col3 = right.height();
-
- if (corners[Qt::TopLeftCorner] == Qt::LeftDockWidgetArea)
- row1 += left.width();
- else
- col1 += top.height();
-
- if (corners[Qt::TopRightCorner] == Qt::RightDockWidgetArea)
- row1 += right.width();
- else
- col3 += top.height();
+ return size_helper(&QDockAreaLayoutInfo::sizeHint, &QLayoutItem::sizeHint);
+}
- if (corners[Qt::BottomLeftCorner] == Qt::LeftDockWidgetArea)
- row3 += left.width();
- else
- col1 += bottom.height();
+QSize QDockAreaLayout::minimumSize() const
+{
+ return size_helper(&QDockAreaLayoutInfo::minimumSize, &QLayoutItem::minimumSize);
+}
- if (corners[Qt::BottomRightCorner] == Qt::RightDockWidgetArea)
- row3 += right.width();
- else
- col3 += bottom.height();
+/*!
+ \internal
- return QSize(qMax(row1, row2, row3), qMax(col1, col2, col3));
+ Returns the smallest size that doesn't change the size of any of the dock areas.
+*/
+QSize QDockAreaLayout::minimumStableSize() const
+{
+ return size_helper(&QDockAreaLayoutInfo::size, &QLayoutItem::minimumSize);
}
/*! \internal
@@ -3020,19 +3061,20 @@ QSize QDockAreaLayout::minimumSize() const
*/
QRect QDockAreaLayout::constrainedRect(QRect rect, QWidget* widget)
{
- QRect desktop;
- if (QDesktopWidgetPrivate::isVirtualDesktop())
- desktop = QDesktopWidgetPrivate::screenGeometry(rect.topLeft());
- else
- desktop = QDesktopWidgetPrivate::screenGeometry(widget);
+ QScreen *screen = nullptr;
+ if (QGuiApplication::primaryScreen()->virtualSiblings().size() > 1)
+ screen = QGuiApplication::screenAt(rect.topLeft());
+ if (!screen)
+ screen = widget->screen();
- if (desktop.isValid()) {
- rect.setWidth(qMin(rect.width(), desktop.width()));
- rect.setHeight(qMin(rect.height(), desktop.height()));
- rect.moveLeft(qMax(rect.left(), desktop.left()));
- rect.moveTop(qMax(rect.top(), desktop.top()));
- rect.moveRight(qMin(rect.right(), desktop.right()));
- rect.moveBottom(qMin(rect.bottom(), desktop.bottom()));
+ const QRect screenRect = screen->geometry();
+ if (screenRect.isValid()) {
+ rect.setWidth(qMin(rect.width(), screenRect.width()));
+ rect.setHeight(qMin(rect.height(), screenRect.height()));
+ rect.moveLeft(qMax(rect.left(), screenRect.left()));
+ rect.moveTop(qMax(rect.top(), screenRect.top()));
+ rect.moveRight(qMin(rect.right(), screenRect.right()));
+ rect.moveBottom(qMin(rect.bottom(), screenRect.bottom()));
}
return rect;
@@ -3042,7 +3084,7 @@ bool QDockAreaLayout::restoreDockWidget(QDockWidget *dockWidget)
{
QDockAreaLayoutItem *item = nullptr;
const auto groups =
- mainWindow->findChildren<QDockWidgetGroupWindow *>(QString(), Qt::FindDirectChildrenOnly);
+ mainWindow->findChildren<QDockWidgetGroupWindow *>(Qt::FindDirectChildrenOnly);
for (QDockWidgetGroupWindow *dwgw : groups) {
QList<int> index = dwgw->layoutInfo()->indexOfPlaceHolder(dockWidget->objectName());
if (!index.isEmpty()) {
@@ -3080,7 +3122,7 @@ void QDockAreaLayout::addDockWidget(QInternal::DockPosition pos, QDockWidget *do
{
QLayoutItem *dockWidgetItem = new QDockWidgetItem(dockWidget);
QDockAreaLayoutInfo &info = docks[pos];
- if (orientation == info.o || info.item_list.count() <= 1) {
+ if (orientation == info.o || info.item_list.size() <= 1) {
// empty dock areas, or dock areas containing exactly one widget can have their orientation
// switched.
info.o = orientation;
@@ -3126,11 +3168,11 @@ void QDockAreaLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
void QDockAreaLayout::resizeDocks(const QList<QDockWidget *> &docks,
const QList<int> &sizes, Qt::Orientation o)
{
- if (Q_UNLIKELY(docks.count() != sizes.count())) {
+ if (Q_UNLIKELY(docks.size() != sizes.size())) {
qWarning("QMainWidget::resizeDocks: size of the lists are not the same");
return;
}
- int count = docks.count();
+ int count = docks.size();
fallbackToSizeHints = false;
for (int i = 0; i < count; ++i) {
QList<int> path = indexOf(docks[i]);
@@ -3150,7 +3192,7 @@ void QDockAreaLayout::resizeDocks(const QList<QDockWidget *> &docks,
if (!info->tabbed && info->o == o) {
info->item_list[path.constLast()].size = size;
int totalSize = 0;
- for (const QDockAreaLayoutItem &item : qAsConst(info->item_list)) {
+ for (const QDockAreaLayoutItem &item : std::as_const(info->item_list)) {
if (!item.skip()) {
if (totalSize != 0)
totalSize += sep;
@@ -3243,7 +3285,7 @@ int QDockAreaLayout::separatorMove(const QList<int> &separator, const QPoint &or
int delta = 0;
int index = separator.last();
- if (separator.count() > 1) {
+ if (separator.size() > 1) {
QDockAreaLayoutInfo *info = this->info(separator);
delta = pick(info->o, dest - origin);
if (delta != 0)
@@ -3252,7 +3294,7 @@ int QDockAreaLayout::separatorMove(const QList<int> &separator, const QPoint &or
return delta;
}
- QVector<QLayoutStruct> list;
+ QList<QLayoutStruct> list;
if (index == QInternal::LeftDock || index == QInternal::RightDock)
getGrid(nullptr, &list);
@@ -3295,7 +3337,7 @@ int QDockAreaLayoutInfo::separatorMove(const QList<int> &separator, const QPoint
#if QT_CONFIG(tabbar)
// Sets the correct positions for the separator widgets
-// Allocates new sepearator widgets with getSeparatorWidget
+// Allocates new separator widgets with getSeparatorWidget
void QDockAreaLayout::updateSeparatorWidgets() const
{
int j = 0;
@@ -3308,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);
@@ -3384,7 +3432,7 @@ QSet<QTabBar*> QDockAreaLayout::usedTabBars() const
QSet<QWidget*> QDockAreaLayout::usedSeparatorWidgets() const
{
QSet<QWidget*> result;
- const int numSeparators = separatorWidgets.count();
+ const int numSeparators = separatorWidgets.size();
result.reserve(numSeparators);
for (int i = 0; i < numSeparators; ++i)
result << separatorWidgets.at(i);
@@ -3402,7 +3450,7 @@ QRect QDockAreaLayout::gapRect(const QList<int> &path) const
if (info == nullptr)
return QRect();
int index = path.last();
- if (index < 0 || index >= info->item_list.count())
+ if (index < 0 || index >= info->item_list.size())
return QRect();
return info->itemRect(index, true);
}
diff --git a/src/widgets/widgets/qdockarealayout_p.h b/src/widgets/widgets/qdockarealayout_p.h
index 81384bd1b7..aa39bf9913 100644
--- a/src/widgets/widgets/qdockarealayout_p.h
+++ b/src/widgets/widgets/qdockarealayout_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDOCKAREALAYOUT_P_H
#define QDOCKAREALAYOUT_P_H
@@ -52,11 +16,9 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
-#include "QtCore/qrect.h"
-#include "QtCore/qpair.h"
-#include "QtCore/qlist.h"
-#include "QtCore/qvector.h"
#include "QtWidgets/qlayout.h"
+#include "QtCore/qlist.h"
+#include "QtCore/qrect.h"
QT_REQUIRE_CONFIG(dockwidget);
@@ -85,7 +47,7 @@ class QTabBar;
// A path indetifies uniquely one object in this tree, the first number being the side and all the following
// indexes into the QDockAreaLayoutInfo::item_list.
-struct QDockAreaLayoutItem
+struct Q_AUTOTEST_EXPORT QDockAreaLayoutItem
{
enum ItemFlags { NoFlags = 0, GapItem = 1, KeepSize = 2 };
@@ -110,6 +72,10 @@ struct 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
@@ -142,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)
@@ -169,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;
@@ -188,12 +156,13 @@ public:
QLayoutItem *itemAt(int *x, int index) const;
QLayoutItem *takeAt(int *x, int index);
+ void add(QWidget *widget);
void deleteAllLayoutItems();
QMainWindowLayout *mainWindowLayout() const;
const int *sep;
- mutable QVector<QWidget*> separatorWidgets;
+ mutable QList<QWidget *> separatorWidgets;
QInternal::DockPosition dockPos;
Qt::Orientation o;
QRect rect;
@@ -236,9 +205,9 @@ public:
QRect centralWidgetRect;
QDockAreaLayout(QMainWindow *win);
QDockAreaLayoutInfo docks[4];
- int sep; // separator extent
+ int sep; // margin between a dock widget and its frame
bool fallbackToSizeHints; //determines if we should use the sizehint for the dock areas (true until the layout is restored or the separator is moved by user)
- mutable QVector<QWidget*> separatorWidgets;
+ mutable QList<QWidget *> separatorWidgets;
bool isValid() const;
@@ -272,6 +241,9 @@ public:
QSize sizeHint() const;
QSize minimumSize() const;
+ QSize minimumStableSize() const;
+ template<typename SizePMF, typename CenterPMF>
+ QSize size_helper(SizePMF sizeFn, CenterPMF centerFn) const;
void addDockWidget(QInternal::DockPosition pos, QDockWidget *dockWidget, Qt::Orientation orientation);
bool restoreDockWidget(QDockWidget *dockWidget);
@@ -296,12 +268,11 @@ public:
QLayoutItem *takeAt(int *x, int index);
void deleteAllLayoutItems();
- void getGrid(QVector<QLayoutStruct> *ver_struct_list,
- QVector<QLayoutStruct> *hor_struct_list);
- void setGrid(QVector<QLayoutStruct> *ver_struct_list,
- QVector<QLayoutStruct> *hor_struct_list);
+ void getGrid(QList<QLayoutStruct> *ver_struct_list, QList<QLayoutStruct> *hor_struct_list);
+ void setGrid(QList<QLayoutStruct> *ver_struct_list, QList<QLayoutStruct> *hor_struct_list);
QRect gapRect(const QList<int> &path) const;
+ QRect gapRect(QInternal::DockPosition dockPos) const;
void keepSize(QDockWidget *w);
#if QT_CONFIG(tabbar)
diff --git a/src/widgets/widgets/qdockwidget.cpp b/src/widgets/widgets/qdockwidget.cpp
index 299e5da8d3..706306000c 100644
--- a/src/widgets/widgets/qdockwidget.cpp
+++ b/src/widgets/widgets/qdockwidget.cpp
@@ -1,47 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qdockwidget.h"
#include <qaction.h>
#include <qapplication.h>
-#include <qdesktopwidget.h>
#include <qdrawutil.h>
#include <qevent.h>
#include <qfontmetrics.h>
@@ -57,11 +20,14 @@
#include <private/qstylesheetstyle_p.h>
#include <qpa/qplatformtheme.h>
+#include <private/qhighdpiscaling_p.h>
#include "qdockwidget_p.h"
#include "qmainwindowlayout_p.h"
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
extern QString qt_setWindowTitle_helperHelper(const QString&, const QWidget*); // qwidget.cpp
// qmainwindow.cpp
@@ -130,7 +96,7 @@ public:
QSize minimumSizeHint() const override
{ return sizeHint(); }
- void enterEvent(QEvent *event) override;
+ void enterEvent(QEnterEvent *event) override;
void leaveEvent(QEvent *event) override;
void paintEvent(QPaintEvent *event) override;
@@ -153,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:
@@ -162,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);
}
@@ -206,7 +151,7 @@ QSize QDockWidgetTitleButton::sizeHint() const
return QSize(size, size);
}
-void QDockWidgetTitleButton::enterEvent(QEvent *event)
+void QDockWidgetTitleButton::enterEvent(QEnterEvent *event)
{
if (isEnabled()) update();
QAbstractButton::enterEvent(event);
@@ -220,21 +165,23 @@ void QDockWidgetTitleButton::leaveEvent(QEvent *event)
void QDockWidgetTitleButton::paintEvent(QPaintEvent *)
{
- QPainter p(this);
+ QStylePainter p(this);
QStyleOptionToolButton opt;
- opt.init(this);
+ opt.initFrom(this);
opt.state |= QStyle::State_AutoRaise;
- if (style()->styleHint(QStyle::SH_DockWidget_ButtonsHaveFrame, nullptr, this))
- {
+ if (style()->styleHint(QStyle::SH_DockWidget_ButtonsHaveFrame, nullptr, this)) {
if (isEnabled() && underMouse() && !isChecked() && !isDown())
opt.state |= QStyle::State_Raised;
if (isChecked())
opt.state |= QStyle::State_On;
if (isDown())
opt.state |= QStyle::State_Sunken;
- style()->drawPrimitive(QStyle::PE_PanelButtonTool, &opt, &p, this);
+ p.drawPrimitive(QStyle::PE_PanelButtonTool, opt);
+ } else if (isDown() || isChecked()) {
+ // no frame, but the icon might have explicit pixmaps for QIcon::On
+ opt.state |= QStyle::State_On | QStyle::State_Sunken;
}
opt.icon = icon();
@@ -243,7 +190,7 @@ void QDockWidgetTitleButton::paintEvent(QPaintEvent *)
opt.features = QStyleOptionToolButton::None;
opt.arrowType = Qt::NoArrow;
opt.iconSize = dockButtonIconSize();
- style()->drawComplexControl(QStyle::CC_ToolButton, &opt, &p, this);
+ p.drawComplexControl(QStyle::CC_ToolButton, opt);
}
/******************************************************************************
@@ -284,8 +231,10 @@ bool QDockWidgetLayout::wmSupportsNativeWindowDeco()
#if defined(Q_OS_ANDROID)
return false;
#else
- static const bool xcb = !QGuiApplication::platformName().compare(QLatin1String("xcb"), Qt::CaseInsensitive);
- return !xcb;
+ static const bool xcb = !QGuiApplication::platformName().compare("xcb"_L1, Qt::CaseInsensitive);
+ static const bool wayland =
+ QGuiApplication::platformName().startsWith("wayland"_L1, Qt::CaseInsensitive);
+ return !(xcb || wayland);
#endif
}
@@ -296,7 +245,7 @@ bool QDockWidgetLayout::wmSupportsNativeWindowDeco()
*/
bool QDockWidgetLayout::nativeWindowDeco(bool floating) const
{
- return wmSupportsNativeWindowDeco() && floating && item_list.at(QDockWidgetLayout::TitleBar) == 0;
+ return wmSupportsNativeWindowDeco() && floating && item_list.at(QDockWidgetLayout::TitleBar) == nullptr;
}
@@ -309,7 +258,7 @@ void QDockWidgetLayout::addItem(QLayoutItem*)
QLayoutItem *QDockWidgetLayout::itemAt(int index) const
{
int cnt = 0;
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
QLayoutItem *item = item_list.at(i);
if (item == nullptr)
continue;
@@ -322,7 +271,7 @@ QLayoutItem *QDockWidgetLayout::itemAt(int index) const
QLayoutItem *QDockWidgetLayout::takeAt(int index)
{
int j = 0;
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
QLayoutItem *item = item_list.at(i);
if (item == nullptr)
continue;
@@ -339,7 +288,7 @@ QLayoutItem *QDockWidgetLayout::takeAt(int index)
int QDockWidgetLayout::count() const
{
int result = 0;
- for (int i = 0; i < item_list.count(); ++i) {
+ for (int i = 0; i < item_list.size(); ++i) {
if (item_list.at(i))
++result;
}
@@ -658,13 +607,14 @@ void QDockWidgetPrivate::init()
layout->setSizeConstraint(QLayout::SetMinAndMaxSize);
QAbstractButton *button = new QDockWidgetTitleButton(q);
- button->setObjectName(QLatin1String("qt_dockwidget_floatbutton"));
- QObject::connect(button, SIGNAL(clicked()), q, SLOT(_q_toggleTopLevel()));
+ button->setObjectName("qt_dockwidget_floatbutton"_L1);
+ QObjectPrivate::connect(button, &QAbstractButton::clicked,
+ this, &QDockWidgetPrivate::toggleTopLevel);
layout->setWidgetForRole(QDockWidgetLayout::FloatButton, button);
button = new QDockWidgetTitleButton(q);
- button->setObjectName(QLatin1String("qt_dockwidget_closebutton"));
- QObject::connect(button, SIGNAL(clicked()), q, SLOT(close()));
+ button->setObjectName("qt_dockwidget_closebutton"_L1);
+ QObject::connect(button, &QAbstractButton::clicked, q, &QDockWidget::close);
layout->setWidgetForRole(QDockWidgetLayout::CloseButton, button);
font = QApplication::font("QDockWidgetTitle");
@@ -675,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();
@@ -711,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()) {
@@ -741,7 +691,7 @@ void QDockWidgetPrivate::updateButtons()
= qobject_cast<QAbstractButton*>(dwLayout->widgetForRole(QDockWidgetLayout::FloatButton));
button->setIcon(q->style()->standardIcon(QStyle::SP_TitleBarNormalButton, &opt, q));
button->setVisible(canFloat && !hideButtons);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
//: Accessible name for button undocking a dock widget (floating state)
button->setAccessibleName(QDockWidget::tr("Float"));
button->setAccessibleDescription(QDockWidget::tr("Undocks and re-attaches the dock widget"));
@@ -750,18 +700,16 @@ void QDockWidgetPrivate::updateButtons()
= qobject_cast <QAbstractButton*>(dwLayout->widgetForRole(QDockWidgetLayout::CloseButton));
button->setIcon(q->style()->standardIcon(QStyle::SP_TitleBarCloseButton, &opt, q));
button->setVisible(canClose && !hideButtons);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
//: Accessible name for button closing a dock widget
button->setAccessibleName(QDockWidget::tr("Close"));
button->setAccessibleDescription(QDockWidget::tr("Closes the dock widget"));
#endif
- q->setAttribute(Qt::WA_ContentsPropagated,
- (canFloat || canClose) && !hideButtons);
layout->invalidate();
}
-void QDockWidgetPrivate::_q_toggleTopLevel()
+void QDockWidgetPrivate::toggleTopLevel()
{
Q_Q(QDockWidget);
q->setFloating(!q->isFloating());
@@ -787,6 +735,8 @@ void QDockWidgetPrivate::initDrag(const QPoint &pos, bool nca)
state = new QDockWidgetPrivate::DragState;
state->pressPos = pos;
+ state->globalPressPos = q->mapToGlobal(pos);
+ state->widgetInitialPos = q->isFloating() ? q->pos() : q->mapToGlobal(QPoint(0, 0));
state->dragging = false;
state->widgetItem = nullptr;
state->ownWidgetItem = false;
@@ -800,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);
@@ -810,12 +760,16 @@ 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) {
- /* I have a QMainWindow parent, but I was never inserted with
+ /* Dock widget has a QMainWindow parent, but was never inserted with
QMainWindow::addDockWidget, so the QMainWindowLayout has no
- widget item for me. :( I have to create it myself, and then
- delete it if I don't get dropped into a dock area. */
+ widget item for it. It will be newly created and deleted if it doesn't
+ get dropped into a dock area. */
QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow*>(parent);
if (floatingTab && !q->isFloating())
state->widgetItem = new QDockWidgetGroupWindowItem(floatingTab);
@@ -828,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
@@ -835,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);
@@ -847,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) {
@@ -869,8 +841,21 @@ void QDockWidgetPrivate::endDrag(bool abort)
if (q->isFloating()) { // Might not be floating when dragging a QDockWidgetGroupWindow
undockedGeometry = q->geometry();
#if QT_CONFIG(tabwidget)
- tabPosition = mwLayout->tabPosition(mainWindow->dockWidgetArea(q));
+ // is the widget located within the mainwindow?
+ const Qt::DockWidgetArea area = mainWindow->dockWidgetArea(q);
+ if (area != Qt::NoDockWidgetArea) {
+ tabPosition = mwLayout->tabPosition(area);
+ } else if (auto dwgw = qobject_cast<QDockWidgetGroupWindow *>(q->parent())) {
+ // DockWidget wasn't found in one of the docks within mainwindow
+ // => derive tabPosition from parent
+ 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 {
@@ -884,15 +869,29 @@ void QDockWidgetPrivate::endDrag(bool abort)
state = nullptr;
}
+Qt::DockWidgetArea QDockWidgetPrivate::toDockWidgetArea(QInternal::DockPosition pos)
+{
+ switch (pos) {
+ case QInternal::LeftDock: return Qt::LeftDockWidgetArea;
+ case QInternal::RightDock: return Qt::RightDockWidgetArea;
+ case QInternal::TopDock: return Qt::TopDockWidgetArea;
+ case QInternal::BottomDock: return Qt::BottomDockWidgetArea;
+ default: break;
+ }
+ return Qt::NoDockWidgetArea;
+}
+
void QDockWidgetPrivate::setResizerActive(bool active)
{
Q_Q(QDockWidget);
- if (active && !resizer) {
+ const auto *dwLayout = qobject_cast<QDockWidgetLayout *>(layout);
+ if (dwLayout->nativeWindowDeco(q->isFloating()))
+ return;
+
+ if (active && !resizer)
resizer = new QWidgetResizeHandler(q);
- resizer->setMovingEnabled(false);
- }
if (resizer)
- resizer->setActive(QWidgetResizeHandler::Resize, active);
+ resizer->setEnabled(active);
}
bool QDockWidgetPrivate::isAnimating() const
@@ -920,16 +919,16 @@ bool QDockWidgetPrivate::mousePressEvent(QMouseEvent *event)
QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow*>(parent);
if (event->button() != Qt::LeftButton ||
- !titleArea.contains(event->pos()) ||
+ !titleArea.contains(event->position().toPoint()) ||
// check if the tool window is movable... do nothing if it
// is not (but allow moving if the window is floating)
(!hasFeature(this, QDockWidget::DockWidgetMovable) && !q->isFloating()) ||
- (qobject_cast<QMainWindow*>(parent) == 0 && !floatingTab) ||
+ (qobject_cast<QMainWindow*>(parent) == nullptr && !floatingTab) ||
isAnimating() || state != nullptr) {
return false;
}
- initDrag(event->pos(), false);
+ initDrag(event->position().toPoint(), false);
if (state)
state->ctrlDrag = (hasFeature(this, QDockWidget::DockWidgetFloatable) && event->modifiers() & Qt::ControlModifier) ||
@@ -949,15 +948,24 @@ bool QDockWidgetPrivate::mouseDoubleClickEvent(QMouseEvent *event)
if (!dwLayout->nativeWindowDeco()) {
QRect titleArea = dwLayout->titleArea();
- if (event->button() == Qt::LeftButton && titleArea.contains(event->pos()) &&
+ 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;
@@ -973,27 +981,75 @@ bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event)
if (!dwlayout->nativeWindowDeco()) {
if (!state->dragging
&& mwlayout->pluggingWidget == nullptr
- && (event->pos() - state->pressPos).manhattanLength()
+ && (event->position().toPoint() - state->pressPos).manhattanLength()
> QApplication::startDragDistance()) {
- startDrag();
- q->grabMouse();
- ret = true;
+
+#ifdef Q_OS_MACOS
+ if (windowHandle() && !q->isFloating()) {
+ // When using native widgets on mac, we have not yet been successful in
+ // starting a drag on an NSView that belongs to one window (QMainWindow),
+ // but continue the drag on another (QDockWidget). This is what happens if
+ // we try to make this widget floating during a drag. So as a fall back
+ // solution, we simply make this widget floating instead, when we would
+ // otherwise start a drag.
+ q->setFloating(true);
+ } else
+#endif
+ {
+ const DragScope scope = isTabbed() ? DragScope::Group : DragScope::Widget;
+ startDrag(scope);
+ q->grabMouse();
+ ret = true;
+ }
}
}
- if (state->dragging && !state->nca) {
+ if (state && state->dragging && !state->nca) {
QMargins windowMargins = q->window()->windowHandle()->frameMargins();
QPoint windowMarginOffset = QPoint(windowMargins.left(), windowMargins.top());
- QPoint pos = event->globalPos() - state->pressPos - windowMarginOffset;
+
+ // TODO maybe use QScreen API (if/when available) to simplify the below code.
+ const QScreen *orgWdgScreen = QGuiApplication::screenAt(state->widgetInitialPos);
+ const QScreen *screenFrom = QGuiApplication::screenAt(state->globalPressPos);
+ const QScreen *screenTo = QGuiApplication::screenAt(event->globalPosition().toPoint());
+ const QScreen *wdgScreen = q->screen();
+
+ QPoint pos;
+ if (Q_LIKELY(screenFrom && screenTo && wdgScreen && orgWdgScreen)) {
+ const QPoint nativeWdgOrgPos = QHighDpiScaling::mapPositionToNative(
+ state->widgetInitialPos, orgWdgScreen->handle());
+ const QPoint nativeTo = QHighDpiScaling::mapPositionToNative(
+ event->globalPosition().toPoint(), screenTo->handle());
+ const QPoint nativeFrom = QHighDpiScaling::mapPositionToNative(state->globalPressPos,
+ screenFrom->handle());
+
+ // Calculate new nativePos based on startPos + mouse delta move.
+ const QPoint nativeNewPos = nativeWdgOrgPos + (nativeTo - nativeFrom);
+ pos = QHighDpiScaling::mapPositionFromNative(nativeNewPos, wdgScreen->handle())
+ - windowMarginOffset;
+ } else {
+ // Fallback in the unlikely case that source and target screens could not be established
+ qCDebug(lcQpaDockWidgets)
+ << "QDockWidget failed to find relevant screen info. screenFrom:" << screenFrom
+ << "screenTo:" << screenTo << " wdgScreen:" << wdgScreen << "orgWdgScreen"
+ << orgWdgScreen;
+ pos = event->globalPosition().toPoint() - state->pressPos - windowMarginOffset;
+ }
+
+ // If the newly floating dock widget has got a native title bar,
+ // offset the position by the native title bar's height or width
+ const int dx = q->geometry().x() - q->x();
+ const int dy = q->geometry().y() - q->y();
+ pos.rx() += dx;
+ pos.ry() += dy;
QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow*>(parent);
if (floatingTab && !q->isFloating())
floatingTab->move(pos);
else
q->move(pos);
-
if (state && !state->ctrlDrag)
- mwlayout->hover(state->widgetItem, event->globalPos());
+ mwlayout->hover(state->widgetItem, event->globalPosition().toPoint());
ret = true;
}
@@ -1005,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
}
@@ -1033,39 +1095,38 @@ void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
switch (event->type()) {
case QEvent::NonClientAreaMouseButtonPress:
- if (!titleRect.contains(event->globalPos()))
+ if (!titleRect.contains(event->globalPosition().toPoint()))
break;
if (state != nullptr)
break;
- if (qobject_cast<QMainWindow*>(parent) == 0 && qobject_cast<QDockWidgetGroupWindow*>(parent) == 0)
+ if (qobject_cast<QMainWindow*>(parent) == nullptr && qobject_cast<QDockWidgetGroupWindow*>(parent) == nullptr)
break;
if (isAnimating())
break;
- initDrag(event->pos(), true);
+ initDrag(event->position().toPoint(), true);
if (state == nullptr)
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;
-#ifndef Q_OS_MAC
- if (state->nca) {
- endDrag();
- }
+#if !defined(Q_OS_MAC) && !defined(Q_OS_WASM)
+ if (state->nca)
+ endDrag(EndDragMode::LocationChange);
#endif
break;
case QEvent::NonClientAreaMouseButtonRelease:
-#ifdef Q_OS_MAC
+#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;
@@ -1088,7 +1149,7 @@ void QDockWidgetPrivate::moveEvent(QMoveEvent *event)
if (state == nullptr || !state->dragging || !state->nca)
return;
- if (!q->isWindow() && qobject_cast<QDockWidgetGroupWindow*>(parent) == 0)
+ if (!q->isWindow() && qobject_cast<QDockWidgetGroupWindow*>(parent) == nullptr)
return;
// When the native window frame is being dragged, all we get is these mouse
@@ -1131,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();
@@ -1152,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);
@@ -1224,15 +1289,18 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect
on whether it is docked; a docked QDockWidget has no frame and a smaller title
bar.
- \sa QMainWindow, {Dock Widgets Example}
+ \note On macOS, if the QDockWidget has a native window handle (for example,
+ if winId() is called on it or the child widget), then due to a limitation it will not be
+ 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
*/
/*!
\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
@@ -1242,11 +1310,6 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect
bar on its left side. This can be used to
increase the amount of vertical space in
a QMainWindow.
- \value AllDockWidgetFeatures (Deprecated) The dock widget can be closed, moved,
- and floated. Since new features might be added in future
- releases, the look and behavior of dock widgets might
- change if you use this flag. Please specify individual
- flags instead.
\value NoDockWidgetFeatures The dock widget cannot be closed, moved,
or floated.
@@ -1369,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.
@@ -1385,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.
@@ -1440,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);
@@ -1467,14 +1539,20 @@ 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 */
void QDockWidget::paintEvent(QPaintEvent *event)
{
- Q_UNUSED(event)
+ Q_UNUSED(event);
Q_D(QDockWidget);
QDockWidgetLayout *layout
@@ -1488,7 +1566,7 @@ void QDockWidget::paintEvent(QPaintEvent *event)
// when not floating.
if (isFloating()) {
QStyleOptionFrame framOpt;
- framOpt.init(this);
+ framOpt.initFrom(this);
p.drawPrimitive(QStyle::PE_FrameDockWidget, framOpt);
}
@@ -1544,7 +1622,7 @@ bool QDockWidget::event(QEvent *event)
bool onTop = false;
if (win != nullptr) {
const QObjectList &siblings = win->children();
- onTop = siblings.count() > 0 && siblings.last() == (QObject*)this;
+ onTop = siblings.size() > 0 && siblings.last() == (QObject*)this;
}
#if QT_CONFIG(tabbar)
if (!isFloating() && layout != nullptr && onTop)
@@ -1596,8 +1674,8 @@ bool QDockWidget::event(QEvent *event)
// Usually the window won't get resized while it's being moved, but it can happen,
// for example on Windows when moving to a screen with bigger scale factor
- // (and Qt::AA_EnableHighDpiScaling is enabled). If that happens we should
- // update state->pressPos, otherwise it will be outside the window when the window shrinks.
+ // If that happens we should update state->pressPos, otherwise it will be outside
+ // the window when the window shrinks.
if (d->state && d->state->dragging)
d->recalculatePressPos(static_cast<QResizeEvent*>(event));
break;
@@ -1658,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.
*/
/*!
@@ -1674,8 +1756,8 @@ QAction * QDockWidget::toggleViewAction() const
\since 4.3
Sets an arbitrary \a widget as the dock widget's title bar. If \a widget
- is 0, any custom title bar widget previously set on the dock widget is
- removed, but not deleted, and the default title bar will be used
+ is \nullptr, any custom title bar widget previously set on the dock widget
+ is removed, but not deleted, and the default title bar will be used
instead.
If a title bar widget is set, QDockWidget will not use native window
@@ -1739,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 b53a991dae..2efa1d3c2f 100644
--- a/src/widgets/widgets/qdockwidget.h
+++ b/src/widgets/widgets/qdockwidget.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDYNAMICDOCKWIDGET_H
#define QDYNAMICDOCKWIDGET_H
@@ -56,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)
@@ -78,7 +42,6 @@ public:
DockWidgetVerticalTitleBar = 0x08,
DockWidgetFeatureMask = 0x0f,
- AllDockWidgetFeatures = DockWidgetClosable|DockWidgetMovable|DockWidgetFloatable, // ### Qt 6: remove
NoDockWidgetFeatures = 0x00,
Reserved = 0xff
@@ -101,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
@@ -109,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:
@@ -117,13 +84,11 @@ protected:
void closeEvent(QCloseEvent *event) override;
void paintEvent(QPaintEvent *event) override;
bool event(QEvent *event) override;
- void initStyleOption(QStyleOptionDockWidget *option) const;
+ virtual void initStyleOption(QStyleOptionDockWidget *option) const;
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 e663ec4c2d..fa936599c6 100644
--- a/src/widgets/widgets/qdockwidget_p.h
+++ b/src/widgets/widgets/qdockwidget_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDYNAMICDOCKWIDGET_P_H
#define QDYNAMICDOCKWIDGET_P_H
@@ -77,6 +41,8 @@ class QDockWidgetPrivate : public QWidgetPrivate
struct DragState {
QPoint pressPos;
+ QPoint globalPressPos;
+ QPoint widgetInitialPos;
bool dragging;
QLayoutItem *widgetItem;
bool ownWidgetItem;
@@ -85,11 +51,22 @@ 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);
#if QT_CONFIG(tabwidget)
QTabWidget::TabPosition tabPosition = QTabWidget::North;
@@ -119,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);
@@ -129,6 +106,7 @@ public:
void setResizerActive(bool active);
bool isAnimating() const;
+ bool isTabbed() const;
private:
QWidgetResizeHandler *resizer = nullptr;
@@ -172,7 +150,7 @@ public:
bool verticalTitleBar;
private:
- QVector<QLayoutItem*> item_list;
+ QList<QLayoutItem *> item_list;
QRect _titleArea;
};
@@ -201,11 +179,7 @@ inline QLayoutItem *QDockWidgetItem::dockWidgetChildItem() const
inline QDockWidgetLayout *QDockWidgetItem::dockWidgetLayout() const
{
-#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
- QWidget *w = const_cast<QDockWidgetItem*>(this)->widget();
-#else
QWidget *w = widget();
-#endif
if (w != nullptr)
return qobject_cast<QDockWidgetLayout*>(w->layout());
return nullptr;
diff --git a/src/widgets/widgets/qeffects.cpp b/src/widgets/widgets/qeffects.cpp
index ee4095cb36..74ac24a2b0 100644
--- a/src/widgets/widgets/qeffects.cpp
+++ b/src/widgets/widgets/qeffects.cpp
@@ -1,45 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qapplication.h"
-#include "qdesktopwidget.h"
+#include "qdebug.h"
#include "qeffects_p.h"
+#include "qelapsedtimer.h"
#include "qevent.h"
#include "qimage.h"
#include "qpainter.h"
@@ -47,10 +12,10 @@
#include "qpixmap.h"
#include "qpointer.h"
#include "qtimer.h"
-#include "qelapsedtimer.h"
-#include "qdebug.h"
+#include "qwidget.h"
+#include "private/qwidget_p.h"
+#include "qwindow.h"
-#include <private/qdesktopwidget_p.h>
QT_BEGIN_NAMESPACE
@@ -98,12 +63,10 @@ static QAlphaWidget* q_blend = nullptr;
/*
Constructs a QAlphaWidget.
*/
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED // ### Qt 6: Find a replacement for QDesktopWidget::screen()
QAlphaWidget::QAlphaWidget(QWidget* w, Qt::WindowFlags f)
- : QWidget(QApplication::desktop()->screen(QDesktopWidgetPrivate::screenNumber(w)), f)
+ : QWidget(nullptr, f)
{
-QT_WARNING_POP
+ QWidgetPrivate::get(this)->setScreen(w->screen());
#ifndef Q_OS_WIN
setEnabled(false);
#endif
@@ -152,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
@@ -165,7 +128,7 @@ void QAlphaWidget::run(int time)
resize(widget->size().width(), widget->size().height());
frontImage = widget->grab().toImage();
- backImage = QGuiApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId(),
+ backImage = QGuiApplication::primaryScreen()->grabWindow(0,
widget->geometry().x(), widget->geometry().y(),
widget->geometry().width(), widget->geometry().height()).toImage();
@@ -175,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;
@@ -208,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
@@ -305,7 +268,7 @@ void QAlphaWidget::alphaBlend()
const int sw = frontImage.width();
const int sh = frontImage.height();
- const int bpl = frontImage.bytesPerLine();
+ const qsizetype bpl = frontImage.bytesPerLine();
switch(frontImage.depth()) {
case 32:
{
@@ -329,6 +292,7 @@ void QAlphaWidget::alphaBlend()
back_data += bpl;
front_data += bpl;
}
+ break;
}
default:
break;
@@ -385,6 +349,7 @@ static QRollEffect* q_roll = nullptr;
QRollEffect::QRollEffect(QWidget* w, Qt::WindowFlags f, DirFlags orient)
: QWidget(nullptr, f), orientation(orient)
{
+ QWidgetPrivate::get(this)->setScreen(w->screen());
#ifndef Q_OS_WIN
setEnabled(false);
#endif
@@ -464,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));
@@ -499,14 +464,12 @@ void QRollEffect::scroll()
+ (2 * totalWidth * (elapsed%duration) + duration)
/ (2 * duration);
// equiv. to int((totalWidth*elapsed) / duration + 0.5)
- done = (currentWidth >= totalWidth);
}
if (currentHeight != totalHeight) {
currentHeight = totalHeight * (elapsed/duration)
+ (2 * totalHeight * (elapsed%duration) + duration)
/ (2 * duration);
// equiv. to int((totalHeight*elapsed) / duration + 0.5)
- done = (currentHeight >= totalHeight);
}
done = (currentHeight >= totalHeight) &&
(currentWidth >= totalWidth);
@@ -555,7 +518,7 @@ void QRollEffect::scroll()
}
}
-/*!
+/*
Scroll widget \a w in \a time ms. \a orient may be 1 (vertical), 2
(horizontal) or 3 (diagonal).
*/
@@ -578,7 +541,7 @@ void qScrollEffect(QWidget* w, QEffects::DirFlags orient, int time)
q_roll->run(time);
}
-/*!
+/*
Fade in widget \a w in \a time ms.
*/
void qFadeEffect(QWidget* w, int time)
diff --git a/src/widgets/widgets/qeffects_p.h b/src/widgets/widgets/qeffects_p.h
index 92f459651f..794ef030a0 100644
--- a/src/widgets/widgets/qeffects_p.h
+++ b/src/widgets/widgets/qeffects_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QEFFECTS_P_H
#define QEFFECTS_P_H
diff --git a/src/widgets/widgets/qfocusframe.cpp b/src/widgets/widgets/qfocusframe.cpp
index 4d64c24db3..d66faedbac 100644
--- a/src/widgets/widgets/qfocusframe.cpp
+++ b/src/widgets/widgets/qfocusframe.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qfocusframe.h"
#include "qstyle.h"
@@ -86,20 +50,22 @@ void QFocusFramePrivate::updateSize()
if (!widget)
return;
- int vmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameVMargin),
- hmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin);
+ QStyleOption opt;
+ q->initStyleOption(&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);
QRect geom(pos.x()-hmargin, pos.y()-vmargin,
widget->width()+(hmargin*2), widget->height()+(vmargin*2));
- if(q->geometry() == geom)
+ if (q->geometry() == geom)
return;
q->setGeometry(geom);
+
+ opt.rect = q->rect();
QStyleHintReturnMask mask;
- QStyleOption opt;
- q->initStyleOption(&opt);
if (q->style()->styleHint(QStyle::SH_FocusFrame_Mask, &opt, q, &mask))
q->setMask(mask.region);
}
@@ -263,8 +229,8 @@ QFocusFrame::paintEvent(QPaintEvent *)
QStylePainter p(this);
QStyleOption option;
initStyleOption(&option);
- int vmargin = style()->pixelMetric(QStyle::PM_FocusFrameVMargin);
- int hmargin = style()->pixelMetric(QStyle::PM_FocusFrameHMargin);
+ 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);
@@ -277,7 +243,7 @@ bool
QFocusFrame::eventFilter(QObject *o, QEvent *e)
{
Q_D(QFocusFrame);
- if(o == d->widget) {
+ if (o == d->widget) {
switch(e->type()) {
case QEvent::Move:
case QEvent::Resize:
diff --git a/src/widgets/widgets/qfocusframe.h b/src/widgets/widgets/qfocusframe.h
index 73d5b42bd8..a281b0dbe3 100644
--- a/src/widgets/widgets/qfocusframe.h
+++ b/src/widgets/widgets/qfocusframe.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFOCUSFRAME_H
#define QFOCUSFRAME_H
@@ -64,7 +28,7 @@ protected:
bool eventFilter(QObject *, QEvent *) override;
void paintEvent(QPaintEvent *) override;
- void initStyleOption(QStyleOption *option) const;
+ virtual void initStyleOption(QStyleOption *option) const;
private:
Q_DECLARE_PRIVATE(QFocusFrame)
diff --git a/src/widgets/widgets/qfontcombobox.cpp b/src/widgets/widgets/qfontcombobox.cpp
index 4a99b0f962..c80687c7ed 100644
--- a/src/widgets/widgets/qfontcombobox.cpp
+++ b/src/widgets/widgets/qfontcombobox.cpp
@@ -1,57 +1,24 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qfontcombobox.h"
+#include <qabstractitemdelegate.h>
+#include <qaccessible.h>
#include <qstringlistmodel.h>
-#include <qitemdelegate.h>
#include <qlistview.h>
#include <qpainter.h>
#include <qevent.h>
#include <qapplication.h>
#include <private/qcombobox_p.h>
-#include <QDesktopWidget>
-#include <private/qdesktopwidget_p.h>
#include <qdebug.h>
+#include <array>
+
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
static QFontDatabase::WritingSystem writingSystemFromScript(QLocale::Script script)
{
switch (script) {
@@ -136,8 +103,8 @@ static QFontDatabase::WritingSystem writingSystemFromLocale()
static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool *hasLatin)
{
- QList<QFontDatabase::WritingSystem> writingSystems = QFontDatabase().writingSystems(font.family());
-// qDebug() << font.family() << writingSystems;
+ 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
writingSystems.removeOne(QFontDatabase::Vietnamese);
@@ -168,23 +135,39 @@ static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool
return system;
}
- if (writingSystems.count() == 1 && system > QFontDatabase::Cyrillic)
+ if (writingSystems.size() == 1 && system > QFontDatabase::Cyrillic)
return system;
- if (writingSystems.count() <= 2 && system > QFontDatabase::Armenian && system < QFontDatabase::Vietnamese)
+ if (writingSystems.size() <= 2 && system > QFontDatabase::Armenian && system < QFontDatabase::Vietnamese)
return system;
- if (writingSystems.count() <= 5 && system >= QFontDatabase::SimplifiedChinese && system <= QFontDatabase::Korean)
+ if (writingSystems.size() <= 5 && system >= QFontDatabase::SimplifiedChinese && system <= QFontDatabase::Korean)
return system;
return QFontDatabase::Any;
}
+class QFontComboBoxPrivate : public QComboBoxPrivate
+{
+public:
+ 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 updateModel();
+ void currentChanged(const QString &);
+
+ Q_DECLARE_PUBLIC(QFontComboBox)
+};
+
class QFontFamilyDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
- explicit QFontFamilyDelegate(QObject *parent);
+ explicit QFontFamilyDelegate(QObject *parent, QFontComboBoxPrivate *comboP);
// painting
void paint(QPainter *painter,
@@ -197,13 +180,15 @@ public:
const QIcon truetype;
const QIcon bitmap;
QFontDatabase::WritingSystem writingSystem;
+ QFontComboBoxPrivate *comboPrivate;
};
-QFontFamilyDelegate::QFontFamilyDelegate(QObject *parent)
+QFontFamilyDelegate::QFontFamilyDelegate(QObject *parent, QFontComboBoxPrivate *comboP)
: QAbstractItemDelegate(parent),
truetype(QStringLiteral(":/qt-project.org/styles/commonstyle/images/fonttruetype-16.png")),
bitmap(QStringLiteral(":/qt-project.org/styles/commonstyle/images/fontbitmap-16.png")),
- writingSystem(QFontDatabase::Any)
+ writingSystem(QFontDatabase::Any),
+ comboPrivate(comboP)
{
}
@@ -215,13 +200,15 @@ void QFontFamilyDelegate::paint(QPainter *painter,
QFont font(option.font);
font.setPointSize(QFontInfo(font).pointSize() * 3 / 2);
QFont font2 = font;
- font2.setFamily(text);
+ font2.setFamilies(QStringList{text});
bool hasLatin;
QFontDatabase::WritingSystem system = writingSystemForFont(font2, &hasLatin);
if (hasLatin)
font = font2;
+ font = comboPrivate->displayFontForFontFamily.value(text, font);
+
QRect r = option.rect;
if (option.state & QStyle::State_Selected) {
@@ -233,7 +220,7 @@ void QFontFamilyDelegate::paint(QPainter *painter,
}
const QIcon *icon = &bitmap;
- if (QFontDatabase().isSmoothlyScalable(text)) {
+ if (QFontDatabase::isSmoothlyScalable(text)) {
icon = &truetype;
}
const QSize actualSize = icon->actualSize(r.size());
@@ -266,10 +253,11 @@ void QFontFamilyDelegate::paint(QPainter *painter,
if (writingSystem != QFontDatabase::Any)
system = writingSystem;
- if (system != QFontDatabase::Any) {
- int w = painter->fontMetrics().horizontalAdvance(text + QLatin1String(" "));
+ const QString sampleText = comboPrivate->sampleTextForFontFamily.value(text, comboPrivate->sampleTextForWritingSystem.value(system));
+ if (system != QFontDatabase::Any || !sampleText.isEmpty()) {
+ int w = painter->fontMetrics().horizontalAdvance(text + " "_L1);
painter->setFont(font2);
- QString sample = QFontDatabase().writingSystemSample(system);
+ const QString sample = !sampleText.isEmpty() ? sampleText : QFontDatabase::writingSystemSample(system);
if (option.direction == Qt::RightToLeft)
r.setRight(r.right() - w);
else
@@ -288,31 +276,20 @@ QSize QFontFamilyDelegate::sizeHint(const QStyleOptionViewItem &option,
{
QString text = index.data(Qt::DisplayRole).toString();
QFont font(option.font);
-// font.setFamily(text);
+// font.setFamilies(QStringList{text});
font.setPointSize(QFontInfo(font).pointSize() * 3/2);
QFontMetrics fontMetrics(font);
return QSize(fontMetrics.horizontalAdvance(text), fontMetrics.height());
}
-class QFontComboBoxPrivate : public QComboBoxPrivate
+void QFontComboBoxPrivate::updateModel()
{
-public:
- inline QFontComboBoxPrivate() { filters = QFontComboBox::AllFonts; }
-
- QFontComboBox::FontFilters filters;
- QFont currentFont;
-
- void _q_updateModel();
- void _q_currentChanged(const QString &);
-
- Q_DECLARE_PUBLIC(QFontComboBox)
-};
+ Q_Q(QFontComboBox);
+ if (QCoreApplication::closingDown())
+ return;
-void QFontComboBoxPrivate::_q_updateModel()
-{
- Q_Q(QFontComboBox);
const int scalableMask = (QFontComboBox::ScalableFonts | QFontComboBox::NonScalableFonts);
const int spacingMask = (QFontComboBox::ProportionalFonts | QFontComboBox::MonospacedFonts);
@@ -322,30 +299,28 @@ void QFontComboBoxPrivate::_q_updateModel()
QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(q->view()->itemDelegate());
QFontDatabase::WritingSystem system = delegate ? delegate->writingSystem : QFontDatabase::Any;
- QFontDatabase fdb;
- QStringList list = fdb.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 (fdb.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) != fdb.isSmoothlyScalable(list.at(i)))
+ if (bool(filters & QFontComboBox::ScalableFonts) != QFontDatabase::isSmoothlyScalable(family))
continue;
}
if ((filters & spacingMask) && (filters & spacingMask) != spacingMask) {
- if (bool(filters & QFontComboBox::MonospacedFonts) != fdb.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() + QLatin1String(" [")))
- offset = result.count() - 1;
+ 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
@@ -353,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);
@@ -367,11 +349,12 @@ void QFontComboBoxPrivate::_q_updateModel()
}
-void QFontComboBoxPrivate::_q_currentChanged(const QString &text)
+void QFontComboBoxPrivate::currentChanged(const QString &text)
{
Q_Q(QFontComboBox);
- if (currentFont.family() != text) {
- currentFont.setFamily(text);
+ const QStringList families = currentFont.families();
+ if (families.isEmpty() || families.first() != text) {
+ currentFont.setFamilies(QStringList{text});
emit q->currentFontChanged(currentFont);
}
}
@@ -406,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
*/
/*!
@@ -421,17 +404,18 @@ QFontComboBox::QFontComboBox(QWidget *parent)
QStringListModel *m = new QStringListModel(this);
setModel(m);
- setItemDelegate(new QFontFamilyDelegate(this));
+ setItemDelegate(new QFontFamilyDelegate(this, d));
QListView *lview = qobject_cast<QListView*>(view());
if (lview)
lview->setUniformItemSizes(true);
setWritingSystem(QFontDatabase::Any);
- connect(this, SIGNAL(currentIndexChanged(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),
+ };
}
@@ -440,6 +424,9 @@ QFontComboBox::QFontComboBox(QWidget *parent)
*/
QFontComboBox::~QFontComboBox()
{
+ Q_D(const QFontComboBox);
+ for (const QMetaObject::Connection &connection : d->connections)
+ QObject::disconnect(connection);
}
/*!
@@ -458,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
@@ -494,7 +481,7 @@ void QFontComboBox::setFontFilters(FontFilters filters)
{
Q_D(QFontComboBox);
d->filters = filters;
- d->_q_updateModel();
+ d->updateModel();
}
QFontComboBox::FontFilters QFontComboBox::fontFilters() const
@@ -520,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);
}
}
@@ -545,7 +532,7 @@ bool QFontComboBox::event(QEvent *e)
QListView *lview = qobject_cast<QListView*>(view());
if (lview) {
lview->window()->setFixedWidth(qMin(width() * 5 / 3,
- QDesktopWidgetPrivate::availableGeometry(lview).width()));
+ QWidgetPrivate::availableScreenGeometry(lview).width()));
}
}
return QComboBox::event(e);
@@ -558,10 +545,81 @@ QSize QFontComboBox::sizeHint() const
{
QSize sz = QComboBox::sizeHint();
QFontMetrics fm(font());
- sz.setWidth(fm.horizontalAdvance(QLatin1Char('m'))*14);
+ sz.setWidth(fm.horizontalAdvance(u'm') * 14);
return sz;
}
+/*!
+ Sets the \a sampleText to show after the font name (when the combo is open) for a given \a writingSystem.
+
+ The sample text given with setSampleTextForFont() has priority.
+
+ \since 6.3
+*/
+void QFontComboBox::setSampleTextForSystem(QFontDatabase::WritingSystem writingSystem, const QString &sampleText)
+{
+ Q_D(QFontComboBox);
+ d->sampleTextForWritingSystem[writingSystem] = sampleText;
+}
+
+
+/*!
+ Returns the sample text to show after the font name (when the combo is open) for a given \a writingSystem.
+
+ \since 6.3
+*/
+QString QFontComboBox::sampleTextForSystem(QFontDatabase::WritingSystem writingSystem) const
+{
+ Q_D(const QFontComboBox);
+ return d->sampleTextForWritingSystem.value(writingSystem);
+}
+
+/*!
+ Sets the \a sampleText to show after the font name (when the combo is open) for a given \a fontFamily.
+
+ The sample text given with this function has priority over the one set with setSampleTextForSystem().
+
+ \since 6.3
+*/
+void QFontComboBox::setSampleTextForFont(const QString &fontFamily, const QString &sampleText)
+{
+ Q_D(QFontComboBox);
+ d->sampleTextForFontFamily[fontFamily] = sampleText;
+}
+
+/*!
+ Returns the sample text to show after the font name (when the combo is open) for a given \a fontFamily.
+
+ \since 6.3
+*/
+QString QFontComboBox::sampleTextForFont(const QString &fontFamily) const
+{
+ Q_D(const QFontComboBox);
+ return d->sampleTextForFontFamily.value(fontFamily);
+}
+
+/*!
+ Sets the \a font to be used to display a given \a fontFamily (when the combo is open).
+
+ \since 6.3
+*/
+void QFontComboBox::setDisplayFont(const QString &fontFamily, const QFont &font)
+{
+ Q_D(QFontComboBox);
+ d->displayFontForFontFamily[fontFamily] = font;
+}
+
+/*!
+ Returns the font (if set) to be used to display a given \a fontFamily (when the combo is open).
+
+ \since 6.3
+*/
+std::optional<QFont> QFontComboBox::displayFont(const QString &fontFamily) const
+{
+ Q_D(const QFontComboBox);
+ return d->displayFontForFontFamily.value(fontFamily, {});
+}
+
QT_END_NAMESPACE
#include "qfontcombobox.moc"
diff --git a/src/widgets/widgets/qfontcombobox.h b/src/widgets/widgets/qfontcombobox.h
index 6c1871dd2d..9c5432b332 100644
--- a/src/widgets/widgets/qfontcombobox.h
+++ b/src/widgets/widgets/qfontcombobox.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFONTCOMBOBOX_H
#define QFONTCOMBOBOX_H
@@ -80,6 +44,15 @@ public:
QFont currentFont() const;
QSize sizeHint() const override;
+ void setSampleTextForSystem(QFontDatabase::WritingSystem writingSystem, const QString &sampleText);
+ QString sampleTextForSystem(QFontDatabase::WritingSystem writingSystem) const;
+
+ void setSampleTextForFont(const QString &fontFamily, const QString &sampleText);
+ QString sampleTextForFont(const QString &fontFamily) const;
+
+ void setDisplayFont(const QString &fontFamily, const QFont &font);
+ std::optional<QFont> displayFont(const QString &fontFamily) const;
+
public Q_SLOTS:
void setCurrentFont(const QFont &f);
@@ -92,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/qframe.cpp b/src/widgets/widgets/qframe.cpp
index 1661c5c881..db8dc20be2 100644
--- a/src/widgets/widgets/qframe.cpp
+++ b/src/widgets/widgets/qframe.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qframe.h"
#include "qbitmap.h"
@@ -44,6 +8,7 @@
#include "qpainter.h"
#include "qstyle.h"
#include "qstyleoption.h"
+#include "qstylepainter.h"
#include "qapplication.h"
#include "qframe_p.h"
@@ -463,9 +428,9 @@ int QFrame::frameWidth() const
\brief the frame's rectangle
The frame's rectangle is the rectangle the frame is drawn in. By
- default, this is the entire widget. Setting the rectangle does
- does \e not cause a widget update. The frame rectangle is
- automatically adjusted when the widget changes size.
+ default, this is the entire widget. Setting the rectangle \e doesn't
+ cause a widget update. The frame rectangle is automatically adjusted
+ when the widget changes size.
If you set the rectangle to a null rectangle (for example,
QRect(0, 0, 0, 0)), then the resulting frame rectangle is
@@ -511,8 +476,8 @@ QSize QFrame::sizeHint() const
void QFrame::paintEvent(QPaintEvent *)
{
- QPainter paint(this);
- drawFrame(&paint);
+ QStylePainter p(this);
+ drawFrame(&p);
}
/*!
diff --git a/src/widgets/widgets/qframe.h b/src/widgets/widgets/qframe.h
index 595dfa929d..0c8a6f81d1 100644
--- a/src/widgets/widgets/qframe.h
+++ b/src/widgets/widgets/qframe.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFRAME_H
#define QFRAME_H
@@ -116,13 +80,15 @@ protected:
protected:
QFrame(QFramePrivate &dd, QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
- void initStyleOption(QStyleOptionFrame *option) const;
+ virtual void initStyleOption(QStyleOptionFrame *option) const;
private:
Q_DISABLE_COPY(QFrame)
Q_DECLARE_PRIVATE(QFrame)
};
+Q_DECLARE_MIXED_ENUM_OPERATORS_SYMMETRIC(int, QFrame::Shape, QFrame::Shadow)
+
QT_END_NAMESPACE
#endif // QFRAME_H
diff --git a/src/widgets/widgets/qframe_p.h b/src/widgets/widgets/qframe_p.h
index e3c101e87c..a45f5735dd 100644
--- a/src/widgets/widgets/qframe_p.h
+++ b/src/widgets/widgets/qframe_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QFRAME_P_H
#define QFRAME_P_H
@@ -57,8 +21,7 @@
QT_BEGIN_NAMESPACE
-// ### unexport this class when and if QAbstractScrollAreaPrivate is unexported
-class Q_WIDGETS_EXPORT QFramePrivate : public QWidgetPrivate
+class QFramePrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QFrame)
public:
diff --git a/src/widgets/widgets/qgroupbox.cpp b/src/widgets/widgets/qgroupbox.cpp
index 048fe42948..eb37599382 100644
--- a/src/widgets/widgets/qgroupbox.cpp
+++ b/src/widgets/widgets/qgroupbox.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qgroupbox.h"
@@ -50,12 +14,15 @@
#include "qstyle.h"
#include "qstyleoption.h"
#include "qstylepainter.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
#include <private/qwidget_p.h>
+#include <private/qguiapplication_p.h>
+#include <qpa/qplatformtheme.h>
#include "qdebug.h"
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
@@ -166,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
*/
@@ -234,7 +201,7 @@ void QGroupBox::setTitle(const QString &title)
update();
updateGeometry();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleEvent event(this, QAccessible::NameChanged);
QAccessible::updateAccessibility(&event);
#endif
@@ -339,7 +306,7 @@ bool QGroupBox::event(QEvent *e)
case QEvent::HoverEnter:
case QEvent::HoverMove: {
QStyle::SubControl control = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
- static_cast<QHoverEvent *>(e)->pos(),
+ static_cast<QHoverEvent *>(e)->position().toPoint(),
this);
bool oldHover = d->hover;
d->hover = d->checkable && (control == QStyle::SC_GroupBoxLabel || control == QStyle::SC_GroupBoxCheckBox);
@@ -360,7 +327,10 @@ bool QGroupBox::event(QEvent *e)
return true;
case QEvent::KeyPress: {
QKeyEvent *k = static_cast<QKeyEvent*>(e);
- if (!k->isAutoRepeat() && (k->key() == Qt::Key_Select || k->key() == Qt::Key_Space)) {
+ const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()
+ ->themeHint(QPlatformTheme::ButtonPressKeys)
+ .value<QList<Qt::Key>>();
+ if (!k->isAutoRepeat() && buttonPressKeys.contains(k->key())) {
d->pressedControl = QStyle::SC_GroupBoxCheckBox;
update(style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this));
return true;
@@ -369,7 +339,10 @@ bool QGroupBox::event(QEvent *e)
}
case QEvent::KeyRelease: {
QKeyEvent *k = static_cast<QKeyEvent*>(e);
- if (!k->isAutoRepeat() && (k->key() == Qt::Key_Select || k->key() == Qt::Key_Space)) {
+ const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()
+ ->themeHint(QPlatformTheme::ButtonPressKeys)
+ .value<QList<Qt::Key>>();
+ if (!k->isAutoRepeat() && buttonPressKeys.contains(k->key())) {
bool toggle = (d->pressedControl == QStyle::SC_GroupBoxLabel
|| d->pressedControl == QStyle::SC_GroupBoxCheckBox);
d->pressedControl = QStyle::SC_None;
@@ -488,12 +461,12 @@ QSize QGroupBox::minimumSizeHint() const
QFontMetrics metrics(fontMetrics());
- int baseWidth = metrics.horizontalAdvance(d->title) + metrics.horizontalAdvance(QLatin1Char(' '));
+ int baseWidth = metrics.horizontalAdvance(d->title) + metrics.horizontalAdvance(u' ');
int baseHeight = metrics.height();
if (d->checkable) {
- baseWidth += style()->pixelMetric(QStyle::PM_IndicatorWidth);
- baseWidth += style()->pixelMetric(QStyle::PM_CheckBoxLabelSpacing);
- baseHeight = qMax(baseHeight, style()->pixelMetric(QStyle::PM_IndicatorHeight));
+ 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);
@@ -637,7 +610,7 @@ void QGroupBox::setChecked(bool b)
update();
d->checked = b;
d->_q_setChildrenEnabled(b);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessible::State st;
st.checked = true;
QAccessibleStateChangeEvent e(this, st);
@@ -702,7 +675,7 @@ void QGroupBox::mousePressEvent(QMouseEvent *event)
QStyleOptionGroupBox box;
initStyleOption(&box);
d->pressedControl = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
- event->pos(), this);
+ event->position().toPoint(), this);
if (d->checkable && (d->pressedControl & (QStyle::SC_GroupBoxCheckBox | QStyle::SC_GroupBoxLabel))) {
d->overCheckBox = true;
update(style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this));
@@ -718,7 +691,7 @@ void QGroupBox::mouseMoveEvent(QMouseEvent *event)
QStyleOptionGroupBox box;
initStyleOption(&box);
QStyle::SubControl pressed = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
- event->pos(), this);
+ event->position().toPoint(), this);
bool oldOverCheckBox = d->overCheckBox;
d->overCheckBox = (pressed == QStyle::SC_GroupBoxCheckBox || pressed == QStyle::SC_GroupBoxLabel);
if (d->checkable && (d->pressedControl == QStyle::SC_GroupBoxCheckBox || d->pressedControl == QStyle::SC_GroupBoxLabel)
@@ -744,7 +717,7 @@ void QGroupBox::mouseReleaseEvent(QMouseEvent *event)
QStyleOptionGroupBox box;
initStyleOption(&box);
QStyle::SubControl released = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
- event->pos(), this);
+ event->position().toPoint(), this);
bool toggle = d->checkable && (released == QStyle::SC_GroupBoxLabel
|| released == QStyle::SC_GroupBoxCheckBox);
d->pressedControl = QStyle::SC_None;
diff --git a/src/widgets/widgets/qgroupbox.h b/src/widgets/widgets/qgroupbox.h
index bd8394b43b..dd4a5b8a93 100644
--- a/src/widgets/widgets/qgroupbox.h
+++ b/src/widgets/widgets/qgroupbox.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QGROUPBOX_H
#define QGROUPBOX_H
@@ -94,7 +58,7 @@ protected:
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
- void initStyleOption(QStyleOptionGroupBox *option) const;
+ virtual void initStyleOption(QStyleOptionGroupBox *option) const;
private:
diff --git a/src/widgets/widgets/qkeysequenceedit.cpp b/src/widgets/widgets/qkeysequenceedit.cpp
index b63b0b4d72..65ed7a465a 100644
--- a/src/widgets/widgets/qkeysequenceedit.cpp
+++ b/src/widgets/widgets/qkeysequenceedit.cpp
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2013 Ivan Komissarov.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2013 Ivan Komissarov.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qkeysequenceedit.h"
#include "qkeysequenceedit_p.h"
@@ -47,7 +11,7 @@
QT_BEGIN_NAMESPACE
-Q_STATIC_ASSERT(QKeySequencePrivate::MaxKeyCount == 4); // assumed by the code around here
+static_assert(QKeySequencePrivate::MaxKeyCount == 4); // assumed by the code around here
void QKeySequenceEditPrivate::init()
{
@@ -55,15 +19,23 @@ void QKeySequenceEditPrivate::init()
lineEdit = new QLineEdit(q);
lineEdit->setObjectName(QStringLiteral("qt_keysequenceedit_lineedit"));
+ lineEdit->setClearButtonEnabled(false);
+ 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();
+ });
+
keyNum = 0;
prevKey = -1;
releaseTimer = 0;
+ finishingKeyCombinations = {Qt::Key_Tab, Qt::Key_Backtab};
QVBoxLayout *layout = new QVBoxLayout(q);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(lineEdit);
- key[0] = key[1] = key[2] = key[3] = 0;
+ std::fill_n(key, QKeySequencePrivate::MaxKeyCount, QKeyCombination::fromCombined(0));
lineEdit->setFocusProxy(q);
lineEdit->installEventFilter(q);
@@ -73,8 +45,6 @@ void QKeySequenceEditPrivate::init()
q->setFocusPolicy(Qt::StrongFocus);
q->setAttribute(Qt::WA_MacShowFocusRect, true);
q->setAttribute(Qt::WA_InputMethodEnabled, false);
-
- // TODO: add clear button
}
int QKeySequenceEditPrivate::translateModifiers(Qt::KeyboardModifiers state, const QString &text)
@@ -167,6 +137,9 @@ QKeySequenceEdit::~QKeySequenceEdit()
\brief This property contains the currently chosen key sequence.
The shortcut can be changed by the user or via setter function.
+
+ \note If the QKeySequence is longer than the maximumSequenceLength
+ property, the key sequence is truncated.
*/
QKeySequence QKeySequenceEdit::keySequence() const
{
@@ -175,6 +148,89 @@ QKeySequence QKeySequenceEdit::keySequence() const
return d->keySequence;
}
+/*!
+ \property QKeySequenceEdit::clearButtonEnabled
+ \brief Whether the key sequence edit displays a clear button when it is not
+ empty.
+
+ If enabled, the key sequence edit displays a trailing \e clear button when
+ it contains some text, otherwise the line edit does not show a clear button
+ (the default).
+
+ \since 6.4
+*/
+void QKeySequenceEdit::setClearButtonEnabled(bool enable)
+{
+ Q_D(QKeySequenceEdit);
+
+ d->lineEdit->setClearButtonEnabled(enable);
+}
+
+bool QKeySequenceEdit::isClearButtonEnabled() const
+{
+ Q_D(const QKeySequenceEdit);
+
+ return d->lineEdit->isClearButtonEnabled();
+}
+
+/*!
+ \property QKeySequenceEdit::maximumSequenceLength
+ \brief The maximum sequence length.
+
+ 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
+*/
+qsizetype QKeySequenceEdit::maximumSequenceLength() const
+{
+ Q_D(const QKeySequenceEdit);
+ return d->maximumSequenceLength;
+}
+
+void QKeySequenceEdit::setMaximumSequenceLength(qsizetype count)
+{
+ Q_D(QKeySequenceEdit);
+
+ if (count < 1 || count > QKeySequencePrivate::MaxKeyCount) {
+ qWarning("QKeySequenceEdit: maximumSequenceLength %lld is out of range (1..%d)",
+ qlonglong(count), QKeySequencePrivate::MaxKeyCount);
+ return;
+ }
+ d->maximumSequenceLength = int(count);
+ if (d->keyNum > count) {
+ for (qsizetype i = d->keyNum; i < count; ++i)
+ d->key[i] = QKeyCombination::fromCombined(0);
+ d->keyNum = count;
+ d->rebuildKeySequence();
+ }
+}
+
+/*!
+ \property QKeySequenceEdit::finishingKeyCombinations
+ \brief The list of key combinations that finish editing the key sequences.
+
+ Any combination in the list will finish the editing of key sequences.
+ All other key combinations can be recorded as part of a key sequence. By
+ default, Qt::Key_Tab and Qt::Key_Backtab will finish recording the key
+ sequence.
+
+ \since 6.5
+*/
+void QKeySequenceEdit::setFinishingKeyCombinations(const QList<QKeyCombination> &finishingKeyCombinations)
+{
+ Q_D(QKeySequenceEdit);
+
+ d->finishingKeyCombinations = finishingKeyCombinations;
+}
+
+QList<QKeyCombination> QKeySequenceEdit::finishingKeyCombinations() const
+{
+ Q_D(const QKeySequenceEdit);
+
+ return d->finishingKeyCombinations;
+}
+
void QKeySequenceEdit::setKeySequence(const QKeySequence &keySequence)
{
Q_D(QKeySequenceEdit);
@@ -184,16 +240,24 @@ void QKeySequenceEdit::setKeySequence(const QKeySequence &keySequence)
if (d->keySequence == keySequence)
return;
- d->keySequence = keySequence;
+ const auto desiredCount = keySequence.count();
+ if (desiredCount > d->maximumSequenceLength) {
+ qWarning("QKeySequenceEdit: setting a key sequence of length %d "
+ "when maximumSequenceLength is %d, truncating.",
+ desiredCount, d->maximumSequenceLength);
+ }
- d->key[0] = d->key[1] = d->key[2] = d->key[3] = 0;
- d->keyNum = keySequence.count();
+ d->keyNum = std::min(desiredCount, d->maximumSequenceLength);
for (int i = 0; i < d->keyNum; ++i)
d->key[i] = keySequence[i];
+ for (int i = d->keyNum; i < QKeySequencePrivate::MaxKeyCount; ++i)
+ d->key[i] = QKeyCombination::fromCombined(0);
- d->lineEdit->setText(keySequence.toString(QKeySequence::NativeText));
+ d->rebuildKeySequence();
- emit keySequenceChanged(keySequence);
+ d->lineEdit->setText(d->keySequence.toString(QKeySequence::NativeText));
+
+ emit keySequenceChanged(d->keySequence);
}
/*!
@@ -218,13 +282,23 @@ void QKeySequenceEdit::clear()
*/
bool QKeySequenceEdit::event(QEvent *e)
{
+ Q_D(const QKeySequenceEdit);
+
switch (e->type()) {
case QEvent::Shortcut:
return true;
case QEvent::ShortcutOverride:
e->accept();
return true;
- default :
+ case QEvent::KeyPress: {
+ QKeyEvent *ke = static_cast<QKeyEvent *>(e);
+ if (!d->finishingKeyCombinations.contains(ke->keyCombination())) {
+ keyPressEvent(ke);
+ return true;
+ }
+ }
+ break;
+ default:
break;
}
@@ -238,6 +312,11 @@ void QKeySequenceEdit::keyPressEvent(QKeyEvent *e)
{
Q_D(QKeySequenceEdit);
+ if (d->finishingKeyCombinations.contains(e->keyCombination())) {
+ d->finishEditing();
+ return;
+ }
+
int nextKey = e->key();
if (d->prevKey == -1) {
@@ -261,38 +340,38 @@ void QKeySequenceEdit::keyPressEvent(QKeyEvent *e)
return;
}
- if (d->keyNum >= QKeySequencePrivate::MaxKeyCount)
+ if (d->keyNum >= d->maximumSequenceLength)
return;
if (e->modifiers() & Qt::ShiftModifier) {
- QList<int> possibleKeys = QKeyMapper::possibleKeys(e);
- int pkTotal = possibleKeys.count();
+ 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());
}
- d->key[d->keyNum] = nextKey;
+ d->key[d->keyNum] = QKeyCombination::fromCombined(nextKey);
d->keyNum++;
- QKeySequence key(d->key[0], d->key[1], d->key[2], d->key[3]);
- d->keySequence = key;
- QString text = key.toString(QKeySequence::NativeText);
- if (d->keyNum < QKeySequencePrivate::MaxKeyCount) {
+ d->rebuildKeySequence();
+ QString text = d->keySequence.toString(QKeySequence::NativeText);
+ if (d->keyNum < d->maximumSequenceLength) {
//: This text is an "unfinished" shortcut, expands like "Ctrl+A, ..."
text = tr("%1, ...").arg(text);
}
@@ -308,7 +387,7 @@ void QKeySequenceEdit::keyReleaseEvent(QKeyEvent *e)
Q_D(QKeySequenceEdit);
if (d->prevKey == e->key()) {
- if (d->keyNum < QKeySequencePrivate::MaxKeyCount)
+ if (d->keyNum < d->maximumSequenceLength)
d->releaseTimer = startTimer(1000);
else
d->finishEditing();
@@ -330,6 +409,17 @@ void QKeySequenceEdit::timerEvent(QTimerEvent *e)
QWidget::timerEvent(e);
}
+/*!
+ \reimp
+*/
+void QKeySequenceEdit::focusOutEvent(QFocusEvent *e)
+{
+ Q_D(QKeySequenceEdit);
+ if (e->reason() != Qt::PopupFocusReason)
+ d->finishEditing();
+ QWidget::focusOutEvent(e);
+}
+
QT_END_NAMESPACE
#include "moc_qkeysequenceedit.cpp"
diff --git a/src/widgets/widgets/qkeysequenceedit.h b/src/widgets/widgets/qkeysequenceedit.h
index 85d76f14a3..db0c4c80dd 100644
--- a/src/widgets/widgets/qkeysequenceedit.h
+++ b/src/widgets/widgets/qkeysequenceedit.h
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2013 Ivan Komissarov.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2013 Ivan Komissarov.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QKEYSEQUENCEEDIT_H
#define QKEYSEQUENCEEDIT_H
@@ -52,7 +16,11 @@ class QKeySequenceEditPrivate;
class Q_WIDGETS_EXPORT QKeySequenceEdit : public QWidget
{
Q_OBJECT
- Q_PROPERTY(QKeySequence keySequence READ keySequence WRITE setKeySequence NOTIFY keySequenceChanged USER true)
+ Q_PROPERTY(QKeySequence keySequence READ keySequence WRITE setKeySequence
+ NOTIFY keySequenceChanged USER true)
+ Q_PROPERTY(bool clearButtonEnabled READ isClearButtonEnabled WRITE setClearButtonEnabled)
+ Q_PROPERTY(qsizetype maximumSequenceLength READ maximumSequenceLength WRITE setMaximumSequenceLength)
+ Q_PROPERTY(QList<QKeyCombination> finishingKeyCombinations READ finishingKeyCombinations WRITE setFinishingKeyCombinations)
public:
explicit QKeySequenceEdit(QWidget *parent = nullptr);
@@ -60,10 +28,18 @@ public:
~QKeySequenceEdit();
QKeySequence keySequence() const;
+ qsizetype maximumSequenceLength() const;
+
+ void setClearButtonEnabled(bool enable);
+ bool isClearButtonEnabled() const;
+
+ void setFinishingKeyCombinations(const QList<QKeyCombination> &finishingKeyCombinations);
+ QList<QKeyCombination> finishingKeyCombinations() const;
public Q_SLOTS:
void setKeySequence(const QKeySequence &keySequence);
void clear();
+ void setMaximumSequenceLength(qsizetype count);
Q_SIGNALS:
void editingFinished();
@@ -76,6 +52,7 @@ protected:
void keyPressEvent(QKeyEvent *) override;
void keyReleaseEvent(QKeyEvent *) override;
void timerEvent(QTimerEvent *) override;
+ void focusOutEvent(QFocusEvent *) override;
private:
Q_DISABLE_COPY(QKeySequenceEdit)
diff --git a/src/widgets/widgets/qkeysequenceedit_p.h b/src/widgets/widgets/qkeysequenceedit_p.h
index 7af034e735..bdf3bfe788 100644
--- a/src/widgets/widgets/qkeysequenceedit_p.h
+++ b/src/widgets/widgets/qkeysequenceedit_p.h
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2013 Ivan Komissarov.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2013 Ivan Komissarov.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QKEYSEQUENCEEDIT_P_H
#define QKEYSEQUENCEEDIT_P_H
@@ -72,13 +36,17 @@ public:
int translateModifiers(Qt::KeyboardModifiers state, const QString &text);
void resetState();
void finishEditing();
+ void rebuildKeySequence()
+ { keySequence = QKeySequence(key[0], key[1], key[2], key[3]); }
QLineEdit *lineEdit;
QKeySequence keySequence;
int keyNum;
- int key[QKeySequencePrivate::MaxKeyCount];
+ int maximumSequenceLength = QKeySequencePrivate::MaxKeyCount;
+ QKeyCombination key[QKeySequencePrivate::MaxKeyCount];
int prevKey;
int releaseTimer;
+ QList<QKeyCombination> finishingKeyCombinations;
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qlabel.cpp b/src/widgets/widgets/qlabel.cpp
index 7bd7283adf..f4155de0a0 100644
--- a/src/widgets/widgets/qlabel.cpp
+++ b/src/widgets/widgets/qlabel.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qpainter.h"
#include "qevent.h"
@@ -54,22 +18,24 @@
#include "private/qstylesheetstyle_p.h"
#include <qmath.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include <qaccessible.h>
#endif
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
QLabelPrivate::QLabelPrivate()
: QFramePrivate(),
sh(),
msh(),
text(),
- pixmap(nullptr),
- scaledpixmap(nullptr),
- cachedimage(nullptr),
+ pixmap(),
+ scaledpixmap(),
+ cachedimage(),
#ifndef QT_NO_PICTURE
- picture(nullptr),
+ picture(),
#endif
#if QT_CONFIG(movie)
movie(),
@@ -100,7 +66,8 @@ QLabelPrivate::QLabelPrivate()
validCursor(false),
onAnchor(false),
#endif
- openExternalLinks(false)
+ openExternalLinks(false),
+ resourceProvider(nullptr)
{
}
@@ -182,22 +149,35 @@ QLabelPrivate::~QLabelPrivate()
was a button (inheriting from QAbstractButton), triggering the
mnemonic would emulate a button click.
- \sa QLineEdit, QTextEdit, QPixmap, QMovie,
- {fowler}{GUI Design Handbook: Label}
+ \sa QLineEdit, QTextEdit, QPixmap, QMovie
*/
#ifndef QT_NO_PICTURE
/*!
- Returns the label's picture or nullptr if the label doesn't have a
- picture.
+ \fn QPicture QLabel::picture(Qt::ReturnByValueConstant) const
+ \deprecated Use the overload without argument instead.
+ \since 5.15
+
+ Returns the label's picture.
+
+ Previously, Qt provided a version of \c picture() which returned the picture
+ by-pointer. That version is now removed. This overload allowed to
+ explicitly differentiate between the by-pointer function and the by-value.
*/
-const QPicture *QLabel::picture() const
+/*!
+ \since 6.0
+
+ Returns the label's picture.
+*/
+QPicture QLabel::picture() const
{
Q_D(const QLabel);
- return d->picture;
+ if (d->picture)
+ return *(d->picture);
+ return QPicture();
}
-#endif
+#endif // QT_NO_PICTURE
/*!
@@ -324,7 +304,7 @@ void QLabel::setText(const QString &text)
d->updateLabel();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (accessibleName().isEmpty()) {
QAccessibleEvent event(this, QAccessible::NameChanged);
QAccessible::updateAccessibility(&event);
@@ -351,9 +331,7 @@ void QLabel::clear()
/*!
\property QLabel::pixmap
- \brief the label's pixmap
-
- If no pixmap has been set this will return nullptr.
+ \brief the label's pixmap.
Setting the pixmap clears any previous content. The buddy
shortcut, if any, is disabled.
@@ -363,21 +341,37 @@ void QLabel::setPixmap(const QPixmap &pixmap)
Q_D(QLabel);
if (!d->pixmap || d->pixmap->cacheKey() != pixmap.cacheKey()) {
d->clearContents();
- d->pixmap = new QPixmap(pixmap);
+ d->pixmap = pixmap;
}
- if (d->pixmap->depth() == 1 && !d->pixmap->mask())
- d->pixmap->setMask(*((QBitmap *)d->pixmap));
-
d->updateLabel();
}
-const QPixmap *QLabel::pixmap() const
+QPixmap QLabel::pixmap() const
{
Q_D(const QLabel);
- return d->pixmap;
+ if (d->pixmap)
+ return *(d->pixmap);
+ return QPixmap();
}
+/*!
+ \fn QPixmap QLabel::pixmap(Qt::ReturnByValueConstant) const
+
+ \deprecated Use the overload without argument instead.
+ \since 5.15
+
+ Returns the label's pixmap.
+
+ Previously, Qt provided a version of \c pixmap() which returned the pixmap
+ by-pointer. That version has now been removed. This overload allowed to
+ explicitly differentiate between the by-pointer function and the by-value.
+
+ \code
+ QPixmap pixmapVal = label->pixmap(Qt::ReturnByValue);
+ \endcode
+*/
+
#ifndef QT_NO_PICTURE
/*!
Sets the label contents to \a picture. Any previous content is
@@ -392,7 +386,7 @@ void QLabel::setPicture(const QPicture &picture)
{
Q_D(QLabel);
d->clearContents();
- d->picture = new QPicture(picture);
+ d->picture = picture;
d->updateLabel();
}
@@ -560,7 +554,7 @@ void QLabel::setMargin(int margin)
QSize QLabelPrivate::sizeForWidth(int w) const
{
Q_Q(const QLabel);
- if(q->minimumWidth() > 0)
+ if (q->minimumWidth() > 0)
w = qMax(w, q->minimumWidth());
QSize contentsMargin(leftmargin + rightmargin, topmargin + bottommargin);
@@ -572,7 +566,7 @@ QSize QLabelPrivate::sizeForWidth(int w) const
if (pixmap && !pixmap->isNull()) {
br = pixmap->rect();
- br.setSize(br.size() / pixmap->devicePixelRatio());
+ br.setSize(pixmap->deviceIndependentSize().toSize());
#ifndef QT_NO_PICTURE
} else if (picture && !picture->isNull()) {
br = picture->boundingRect();
@@ -580,7 +574,7 @@ QSize QLabelPrivate::sizeForWidth(int w) const
#if QT_CONFIG(movie)
} else if (movie && !movie->currentPixmap().isNull()) {
br = movie->currentPixmap().rect();
- br.setSize(br.size() / movie->currentPixmap().devicePixelRatio());
+ br.setSize(movie->currentPixmap().deviceIndependentSize().toSize());
#endif
} else if (isTextLabel) {
int align = QStyle::visualAlignment(textDirection(), QFlag(this->align));
@@ -588,7 +582,7 @@ QSize QLabelPrivate::sizeForWidth(int w) const
int m = indent;
if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
- m = fm.horizontalAdvance(QLatin1Char('x')) - margin*2;
+ m = fm.horizontalAdvance(u'x') - margin*2;
if (m > 0) {
if ((align & Qt::AlignLeft) || (align & Qt::AlignRight))
hextra += m;
@@ -994,6 +988,9 @@ bool QLabel::event(QEvent *e)
) {
d->setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
d->updateLabel();
+ } else if (type == QEvent::Polish) {
+ if (d->needTextControl())
+ d->ensureTextControl();
}
return QFrame::event(e);
@@ -1094,17 +1091,19 @@ void QLabel::paintEvent(QPaintEvent *)
#endif
if (d->pixmap && !d->pixmap->isNull()) {
QPixmap pix;
- if (d->scaledcontents) {
- QSize scaledSize = cr.size() * devicePixelRatioF();
+ const qreal dpr = devicePixelRatio();
+ if (d->scaledcontents || dpr != d->pixmap->devicePixelRatio()) {
+ QSize scaledSize = d->scaledcontents ? (cr.size() * dpr)
+ : (d->pixmap->size() * (dpr / d->pixmap->devicePixelRatio()));
if (!d->scaledpixmap || d->scaledpixmap->size() != scaledSize) {
if (!d->cachedimage)
- d->cachedimage = new QImage(d->pixmap->toImage());
- delete d->scaledpixmap;
+ d->cachedimage = d->pixmap->toImage();
+ d->scaledpixmap.reset();
QImage scaledImage =
d->cachedimage->scaled(scaledSize,
Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
- d->scaledpixmap = new QPixmap(QPixmap::fromImage(std::move(scaledImage)));
- d->scaledpixmap->setDevicePixelRatio(devicePixelRatioF());
+ d->scaledpixmap = QPixmap::fromImage(std::move(scaledImage));
+ d->scaledpixmap->setDevicePixelRatio(dpr);
}
pix = *d->scaledpixmap;
} else
@@ -1172,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)
@@ -1213,14 +1214,14 @@ void QLabelPrivate::updateShortcut()
// But then we do want to hide the ampersands, so we can't use shortcutId.
hasShortcut = false;
- if (!text.contains(QLatin1Char('&')))
+ if (!text.contains(u'&'))
return;
hasShortcut = true;
shortcutId = q->grabShortcut(QKeySequence::mnemonic(text));
}
-void QLabelPrivate::_q_buddyDeleted()
+void QLabelPrivate::buddyDeleted()
{
Q_Q(QLabel);
q->setBuddy(nullptr);
@@ -1229,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()) {
@@ -1252,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 smaler
+ 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();
}
@@ -1279,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
@@ -1304,15 +1307,11 @@ void QLabelPrivate::clearContents()
hasShortcut = false;
#ifndef QT_NO_PICTURE
- delete picture;
- picture = nullptr;
+ picture.reset();
#endif
- delete scaledpixmap;
- scaledpixmap = nullptr;
- delete cachedimage;
- cachedimage = nullptr;
- delete pixmap;
- pixmap = nullptr;
+ scaledpixmap.reset();
+ cachedimage.reset();
+ pixmap.reset();
text.clear();
Q_Q(QLabel);
@@ -1322,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
@@ -1390,12 +1387,38 @@ void QLabel::setTextFormat(Qt::TextFormat format)
}
/*!
+ \since 6.1
+
+ Returns the resource provider for rich text of this label.
+*/
+QTextDocument::ResourceProvider QLabel::resourceProvider() const
+{
+ Q_D(const QLabel);
+ return d->control ? d->control->document()->resourceProvider() : d->resourceProvider;
+}
+
+/*!
+ \since 6.1
+
+ Sets the \a provider of resources for rich text of this label.
+
+ \note The label \e{does not} take ownership of the \a provider.
+*/
+void QLabel::setResourceProvider(const QTextDocument::ResourceProvider &provider)
+{
+ Q_D(QLabel);
+ d->resourceProvider = provider;
+ if (d->control != nullptr)
+ d->control->document()->setResourceProvider(provider);
+}
+
+/*!
\reimp
*/
void QLabel::changeEvent(QEvent *ev)
{
Q_D(QLabel);
- if(ev->type() == QEvent::FontChange || ev->type() == QEvent::ApplicationFontChange) {
+ if (ev->type() == QEvent::FontChange || ev->type() == QEvent::ApplicationFontChange) {
if (d->isTextLabel) {
if (d->control)
d->control->document()->setDefaultFont(font());
@@ -1432,10 +1455,8 @@ void QLabel::setScaledContents(bool enable)
return;
d->scaledcontents = enable;
if (!enable) {
- delete d->scaledpixmap;
- d->scaledpixmap = nullptr;
- delete d->cachedimage;
- d->cachedimage = nullptr;
+ d->scaledpixmap.reset();
+ d->cachedimage.reset();
}
update(contentsRect());
}
@@ -1462,7 +1483,7 @@ QRect QLabelPrivate::documentRect() const
: q->layoutDirection(), QFlag(this->align));
int m = indent;
if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
- m = q->fontMetrics().horizontalAdvance(QLatin1Char('x')) / 2 - margin;
+ m = q->fontMetrics().horizontalAdvance(u'x') / 2 - margin;
if (m > 0) {
if (align & Qt::AlignLeft)
cr.setLeft(cr.left() + m);
@@ -1504,11 +1525,11 @@ void QLabelPrivate::ensureTextPopulated() const
int from = 0;
bool found = false;
QTextCursor cursor;
- while (!(cursor = control->document()->find((QLatin1String("&")), from)).isNull()) {
+ while (!(cursor = control->document()->find(("&"_L1), from)).isNull()) {
cursor.deleteChar(); // remove the ampersand
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
from = cursor.position();
- if (!found && cursor.selectedText() != QLatin1String("&")) { //not a second &
+ if (!found && cursor.selectedText() != "&"_L1) { //not a second &
found = true;
shortcutCursor = cursor;
}
@@ -1555,16 +1576,18 @@ void QLabelPrivate::ensureTextControl() const
control = new QWidgetTextControl(const_cast<QLabel *>(q));
control->document()->setUndoRedoEnabled(false);
control->document()->setDefaultFont(q->font());
+ if (resourceProvider != nullptr)
+ control->document()->setResourceProvider(resourceProvider);
control->setTextInteractionFlags(textInteractionFlags);
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;
}
@@ -1580,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
@@ -1611,7 +1634,7 @@ QRectF QLabelPrivate::layoutRect() const
if (!control)
return cr;
ensureTextLayouted();
- // Caculate y position manually
+ // Calculate y position manually
qreal rh = control->document()->documentLayout()->documentSize().height();
qreal yo = 0;
if (align & Qt::AlignVCenter)
@@ -1631,16 +1654,10 @@ QPoint QLabelPrivate::layoutPoint(const QPoint& p) const
#ifndef QT_NO_CONTEXTMENU
QMenu *QLabelPrivate::createStandardContextMenu(const QPoint &pos)
{
- QString linkToCopy;
- QPoint p;
- if (control && effectiveTextFormat != Qt::PlainText) {
- p = layoutPoint(pos);
- linkToCopy = control->document()->documentLayout()->anchorAt(p);
- }
-
- if (linkToCopy.isEmpty() && !control)
+ if (!control)
return nullptr;
+ const QPoint p = layoutPoint(pos);
return control->createStandardContextMenu(p, q_func());
}
#endif
diff --git a/src/widgets/widgets/qlabel.h b/src/widgets/widgets/qlabel.h
index 2f5db5a7d3..3749ec366a 100644
--- a/src/widgets/widgets/qlabel.h
+++ b/src/widgets/widgets/qlabel.h
@@ -1,47 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLABEL_H
#define QLABEL_H
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qframe.h>
+#include <QtGui/qpicture.h>
+#include <QtGui/qtextdocument.h>
QT_REQUIRE_CONFIG(label);
@@ -62,7 +28,8 @@ class Q_WIDGETS_EXPORT QLabel : public QFrame
Q_PROPERTY(int margin READ margin WRITE setMargin)
Q_PROPERTY(int indent READ indent WRITE setIndent)
Q_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
+ Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags
+ WRITE setTextInteractionFlags)
Q_PROPERTY(bool hasSelectedText READ hasSelectedText)
Q_PROPERTY(QString selectedText READ selectedText)
@@ -72,9 +39,17 @@ public:
~QLabel();
QString text() const;
- const QPixmap *pixmap() const;
+
+#if QT_DEPRECATED_SINCE(6,6)
+ QPixmap pixmap(Qt::ReturnByValueConstant) const { return pixmap(); }
+#endif
+ QPixmap pixmap() const;
+
#ifndef QT_NO_PICTURE
- const QPicture *picture() const;
+#if QT_DEPRECATED_SINCE(6,6)
+ QPicture picture(Qt::ReturnByValueConstant) const { return picture(); }
+#endif
+ QPicture picture() const;
#endif
#if QT_CONFIG(movie)
QMovie *movie() const;
@@ -83,6 +58,9 @@ public:
Qt::TextFormat textFormat() const;
void setTextFormat(Qt::TextFormat);
+ QTextDocument::ResourceProvider resourceProvider() const;
+ void setResourceProvider(const QTextDocument::ResourceProvider &provider);
+
Qt::Alignment alignment() const;
void setAlignment(Qt::Alignment);
@@ -152,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 6b3fbc5f0c..fb6ccb04eb 100644
--- a/src/widgets/widgets/qlabel_p.h
+++ b/src/widgets/widgets/qlabel_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLABEL_P_H
#define QLABEL_P_H
@@ -69,6 +33,11 @@
#include "qmenu.h"
#endif
+#include <QtCore/qpointer.h>
+
+#include <array>
+#include <optional>
+
QT_BEGIN_NAMESPACE
class Q_AUTOTEST_EXPORT QLabelPrivate : public QFramePrivate
@@ -84,17 +53,19 @@ 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);
return isTextLabel
&& (effectiveTextFormat != Qt::PlainText
- || (textInteractionFlags & (Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard)));
+ || (textInteractionFlags & (Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard))
+ || q->focusPolicy() != Qt::NoFocus);
}
void ensureTextPopulated() const;
@@ -102,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;
@@ -115,14 +86,15 @@ public:
mutable QSize sh;
mutable QSize msh;
QString text;
- QPixmap *pixmap;
- QPixmap *scaledpixmap;
- QImage *cachedimage;
+ std::optional<QPixmap> pixmap;
+ std::optional<QPixmap> scaledpixmap;
+ std::optional<QImage> cachedimage;
#ifndef QT_NO_PICTURE
- QPicture *picture;
+ std::optional<QPicture> picture;
#endif
#if QT_CONFIG(movie)
QPointer<QMovie> movie;
+ std::array<QMetaObject::Connection, 2> movieConnections;
#endif
mutable QWidgetTextControl *control;
mutable QTextCursor shortcutCursor;
@@ -152,6 +124,7 @@ public:
#endif
uint openExternalLinks : 1;
// <-- space for more bit field values here
+ QTextDocument::ResourceProvider resourceProvider;
friend class QMessageBoxPrivate;
};
diff --git a/src/widgets/widgets/qlcdnumber.cpp b/src/widgets/widgets/qlcdnumber.cpp
index 3ddada4514..3a65b06415 100644
--- a/src/widgets/widgets/qlcdnumber.cpp
+++ b/src/widgets/widgets/qlcdnumber.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qlcdnumber.h"
@@ -52,7 +16,7 @@ public:
void init();
void internalSetString(const QString& s);
void drawString(const QString& s, QPainter &, QBitArray * = nullptr, bool = true);
- //void drawString(const QString &, QPainter &, QBitArray * = 0) const;
+ //void drawString(const QString &, QPainter &, QBitArray * = nullptr) const;
void drawDigit(const QPoint &, QPainter &, int, char, char = ' ');
void drawSegment(const QPoint &, char, QPainter &, int, bool = false);
@@ -105,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
*/
/*!
@@ -179,25 +143,25 @@ static QString int2string(int num, int base, int ndigits, bool *oflow)
} while (n != 0);
len = ndigits - len;
if (len > 0)
- s += QString(len, QLatin1Char(' '));
- s += QLatin1String(p);
+ s += QString(len, u' ');
+ s += QLatin1StringView(p);
}
break;
}
if (negative) {
- for (int i=0; i<(int)s.length(); i++) {
- if (s[i] != QLatin1Char(' ')) {
+ for (int i=0; i<(int)s.size(); i++) {
+ if (s[i] != u' ') {
if (i != 0) {
- s[i-1] = QLatin1Char('-');
+ s[i-1] = u'-';
} else {
- s.insert(0, QLatin1Char('-'));
+ s.insert(0, u'-');
}
break;
}
}
}
if (oflow)
- *oflow = (int)s.length() > ndigits;
+ *oflow = (int)s.size() > ndigits;
return s;
}
@@ -217,15 +181,15 @@ static QString double2string(double num, int base, int ndigits, bool *oflow)
int nd = ndigits;
do {
s = QString::asprintf("%*.*g", ndigits, nd, num);
- int i = s.indexOf(QLatin1Char('e'));
- if (i > 0 && s[i+1]==QLatin1Char('+')) {
- s[i] = QLatin1Char(' ');
- s[i+1] = QLatin1Char('e');
+ qsizetype i = s.indexOf(u'e');
+ if (i > 0 && s[i+1]==u'+') {
+ s[i] = u' ';
+ s[i+1] = u'e';
}
- } while (nd-- && (int)s.length() > ndigits);
+ } while (nd-- && (int)s.size() > ndigits);
}
if (oflow)
- *oflow = (int)s.length() > ndigits;
+ *oflow = (int)s.size() > ndigits;
return s;
}
@@ -408,9 +372,9 @@ void QLCDNumber::setDigitCount(int numDigits)
}
if (d->digitStr.isNull()) { // from constructor
d->ndigits = numDigits;
- d->digitStr.fill(QLatin1Char(' '), d->ndigits);
+ d->digitStr.fill(u' ', d->ndigits);
d->points.fill(0, d->ndigits);
- d->digitStr[d->ndigits - 1] = QLatin1Char('0'); // "0" is the default number
+ d->digitStr[d->ndigits - 1] = u'0'; // "0" is the default number
} else {
bool doDisplay = d->ndigits == 0;
if (numDigits == d->ndigits) // no change
@@ -420,7 +384,7 @@ void QLCDNumber::setDigitCount(int numDigits)
if (numDigits > d->ndigits) { // expand
dif = numDigits - d->ndigits;
QString buf;
- buf.fill(QLatin1Char(' '), dif);
+ buf.fill(u' ', dif);
d->digitStr.insert(0, buf);
d->points.resize(numDigits);
for (i=numDigits-1; i>=dif; i--)
@@ -432,7 +396,7 @@ void QLCDNumber::setDigitCount(int numDigits)
d->digitStr = d->digitStr.right(numDigits);
QBitArray tmpPoints = d->points;
d->points.resize(numDigits);
- for (i=0; i<(int)numDigits; i++)
+ for (i=0; i<numDigits; i++)
d->points.setBit(i, tmpPoints.testBit(i+dif));
}
d->ndigits = numDigits;
@@ -713,27 +677,27 @@ void QLCDNumber::paintEvent(QPaintEvent *)
void QLCDNumberPrivate::internalSetString(const QString& s)
{
Q_Q(QLCDNumber);
- QString buffer;
+ QString buffer(ndigits, QChar());
int i;
- int len = s.length();
+ int len = s.size();
QBitArray newPoints(ndigits);
if (!smallPoint) {
if (len == ndigits)
buffer = s;
else
- buffer = s.right(ndigits).rightJustified(ndigits, QLatin1Char(' '));
+ buffer = s.right(ndigits).rightJustified(ndigits, u' ');
} else {
int index = -1;
bool lastWasPoint = true;
newPoints.clearBit(0);
for (i=0; i<len; i++) {
- if (s[i] == QLatin1Char('.')) {
+ if (s[i] == u'.') {
if (lastWasPoint) { // point already set for digit?
if (index == ndigits - 1) // no more digits
break;
index++;
- buffer[index] = QLatin1Char(' '); // 2 points in a row, add space
+ buffer[index] = u' '; // 2 points in a row, add space
}
newPoints.setBit(index); // set decimal point
lastWasPoint = true;
@@ -753,7 +717,7 @@ void QLCDNumberPrivate::internalSetString(const QString& s)
newPoints.testBit(i));
}
for(i=0; i<ndigits-index-1; i++) {
- buffer[i] = QLatin1Char(' ');
+ buffer[i] = u' ';
newPoints.clearBit(i);
}
}
@@ -1159,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/qlcdnumber.h b/src/widgets/widgets/qlcdnumber.h
index 644c39eaf3..bcd0623d02 100644
--- a/src/widgets/widgets/qlcdnumber.h
+++ b/src/widgets/widgets/qlcdnumber.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLCDNUMBER_H
#define QLCDNUMBER_H
diff --git a/src/widgets/widgets/qlineedit.cpp b/src/widgets/widgets/qlineedit.cpp
index bd5e0b047e..8909ac80d9 100644
--- a/src/widgets/widgets/qlineedit.cpp
+++ b/src/widgets/widgets/qlineedit.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qlineedit.h"
#include "qlineedit_p.h"
@@ -64,7 +28,6 @@
#include "qtimer.h"
#include "qvalidator.h"
#include "qvariant.h"
-#include "qvector.h"
#include "qdebug.h"
#if QT_CONFIG(textedit)
#include "qtextedit.h"
@@ -72,7 +35,7 @@
#endif
#include <private/qwidgettextcontrol_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
#if QT_CONFIG(itemviews)
@@ -84,10 +47,9 @@
#include "private/qapplication_p.h"
#include "private/qshortcutmap_p.h"
#include "qkeysequence.h"
-#define ACCEL_KEY(k) ((!QCoreApplication::testAttribute(Qt::AA_DontShowIconsInMenus) \
- && QGuiApplication::styleHints()->showShortcutsInContextMenus()) \
+#define ACCEL_KEY(k) (!QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus) \
&& !QGuiApplicationPrivate::instance()->shortcutMap.hasShortcutForKeySequence(k) ? \
- QLatin1Char('\t') + QKeySequence(k).toString(QKeySequence::NativeText) : QString())
+ u'\t' + QKeySequence(k).toString(QKeySequence::NativeText) : QString())
#else
#define ACCEL_KEY(k) QString()
#endif
@@ -99,6 +61,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
Initialize \a option with the values from this QLineEdit. This method
is useful for subclasses when they need a QStyleOptionFrame, but don't want
@@ -136,54 +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.
-
- 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 write-only field for inputs such as passwords.
- 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 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.
@@ -194,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.
@@ -206,10 +182,10 @@ 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, {fowler}{GUI Design Handbook: Field, Entry}, {Line Edits Example}
+ \sa QTextEdit, QLabel, QComboBox, {Line Edits Example}
*/
@@ -265,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()
*/
@@ -295,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().
@@ -324,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.
@@ -356,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.
@@ -377,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
@@ -407,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
{
@@ -470,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
@@ -489,13 +463,13 @@ void QLineEdit::setClearButtonEnabled(bool enable)
if (enable) {
QAction *clearAction = new QAction(d->clearButtonIcon(), QString(), this);
clearAction->setEnabled(!isReadOnly());
- clearAction->setObjectName(QLatin1String(clearButtonActionNameC));
+ clearAction->setObjectName(QLatin1StringView(clearButtonActionNameC));
int flags = QLineEditPrivate::SideWidgetClearButton | QLineEditPrivate::SideWidgetFadeInWithText;
auto widgetAction = d->addAction(clearAction, nullptr, QLineEdit::TrailingPosition, flags);
widgetAction->setVisible(!text().isEmpty());
} else {
- QAction *clearAction = findChild<QAction *>(QLatin1String(clearButtonActionNameC));
+ QAction *clearAction = findChild<QAction *>(QLatin1StringView(clearButtonActionNameC));
Q_ASSERT(clearAction);
d->removeAction(clearAction);
delete clearAction;
@@ -508,7 +482,7 @@ void QLineEdit::setClearButtonEnabled(bool enable)
bool QLineEdit::isClearButtonEnabled() const
{
#if QT_CONFIG(action)
- return findChild<QAction *>(QLatin1String(clearButtonActionNameC));
+ return findChild<QAction *>(QLatin1StringView(clearButtonActionNameC));
#else
return false;
#endif
@@ -536,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()
*/
@@ -546,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.
@@ -601,15 +574,23 @@ const QValidator * QLineEdit::validator() const
}
/*!
- Sets this line edit to only accept input that the validator, \a v,
- will accept. This allows you to place any arbitrary constraints on
- the text which may be entered.
+ Sets the validator for values of line edit to \a v.
+
+ The line edit's returnPressed() and editingFinished() signals will only
+ be emitted if \a v validates the line edit's content as \l{QValidator::}{Acceptable}.
+ The user may change the content to any \l{QValidator::}{Intermediate}
+ value during editing, but will be prevented from editing the text to a
+ value that \a v validates as \l{QValidator::}{Invalid}.
- 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()).
+ 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.
- \sa validator(), hasAcceptableInput(), QIntValidator, QDoubleValidator, QRegExpValidator
+ 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
*/
void QLineEdit::setValidator(const QValidator *v)
@@ -631,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
*/
@@ -642,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();
@@ -652,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();
}
/*!
@@ -690,20 +666,19 @@ QSize QLineEdit::sizeHint() const
int h = qMax(fm.height(), qMax(14, iconSize - 2)) + 2 * QLineEditPrivate::verticalMargin
+ tm.top() + tm.bottom()
+ d->topmargin + d->bottommargin;
- int w = fm.horizontalAdvance(QLatin1Char('x')) * 17 + 2 * QLineEditPrivate::horizontalMargin
+ int w = fm.horizontalAdvance(u'x') * 17 + 2 * QLineEditPrivate::horizontalMargin
+ tm.left() + tm.right()
+ d->leftmargin + d->rightmargin; // "some"
QStyleOptionFrame opt;
initStyleOption(&opt);
- return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
- expandedTo(QApplication::globalStrut()), this));
+ return style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h), this);
}
/*!
Returns a minimum size for the line edit.
- The width returned is enough for at least one character.
+ The width returned is usually enough for at least one character.
*/
QSize QLineEdit::minimumSizeHint() const
@@ -715,19 +690,18 @@ QSize QLineEdit::minimumSizeHint() const
int h = fm.height() + qMax(2 * QLineEditPrivate::verticalMargin, fm.leading())
+ tm.top() + tm.bottom()
+ d->topmargin + d->bottommargin;
- int w = fm.maxWidth()
+ int w = fm.maxWidth() + 2 * QLineEditPrivate::horizontalMargin
+ tm.left() + tm.right()
+ d->leftmargin + d->rightmargin;
QStyleOptionFrame opt;
initStyleOption(&opt);
- return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
- expandedTo(QApplication::globalStrut()), this));
+ return style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h), this);
}
/*!
\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.
@@ -760,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.
@@ -785,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()
*/
@@ -800,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()
*/
@@ -839,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()
*/
@@ -854,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()
*/
@@ -868,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()
@@ -883,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()
@@ -898,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
@@ -928,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.
@@ -947,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.
@@ -965,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()
@@ -980,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()
@@ -1034,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.
@@ -1049,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.
*/
@@ -1065,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.
@@ -1085,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.
*/
@@ -1113,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.
@@ -1127,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)
{
@@ -1142,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)
{
@@ -1152,30 +1127,6 @@ void QLineEdit::setTextMargins(const QMargins &margins)
update();
}
-#if QT_DEPRECATED_SINCE(5, 14)
-/*!
- \obsolete
- Use textMargins()
-
- Returns the widget's text margins for \a left, \a top, \a right, and \a bottom.
- \since 4.5
-
- \sa setTextMargins()
-*/
-void QLineEdit::getTextMargins(int *left, int *top, int *right, int *bottom) const
-{
- QMargins m = textMargins();
- if (left)
- *left = m.left();
- if (top)
- *top = m.top();
- if (right)
- *right = m.right();
- if (bottom)
- *bottom = m.bottom();
-}
-#endif
-
/*!
\since 4.6
Returns the widget's text margins.
@@ -1192,37 +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 class 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 ASCII alphabetic character required. A-Z, a-z.
- \row \li \c a \li ASCII alphabetic character permitted but not required.
- \row \li \c N \li ASCII alphanumeric character required. A-Z, a-z, 0-9.
- \row \li \c n \li ASCII alphanumeric character 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 ASCII digit required. 0-9.
- \row \li \c 0 \li ASCII digit permitted but not required.
- \row \li \c D \li ASCII digit required. 1-9.
- \row \li \c d \li ASCII digit permitted but not required (1-9).
- \row \li \c # \li ASCII digit or plus/minus sign permitted but not required.
+ \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.
@@ -1231,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
@@ -1248,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
@@ -1264,7 +1225,7 @@ QMargins QLineEdit::textMargins() const
To get range control (e.g., for an IP address) use masks together
with \l{setValidator()}{validators}.
- \sa maxLength
+ \sa maxLength, QChar::isLetter(), QChar::isNumber(), QChar::digitValue()
*/
QString QLineEdit::inputMask() const
{
@@ -1279,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.
@@ -1308,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()
@@ -1357,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),
@@ -1390,7 +1353,7 @@ void QLineEdit::setReadOnly(bool enable)
QEvent event(QEvent::ReadOnlyChange);
QCoreApplication::sendEvent(this, &event);
update();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessible::State changedState;
changedState.readOnly = true;
QAccessibleStateChangeEvent ev(this, changedState);
@@ -1437,7 +1400,7 @@ void QLineEdit::copy() const
Inserts the clipboard's text at the cursor position, deleting any
selected text, providing the line edit is not \l{QLineEdit::readOnly}{read-only}.
- If the end result would not be acceptable to the current
+ If the end result would be invalid to the current
\l{setValidator()}{validator}, nothing happens.
\sa copy(), cut()
@@ -1451,37 +1414,44 @@ void QLineEdit::paste()
#endif // !QT_NO_CLIPBOARD
-/*! \reimp
+/*!
+ \reimp
*/
-bool QLineEdit::event(QEvent * e)
+void QLineEdit::timerEvent(QTimerEvent *e)
{
Q_D(QLineEdit);
- if (e->type() == QEvent::Timer) {
- // ### Qt6: move to timerEvent, is here for binary compatibility
- int timerId = ((QTimerEvent*)e)->timerId();
- if (false) {
+ int timerId = ((QTimerEvent*)e)->timerId();
+ if (false) {
#if QT_CONFIG(draganddrop)
- } else if (timerId == d->dndTimer.timerId()) {
- d->drag();
+ } else if (timerId == d->dndTimer.timerId()) {
+ d->drag();
#endif
- }
- else if (timerId == d->tripleClickTimer.timerId())
- d->tripleClickTimer.stop();
- } else if (e->type() == QEvent::ContextMenu) {
+ }
+ else if (timerId == d->tripleClickTimer.timerId())
+ d->tripleClickTimer.stop();
+}
+
+/*! \reimp
+*/
+bool QLineEdit::event(QEvent * e)
+{
+ Q_D(QLineEdit);
+ if (e->type() == QEvent::ContextMenu) {
#ifndef QT_NO_IM
if (d->control->composeMode())
return true;
#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);
d->control->processShortcutOverrideEvent(ke);
#endif
- } else if (e->type() == QEvent::KeyRelease) {
- d->control->updateCursorBlinking();
} else if (e->type() == QEvent::Show) {
//In order to get the cursor blinking if QComboBox::setEditable is called when the combobox has focus
if (hasFocus()) {
@@ -1492,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());
@@ -1527,7 +1499,7 @@ void QLineEdit::mousePressEvent(QMouseEvent* e)
{
Q_D(QLineEdit);
- d->mousePressPos = e->pos();
+ d->mousePressPos = e->position().toPoint();
if (d->sendMouseEventToInputContext(e))
return;
@@ -1541,7 +1513,7 @@ void QLineEdit::mousePressEvent(QMouseEvent* e)
d->control->completer()->complete();
}
#endif
- if (d->tripleClickTimer.isActive() && (e->pos() - d->tripleClick).manhattanLength() <
+ if (d->tripleClickTimer.isActive() && (e->position().toPoint() - d->tripleClick).manhattanLength() <
QApplication::startDragDistance()) {
selectAll();
return;
@@ -1550,10 +1522,10 @@ void QLineEdit::mousePressEvent(QMouseEvent* e)
#ifdef Q_OS_ANDROID
mark = mark && (d->imHints & Qt::ImhNoPredictiveText);
#endif // Q_OS_ANDROID
- int cursor = d->xToPos(e->pos().x());
+ int cursor = d->xToPos(e->position().toPoint().x());
#if QT_CONFIG(draganddrop)
if (!mark && d->dragEnabled && d->control->echoMode() == Normal &&
- e->button() == Qt::LeftButton && d->inSelection(e->pos().x())) {
+ e->button() == Qt::LeftButton && d->inSelection(e->position().toPoint().x())) {
if (!d->dndTimer.isActive())
d->dndTimer.start(QApplication::startDragTime(), this);
} else
@@ -1572,7 +1544,7 @@ void QLineEdit::mouseMoveEvent(QMouseEvent * e)
if (e->buttons() & Qt::LeftButton) {
#if QT_CONFIG(draganddrop)
if (d->dndTimer.isActive()) {
- if ((d->mousePressPos - e->pos()).manhattanLength() > QApplication::startDragDistance())
+ if ((d->mousePressPos - e->position().toPoint()).manhattanLength() > QApplication::startDragDistance())
d->drag();
} else
#endif
@@ -1583,26 +1555,26 @@ void QLineEdit::mouseMoveEvent(QMouseEvent * e)
const bool select = (d->imHints & Qt::ImhNoPredictiveText);
#endif
#ifndef QT_NO_IM
- if (d->mouseYThreshold > 0 && e->pos().y() > d->mousePressPos.y() + d->mouseYThreshold) {
+ if (d->mouseYThreshold > 0 && e->position().toPoint().y() > d->mousePressPos.y() + d->mouseYThreshold) {
if (layoutDirection() == Qt::RightToLeft)
d->control->home(select);
else
d->control->end(select);
- } else if (d->mouseYThreshold > 0 && e->pos().y() + d->mouseYThreshold < d->mousePressPos.y()) {
+ } else if (d->mouseYThreshold > 0 && e->position().toPoint().y() + d->mouseYThreshold < d->mousePressPos.y()) {
if (layoutDirection() == Qt::RightToLeft)
d->control->end(select);
else
d->control->home(select);
} else if (d->control->composeMode() && select) {
int startPos = d->xToPos(d->mousePressPos.x());
- int currentPos = d->xToPos(e->pos().x());
+ int currentPos = d->xToPos(e->position().toPoint().x());
if (startPos != currentPos)
d->control->setSelection(startPos, currentPos - startPos);
} else
#endif
{
- d->control->moveCursor(d->xToPos(e->pos().x()), select);
+ d->control->moveCursor(d->xToPos(e->position().toPoint().x()), select);
}
}
}
@@ -1630,14 +1602,14 @@ void QLineEdit::mouseReleaseEvent(QMouseEvent* e)
if (QGuiApplication::clipboard()->supportsSelection()) {
if (e->button() == Qt::LeftButton) {
d->control->copy(QClipboard::Selection);
- } else if (!d->control->isReadOnly() && e->button() == Qt::MidButton) {
+ } else if (!d->control->isReadOnly() && e->button() == Qt::MiddleButton) {
deselect();
d->control->paste(QClipboard::Selection);
}
}
#endif
- if (!isReadOnly() && rect().contains(e->pos()))
+ if (!isReadOnly() && rect().contains(e->position().toPoint()))
d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
d->clickCausedFocus = 0;
}
@@ -1649,14 +1621,14 @@ void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e)
Q_D(QLineEdit);
if (e->button() == Qt::LeftButton) {
- int position = d->xToPos(e->pos().x());
+ int position = d->xToPos(e->position().toPoint().x());
// exit composition mode
#ifndef QT_NO_IM
if (d->control->composeMode()) {
int preeditPos = d->control->cursor();
int posInPreedit = position - d->control->cursor();
- int preeditLength = d->control->preeditAreaText().length();
+ int preeditLength = d->control->preeditAreaText().size();
bool positionOnPreedit = false;
if (posInPreedit >= 0 && posInPreedit <= preeditLength)
@@ -1683,7 +1655,7 @@ void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e)
d->control->selectWordAtPos(position);
d->tripleClickTimer.start(QApplication::doubleClickInterval(), this);
- d->tripleClick = e->pos();
+ d->tripleClick = e->position().toPoint();
} else {
d->sendMouseEventToInputContext(e);
}
@@ -1692,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.
@@ -1702,38 +1675,39 @@ void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e)
/*!
\fn void QLineEdit::editingFinished()
- This signal is emitted when the Return or Enter key is pressed or
- the line edit loses focus. 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.
+ 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 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)
@@ -1782,17 +1756,26 @@ void QLineEdit::keyPressEvent(QKeyEvent *event)
}
#endif
d->control->processKeyEvent(event);
- if (event->isAccepted()) {
- if (layoutDirection() != d->control->layoutDirection())
- setLayoutDirection(d->control->layoutDirection());
+ if (event->isAccepted())
d->control->updateCursorBlinking();
- }
+}
+
+/*!
+ \reimp
+*/
+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
{
@@ -1805,10 +1788,6 @@ QRect QLineEdit::cursorRect() const
void QLineEdit::inputMethodEvent(QInputMethodEvent *e)
{
Q_D(QLineEdit);
- if (d->control->isReadOnly()) {
- e->ignore();
- return;
- }
if (echoMode() == PasswordEchoOnEdit && !d->control->passwordEchoEditing()) {
// Clear the edit and reset to normal echo mode while entering input
@@ -1840,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());
}
@@ -1849,12 +1844,15 @@ QVariant QLineEdit::inputMethodQuery(Qt::InputMethodQuery property, QVariant arg
{
Q_D(const QLineEdit);
switch(property) {
+ case Qt::ImEnabled:
+ return isEnabled() && !isReadOnly();
case Qt::ImCursorRectangle:
return d->cursorRect();
case Qt::ImAnchorRectangle:
return d->adjustedControlRect(d->control->anchorRect());
case Qt::ImFont:
return font();
+ case Qt::ImAbsolutePosition:
case Qt::ImCursorPosition: {
const QPointF pt = argument.toPointF();
if (!pt.isNull())
@@ -1873,6 +1871,20 @@ QVariant QLineEdit::inputMethodQuery(Qt::InputMethodQuery property, QVariant arg
return QVariant(d->control->selectionEnd());
else
return QVariant(d->control->selectionStart());
+ case Qt::ImReadOnly:
+ return isReadOnly();
+ case Qt::ImTextBeforeCursor: {
+ const QPointF pt = argument.toPointF();
+ if (!pt.isNull())
+ return d->textBeforeCursor(d->xToPos(pt.x(), QTextLine::CursorBetweenCharacters));
+ else
+ return d->textBeforeCursor(d->control->cursor()); }
+ case Qt::ImTextAfterCursor: {
+ const QPointF pt = argument.toPointF();
+ if (!pt.isNull())
+ return d->textAfterCursor(d->xToPos(pt.x(), QTextLine::CursorBetweenCharacters));
+ else
+ return d->textAfterCursor(d->control->cursor()); }
default:
return QWidget::inputMethodQuery(property);
}
@@ -1891,8 +1903,11 @@ void QLineEdit::focusInEvent(QFocusEvent *e)
d->control->moveCursor(d->control->nextMaskBlank(0));
else if (!d->control->hasSelectedText())
selectAll();
+ else
+ updateMicroFocus();
} else if (e->reason() == Qt::MouseFocusReason) {
d->clickCausedFocus = 1;
+ updateMicroFocus();
}
#ifdef QT_KEYPAD_NAVIGATION
if (!QApplicationPrivate::keypadNavigationEnabled() || (hasEditFocus() && ( e->reason() == Qt::PopupFocusReason))) {
@@ -1900,7 +1915,7 @@ void QLineEdit::focusInEvent(QFocusEvent *e)
d->control->setBlinkingCursorEnabled(true);
QStyleOptionFrame opt;
initStyleOption(&opt);
- if((!hasSelectedText() && d->control->preeditAreaText().isEmpty())
+ if ((!hasSelectedText() && d->control->preeditAreaText().isEmpty())
|| style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
d->setCursorVisible(true);
#ifdef QT_KEYPAD_NAVIGATION
@@ -1910,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();
@@ -1952,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);
}
@@ -1975,21 +1986,28 @@ void QLineEdit::paintEvent(QPaintEvent *)
p.setClipRect(r);
QFontMetrics fm = fontMetrics();
+ int fmHeight = 0;
+ if (d->shouldShowPlaceholderText())
+ fmHeight = fm.boundingRect(d->placeholderText).height();
+ else
+ fmHeight = fm.boundingRect(d->control->text() + d->control->preeditAreaText()).height();
+ fmHeight = qMax(fmHeight, fm.height());
+
Qt::Alignment va = QStyle::visualAlignment(d->control->layoutDirection(), QFlag(d->alignment));
switch (va & Qt::AlignVertical_Mask) {
case Qt::AlignBottom:
- d->vscroll = r.y() + r.height() - fm.height() - QLineEditPrivate::verticalMargin;
+ d->vscroll = r.y() + r.height() - fmHeight - QLineEditPrivate::verticalMargin;
break;
case Qt::AlignTop:
d->vscroll = r.y() + QLineEditPrivate::verticalMargin;
break;
default:
//center
- d->vscroll = r.y() + (r.height() - fm.height() + 1) / 2;
+ d->vscroll = r.y() + (r.height() - fmHeight + 1) / 2;
break;
}
QRect lineRect(r.x() + QLineEditPrivate::horizontalMargin, d->vscroll,
- r.width() - 2 * QLineEditPrivate::horizontalMargin, fm.height());
+ r.width() - 2 * QLineEditPrivate::horizontalMargin, fmHeight);
if (d->shouldShowPlaceholderText()) {
if (!d->placeholderText.isEmpty()) {
@@ -2046,6 +2064,7 @@ void QLineEdit::paintEvent(QPaintEvent *)
}
// the y offset is there to keep the baseline constant in case we have script changes in the text.
+ // Needs to be kept in sync with QLineEditPrivate::adjustedControlRect
QPoint topLeft = lineRect.topLeft() - QPoint(d->hscroll, d->control->ascent() - fm.ascent());
// draw text, selections and cursors
@@ -2071,11 +2090,13 @@ void QLineEdit::paintEvent(QPaintEvent *)
// Asian users see an IM selection text as cursor on candidate
// selection phase of input method, so the ordinary cursor should be
- // invisible if we have a preedit string.
- if (d->cursorVisible && !d->control->isReadOnly())
+ // invisible if we have a preedit string. another condition is when inputmask
+ // isn't empty,we don't need draw cursor,because cursor and character overlapping
+ // area is white.
+ if (d->cursorVisible && !d->control->isReadOnly() && d->control->inputMask().isEmpty())
flags |= QWidgetLineControl::DrawCursor;
- d->control->setCursorWidth(style()->pixelMetric(QStyle::PM_TextCursorWidth));
+ d->control->setCursorWidth(style()->pixelMetric(QStyle::PM_TextCursorWidth, &panel, this));
d->control->draw(&p, topLeft, r, flags);
}
@@ -2087,9 +2108,9 @@ void QLineEdit::paintEvent(QPaintEvent *)
void QLineEdit::dragMoveEvent(QDragMoveEvent *e)
{
Q_D(QLineEdit);
- if (!d->control->isReadOnly() && e->mimeData()->hasFormat(QLatin1String("text/plain"))) {
+ if (!d->control->isReadOnly() && e->mimeData()->hasFormat("text/plain"_L1)) {
e->acceptProposedAction();
- d->control->moveCursor(d->xToPos(e->pos().x()), false);
+ d->control->moveCursor(d->xToPos(e->position().toPoint().x()), false);
d->cursorVisible = true;
update();
}
@@ -2120,7 +2141,7 @@ void QLineEdit::dropEvent(QDropEvent* e)
if (!str.isNull() && !d->control->isReadOnly()) {
if (e->source() == this && e->dropAction() == Qt::CopyAction)
deselect();
- int cursorPos = d->xToPos(e->pos().x());
+ int cursorPos = d->xToPos(e->position().toPoint().x());
int selStart = cursorPos;
int oldSelStart = d->control->selectionStart();
int oldSelEnd = d->control->selectionEnd();
@@ -2131,13 +2152,13 @@ void QLineEdit::dropEvent(QDropEvent* e)
if (e->source() == this) {
if (e->dropAction() == Qt::MoveAction) {
if (selStart > oldSelStart && selStart <= oldSelEnd)
- setSelection(oldSelStart, str.length());
+ setSelection(oldSelStart, str.size());
else if (selStart > oldSelEnd)
- setSelection(selStart - str.length(), str.length());
+ setSelection(selStart - str.size(), str.size());
else
- setSelection(selStart, str.length());
+ setSelection(selStart, str.size());
} else {
- setSelection(selStart, str.length());
+ setSelection(selStart, str.size());
}
}
} else {
@@ -2154,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
@@ -2174,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.
@@ -2191,19 +2205,19 @@ QMenu *QLineEdit::createStandardContextMenu()
{
Q_D(QLineEdit);
QMenu *popup = new QMenu(this);
- popup->setObjectName(QLatin1String("qt_edit_menu"));
+ popup->setObjectName("qt_edit_menu"_L1);
QAction *action = nullptr;
if (!isReadOnly()) {
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();
}
@@ -2214,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
@@ -2235,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())
@@ -2245,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();
@@ -2273,7 +2288,7 @@ void QLineEdit::changeEvent(QEvent *ev)
{
QStyleOptionFrame opt;
initStyleOption(&opt);
- d->control->setPasswordCharacter(style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, this));
+ d->control->setPasswordCharacter(char16_t(style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, this)));
d->control->setPasswordMaskDelay(style()->styleHint(QStyle::SH_LineEdit_PasswordMaskDelay, &opt, this));
}
update();
diff --git a/src/widgets/widgets/qlineedit.h b/src/widgets/widgets/qlineedit.h
index 1cf1f24449..8955a67895 100644
--- a/src/widgets/widgets/qlineedit.h
+++ b/src/widgets/widgets/qlineedit.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLINEEDIT_H
#define QLINEEDIT_H
@@ -172,10 +136,6 @@ public:
void setTextMargins(int left, int top, int right, int bottom);
void setTextMargins(const QMargins &margins);
-#if QT_DEPRECATED_SINCE(5, 14)
- QT_DEPRECATED_X("use textMargins()")
- void getTextMargins(int *left, int *top, int *right, int *bottom) const;
-#endif
QMargins textMargins() const;
#if QT_CONFIG(action)
@@ -218,6 +178,7 @@ protected:
void mouseReleaseEvent(QMouseEvent *) override;
void mouseDoubleClickEvent(QMouseEvent *) override;
void keyPressEvent(QKeyEvent *) override;
+ void keyReleaseEvent(QKeyEvent *) override;
void focusInEvent(QFocusEvent *) override;
void focusOutEvent(QFocusEvent *) override;
void paintEvent(QPaintEvent *) override;
@@ -233,10 +194,11 @@ protected:
#endif
void inputMethodEvent(QInputMethodEvent *) override;
- void initStyleOption(QStyleOptionFrame *option) const;
+ virtual void initStyleOption(QStyleOptionFrame *option) const;
public:
QVariant inputMethodQuery(Qt::InputMethodQuery) const override;
Q_INVOKABLE QVariant inputMethodQuery(Qt::InputMethodQuery property, QVariant argument) const;
+ void timerEvent(QTimerEvent *) override;
bool event(QEvent *) override;
protected:
QRect cursorRect() const;
@@ -252,19 +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())
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qlineedit_p.cpp b/src/widgets/widgets/qlineedit_p.cpp
index 29e0ae3b39..fdd6a3aa4f 100644
--- a/src/widgets/widgets/qlineedit_p.cpp
+++ b/src/widgets/widgets/qlineedit_p.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qlineedit.h"
#include "qlineedit_p.h"
@@ -51,7 +15,7 @@
# include "qwidgetaction.h"
#endif
#include "qclipboard.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
#ifndef QT_NO_IM
@@ -70,12 +34,13 @@ QT_BEGIN_NAMESPACE
const int QLineEditPrivate::verticalMargin(1);
const int QLineEditPrivate::horizontalMargin(2);
+// Needs to be kept in sync with QLineEdit::paintEvent
QRect QLineEditPrivate::adjustedControlRect(const QRect &rect) const
{
QRect widgetRect = !rect.isEmpty() ? rect : q_func()->rect();
QRect cr = adjustedContentsRect();
int cix = cr.x() - hscroll + horizontalMargin;
- return widgetRect.translated(QPoint(cix, vscroll));
+ return widgetRect.translated(QPoint(cix, vscroll - control->ascent() + q_func()->fontMetrics().ascent()));
}
int QLineEditPrivate::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const
@@ -85,6 +50,18 @@ int QLineEditPrivate::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const
return control->xToPos(x, betweenOrOn);
}
+QString QLineEditPrivate::textBeforeCursor(int curPos) const
+{
+ const QString &text = control->text();
+ return text.mid(0, curPos);
+}
+
+QString QLineEditPrivate::textAfterCursor(int curPos) const
+{
+ const QString &text = control->text();
+ return text.mid(curPos);
+}
+
bool QLineEditPrivate::inSelection(int x) const
{
x -= adjustedContentsRect().x() - hscroll + horizontalMargin;
@@ -97,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) {
@@ -106,7 +100,7 @@ void QLineEditPrivate::_q_completionHighlighted(const QString &newText)
} else {
int c = control->cursor();
QString text = control->text();
- q->setText(text.leftRef(c) + newText.midRef(c));
+ q->setText(QStringView{text}.left(c) + QStringView{newText}.mid(c));
control->moveCursor(control->end(), false);
#ifndef Q_OS_ANDROID
const bool mark = true;
@@ -119,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;
@@ -138,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();
@@ -146,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()) {
@@ -166,14 +160,14 @@ void QLineEditPrivate::_q_selectionChanged()
}
emit q->selectionChanged();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleTextSelectionEvent ev(q, control->selectionStart(), control->selectionEnd());
ev.setCursorPosition(control->cursorPosition());
QAccessible::updateAccessibility(&ev);
#endif
}
-void QLineEditPrivate::_q_updateNeeded(const QRect &rect)
+void QLineEditPrivate::updateNeeded(const QRect &rect)
{
q_func()->update(adjustedControlRect(rect));
}
@@ -181,51 +175,55 @@ 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(accepted()),
- q, SIGNAL(returnPressed()));
- QObject::connect(control, SIGNAL(editingFinished()),
- q, SIGNAL(editingFinished()));
+ 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);
- control->setPasswordCharacter(q->style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, q));
+ control->setPasswordCharacter(char16_t(q->style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, q)));
control->setPasswordMaskDelay(q->style()->styleHint(QStyle::SH_LineEdit_PasswordMaskDelay, &opt, q));
#ifndef QT_NO_CURSOR
q->setCursor(Qt::IBeamCursor);
@@ -302,9 +300,9 @@ bool QLineEditPrivate::sendMouseEventToInputContext( QMouseEvent *e )
{
#if !defined QT_NO_IM
if ( control->composeMode() ) {
- int tmp_cursor = xToPos(e->pos().x());
+ int tmp_cursor = xToPos(e->position().toPoint().x());
int mousePos = tmp_cursor - control->cursor();
- if ( mousePos < 0 || mousePos > control->preeditAreaText().length() )
+ if ( mousePos < 0 || mousePos > control->preeditAreaText().size() )
mousePos = -1;
if (mousePos >= 0) {
@@ -354,14 +352,13 @@ QLineEditPrivate *QLineEditIconButton::lineEditPrivate() const
void QLineEditIconButton::paintEvent(QPaintEvent *)
{
QPainter painter(this);
- QWindow *window = qt_widget_private(this)->windowHandle(QWidgetPrivate::WindowHandleMode::Closest);
QIcon::Mode state = QIcon::Disabled;
if (isEnabled())
state = isDown() ? QIcon::Active : QIcon::Normal;
const QLineEditPrivate *lep = lineEditPrivate();
const int iconWidth = lep ? lep->sideWidgetParameters().iconSize : 16;
const QSize iconSize(iconWidth, iconWidth);
- const QPixmap iconPixmap = icon().pixmap(window, iconSize, state, QIcon::Off);
+ const QPixmap iconPixmap = icon().pixmap(iconSize, devicePixelRatio(), state, QIcon::Off);
QRect pixmapRect = QRect(QPoint(0, 0), iconSize);
pixmapRect.moveCenter(rect().center());
painter.setOpacity(m_opacity);
@@ -408,8 +405,9 @@ void QLineEditIconButton::setHideWithText(bool hide)
void QLineEditIconButton::onAnimationFinished()
{
- if (shouldHideWithText() && isVisible() && !m_wasHidden) {
+ if (shouldHideWithText() && isVisible() && m_fadingOut) {
hide();
+ m_fadingOut = false;
// Invalidate previous geometry to take into account new size of side widgets
if (auto le = lineEditPrivate())
@@ -419,7 +417,7 @@ void QLineEditIconButton::onAnimationFinished()
void QLineEditIconButton::animateShow(bool visible)
{
- m_wasHidden = visible;
+ m_fadingOut = !visible;
if (shouldHideWithText() && !isVisible()) {
show();
@@ -434,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);
@@ -461,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();
@@ -476,21 +474,29 @@ void QLineEditPrivate::_q_textChanged(const QString &text)
}
}
-void QLineEditPrivate::_q_clearButtonClicked()
+void QLineEditPrivate::clearButtonClicked()
{
Q_Q(QLineEdit);
if (!q->text().isEmpty()) {
q->clear();
- emit q->textEdited(QString());
+ textEdited(QString());
}
}
+void QLineEditPrivate::controlEditingFinished()
+{
+ Q_Q(QLineEdit);
+ edited = false;
+ emit q->returnPressed();
+ emit q->editingFinished();
+}
+
QLineEditPrivate::SideWidgetParameters QLineEditPrivate::sideWidgetParameters() const
{
Q_Q(const QLineEdit);
SideWidgetParameters result;
- result.iconSize = q->style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, q);
- result.margin = result.iconSize / 4;
+ result.iconSize = q->style()->pixelMetric(QStyle::PM_LineEditIconSize, nullptr, q);
+ result.margin = q->style()->pixelMetric(QStyle::PM_LineEditIconMargin, nullptr, q);
result.widgetWidth = result.iconSize + 6;
result.widgetHeight = result.iconSize + 2;
return result;
@@ -548,7 +554,7 @@ void QLineEditPrivate::positionSideWidgets()
}
#if QT_CONFIG(action)
-QLineEditPrivate::SideWidgetLocation QLineEditPrivate::findSideWidget(const QGuiAction *a) const
+QLineEditPrivate::SideWidgetLocation QLineEditPrivate::findSideWidget(const QAction *a) const
{
int i = 0;
for (const auto &e : leadingSideWidgets) {
@@ -571,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;
@@ -587,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
@@ -635,7 +643,7 @@ QWidget *QLineEditPrivate::addAction(QAction *newAction, QAction *before, QLineE
return w;
}
-void QLineEditPrivate::removeAction(QGuiAction *action)
+void QLineEditPrivate::removeAction(QAction *action)
{
Q_Q(QLineEdit);
const auto location = findSideWidget(action);
@@ -650,7 +658,8 @@ void QLineEditPrivate::removeAction(QGuiAction *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)
@@ -661,10 +670,18 @@ static int effectiveTextMargin(int defaultMargin, const QLineEditPrivate::SideWi
if (widgets.empty())
return defaultMargin;
- return defaultMargin + (parameters.margin + parameters.widgetWidth) *
- int(std::count_if(widgets.begin(), widgets.end(),
+ const auto visibleSideWidgetCount = std::count_if(widgets.begin(), widgets.end(),
[](const QLineEditPrivate::SideWidgetEntry &e) {
- return e.widget->isVisibleTo(e.widget->parentWidget()); }));
+#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();
+
+#endif
+ return e.widget->isVisibleTo(e.widget->parentWidget());
+ });
+
+ return defaultMargin + (parameters.margin + parameters.widgetWidth) * visibleSideWidgetCount;
}
QMargins QLineEditPrivate::effectiveTextMargins() const
diff --git a/src/widgets/widgets/qlineedit_p.h b/src/widgets/widgets/qlineedit_p.h
index 9fe571b4bb..3737ac8fe6 100644
--- a/src/widgets/widgets/qlineedit_p.h
+++ b/src/widgets/widgets/qlineedit_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QLINEEDIT_P_H
#define QLINEEDIT_P_H
@@ -95,6 +59,11 @@ public:
bool shouldHideWithText() const;
void setHideWithText(bool hide);
+ bool needsSpace() const {
+ if (m_fadingOut)
+ return false;
+ return isVisibleTo(parentWidget());
+ }
#endif
protected:
@@ -118,7 +87,7 @@ private:
#if QT_CONFIG(animation)
bool m_hideWithText = false;
- bool m_wasHidden = false;
+ bool m_fadingOut = false;
#endif
};
@@ -179,13 +148,19 @@ public:
void setCursorVisible(bool visible);
void setText(const QString& text);
+ QString textBeforeCursor(int curPos) const;
+ QString textAfterCursor(int curPos) const;
void updatePasswordEchoEditing(bool);
void resetInputMethod();
inline bool shouldEnableInputMethod() const
{
+#if defined (Q_OS_ANDROID)
+ return !control->isReadOnly() || control->isSelectableByMouse();
+#else
return !control->isReadOnly();
+#endif
}
inline bool shouldShowPlaceholderText() const
{
@@ -215,24 +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 textChanged(const QString &);
+ void clearButtonClicked();
+ void controlEditingFinished();
QMargins textMargins; // use effectiveTextMargins() in case of icon.
@@ -240,7 +218,7 @@ public:
#if QT_CONFIG(action)
QWidget *addAction(QAction *newAction, QAction *before, QLineEdit::ActionPosition, int flags = 0);
- void removeAction(QGuiAction *action);
+ void removeAction(QAction *action);
#endif
SideWidgetParameters sideWidgetParameters() const;
QIcon clearButtonIcon() const;
@@ -264,7 +242,7 @@ private:
friend class QTypeInfo<SideWidgetLocation>;
#if QT_CONFIG(action)
- SideWidgetLocation findSideWidget(const QGuiAction *a) const;
+ SideWidgetLocation findSideWidget(const QAction *a) const;
#endif
SideWidgetEntryList leadingSideWidgets;
diff --git a/src/widgets/widgets/qmaccocoaviewcontainer_mac.h b/src/widgets/widgets/qmaccocoaviewcontainer_mac.h
deleted file mode 100644
index 0de3989167..0000000000
--- a/src/widgets/widgets/qmaccocoaviewcontainer_mac.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QCOCOAVIEWCONTAINER_H
-#define QCOCOAVIEWCONTAINER_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtWidgets/QWidget>
-
-Q_FORWARD_DECLARE_OBJC_CLASS(NSView);
-
-QT_BEGIN_NAMESPACE
-
-class QMacCocoaViewContainerPrivate;
-class Q_WIDGETS_EXPORT QMacCocoaViewContainer : public QWidget
-{
- Q_OBJECT
-public:
- QMacCocoaViewContainer(NSView *cocoaViewToWrap, QWidget *parent = nullptr);
- virtual ~QMacCocoaViewContainer();
-
- void setCocoaView(NSView *view);
- NSView *cocoaView() const;
-
-private:
- Q_DECLARE_PRIVATE(QMacCocoaViewContainer)
-};
-
-QT_END_NAMESPACE
-
-#endif // QCOCOAVIEWCONTAINER_H
diff --git a/src/widgets/widgets/qmaccocoaviewcontainer_mac.mm b/src/widgets/widgets/qmaccocoaviewcontainer_mac.mm
deleted file mode 100644
index f261314c64..0000000000
--- a/src/widgets/widgets/qmaccocoaviewcontainer_mac.mm
+++ /dev/null
@@ -1,199 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#import <AppKit/AppKit.h>
-#include "qmaccocoaviewcontainer_mac.h"
-
-#include <QtCore/QDebug>
-#include <QtGui/QWindow>
-#include <qpa/qplatformnativeinterface.h>
-#include <private/qwidget_p.h>
-#include <private/qwindow_p.h>
-
-/*!
- \class QMacCocoaViewContainer
- \since 4.5
-
- \brief The QMacCocoaViewContainer class provides a widget for \macos that can be used to wrap arbitrary
- Cocoa views (i.e., NSView subclasses) and insert them into Qt hierarchies.
-
- \ingroup advanced
- \inmodule QtWidgets
-
- While Qt offers a lot of classes for writing your application, Apple's
- Cocoa frameworks offer functionality that is not currently available (or
- may never end up) in Qt. Using QMacCocoaViewContainer, it is possible to take an
- arbitrary NSView-derived class from Cocoa and put it in a Qt widgets hierarchy.
- Depending on the level of integration you need, you can use QMacCocoaViewContainer
- directly or subclass it to wrap more functionality of the underlying NSView.
-
- It should be also noted that, at the Cocoa level, there is a difference
- between top-level windows and views (widgets that are inside a window).
- For this reason, make sure that the NSView that you are wrapping doesn't
- end up as a top-level window. The best way to ensure this is to make sure
- QMacCocoaViewContainer's parent widget is not null.
-
- If you are using QMacCocoaViewContainer as a subclass and are accessing Cocoa API,
- it is probably simpler to have your file end with \tt{.mm} instead of \tt{.cpp}.
- Most Apple tools will correctly identify the source as Objective-C++.
-
- QMacCocoaViewContainer requires knowledge of how Cocoa works, especially in
- regard to its reference counting (retain/release) nature. It is noted in
- the functions below if there is any change in the reference count. Cocoa
- views often generate temporary objects that are released by an autorelease
- pool. If this is done outside of a running event loop, it is up to the
- developer to provide the autorelease pool.
-
- The following is a snippet showing how to subclass QMacCocoaViewContainer
- to wrap an NSSearchField.
-
- \code
- SearchWidget::SearchWidget(QWidget *parent)
- : QMacCocoaViewContainer(0, parent)
- {
- // Many Cocoa objects create temporary autorelease objects,
- // so create a pool to catch them.
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
- // Create the NSSearchField, set it on the QCocoaViewContainer.
- NSSearchField *search = [[NSSearchField alloc] init];
- setCocoaView(search);
-
- // Use a Qt menu for the search field menu.
- QMenu *qtMenu = createMenu(this);
- NSMenu *nsMenu = qtMenu->macMenu(0);
- [[search cell] setSearchMenuTemplate:nsMenu];
-
- // Release our reference, since our super class takes ownership and we
- // don't need it anymore.
- [search release];
-
- // Clean up our pool as we no longer need it.
- [pool release];
- }
- \endcode
-*/
-
-QT_BEGIN_NAMESPACE
-
-class QMacCocoaViewContainerPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QMacCocoaViewContainer)
-public:
- NSView *nsview;
- QMacCocoaViewContainerPrivate();
- ~QMacCocoaViewContainerPrivate();
-};
-
-QMacCocoaViewContainerPrivate::QMacCocoaViewContainerPrivate()
- : nsview(0)
-{
-}
-
-QMacCocoaViewContainerPrivate::~QMacCocoaViewContainerPrivate()
-{
- [nsview release];
-}
-
-/*!
- Create a new QMacCocoaViewContainer using the NSView pointer in
- the \a view with parent, \a parent. QMacCocoaViewContainer will
- retain the \a view.
-
-*/
-QMacCocoaViewContainer::QMacCocoaViewContainer(NSView *view, QWidget *parent)
- : QWidget(*new QMacCocoaViewContainerPrivate, parent, {})
-{
- // Ensures that we have a QWindow, even if we're not a top level widget
- setAttribute(Qt::WA_NativeWindow);
-
- setCocoaView(view);
-}
-
-/*!
- Destroy the QMacCocoaViewContainer and release the wrapped view.
-*/
-QMacCocoaViewContainer::~QMacCocoaViewContainer()
-{
-
-}
-
-/*!
- Returns the NSView that has been set on this container.
-*/
-NSView *QMacCocoaViewContainer::cocoaView() const
-{
- Q_D(const QMacCocoaViewContainer);
- return d->nsview;
-}
-
-/*!
- Sets \a view as the NSView to contain and retains it. If this
- container already had a view set, it will release the previously set view.
-*/
-void QMacCocoaViewContainer::setCocoaView(NSView *view)
-{
- Q_D(QMacCocoaViewContainer);
- NSView *oldView = d->nsview;
- [view retain];
- d->nsview = view;
-
- // Get rid of QWindow completely, and re-create a new vanilla one, which
- // we will then re-configure to be a foreign window.
- destroy();
- create();
-
- // Can't use QWindow::fromWinId() here due to QWidget controlling its
- // QWindow, and can't use QWidget::createWindowContainer() due to the
- // QMacCocoaViewContainer class being public API instead of a factory
- // function.
- QWindow *window = windowHandle();
- window->destroy();
- qt_window_private(window)->create(false, WId(view));
- Q_ASSERT(window->handle());
-
- [oldView release];
-
- // The QWindow::destroy()) call above will explicitly hide this widget.
- // Clear the hidden state here so it can be implicitly shown again.
- setAttribute(Qt::WA_WState_Hidden, false);
-
-}
-
-QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qmacnativewidget_mac.h b/src/widgets/widgets/qmacnativewidget_mac.h
deleted file mode 100644
index 6fd90516ac..0000000000
--- a/src/widgets/widgets/qmacnativewidget_mac.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QMACNATIVEWIDGET_H
-#define QMACNATIVEWIDGET_H
-
-#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtWidgets/QWidget>
-
-Q_FORWARD_DECLARE_OBJC_CLASS(NSView);
-
-QT_BEGIN_NAMESPACE
-
-class Q_WIDGETS_EXPORT QMacNativeWidget : public QWidget
-{
- Q_OBJECT
-public:
- QMacNativeWidget(NSView *parentView = nullptr);
- ~QMacNativeWidget();
-
- QSize sizeHint() const override;
- NSView *nativeView() const;
-
-protected:
- bool event(QEvent *ev) override;
-};
-
-QT_END_NAMESPACE
-
-#endif // QMACNATIVEWIDGET_H
diff --git a/src/widgets/widgets/qmacnativewidget_mac.mm b/src/widgets/widgets/qmacnativewidget_mac.mm
deleted file mode 100644
index 874ca84b61..0000000000
--- a/src/widgets/widgets/qmacnativewidget_mac.mm
+++ /dev/null
@@ -1,166 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#import <AppKit/AppKit.h>
-#include "qmacnativewidget_mac.h"
-
-#include <QtCore/qdebug.h>
-#include <QtGui/qwindow.h>
-#include <QtGui/qguiapplication.h>
-#include <qpa/qplatformnativeinterface.h>
-
-/*!
- \class QMacNativeWidget
- \since 4.5
- \brief The QMacNativeWidget class provides a widget for \macos that provides
- a way to put Qt widgets into Cocoa hierarchies.
-
- \ingroup advanced
- \inmodule QtWidgets
-
- On \macos, there is a difference between a window and view;
- normally expressed as widgets in Qt. Qt makes assumptions about its
- parent-child hierarchy that make it complex to put an arbitrary Qt widget
- into a hierarchy of "normal" views from Apple frameworks. QMacNativeWidget
- bridges the gap between views and windows and makes it possible to put a
- hierarchy of Qt widgets into a non-Qt window or view.
-
- QMacNativeWidget pretends it is a window (i.e. isWindow() will return true),
- but it cannot be shown on its own. It needs to be put into a window
- when it is created or later through a native call.
-
- Here is an example showing how to put a QPushButton into a NSWindow:
-
- \snippet qmacnativewidget/main.mm 0
-
- Note that QMacNativeWidget requires knowledge of Cocoa. All it
- does is get the Qt hierarchy into a window not owned by Qt. It is then up
- to the programmer to ensure it is placed correctly in the window and
- responds correctly to events.
-*/
-
-QT_BEGIN_NAMESPACE
-
-namespace {
-// TODO use QtMacExtras copy of this function when available.
-inline QPlatformNativeInterface::NativeResourceForIntegrationFunction resolvePlatformFunction(const QByteArray &functionName)
-{
- QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
- QPlatformNativeInterface::NativeResourceForIntegrationFunction function =
- nativeInterface->nativeResourceFunctionForIntegration(functionName);
- if (Q_UNLIKELY(!function))
- qWarning("Qt could not resolve function %s from "
- "QGuiApplication::platformNativeInterface()->nativeResourceFunctionForIntegration()",
- functionName.constData());
- return function;
-}
-} //namespsace
-
-NSView *getEmbeddableView(QWindow *qtWindow)
-{
- // Make sure the platform window is created
- qtWindow->create();
-
- // Inform the window that it's a subwindow of a non-Qt window. This must be
- // done after create() because we need to have a QPlatformWindow instance.
- // The corresponding NSWindow will not be shown and can be deleted later.
- typedef void (*SetEmbeddedInForeignViewFunction)(QPlatformWindow *window, bool embedded);
- reinterpret_cast<SetEmbeddedInForeignViewFunction>(resolvePlatformFunction("setEmbeddedInForeignView"))(qtWindow->handle(), true);
-
- // Get the Qt content NSView for the QWindow from the Qt platform plugin
- QPlatformNativeInterface *platformNativeInterface = QGuiApplication::platformNativeInterface();
- NSView *qtView = (NSView *)platformNativeInterface->nativeResourceForWindow("nsview", qtWindow);
- return qtView; // qtView is ready for use.
-}
-
-/*!
- Create a QMacNativeWidget with \a parentView as its "superview" (i.e.,
- parent). The \a parentView is a NSView pointer.
-*/
-QMacNativeWidget::QMacNativeWidget(NSView *parentView)
- : QWidget(0)
-{
- Q_UNUSED(parentView);
-
- //d_func()->topData()->embedded = true;
- setPalette(QPalette(Qt::transparent));
- setAttribute(Qt::WA_SetPalette, false);
- setAttribute(Qt::WA_LayoutUsesWidgetRect);
- setAttribute(Qt::WA_TranslucentBackground);
- setAttribute(Qt::WA_NoSystemBackground, false);
-}
-
-/*!
- Destroy the QMacNativeWidget.
-*/
-QMacNativeWidget::~QMacNativeWidget()
-{
-}
-
-/*!
- \reimp
-*/
-QSize QMacNativeWidget::sizeHint() const
-{
- // QMacNativeWidget really does not have any other choice
- // than to fill its designated area.
- if (windowHandle())
- return windowHandle()->size();
- return QWidget::sizeHint();
-}
-
-/*!
- Returns the native view backing the QMacNativeWidget.
-
-*/
-NSView *QMacNativeWidget::nativeView() const
-{
- winId();
- return getEmbeddableView(windowHandle());
-}
-
-/*!
- \reimp
-*/
-bool QMacNativeWidget::event(QEvent *ev)
-{
- return QWidget::event(ev);
-}
-
-QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qmainwindow.cpp b/src/widgets/widgets/qmainwindow.cpp
index 4f94b81b19..4534058d45 100644
--- a/src/widgets/widgets/qmainwindow.cpp
+++ b/src/widgets/widgets/qmainwindow.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
//#define QT_EXPERIMENTAL_CLIENT_DECORATIONS
@@ -61,40 +25,42 @@
#include <qstyle.h>
#include <qdebug.h>
#include <qpainter.h>
+#include <qmimedata.h>
#include <private/qwidget_p.h>
#if QT_CONFIG(toolbar)
#include "qtoolbar_p.h"
#endif
#include "qwidgetanimator_p.h"
-#ifdef Q_OS_OSX
-#include <qpa/qplatformnativeinterface.h>
-#endif
+#include <QtGui/qpa/qplatformwindow.h>
+#include <QtGui/qpa/qplatformwindow_p.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
class QMainWindowPrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QMainWindow)
public:
inline QMainWindowPrivate()
: layout(nullptr), explicitIconSize(false), toolButtonStyle(Qt::ToolButtonIconOnly)
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
, useUnifiedToolBar(false)
#endif
{ }
- QMainWindowLayout *layout;
+ QPointer<QMainWindowLayout> layout;
QSize iconSize;
bool explicitIconSize;
Qt::ToolButtonStyle toolButtonStyle;
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
bool useUnifiedToolBar;
#endif
void init();
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);
}
};
@@ -158,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);
}
/*
@@ -214,9 +181,6 @@ void QMainWindowPrivate::init()
\image mainwindowlayout.png
- \note Creating a main window without a central widget is not supported.
- You must have a central widget even if it is just a placeholder.
-
\section1 Creating Main Window Components
A central widget will typically be a standard Qt widget such
@@ -316,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, {Application
- Example}, {Dock Widgets Example}, {MDI Example}, {SDI Example},
- {Menus Example}
+ \sa QMenuBar, QToolBar, QStatusBar, QDockWidget, {Menus Example}
*/
/*!
@@ -523,10 +485,10 @@ void QMainWindow::setMenuBar(QMenuBar *menuBar)
{
QLayout *topLayout = layout();
- if (topLayout->menuBar() && topLayout->menuBar() != menuBar) {
+ if (QWidget *existingMenuBar = topLayout->menuBar(); existingMenuBar && existingMenuBar != menuBar) {
// Reparent corner widgets before we delete the old menu bar.
- QMenuBar *oldMenuBar = qobject_cast<QMenuBar *>(topLayout->menuBar());
- if (menuBar) {
+ QMenuBar *oldMenuBar = qobject_cast<QMenuBar *>(existingMenuBar);
+ if (oldMenuBar && menuBar) {
// TopLeftCorner widget.
QWidget *cornerWidget = oldMenuBar->cornerWidget(Qt::TopLeftCorner);
if (cornerWidget)
@@ -536,9 +498,10 @@ void QMainWindow::setMenuBar(QMenuBar *menuBar)
if (cornerWidget)
menuBar->setCornerWidget(cornerWidget, Qt::TopRightCorner);
}
- oldMenuBar->hide();
- oldMenuBar->setParent(nullptr);
- oldMenuBar->deleteLater();
+
+ existingMenuBar->hide();
+ existingMenuBar->setParent(nullptr);
+ existingMenuBar->deleteLater();
}
topLayout->setMenuBar(menuBar);
}
@@ -615,7 +578,7 @@ void QMainWindow::setStatusBar(QStatusBar *statusbar)
/*!
Returns the central widget for the main window. This function
- returns zero if the central widget has not been set.
+ returns \nullptr if the central widget has not been set.
\sa setCentralWidget()
*/
@@ -762,7 +725,7 @@ void QMainWindow::addToolBar(Qt::ToolBarArea area, QToolBar *toolbar)
disconnect(this, SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)),
toolbar, SLOT(_q_updateToolButtonStyle(Qt::ToolButtonStyle)));
- if(toolbar->d_func()->state && toolbar->d_func()->state->dragging) {
+ if (toolbar->d_func()->state && toolbar->d_func()->state->dragging) {
//removing a toolbar which is dragging will cause crash
#if QT_CONFIG(dockwidget)
bool animated = isAnimated();
@@ -851,11 +814,7 @@ void QMainWindow::removeToolBar(QToolBar *toolbar)
\sa addToolBar(), addToolBarBreak(), Qt::ToolBarArea
*/
-Qt::ToolBarArea QMainWindow::toolBarArea(
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
- const
-#endif
- QToolBar *toolbar) const
+Qt::ToolBarArea QMainWindow::toolBarArea(const QToolBar *toolbar) const
{ return d_func()->layout->toolBarArea(toolbar); }
/*!
@@ -954,10 +913,10 @@ void QMainWindow::setDockNestingEnabled(bool enabled)
\since 4.2
If this property is set to false, dock areas containing tabbed dock widgets
- display horizontal tabs, simmilar to Visual Studio.
+ display horizontal tabs, similar to Visual Studio.
If this property is set to true, then the right and left dock areas display vertical
- tabs, simmilar to KDevelop.
+ tabs, similar to KDevelop.
This property should be set before any dock widgets are added to the main window.
*/
@@ -1164,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.count(); ++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)
@@ -1223,7 +1169,7 @@ Qt::DockWidgetArea QMainWindow::dockWidgetArea(QDockWidget *dockwidget) const
resized such that the yellowWidget is twice as big as the blueWidget
If some widgets are grouped in tabs, only one widget per group should be
- specified. Widgets not in the list might be changed to repect the constraints.
+ specified. Widgets not in the list might be changed to respect the constraints.
*/
void QMainWindow::resizeDocks(const QList<QDockWidget *> &docks,
const QList<int> &sizes, Qt::Orientation orientation)
@@ -1260,6 +1206,7 @@ QByteArray QMainWindow::saveState(int version) const
{
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
+ stream.setVersion(QDataStream::Qt_5_0);
stream << QMainWindowLayout::VersionMarker;
stream << version;
d_func()->layout->saveState(stream);
@@ -1288,6 +1235,7 @@ bool QMainWindow::restoreState(const QByteArray &state, int version)
return false;
QByteArray sd = state;
QDataStream stream(&sd, QIODevice::ReadOnly);
+ stream.setVersion(QDataStream::Qt_5_0);
int marker, v;
stream >> marker;
stream >> v;
@@ -1311,6 +1259,7 @@ bool QMainWindow::event(QEvent *event)
#if QT_CONFIG(toolbar)
case QEvent::ToolBarChange: {
+ Q_ASSERT(d->layout);
d->layout->toggleToolBarsVisible();
return true;
}
@@ -1319,6 +1268,7 @@ bool QMainWindow::event(QEvent *event)
#if QT_CONFIG(statustip)
case QEvent::StatusTip:
#if QT_CONFIG(statusbar)
+ Q_ASSERT(d->layout);
if (QStatusBar *sb = d->layout->statusBar())
sb->showMessage(static_cast<QStatusTipEvent*>(event)->tip());
else
@@ -1329,11 +1279,34 @@ bool QMainWindow::event(QEvent *event)
case QEvent::StyleChange:
#if QT_CONFIG(dockwidget)
+ Q_ASSERT(d->layout);
d->layout->layoutState.dockAreaLayout.styleChangedEvent();
#endif
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;
}
@@ -1349,40 +1322,42 @@ bool QMainWindow::event(QEvent *event)
Note that the Qt 5 implementation has several limitations compared to Qt 4:
\list
- \li Use in windows with OpenGL content is not supported. This includes QGLWidget and QOpenGLWidget.
+ \li Use in windows with OpenGL content is not supported. This includes QOpenGLWidget.
\li Using dockable or movable toolbars may result in painting errors and is not recommended
\endlist
\since 5.2
*/
-void QMainWindow::setUnifiedTitleAndToolBarOnMac(bool set)
+void QMainWindow::setUnifiedTitleAndToolBarOnMac(bool enabled)
{
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
+ if (!isWindow())
+ return;
+
Q_D(QMainWindow);
- if (isWindow()) {
- d->useUnifiedToolBar = set;
- createWinId();
-
- QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
- if (!nativeInterface)
- return; // Not Cocoa platform plugin.
- QPlatformNativeInterface::NativeResourceForIntegrationFunction function =
- nativeInterface->nativeResourceFunctionForIntegration("setContentBorderEnabled");
- if (!function)
- return; // Not Cocoa platform plugin.
-
- typedef void (*SetContentBorderEnabledFunction)(QWindow *window, bool enable);
- (reinterpret_cast<SetContentBorderEnabledFunction>(function))(window()->windowHandle(), set);
- update();
- }
+ d->useUnifiedToolBar = enabled;
+
+ // The unified toolbar is drawn by the macOS style with a transparent background.
+ // To ensure a suitable surface format is used we need to first create backing
+ // QWindow so we have something to update the surface format on, and then let
+ // QWidget know about the translucency, which it will propagate to the surface.
+ setAttribute(Qt::WA_NativeWindow);
+ setAttribute(Qt::WA_TranslucentBackground, enabled);
+
+ d->create(); // Create first, before querying the platform window
+ using namespace QNativeInterface::Private;
+ if (auto *platformWindow = dynamic_cast<QCocoaWindow*>(window()->windowHandle()->handle()))
+ platformWindow->setContentBorderEnabled(enabled);
+
+ update();
#else
- Q_UNUSED(set)
+ Q_UNUSED(enabled);
#endif
}
bool QMainWindow::unifiedTitleAndToolBarOnMac() const
{
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
return d_func()->useUnifiedToolBar;
#endif
return false;
diff --git a/src/widgets/widgets/qmainwindow.h b/src/widgets/widgets/qmainwindow.h
index c69451fa3e..a050093417 100644
--- a/src/widgets/widgets/qmainwindow.h
+++ b/src/widgets/widgets/qmainwindow.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDYNAMICMAINWINDOW_H
#define QDYNAMICMAINWINDOW_H
@@ -75,7 +39,8 @@ class Q_WIDGETS_EXPORT QMainWindow : public QWidget
#endif // QT_CONFIG(dockwidget)
Q_PROPERTY(DockOptions dockOptions READ dockOptions WRITE setDockOptions)
#if QT_CONFIG(toolbar)
- Q_PROPERTY(bool unifiedTitleAndToolBarOnMac READ unifiedTitleAndToolBarOnMac WRITE setUnifiedTitleAndToolBarOnMac)
+ Q_PROPERTY(bool unifiedTitleAndToolBarOnMac READ unifiedTitleAndToolBarOnMac
+ WRITE setUnifiedTitleAndToolBarOnMac)
#endif
public:
@@ -158,13 +123,10 @@ public:
bool unifiedTitleAndToolBarOnMac() const;
- Qt::ToolBarArea toolBarArea(
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
- const
-#endif
- QToolBar *toolbar) const;
+ Qt::ToolBarArea toolBarArea(const QToolBar *toolbar) const;
bool toolBarBreak(QToolBar *toolbar) const;
-#endif
+#endif // QT_CONFIG(toolbar)
+
#if QT_CONFIG(dockwidget)
void addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget);
void addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget,
@@ -216,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 30562d8270..db17e50d5c 100644
--- a/src/widgets/widgets/qmainwindowlayout.cpp
+++ b/src/widgets/widgets/qmainwindowlayout.cpp
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qmainwindowlayout_p.h"
@@ -60,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
@@ -82,8 +50,12 @@
#include <private/qlayoutengine_p.h>
#include <private/qwidgetresizehandler_p.h>
+#include <QScopedValueRollback>
+
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
/******************************************************************************
@@ -100,14 +72,14 @@ static void dumpLayout(QTextStream &qout, const QDockAreaLayoutItem &item, QStri
<< "pos: " << item.pos << " size:" << item.size
<< " gap:" << (item.flags & QDockAreaLayoutItem::GapItem)
<< " keepSize:" << (item.flags & QDockAreaLayoutItem::KeepSize) << '\n';
- indent += QLatin1String(" ");
+ indent += " "_L1;
if (item.widgetItem != nullptr) {
qout << indent << "widget: "
<< item.widgetItem->widget()->metaObject()->className()
<< " \"" << item.widgetItem->widget()->windowTitle() << "\"\n";
} else if (item.subinfo != nullptr) {
qout << indent << "subinfo:\n";
- dumpLayout(qout, *item.subinfo, indent + QLatin1String(" "));
+ dumpLayout(qout, *item.subinfo, indent + " "_L1);
} else if (item.placeHolderItem != nullptr) {
QRect r = item.placeHolderItem->topLevelRect;
qout << indent << "placeHolder: "
@@ -138,11 +110,11 @@ static void dumpLayout(QTextStream &qout, const QDockAreaLayoutInfo &layout, QSt
#endif
<< '\n';
- indent += QLatin1String(" ");
+ indent += " "_L1;
- for (int i = 0; i < layout.item_list.count(); ++i) {
+ for (int i = 0; i < layout.item_list.size(); ++i) {
qout << indent << "Item: " << i << '\n';
- dumpLayout(qout, layout.item_list.at(i), indent + QLatin1String(" "));
+ dumpLayout(qout, layout.item_list.at(i), indent + " "_L1);
}
}
@@ -155,13 +127,13 @@ static void dumpLayout(QTextStream &qout, const QDockAreaLayout &layout)
<< layout.rect.height() << '\n';
qout << "TopDockArea:\n";
- dumpLayout(qout, layout.docks[QInternal::TopDock], QLatin1String(" "));
+ dumpLayout(qout, layout.docks[QInternal::TopDock], " "_L1);
qout << "LeftDockArea:\n";
- dumpLayout(qout, layout.docks[QInternal::LeftDock], QLatin1String(" "));
+ dumpLayout(qout, layout.docks[QInternal::LeftDock], " "_L1);
qout << "RightDockArea:\n";
- dumpLayout(qout, layout.docks[QInternal::RightDock], QLatin1String(" "));
+ dumpLayout(qout, layout.docks[QInternal::RightDock], " "_L1);
qout << "BottomDockArea:\n";
- dumpLayout(qout, layout.docks[QInternal::BottomDock], QLatin1String(" "));
+ dumpLayout(qout, layout.docks[QInternal::BottomDock], " "_L1);
}
QDebug operator<<(QDebug debug, const QDockAreaLayout &layout)
@@ -179,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>
@@ -200,7 +211,6 @@ public:
QDockWidgetGroupLayout(QDockWidgetGroupWindow* parent) : QLayout(parent) {
setSizeConstraint(QLayout::SetMinAndMaxSize);
resizer = new QWidgetResizeHandler(parent);
- resizer->setMovingEnabled(false);
}
~QDockWidgetGroupLayout() {
layoutState.deleteAllLayoutItems();
@@ -259,7 +269,7 @@ public:
li->apply(false);
if (savedState.rect.isValid())
savedState.rect = li->rect;
- resizer->setActive(QWidgetResizeHandler::Resize, !nativeWindowDeco());
+ resizer->setEnabled(!nativeWindowDeco());
}
QDockAreaLayoutInfo *dockAreaLayoutInfo() { return &layoutState; }
@@ -295,7 +305,6 @@ bool QDockWidgetGroupWindow::event(QEvent *e)
#if QT_CONFIG(tabbar)
// Forward the close to the QDockWidget just as if its close button was pressed
if (QDockWidget *dw = activeTabbedDockWidget()) {
- e->ignore();
dw->close();
adjustFlags();
}
@@ -329,6 +338,7 @@ bool QDockWidgetGroupWindow::event(QEvent *e)
case QEvent::Resize:
updateCurrentGapRect();
emit resized();
+ break;
default:
break;
}
@@ -342,7 +352,7 @@ void QDockWidgetGroupWindow::paintEvent(QPaintEvent *)
if (!nativeDeco) {
QStyleOptionFrame framOpt;
- framOpt.init(this);
+ framOpt.initFrom(this);
QStylePainter p(this);
p.drawPrimitive(QStyle::PE_FrameDockWidget, framOpt);
}
@@ -402,7 +412,7 @@ QDockWidget *QDockWidgetGroupWindow::activeTabbedDockWidget() const
}
}
if (!dw) {
- for (int i = 0; !dw && i < info->item_list.count(); ++i) {
+ for (int i = 0; !dw && i < info->item_list.size(); ++i) {
const QDockAreaLayoutItem &item = info->item_list.at(i);
if (item.skip())
continue;
@@ -421,22 +431,24 @@ QDockWidget *QDockWidgetGroupWindow::activeTabbedDockWidget() const
*/
void QDockWidgetGroupWindow::destroyOrHideIfEmpty()
{
- if (!layoutInfo()->isEmpty()) {
+ const QDockAreaLayoutInfo *info = layoutInfo();
+ if (!info->isEmpty()) {
show(); // It might have been hidden,
return;
}
// There might still be placeholders
- if (!layoutInfo()->item_list.isEmpty()) {
+ if (!info->item_list.isEmpty()) {
hide();
return;
}
// Make sure to reparent the possibly floating or hidden QDockWidgets to the parent
- const auto dockWidgets = findChildren<QDockWidget *>(QString(), Qt::FindDirectChildrenOnly);
- for (QDockWidget *dw : dockWidgets) {
- bool wasFloating = dw->isFloating();
- bool wasHidden = dw->isHidden();
+ const auto dockWidgetsList = dockWidgets();
+ for (QDockWidget *dw : dockWidgetsList) {
+ const bool wasFloating = dw->isFloating();
+ const bool wasHidden = dw->isHidden();
dw->setParent(parentWidget());
+ qCDebug(lcQpaDockWidgets) << "Reparented:" << dw << "to" << parentWidget() << "by" << this;
if (wasFloating) {
dw->setFloating(true);
} else {
@@ -445,20 +457,35 @@ void QDockWidgetGroupWindow::destroyOrHideIfEmpty()
qt_mainwindow_layout(static_cast<QMainWindow *>(parentWidget()));
Qt::DockWidgetArea area = ml->dockWidgetArea(this);
if (area == Qt::NoDockWidgetArea)
- area = Qt::LeftDockWidgetArea;
+ area = Qt::LeftDockWidgetArea; // FIXME: DockWidget doesn't save original docking area
static_cast<QMainWindow *>(parentWidget())->addDockWidget(area, dw);
+ qCDebug(lcQpaDockWidgets) << "Redocked to Mainwindow:" << area << dw << "by" << this;
}
if (!wasHidden)
dw->show();
}
-#if QT_CONFIG(tabbar)
- const auto tabBars = findChildren<QTabBar *>(QString(), 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
*/
@@ -507,7 +534,7 @@ void QDockWidgetGroupWindow::adjustFlags()
m_removedFrameSize = QSize();
}
- show(); // setWindowFlags hides the window
+ setVisible(hasVisibleDockWidgets());
}
QWidget *titleBarOf = top ? top : parentWidget();
@@ -568,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();
@@ -616,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
/******************************************************************************
@@ -647,7 +780,7 @@ QSize QMainWindowLayoutState::sizeHint() const
#if QT_CONFIG(dockwidget)
result = dockAreaLayout.sizeHint();
#else
- if (centralWidgetItem != 0)
+ if (centralWidgetItem)
result = centralWidgetItem->sizeHint();
#endif
@@ -665,7 +798,7 @@ QSize QMainWindowLayoutState::minimumSize() const
#if QT_CONFIG(dockwidget)
result = dockAreaLayout.minimumSize();
#else
- if (centralWidgetItem != 0)
+ if (centralWidgetItem)
result = centralWidgetItem->minimumSize();
#endif
@@ -676,6 +809,31 @@ QSize QMainWindowLayoutState::minimumSize() const
return result;
}
+/*!
+ \internal
+
+ Returns whether the layout fits into the main window.
+*/
+bool QMainWindowLayoutState::fits() const
+{
+ Q_ASSERT(mainWindow);
+
+ QSize size;
+
+#if QT_CONFIG(dockwidget)
+ size = dockAreaLayout.minimumStableSize();
+#endif
+
+#if QT_CONFIG(toolbar)
+ size.rwidth() += toolBarAreaLayout.docks[QInternal::LeftDock].rect.width();
+ size.rwidth() += toolBarAreaLayout.docks[QInternal::RightDock].rect.width();
+ size.rheight() += toolBarAreaLayout.docks[QInternal::TopDock].rect.height();
+ size.rheight() += toolBarAreaLayout.docks[QInternal::BottomDock].rect.height();
+#endif
+
+ return size.width() <= mainWindow->width() && size.height() <= mainWindow->height();
+}
+
void QMainWindowLayoutState::apply(bool animated)
{
#if QT_CONFIG(toolbar)
@@ -686,9 +844,9 @@ void QMainWindowLayoutState::apply(bool animated)
// dumpLayout(dockAreaLayout, QString());
dockAreaLayout.apply(animated);
#else
- if (centralWidgetItem != 0) {
+ if (centralWidgetItem) {
QMainWindowLayout *layout = qt_mainwindow_layout(mainWindow);
- Q_ASSERT(layout != 0);
+ Q_ASSERT(layout);
layout->widgetAnimator.animate(centralWidgetItem->widget(), centralWidgetRect, animated);
}
#endif
@@ -745,7 +903,7 @@ QLayoutItem *QMainWindowLayoutState::itemAt(int index, int *x) const
if (QLayoutItem *ret = dockAreaLayout.itemAt(x, index))
return ret;
#else
- if (centralWidgetItem != 0 && (*x)++ == index)
+ if (centralWidgetItem && (*x)++ == index)
return centralWidgetItem;
#endif
@@ -763,9 +921,9 @@ QLayoutItem *QMainWindowLayoutState::takeAt(int index, int *x)
if (QLayoutItem *ret = dockAreaLayout.takeAt(x, index))
return ret;
#else
- if (centralWidgetItem != 0 && (*x)++ == index) {
+ if (centralWidgetItem && (*x)++ == index) {
QLayoutItem *ret = centralWidgetItem;
- centralWidgetItem = 0;
+ centralWidgetItem = nullptr;
return ret;
}
#endif
@@ -808,7 +966,7 @@ bool QMainWindowLayoutState::contains(QWidget *widget) const
if (!dockAreaLayout.indexOf(widget).isEmpty())
return true;
#else
- if (centralWidgetItem != 0 && centralWidgetItem->widget() == widget)
+ if (centralWidgetItem && centralWidgetItem->widget() == widget)
return true;
#endif
@@ -857,7 +1015,7 @@ QList<int> QMainWindowLayoutState::gapIndex(QWidget *widget,
#if QT_CONFIG(toolbar)
// is it a toolbar?
- if (qobject_cast<QToolBar*>(widget) != 0) {
+ if (qobject_cast<QToolBar*>(widget) != nullptr) {
result = toolBarAreaLayout.gapIndex(pos);
if (!result.isEmpty())
result.prepend(0);
@@ -867,7 +1025,7 @@ QList<int> QMainWindowLayoutState::gapIndex(QWidget *widget,
#if QT_CONFIG(dockwidget)
// is it a dock widget?
- if (qobject_cast<QDockWidget *>(widget) != 0
+ if (qobject_cast<QDockWidget *>(widget) != nullptr
|| qobject_cast<QDockWidgetGroupWindow *>(widget)) {
bool disallowTabs = false;
#if QT_CONFIG(tabbar)
@@ -895,7 +1053,7 @@ bool QMainWindowLayoutState::insertGap(const QList<int> &path, QLayoutItem *item
#if QT_CONFIG(toolbar)
if (i == 0) {
- Q_ASSERT(qobject_cast<QToolBar*>(item->widget()) != 0);
+ Q_ASSERT(qobject_cast<QToolBar*>(item->widget()) != nullptr);
return toolBarAreaLayout.insertGap(path.mid(1), item);
}
#endif
@@ -1057,7 +1215,7 @@ void QMainWindowLayoutState::saveState(QDataStream &stream) const
dockAreaLayout.saveState(stream);
#if QT_CONFIG(tabbar)
const QList<QDockWidgetGroupWindow *> floatingTabs =
- mainWindow->findChildren<QDockWidgetGroupWindow *>(QString(), Qt::FindDirectChildrenOnly);
+ mainWindow->findChildren<QDockWidgetGroupWindow *>(Qt::FindDirectChildrenOnly);
for (QDockWidgetGroupWindow *floating : floatingTabs) {
if (floating->layoutInfo()->isEmpty())
@@ -1172,10 +1330,12 @@ bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
}
QDataStream ds(copy);
+ ds.setVersion(_stream.version());
if (!checkFormat(ds))
return false;
QDataStream stream(copy);
+ stream.setVersion(_stream.version());
while (!stream.atEnd()) {
uchar marker;
@@ -1201,7 +1361,7 @@ bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
if (info == nullptr) {
continue;
}
- info->item_list.append(QDockAreaLayoutItem(new QDockWidgetItem(w)));
+ info->add(w);
}
}
}
@@ -1211,8 +1371,9 @@ bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
{
auto dockWidgets = allMyDockWidgets(mainWindow);
QDockWidgetGroupWindow* floatingTab = qt_mainwindow_layout(mainWindow)->createTabbedDockWindow();
- *floatingTab->layoutInfo() = QDockAreaLayoutInfo(&dockAreaLayout.sep, QInternal::LeftDock,
- Qt::Horizontal, QTabBar::RoundedSouth, mainWindow);
+ *floatingTab->layoutInfo() = QDockAreaLayoutInfo(
+ &dockAreaLayout.sep, QInternal::LeftDock, // FIXME: DockWidget doesn't save original docking area
+ Qt::Horizontal, QTabBar::RoundedSouth, mainWindow);
QRect geometry;
stream >> geometry;
QDockAreaLayoutInfo *info = floatingTab->layoutInfo();
@@ -1270,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)
@@ -1316,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())
@@ -1370,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);
@@ -1465,23 +1627,46 @@ static QInternal::DockPosition toDockPos(Qt::DockWidgetArea area)
return QInternal::DockCount;
}
-static Qt::DockWidgetArea toDockWidgetArea(QInternal::DockPosition pos)
+inline static Qt::DockWidgetArea toDockWidgetArea(int pos)
{
- switch (pos) {
- case QInternal::LeftDock : return Qt::LeftDockWidgetArea;
- case QInternal::RightDock : return Qt::RightDockWidgetArea;
- case QInternal::TopDock : return Qt::TopDockWidgetArea;
- case QInternal::BottomDock : return Qt::BottomDockWidgetArea;
- default:
- break;
- }
-
- return Qt::NoDockWidgetArea;
+ return QDockWidgetPrivate::toDockWidgetArea(static_cast<QInternal::DockPosition>(pos));
}
-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.
+static bool isAreaAllowed(QWidget *widget, const QList<int> &path)
{
- return toDockWidgetArea(static_cast<QInternal::DockPosition>(pos));
+ Q_ASSERT_X((path.size() > 1), "isAreaAllowed", "invalid path size");
+ const Qt::DockWidgetArea area = toDockWidgetArea(path[1]);
+
+ // Read permissions directly from a single dock widget
+ if (QDockWidget *dw = qobject_cast<QDockWidget *>(widget)) {
+ const bool allowed = dw->isAreaAllowed(area);
+ if (!allowed)
+ qCDebug(lcQpaDockWidgets) << "No permission for single DockWidget" << widget << "to dock on" << area;
+ return allowed;
+ }
+
+ // Read permissions from a DockWidgetGroupWindow depending on its DockWidget children
+ if (QDockWidgetGroupWindow *dwgw = qobject_cast<QDockWidgetGroupWindow *>(widget)) {
+ const QList<QDockWidget *> children = dwgw->findChildren<QDockWidget *>(QString(), Qt::FindDirectChildrenOnly);
+
+ if (children.size() == 1) {
+ // Group window has a single child => read its permissions
+ const bool allowed = children.at(0)->isAreaAllowed(area);
+ if (!allowed)
+ qCDebug(lcQpaDockWidgets) << "No permission for DockWidgetGroupWindow" << widget << "to dock on" << area;
+ return allowed;
+ } else {
+ // Group window has more than one or no children => dock it anywhere
+ qCDebug(lcQpaDockWidgets) << "DockWidgetGroupWindow" << widget << "has" << children.size() << "children:";
+ qCDebug(lcQpaDockWidgets) << children;
+ qCDebug(lcQpaDockWidgets) << "DockWidgetGroupWindow" << widget << "can dock at" << area << "and anywhere else.";
+ return true;
+ }
+ }
+ qCDebug(lcQpaDockWidgets) << "Docking requested for invalid widget type (coding error)." << widget << area;
+ return false;
}
void QMainWindowLayout::setCorner(Qt::Corner corner, Qt::DockWidgetArea area)
@@ -1499,6 +1684,25 @@ Qt::DockWidgetArea QMainWindowLayout::corner(Qt::Corner corner) const
return layoutState.dockAreaLayout.corners[corner];
}
+// Returns the rectangle of a dockWidgetArea
+// if max is true, the maximum possible rectangle for dropping is returned
+// the current visible rectangle otherwise
+QRect QMainWindowLayout::dockWidgetAreaRect(const Qt::DockWidgetArea area, DockWidgetAreaSize size) const
+{
+ const QInternal::DockPosition dockPosition = toDockPos(area);
+
+ // Called with invalid dock widget area
+ if (dockPosition == QInternal::DockCount) {
+ qCDebug(lcQpaDockWidgets) << "QMainWindowLayout::dockWidgetAreaRect called with" << area;
+ return QRect();
+ }
+
+ const QDockAreaLayout dl = layoutState.dockAreaLayout;
+
+ // Return maximum or visible rectangle
+ return (size == Maximum) ? dl.gapRect(dockPosition) : dl.docks[dockPosition].rect;
+}
+
void QMainWindowLayout::addDockWidget(Qt::DockWidgetArea area,
QDockWidget *dockwidget,
Qt::Orientation orientation)
@@ -1528,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));
@@ -1547,9 +1752,9 @@ void QMainWindowLayout::setDocumentMode(bool enabled)
_documentMode = enabled;
// Update the document mode for all tab bars
- for (QTabBar *bar : qAsConst(usedTabBars))
+ for (QTabBar *bar : std::as_const(usedTabBars))
bar->setDocumentMode(_documentMode);
- for (QTabBar *bar : qAsConst(unusedTabBars))
+ for (QTabBar *bar : std::as_const(unusedTabBars))
bar->setDocumentMode(_documentMode);
}
@@ -1581,7 +1786,11 @@ void QMainWindowLayout::setTabShape(QTabWidget::TabShape tabShape)
QTabWidget::TabPosition QMainWindowLayout::tabPosition(Qt::DockWidgetArea area) const
{
- return tabPositions[toDockPos(area)];
+ const QInternal::DockPosition dockPos = toDockPos(area);
+ if (dockPos < QInternal::DockCount)
+ return tabPositions[dockPos];
+ qWarning("QMainWindowLayout::tabPosition called with out-of-bounds value '%d'", int(area));
+ return QTabWidget::North;
}
void QMainWindowLayout::setTabPosition(Qt::DockWidgetAreas areas, QTabWidget::TabPosition tabPosition)
@@ -1606,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()
@@ -1644,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
@@ -1657,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));
@@ -1681,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;
@@ -1692,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.
@@ -1710,14 +1956,9 @@ void QMainWindowTabBar::mouseMoveEvent(QMouseEvent *e)
int offset = QApplication::startDragDistance() + 1;
offset *= 3;
QRect r = rect().adjusted(-offset, -offset, offset, offset);
- if (d->dragInProgress && !r.contains(e->pos()) && 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()))) {
+ if (d->dragInProgress && !r.contains(e->position().toPoint()) && d->validIndex(d->pressedIndex)) {
+ 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);
@@ -1730,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;
}
@@ -1740,7 +1981,7 @@ void QMainWindowTabBar::mouseMoveEvent(QMouseEvent *e)
if (draggingDock) {
QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
if (dockPriv->state && dockPriv->state->dragging) {
- QPoint pos = e->globalPos() - dockPriv->state->pressPos;
+ QPoint pos = e->globalPosition().toPoint() - dockPriv->state->pressPos;
draggingDock->move(pos);
// move will call QMainWindowLayout::hover
}
@@ -1748,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);
@@ -1778,8 +2034,39 @@ 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() && !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
+ docking areas haven't been put in the cache yet.
+ */
+ activate();
+ }
+
QTabBar *result = nullptr;
if (!unusedTabBars.isEmpty()) {
result = unusedTabBars.takeLast();
@@ -1807,7 +2094,7 @@ QWidget *QMainWindowLayout::getSeparatorWidget()
result = new QWidget(parentWidget());
result->setAttribute(Qt::WA_MouseNoMask, true);
result->setAutoFillBackground(false);
- result->setObjectName(QLatin1String("qt_qmainwindow_extended_splitter"));
+ result->setObjectName("qt_qmainwindow_extended_splitter"_L1);
}
usedSeparatorWidgets.insert(result);
return result;
@@ -1823,7 +2110,7 @@ QDockAreaLayoutInfo *QMainWindowLayout::dockInfo(QWidget *widget)
if (info)
return info;
const auto groups =
- parent()->findChildren<QDockWidgetGroupWindow*>(QString(), Qt::FindDirectChildrenOnly);
+ parent()->findChildren<QDockWidgetGroupWindow*>(Qt::FindDirectChildrenOnly);
for (QDockWidgetGroupWindow *dwgw : groups) {
info = dwgw->layoutInfo()->info(widget);
if (info)
@@ -1883,8 +2170,10 @@ void QMainWindowLayout::raise(QDockWidget *widget)
int QMainWindowLayout::count() const
{
- qWarning("QMainWindowLayout::count: ?");
- return 0; //#################################################
+ int result = 0;
+ while (itemAt(result))
+ ++result;
+ return result;
}
QLayoutItem *QMainWindowLayout::itemAt(int index) const
@@ -1941,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;
@@ -1960,11 +2277,47 @@ void QMainWindowLayout::setGeometry(const QRect &_r)
r.setBottom(sbr.top() - 1);
}
+ if (restoredState) {
+ /*
+ The main window was hidden and was going to be maximized or full-screened when
+ the state was restored. The state might have been for a larger window size than
+ the current size (in _r), and the window might still be in the process of being
+ shown and transitioning to the final size (there's no reliable way of knowing
+ this across different platforms). Try again with the restored state.
+ */
+ layoutState = *restoredState;
+ if (restoredState->fits()) {
+ restoredState.reset();
+ discardRestoredStateTimer.stop();
+ } else {
+ /*
+ Try again in the next setGeometry call, but discard the restored state
+ after 150ms without any further tries. That's a reasonably short amount of
+ time during which we can expect the windowing system to either have completed
+ showing the window, or resized the window once more (which then restarts the
+ timer in timerEvent).
+ If the windowing system is done, then the user won't have had a chance to
+ change the layout interactively AND trigger another resize.
+ */
+ discardRestoredStateTimer.start(150, this);
+ }
+ }
+
layoutState.rect = r;
+
layoutState.fitLayout();
applyState(layoutState, false);
}
+void QMainWindowLayout::timerEvent(QTimerEvent *e)
+{
+ if (e->timerId() == discardRestoredStateTimer.timerId()) {
+ discardRestoredStateTimer.stop();
+ restoredState.reset();
+ }
+ QLayout::timerEvent(e);
+}
+
void QMainWindowLayout::addItem(QLayoutItem *)
{ qWarning("QMainWindowLayout::addItem: Please use the public QMainWindow API instead"); }
@@ -2090,7 +2443,7 @@ bool QMainWindowLayout::plug(QLayoutItem *widgetItem)
previousPath = currentHoveredFloat->layoutInfo()->indexOf(widget);
// Let's remove the widget from any possible group window
const auto groups =
- parent()->findChildren<QDockWidgetGroupWindow*>(QString(), Qt::FindDirectChildrenOnly);
+ parent()->findChildren<QDockWidgetGroupWindow*>(Qt::FindDirectChildrenOnly);
for (QDockWidgetGroupWindow *dwgw : groups) {
if (dwgw == currentHoveredFloat)
continue;
@@ -2120,7 +2473,7 @@ bool QMainWindowLayout::plug(QLayoutItem *widgetItem)
#if QT_CONFIG(dockwidget)
// Let's remove the widget from any possible group window
const auto groups =
- parent()->findChildren<QDockWidgetGroupWindow*>(QString(), Qt::FindDirectChildrenOnly);
+ parent()->findChildren<QDockWidgetGroupWindow*>(Qt::FindDirectChildrenOnly);
for (QDockWidgetGroupWindow *dwgw : groups) {
QList<int> path = dwgw->layoutInfo()->indexOf(widget);
if (!path.isEmpty())
@@ -2141,7 +2494,7 @@ bool QMainWindowLayout::plug(QLayoutItem *widgetItem)
QRect globalRect = currentGapRect;
globalRect.moveTopLeft(parentWidget()->mapToGlobal(globalRect.topLeft()));
#if QT_CONFIG(dockwidget)
- if (qobject_cast<QDockWidget*>(widget) != 0) {
+ if (qobject_cast<QDockWidget*>(widget) != nullptr) {
QDockWidgetLayout *layout = qobject_cast<QDockWidgetLayout*>(widget->layout());
if (layout->nativeWindowDeco()) {
globalRect.adjust(0, layout->titleHeight(), 0, 0);
@@ -2248,7 +2601,7 @@ void QMainWindowLayout::animationFinished(QWidget *widget)
#if QT_CONFIG(dockwidget)
#if QT_CONFIG(tabbar)
- if (qobject_cast<QDockWidget*>(widget) != 0) {
+ if (qobject_cast<QDockWidget*>(widget) != nullptr) {
// info() might return null if the widget is destroyed while
// animating but before the animationFinished signal is received.
if (QDockAreaLayoutInfo *info = dockInfo(widget))
@@ -2320,7 +2673,7 @@ QMainWindowLayout::QMainWindowLayout(QMainWindow *mainwindow, QLayout *parentLay
#endif // QT_CONFIG(dockwidget)
pluggingWidget = nullptr;
- setObjectName(mainwindow->objectName() + QLatin1String("_layout"));
+ setObjectName(mainwindow->objectName() + "_layout"_L1);
}
QMainWindowLayout::~QMainWindowLayout()
@@ -2395,7 +2748,6 @@ static bool unplugGroup(QMainWindowLayout *layout, QLayoutItem **item,
return false;
// The QDockWidget is part of a group of tab and we need to unplug them all.
-
QDockWidgetGroupWindow *floatingTabs = layout->createTabbedDockWindow();
QDockAreaLayoutInfo *info = floatingTabs->layoutInfo();
*info = std::move(*parentItem.subinfo);
@@ -2410,6 +2762,30 @@ static bool unplugGroup(QMainWindowLayout *layout, QLayoutItem **item,
}
#endif
+#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
+static QTabBar::Shape tabwidgetPositionToTabBarShape(QWidget *w)
+{
+ QTabBar::Shape result = QTabBar::RoundedSouth;
+ if (qobject_cast<QDockWidget *>(w)) {
+ switch (static_cast<QDockWidgetPrivate *>(qt_widget_private(w))->tabPosition) {
+ case QTabWidget::North:
+ result = QTabBar::RoundedNorth;
+ break;
+ case QTabWidget::South:
+ result = QTabBar::RoundedSouth;
+ break;
+ case QTabWidget::West:
+ result = QTabBar::RoundedWest;
+ break;
+ case QTabWidget::East:
+ result = QTabBar::RoundedEast;
+ break;
+ }
+ }
+ return result;
+}
+#endif // QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
+
/*! \internal
Unplug \a widget (QDockWidget or QToolBar) from it's parent container.
@@ -2420,33 +2796,35 @@ static bool unplugGroup(QMainWindowLayout *layout, QLayoutItem **item,
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:" << (scope == QDockWidgetPrivate::DragScope::Group);
return nullptr;
}
QList<int> path = groupWindow->layoutInfo()->indexOf(widget);
- QLayoutItem *item = groupWindow->layoutInfo()->item(path).widgetItem;
- if (group && path.size() > 1
- && unplugGroup(this, &item,
- groupWindow->layoutInfo()->item(path.mid(0, path.size() - 1)))) {
+ QDockAreaLayoutItem parentItem = groupWindow->layoutInfo()->item(path);
+ QLayoutItem *item = parentItem.widgetItem;
+ if (scope == QDockWidgetPrivate::DragScope::Group && path.size() > 1
+ && unplugGroup(this, &item, parentItem)) {
+ qCDebug(lcQpaDockWidgets) << "Unplugging:" << widget << "from" << item;
return item;
} else {
- // We are unplugging a dock widget from a floating window.
- QDockWidget *dw = qobject_cast<QDockWidget *>(widget);
- Q_ASSERT(dw); // cannot be a QDockWidgetGroupWindow because it's not floating.
- dw->d_func()->unplug(widget->geometry());
- groupWindow->layoutInfo()->fitItems();
- groupWindow->layoutInfo()->apply(dockOptions & QMainWindow::AnimatedDocks);
+ // 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.
+ dockWidget->d_func()->unplug(widget->geometry());
+
+ qCDebug(lcQpaDockWidgets) << "Unplugged from floating dock:" << widget << "from" << parentItem.widgetItem;
return item;
}
}
@@ -2466,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();
@@ -2474,6 +2852,36 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
} else
#endif // QT_CONFIG(tabwidget)
{
+ // 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.setHeight(r.height() - sep);
+ break;
+ case Qt::TopDockWidgetArea:
+ case Qt::BottomDockWidgetArea:
+ 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);
}
}
@@ -2485,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);
@@ -2515,58 +2923,45 @@ void QMainWindowLayout::updateGapIndicator()
if (!gapIndicator) {
gapIndicator = new QRubberBand(QRubberBand::Rectangle, expectedParent);
// For accessibility to identify this special widget.
- gapIndicator->setObjectName(QLatin1String("qt_rubberband"));
+ gapIndicator->setObjectName("qt_rubberband"_L1);
} else if (gapIndicator->parent() != expectedParent) {
gapIndicator->setParent(expectedParent);
}
+ // Prevent re-entry in case of size change
+ const bool sigBlockState = gapIndicator->signalsBlocked();
+ auto resetSignals = qScopeGuard([this, sigBlockState](){ gapIndicator->blockSignals(sigBlockState); });
+ gapIndicator->blockSignals(true);
+
#if QT_CONFIG(dockwidget)
if (currentHoveredFloat)
gapIndicator->setGeometry(currentHoveredFloat->currentGapRect);
else
#endif
gapIndicator->setGeometry(currentGapRect);
+
gapIndicator->show();
gapIndicator->raise();
+
+ // Reset signal state
+
} else if (gapIndicator) {
gapIndicator->hide();
}
+
#endif // QT_CONFIG(rubberband)
}
-#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
-static QTabBar::Shape tabwidgetPositionToTabBarShape(QWidget *w)
-{
- QTabBar::Shape result = QTabBar::RoundedSouth;
- if (qobject_cast<QDockWidget *>(w)) {
- switch (static_cast<QDockWidgetPrivate *>(qt_widget_private(w))->tabPosition) {
- case QTabWidget::North:
- result = QTabBar::RoundedNorth;
- break;
- case QTabWidget::South:
- result = QTabBar::RoundedSouth;
- break;
- case QTabWidget::West:
- result = QTabBar::RoundedWest;
- break;
- case QTabWidget::East:
- result = QTabBar::RoundedEast;
- break;
- }
- }
- return result;
-}
-#endif // QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
+void QMainWindowLayout::hover(QLayoutItem *hoverTarget,
+ const QPoint &mousePos) {
+ if (!parentWidget()->isVisible() || parentWidget()->isMinimized() ||
+ pluggingWidget != nullptr || hoverTarget == nullptr)
+ return;
-void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
-{
- if (!parentWidget()->isVisible() || parentWidget()->isMinimized()
- || pluggingWidget != nullptr || widgetItem == nullptr)
- return;
-
- QWidget *widget = widgetItem->widget();
+ QWidget *widget = hoverTarget->widget();
#if QT_CONFIG(dockwidget)
+ widget->raise();
if ((dockOptions & QMainWindow::GroupedDragging) && (qobject_cast<QDockWidget*>(widget)
|| qobject_cast<QDockWidgetGroupWindow *>(widget))) {
@@ -2577,12 +2972,20 @@ void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
QWidget *w = qobject_cast<QWidget*>(c);
if (!w)
continue;
+
+ // Handle only dock widgets and group windows
if (!qobject_cast<QDockWidget*>(w) && !qobject_cast<QDockWidgetGroupWindow *>(w))
continue;
- if (w != widget && w->isTopLevel() && w->isVisible() && !w->isMinimized())
+
+ // Check permission to dock on another dock widget or floating dock
+ // FIXME in Qt 7
+
+ if (w != widget && w->isWindow() && w->isVisible() && !w->isMinimized())
candidates << w;
+
if (QDockWidgetGroupWindow *group = qobject_cast<QDockWidgetGroupWindow *>(w)) {
- // Sometimes, there are floating QDockWidget that have a QDockWidgetGroupWindow as a parent.
+ // floating QDockWidgets have a QDockWidgetGroupWindow as a parent,
+ // if they have been hovered over
const auto groupChildren = group->children();
for (QObject *c : groupChildren) {
if (QDockWidget *dw = qobject_cast<QDockWidget*>(c)) {
@@ -2592,6 +2995,7 @@ void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
}
}
}
+
for (QWidget *w : candidates) {
const QScreen *screen1 = qt_widget_private(widget)->associatedScreen();
const QScreen *screen2 = qt_widget_private(w)->associatedScreen();
@@ -2602,36 +3006,63 @@ void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
#if QT_CONFIG(tabwidget)
if (auto dropTo = qobject_cast<QDockWidget *>(w)) {
- // dropping to a normal widget, we mutate it in a QDockWidgetGroupWindow with two
- // tabs
- QDockWidgetGroupWindow *floatingTabs = createTabbedDockWindow(); // FIXME
- floatingTabs->setGeometry(dropTo->geometry());
- QDockAreaLayoutInfo *info = floatingTabs->layoutInfo();
- const QTabBar::Shape shape = tabwidgetPositionToTabBarShape(dropTo);
- *info = QDockAreaLayoutInfo(&layoutState.dockAreaLayout.sep, QInternal::LeftDock,
- Qt::Horizontal, shape,
- static_cast<QMainWindow *>(parentWidget()));
- info->tabbed = true;
- QLayout *parentLayout = dropTo->parentWidget()->layout();
- info->item_list.append(
- QDockAreaLayoutItem(parentLayout->takeAt(parentLayout->indexOf(dropTo))));
-
- dropTo->setParent(floatingTabs);
+
+ // w is the drop target's widget
+ w = dropTo->widget();
+
+ // Create a floating tab, unless already existing
+ if (!qobject_cast<QDockWidgetGroupWindow *>(w)) {
+ QDockWidgetGroupWindow *floatingTabs = createTabbedDockWindow();
+ floatingTabs->setGeometry(dropTo->geometry());
+ QDockAreaLayoutInfo *info = floatingTabs->layoutInfo();
+ const QTabBar::Shape shape = tabwidgetPositionToTabBarShape(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;
+ 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;
+ }
+
+ // Show the drop target and raise widget to foreground
dropTo->show();
- dropTo->d_func()->plug(QRect());
- w = floatingTabs;
- widget->raise(); // raise, as our newly created drop target is now on top
+ qCDebug(lcQpaDockWidgets) << "Showing" << dropTo;
+ widget->raise();
+ qCDebug(lcQpaDockWidgets) << "Raising" << widget;
}
#endif
- Q_ASSERT(qobject_cast<QDockWidgetGroupWindow *>(w));
- auto group = static_cast<QDockWidgetGroupWindow *>(w);
- if (group->hover(widgetItem, 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)
@@ -2647,11 +3078,7 @@ void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
bool allowed = false;
#if QT_CONFIG(dockwidget)
- if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget))
- allowed = dw->isAreaAllowed(toDockWidgetArea(path.at(1)));
-
- if (qobject_cast<QDockWidgetGroupWindow *>(widget))
- allowed = true;
+ allowed = isAreaAllowed(widget, path);
#endif
#if QT_CONFIG(toolbar)
if (QToolBar *tb = qobject_cast<QToolBar*>(widget))
@@ -2667,16 +3094,16 @@ void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
currentGapPos = path;
if (path.isEmpty()) {
- fixToolBarOrientation(widgetItem, 2); // 2 = top dock, ie. horizontal
+ fixToolBarOrientation(hoverTarget, 2); // 2 = top dock, ie. horizontal
restore(true);
return;
}
- fixToolBarOrientation(widgetItem, currentGapPos.at(1));
+ fixToolBarOrientation(hoverTarget, currentGapPos.at(1));
QMainWindowLayoutState newState = savedState;
- if (!newState.insertGap(path, widgetItem)) {
+ if (!newState.insertGap(path, hoverTarget)) {
restore(true); // not enough space
return;
}
@@ -2713,10 +3140,16 @@ QDockWidgetGroupWindow *QMainWindowLayout::createTabbedDockWindow()
void QMainWindowLayout::applyState(QMainWindowLayoutState &newState, bool animate)
{
+ // applying the state can lead to showing separator widgets, which would lead to a re-layout
+ // (even though the separator widgets are not really part of the layout)
+ // break the loop
+ if (isInApplyState)
+ return;
+ isInApplyState = true;
#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
QSet<QTabBar*> used = newState.dockAreaLayout.usedTabBars();
const auto groups =
- parent()->findChildren<QDockWidgetGroupWindow*>(QString(), Qt::FindDirectChildrenOnly);
+ parent()->findChildren<QDockWidgetGroupWindow*>(Qt::FindDirectChildrenOnly);
for (QDockWidgetGroupWindow *dwgw : groups)
used += dwgw->layoutInfo()->usedTabBars();
@@ -2735,6 +3168,7 @@ void QMainWindowLayout::applyState(QMainWindowLayoutState &newState, bool animat
usedSeparatorWidgets = usedSeps;
for (QWidget *sepWidget : retiredSeps) {
unusedSeparatorWidgets.append(sepWidget);
+ sepWidget->hide();
}
}
@@ -2743,6 +3177,7 @@ void QMainWindowLayout::applyState(QMainWindowLayoutState &newState, bool animat
#endif // QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
newState.apply(dockOptions & QMainWindow::AnimatedDocks && animate);
+ isInApplyState = false;
}
void QMainWindowLayout::saveState(QDataStream &stream) const
@@ -2752,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;
@@ -2767,6 +3203,18 @@ bool QMainWindowLayout::restoreState(QDataStream &stream)
if (parentWidget()->isVisible()) {
layoutState.fitLayout();
applyState(layoutState, false);
+ } else {
+ /*
+ The state might not fit into the size of the widget as it gets shown, but
+ if the window is expected to be maximized or full screened, then we might
+ get several resizes as part of that transition, at the end of which the
+ state might fit. So keep the restored state around for now and try again
+ later in setGeometry.
+ */
+ if ((parentWidget()->windowState() & (Qt::WindowFullScreen | Qt::WindowMaximized))
+ && !layoutState.fits()) {
+ restoredState.reset(new QMainWindowLayoutState(layoutState));
+ }
}
savedState.deleteAllLayoutItems();
@@ -2775,7 +3223,7 @@ bool QMainWindowLayout::restoreState(QDataStream &stream)
#if QT_CONFIG(dockwidget)
if (parentWidget()->isVisible()) {
#if QT_CONFIG(tabbar)
- for (QTabBar *tab_bar : qAsConst(usedTabBars))
+ for (QTabBar *tab_bar : std::as_const(usedTabBars))
tab_bar->show();
#endif
@@ -2785,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 d4f0bd4517..55a27e4849 100644
--- a/src/widgets/widgets/qmainwindowlayout_p.h
+++ b/src/widgets/widgets/qmainwindowlayout_p.h
@@ -1,44 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QDYNAMICMAINWINDOWLAYOUT_P_H
-#define QDYNAMICMAINWINDOWLAYOUT_P_H
+// 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 QMAINWINDOWLAYOUT_P_H
+#define QMAINWINDOWLAYOUT_P_H
//
// W A R N I N G
@@ -60,23 +24,36 @@
#include "QtGui/qpainter.h"
#include "QtGui/qevent.h"
#endif
-#include "QtCore/qvector.h"
-#include "QtCore/qset.h"
#include "QtCore/qbasictimer.h"
+#include "QtCore/qlist.h"
+#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);
QT_BEGIN_NAMESPACE
+Q_DECLARE_LOGGING_CATEGORY(lcQpaDockWidgets);
+
class QToolBar;
class QRubberBand;
@@ -210,7 +187,7 @@ bool QMainWindowLayoutSeparatorHelper<Layout>::windowEvent(QEvent *event)
#if QT_CONFIG(cursor)
case QEvent::HoverMove: {
- adjustCursor(static_cast<QHoverEvent *>(event)->pos());
+ adjustCursor(static_cast<QHoverEvent *>(event)->position().toPoint());
break;
}
@@ -228,7 +205,7 @@ bool QMainWindowLayoutSeparatorHelper<Layout>::windowEvent(QEvent *event)
case QEvent::MouseButtonPress: {
QMouseEvent *e = static_cast<QMouseEvent *>(event);
- if (e->button() == Qt::LeftButton && startSeparatorMove(e->pos())) {
+ if (e->button() == Qt::LeftButton && startSeparatorMove(e->position().toPoint())) {
// The click was on a separator, eat this event
e->accept();
return true;
@@ -240,10 +217,10 @@ bool QMainWindowLayoutSeparatorHelper<Layout>::windowEvent(QEvent *event)
QMouseEvent *e = static_cast<QMouseEvent *>(event);
#if QT_CONFIG(cursor)
- adjustCursor(e->pos());
+ adjustCursor(e->position().toPoint());
#endif
if (e->buttons() & Qt::LeftButton) {
- if (separatorMove(e->pos())) {
+ if (separatorMove(e->position().toPoint())) {
// We're moving a separator, eat this event
e->accept();
return true;
@@ -255,7 +232,7 @@ bool QMainWindowLayoutSeparatorHelper<Layout>::windowEvent(QEvent *event)
case QEvent::MouseButtonRelease: {
QMouseEvent *e = static_cast<QMouseEvent *>(event);
- if (endSeparatorMove(e->pos())) {
+ if (endSeparatorMove(e->position().toPoint())) {
// We've released a separator, eat this event
e->accept();
return true;
@@ -334,18 +311,21 @@ bool QMainWindowLayoutSeparatorHelper<Layout>::endSeparatorMove(const QPoint &)
return true;
}
-class QDockWidgetGroupWindow : public QWidget
+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;
@@ -353,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;
@@ -362,6 +346,7 @@ signals:
protected:
bool event(QEvent *) override;
+ bool eventFilter(QObject *obj, QEvent *event) override;
void paintEvent(QPaintEvent*) override;
private:
@@ -369,14 +354,35 @@ private:
};
// This item will be used in the layout for the gap item. We cannot use QWidgetItem directly
-// because QWidgetItem functions return an empty size for widgets that are are floating.
+// because QWidgetItem functions return an empty size for widgets that are floating.
class QDockWidgetGroupWindowItem : public QWidgetItem
{
public:
explicit QDockWidgetGroupWindowItem(QDockWidgetGroupWindow *parent) : QWidgetItem(parent) {}
- QSize minimumSize() const override { return lay()->minimumSize(); }
- QSize maximumSize() const override { return lay()->maximumSize(); }
- QSize sizeHint() const override { return lay()->sizeHint(); }
+
+ // when the item contains a dock widget, obtain its size (to prevent infinite loop)
+ // ask the layout otherwise
+ QSize minimumSize() const override
+ {
+ if (auto dw = widget()->findChild<QDockWidget *>())
+ return dw->minimumSize();
+ return lay()->minimumSize();
+ }
+ QSize maximumSize() const override
+ {
+ auto dw = widget()->findChild<QDockWidget *>();
+ if (dw)
+ return dw->maximumSize();
+ return lay()->maximumSize();
+ }
+ QSize sizeHint() const override
+ {
+ auto dw = widget()->findChild<QDockWidget *>();
+ if (dw)
+ return dw->sizeHint();
+ return lay()->sizeHint();
+ }
+ QWidget* widget() const override { return wid; }
private:
QLayout *lay() const { return const_cast<QDockWidgetGroupWindowItem *>(this)->widget()->layout(); }
@@ -384,12 +390,12 @@ private:
#endif // QT_CONFIG(dockwidget)
/* This data structure represents the state of all the tool-bars and dock-widgets. It's value based
- so it can be easilly copied into a temporary variable. All operations are performed without moving
+ so it can be easily copied into a temporary variable. All operations are performed without moving
any widgets. Only when we are sure we have the desired state, we call apply(), which moves the
widgets.
*/
-class QMainWindowLayoutState
+class Q_AUTOTEST_EXPORT QMainWindowLayoutState
{
public:
QRect rect;
@@ -414,6 +420,7 @@ public:
QSize sizeHint() const;
QSize minimumSize() const;
+ bool fits() const;
void fitLayout();
QLayoutItem *itemAt(int index, int *x) const;
@@ -443,6 +450,7 @@ public:
bool restoreState(QDataStream &stream, const QMainWindowLayoutState &oldState);
};
+class QMainWindowTabBar;
class Q_AUTOTEST_EXPORT QMainWindowLayout
: public QLayout,
public QMainWindowLayoutSeparatorHelper<QMainWindowLayout>
@@ -451,6 +459,7 @@ class Q_AUTOTEST_EXPORT QMainWindowLayout
public:
QMainWindowLayoutState layoutState, savedState;
+ std::unique_ptr<QMainWindowLayoutState> restoredState;
QMainWindowLayout(QMainWindow *mainwindow, QLayout *parentLayout);
~QMainWindowLayout();
@@ -458,22 +467,19 @@ public:
QMainWindow::DockOptions dockOptions;
void setDockOptions(QMainWindow::DockOptions opts);
- // status bar
-
QLayoutItem *statusbar;
+ // status bar
#if QT_CONFIG(statusbar)
QStatusBar *statusBar() const;
void setStatusBar(QStatusBar *sb);
#endif
// central widget
-
QWidget *centralWidget() const;
void setCentralWidget(QWidget *cw);
// toolbars
-
#if QT_CONFIG(toolbar)
void addToolBarBreak(Qt::ToolBarArea area);
void insertToolBarBreak(QToolBar *before);
@@ -490,10 +496,11 @@ public:
#endif
// dock widgets
-
#if QT_CONFIG(dockwidget)
void setCorner(Qt::Corner corner, Qt::DockWidgetArea area);
Qt::DockWidgetArea corner(Qt::Corner corner) const;
+ enum DockWidgetAreaSize {Visible, Maximum};
+ QRect dockWidgetAreaRect(Qt::DockWidgetArea area, DockWidgetAreaSize size = Maximum) const;
void addDockWidget(Qt::DockWidgetArea area,
QDockWidget *dockwidget,
Qt::Orientation orientation);
@@ -523,7 +530,7 @@ public:
int sep; // separator extent
#if QT_CONFIG(tabwidget)
- QTabWidget::TabPosition tabPositions[4];
+ QTabWidget::TabPosition tabPositions[QInternal::DockCount];
QTabWidget::TabShape _tabShape;
QTabWidget::TabShape tabShape() const;
@@ -540,15 +547,14 @@ public:
#endif // QT_CONFIG(dockwidget)
// save/restore
-
enum VersionMarkers { // sentinel values used to validate state data
VersionMarker = 0xff
};
void saveState(QDataStream &stream) const;
bool restoreState(QDataStream &stream);
+ QBasicTimer discardRestoredStateTimer;
// QLayout interface
-
void addItem(QLayoutItem *item) override;
void setGeometry(const QRect &r) override;
QLayoutItem *itemAt(int index) const override;
@@ -562,7 +568,6 @@ public:
void invalidate() override;
// animations
-
QWidgetAnimator widgetAnimator;
QList<int> currentGapPos;
QRect currentGapRect;
@@ -573,17 +578,32 @@ 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 *widgetItem, const QPoint &mousePos);
+ 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 paintDropIndicator(QPainter *p, QWidget *widget, const QRegion &clip);
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;
+
private Q_SLOTS:
void updateGapIndicator();
#if QT_CONFIG(dockwidget)
@@ -596,6 +616,7 @@ private:
#if QT_CONFIG(tabbar)
void updateTabBarShapes();
#endif
+ bool isInRestoreState = false;
};
#if QT_CONFIG(dockwidget) && !defined(QT_NO_DEBUG_STREAM)
@@ -606,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 3272ac440b..79b83453ac 100644
--- a/src/widgets/widgets/qmdiarea.cpp
+++ b/src/widgets/widgets/qmdiarea.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QMdiArea
@@ -51,7 +15,7 @@
applications, but can also be placed in any layout. The following
code adds an area to a main window:
- \snippet mdiareasnippets.cpp 0
+ \snippet mdiarea/mdiareasnippets.cpp 0
Unlike the window managers for top-level windows, all window flags
(Qt::WindowFlags) are supported by QMdiArea as long as the flags
@@ -63,7 +27,7 @@
Subwindows in QMdiArea are instances of QMdiSubWindow. They
are added to an MDI area with addSubWindow(). It is common to pass
a QWidget, which is set as the internal widget, to this function,
- but it is also possible to pass a QMdiSubWindow directly.The class
+ but it is also possible to pass a QMdiSubWindow directly. The class
inherits QWidget, and you can use the same API as with a normal
top-level window when programming. QMdiSubWindow also has behavior
that is specific to MDI windows. See the QMdiSubWindow class
@@ -103,8 +67,8 @@
\fn void QMdiArea::subWindowActivated(QMdiSubWindow *window)
QMdiArea emits this signal after \a window has been activated. When \a
- window is 0, QMdiArea has just deactivated its last active window, and
- there are no active windows on the workspace.
+ window is \nullptr, QMdiArea has just deactivated its last active window,
+ and there are no active windows on the workspace.
\sa QMdiArea::activeSubWindow()
*/
@@ -165,8 +129,6 @@
#include <QPainter>
#include <QFontMetrics>
#include <QStyleOption>
-#include <QDesktopWidget>
-#include <private/qdesktopwidget_p.h>
#include <QDebug>
#include <qmath.h>
#if QT_CONFIG(menu)
@@ -178,6 +140,7 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
using namespace QMdi;
// Asserts in debug mode, gives warning otherwise.
@@ -257,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)
@@ -279,7 +230,7 @@ static inline QString tabTextFor(QMdiSubWindow *subWindow)
QString title = subWindow->windowTitle();
if (subWindow->isWindowModified()) {
- title.replace(QLatin1String("[*]"), QLatin1String("*"));
+ title.replace("[*]"_L1, "*"_L1);
} else {
extern QString qt_setWindowTitle_helperHelper(const QString&, const QWidget*);
title = qt_setWindowTitle_helperHelper(title, subWindow);
@@ -410,7 +361,7 @@ void IconTiler::rearrange(QList<QWidget *> &widgets, const QRect &domain) const
\internal
Calculates the accumulated overlap (intersection area) between 'source' and 'rects'.
*/
-int MinOverlapPlacer::accumulatedOverlap(const QRect &source, const QVector<QRect> &rects)
+int MinOverlapPlacer::accumulatedOverlap(const QRect &source, const QList<QRect> &rects)
{
int accOverlap = 0;
for (const QRect &rect : rects) {
@@ -426,7 +377,7 @@ int MinOverlapPlacer::accumulatedOverlap(const QRect &source, const QVector<QRec
Finds among 'source' the rectangle with the minimum accumulated overlap with the
rectangles in 'rects'.
*/
-QRect MinOverlapPlacer::findMinOverlapRect(const QVector<QRect> &source, const QVector<QRect> &rects)
+QRect MinOverlapPlacer::findMinOverlapRect(const QList<QRect> &source, const QList<QRect> &rects)
{
int minAccOverlap = -1;
QRect minAccOverlapRect;
@@ -444,16 +395,16 @@ QRect MinOverlapPlacer::findMinOverlapRect(const QVector<QRect> &source, const Q
\internal
Gets candidates for the final placement.
*/
-QVector<QRect> MinOverlapPlacer::getCandidatePlacements(const QSize &size, const QVector<QRect> &rects,
- const QRect &domain)
+QList<QRect> MinOverlapPlacer::getCandidatePlacements(const QSize &size, const QList<QRect> &rects,
+ const QRect &domain)
{
- QVector<QRect> result;
+ QList<QRect> result;
- QVector<int> xlist;
+ QList<int> xlist;
xlist.reserve(2 + rects.size());
xlist << domain.left() << domain.right() - size.width() + 1;
- QVector<int> ylist;
+ QList<int> ylist;
ylist.reserve(2 + rects.size());
ylist << domain.top();
if (domain.bottom() - size.height() + 1 >= 0)
@@ -471,8 +422,8 @@ QVector<QRect> MinOverlapPlacer::getCandidatePlacements(const QSize &size, const
ylist.erase(std::unique(ylist.begin(), ylist.end()), ylist.end());
result.reserve(ylist.size() * xlist.size());
- for (int y : qAsConst(ylist))
- for (int x : qAsConst(xlist))
+ for (int y : std::as_const(ylist))
+ for (int x : std::as_const(xlist))
result << QRect(QPoint(x, y), size);
return result;
}
@@ -482,14 +433,14 @@ QVector<QRect> MinOverlapPlacer::getCandidatePlacements(const QSize &size, const
Finds all rectangles in 'source' not completely inside 'domain'. The result is stored
in 'result' and also removed from 'source'.
*/
-QVector<QRect> MinOverlapPlacer::findNonInsiders(const QRect &domain, QVector<QRect> &source)
+QList<QRect> MinOverlapPlacer::findNonInsiders(const QRect &domain, QList<QRect> &source)
{
const auto containedInDomain =
[domain](const QRect &srcRect) { return domain.contains(srcRect); };
const auto firstOut = std::stable_partition(source.begin(), source.end(), containedInDomain);
- QVector<QRect> result;
+ QList<QRect> result;
result.reserve(source.end() - firstOut);
std::copy(firstOut, source.end(), std::back_inserter(result));
@@ -503,9 +454,9 @@ QVector<QRect> MinOverlapPlacer::findNonInsiders(const QRect &domain, QVector<QR
Finds all rectangles in 'source' that overlaps 'domain' by the maximum overlap area
between 'domain' and any rectangle in 'source'. The result is stored in 'result'.
*/
-QVector<QRect> MinOverlapPlacer::findMaxOverlappers(const QRect &domain, const QVector<QRect> &source)
+QList<QRect> MinOverlapPlacer::findMaxOverlappers(const QRect &domain, const QList<QRect> &source)
{
- QVector<QRect> result;
+ QList<QRect> result;
result.reserve(source.size());
int maxOverlap = -1;
@@ -530,15 +481,15 @@ QVector<QRect> MinOverlapPlacer::findMaxOverlappers(const QRect &domain, const Q
placement that overlaps the rectangles in 'rects' as little as possible while at the
same time being as much as possible inside 'domain'.
*/
-QPoint MinOverlapPlacer::findBestPlacement(const QRect &domain, const QVector<QRect> &rects,
- QVector<QRect> &source)
+QPoint MinOverlapPlacer::findBestPlacement(const QRect &domain, const QList<QRect> &rects,
+ QList<QRect> &source)
{
- const QVector<QRect> nonInsiders = findNonInsiders(domain, source);
+ const QList<QRect> nonInsiders = findNonInsiders(domain, source);
if (!source.empty())
return findMinOverlapRect(source, rects).topLeft();
- QVector<QRect> maxOverlappers = findMaxOverlappers(domain, nonInsiders);
+ QList<QRect> maxOverlappers = findMaxOverlappers(domain, nonInsiders);
return findMinOverlapRect(maxOverlappers, rects).topLeft();
}
@@ -549,7 +500,7 @@ QPoint MinOverlapPlacer::findBestPlacement(const QRect &domain, const QVector<QR
overlaps 'rects' as little as possible and 'domain' as much as possible.
Returns the position of the resulting rectangle.
*/
-QPoint MinOverlapPlacer::place(const QSize &size, const QVector<QRect> &rects,
+QPoint MinOverlapPlacer::place(const QSize &size, const QList<QRect> &rects,
const QRect &domain) const
{
if (size.isEmpty() || !domain.isValid())
@@ -559,7 +510,7 @@ QPoint MinOverlapPlacer::place(const QSize &size, const QVector<QRect> &rects,
return QPoint();
}
- QVector<QRect> candidates = getCandidatePlacements(size, rects, domain);
+ QList<QRect> candidates = getCandidatePlacements(size, rects, domain);
return findBestPlacement(domain, rects, candidates);
}
@@ -584,12 +535,12 @@ private:
*/
void QMdiAreaTabBar::mousePressEvent(QMouseEvent *event)
{
- if (event->button() != Qt::MidButton) {
+ if (event->button() != Qt::MiddleButton) {
QTabBar::mousePressEvent(event);
return;
}
- QMdiSubWindow *subWindow = subWindowFromIndex(tabAt(event->pos()));
+ QMdiSubWindow *subWindow = subWindowFromIndex(tabAt(event->position().toPoint()));
if (!subWindow) {
event->ignore();
return;
@@ -720,12 +671,16 @@ 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().
ignoreWindowStateChange = true;
- if(!(options & QMdiArea::DontMaximizeSubWindowOnActivation) && !showActiveWindowMaximized)
+ if (!(options & QMdiArea::DontMaximizeSubWindowOnActivation) && !showActiveWindowMaximized)
showActiveWindowMaximized = child->isMaximized() && child->isVisible();
if (showActiveWindowMaximized && child->isMaximized()) {
if (q->updatesEnabled()) {
@@ -787,7 +742,7 @@ void QMdiAreaPrivate::_q_currentTabChanged(int index)
// If the previous active sub-window was hidden, disable the tab.
if (indexToLastActiveTab >= 0 && indexToLastActiveTab < tabBar->count()
- && indexToLastActiveTab < childWindows.count()) {
+ && indexToLastActiveTab < childWindows.size()) {
QMdiSubWindow *lastActive = childWindows.at(indexToLastActiveTab);
if (lastActive && lastActive->isHidden())
tabBar->setTabEnabled(indexToLastActiveTab, false);
@@ -861,7 +816,7 @@ void QMdiAreaPrivate::appendChild(QMdiSubWindow *child)
if (tabBar) {
tabBar->addTab(child->windowIcon(), tabTextFor(child));
updateTabBarGeometry();
- if (childWindows.count() == 1 && !(options & QMdiArea::DontMaximizeSubWindowOnActivation))
+ if (childWindows.size() == 1 && !(options & QMdiArea::DontMaximizeSubWindowOnActivation))
showActiveWindowMaximized = true;
}
#endif
@@ -892,10 +847,10 @@ void QMdiAreaPrivate::place(Placer *placer, QMdiSubWindow *child)
return;
}
- QVector<QRect> rects;
+ 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;
@@ -937,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) {
@@ -956,7 +911,7 @@ void QMdiAreaPrivate::rearrange(Rearranger *rearranger)
QRect domain = viewport->rect();
if (rearranger->type() == Rearranger::RegularTiler && !widgets.isEmpty())
- domain = resizeToMinimumTileSize(minSubWindowSize, widgets.count());
+ domain = resizeToMinimumTileSize(minSubWindowSize, widgets.size());
rearranger->rearrange(widgets, domain);
@@ -1002,6 +957,10 @@ void QMdiAreaPrivate::activateWindow(QMdiSubWindow *child)
if (child->isHidden() || child == active)
return;
+
+ if (child->d_func()->isActive && active == nullptr)
+ child->d_func()->isActive = false;
+
child->d_func()->setActive(true);
}
@@ -1329,7 +1288,7 @@ bool QMdiAreaPrivate::scrollBarsEnabled() const
*/
bool QMdiAreaPrivate::lastWindowAboutToBeDestroyed() const
{
- if (childWindows.count() != 1)
+ if (childWindows.size() != 1)
return false;
QMdiSubWindow *last = childWindows.at(0);
@@ -1347,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)
@@ -1369,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);
@@ -1385,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)
@@ -1405,7 +1368,7 @@ QMdiAreaPrivate::subWindowList(QMdiArea::WindowOrder order, bool reversed) const
}
} else { // ActivationHistoryOrder
Q_ASSERT(indicesToActivatedChildren.size() == childWindows.size());
- for (int i = indicesToActivatedChildren.count() - 1; i >= 0; --i) {
+ for (int i = indicesToActivatedChildren.size() - 1; i >= 0; --i) {
QMdiSubWindow *child = childWindows.at(indicesToActivatedChildren.at(i));
if (!child)
continue;
@@ -1513,7 +1476,7 @@ void QMdiAreaPrivate::highlightNextSubWindow(int increaseFactor)
if (!rubberBand) {
rubberBand = new QRubberBand(QRubberBand::Rectangle, q);
// For accessibility to identify this special widget.
- rubberBand->setObjectName(QLatin1String("qt_rubberband"));
+ rubberBand->setObjectName("qt_rubberband"_L1);
rubberBand->setWindowFlags(rubberBand->windowFlags() | Qt::WindowStaysOnTopHint);
}
#endif
@@ -1566,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();
@@ -1630,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();
@@ -1687,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();
}
@@ -1733,7 +1701,7 @@ QMdiArea::~QMdiArea()
*/
QSize QMdiArea::sizeHint() const
{
- // Calculate a proper scale factor for QDesktopWidget::size().
+ // Calculate a proper scale factor for the desktop's size.
// This also takes into account that we can have nested workspaces.
int nestedCount = 0;
QWidget *widget = this->parentWidget();
@@ -1744,14 +1712,14 @@ QSize QMdiArea::sizeHint() const
}
const int scaleFactor = 3 * (nestedCount + 1);
- QSize desktopSize = QDesktopWidgetPrivate::size();
+ QSize desktopSize = QGuiApplication::primaryScreen()->virtualSize();
QSize size(desktopSize.width() * 2 / scaleFactor, desktopSize.height() * 2 / scaleFactor);
for (QMdiSubWindow *child : d_func()->childWindows) {
if (!sanityCheck(child, "QMdiArea::sizeHint"))
continue;
size = size.expandedTo(child->sizeHint());
}
- return size.expandedTo(QApplication::globalStrut());
+ return size;
}
/*!
@@ -1770,7 +1738,7 @@ QSize QMdiArea::minimumSizeHint() const
size = size.expandedTo(child->minimumSizeHint());
}
}
- return size.expandedTo(QApplication::globalStrut());
+ return size;
}
/*!
@@ -1794,7 +1762,7 @@ QMdiSubWindow *QMdiArea::currentSubWindow() const
if (d->isActivated && !window()->isMinimized())
return nullptr;
- Q_ASSERT(d->indicesToActivatedChildren.count() > 0);
+ Q_ASSERT(d->indicesToActivatedChildren.size() > 0);
int index = d->indicesToActivatedChildren.at(0);
Q_ASSERT(index >= 0 && index < d->childWindows.size());
QMdiSubWindow *current = d->childWindows.at(index);
@@ -1893,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();
@@ -1950,7 +1922,7 @@ void QMdiArea::activatePreviousSubWindow()
\note Once the subwindow has been added, its parent will be the
\e{viewport widget} of the QMdiArea.
- \snippet mdiareasnippets.cpp 1
+ \snippet mdiarea/mdiareasnippets.cpp 1
When you create your own subwindow, you must set the
Qt::WA_DeleteOnClose widget attribute if you want the window to be
@@ -2032,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) {
@@ -2313,10 +2289,21 @@ 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()) {
- child->resize(resizeEvent->size());
+ auto realSize = resizeEvent->size();
+ const auto minSizeHint = child->minimumSizeHint();
+ // QMdiSubWindow is no tlw so minimumSize() is not set by the layout manager
+ // and therefore we have to take care by ourself that we're not getting smaller
+ // than allowed
+ if (minSizeHint.isValid())
+ realSize = realSize.expandedTo(minSizeHint);
+ child->resize(realSize);
if (!hasMaximizedSubWindow)
hasMaximizedSubWindow = true;
}
@@ -2365,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)
@@ -2379,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)));
@@ -2515,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);
@@ -2549,7 +2552,7 @@ bool QMdiArea::eventFilter(QObject *object, QEvent *event)
if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
- // Ingore key events without a Ctrl modifier (except for press/release on the modifier itself).
+ // Ignore key events without a Ctrl modifier (except for press/release on the modifier itself).
if (!(keyEvent->modifiers() & Qt::ControlModifier) && keyEvent->key() != Qt::Key_Control)
return QAbstractScrollArea::eventFilter(object, event);
@@ -2675,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.h b/src/widgets/widgets/qmdiarea.h
index 35edde9eb8..c1442bc645 100644
--- a/src/widgets/widgets/qmdiarea.h
+++ b/src/widgets/widgets/qmdiarea.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMDIAREA_H
#define QMDIAREA_H
diff --git a/src/widgets/widgets/qmdiarea_p.h b/src/widgets/widgets/qmdiarea_p.h
index 0a6368044a..e57b9772ca 100644
--- a/src/widgets/widgets/qmdiarea_p.h
+++ b/src/widgets/widgets/qmdiarea_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMDIAREA_P_H
#define QMDIAREA_P_H
@@ -58,13 +22,15 @@
QT_REQUIRE_CONFIG(mdiarea);
#include <QList>
-#include <QVector>
+#include <QList>
#include <QRect>
#include <QPoint>
#include <QtWidgets/qapplication.h>
#include <private/qmdisubwindow_p.h>
#include <private/qabstractscrollarea_p.h>
+#include <QtCore/qpointer.h>
+
QT_BEGIN_NAMESPACE
namespace QMdi {
@@ -115,20 +81,22 @@ class Placer
public:
// Places the rectangle defined by 'size' relative to 'rects' and 'domain'.
// Returns the position of the resulting rectangle.
- virtual QPoint place(
- const QSize &size, const QVector<QRect> &rects, const QRect &domain) const = 0;
+ virtual QPoint place(const QSize &size, const QList<QRect> &rects,
+ const QRect &domain) const = 0;
virtual ~Placer() {}
};
class MinOverlapPlacer : public Placer
{
- QPoint place(const QSize &size, const QVector<QRect> &rects, const QRect &domain) const override;
- static int accumulatedOverlap(const QRect &source, const QVector<QRect> &rects);
- static QRect findMinOverlapRect(const QVector<QRect> &source, const QVector<QRect> &rects);
- static QVector<QRect> getCandidatePlacements(const QSize &size, const QVector<QRect> &rects, const QRect &domain);
- static QPoint findBestPlacement(const QRect &domain, const QVector<QRect> &rects, QVector<QRect> &source);
- static QVector<QRect> findNonInsiders(const QRect &domain, QVector<QRect> &source);
- static QVector<QRect> findMaxOverlappers(const QRect &domain, const QVector<QRect> &source);
+ QPoint place(const QSize &size, const QList<QRect> &rects, const QRect &domain) const override;
+ static int accumulatedOverlap(const QRect &source, const QList<QRect> &rects);
+ static QRect findMinOverlapRect(const QList<QRect> &source, const QList<QRect> &rects);
+ static QList<QRect> getCandidatePlacements(const QSize &size, const QList<QRect> &rects,
+ const QRect &domain);
+ static QPoint findBestPlacement(const QRect &domain, const QList<QRect> &rects,
+ QList<QRect> &source);
+ static QList<QRect> findNonInsiders(const QRect &domain, QList<QRect> &source);
+ static QList<QRect> findMaxOverlappers(const QRect &domain, const QList<QRect> &source);
};
} // namespace QMdi
@@ -149,9 +117,9 @@ public:
#endif
QMdiAreaTabBar *tabBar;
QList<QMdi::Rearranger *> pendingRearrangements;
- QVector< QPointer<QMdiSubWindow> > pendingPlacements;
- QVector< QPointer<QMdiSubWindow> > childWindows;
- QVector<int> indicesToActivatedChildren;
+ QList<QPointer<QMdiSubWindow>> pendingPlacements;
+ QList<QPointer<QMdiSubWindow>> childWindows;
+ QList<int> indicesToActivatedChildren;
QPointer<QMdiSubWindow> active;
QPointer<QMdiSubWindow> aboutToBecomeActive;
QBrush background;
diff --git a/src/widgets/widgets/qmdisubwindow.cpp b/src/widgets/widgets/qmdisubwindow.cpp
index f8460a4718..d8700e3df2 100644
--- a/src/widgets/widgets/qmdisubwindow.cpp
+++ b/src/widgets/widgets/qmdisubwindow.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
/*!
\class QMdiSubWindow
@@ -154,7 +118,9 @@
#if QT_CONFIG(whatsthis)
#include <QWhatsThis>
#endif
+#if QT_CONFIG(tooltip)
#include <QToolTip>
+#endif
#if QT_CONFIG(mainwindow)
#include <QMainWindow>
#endif
@@ -168,9 +134,12 @@
#if QT_CONFIG(menu)
#include <QMenu>
#endif
+#include <QProxyStyle>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
using namespace QMdi;
static const QStyle::SubControl SubControls[] =
@@ -201,7 +170,9 @@ static const int BoundaryMargin = 5;
static inline bool isMacStyle(QStyle *style)
{
- return style->inherits("QMacStyle");
+ auto proxyStyle = qobject_cast<QProxyStyle *>(style);
+ auto styleToCheck = proxyStyle ? proxyStyle->baseStyle() : style;
+ return styleToCheck->inherits("QMacStyle");
}
static inline int getMoveDeltaComponent(uint cflags, uint moveFlag, uint resizeFlag,
@@ -258,13 +229,30 @@ static inline ControlElement<T> *ptr(QWidget *widget)
return nullptr;
}
+QString QMdiSubWindowPrivate::originalWindowTitleHelper() const
+{
+ Q_Q(const QMdiSubWindow);
+ // QTBUG-92240: When DontMaximizeSubWindowOnActivation is set and
+ // there is another subwindow maximized, use its original title.
+ if (auto *mdiArea = q->mdiArea()) {
+ const auto &subWindows = mdiArea->subWindowList();
+ for (auto *subWindow : subWindows) {
+ if (subWindow != q && subWindow->isMaximized()) {
+ auto *subWindowD = static_cast<QMdiSubWindowPrivate *>(qt_widget_private(subWindow));
+ if (!subWindowD->originalTitle.isNull())
+ return subWindowD->originalTitle;
+ }
+ }
+ }
+ return q->window()->windowTitle();
+}
+
QString QMdiSubWindowPrivate::originalWindowTitle()
{
- Q_Q(QMdiSubWindow);
if (originalTitle.isNull()) {
- originalTitle = q->window()->windowTitle();
+ originalTitle = originalWindowTitleHelper();
if (originalTitle.isNull())
- originalTitle = QLatin1String("");
+ originalTitle = ""_L1;
}
return originalTitle;
}
@@ -277,11 +265,17 @@ void QMdiSubWindowPrivate::setNewWindowTitle()
return;
QString original = originalWindowTitle();
if (!original.isEmpty()) {
- if (!original.contains(QMdiSubWindow::tr("- [%1]").arg(childTitle)))
- q->window()->setWindowTitle(QMdiSubWindow::tr("%1 - [%2]").arg(original, childTitle));
+ if (!original.contains(QMdiSubWindow::tr("- [%1]").arg(childTitle))) {
+ auto title = QMdiSubWindow::tr("%1 - [%2]").arg(original, childTitle);
+ ignoreWindowTitleChange = true;
+ q->window()->setWindowTitle(title);
+ ignoreWindowTitleChange = false;
+ }
} else {
+ ignoreWindowTitleChange = true;
q->window()->setWindowTitle(childTitle);
+ ignoreWindowTitleChange = false;
}
}
@@ -290,7 +284,7 @@ static inline bool isHoverControl(QStyle::SubControl control)
return control != QStyle::SC_None && control != QStyle::SC_TitleBarLabel;
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
static void showToolTip(QHelpEvent *helpEvent, QWidget *widget, const QStyleOptionComplex &opt,
QStyle::ComplexControl complexControl, QStyle::SubControl subControl)
{
@@ -355,7 +349,7 @@ static void showToolTip(QHelpEvent *helpEvent, QWidget *widget, const QStyleOpti
const QRect rect = widget->style()->subControlRect(complexControl, &opt, subControl, widget);
QToolTip::showText(helpEvent->globalPos(), toolTip, widget, rect);
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
namespace QMdi {
/*
@@ -394,7 +388,7 @@ ControlLabel::ControlLabel(QMdiSubWindow *subWindow, QWidget *parent)
Q_UNUSED(subWindow);
setFocusPolicy(Qt::NoFocus);
updateWindowIcon();
- setFixedSize(label.size());
+ setFixedSize(label.deviceIndependentSize().toSize());
}
/*
@@ -402,7 +396,7 @@ ControlLabel::ControlLabel(QMdiSubWindow *subWindow, QWidget *parent)
*/
QSize ControlLabel::sizeHint() const
{
- return label.size();
+ return label.deviceIndependentSize().toSize();
}
/*
@@ -416,7 +410,7 @@ bool ControlLabel::event(QEvent *event)
updateWindowIcon();
setFixedSize(label.size());
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
else if (event->type() == QEvent::ToolTip) {
QStyleOptionTitleBar options;
options.initFrom(this);
@@ -611,7 +605,7 @@ void ControllerWidget::mousePressEvent(QMouseEvent *event)
event->ignore();
return;
}
- activeControl = getSubControl(event->pos());
+ activeControl = getSubControl(event->position().toPoint());
update();
}
@@ -625,7 +619,7 @@ void ControllerWidget::mouseReleaseEvent(QMouseEvent *event)
return;
}
- QStyle::SubControl under_mouse = getSubControl(event->pos());
+ QStyle::SubControl under_mouse = getSubControl(event->position().toPoint());
if (under_mouse == activeControl) {
switch (activeControl) {
case QStyle::SC_MdiCloseButton:
@@ -651,7 +645,7 @@ void ControllerWidget::mouseReleaseEvent(QMouseEvent *event)
*/
void ControllerWidget::mouseMoveEvent(QMouseEvent *event)
{
- QStyle::SubControl under_mouse = getSubControl(event->pos());
+ QStyle::SubControl under_mouse = getSubControl(event->position().toPoint());
//test if hover state changes
if (hoverControl != under_mouse) {
hoverControl = under_mouse;
@@ -673,14 +667,14 @@ void ControllerWidget::leaveEvent(QEvent * /*event*/)
*/
bool ControllerWidget::event(QEvent *event)
{
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
if (event->type() == QEvent::ToolTip) {
QStyleOptionComplex opt;
initStyleOption(&opt);
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
showToolTip(helpEvent, this, opt, QStyle::CC_MdiControls, getSubControl(helpEvent->pos()));
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
return QWidget::event(event);
}
@@ -739,7 +733,7 @@ ControlContainer::~ControlContainer()
QMenuBar *QMdiSubWindowPrivate::menuBar() const
{
#if !QT_CONFIG(mainwindow)
- return 0;
+ return nullptr;
#else
Q_Q(const QMdiSubWindow);
if (!q->isMaximized() || drawTitleBarWhenMaximized() || isChildOfTabbedQMdiArea(q))
@@ -1891,7 +1885,7 @@ void QMdiSubWindowPrivate::enterRubberBandMode()
if (!rubberBand) {
rubberBand = new QRubberBand(QRubberBand::Rectangle, q->parentWidget());
// For accessibility to identify this special widget.
- rubberBand->setObjectName(QLatin1String("qt_rubberband"));
+ rubberBand->setObjectName("qt_rubberband"_L1);
}
QPoint rubberBandPos = q->mapToParent(QPoint(0, 0));
rubberBand->setGeometry(rubberBandPos.x(), rubberBandPos.y(),
@@ -1920,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;
}
@@ -2188,7 +2178,7 @@ void QMdiSubWindowPrivate::updateInternalWindowTitle()
Q_Q(QMdiSubWindow);
if (q->isWindowModified()) {
windowTitle = q->windowTitle();
- windowTitle.replace(QLatin1String("[*]"), QLatin1String("*"));
+ windowTitle.replace("[*]"_L1, "*"_L1);
} else {
windowTitle = qt_setWindowTitle_helperHelper(q->windowTitle(), q);
}
@@ -2306,10 +2296,8 @@ void QMdiSubWindow::setWidget(QWidget *widget)
d->updateWindowTitle(true);
isWindowModified = d->baseWidget->isWindowModified();
}
- if (!this->isWindowModified() && isWindowModified
- && windowTitle().contains(QLatin1String("[*]"))) {
+ if (!this->isWindowModified() && isWindowModified && windowTitle().contains("[*]"_L1))
setWindowModified(isWindowModified);
- }
d->lastChildWindowTitle = d->baseWidget->windowTitle();
d->ignoreWindowTitleChange = false;
@@ -2657,12 +2645,12 @@ bool QMdiSubWindow::eventFilter(QObject *object, QEvent *event)
if (d->systemMenu && d->systemMenu == object) {
if (event->type() == QEvent::MouseButtonDblClick) {
const QMouseEvent *mouseEvent = static_cast<const QMouseEvent *>(event);
- const QAction *action = d->systemMenu->actionAt(mouseEvent->pos());
+ const QAction *action = d->systemMenu->actionAt(mouseEvent->position().toPoint());
if (!action || action->isEnabled())
close();
} else if (event->type() == QEvent::MouseMove) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
- d->hoveredSubControl = d->getSubControl(mapFromGlobal(mouseEvent->globalPos()));
+ d->hoveredSubControl = d->getSubControl(mapFromGlobal(mouseEvent->globalPosition().toPoint()));
} else if (event->type() == QEvent::Hide) {
d->activeSubControl = QStyle::SC_None;
update(QRegion(0, 0, width(), d->titleBarHeight()));
@@ -2676,7 +2664,7 @@ bool QMdiSubWindow::eventFilter(QObject *object, QEvent *event)
if (event->type() != QEvent::MouseButtonPress || !testOption(QMdiSubWindow::RubberBandResize))
return QWidget::eventFilter(object, event);
const QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
- d->mousePressPosition = parentWidget()->mapFromGlobal(mouseEvent->globalPos());
+ d->mousePressPosition = parentWidget()->mapFromGlobal(mouseEvent->globalPosition().toPoint());
d->oldGeometry = geometry();
d->currentOperation = isLeftToRight() ? QMdiSubWindowPrivate::BottomRightResize
: QMdiSubWindowPrivate::BottomLeftResize;
@@ -2742,7 +2730,7 @@ bool QMdiSubWindow::eventFilter(QObject *object, QEvent *event)
bool windowModified = d->baseWidget->isWindowModified();
if (!windowModified && d->baseWidget->windowTitle() != windowTitle())
break;
- if (windowTitle().contains(QLatin1String("[*]")))
+ if (windowTitle().contains("[*]"_L1))
setWindowModified(windowModified);
break;
}
@@ -2843,7 +2831,7 @@ bool QMdiSubWindow::event(QEvent *event)
d->updateInternalWindowTitle();
break;
case QEvent::ModifiedChange:
- if (!windowTitle().contains(QLatin1String("[*]")))
+ if (!windowTitle().contains("[*]"_L1))
break;
#if QT_CONFIG(menubar)
if (maximizedButtonsWidget() && d->controlContainer->menuBar() && d->controlContainer->menuBar()
@@ -2874,7 +2862,7 @@ bool QMdiSubWindow::event(QEvent *event)
case QEvent::FontChange:
d->font = font();
break;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::ToolTip:
showToolTip(static_cast<QHelpEvent *>(event), this, d->titleBarOptions(),
QStyle::CC_TitleBar, d->hoveredSubControl);
@@ -3171,7 +3159,7 @@ void QMdiSubWindow::mousePressEvent(QMouseEvent *mouseEvent)
if (d->currentOperation != QMdiSubWindowPrivate::None) {
d->updateCursor();
- d->mousePressPosition = mapToParent(mouseEvent->pos());
+ d->mousePressPosition = mapToParent(mouseEvent->position().toPoint());
if (d->resizeEnabled || d->moveEnabled)
d->oldGeometry = geometry();
#if QT_CONFIG(rubberband)
@@ -3262,10 +3250,10 @@ void QMdiSubWindow::mouseReleaseEvent(QMouseEvent *mouseEvent)
d->oldGeometry = geometry();
}
- d->currentOperation = d->getOperation(mouseEvent->pos());
+ d->currentOperation = d->getOperation(mouseEvent->position().toPoint());
d->updateCursor();
- d->hoveredSubControl = d->getSubControl(mouseEvent->pos());
+ d->hoveredSubControl = d->getSubControl(mouseEvent->position().toPoint());
if (d->activeSubControl != QStyle::SC_None
&& d->activeSubControl == d->hoveredSubControl) {
d->processClickedSubControl();
@@ -3290,7 +3278,7 @@ void QMdiSubWindow::mouseMoveEvent(QMouseEvent *mouseEvent)
// Find previous and current hover region.
const QStyleOptionTitleBar options = d->titleBarOptions();
QStyle::SubControl oldHover = d->hoveredSubControl;
- d->hoveredSubControl = d->getSubControl(mouseEvent->pos());
+ d->hoveredSubControl = d->getSubControl(mouseEvent->position().toPoint());
QRegion hoverRegion;
if (isHoverControl(oldHover) && oldHover != d->hoveredSubControl)
hoverRegion += style()->subControlRect(QStyle::CC_TitleBar, &options, oldHover, this);
@@ -3310,13 +3298,13 @@ void QMdiSubWindow::mouseMoveEvent(QMouseEvent *mouseEvent)
if ((d->isResizeOperation() && d->resizeEnabled) || (d->isMoveOperation() && d->moveEnabled)) {
// As setNewGeometry moves the window, it invalidates the pos() value of any mouse move events that are
// currently queued in the event loop. Map to parent using globalPos() instead.
- d->setNewGeometry(parentWidget()->mapFromGlobal(mouseEvent->globalPos()));
+ d->setNewGeometry(parentWidget()->mapFromGlobal(mouseEvent->globalPosition().toPoint()));
}
return;
}
// Do not resize/move if not allowed.
- d->currentOperation = d->getOperation(mouseEvent->pos());
+ d->currentOperation = d->getOperation(mouseEvent->position().toPoint());
if ((d->isResizeOperation() && !d->resizeEnabled) || (d->isMoveOperation() && !d->moveEnabled))
d->currentOperation = QMdiSubWindowPrivate::None;
d->updateCursor();
@@ -3516,7 +3504,7 @@ QSize QMdiSubWindow::minimumSizeHint() const
minHeight = qMax(minHeight, decorationHeight + sizeGripHeight);
#endif
- return QSize(minWidth, minHeight).expandedTo(QApplication::globalStrut());
+ return QSize(minWidth, minHeight);
}
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qmdisubwindow.h b/src/widgets/widgets/qmdisubwindow.h
index 302522e1c3..4227f02dac 100644
--- a/src/widgets/widgets/qmdisubwindow.h
+++ b/src/widgets/widgets/qmdisubwindow.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMDISUBWINDOW_H
#define QMDISUBWINDOW_H
@@ -137,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 d3513b6708..2a1f83269a 100644
--- a/src/widgets/widgets/qmdisubwindow_p.h
+++ b/src/widgets/widgets/qmdisubwindow_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMDISUBWINDOW_P_H
#define QMDISUBWINDOW_P_H
@@ -75,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)
@@ -94,7 +58,7 @@ public:
QPointer<QMdiSubWindow> mdiChild;
};
-class ControlContainer : public QObject
+class ControlContainer : public QObject // ELFVERSION:ignore
{
public:
ControlContainer(QMdiSubWindow *mdiChild);
@@ -121,7 +85,7 @@ private:
};
} // namespace QMdi
-class QMdiSubWindowPrivate : public QWidgetPrivate
+class Q_AUTOTEST_EXPORT QMdiSubWindowPrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QMdiSubWindow)
public:
@@ -286,6 +250,7 @@ public:
#endif
void updateInternalWindowTitle();
QString originalWindowTitle();
+ QString originalWindowTitleHelper() const;
void setNewWindowTitle();
inline int titleBarHeight() const
diff --git a/src/widgets/widgets/qmenu.cpp b/src/widgets/widgets/qmenu.cpp
index fc7e2dbbcb..db00f8a650 100644
--- a/src/widgets/widgets/qmenu.cpp
+++ b/src/widgets/widgets/qmenu.cpp
@@ -1,59 +1,21 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qmenu.h"
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include <QtWidgets/private/qwidgetwindow_p.h>
+#include "qactiongroup.h"
#include "qdebug.h"
#include "qstyle.h"
#include "qevent.h"
#include "qtimer.h"
#include "qlayout.h"
-#include "qpainter.h"
+#include "qstylepainter.h"
#include <qpa/qplatformtheme.h>
-#ifdef Q_OS_OSX
-#include "qmacnativewidget_mac.h"
-#endif
#include "qapplication.h"
-#include "qdesktopwidget.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
# include "qaccessible.h"
#endif
#if QT_CONFIG(effects)
@@ -72,13 +34,14 @@
#include "qtoolbutton.h"
#endif
#include "qpushbutton.h"
+#if QT_CONFIG(tooltip)
#include "qtooltip.h"
+#endif
#include <qwindow.h>
#include <private/qpushbutton_p.h>
#include <private/qaction_p.h>
#include <private/qguiapplication_p.h>
#include <qpa/qplatformtheme.h>
-#include <private/qdesktopwidget_p.h>
#include <private/qstyle_p.h>
QT_BEGIN_NAMESPACE
@@ -105,7 +68,7 @@ class QTornOffMenu : public QMenu
Q_Q(QTornOffMenu);
QSize size = menuSize;
const QPoint p = (!initialized) ? causedMenu->pos() : q->pos();
- QRect screen = popupGeometry(QDesktopWidgetPrivate::screenNumber(p));
+ const QRect screen = popupGeometry(QGuiApplication::screenAt(p));
const int desktopFrame = q->style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, nullptr, q);
const int titleBarHeight = q->style()->pixelMetric(QStyle::PM_TitleBarHeight, nullptr, q);
if (scroll && (size.height() > screen.height() - titleBarHeight || size.width() > screen.width())) {
@@ -118,9 +81,9 @@ class QTornOffMenu : public QMenu
q->setFixedSize(size);
}
- QVector<QPointer<QWidget> > calcCausedStack() const override { return causedStack; }
+ QList<QPointer<QWidget>> calcCausedStack() const override { return causedStack; }
QPointer<QMenu> causedMenu;
- QVector<QPointer<QWidget> > causedStack;
+ QList<QPointer<QWidget>> causedStack;
bool initialized;
};
@@ -130,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);
@@ -147,7 +112,7 @@ public:
//QObject::connect(this, SIGNAL(triggered(QAction*)), this, SLOT(onTrigger(QAction*)));
//QObject::connect(this, SIGNAL(hovered(QAction*)), this, SLOT(onHovered(QAction*)));
QList<QAction*> items = p->actions();
- for(int i = 0; i < items.count(); i++)
+ for(int i = 0; i < items.size(); i++)
addAction(items.at(i));
d->setMenuSize(sizeHint());
d->initialized = true;
@@ -155,7 +120,7 @@ public:
void syncWithMenu(QMenu *menu, QActionEvent *act)
{
Q_D(QTornOffMenu);
- if(menu != d->causedMenu)
+ if (menu != d->causedMenu)
return;
auto action = static_cast<QAction *>(act->action());
if (act->type() == QEvent::ActionAdded) {
@@ -198,8 +163,9 @@ void QMenuPrivate::init()
#endif
q->setAttribute(Qt::WA_X11NetWmWindowTypePopupMenu);
defaultMenuAction = menuAction = new QAction(q);
- menuAction->d_func()->menu = q;
- QObject::connect(menuAction, &QAction::changed, [this] {
+ menuAction->setMenu(q); // this calls setOverrideMenuAction
+ setOverrideMenuAction(nullptr);
+ QObject::connect(menuAction, &QAction::changed, q, [this] {
if (!tornPopup.isNull())
tornPopup->updateWindowTitle();
});
@@ -251,15 +217,23 @@ void QMenuPrivate::syncPlatformMenu()
platformMenu->setEnabled(q->isEnabled());
}
+static QWidget *getParentWidget(const QAction *action)
+{
+ auto result = action->parent();
+ while (result && !qobject_cast<QWidget *>(result))
+ result = result->parent();
+ return static_cast<QWidget *>(result);
+}
+
void QMenuPrivate::copyActionToPlatformItem(const QAction *action, QPlatformMenuItem *item)
{
item->setText(action->text());
item->setIsSeparator(action->isSeparator());
if (action->isIconVisibleInMenu()) {
item->setIcon(action->icon());
- if (QWidget *w = action->parentWidget()) {
+ if (QWidget *w = getParentWidget(action)) {
QStyleOption opt;
- opt.init(w);
+ opt.initFrom(w);
item->setIconSize(w->style()->pixelMetric(QStyle::PM_SmallIconSize, &opt, w));
} else {
QStyleOption opt;
@@ -305,7 +279,7 @@ QPlatformMenuItem * QMenuPrivate::insertActionInPlatformMenu(const QAction *acti
int QMenuPrivate::scrollerHeight() const
{
Q_Q(const QMenu);
- return qMax(QApplication::globalStrut().height(), q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, nullptr, q));
+ return q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, nullptr, q);
}
// Windows and KDE allow menus to cover the taskbar, while GNOME and macOS
@@ -315,24 +289,26 @@ inline bool QMenuPrivate::useFullScreenForPopup() const
return !tornoff && QStylePrivate::useFullScreenForPopup();
}
-QRect QMenuPrivate::popupGeometry() const
+QRect QMenuPrivate::popupGeometry(QScreen *screen) const
{
Q_Q(const QMenu);
- return useFullScreenForPopup()
- ? QDesktopWidgetPrivate::screenGeometry(q)
- : QDesktopWidgetPrivate::availableGeometry(q);
-}
-
-QRect QMenuPrivate::popupGeometry(int screen) const
-{
- return useFullScreenForPopup()
- ? QDesktopWidgetPrivate::screenGeometry(screen)
- : QDesktopWidgetPrivate::availableGeometry(screen);
+ 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);
+ return screen ? screen->availableGeometry()
+ : QWidgetPrivate::availableScreenGeometry(q);
}
-QVector<QPointer<QWidget> > QMenuPrivate::calcCausedStack() const
+QList<QPointer<QWidget>> QMenuPrivate::calcCausedStack() const
{
- QVector<QPointer<QWidget> > ret;
+ QList<QPointer<QWidget>> ret;
for(QWidget *widget = causedPopup.widget; widget; ) {
ret.append(widget);
if (QTornOffMenu *qtmenu = qobject_cast<QTornOffMenu*>(widget))
@@ -347,7 +323,11 @@ QVector<QPointer<QWidget> > QMenuPrivate::calcCausedStack() const
bool QMenuPrivate::isContextMenu() const
{
+#if QT_CONFIG(menubar)
return qobject_cast<const QMenuBar *>(topCausedWidget()) == nullptr;
+#else
+ return true;
+#endif
}
void QMenuPrivate::updateActionRects() const
@@ -364,14 +344,14 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const
q->ensurePolished();
//let's reinitialize the buffer
- actionRects.resize(actions.count());
+ actionRects.resize(actions.size());
actionRects.fill(QRect());
int lastVisibleAction = getLastVisibleAction();
QStyle *style = q->style();
QStyleOption opt;
- opt.init(q);
+ opt.initFrom(q);
const int hmargin = style->pixelMetric(QStyle::PM_MenuHMargin, &opt, q),
vmargin = style->pixelMetric(QStyle::PM_MenuVMargin, &opt, q),
icone = style->pixelMetric(QStyle::PM_SmallIconSize, &opt, q);
@@ -389,7 +369,7 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const
hasCheckableItems = false;
ncols = 1;
- for (int i = 0; i < actions.count(); ++i) {
+ for (int i = 0; i < actions.size(); ++i) {
QAction *action = actions.at(i);
if (action->isSeparator() || !action->isVisible() || widgetItems.contains(action))
continue;
@@ -433,7 +413,7 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const
sz = QSize(2, 2);
} else {
QString s = action->text();
- int t = s.indexOf(QLatin1Char('\t'));
+ qsizetype t = s.indexOf(u'\t');
if (t != -1) {
tabWidth = qMax(int(tabWidth), qfm.horizontalAdvance(s.mid(t+1)));
s = s.left(t);
@@ -473,8 +453,8 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const
}
max_column_width += tabWidth; //finally add in the tab width
- if (!tornoff || (tornoff && scroll)) { // exclude non-scrollable tear-off menu since the tear-off menu has a fixed size
- const int sfcMargin = style->sizeFromContents(QStyle::CT_Menu, &opt, QApplication::globalStrut(), q).width() - QApplication::globalStrut().width();
+ if (!tornoff || scroll) { // exclude non-scrollable tear-off menu since the tear-off menu has a fixed size
+ const int sfcMargin = style->sizeFromContents(QStyle::CT_Menu, &opt, QSize(0, 0), q).width();
const int min_column_width = q->minimumWidth() - (sfcMargin + leftmargin + rightmargin + 2 * (fw + hmargin));
max_column_width = qMax(min_column_width, max_column_width);
}
@@ -483,7 +463,7 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const
int x = hmargin + fw + leftmargin;
y = base_y;
- for(int i = 0; i < actions.count(); i++) {
+ for(int i = 0; i < actions.size(); i++) {
QRect &rect = actionRects[i];
if (rect.isNull())
continue;
@@ -508,7 +488,7 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const
int QMenuPrivate::getLastVisibleAction() const
{
//let's try to get the last visible action
- int lastVisibleAction = actions.count() - 1;
+ int lastVisibleAction = actions.size() - 1;
for (;lastVisibleAction >= 0; --lastVisibleAction) {
const QAction *action = actions.at(lastVisibleAction);
if (action->isVisible()) {
@@ -566,20 +546,59 @@ void QMenuPrivate::hideMenu(QMenu *menu)
{
if (!menu)
return;
+
+ // See two execs below. They may trigger an akward situation
+ // when 'menu' (also known as 'q' or 'this' in the many functions
+ // around) to become a dangling pointer if the loop manages
+ // to execute 'deferred delete' ... posted while executing
+ // this same loop. Not good!
+ struct Reposter : QObject
+ {
+ Reposter(QMenu *menu) : q(menu)
+ {
+ Q_ASSERT(q);
+ q->installEventFilter(this);
+ }
+ ~Reposter()
+ {
+ if (deleteLater)
+ q->deleteLater();
+ }
+ bool eventFilter(QObject *obj, QEvent *event) override
+ {
+ if (obj == q && event->type() == QEvent::DeferredDelete)
+ return deleteLater = true;
+
+ return QObject::eventFilter(obj, event);
+ }
+ QMenu *q = nullptr;
+ bool deleteLater = false;
+ };
+
#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;
QAction *activeAction = currentAction;
menu->setActiveAction(nullptr);
+ const Reposter deleteDeleteLate(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()));
@@ -587,15 +606,44 @@ 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;
}
+QWindow *QMenuPrivate::transientParentWindow() const
+{
+ Q_Q(const QMenu);
+ if (const QWidget *parent = q->nativeParentWidget()) {
+ if (parent->windowHandle())
+ return parent->windowHandle();
+ }
+
+ if (const QWindow *w = q->windowHandle()) {
+ if (w->transientParent())
+ return w->transientParent();
+ }
+
+ if (causedPopup.widget) {
+ if (const QWidget *w = causedPopup.widget.data()) {
+ if (const QWidget *ww = w->window())
+ return ww->windowHandle();
+ }
+ }
+
+ return nullptr;
+}
+
void QMenuPrivate::popupAction(QAction *action, int delay, bool activateFirst)
{
Q_Q(QMenu);
@@ -619,7 +667,7 @@ void QMenuPrivate::setSyncAction()
{
Q_Q(QMenu);
QAction *current = currentAction;
- if(current && (!current->isEnabled() || current->menu() || current->isSeparator()))
+ if (current && (!current->isEnabled() || current->menu() || current->isSeparator()))
current = nullptr;
for(QWidget *caused = q; caused;) {
if (QMenu *m = qobject_cast<QMenu*>(caused)) {
@@ -637,7 +685,7 @@ void QMenuPrivate::setFirstActionActive()
{
Q_Q(QMenu);
updateActionRects();
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
+ for(int i = 0, saccum = 0; i < actions.size(); i++) {
const QRect &rect = actionRects.at(i);
if (rect.isNull())
continue;
@@ -874,7 +922,7 @@ QAction *QMenuPrivate::actionAt(QPoint p) const
if (!rect().contains(p)) //sanity check
return nullptr;
- for(int i = 0; i < actionRects.count(); i++) {
+ for(int i = 0; i < actionRects.size(); i++) {
if (actionRects.at(i).contains(p))
return actions.at(i);
}
@@ -929,7 +977,7 @@ void QMenuPrivate::drawScroller(QPainter *painter, QMenuPrivate::ScrollerTearOff
menuOpt.state = QStyle::State_None;
menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
menuOpt.maxIconWidth = 0;
- menuOpt.tabWidth = 0;
+ menuOpt.reservedShortcutWidth = 0;
menuOpt.rect = rect;
menuOpt.menuItemType = QStyleOptionMenuItem::Scroller;
menuOpt.state |= QStyle::State_Enabled;
@@ -954,7 +1002,7 @@ void QMenuPrivate::drawTearOff(QPainter *painter, const QRect &rect)
menuOpt.state = QStyle::State_None;
menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
menuOpt.maxIconWidth = 0;
- menuOpt.tabWidth = 0;
+ menuOpt.reservedShortcutWidth = 0;
menuOpt.rect = rect;
menuOpt.menuItemType = QStyleOptionMenuItem::TearOff;
if (tearoffHighlighted)
@@ -969,7 +1017,7 @@ QRect QMenuPrivate::rect() const
Q_Q(const QMenu);
QStyle *style = q->style();
QStyleOption opt(0);
- opt.init(q);
+ opt.initFrom(q);
const int hmargin = style->pixelMetric(QStyle::PM_MenuHMargin, &opt, q);
const int vmargin = style->pixelMetric(QStyle::PM_MenuVMargin, &opt, q);
const int fw = style->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, q);
@@ -1024,6 +1072,16 @@ QAction *QMenu::menuAction() const
}
/*!
+ \fn static QMenu *QMenu::menuInAction(const QAction *action)
+
+ Returns the menu contained by \a action, or \nullptr if \a action does not
+ contain a menu.
+
+ In widget applications, actions that contain menus can be used to create menu
+ items with submenus, or inserted into toolbars to create buttons with popup menus.
+*/
+
+/*!
\property QMenu::title
\brief The title of the menu
@@ -1075,7 +1133,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc
const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, nullptr, q);
if (location == QMenuScroller::ScrollTop) {
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
+ for(int i = 0, saccum = 0; i < actions.size(); i++) {
if (actions.at(i) == action) {
newOffset = topScroll - saccum;
break;
@@ -1083,7 +1141,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc
saccum += actionRects.at(i).height();
}
} else {
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
+ for(int i = 0, saccum = 0; i < actions.size(); i++) {
saccum += actionRects.at(i).height();
if (actions.at(i) == action) {
if (location == QMenuScroller::ScrollCenter)
@@ -1093,7 +1151,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc
break;
}
}
- if(newOffset)
+ if (newOffset)
newOffset -= fw * 2;
}
@@ -1102,7 +1160,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc
if (newOffset < 0) //easy and cheap one
newScrollFlags |= QMenuScroller::ScrollUp;
int saccum = newOffset;
- for(int i = 0; i < actionRects.count(); i++) {
+ for(int i = 0; i < actionRects.size(); i++) {
saccum += actionRects.at(i).height();
if (saccum > q->height()) {
newScrollFlags |= QMenuScroller::ScrollDown;
@@ -1129,9 +1187,9 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc
QRect geom = q->geometry();
if (newOffset > scroll->scrollOffset && (scroll->scrollFlags & newScrollFlags & QMenuScroller::ScrollUp)) { //scroll up
const int newHeight = geom.height()-(newOffset-scroll->scrollOffset);
- if(newHeight > geom.height())
+ if (newHeight > geom.height())
geom.setHeight(newHeight);
- } else if(scroll->scrollFlags & newScrollFlags & QMenuScroller::ScrollDown) {
+ } else if (scroll->scrollFlags & newScrollFlags & QMenuScroller::ScrollDown) {
int newTop = geom.top() + (newOffset-scroll->scrollOffset);
if (newTop < desktopFrame+screen.top())
newTop = desktopFrame+screen.top();
@@ -1159,7 +1217,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc
const int delta = qMin(0, newOffset) - scroll->scrollOffset; //make sure the new offset is always negative
if (!itemsDirty && delta) {
//we've scrolled so we need to update the action rects
- for (int i = 0; i < actionRects.count(); ++i) {
+ for (int i = 0; i < actionRects.size(); ++i) {
QRect &current = actionRects[i];
current.moveTop(current.top() + delta);
@@ -1180,7 +1238,7 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollLocation location, bool activ
{
Q_Q(QMenu);
updateActionRects();
- if(location == QMenuScroller::ScrollBottom) {
+ if (location == QMenuScroller::ScrollBottom) {
for(int i = actions.size()-1; i >= 0; --i) {
QAction *act = actions.at(i);
if (actionRects.at(i).isNull())
@@ -1188,14 +1246,14 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollLocation location, bool activ
if (!act->isSeparator() &&
(q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, nullptr, q)
|| act->isEnabled())) {
- if(scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown)
+ if (scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown)
scrollMenu(act, QMenuPrivate::QMenuScroller::ScrollBottom, active);
- else if(active)
+ else if (active)
setCurrentAction(act, /*popup*/-1, QMenuPrivate::SelectedFromKeyboard);
break;
}
}
- } else if(location == QMenuScroller::ScrollTop) {
+ } else if (location == QMenuScroller::ScrollTop) {
for(int i = 0; i < actions.size(); ++i) {
QAction *act = actions.at(i);
if (actionRects.at(i).isNull())
@@ -1203,9 +1261,9 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollLocation location, bool activ
if (!act->isSeparator() &&
(q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, nullptr, q)
|| act->isEnabled())) {
- if(scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
+ if (scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
scrollMenu(act, QMenuPrivate::QMenuScroller::ScrollTop, active);
- else if(active)
+ else if (active)
setCurrentAction(act, /*popup*/-1, QMenuPrivate::SelectedFromKeyboard);
break;
}
@@ -1226,7 +1284,7 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollDirection direction, bool pag
const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, nullptr, q);
const int offset = topScroll ? topScroll-vmargin : 0;
if (direction == QMenuScroller::ScrollUp) {
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
+ for(int i = 0, saccum = 0; i < actions.size(); i++) {
saccum -= actionRects.at(i).height();
if (saccum <= scroll->scrollOffset-offset) {
scrollMenu(actions.at(i), page ? QMenuScroller::ScrollBottom : QMenuScroller::ScrollTop, active);
@@ -1235,13 +1293,13 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollDirection direction, bool pag
}
} else if (direction == QMenuScroller::ScrollDown) {
bool scrolled = false;
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
+ for(int i = 0, saccum = 0; i < actions.size(); i++) {
const int iHeight = actionRects.at(i).height();
saccum -= iHeight;
if (saccum <= scroll->scrollOffset-offset) {
const int scrollerArea = q->height() - botScroll - fw*2;
int visible = (scroll->scrollOffset-offset) - saccum;
- for(i++ ; i < actions.count(); i++) {
+ for(i++ ; i < actions.size(); i++) {
visible += actionRects.at(i).height();
if (visible > scrollerArea - topScroll) {
scrolled = true;
@@ -1252,7 +1310,7 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollDirection direction, bool pag
break;
}
}
- if(!scrolled) {
+ if (!scrolled) {
scroll->scrollFlags &= ~QMenuScroller::ScrollDown;
q->update();
}
@@ -1264,11 +1322,11 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollDirection direction, bool pag
bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
{
Q_Q(QMenu);
- QPoint pos = q->mapFromGlobal(e->globalPos());
+ QPoint pos = q->mapFromGlobal(e->globalPosition().toPoint());
QStyle *style = q->style();
QStyleOption opt(0);
- opt.init(q);
+ opt.initFrom(q);
const int hmargin = style->pixelMetric(QStyle::PM_MenuHMargin, &opt, q);
const int vmargin = style->pixelMetric(QStyle::PM_MenuVMargin, &opt, q);
const int fw = style->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, q);
@@ -1303,7 +1361,7 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
if (scroll && scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
tearRect.translate(0, scrollerHeight());
q->update(tearRect);
- if (tearRect.contains(pos) && hasMouseMoved(e->globalPos())) {
+ if (tearRect.contains(pos) && hasMouseMoved(e->globalPosition().toPoint())) {
setCurrentAction(nullptr);
tearoffHighlighted = 1;
if (e->type() == QEvent::MouseButtonRelease) {
@@ -1318,26 +1376,27 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
tearoffHighlighted = 0;
}
- if (q->frameGeometry().contains(e->globalPos()))
+ if (q->frameGeometry().contains(e->globalPosition().toPoint()))
return false; //otherwise if the event is in our rect we want it..
for(QWidget *caused = causedPopup.widget; caused;) {
bool passOnEvent = false;
QWidget *next_widget = nullptr;
- QPoint cpos = caused->mapFromGlobal(e->globalPos());
+ QPointF cpos = caused->mapFromGlobal(e->globalPosition());
#if QT_CONFIG(menubar)
if (QMenuBar *mb = qobject_cast<QMenuBar*>(caused)) {
- passOnEvent = mb->rect().contains(cpos);
+ passOnEvent = mb->rect().contains(cpos.toPoint());
} else
#endif
if (QMenu *m = qobject_cast<QMenu*>(caused)) {
- passOnEvent = m->rect().contains(cpos);
+ passOnEvent = m->rect().contains(cpos.toPoint());
next_widget = m->d_func()->causedPopup.widget;
}
if (passOnEvent) {
if (e->type() != QEvent::MouseButtonRelease || mouseDown == caused) {
- QMouseEvent new_e(e->type(), cpos, caused->mapTo(caused->topLevelWidget(), cpos), e->screenPos(),
- e->button(), e->buttons(), e->modifiers(), e->source());
+ QMouseEvent new_e(e->type(), cpos, caused->mapTo(caused->topLevelWidget(), cpos), e->globalPosition(),
+ e->button(), e->buttons(), e->modifiers(),
+ e->source(), e->pointingDevice());
QCoreApplication::sendEvent(caused, &new_e);
return true;
}
@@ -1349,11 +1408,21 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
return false;
}
-void QMenuPrivate::activateCausedStack(const QVector<QPointer<QWidget> > &causedStack, QAction *action, QAction::ActionEvent action_e, bool self)
+void QMenuPrivate::activateCausedStack(const QList<QPointer<QWidget>> &causedStack, QAction *action,
+ QAction::ActionEvent action_e, bool self)
{
- QBoolBlocker guard(activationRecursionGuard);
- if(self)
+ 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);
@@ -1397,7 +1466,7 @@ void QMenuPrivate::activateAction(QAction *action, QAction::ActionEvent action_e
/* I have to save the caused stack here because it will be undone after popup execution (ie in the hide).
Then I iterate over the list to actually send the events. --Sam
*/
- const QVector<QPointer<QWidget> > causedStack = calcCausedStack();
+ const QList<QPointer<QWidget>> causedStack = calcCausedStack();
if (action_e == QAction::Trigger) {
#if QT_CONFIG(whatsthis)
if (!inWhatsThisMode)
@@ -1409,7 +1478,7 @@ void QMenuPrivate::activateAction(QAction *action, QAction::ActionEvent action_e
} else {
for(QWidget *widget = QApplication::activePopupWidget(); widget; ) {
if (QMenu *qmenu = qobject_cast<QMenu*>(widget)) {
- if(qmenu == q)
+ if (qmenu == q)
hideUpToMenuBar();
widget = qmenu->d_func()->causedPopup.widget;
} else {
@@ -1429,12 +1498,13 @@ 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) {
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
int actionIndex = indexOf(action);
QAccessibleEvent focusEvent(q, QAccessible::Focus);
@@ -1459,7 +1529,7 @@ void QMenuPrivate::_q_actionTriggered()
if (!activationRecursionGuard && actionGuard) {
//in case the action has not been activated by the mouse
//we check the parent hierarchy
- QVector< QPointer<QWidget> > list;
+ QList<QPointer<QWidget>> list;
for(QWidget *widget = q->parentWidget(); widget; ) {
if (qobject_cast<QMenu*>(widget)
#if QT_CONFIG(menubar)
@@ -1473,6 +1543,9 @@ void QMenuPrivate::_q_actionTriggered()
}
}
activateCausedStack(list, action, QAction::Trigger, false);
+ // if a widget action fires, we need to hide the menu explicitly
+ if (qobject_cast<QWidgetAction*>(action))
+ hideUpToMenuBar();
}
}
}
@@ -1491,7 +1564,7 @@ void QMenuPrivate::_q_platformMenuAboutToShow()
emit q->aboutToShow();
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
if (platformMenu) {
const auto actions = q->actions();
for (QAction *action : actions) {
@@ -1570,14 +1643,14 @@ void QMenu::initStyleOption(QStyleOptionMenuItem *option, const QAction *action)
QString textAndAccel = action->text();
#ifndef QT_NO_SHORTCUT
if ((action->isShortcutVisibleInContextMenu() || !d->isContextMenu())
- && textAndAccel.indexOf(QLatin1Char('\t')) == -1) {
+ && textAndAccel.indexOf(u'\t') == -1) {
QKeySequence seq = action->shortcut();
if (!seq.isEmpty())
- textAndAccel += QLatin1Char('\t') + seq.toString(QKeySequence::NativeText);
+ textAndAccel += u'\t' + seq.toString(QKeySequence::NativeText);
}
#endif
option->text = textAndAccel;
- option->tabWidth = d->tabWidth;
+ option->reservedShortcutWidth = d->tabWidth;
option->maxIconWidth = d->maxIconWidth;
option->menuRect = rect();
}
@@ -1620,7 +1693,7 @@ void QMenu::initStyleOption(QStyleOptionMenuItem *option, const QAction *action)
and all other items are considered action items.
When inserting action items you usually specify a receiver and a
- slot. The receiver will be notifed whenever the item is
+ slot. The receiver will be notified whenever the item is
\l{QAction::triggered()}{triggered()}. In addition, QMenu provides
two signals, triggered() and hovered(), which signal the
QAction that was triggered from the menu.
@@ -1640,13 +1713,13 @@ void QMenu::initStyleOption(QStyleOptionMenuItem *option, const QAction *action)
Widgets can be inserted into menus with the QWidgetAction class.
Instances of this class are used to hold widgets, and are inserted
- into menus with the addAction() overload that takes a QAction.
-
- Conversely, actions can be added to widgets with the addAction(),
- addActions() and insertAction() functions.
+ into menus with the addAction() overload that takes a QAction. If the
+ QWidgetAction fires the triggered() signal, the menu will close.
\warning To make QMenu visible on the screen, exec() or popup() should be
- used instead of show().
+ used instead of show() or setVisible(). To hide or disable the menu in the
+ menubar, or in another menu to which it was added as a submenu, use the
+ respective properties of menuAction() instead.
\section1 QMenu on \macos with Qt Build Against Cocoa
@@ -1659,8 +1732,7 @@ void QMenu::initStyleOption(QStyleOptionMenuItem *option, const QAction *action)
\b{Important inherited functions:} addAction(), removeAction(), clear(),
addSeparator(), and addMenu().
- \sa QMenuBar, {fowler}{GUI Design Handbook: Menu, Drop-Down and Pop-Up},
- {Application Example}, {Menus Example}
+ \sa QMenuBar, {Menus Example}
*/
@@ -1725,162 +1797,75 @@ QMenu::~QMenu()
hideTearOffMenu();
}
+#if QT_DEPRECATED_SINCE(6, 4)
/*!
- This convenience function creates a new action with \a text.
- The function adds the newly created action to the menu's
- list of actions, and returns it.
+ \fn QAction *QMenu::addAction(const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut)
+ \obsolete
- QMenu takes ownership of the returned QAction.
-
- \sa QWidget::addAction()
+ Use \c{QWidget::addAction(text, shortcut, receiver, member)} instead.
*/
-QAction *QMenu::addAction(const QString &text)
-{
- QAction *ret = new QAction(text, this);
- addAction(ret);
- return ret;
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with an \a icon
- and some \a text. The function adds the newly created action to
- the menu's list of actions, and returns it.
-
- QMenu takes ownership of the returned QAction.
-
- \sa QWidget::addAction()
-*/
-QAction *QMenu::addAction(const QIcon &icon, const QString &text)
-{
- QAction *ret = new QAction(icon, text, this);
- addAction(ret);
- return ret;
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with the text \a
- text and an optional shortcut \a shortcut. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a receiver's \a member slot. The function adds the newly created
- action to the menu's list of actions and returns it.
-
- QMenu takes ownership of the returned QAction.
-
- \sa QWidget::addAction()
-*/
-QAction *QMenu::addAction(const QString &text, const QObject *receiver, const char* member
#if QT_CONFIG(shortcut)
- , const QKeySequence &shortcut
-#endif
- )
+QAction *QMenu::addAction(const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut)
{
- QAction *action = new QAction(text, this);
-#if QT_CONFIG(shortcut)
- action->setShortcut(shortcut);
-#endif
- QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
- addAction(action);
- return action;
+ return QWidget::addAction(text, shortcut, receiver, member);
}
+#endif
-/*!\fn template<typename Functor> QAction *QMenu::addAction(const QString &text, Functor functor, const QKeySequence &shortcut = 0)
+/*!
+ \fn template<typename Functor> QAction *QMenu::addAction(const QString &text, Functor functor, const QKeySequence &shortcut)
\since 5.6
+ \obsolete
- \overload
-
- This convenience function creates a new action with the text \a
- text and an optional shortcut \a shortcut. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a functor. The function adds the newly created
- action to the menu's list of actions and returns it.
-
- QMenu takes ownership of the returned QAction.
+ Use QWidget::addAction(text, shortcut, functor) instead.
*/
-/*!\fn template<typename Functor> QAction *QMenu::addAction(const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut)
+/*!
+ \fn template<typename Functor> QAction *QMenu::addAction(const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut)
\since 5.6
+ \obsolete
- \overload
-
- This convenience function creates a new action with the text \a
- text and an optional shortcut \a shortcut. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a functor. The functor can be a pointer to a member function of
- the \a context object. The newly created action is added to the
- menu's list of actions and a pointer to it is returned.
-
- If the \a context object is destroyed, the functor will not be called.
-
- QMenu takes ownership of the returned QAction.
+ Use QWidget::addAction(text, shortcut, context, functor) instead.
*/
-/*!\fn template<typename Functor> QAction *QMenu::addAction(const QIcon &icon, const QString &text, Functor functor, const QKeySequence &shortcut = 0)
+/*!
+ \fn template<typename Functor> QAction *QMenu::addAction(const QIcon &icon, const QString &text, Functor functor, const QKeySequence &shortcut)
\since 5.6
+ \obsolete
- \overload
-
- This convenience function creates a new action with an \a icon
- and some \a text and an optional shortcut \a shortcut. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a functor. The function adds the newly created
- action to the menu's list of actions and returns it.
-
- QMenu takes ownership of the returned QAction.
+ Use QWidget::addAction(icon, text, shortcut, functor) instead.
*/
-/*!\fn template<typename Functor> QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut)
+/*!
+ \fn template<typename Functor> QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut)
\since 5.6
+ \obsolete
- \overload
-
- This convenience function creates a new action with an \a icon
- and some \a text and an optional shortcut \a shortcut. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a functor. The \a functor can be a pointer to a member function
- of the \a context object. The newly created action is added to the
- menu's list of actions and a pointer to it is returned.
-
- If \a context is destroyed, the functor will not be called.
-
- QMenu takes ownership of the returned QAction.
+ Use QWidget::addAction(icon, text, shortcut, context, functor) instead.
*/
/*!
- \overload
+ \fn QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut)
- This convenience function creates a new action with an \a icon and
- some \a text and an optional shortcut \a shortcut. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a member slot of the \a receiver object. The function adds the
- newly created action to the menu's list of actions, and returns it.
+ \obsolete
- QMenu takes ownership of the returned QAction.
-
- \sa QWidget::addAction()
+ Use QWidget::addAction(icon, text, shortcut, receiver, member) instead.
*/
-QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver,
- const char* member
#if QT_CONFIG(shortcut)
- , const QKeySequence &shortcut
-#endif
- )
+QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver,
+ const char* member, const QKeySequence &shortcut)
{
QAction *action = new QAction(icon, text, this);
-#if QT_CONFIG(shortcut)
action->setShortcut(shortcut);
-#endif
QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
addAction(action);
return action;
}
+#endif
+#endif // QT_DEPRECATED_SINCE(6, 4)
/*!
This convenience function adds \a menu as a submenu to this menu.
@@ -2196,7 +2181,7 @@ void QMenu::setActiveAction(QAction *act)
{
Q_D(QMenu);
d->setCurrentAction(act, 0);
- if (d->scroll)
+ if (d->scroll && act)
d->scrollMenu(act, QMenuPrivate::QMenuScroller::ScrollCenter);
}
@@ -2222,7 +2207,7 @@ QAction *QMenu::activeAction() const
bool QMenu::isEmpty() const
{
bool ret = true;
- for(int i = 0; ret && i < actions().count(); ++i) {
+ for(int i = 0; ret && i < actions().size(); ++i) {
const QAction *action = actions().at(i);
if (!action->isSeparator() && action->isVisible()) {
ret = false;
@@ -2243,7 +2228,7 @@ void QMenu::clear()
for(int i = 0; i < acts.size(); i++) {
removeAction(acts[i]);
- if (acts[i]->parent() == this && acts[i]->d_func()->widgets.isEmpty())
+ if (acts[i]->parent() == this && acts[i]->d_func()->associatedObjects.isEmpty())
delete acts[i];
}
}
@@ -2287,7 +2272,7 @@ QSize QMenu::sizeHint() const
d->updateActionRects();
QSize s;
- for (int i = 0; i < d->actionRects.count(); ++i) {
+ for (int i = 0; i < d->actionRects.size(); ++i) {
const QRect &rect = d->actionRects.at(i);
if (rect.isNull())
continue;
@@ -2300,13 +2285,12 @@ QSize QMenu::sizeHint() const
// the top and left margins, so we only need to add margins for
// the bottom and right.
QStyleOption opt(0);
- opt.init(this);
+ opt.initFrom(this);
const int fw = style()->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, this);
s.rwidth() += style()->pixelMetric(QStyle::PM_MenuHMargin, &opt, this) + fw + d->rightmargin;
s.rheight() += style()->pixelMetric(QStyle::PM_MenuVMargin, &opt, this) + fw + d->bottommargin;
- return style()->sizeFromContents(QStyle::CT_Menu, &opt,
- s.expandedTo(QApplication::globalStrut()), this);
+ return style()->sizeFromContents(QStyle::CT_Menu, &opt, s, this);
}
/*!
@@ -2326,76 +2310,105 @@ QSize QMenu::sizeHint() const
void QMenu::popup(const QPoint &p, QAction *atAction)
{
Q_D(QMenu);
- if (d->scroll) { // reset scroll state from last popup
- if (d->scroll->scrollOffset)
- d->itemsDirty = 1; // sizeHint will be incorrect if there is previous scroll
- d->scroll->scrollOffset = 0;
- d->scroll->scrollFlags = QMenuPrivate::QMenuScroller::ScrollNone;
+ d->popup(p, 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
+ scroll->scrollOffset = 0;
+ scroll->scrollFlags = QMenuPrivate::QMenuScroller::ScrollNone;
}
- d->tearoffHighlighted = 0;
- d->motions = 0;
- d->doChildEffects = true;
- d->updateLayoutDirection();
+ tearoffHighlighted = 0;
+ motions = 0;
+ doChildEffects = true;
+ updateLayoutDirection();
+
+ q->ensurePolished(); // Get the right font
// Ensure that we get correct sizeHints by placing this window on the correct screen.
- // However if the QMenu was constructed with a QDesktopScreenWidget as its parent,
+ // However if the QMenu was constructed with a Qt::Desktop widget as its parent,
// then initialScreenIndex was set, so we should respect that for the lifetime of this menu.
- // Use d->popupScreen to remember, because initialScreenIndex will be reset after the first showing.
// However if eventLoop exists, then exec() already did this by calling createWinId(); so leave it alone. (QTBUG-76162)
- if (!d->eventLoop) {
- const int screenIndex = d->topData()->initialScreenIndex;
- if (screenIndex >= 0)
- d->popupScreen = screenIndex;
- if (auto s = QGuiApplication::screens().value(d->popupScreen)) {
- if (d->setScreen(s))
- d->itemsDirty = true;
- } else if (d->setScreenForPoint(p)) {
- d->itemsDirty = true;
- }
+ if (!eventLoop) {
+ bool screenSet = false;
+ QScreen *screen = topData()->initialScreen;
+ if (screen) {
+ if (setScreen(screen))
+ itemsDirty = true;
+ screenSet = true;
+ } else if (QMenu *parentMenu = qobject_cast<QMenu *>(parent)) {
+ // a submenu is always opened from an open parent menu,
+ // so show it on the same screen where the parent is. (QTBUG-76162)
+ if (setScreen(parentMenu->screen()))
+ itemsDirty = true;
+ screenSet = true;
+ }
+ if (!screenSet && setScreenForPoint(p))
+ itemsDirty = true;
+ }
+
+ const bool contextMenu = isContextMenu();
+ if (lastContextMenu != contextMenu) {
+ itemsDirty = true;
+ lastContextMenu = contextMenu;
}
- const bool contextMenu = d->isContextMenu();
- if (d->lastContextMenu != contextMenu) {
- d->itemsDirty = true;
- d->lastContextMenu = contextMenu;
+ // Until QWidget::metric accepts the screen set on a widget (without having a window handle)
+ // we need to make sure we get a window handle. This must be done near here because
+ // we want the screen to be correctly set and items to be marked dirty.
+ // (and screen set could 'fail' on oldscreen == newScreen if created before causing the
+ // itemsDirty not to be set though needed to get the correct size on first show).
+ if (!windowHandle()) {
+ createWinId();
}
#if QT_CONFIG(menubar)
// if this menu is part of a chain attached to a QMenuBar, set the
// _NET_WM_WINDOW_TYPE_DROPDOWN_MENU X11 window type
- setAttribute(Qt::WA_X11NetWmWindowTypeDropDownMenu, qobject_cast<QMenuBar *>(d->topCausedWidget()) != 0);
+ q->setAttribute(Qt::WA_X11NetWmWindowTypeDropDownMenu, qobject_cast<QMenuBar *>(topCausedWidget()) != nullptr);
#endif
- ensurePolished(); // Get the right font
- emit aboutToShow();
- const bool actionListChanged = d->itemsDirty;
+ emit q->aboutToShow();
+ const bool actionListChanged = itemsDirty;
QRect screen;
#if QT_CONFIG(graphicsview)
- bool isEmbedded = !bypassGraphicsProxyWidget(this) && QMenuPrivate::nearestGraphicsProxyWidget(this);
+ bool isEmbedded = !bypassGraphicsProxyWidget(q) && QMenuPrivate::nearestGraphicsProxyWidget(q);
if (isEmbedded)
- screen = d->popupGeometry();
+ screen = popupGeometry();
else
#endif
- screen = d->popupGeometry(QDesktopWidgetPrivate::screenNumber(p));
- d->updateActionRects(screen);
+ screen = popupGeometry(QGuiApplication::screenAt(p));
+ updateActionRects(screen);
QPoint pos;
- QPushButton *causedButton = qobject_cast<QPushButton*>(d->causedPopup.widget);
+ QPushButton *causedButton = qobject_cast<QPushButton*>(causedPopup.widget);
if (actionListChanged && causedButton)
pos = QPushButtonPrivate::get(causedButton)->adjustedMenuPosition();
else
pos = p;
+ popupScreen = QGuiApplication::screenAt(pos);
- const QSize menuSizeHint(sizeHint());
+ const QSize menuSizeHint(q->sizeHint());
QSize size = menuSizeHint;
- const int desktopFrame = style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, nullptr, this);
- bool adjustToDesktop = !window()->testAttribute(Qt::WA_DontShowOnScreen);
+
+ if (positionFunction)
+ pos = positionFunction(menuSizeHint);
+
+ const int desktopFrame = q->style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, nullptr, q);
+ bool adjustToDesktop = !q->window()->testAttribute(Qt::WA_DontShowOnScreen);
// if the screens have very different geometries and the menu is too big, we have to recalculate
if ((size.height() > screen.height() || size.width() > screen.width()) ||
// Layout is not right, we might be able to save horizontal space
- (d->ncols >1 && size.height() < screen.height())) {
+ (ncols >1 && size.height() < screen.height())) {
size.setWidth(qMin(menuSizeHint.width(), screen.width() - desktopFrame * 2));
size.setHeight(qMin(menuSizeHint.height(), screen.height() - desktopFrame * 2));
adjustToDesktop = true;
@@ -2404,61 +2417,61 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
#ifdef QT_KEYPAD_NAVIGATION
if (!atAction && QApplicationPrivate::keypadNavigationEnabled()) {
// Try to have one item activated
- if (d->defaultAction && d->defaultAction->isEnabled()) {
- atAction = d->defaultAction;
+ if (defaultAction && defaultAction->isEnabled()) {
+ atAction = defaultAction;
// TODO: This works for first level menus, not yet sub menus
} else {
- for (QAction *action : qAsConst(d->actions))
+ for (QAction *action : std::as_const(actions))
if (action->isEnabled()) {
atAction = action;
break;
}
}
- d->currentAction = atAction;
+ currentAction = atAction;
}
#endif
- if (d->ncols > 1) {
+ if (ncols > 1) {
pos.setY(screen.top() + desktopFrame);
} else if (atAction) {
- for (int i = 0, above_height = 0; i < d->actions.count(); i++) {
- QAction *action = d->actions.at(i);
+ for (int i = 0, above_height = 0; i < actions.size(); i++) {
+ QAction *action = actions.at(i);
if (action == atAction) {
int newY = pos.y() - above_height;
- if (d->scroll && newY < desktopFrame) {
- d->scroll->scrollFlags = d->scroll->scrollFlags
+ if (scroll && newY < desktopFrame) {
+ scroll->scrollFlags = scroll->scrollFlags
| QMenuPrivate::QMenuScroller::ScrollUp;
- d->scroll->scrollOffset = newY;
+ scroll->scrollOffset = newY;
newY = desktopFrame;
}
pos.setY(newY);
- if (d->scroll && d->scroll->scrollFlags != QMenuPrivate::QMenuScroller::ScrollNone
- && !style()->styleHint(QStyle::SH_Menu_FillScreenWithScroll, nullptr, this)) {
- int below_height = above_height + d->scroll->scrollOffset;
- for (int i2 = i; i2 < d->actionRects.count(); i2++)
- below_height += d->actionRects.at(i2).height();
+ if (scroll && scroll->scrollFlags != QMenuPrivate::QMenuScroller::ScrollNone
+ && !q->style()->styleHint(QStyle::SH_Menu_FillScreenWithScroll, nullptr, q)) {
+ int below_height = above_height + scroll->scrollOffset;
+ for (int i2 = i; i2 < actionRects.size(); i2++)
+ below_height += actionRects.at(i2).height();
size.setHeight(below_height);
}
break;
} else {
- above_height += d->actionRects.at(i).height();
+ above_height += actionRects.at(i).height();
}
}
}
QPoint mouse = QCursor::pos();
- d->mousePopupPos = mouse;
- const bool snapToMouse = !d->causedPopup.widget && (QRect(p.x() - 3, p.y() - 3, 6, 6).contains(mouse));
+ mousePopupPos = mouse;
+ const bool snapToMouse = !causedPopup.widget && (QRect(p.x() - 3, p.y() - 3, 6, 6).contains(mouse));
if (adjustToDesktop) {
// handle popup falling "off screen"
- if (isRightToLeft()) {
+ if (q->isRightToLeft()) {
if (snapToMouse) // position flowing left from the mouse
pos.setX(mouse.x() - size.width());
#if QT_CONFIG(menubar)
// if the menu is in a menubar or is a submenu, it should be right-aligned
- if (qobject_cast<QMenuBar*>(d->causedPopup.widget) || qobject_cast<QMenu*>(d->causedPopup.widget))
+ if (qobject_cast<QMenuBar*>(causedPopup.widget) || qobject_cast<QMenu*>(causedPopup.widget))
pos.rx() -= size.width();
#endif // QT_CONFIG(menubar)
@@ -2473,7 +2486,7 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
pos.setX(screen.left() + desktopFrame);
}
if (pos.y() + size.height() - 1 > screen.bottom() - desktopFrame) {
- if(snapToMouse)
+ if (snapToMouse)
pos.setY(qMin(mouse.y() - (size.height() + desktopFrame), screen.bottom()-desktopFrame-size.height()+1));
else
pos.setY(qMax(p.y() - (size.height() + desktopFrame), screen.bottom()-desktopFrame-size.height()+1));
@@ -2482,8 +2495,8 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
if (pos.y() < screen.top() + desktopFrame)
pos.setY(screen.top() + desktopFrame);
if (pos.y() + menuSizeHint.height() - 1 > screen.bottom() - desktopFrame) {
- if (d->scroll) {
- d->scroll->scrollFlags |= uint(QMenuPrivate::QMenuScroller::ScrollDown);
+ if (scroll) {
+ scroll->scrollFlags |= uint(QMenuPrivate::QMenuScroller::ScrollDown);
int y = qMax(screen.y(),pos.y());
size.setHeight(screen.bottom() - (desktopFrame * 2) - y);
} else {
@@ -2492,13 +2505,13 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
}
}
}
- const int subMenuOffset = style()->pixelMetric(QStyle::PM_SubMenuOverlap, nullptr, this);
- QMenu *caused = qobject_cast<QMenu*>(d_func()->causedPopup.widget);
+ const int subMenuOffset = q->style()->pixelMetric(QStyle::PM_SubMenuOverlap, nullptr, q);
+ QMenu *caused = qobject_cast<QMenu*>(causedPopup.widget);
if (caused && caused->geometry().width() + menuSizeHint.width() + subMenuOffset < screen.width()) {
QRect parentActionRect(caused->d_func()->actionRect(caused->d_func()->currentAction));
const QPoint actionTopLeft = caused->mapToGlobal(parentActionRect.topLeft());
parentActionRect.moveTopLeft(actionTopLeft);
- if (isRightToLeft()) {
+ if (q->isRightToLeft()) {
if ((pos.x() + menuSizeHint.width() > parentActionRect.left() - subMenuOffset)
&& (pos.x() < parentActionRect.right()))
{
@@ -2520,61 +2533,62 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
}
}
}
- setGeometry(QRect(pos, size));
+ popupScreen = QGuiApplication::screenAt(pos);
+ q->setGeometry(QRect(pos, size));
#if QT_CONFIG(effects)
- int hGuess = isRightToLeft() ? QEffects::LeftScroll : QEffects::RightScroll;
+ int hGuess = q->isRightToLeft() ? QEffects::LeftScroll : QEffects::RightScroll;
int vGuess = QEffects::DownScroll;
- if (isRightToLeft()) {
+ if (q->isRightToLeft()) {
if ((snapToMouse && (pos.x() + size.width() / 2 > mouse.x())) ||
- (qobject_cast<QMenu*>(d->causedPopup.widget) && pos.x() + size.width() / 2 > d->causedPopup.widget->x()))
+ (qobject_cast<QMenu*>(causedPopup.widget) && pos.x() + size.width() / 2 > causedPopup.widget->x()))
hGuess = QEffects::RightScroll;
} else {
if ((snapToMouse && (pos.x() + size.width() / 2 < mouse.x())) ||
- (qobject_cast<QMenu*>(d->causedPopup.widget) && pos.x() + size.width() / 2 < d->causedPopup.widget->x()))
+ (qobject_cast<QMenu*>(causedPopup.widget) && pos.x() + size.width() / 2 < causedPopup.widget->x()))
hGuess = QEffects::LeftScroll;
}
#if QT_CONFIG(menubar)
if ((snapToMouse && (pos.y() + size.height() / 2 < mouse.y())) ||
- (qobject_cast<QMenuBar*>(d->causedPopup.widget) &&
- pos.y() + size.width() / 2 < d->causedPopup.widget->mapToGlobal(d->causedPopup.widget->pos()).y()))
+ (qobject_cast<QMenuBar*>(causedPopup.widget) &&
+ pos.y() + size.width() / 2 < causedPopup.widget->mapToGlobal(causedPopup.widget->pos()).y()))
vGuess = QEffects::UpScroll;
#endif
if (QApplication::isEffectEnabled(Qt::UI_AnimateMenu)) {
bool doChildEffects = true;
#if QT_CONFIG(menubar)
- if (QMenuBar *mb = qobject_cast<QMenuBar*>(d->causedPopup.widget)) {
+ if (QMenuBar *mb = qobject_cast<QMenuBar*>(causedPopup.widget)) {
doChildEffects = mb->d_func()->doChildEffects;
mb->d_func()->doChildEffects = false;
} else
#endif
- if (QMenu *m = qobject_cast<QMenu*>(d->causedPopup.widget)) {
+ if (QMenu *m = qobject_cast<QMenu*>(causedPopup.widget)) {
doChildEffects = m->d_func()->doChildEffects;
m->d_func()->doChildEffects = false;
}
if (doChildEffects) {
if (QApplication::isEffectEnabled(Qt::UI_FadeMenu))
- qFadeEffect(this);
- else if (d->causedPopup.widget)
- qScrollEffect(this, qobject_cast<QMenu*>(d->causedPopup.widget) ? hGuess : vGuess);
+ qFadeEffect(q);
+ else if (causedPopup.widget)
+ qScrollEffect(q, qobject_cast<QMenu*>(causedPopup.widget) ? hGuess : vGuess);
else
- qScrollEffect(this, hGuess | vGuess);
+ qScrollEffect(q, hGuess | vGuess);
} else {
// kill any running effect
qFadeEffect(nullptr);
qScrollEffect(nullptr);
- show();
+ q->show();
}
} else
#endif
{
- show();
+ q->show();
}
-#ifndef QT_NO_ACCESSIBILITY
- QAccessibleEvent event(this, QAccessible::PopupMenuStart);
+#if QT_CONFIG(accessibility)
+ QAccessibleEvent event(q, QAccessible::PopupMenuStart);
QAccessible::updateAccessibility(&event);
#endif
}
@@ -2640,20 +2654,27 @@ QAction *QMenu::exec()
QAction *QMenu::exec(const QPoint &p, QAction *action)
{
Q_D(QMenu);
- ensurePolished();
- createWinId();
- QEventLoop eventLoop;
- d->eventLoop = &eventLoop;
- popup(p, action);
-
- QPointer<QObject> guard = this;
- (void) eventLoop.exec();
+ return d->exec(p, action);
+}
+
+QAction *QMenuPrivate::exec(const QPoint &p, QAction *action, PositionFunction positionFunction)
+{
+ Q_Q(QMenu);
+ q->ensurePolished();
+ q->createWinId();
+ QEventLoop evtLoop;
+ eventLoop = &evtLoop;
+ popup(p, action, positionFunction);
+
+ QPointer<QObject> guard = q;
+ (void) evtLoop.exec();
if (guard.isNull())
return nullptr;
- action = d->syncAction;
- d->syncAction = nullptr;
- d->eventLoop = nullptr;
+ action = syncAction;
+ syncAction = nullptr;
+ eventLoop = nullptr;
+ popupScreen.clear();
return action;
}
@@ -2679,11 +2700,7 @@ QAction *QMenu::exec(const QPoint &p, QAction *action)
\sa popup(), QWidget::mapToGlobal()
*/
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
QAction *QMenu::exec(const QList<QAction *> &actions, const QPoint &pos, QAction *at, QWidget *parent)
-#else
-QAction *QMenu::exec(QList<QAction*> actions, const QPoint &pos, QAction *at, QWidget *parent)
-#endif
{
QMenu menu(parent);
menu.addActions(actions);
@@ -2700,7 +2717,7 @@ void QMenu::hideEvent(QHideEvent *)
if (d->eventLoop)
d->eventLoop->exit();
d->setCurrentAction(nullptr);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleEvent event(this, QAccessible::PopupMenuEnd);
QAccessible::updateAccessibility(&event);
#endif
@@ -2726,7 +2743,7 @@ void QMenu::paintEvent(QPaintEvent *e)
{
Q_D(QMenu);
d->updateActionRects();
- QPainter p(this);
+ QStylePainter p(this);
QRegion emptyArea = QRegion(rect());
QStyleOptionMenuItem menuOpt;
@@ -2734,8 +2751,8 @@ void QMenu::paintEvent(QPaintEvent *e)
menuOpt.state = QStyle::State_None;
menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
menuOpt.maxIconWidth = 0;
- menuOpt.tabWidth = 0;
- style()->drawPrimitive(QStyle::PE_PanelMenu, &menuOpt, &p, this);
+ menuOpt.reservedShortcutWidth = 0;
+ p.drawPrimitive(QStyle::PE_PanelMenu, menuOpt);
//calculate the scroll up / down rect
const int fw = style()->pixelMetric(QStyle::PM_MenuPanelWidth, nullptr, this);
@@ -2767,7 +2784,7 @@ void QMenu::paintEvent(QPaintEvent *e)
//draw the items that need updating..
QRect scrollUpTearOffRect = scrollUpRect.united(tearOffRect);
- for (int i = 0; i < d->actions.count(); ++i) {
+ for (int i = 0; i < d->actions.size(); ++i) {
QAction *action = d->actions.at(i);
QRect actionRect = d->actionRects.at(i);
if (!e->rect().intersects(actionRect)
@@ -2803,7 +2820,7 @@ void QMenu::paintEvent(QPaintEvent *e)
QStyleOptionMenuItem opt;
initStyleOption(&opt, action);
opt.rect = actionRect;
- style()->drawControl(QStyle::CE_MenuItem, &opt, &p, this);
+ p.drawControl(QStyle::CE_MenuItem, opt);
}
emptyArea -= QRegion(scrollUpTearOffRect);
@@ -2835,9 +2852,9 @@ void QMenu::paintEvent(QPaintEvent *e)
frame.rect = rect();
frame.palette = palette();
frame.state = QStyle::State_None;
- frame.lineWidth = style()->pixelMetric(QStyle::PM_MenuPanelWidth);
+ frame.lineWidth = style()->pixelMetric(QStyle::PM_MenuPanelWidth, &frame, this);
frame.midLineWidth = 0;
- style()->drawPrimitive(QStyle::PE_FrameMenu, &frame, &p, this);
+ p.drawPrimitive(QStyle::PE_FrameMenu, frame);
}
//finally the rest of the spaces
@@ -2847,7 +2864,7 @@ void QMenu::paintEvent(QPaintEvent *e)
menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
menuOpt.rect = rect();
menuOpt.menuRect = rect();
- style()->drawControl(QStyle::CE_MenuEmptyArea, &menuOpt, &p, this);
+ p.drawControl(QStyle::CE_MenuEmptyArea, menuOpt);
}
#if QT_CONFIG(wheelevent)
@@ -2875,9 +2892,9 @@ void QMenu::mousePressEvent(QMouseEvent *e)
// and mouse clicks on second screen, e->pos() is QPoint(0,0) and the menu doesn't hide. This trick makes
// possible to hide the menu when mouse clicks on another screen (e->screenPos() returns correct value).
// Only when mouse clicks in QPoint(0,0) on second screen, the menu doesn't hide.
- if ((e->pos().isNull() && !e->screenPos().isNull()) || !rect().contains(e->pos())) {
+ if ((e->position().toPoint().isNull() && !e->globalPosition().isNull()) || !rect().contains(e->position().toPoint())) {
if (d->noReplayFor
- && QRect(d->noReplayFor->mapToGlobal(QPoint()), d->noReplayFor->size()).contains(e->globalPos()))
+ && QRect(d->noReplayFor->mapToGlobal(QPoint()), d->noReplayFor->size()).contains(e->globalPosition().toPoint()))
setAttribute(Qt::WA_NoMouseReplay);
if (d->eventLoop) // synchronous operation
d->syncAction = nullptr;
@@ -2886,7 +2903,7 @@ void QMenu::mousePressEvent(QMouseEvent *e)
}
QMenuPrivate::mouseDown = this;
- QAction *action = d->actionAt(e->pos());
+ QAction *action = d->actionAt(e->position().toPoint());
d->setCurrentAction(action, 20);
update();
}
@@ -2906,17 +2923,17 @@ void QMenu::mouseReleaseEvent(QMouseEvent *e)
QMenuPrivate::mouseDown = nullptr;
d->setSyncAction();
- QAction *action = d->actionAt(e->pos());
+ QAction *action = d->actionAt(e->position().toPoint());
if (action && action == d->currentAction) {
- if (!action->menu()){
+ if (!action->menu()) {
#if defined(Q_OS_WIN)
//On Windows only context menus can be activated with the right button
if (e->button() == Qt::LeftButton || d->topCausedWidget() == 0)
#endif
d->activateAction(action, QAction::Trigger);
}
- } else if ((!action || action->isEnabled()) && d->hasMouseMoved(e->globalPos())) {
+ } else if ((!action || action->isEnabled()) && d->hasMouseMoved(e->globalPosition().toPoint())) {
d->hideUpToMenuBar();
}
}
@@ -2954,8 +2971,7 @@ void QMenu::changeEvent(QEvent *e)
/*!
\reimp
*/
-bool
-QMenu::event(QEvent *e)
+bool QMenu::event(QEvent *e)
{
Q_D(QMenu);
switch (e->type()) {
@@ -2963,7 +2979,7 @@ 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
@@ -2977,7 +2993,7 @@ 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;
@@ -3010,8 +3026,10 @@ QMenu::event(QEvent *e)
d->sloppyState.reset();
if (d->currentAction)
d->popupAction(d->currentAction, 0, false);
+ if (isWindow() && window() && window()->windowHandle() && !window()->windowHandle()->transientParent())
+ window()->windowHandle()->setTransientParent(d->transientParentWindow());
break;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::ToolTip:
if (d->toolTipsVisible) {
const QHelpEvent *ev = static_cast<const QHelpEvent*>(e);
@@ -3019,11 +3037,13 @@ QMenu::event(QEvent *e)
const QString toolTip = action->d_func()->tooltip;
if (!toolTip.isEmpty())
QToolTip::showText(ev->globalPos(), toolTip, this);
+ else
+ QToolTip::hideText();
return true;
}
}
break;
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
#if QT_CONFIG(whatsthis)
case QEvent::QueryWhatsThis:
e->setAccepted(d->whatsThis.size());
@@ -3086,7 +3106,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
case Qt::Key_PageUp:
key_consumed = true;
if (d->currentAction && d->scroll) {
- if(d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
+ if (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollUp, true, true);
else
d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollTop, true);
@@ -3095,7 +3115,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
case Qt::Key_PageDown:
key_consumed = true;
if (d->currentAction && d->scroll) {
- if(d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown)
+ if (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown)
d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollDown, true, true);
else
d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollBottom, true);
@@ -3107,8 +3127,8 @@ void QMenu::keyPressEvent(QKeyEvent *e)
QAction *nextAction = nullptr;
QMenuPrivate::QMenuScroller::ScrollLocation scroll_loc = QMenuPrivate::QMenuScroller::ScrollStay;
if (!d->currentAction) {
- if(key == Qt::Key_Down) {
- for(int i = 0; i < d->actions.count(); ++i) {
+ if (key == Qt::Key_Down) {
+ for(int i = 0; i < d->actions.size(); ++i) {
QAction *act = d->actions.at(i);
if (d->actionRects.at(i).isNull())
continue;
@@ -3120,7 +3140,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
}
}
} else {
- for(int i = d->actions.count()-1; i >= 0; --i) {
+ for(int i = d->actions.size()-1; i >= 0; --i) {
QAction *act = d->actions.at(i);
if (d->actionRects.at(i).isNull())
continue;
@@ -3133,7 +3153,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
}
}
} else {
- for(int i = 0, y = 0; !nextAction && i < d->actions.count(); i++) {
+ for(int i = 0, y = 0; !nextAction && i < d->actions.size(); i++) {
QAction *act = d->actions.at(i);
if (act == d->currentAction) {
if (key == Qt::Key_Up) {
@@ -3143,7 +3163,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
break;
if (d->scroll)
scroll_loc = QMenuPrivate::QMenuScroller::ScrollBottom;
- next_i = d->actionRects.count()-1;
+ next_i = d->actionRects.size()-1;
}
QAction *next = d->actions.at(next_i);
if (next == d->currentAction)
@@ -3169,7 +3189,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
} else {
y += d->actionRects.at(i).height();
for(int next_i = i+1; true; next_i++) {
- if (next_i == d->actionRects.count()) {
+ if (next_i == d->actionRects.size()) {
if (!style()->styleHint(QStyle::SH_Menu_SelectionWrap, nullptr, this))
break;
if (d->scroll)
@@ -3326,7 +3346,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
if (!key_consumed) { // send to menu bar
if ((!e->modifiers() || e->modifiers() == Qt::AltModifier || e->modifiers() == Qt::ShiftModifier) &&
- e->text().length()==1) {
+ e->text().size()==1) {
bool activateAction = false;
QAction *nextAction = nullptr;
if (style()->styleHint(QStyle::SH_Menu_KeyboardSearch, nullptr, this) && !e->modifiers()) {
@@ -3340,10 +3360,10 @@ void QMenu::keyPressEvent(QKeyEvent *e)
QAction *act = d->actions.at(i);
const QString act_text = act->text();
for(int c = 0; c < d->searchBuffer.size(); ++c) {
- if(act_text.indexOf(d->searchBuffer.at(c), 0, Qt::CaseInsensitive) != -1)
+ if (act_text.indexOf(d->searchBuffer.at(c), 0, Qt::CaseInsensitive) != -1)
++match_count;
}
- if(match_count > best_match_count) {
+ if (match_count > best_match_count) {
best_match_count = match_count;
nextAction = act;
}
@@ -3359,7 +3379,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
continue;
QAction *act = d->actions.at(i);
QKeySequence sequence = QKeySequence::mnemonic(act->text());
- int key = sequence[0] & 0xffff;
+ int key = sequence[0].toCombined() & 0xffff; // suspicious
if (key == c.unicode()) {
clashCount++;
if (!first)
@@ -3382,7 +3402,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
#endif
if (nextAction) {
key_consumed = true;
- if(d->scroll)
+ if (d->scroll)
d->scrollMenu(nextAction, QMenuPrivate::QMenuScroller::ScrollCenter, false);
d->setCurrentAction(nextAction, 0, QMenuPrivate::SelectedFromElsewhere, true);
if (!nextAction->menu() && activateAction) {
@@ -3423,12 +3443,12 @@ void QMenu::mouseMoveEvent(QMouseEvent *e)
return;
d->motions++;
- if (d->motions == 0)
+ if (!d->hasMouseMoved(e->globalPosition().toPoint()))
return;
- d->hasHadMouse = d->hasHadMouse || rect().contains(e->pos());
+ d->hasHadMouse = d->hasHadMouse || rect().contains(e->position().toPoint());
- QAction *action = d->actionAt(e->pos());
+ QAction *action = d->actionAt(e->position().toPoint());
if ((!action || action->isSeparator()) && !d->sloppyState.enabled()) {
if (d->hasHadMouse
|| (!d->currentAction || !d->currentAction->menu() || !d->currentAction->menu()->isVisible())) {
@@ -3443,7 +3463,7 @@ void QMenu::mouseMoveEvent(QMouseEvent *e)
if (d->activeMenu)
d->activeMenu->d_func()->setCurrentAction(nullptr);
- QMenuSloppyState::MouseEventResult sloppyEventResult = d->sloppyState.processMouseEvent(e->localPos(), action, d->currentAction);
+ QMenuSloppyState::MouseEventResult sloppyEventResult = d->sloppyState.processMouseEvent(e->position(), action, d->currentAction);
if (sloppyEventResult == QMenuSloppyState::EventShouldBePropagated) {
d->setCurrentAction(action, d->mousePopupDelay);
} else if (sloppyEventResult == QMenuSloppyState::EventDiscardsSloppyState) {
@@ -3455,7 +3475,7 @@ void QMenu::mouseMoveEvent(QMouseEvent *e)
/*!
\reimp
*/
-void QMenu::enterEvent(QEvent *)
+void QMenu::enterEvent(QEnterEvent *)
{
Q_D(QMenu);
d->hasReceievedEnter = true;
@@ -3493,7 +3513,7 @@ QMenu::timerEvent(QTimerEvent *e)
internalDelayedPopup();
} else if (d->sloppyState.isTimerId(e->timerId())) {
d->sloppyState.timeout();
- } else if(d->searchBufferTimer.timerId() == e->timerId()) {
+ } else if (d->searchBufferTimer.timerId() == e->timerId()) {
d->searchBuffer.clear();
}
}
@@ -3511,7 +3531,10 @@ void QMenu::actionEvent(QActionEvent *e)
if (e->type() == QEvent::ActionAdded) {
if (!d->tornoff
- && !qobject_cast<QMenuBar*>(e->action()->parent())) {
+#if QT_CONFIG(menubar)
+ && !qobject_cast<QMenuBar*>(e->action()->parent())
+#endif
+ ) {
// Only connect if the action was not directly added by QMenuBar::addAction(const QString &text)
// to avoid the signal being emitted twice
connect(e->action(), SIGNAL(triggered()), this, SLOT(_q_actionTriggered()), Qt::UniqueConnection);
@@ -3536,19 +3559,8 @@ void QMenu::actionEvent(QActionEvent *e)
if (e->action() == d->currentAction)
d->currentAction = nullptr;
if (QWidgetAction *wa = qobject_cast<QWidgetAction *>(e->action())) {
- if (QWidget *widget = d->widgetItems.value(wa)) {
-#ifdef Q_OS_OSX
- QWidget *p = widget->parentWidget();
- if (p != this && qobject_cast<QMacNativeWidget *>(p)) {
- // This widget was reparented into a native Mac view
- // (see QMenuPrivate::moveWidgetToPlatformItem).
- // Reset the parent and delete the native widget.
- widget->setParent(this);
- p->deleteLater();
- }
-#endif
+ if (QWidget *widget = d->widgetItems.value(wa))
wa->releaseWidget(widget);
- }
}
d->widgetItems.remove(static_cast<QAction *>(e->action()));
}
@@ -3609,13 +3621,13 @@ void QMenu::internalDelayedPopup()
screen = d->popupGeometry();
else
#endif
- screen = d->popupGeometry(QDesktopWidgetPrivate::screenNumber(pos()));
+ screen = d->popupGeometry(QGuiApplication::screenAt(pos()));
int subMenuOffset = style()->pixelMetric(QStyle::PM_SubMenuOverlap, nullptr, this);
const QRect actionRect(d->actionRect(d->currentAction));
QPoint subMenuPos(mapToGlobal(QPoint(actionRect.right() + subMenuOffset + 1, actionRect.top())));
if (subMenuPos.x() > screen.right())
- subMenuPos.setX(QCursor::pos().x());
+ subMenuPos.setX(geometry().left());
const auto &subMenuActions = d->activeMenu->actions();
if (!subMenuActions.isEmpty()) {
diff --git a/src/widgets/widgets/qmenu.h b/src/widgets/widgets/qmenu.h
index 35d5a865ff..33ebd79d1f 100644
--- a/src/widgets/widgets/qmenu.h
+++ b/src/widgets/widgets/qmenu.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMENU_H
#define QMENU_H
@@ -44,9 +8,9 @@
#include <QtWidgets/qwidget.h>
#include <QtCore/qstring.h>
#include <QtGui/qicon.h>
-#include <QtWidgets/qaction.h>
+#include <QtGui/qaction.h>
-#if defined(Q_OS_MACOS) || defined(Q_CLANG_QDOC)
+#if defined(Q_OS_MACOS) || defined(Q_QDOC)
Q_FORWARD_DECLARE_OBJC_CLASS(NSMenu);
#endif
@@ -76,96 +40,75 @@ public:
~QMenu();
using QWidget::addAction;
+#if QT_WIDGETS_REMOVED_SINCE(6, 3)
QAction *addAction(const QString &text);
QAction *addAction(const QIcon &icon, const QString &text);
-
- QAction *addAction(const QString &text, const QObject *receiver, const char* member
-#if QT_CONFIG(shortcut)
- , const QKeySequence &shortcut = {}
+#if !QT_CONFIG(shortcut)
+ QAction *addAction(const QString &text, const QObject *receiver, const char* member);
+ QAction *addAction(const QIcon &icon, const QString &text,
+ const QObject *receiver, const char* member);
#endif
- );
- QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char* member
-#if QT_CONFIG(shortcut)
- , const QKeySequence &shortcut = {}
#endif
- );
-#ifdef Q_CLANG_QDOC
+#if QT_CONFIG(shortcut)
+#if QT_DEPRECATED_SINCE(6, 4)
+ QT_DEPRECATED_VERSION_X_6_4("Use addAction(text, shortcut, receiver, member) instead.")
+ QAction *addAction(const QString &text, const QObject *receiver, const char* member,
+ const QKeySequence &shortcut);
+ QT_DEPRECATED_VERSION_X_6_4("Use addAction(icon, text, shortcut, receiver, member) instead.")
+ QAction *addAction(const QIcon &icon, const QString &text,
+ const QObject *receiver, const char* member,
+ const QKeySequence &shortcut);
+
+#ifdef Q_QDOC
template<typename Functor>
- QAction *addAction(const QString &text, Functor functor, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QString &text, Functor functor, const QKeySequence &shortcut);
template<typename Functor>
- QAction *addAction(const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut);
template<typename Functor>
- QAction *addAction(const QIcon &icon, const QString &text, Functor functor, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QIcon &icon, const QString &text, Functor functor, const QKeySequence &shortcut);
template<typename Functor>
- QAction *addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut = 0);
+ QAction *addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut);
#else
// addAction(QString): Connect to a QObject slot / functor or function pointer (with context)
template<class Obj, typename Func1>
+ QT_DEPRECATED_VERSION_X_6_4("Use addAction(text, shortcut, object, slot) instead.")
inline typename std::enable_if<!std::is_same<const char*, Func1>::value
&& QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::type
- addAction(const QString &text, const Obj *object, Func1 slot
-#if QT_CONFIG(shortcut)
- , const QKeySequence &shortcut = {}
-#endif
- )
+ addAction(const QString &text, const Obj *object, Func1 slot,
+ const QKeySequence &shortcut)
{
- QAction *result = addAction(text);
-#if QT_CONFIG(shortcut)
- result->setShortcut(shortcut);
-#endif
- connect(result, &QAction::triggered, object, std::move(slot));
- return result;
+ return addAction(text, shortcut, object, slot);
}
// addAction(QString): Connect to a functor or function pointer (without context)
template <typename Func1>
- inline QAction *addAction(const QString &text, Func1 slot
-#if QT_CONFIG(shortcut)
- , const QKeySequence &shortcut = {}
-#endif
- )
+ QT_DEPRECATED_VERSION_X_6_4("Use addAction(text, shortcut, slot) instead.")
+ inline QAction *addAction(const QString &text, Func1 slot, const QKeySequence &shortcut)
{
- QAction *result = addAction(text);
-#if QT_CONFIG(shortcut)
- result->setShortcut(shortcut);
-#endif
- connect(result, &QAction::triggered, std::move(slot));
- return result;
+ return addAction(text, shortcut, slot);
}
// addAction(QIcon, QString): Connect to a QObject slot / functor or function pointer (with context)
template<class Obj, typename Func1>
+ QT_DEPRECATED_VERSION_X_6_4("Use addAction(icon, text, shortcut, object, slot) instead.")
inline typename std::enable_if<!std::is_same<const char*, Func1>::value
&& QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::type
- addAction(const QIcon &actionIcon, const QString &text, const Obj *object, Func1 slot
-#if QT_CONFIG(shortcut)
- , const QKeySequence &shortcut = {}
-#endif
- )
+ addAction(const QIcon &actionIcon, const QString &text, const Obj *object, Func1 slot,
+ const QKeySequence &shortcut)
{
- QAction *result = addAction(actionIcon, text);
-#if QT_CONFIG(shortcut)
- result->setShortcut(shortcut);
-#endif
- connect(result, &QAction::triggered, object, std::move(slot));
- return result;
+ return addAction(actionIcon, text, shortcut, object, slot);
}
// addAction(QIcon, QString): Connect to a functor or function pointer (without context)
template <typename Func1>
- inline QAction *addAction(const QIcon &actionIcon, const QString &text, Func1 slot
-#if QT_CONFIG(shortcut)
- , const QKeySequence &shortcut = {}
-#endif
- )
+ QT_DEPRECATED_VERSION_X_6_4("Use addAction(icon, text, shortcut, slot) instead.")
+ inline QAction *addAction(const QIcon &actionIcon, const QString &text, Func1 slot,
+ const QKeySequence &shortcut)
{
- QAction *result = addAction(actionIcon, text);
-#if QT_CONFIG(shortcut)
- result->setShortcut(shortcut);
-#endif
- connect(result, &QAction::triggered, std::move(slot));
- return result;
+ return addAction(actionIcon, text, shortcut, slot);
}
-#endif // !Q_CLANG_QDOC
+#endif // !Q_QDOC
+#endif // QT_DEPRECATED_SINCE(6, 4)
+#endif // QT_CONFIG(shortcut)
QAction *addMenu(QMenu *menu);
QMenu *addMenu(const QString &title);
@@ -202,11 +145,7 @@ public:
QAction *exec();
QAction *exec(const QPoint &pos, QAction *at = nullptr);
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
static QAction *exec(const QList<QAction *> &actions, const QPoint &pos, QAction *at = nullptr, QWidget *parent = nullptr);
-#else
- static QAction *exec(QList<QAction*> actions, const QPoint &pos, QAction *at = nullptr, QWidget *parent = nullptr);
-#endif
QSize sizeHint() const override;
@@ -214,6 +153,8 @@ public:
QAction *actionAt(const QPoint &) const;
QAction *menuAction() const;
+ static QMenu *menuInAction(const QAction *action)
+ { return qobject_cast<QMenu *>(action->menuObject()); }
QString title() const;
void setTitle(const QString &title);
@@ -225,7 +166,7 @@ public:
QPlatformMenu *platformMenu();
void setPlatformMenu(QPlatformMenu *platformMenu);
-#if defined(Q_OS_MACOS) || defined(Q_CLANG_QDOC)
+#if defined(Q_OS_MACOS) || defined(Q_QDOC)
NSMenu* toNSMenu();
void setAsDockMenu();
#endif
@@ -253,7 +194,7 @@ protected:
#if QT_CONFIG(wheelevent)
void wheelEvent(QWheelEvent *) override;
#endif
- void enterEvent(QEvent *) override;
+ void enterEvent(QEnterEvent *) override;
void leaveEvent(QEvent *) override;
void hideEvent(QHideEvent *) override;
void paintEvent(QPaintEvent *) override;
@@ -261,7 +202,7 @@ protected:
void timerEvent(QTimerEvent *) override;
bool event(QEvent *) override;
bool focusNextPrevChild(bool next) override;
- void initStyleOption(QStyleOptionMenuItem *option, const QAction *action) const;
+ virtual void initStyleOption(QStyleOptionMenuItem *option, const QAction *action) const;
private Q_SLOTS:
void internalDelayedPopup();
@@ -282,17 +223,12 @@ private:
friend class QMenuBarPrivate;
friend class QTornOffMenu;
friend class QComboBox;
- friend class QAction;
+ friend class QtWidgetsActionPrivate;
friend class QToolButtonPrivate;
friend void qt_mac_emit_menuSignals(QMenu *menu, bool show);
friend void qt_mac_menu_emit_hovered(QMenu *menu, QAction *action);
};
-#ifdef Q_OS_OSX
-// ### Qt 4 compatibility; remove in Qt 6
-inline QT_DEPRECATED void qt_mac_set_dock_menu(QMenu *menu) { menu->setAsDockMenu(); }
-#endif
-
QT_END_NAMESPACE
#endif // QMENU_H
diff --git a/src/widgets/widgets/qmenu_mac.mm b/src/widgets/widgets/qmenu_mac.mm
index 0872da803d..184386a731 100644
--- a/src/widgets/widgets/qmenu_mac.mm
+++ b/src/widgets/widgets/qmenu_mac.mm
@@ -1,77 +1,31 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
+#include <qtwidgetsglobal.h>
+
+QT_USE_NAMESPACE
+
#include "qmenu.h"
#if QT_CONFIG(menubar)
#include "qmenubar.h"
#include "qmenubar_p.h"
#endif
-#include "qmacnativewidget_mac.h"
#include <QtCore/QDebug>
#include <QtGui/QGuiApplication>
#include <QtGui/QWindow>
#include <qpa/qplatformnativeinterface.h>
+#include <qpa/qplatformmenu_p.h>
+
+using namespace QNativeInterface::Private;
QT_BEGIN_NAMESPACE
#if QT_CONFIG(menu)
-namespace {
-// TODO use QtMacExtras copy of this function when available.
-inline QPlatformNativeInterface::NativeResourceForIntegrationFunction resolvePlatformFunction(const QByteArray &functionName)
-{
- QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
- QPlatformNativeInterface::NativeResourceForIntegrationFunction function =
- nativeInterface->nativeResourceFunctionForIntegration(functionName);
- if (Q_UNLIKELY(!function))
- qWarning("Qt could not resolve function %s from "
- "QGuiApplication::platformNativeInterface()->nativeResourceFunctionForIntegration()",
- functionName.constData());
- return function;
-}
-} //namespsace
-
-
/*!
\fn NSMenu *QMenu::toNSMenu()
\since 5.2
@@ -84,12 +38,9 @@ inline QPlatformNativeInterface::NativeResourceForIntegrationFunction resolvePla
NSMenu *QMenu::toNSMenu()
{
Q_D(QMenu);
- // Call into the cocoa platform plugin: qMenuToNSMenu(platformMenu())
- QPlatformNativeInterface::NativeResourceForIntegrationFunction function = resolvePlatformFunction("qmenutonsmenu");
- if (function) {
- typedef void* (*QMenuToNSMenuFunction)(QPlatformMenu *platformMenu);
- return reinterpret_cast<NSMenu *>(reinterpret_cast<QMenuToNSMenuFunction>(function)(d->createPlatformMenu()));
- }
+ if (auto *cocoaPlatformMenu = dynamic_cast<QCocoaMenu *>(d->createPlatformMenu()))
+ return cocoaPlatformMenu->nsMenu();
+
return nil;
}
@@ -104,46 +55,46 @@ NSMenu *QMenu::toNSMenu()
void QMenu::setAsDockMenu()
{
Q_D(QMenu);
- // Call into the cocoa platform plugin: setDockMenu(platformMenu())
- QPlatformNativeInterface::NativeResourceForIntegrationFunction function = resolvePlatformFunction("setdockmenu");
- if (function) {
- typedef void (*SetDockMenuFunction)(QPlatformMenu *platformMenu);
- reinterpret_cast<SetDockMenuFunction>(function)(d->createPlatformMenu());
- }
+ if (auto *cocoaPlatformMenu = dynamic_cast<QCocoaMenu *>(d->createPlatformMenu()))
+ cocoaPlatformMenu->setAsDockMenu();
}
-
-/*! \fn void qt_mac_set_dock_menu(QMenu *menu)
- \relates QMenu
- \deprecated
-
- Sets this \a menu to be the dock menu available by option-clicking
- on the application dock icon. Available on \macos only.
-
- Deprecated; use \l QMenu::setAsDockMenu() instead.
-*/
-
void QMenuPrivate::moveWidgetToPlatformItem(QWidget *widget, QPlatformMenuItem* item)
{
- QMacNativeWidget *container = new QMacNativeWidget;
- QObject::connect(platformMenu, SIGNAL(destroyed()), container, SLOT(deleteLater()));
- container->resize(widget->sizeHint());
- widget->setParent(container);
- widget->setVisible(true);
-
- NSView *containerView = container->nativeView();
- QWindow *containerWindow = container->windowHandle();
- Qt::WindowFlags wf = containerWindow->flags();
- containerWindow->setFlags(wf | Qt::SubWindow);
- [(NSView *)widget->winId() setAutoresizingMask:NSViewWidthSizable];
-
- if (QPlatformNativeInterface::NativeResourceForIntegrationFunction function = resolvePlatformFunction("setEmbeddedInForeignView")) {
- typedef void (*SetEmbeddedInForeignViewFunction)(QPlatformWindow *window, bool embedded);
- reinterpret_cast<SetEmbeddedInForeignViewFunction>(function)(containerWindow->handle(), true);
- }
-
- item->setNativeContents((WId)containerView);
- container->show();
+ // Hide the widget before we mess with it
+ widget->hide();
+
+ // Move out of QMenu, since this widget will live in the native menu item
+ widget->setParent(nullptr);
+
+ // Make sure the widget doesn't prevent quitting the application,
+ // just because it's a parent-less (top level) window.
+ widget->setAttribute(Qt::WA_QuitOnClose, false);
+
+ // And that it blends nicely with the native menu background
+ widget->setAttribute(Qt::WA_TranslucentBackground);
+
+ // Trigger creation of the backing QWindow, the platform window, and its
+ // underlying NSView and NSWindow. At this point the widget is still hidden,
+ // so the corresponding NSWindow that is created is not shown.
+ widget->setAttribute(Qt::WA_NativeWindow);
+ QWindow *widgetWindow = widget->windowHandle();
+ widgetWindow->create();
+
+ // Inform the window that it's actually a sub-window. This
+ // ensures that we dispose of the NSWindow when the widget is
+ // finally shown. We need to do this on a QWindow level, as
+ // QWidget will ignore the flag if there is no parentWidget().
+ // And we need to do it after creating the platform window, as
+ // QWidget will overwrite the window flags during creation.
+ widgetWindow->setFlag(Qt::SubWindow);
+
+ // Finally, we can associate the underlying NSView with the menu item,
+ // and show it. This will dispose of the created NSWindow, due to
+ // the Qt::SubWindow flag above. The widget will not actually be
+ // visible until it's re-parented into the NSMenu hierarchy.
+ item->setNativeContents(WId(widgetWindow->winId()));
+ widget->show();
}
#endif // QT_CONFIG(menu)
@@ -161,12 +112,9 @@ void QMenuPrivate::moveWidgetToPlatformItem(QWidget *widget, QPlatformMenuItem*
*/
NSMenu *QMenuBar::toNSMenu()
{
- // Call into the cocoa platform plugin: qMenuBarToNSMenu(platformMenuBar())
- QPlatformNativeInterface::NativeResourceForIntegrationFunction function = resolvePlatformFunction("qmenubartonsmenu");
- if (function) {
- typedef void* (*QMenuBarToNSMenuFunction)(QPlatformMenuBar *platformMenuBar);
- return reinterpret_cast<NSMenu *>(reinterpret_cast<QMenuBarToNSMenuFunction>(function)(platformMenuBar()));
- }
+ if (auto *cocoaMenuBar = dynamic_cast<QCocoaMenuBar *>(platformMenuBar()))
+ return cocoaMenuBar->nsMenu();
+
return nil;
}
#endif // QT_CONFIG(menubar)
diff --git a/src/widgets/widgets/qmenu_p.h b/src/widgets/widgets/qmenu_p.h
index efbbc099a1..1e32fbcdfa 100644
--- a/src/widgets/widgets/qmenu_p.h
+++ b/src/widgets/widgets/qmenu_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMENU_P_H
#define QMENU_P_H
@@ -52,6 +16,7 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include "QtWidgets/qmenu.h"
#if QT_CONFIG(menubar)
#include "QtWidgets/qmenubar.h"
#endif
@@ -64,6 +29,10 @@
#include <qpa/qplatformmenu.h>
+#include <QtCore/qpointer.h>
+
+#include <functional>
+
QT_REQUIRE_CONFIG(menu);
QT_BEGIN_NAMESPACE
@@ -302,6 +271,8 @@ class QMenuPrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QMenu)
public:
+ using PositionFunction = std::function<QPoint(const QSize &)>;
+
QMenuPrivate() :
itemsDirty(false),
hasCheckableItems(false),
@@ -331,7 +302,7 @@ public:
void copyActionToPlatformItem(const QAction *action, QPlatformMenuItem *item);
QPlatformMenuItem *insertActionInPlatformMenu(const QAction *action, QPlatformMenuItem *beforeItem);
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
void moveWidgetToPlatformItem(QWidget *w, QPlatformMenuItem* item);
#endif
@@ -343,14 +314,15 @@ public:
//item calculations
QRect actionRect(QAction *) const;
- mutable QVector<QRect> actionRects;
+ mutable QList<QRect> actionRects;
mutable QHash<QAction *, QWidget *> widgetItems;
void updateActionRects() const;
void updateActionRects(const QRect &screen) const;
- QRect popupGeometry() const;
- QRect popupGeometry(int screen) const;
+ QRect popupGeometry(QScreen *screen = nullptr) const;
bool useFullScreenForPopup() const;
int getLastVisibleAction() const;
+ void popup(const QPoint &p, QAction *atAction, PositionFunction positionFunction = {});
+ QAction *exec(const QPoint &p, QAction *action, PositionFunction positionFunction = {});
//selection
static QMenu *mouseDown;
@@ -430,10 +402,11 @@ public:
QPointer<QWidget> widget;
QPointer<QAction> action;
};
- virtual QVector<QPointer<QWidget> > calcCausedStack() const;
+ virtual QList<QPointer<QWidget>> calcCausedStack() const;
QMenuCaused causedPopup;
void hideUpToMenuBar();
void hideMenu(QMenu *menu);
+ QWindow *transientParentWindow() const;
//index mappings
inline QAction *actionAt(int i) const { return q_func()->actions().at(i); }
@@ -455,7 +428,8 @@ public:
//firing of events
void activateAction(QAction *, QAction::ActionEvent, bool self=true);
- void activateCausedStack(const QVector<QPointer<QWidget> > &, QAction *, QAction::ActionEvent, bool);
+ void activateCausedStack(const QList<QPointer<QWidget>> &, QAction *, QAction::ActionEvent,
+ bool);
void _q_actionTriggered();
void _q_actionHovered();
@@ -499,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;
@@ -515,8 +494,6 @@ public:
bool tearoffHighlighted : 1;
//menu fading/scrolling effects
bool doChildEffects : 1;
-
- int popupScreen = -1;
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qmenubar.cpp b/src/widgets/widgets/qmenubar.cpp
index 59c8af30b4..c9c9191c17 100644
--- a/src/widgets/widgets/qmenubar.cpp
+++ b/src/widgets/widgets/qmenubar.cpp
@@ -1,49 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <qmenubar.h>
#include <qstyle.h>
#include <qlayout.h>
#include <qapplication.h>
-#include <qdesktopwidget.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
# include <qaccessible.h>
#endif
#include <qpainter.h>
@@ -64,7 +27,6 @@
#include <qpa/qplatformtheme.h>
#include "private/qguiapplication_p.h"
#include "qpa/qplatformintegration.h"
-#include <private/qdesktopwidget_p.h>
#include "qmenu_p.h"
#include "qmenubar_p.h"
@@ -73,6 +35,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
class QMenuBarExtension : public QToolButton
{
public:
@@ -85,7 +49,7 @@ public:
QMenuBarExtension::QMenuBarExtension(QWidget *parent)
: QToolButton(parent)
{
- setObjectName(QLatin1String("qt_menubar_ext_button"));
+ setObjectName("qt_menubar_ext_button"_L1);
setAutoRaise(true);
#if QT_CONFIG(menu)
setPopupMode(QToolButton::InstantPopup);
@@ -117,7 +81,7 @@ QSize QMenuBarExtension::sizeHint() const
QAction *QMenuBarPrivate::actionAt(QPoint p) const
{
for(int i = 0; i < actions.size(); ++i) {
- if(actionRect(actions.at(i)).contains(p))
+ if (actionRect(actions.at(i)).contains(p))
return actions.at(i);
}
return nullptr;
@@ -165,11 +129,11 @@ bool QMenuBarPrivate::isVisible(QAction *action)
void QMenuBarPrivate::updateGeometries()
{
Q_Q(QMenuBar);
- if(!itemsDirty)
+ if (!itemsDirty)
return;
int q_width = q->width()-(q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, q)*2);
int q_start = -1;
- if(leftWidget || rightWidget) {
+ if (leftWidget || rightWidget) {
int vmargin = q->style()->pixelMetric(QStyle::PM_MenuBarVMargin, nullptr, q)
+ q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, q);
int hmargin = q->style()->pixelMetric(QStyle::PM_MenuBarHMargin, nullptr, q)
@@ -192,7 +156,7 @@ void QMenuBarPrivate::updateGeometries()
}
#ifdef Q_OS_MAC
- if(q->isNativeMenuBar()) {//nothing to see here folks, move along..
+ if (q->isNativeMenuBar()) {//nothing to see here folks, move along..
itemsDirty = false;
return;
}
@@ -200,11 +164,11 @@ void QMenuBarPrivate::updateGeometries()
calcActionRects(q_width, q_start);
currentAction = nullptr;
#ifndef QT_NO_SHORTCUT
- if(itemsDirty) {
+ if (itemsDirty) {
for(int j = 0; j < shortcutIndexMap.size(); ++j)
q->releaseShortcut(shortcutIndexMap.value(j));
shortcutIndexMap.clear();
- const int actionsCount = actions.count();
+ const int actionsCount = actions.size();
shortcutIndexMap.reserve(actionsCount);
for (int i = 0; i < actionsCount; i++)
shortcutIndexMap.append(q->grabShortcut(QKeySequence::mnemonic(actions.at(i)->text())));
@@ -218,7 +182,7 @@ void QMenuBarPrivate::updateGeometries()
//we try to see if the actions will fit there
bool hasHiddenActions = false;
- for (int i = 0; i < actions.count(); ++i) {
+ for (int i = 0; i < actions.size(); ++i) {
const QRect &rect = actionRects.at(i);
if (rect.isValid() && !menuRect.contains(rect)) {
hasHiddenActions = true;
@@ -229,7 +193,7 @@ void QMenuBarPrivate::updateGeometries()
//...and if not, determine the ones that fit on the menu with the extension visible
if (hasHiddenActions) {
menuRect = this->menuRect(true);
- for (int i = 0; i < actions.count(); ++i) {
+ for (int i = 0; i < actions.size(); ++i) {
const QRect &rect = actionRects.at(i);
if (rect.isValid() && !menuRect.contains(rect)) {
hiddenActions.append(actions.at(i));
@@ -237,7 +201,7 @@ void QMenuBarPrivate::updateGeometries()
}
}
- if (hiddenActions.count() > 0) {
+ if (hiddenActions.size() > 0) {
QMenu *pop = extension->menu();
if (!pop) {
pop = new QMenu(q);
@@ -265,7 +229,7 @@ QRect QMenuBarPrivate::actionRect(QAction *act) const
//makes sure the geometries are up-to-date
const_cast<QMenuBarPrivate*>(this)->updateGeometries();
- if (index < 0 || index >= actionRects.count())
+ if (index < 0 || index >= actionRects.size())
return QRect(); // that can happen in case of native menubar
return actionRects.at(index);
@@ -273,11 +237,11 @@ QRect QMenuBarPrivate::actionRect(QAction *act) const
void QMenuBarPrivate::focusFirstAction()
{
- if(!currentAction) {
+ if (!currentAction) {
updateGeometries();
int index = 0;
- while (index < actions.count() && actionRects.at(index).isNull()) ++index;
- if (index < actions.count())
+ while (index < actions.size() && actionRects.at(index).isNull()) ++index;
+ if (index < actions.size())
setCurrentAction(actions.at(index));
}
}
@@ -290,16 +254,16 @@ void QMenuBarPrivate::setKeyboardMode(bool b)
return;
}
keyboardState = b;
- if(b) {
+ if (b) {
QWidget *fw = QApplication::focusWidget();
if (fw && fw != q && fw->window() != QApplication::activePopupWidget())
keyboardFocusWidget = fw;
focusFirstAction();
q->setFocus(Qt::MenuBarFocusReason);
} else {
- if(!popupState)
+ if (!popupState)
setCurrentAction(nullptr);
- if(keyboardFocusWidget) {
+ if (keyboardFocusWidget) {
if (QApplication::focusWidget() == q)
keyboardFocusWidget->setFocus(Qt::MenuBarFocusReason);
keyboardFocusWidget = nullptr;
@@ -311,23 +275,34 @@ void QMenuBarPrivate::setKeyboardMode(bool b)
void QMenuBarPrivate::popupAction(QAction *action, bool activateFirst)
{
Q_Q(QMenuBar);
- if(!action || !action->menu() || closePopupMode)
+ if (!action || !action->menu() || closePopupMode)
return;
popupState = true;
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());
@@ -353,11 +328,11 @@ void QMenuBarPrivate::popupAction(QAction *action, bool activateFirst)
pos.rx() += actionWidth;
}
- if(!defaultPopDown || (fitUp && !fitDown))
+ if (!defaultPopDown || (fitUp && !fitDown))
pos.setY(qMax(screenRect.y(), q->mapToGlobal(QPoint(0, adjustedActionRect.top()-popup_size.height())).y()));
- QMenuPrivate::get(activeMenu)->topData()->initialScreenIndex = QGuiApplication::screens().indexOf(popupScreen);
+ QMenuPrivate::get(activeMenu)->topData()->initialScreen = popupScreen;
activeMenu->popup(pos);
- if(activateFirst)
+ if (activateFirst)
activeMenu->d_func()->setFirstActionActive();
}
q->update(actionRect(action));
@@ -365,7 +340,7 @@ void QMenuBarPrivate::popupAction(QAction *action, bool activateFirst)
void QMenuBarPrivate::setCurrentAction(QAction *action, bool popup, bool activateFirst)
{
- if(currentAction == action && popup == popupState)
+ if (currentAction == action && popup == popupState)
return;
autoReleaseTimer.stop();
@@ -373,7 +348,7 @@ void QMenuBarPrivate::setCurrentAction(QAction *action, bool popup, bool activat
doChildEffects = (popup && !activeMenu);
Q_Q(QMenuBar);
QWidget *fw = nullptr;
- if(QMenu *menu = activeMenu) {
+ if (QMenu *menu = activeMenu) {
activeMenu = nullptr;
if (popup) {
fw = q->window()->focusWidget();
@@ -382,7 +357,7 @@ void QMenuBarPrivate::setCurrentAction(QAction *action, bool popup, bool activat
menu->hide();
}
- if(currentAction)
+ if (currentAction)
q->update(actionRect(currentAction));
popupState = popup;
@@ -392,7 +367,7 @@ void QMenuBarPrivate::setCurrentAction(QAction *action, bool popup, bool activat
currentAction = action;
if (action && action->isEnabled()) {
activateAction(action, QAction::Hover);
- if(popup)
+ if (popup)
popupAction(action, activateFirst);
q->update(actionRect(action));
#if QT_CONFIG(statustip)
@@ -410,11 +385,11 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const
{
Q_Q(const QMenuBar);
- if(!itemsDirty)
+ if (!itemsDirty)
return;
//let's reinitialize the buffer
- actionRects.resize(actions.count());
+ actionRects.resize(actions.size());
actionRects.fill(QRect());
const QStyle *style = q->style();
@@ -427,15 +402,15 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const
const int hmargin = style->pixelMetric(QStyle::PM_MenuBarHMargin, nullptr, q),
vmargin = style->pixelMetric(QStyle::PM_MenuBarVMargin, nullptr, q),
icone = style->pixelMetric(QStyle::PM_SmallIconSize, nullptr, q);
- for(int i = 0; i < actions.count(); i++) {
+ for(int i = 0; i < actions.size(); i++) {
QAction *action = actions.at(i);
- if(!action->isVisible())
+ if (!action->isVisible())
continue;
QSize sz;
//calc what I think the size is..
- if(action->isSeparator()) {
+ if (action->isSeparator()) {
if (style->styleHint(QStyle::SH_DrawMenuBarSeparator, nullptr, q))
separator = i;
continue; //we don't really position these!
@@ -454,10 +429,10 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const
q->initStyleOption(&opt, action);
sz = q->style()->sizeFromContents(QStyle::CT_MenuBarItem, &opt, sz, q);
- if(!sz.isEmpty()) {
+ if (!sz.isEmpty()) {
{ //update the separator state
int iWidth = sz.width() + itemSpacing;
- if(separator == -1)
+ if (separator == -1)
separator_start += iWidth;
else
separator_len += iWidth;
@@ -473,7 +448,7 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const
const int fw = q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, q);
int x = fw + ((start == -1) ? hmargin : start) + itemSpacing;
int y = fw + vmargin;
- for(int i = 0; i < actions.count(); i++) {
+ for(int i = 0; i < actions.size(); i++) {
QRect &rect = actionRects[i];
if (rect.isNull())
continue;
@@ -482,9 +457,9 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const
rect.setHeight(max_item_height);
//move
- if(separator != -1 && i >= separator) { //after the separator
+ if (separator != -1 && i >= separator) { //after the separator
int left = (max_width - separator_len - hmargin - itemSpacing) + (x - separator_start - hmargin);
- if(left < separator_start) { //wrap
+ if (left < separator_start) { //wrap
separator_start = x = hmargin;
y += max_item_height;
}
@@ -511,9 +486,9 @@ void QMenuBarPrivate::activateAction(QAction *action, QAction::ActionEvent actio
if (action_e == QAction::Hover)
action->showStatusText(q);
-// if(action_e == QAction::Trigger)
+// if (action_e == QAction::Trigger)
// emit q->activated(action);
-// else if(action_e == QAction::Hover)
+// else if (action_e == QAction::Hover)
// emit q->highlighted(action);
}
@@ -531,14 +506,14 @@ void QMenuBarPrivate::_q_actionHovered()
Q_Q(QMenuBar);
if (QAction *action = qobject_cast<QAction *>(q->sender())) {
emit q->hovered(action);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
int actionIndex = actions.indexOf(action);
QAccessibleEvent focusEvent(q, QAccessible::Focus);
focusEvent.setChild(actionIndex);
QAccessible::updateAccessibility(&focusEvent);
}
-#endif //QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
}
}
@@ -583,7 +558,7 @@ void QMenuBar::initStyleOption(QStyleOptionMenuItem *option, const QAction *acti
\inmodule QtWidgets
A menu bar consists of a list of pull-down menu items. You add
- menu items with addMenu(). For example, asuming that \c menubar
+ menu items with addMenu(). For example, assuming that \c menubar
is a pointer to a QMenuBar and \c fileMenu is a pointer to a
QMenu, the following statement inserts the menu into the menu bar:
\snippet code/src_gui_widgets_qmenubar.cpp 0
@@ -632,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
@@ -654,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.
@@ -686,7 +663,7 @@ void QMenuBar::initStyleOption(QStyleOptionMenuItem *option, const QAction *acti
\sa QMenu, QShortcut, QAction,
{http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGIntro/XHIGIntro.html}{Introduction to Apple Human Interface Guidelines},
- {fowler}{GUI Design Handbook: Menu Bar}, {Menus Example}
+ {Menus Example}
*/
@@ -716,8 +693,8 @@ QAction *QMenuBarPrivate::getNextAction(const int _start, const int increment) c
Q_Q(const QMenuBar);
const_cast<QMenuBarPrivate*>(this)->updateGeometries();
bool allowActiveAndDisabled = q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, nullptr, q);
- const int start = (_start == -1 && increment == -1) ? actions.count() : _start;
- const int end = increment == -1 ? 0 : actions.count() - 1;
+ const int start = (_start == -1 && increment == -1) ? actions.size() : _start;
+ const int end = increment == -1 ? 0 : actions.size() - 1;
for (int i = start; i != end;) {
i += increment;
@@ -753,72 +730,6 @@ QMenuBar::~QMenuBar()
}
/*!
- This convenience function creates a new action with \a text.
- The function adds the newly created action to the menu's
- list of actions, and returns it.
-
- \sa QWidget::addAction(), QWidget::actions()
-*/
-QAction *QMenuBar::addAction(const QString &text)
-{
- QAction *ret = new QAction(text, this);
- addAction(ret);
- return ret;
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with the given \a
- text. The action's triggered() signal is connected to the \a
- receiver's \a member slot. The function adds the newly created
- action to the menu's list of actions and returns it.
-
- \sa QWidget::addAction(), QWidget::actions()
-*/
-QAction *QMenuBar::addAction(const QString &text, const QObject *receiver, const char* member)
-{
- QAction *ret = new QAction(text, this);
- QObject::connect(ret, SIGNAL(triggered(bool)), receiver, member);
- addAction(ret);
- return ret;
-}
-
-/*!
- \fn template<typename Obj, typename PointerToMemberFunctionOrFunctor> QAction *QMenuBar::addAction(const QString &text, const Obj *receiver, PointerToMemberFunctionOrFunctor method)
-
- \since 5.11
-
- \overload
-
- This convenience function creates a new action with the given \a
- text. The action's triggered() signal is connected to the
- \a method of the \a receiver. The function adds the newly created
- action to the menu's list of actions and returns it.
-
- QMenuBar takes ownership of the returned QAction.
-
- \sa QWidget::addAction(), QWidget::actions()
-*/
-
-/*!
- \fn template<typename Functor> QAction *QMenuBar::addAction(const QString &text, Functor functor)
-
- \since 5.11
-
- \overload
-
- This convenience function creates a new action with the given \a
- text. The action's triggered() signal is connected to the
- \a functor. The function adds the newly created
- action to the menu's list of actions and returns it.
-
- QMenuBar takes ownership of the returned QAction.
-
- \sa QWidget::addAction(), QWidget::actions()
-*/
-
-/*!
Appends a new QMenu with \a title to the menu bar. The menu bar
takes ownership of the menu. Returns the new menu.
@@ -986,12 +897,12 @@ void QMenuBar::paintEvent(QPaintEvent *e)
QRegion emptyArea(rect());
//draw the items
- for (int i = 0; i < d->actions.count(); ++i) {
+ for (int i = 0; i < d->actions.size(); ++i) {
QAction *action = d->actions.at(i);
QRect adjustedActionRect = d->actionRect(action);
if (adjustedActionRect.isEmpty() || !d->isVisible(action))
continue;
- if(!e->rect().intersects(adjustedActionRect))
+ if (!e->rect().intersects(adjustedActionRect))
continue;
emptyArea -= adjustedActionRect;
@@ -1014,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.lineWidth = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, &frame, this);
frame.midLineWidth = 0;
style()->drawPrimitive(QStyle::PE_PanelMenuBar, &frame, &p, this);
}
@@ -1048,23 +959,23 @@ void QMenuBar::setVisible(bool visible)
void QMenuBar::mousePressEvent(QMouseEvent *e)
{
Q_D(QMenuBar);
- if(e->button() != Qt::LeftButton)
+ if (e->button() != Qt::LeftButton)
return;
d->mouseDown = true;
- QAction *action = d->actionAt(e->pos());
+ QAction *action = d->actionAt(e->position().toPoint());
if (!action || !d->isVisible(action) || !action->isEnabled()) {
d->setCurrentAction(nullptr);
#if QT_CONFIG(whatsthis)
if (QWhatsThis::inWhatsThisMode())
- QWhatsThis::showText(e->globalPos(), d->whatsThis, this);
+ QWhatsThis::showText(e->globalPosition().toPoint(), d->whatsThis, this);
#endif
return;
}
- if(d->currentAction == action && d->popupState) {
- if(QMenu *menu = d->activeMenu) {
+ if (d->currentAction == action && d->popupState) {
+ if (QMenu *menu = d->activeMenu) {
d->activeMenu = nullptr;
menu->setAttribute(Qt::WA_NoMouseReplay);
menu->hide();
@@ -1080,20 +991,20 @@ void QMenuBar::mousePressEvent(QMouseEvent *e)
void QMenuBar::mouseReleaseEvent(QMouseEvent *e)
{
Q_D(QMenuBar);
- if(e->button() != Qt::LeftButton || !d->mouseDown)
+ if (e->button() != Qt::LeftButton || !d->mouseDown)
return;
d->mouseDown = false;
- QAction *action = d->actionAt(e->pos());
+ QAction *action = d->actionAt(e->position().toPoint());
// do noting if the action is hidden
if (!d->isVisible(action))
return;
- if((d->closePopupMode && action == d->currentAction) || !action || !action->menu()) {
+ if ((d->closePopupMode && action == d->currentAction) || !action || !action->menu()) {
//we set the current action before activating
//so that we let the leave event set the current back to 0
d->setCurrentAction(action, false);
- if(action)
+ if (action)
d->activateAction(action, QAction::Trigger);
}
d->closePopupMode = 0;
@@ -1107,15 +1018,15 @@ void QMenuBar::keyPressEvent(QKeyEvent *e)
Q_D(QMenuBar);
d->updateGeometries();
int key = e->key();
- if(isRightToLeft()) { // in reverse mode open/close key for submenues are reversed
- if(key == Qt::Key_Left)
+ if (isRightToLeft()) { // in reverse mode open/close key for submenues are reversed
+ if (key == Qt::Key_Left)
key = Qt::Key_Right;
- else if(key == Qt::Key_Right)
+ else if (key == Qt::Key_Right)
key = Qt::Key_Left;
}
- if(key == Qt::Key_Tab) //means right
+ if (key == Qt::Key_Tab) //means right
key = Qt::Key_Right;
- else if(key == Qt::Key_Backtab) //means left
+ else if (key == Qt::Key_Backtab) //means left
key = Qt::Key_Left;
bool key_consumed = false;
@@ -1127,9 +1038,9 @@ void QMenuBar::keyPressEvent(QKeyEvent *e)
case Qt::Key_Return: {
if (!style()->styleHint(QStyle::SH_MenuBar_AltKeyNavigation, nullptr, this) || !d->currentAction)
break;
- if(d->currentAction->menu()) {
+ if (d->currentAction->menu()) {
d->popupAction(d->currentAction, true);
- } else if(key == Qt::Key_Enter || key == Qt::Key_Return || key == Qt::Key_Space) {
+ } else if (key == Qt::Key_Enter || key == Qt::Key_Return || key == Qt::Key_Space) {
d->activateAction(d->currentAction, QAction::Trigger);
d->setCurrentAction(d->currentAction, false);
d->setKeyboardMode(false);
@@ -1139,7 +1050,7 @@ void QMenuBar::keyPressEvent(QKeyEvent *e)
case Qt::Key_Right:
case Qt::Key_Left: {
- if(d->currentAction) {
+ if (d->currentAction) {
int index = d->actions.indexOf(d->currentAction);
if (QAction *nextAction = d->getNextAction(index, key == Qt::Key_Left ? -1 : +1)) {
d->setCurrentAction(nextAction, d->popupState, true);
@@ -1160,9 +1071,9 @@ void QMenuBar::keyPressEvent(QKeyEvent *e)
}
#endif
- if(!key_consumed &&
+ if (!key_consumed &&
(!e->modifiers() ||
- (e->modifiers()&(Qt::MetaModifier|Qt::AltModifier))) && e->text().length()==1 && !d->popupState) {
+ (e->modifiers()&(Qt::MetaModifier|Qt::AltModifier))) && e->text().size()==1 && !d->popupState) {
int clashCount = 0;
QAction *first = nullptr, *currentSelected = nullptr, *firstAfterCurrent = nullptr;
{
@@ -1172,14 +1083,14 @@ void QMenuBar::keyPressEvent(QKeyEvent *e)
continue;
QAction *act = d->actions.at(i);
QString s = act->text();
- if(!s.isEmpty()) {
- int ampersand = s.indexOf(QLatin1Char('&'));
- if(ampersand >= 0) {
- if(s[ampersand+1].toUpper() == c) {
+ if (!s.isEmpty()) {
+ qsizetype ampersand = s.indexOf(u'&');
+ if (ampersand >= 0) {
+ if (s[ampersand+1].toUpper() == c) {
clashCount++;
- if(!first)
+ if (!first)
first = act;
- if(act == d->currentAction)
+ if (act == d->currentAction)
currentSelected = act;
else if (!firstAfterCurrent && currentSelected)
firstAfterCurrent = act;
@@ -1189,18 +1100,18 @@ void QMenuBar::keyPressEvent(QKeyEvent *e)
}
}
QAction *next_action = nullptr;
- if(clashCount >= 1) {
- if(clashCount == 1 || !d->currentAction || (currentSelected && !firstAfterCurrent))
+ if (clashCount >= 1) {
+ if (clashCount == 1 || !d->currentAction || (currentSelected && !firstAfterCurrent))
next_action = first;
else
next_action = firstAfterCurrent;
}
- if(next_action) {
+ if (next_action) {
key_consumed = true;
d->setCurrentAction(next_action, true, true);
}
}
- if(key_consumed)
+ if (key_consumed)
e->accept();
else
e->ignore();
@@ -1222,7 +1133,7 @@ void QMenuBar::mouseMoveEvent(QMouseEvent *e)
}
bool popupState = d->popupState || d->mouseDown;
- QAction *action = d->actionAt(e->pos());
+ QAction *action = d->actionAt(e->position().toPoint());
if ((action && d->isVisible(action)) || !popupState)
d->setCurrentAction(action, popupState);
}
@@ -1233,7 +1144,7 @@ void QMenuBar::mouseMoveEvent(QMouseEvent *e)
void QMenuBar::leaveEvent(QEvent *)
{
Q_D(QMenuBar);
- if((!hasFocus() && !d->popupState) ||
+ if ((!hasFocus() && !d->popupState) ||
(d->currentAction && d->currentAction->menu() == nullptr))
d->setCurrentAction(nullptr);
}
@@ -1324,10 +1235,10 @@ void QMenuBar::actionEvent(QActionEvent *e)
}
}
- if(e->type() == QEvent::ActionAdded) {
+ if (e->type() == QEvent::ActionAdded) {
connect(e->action(), SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
connect(e->action(), SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
- } else if(e->type() == QEvent::ActionRemoved) {
+ } else if (e->type() == QEvent::ActionRemoved) {
e->action()->disconnect(this);
}
// updateGeometries() is also needed for native menu bars because
@@ -1344,7 +1255,7 @@ void QMenuBar::actionEvent(QActionEvent *e)
void QMenuBar::focusInEvent(QFocusEvent *)
{
Q_D(QMenuBar);
- if(d->keyboardState)
+ if (d->keyboardState)
d->focusFirstAction();
}
@@ -1354,7 +1265,7 @@ void QMenuBar::focusInEvent(QFocusEvent *)
void QMenuBar::focusOutEvent(QFocusEvent *)
{
Q_D(QMenuBar);
- if(!d->popupState) {
+ if (!d->popupState) {
d->setCurrentAction(nullptr);
d->setKeyboardMode(false);
}
@@ -1384,10 +1295,15 @@ void QMenuBarPrivate::handleReparent()
// also a window (for shortcuts)
QWidget *newWindow = newParent ? newParent->window() : nullptr;
- QVector<QPointer<QWidget> > newParents;
+ 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);
@@ -1433,10 +1349,10 @@ void QMenuBarPrivate::handleReparent()
void QMenuBar::changeEvent(QEvent *e)
{
Q_D(QMenuBar);
- if(e->type() == QEvent::StyleChange) {
+ if (e->type() == QEvent::StyleChange) {
d->itemsDirty = true;
setMouseTracking(style()->styleHint(QStyle::SH_MenuBar_MouseTracking, nullptr, this));
- if(parentWidget())
+ if (parentWidget())
resize(parentWidget()->width(), heightForWidth(parentWidget()->width()));
d->updateGeometries();
} else if (e->type() == QEvent::ParentChange) {
@@ -1458,14 +1374,14 @@ 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..
+ if (!d->keyboardState) { //all keypresses..
d->setCurrentAction(0);
return ;
}
#endif
- if(ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
+ if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
keyPressEvent(ke);
return true;
}
@@ -1486,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();
@@ -1590,7 +1506,7 @@ bool QMenuBar::eventFilter(QObject *object, QEvent *event)
Returns the QAction at \a pt. Returns \nullptr if there is no action at \a pt or if
the location has a separator.
- \sa addAction(), addSeparator()
+ \sa QWidget::addAction(), addSeparator()
*/
QAction *QMenuBar::actionAt(const QPoint &pt) const
{
@@ -1624,29 +1540,29 @@ QSize QMenuBar::minimumSizeHint() const
const int vmargin = style()->pixelMetric(QStyle::PM_MenuBarVMargin, nullptr, this);
int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, this);
int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, nullptr, this);
- if(as_gui_menubar) {
- int w = parentWidget() ? parentWidget()->width() : QDesktopWidgetPrivate::width();
+ if (as_gui_menubar) {
+ int w = parentWidget() ? parentWidget()->width() : QGuiApplication::primaryScreen()->virtualGeometry().width();
d->calcActionRects(w - (2 * fw), 0);
- for (int i = 0; ret.isNull() && i < d->actions.count(); ++i)
+ for (int i = 0; ret.isNull() && i < d->actions.size(); ++i)
ret = d->actionRects.at(i).size();
if (!d->extension->isHidden())
ret += QSize(d->extension->sizeHint().width(), 0);
ret += QSize(2*fw + hmargin, 2*fw + vmargin);
}
int margin = 2*vmargin + 2*fw + spaceBelowMenuBar;
- if(d->leftWidget) {
+ if (d->leftWidget) {
QSize sz = d->leftWidget->minimumSizeHint();
ret.setWidth(ret.width() + sz.width());
- if(sz.height() + margin > ret.height())
+ if (sz.height() + margin > ret.height())
ret.setHeight(sz.height() + margin);
}
- if(d->rightWidget) {
+ if (d->rightWidget) {
QSize sz = d->rightWidget->minimumSizeHint();
ret.setWidth(ret.width() + sz.width());
- if(sz.height() + margin > ret.height())
+ if (sz.height() + margin > ret.height())
ret.setHeight(sz.height() + margin);
}
- if(as_gui_menubar) {
+ if (as_gui_menubar) {
QStyleOptionMenuItem opt;
opt.rect = rect();
opt.menuRect = rect();
@@ -1654,9 +1570,7 @@ QSize QMenuBar::minimumSizeHint() const
opt.menuItemType = QStyleOptionMenuItem::Normal;
opt.checkType = QStyleOptionMenuItem::NotCheckable;
opt.palette = palette();
- return (style()->sizeFromContents(QStyle::CT_MenuBar, &opt,
- ret.expandedTo(QApplication::globalStrut()),
- this));
+ return style()->sizeFromContents(QStyle::CT_MenuBar, &opt, ret, this);
}
return ret;
}
@@ -1676,10 +1590,10 @@ QSize QMenuBar::sizeHint() const
const int vmargin = style()->pixelMetric(QStyle::PM_MenuBarVMargin, nullptr, this);
int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, this);
int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, nullptr, this);
- if(as_gui_menubar) {
- const int w = parentWidget() ? parentWidget()->width() : QDesktopWidgetPrivate::width();
+ if (as_gui_menubar) {
+ const int w = parentWidget() ? parentWidget()->width() : QGuiApplication::primaryScreen()->virtualGeometry().width();
d->calcActionRects(w - (2 * fw), 0);
- for (int i = 0; i < d->actionRects.count(); ++i) {
+ for (int i = 0; i < d->actionRects.size(); ++i) {
const QRect &actionRect = d->actionRects.at(i);
ret = ret.expandedTo(QSize(actionRect.x() + actionRect.width(), actionRect.y() + actionRect.height()));
}
@@ -1688,18 +1602,18 @@ QSize QMenuBar::sizeHint() const
ret += QSize(fw + hmargin, fw + vmargin);
}
int margin = 2*vmargin + 2*fw + spaceBelowMenuBar;
- if(d->leftWidget) {
+ if (d->leftWidget) {
QSize sz = d->leftWidget->sizeHint();
sz.rheight() += margin;
ret = ret.expandedTo(sz);
}
- if(d->rightWidget) {
+ if (d->rightWidget) {
QSize sz = d->rightWidget->sizeHint();
ret.setWidth(ret.width() + sz.width());
- if(sz.height() + margin > ret.height())
+ if (sz.height() + margin > ret.height())
ret.setHeight(sz.height() + margin);
}
- if(as_gui_menubar) {
+ if (as_gui_menubar) {
QStyleOptionMenuItem opt;
opt.rect = rect();
opt.menuRect = rect();
@@ -1707,9 +1621,7 @@ QSize QMenuBar::sizeHint() const
opt.menuItemType = QStyleOptionMenuItem::Normal;
opt.checkType = QStyleOptionMenuItem::NotCheckable;
opt.palette = palette();
- return (style()->sizeFromContents(QStyle::CT_MenuBar, &opt,
- ret.expandedTo(QApplication::globalStrut()),
- this));
+ return style()->sizeFromContents(QStyle::CT_MenuBar, &opt, ret, this);
}
return ret;
}
@@ -1727,8 +1639,8 @@ int QMenuBar::heightForWidth(int) const
const int vmargin = style()->pixelMetric(QStyle::PM_MenuBarVMargin, nullptr, this);
int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, this);
int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, nullptr, this);
- if(as_gui_menubar) {
- for (int i = 0; i < d->actionRects.count(); ++i)
+ if (as_gui_menubar) {
+ for (int i = 0; i < d->actionRects.size(); ++i)
height = qMax(height, d->actionRects.at(i).height());
if (height) //there is at least one non-null item
height += spaceBelowMenuBar;
@@ -1736,13 +1648,13 @@ int QMenuBar::heightForWidth(int) const
height += 2*vmargin;
}
int margin = 2*vmargin + 2*fw + spaceBelowMenuBar;
- if(d->leftWidget)
+ if (d->leftWidget)
height = qMax(d->leftWidget->sizeHint().height() + margin, height);
- if(d->rightWidget)
+ if (d->rightWidget)
height = qMax(d->rightWidget->sizeHint().height() + margin, height);
- if(as_gui_menubar) {
+ if (as_gui_menubar) {
QStyleOptionMenuItem opt;
- opt.init(this);
+ opt.initFrom(this);
opt.menuRect = rect();
opt.state = QStyle::State_None;
opt.menuItemType = QStyleOptionMenuItem::Normal;
@@ -1878,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.h b/src/widgets/widgets/qmenubar.h
index cf6663f94a..dc0d1559bf 100644
--- a/src/widgets/widgets/qmenubar.h
+++ b/src/widgets/widgets/qmenubar.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMENUBAR_H
#define QMENUBAR_H
@@ -64,34 +28,10 @@ public:
~QMenuBar();
using QWidget::addAction;
+#if QT_WIDGETS_REMOVED_SINCE(6, 3)
QAction *addAction(const QString &text);
QAction *addAction(const QString &text, const QObject *receiver, const char* member);
-
-#ifdef Q_CLANG_QDOC
- template<typename Obj, typename PointerToMemberFunctionOrFunctor>
- QAction *addAction(const QString &text, const Obj *receiver, PointerToMemberFunctionOrFunctor method);
- template<typename Functor>
- QAction *addAction(const QString &text, Functor functor);
-#else
- // addAction(QString): Connect to a QObject slot / functor or function pointer (with context)
- template<typename Obj, typename Func1>
- inline typename std::enable_if<!std::is_same<const char*, Func1>::value
- && QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::type
- addAction(const QString &text, const Obj *object, Func1 slot)
- {
- QAction *result = addAction(text);
- connect(result, &QAction::triggered, object, std::move(slot));
- return result;
- }
- // addAction(QString): Connect to a functor or function pointer (without context)
- template <typename Func1>
- inline QAction *addAction(const QString &text, Func1 slot)
- {
- QAction *result = addAction(text);
- connect(result, &QAction::triggered, std::move(slot));
- return result;
- }
-#endif // !Q_CLANG_QDOC
+#endif
QAction *addMenu(QMenu *menu);
QMenu *addMenu(const QString &title);
@@ -121,7 +61,7 @@ public:
void setCornerWidget(QWidget *w, Qt::Corner corner = Qt::TopRightCorner);
QWidget *cornerWidget(Qt::Corner corner = Qt::TopRightCorner) const;
-#if defined(Q_OS_MACOS) || defined(Q_CLANG_QDOC)
+#if defined(Q_OS_MACOS) || defined(Q_QDOC)
NSMenu* toNSMenu();
#endif
@@ -150,7 +90,7 @@ protected:
void timerEvent(QTimerEvent *) override;
bool eventFilter(QObject *, QEvent *) override;
bool event(QEvent *) override;
- void initStyleOption(QStyleOptionMenuItem *option, const QAction *action) const;
+ virtual void initStyleOption(QStyleOptionMenuItem *option, const QAction *action) const;
private:
Q_DECLARE_PRIVATE(QMenuBar)
diff --git a/src/widgets/widgets/qmenubar_p.h b/src/widgets/widgets/qmenubar_p.h
index e3db16d190..549a4c7a1f 100644
--- a/src/widgets/widgets/qmenubar_p.h
+++ b/src/widgets/widgets/qmenubar_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QMENUBAR_P_H
#define QMENUBAR_P_H
@@ -56,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
@@ -81,8 +47,8 @@ public:
//item calculations
uint itemsDirty : 1;
- QVector<int> shortcutIndexMap;
- mutable QVector<QRect> actionRects;
+ QList<int> shortcutIndexMap;
+ mutable QList<QRect> actionRects;
void calcActionRects(int max_width, int start) const;
QRect actionRect(QAction *) const;
void updateGeometries();
@@ -124,7 +90,7 @@ public:
// reparenting
void handleReparent();
- QVector<QPointer<QWidget> > oldParents;
+ QList<QPointer<QWidget>> oldParents;
QList<QAction*> hiddenActions;
//default action
diff --git a/src/widgets/widgets/qplaintextedit.cpp b/src/widgets/widgets/qplaintextedit.cpp
index d54c0d0b20..8362c6c629 100644
--- a/src/widgets/widgets/qplaintextedit.cpp
+++ b/src/widgets/widgets/qplaintextedit.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qplaintextedit_p.h"
@@ -71,9 +35,14 @@
QT_BEGIN_NAMESPACE
-static inline bool shouldEnableInputMethod(QPlainTextEdit *plaintextedit)
+static inline bool shouldEnableInputMethod(QPlainTextEdit *control)
{
- return !plaintextedit->isReadOnly();
+#if defined(Q_OS_ANDROID)
+ Q_UNUSED(control);
+ return !control->isReadOnly() || (control->textInteractionFlags() & Qt::TextSelectableByMouse);
+#else
+ return !control->isReadOnly();
+#endif
}
class QPlainTextDocumentLayoutPrivate : public QAbstractTextDocumentLayoutPrivate
@@ -449,22 +418,29 @@ QPlainTextEditControl::QPlainTextEditControl(QPlainTextEdit *parent)
setAcceptRichText(false);
}
-void QPlainTextEditPrivate::_q_cursorPositionChanged()
+void QPlainTextEditPrivate::cursorPositionChanged()
{
pageUpDownLastCursorYIsValid = false;
Q_Q(QPlainTextEdit);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleTextCursorEvent ev(q, q->textCursor().position());
QAccessible::updateAccessibility(&ev);
#endif
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;
}
}
@@ -653,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;
@@ -672,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);
@@ -755,21 +725,17 @@ void QPlainTextEditPrivate::updateViewport()
}
QPlainTextEditPrivate::QPlainTextEditPrivate()
- : control(nullptr),
- tabChangesFocus(false),
- lineWrap(QPlainTextEdit::WidgetWidth),
- wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere),
- clickCausedFocus(0), placeholderVisible(1),
- topLine(0), topLineFracture(0),
- pageUpDownLastCursorYIsValid(false)
+ : tabChangesFocus(false)
+ , showCursorOnInitialShow(false)
+ , backgroundVisible(false)
+ , centerOnScroll(false)
+ , inDrag(false)
+ , clickCausedFocus(false)
+ , pageUpDownLastCursorYIsValid(false)
+ , placeholderTextShown(false)
{
- showCursorOnInitialShow = true;
- backgroundVisible = false;
- centerOnScroll = false;
- inDrag = false;
}
-
void QPlainTextEditPrivate::init(const QString &txt)
{
Q_Q(QPlainTextEdit);
@@ -782,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_textChanged()));
- 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
@@ -824,29 +795,21 @@ void QPlainTextEditPrivate::init(const QString &txt)
#ifndef QT_NO_CURSOR
viewport->setCursor(Qt::IBeamCursor);
#endif
- originalOffsetY = 0;
}
-void QPlainTextEditPrivate::_q_textChanged()
+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()) {
@@ -972,14 +935,14 @@ void QPlainTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCurso
}
if (moveCursor) {
- control->setTextCursor(cursor);
+ control->setTextCursor(cursor, moveMode == QTextCursor::KeepAnchor);
pageUpDownLastCursorYIsValid = true;
}
}
#if QT_CONFIG(scrollbar)
-void QPlainTextEditPrivate::_q_adjustScrollbars()
+void QPlainTextEditPrivate::adjustScrollbars()
{
Q_Q(QPlainTextEdit);
QTextDocument *doc = control->document();
@@ -1033,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);
@@ -1043,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());
@@ -1226,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, {Application Example},
- {Code Editor Example}, {Syntax Highlighter Example},
- {Rich Text Processing}
+ \sa QTextDocument, QTextCursor
+ {Syntax Highlighter Example}, {Rich Text Processing}
*/
@@ -1341,7 +1297,7 @@ void QPlainTextEdit::setDocument(QTextDocument *document)
d->documentLayoutPtr = documentLayout;
d->updateDefaultTextOption();
d->relayoutDocument();
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
}
/*!
@@ -1373,8 +1329,7 @@ void QPlainTextEdit::setPlaceholderText(const QString &placeholderText)
Q_D(QPlainTextEdit);
if (d->placeholderText != placeholderText) {
d->placeholderText = placeholderText;
- if (d->control->document()->isEmpty())
- d->viewport->update();
+ d->updatePlaceholderVisibility();
}
}
@@ -1430,7 +1385,7 @@ QString QPlainTextEdit::anchorAt(const QPoint &pos) const
if (cursorPos < 0)
return QString();
- QTextDocumentPrivate *pieceTable = document()->docHandle();
+ QTextDocumentPrivate *pieceTable = QTextDocumentPrivate::get(document());
QTextDocumentPrivate::FragmentIterator it = pieceTable->find(cursorPos);
QTextCharFormat fmt = pieceTable->formatCollection()->charFormat(it->format);
return fmt.anchorHref();
@@ -1554,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);
}
@@ -1833,8 +1796,11 @@ void QPlainTextEdit::keyPressEvent(QKeyEvent *e)
*/
void QPlainTextEdit::keyReleaseEvent(QKeyEvent *e)
{
-#ifdef QT_KEYPAD_NAVIGATION
Q_D(QPlainTextEdit);
+ if (!isReadOnly())
+ d->handleSoftwareInputPanel();
+
+#ifdef QT_KEYPAD_NAVIGATION
if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!e->isAutoRepeat() && e->key() == Qt::Key_Back
&& d->deleteAllTimer.isActive()) {
@@ -1880,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()
@@ -1942,11 +1908,11 @@ void QPlainTextEdit::paintEvent(QPaintEvent *e)
// keep right margin clean from full-width selection
int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth)
- - document()->documentMargin();
+ - document()->documentMargin() + cursorWidth();
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());
@@ -1980,8 +1946,7 @@ void QPlainTextEdit::paintEvent(QPaintEvent *e)
fillBackground(&painter, contentsRect, bg);
}
-
- QVector<QTextLayout::FormatRange> selections;
+ QList<QTextLayout::FormatRange> selections;
int blpos = block.position();
int bllen = block.length();
for (int i = 0; i < context.selections.size(); ++i) {
@@ -2091,7 +2056,7 @@ void QPlainTextEdit::mouseMoveEvent(QMouseEvent *e)
{
Q_D(QPlainTextEdit);
d->inDrag = false; // paranoia
- const QPoint pos = e->pos();
+ const QPoint pos = e->position().toPoint();
d->sendControlEvent(e);
if (!(e->buttons() & Qt::LeftButton))
return;
@@ -2115,7 +2080,7 @@ void QPlainTextEdit::mouseReleaseEvent(QMouseEvent *e)
d->ensureCursorVisible();
}
- if (!isReadOnly() && rect().contains(e->pos()))
+ if (!isReadOnly() && rect().contains(e->position().toPoint()))
d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
d->clickCausedFocus = 0;
}
@@ -2186,7 +2151,7 @@ void QPlainTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
void QPlainTextEdit::dragMoveEvent(QDragMoveEvent *e)
{
Q_D(QPlainTextEdit);
- d->autoScrollDragPos = e->pos();
+ d->autoScrollDragPos = e->position().toPoint();
if (!d->autoScrollTimer.isActive())
d->autoScrollTimer.start(100, this);
d->sendControlEvent(e);
@@ -2218,6 +2183,10 @@ void QPlainTextEdit::inputMethodEvent(QInputMethodEvent *e)
}
#endif
d->sendControlEvent(e);
+ const bool emptyEvent = e->preeditString().isEmpty() && e->commitString().isEmpty()
+ && e->attributes().isEmpty();
+ if (emptyEvent)
+ return;
ensureCursorVisible();
}
@@ -2242,25 +2211,29 @@ QVariant QPlainTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant a
{
Q_D(const QPlainTextEdit);
switch (query) {
- case Qt::ImHints:
- case Qt::ImInputItemClipRectangle:
+ case Qt::ImEnabled:
+ return isEnabled() && !isReadOnly();
+ case Qt::ImHints:
+ case Qt::ImInputItemClipRectangle:
return QWidget::inputMethodQuery(query);
+ case Qt::ImReadOnly:
+ return isReadOnly();
default:
break;
}
const QPointF offset = contentOffset();
- switch (argument.type()) {
- case QVariant::RectF:
+ switch (argument.userType()) {
+ case QMetaType::QRectF:
argument = argument.toRectF().translated(-offset);
break;
- case QVariant::PointF:
+ case QMetaType::QPointF:
argument = argument.toPointF() - offset;
break;
- case QVariant::Rect:
+ case QMetaType::QRect:
argument = argument.toRect().translated(-offset.toPoint());
break;
- case QVariant::Point:
+ case QMetaType::QPoint:
argument = argument.toPoint() - offset;
break;
default:
@@ -2268,14 +2241,14 @@ QVariant QPlainTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant a
}
const QVariant v = d->control->inputMethodQuery(query, argument);
- switch (v.type()) {
- case QVariant::RectF:
+ switch (v.userType()) {
+ case QMetaType::QRectF:
return v.toRectF().translated(offset);
- case QVariant::PointF:
+ case QMetaType::QPointF:
return v.toPointF() + offset;
- case QVariant::Rect:
+ case QMetaType::QRect:
return v.toRect().translated(offset.toPoint());
- case QVariant::Point:
+ case QMetaType::QPoint:
return v.toPoint() + offset.toPoint();
default:
break;
@@ -2313,6 +2286,7 @@ void QPlainTextEdit::showEvent(QShowEvent *)
d->showCursorOnInitialShow = false;
ensureCursorVisible();
}
+ d->adjustScrollbars();
}
/*! \reimp
@@ -2321,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;
}
}
@@ -2491,32 +2474,18 @@ void QPlainTextEdit::setOverwriteMode(bool overwrite)
d->control->setOverwriteMode(overwrite);
}
-#if QT_DEPRECATED_SINCE(5, 10)
-/*!
- \property QPlainTextEdit::tabStopWidth
- \brief the tab stop width in pixels
- \deprecated in Qt 5.10. Use tabStopDistance instead.
-
- By default, this property contains a value of 80.
-*/
-
-int QPlainTextEdit::tabStopWidth() const
-{
- return qRound(tabStopDistance());
-}
-
-void QPlainTextEdit::setTabStopWidth(int width)
-{
- setTabStopDistance(width);
-}
-#endif
-
/*!
\property QPlainTextEdit::tabStopDistance
\brief the tab stop distance in pixels
\since 5.10
- By default, this property contains a value of 80.
+ By default, this property contains a value of 80 pixels.
+
+ Do not set a value less than the \l {QFontMetrics::}{horizontalAdvance()}
+ of the QChar::VisualTabCharacter character, otherwise the tab-character
+ will be drawn incompletely.
+
+ \sa QTextOption::ShowTabsAndSpaces, QTextDocument::defaultTextOption
*/
qreal QPlainTextEdit::tabStopDistance() const
@@ -2634,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)
@@ -2819,7 +2788,7 @@ void QPlainTextEdit::setLineWrapMode(LineWrapMode wrap)
d->lineWrap = wrap;
d->updateDefaultTextOption();
d->relayoutDocument();
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
ensureCursorVisible();
}
@@ -2905,7 +2874,7 @@ void QPlainTextEdit::setCenterOnScroll(bool enabled)
if (enabled == d->centerOnScroll)
return;
d->centerOnScroll = enabled;
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
}
@@ -2922,38 +2891,20 @@ bool QPlainTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
}
/*!
- \fn bool QPlainTextEdit::find(const QRegExp &exp, QTextDocument::FindFlags options)
-
- \since 5.3
- \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 QRegExp::caseSensitivity instead.
-
- Returns \c true if a match was found and changes the cursor to select the match;
- otherwise returns \c false.
-*/
-#ifndef QT_NO_REGEXP
-bool QPlainTextEdit::find(const QRegExp &exp, QTextDocument::FindFlags options)
-{
- Q_D(QPlainTextEdit);
- return d->control->find(exp, options);
-}
-#endif
-
-/*!
\fn bool QPlainTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
\since 5.13
\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)
@@ -3054,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) {
@@ -3081,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 a5945d649a..89a4d3ab04 100644
--- a/src/widgets/widgets/qplaintextedit.h
+++ b/src/widgets/widgets/qplaintextedit.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPLAINTEXTEDIT_H
#define QPLAINTEXTEDIT_H
@@ -74,12 +38,10 @@ class Q_WIDGETS_EXPORT QPlainTextEdit : public QAbstractScrollArea
Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
Q_PROPERTY(QString plainText READ toPlainText WRITE setPlainText NOTIFY textChanged USER true)
Q_PROPERTY(bool overwriteMode READ overwriteMode WRITE setOverwriteMode)
-#if QT_DEPRECATED_SINCE(5, 10)
- Q_PROPERTY(int tabStopWidth READ tabStopWidth WRITE setTabStopWidth)
-#endif
Q_PROPERTY(qreal tabStopDistance READ tabStopDistance WRITE setTabStopDistance)
Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
+ Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags
+ WRITE setTextInteractionFlags)
Q_PROPERTY(int blockCount READ blockCount)
Q_PROPERTY(int maximumBlockCount READ maximumBlockCount WRITE setMaximumBlockCount)
Q_PROPERTY(bool backgroundVisible READ backgroundVisible WRITE setBackgroundVisible)
@@ -147,9 +109,6 @@ public:
bool centerOnScroll() const;
bool find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
-#ifndef QT_NO_REGEXP
- bool find(const QRegExp &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
-#endif
#if QT_CONFIG(regularexpression)
bool find(const QRegularExpression &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#endif
@@ -174,11 +133,6 @@ public:
bool overwriteMode() const;
void setOverwriteMode(bool overwrite);
-#if QT_DEPRECATED_SINCE(5, 10)
- QT_DEPRECATED int tabStopWidth() const;
- QT_DEPRECATED void setTabStopWidth(int width);
-#endif
-
qreal tabStopDistance() const;
void setTabStopDistance(qreal distance);
@@ -286,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_textChanged())
- 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 534f0d4681..9ca1cdcc67 100644
--- a/src/widgets/widgets/qplaintextedit_p.h
+++ b/src/widgets/widgets/qplaintextedit_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPLAINTEXTEDIT_P_H
#define QPLAINTEXTEDIT_P_H
@@ -68,6 +32,8 @@
#include "private/qwidgettextcontrol_p.h"
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(textedit);
QT_BEGIN_NAMESPACE
@@ -120,14 +86,14 @@ public:
QPlainTextEditPrivate();
void init(const QString &txt = QString());
- void _q_repaintContents(const QRectF &contentsRect);
- void _q_textChanged();
+ 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();
@@ -143,25 +109,29 @@ public:
void updateDefaultTextOption();
- QPlainTextEditControl *control;
-
- bool tabChangesFocus;
-
QBasicTimer autoScrollTimer;
+#ifdef QT_KEYPAD_NAVIGATION
+ QBasicTimer deleteAllTimer;
+#endif
QPoint autoScrollDragPos;
+ QString placeholderText;
- QPlainTextEdit::LineWrapMode lineWrap;
- QTextOption::WrapMode wordWrap;
+ QPlainTextEditControl *control = nullptr;
+ qreal topLineFracture = 0; // for non-int sized fonts
+ qreal pageUpDownLastCursorY = 0;
+ QPlainTextEdit::LineWrapMode lineWrap = QPlainTextEdit::WidgetWidth;
+ QTextOption::WrapMode wordWrap = QTextOption::WrapAtWordBoundaryOrAnywhere;
+ int originalOffsetY = 0;
+ int topLine = 0;
+ uint tabChangesFocus : 1;
uint showCursorOnInitialShow : 1;
uint backgroundVisible : 1;
uint centerOnScroll : 1;
uint inDrag : 1;
uint clickCausedFocus : 1;
- uint placeholderVisible : 1;
-
- int topLine;
- qreal topLineFracture; // for non-int sized fonts
+ uint pageUpDownLastCursorYIsValid : 1;
+ uint placeholderTextShown : 1;
void setTopLine(int visualTopLine, int dx = 0);
void setTopBlock(int newTopBlock, int newTopLine, int dx = 0);
@@ -174,19 +144,13 @@ public:
void append(const QString &text, Qt::TextFormat format = Qt::AutoText);
- qreal pageUpDownLastCursorY;
- bool pageUpDownLastCursorYIsValid;
-
-
-#ifdef QT_KEYPAD_NAVIGATION
- QBasicTimer deleteAllTimer;
-#endif
-
- void _q_cursorPositionChanged();
- void _q_modificationChanged(bool);
-
- int originalOffsetY;
- QString placeholderText;
+ 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/qprogressbar.cpp b/src/widgets/widgets/qprogressbar.cpp
index 04241fda09..79cdecd22a 100644
--- a/src/widgets/widgets/qprogressbar.cpp
+++ b/src/widgets/widgets/qprogressbar.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qprogressbar.h"
@@ -45,13 +9,15 @@
#include <qstylepainter.h>
#include <qstyleoption.h>
#include <private/qwidget_p.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include <qaccessible.h>
#endif
#include <limits.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
class QProgressBarPrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QProgressBar)
@@ -89,7 +55,7 @@ QProgressBarPrivate::QProgressBarPrivate()
void QProgressBarPrivate::initDefaultFormat()
{
if (defaultFormat)
- format = QLatin1String("%p") + locale.percent();
+ format = "%p"_L1 + locale.percent();
}
void QProgressBarPrivate::init()
@@ -107,6 +73,8 @@ void QProgressBarPrivate::resetLayoutItemMargins()
{
Q_Q(QProgressBar);
QStyleOptionProgressBar option;
+ // ### It seems like this can be called directly from the constructor which should be avoided
+ // ### if possible, since we will not call a possible re-implemented version
q->initStyleOption(&option);
setLayoutItemMargins(QStyle::SE_ProgressBarLayoutItem, &option);
}
@@ -133,7 +101,6 @@ void QProgressBar::initStyleOption(QStyleOptionProgressBar *option) const
option->textAlignment = d->alignment;
option->textVisible = d->textVisible;
option->text = text();
- option->orientation = d->orientation; // ### Qt 6: remove this member from QStyleOptionProgressBar
option->invertedAppearance = d->invertedAppearance;
option->bottomToTop = d->textDirection == QProgressBar::BottomToTop;
}
@@ -151,10 +118,9 @@ bool QProgressBarPrivate::repaintRequired() const
const auto totalSteps = qint64(maximum) - minimum;
if (textVisible) {
- if ((format.contains(QLatin1String("%v"))))
+ if (format.contains("%v"_L1))
return true;
- if ((format.contains(QLatin1String("%p"))
- && valueDifference >= qAbs(totalSteps / 100)))
+ if (format.contains("%p"_L1) && valueDifference >= qAbs(totalSteps / 100))
return true;
}
@@ -200,7 +166,7 @@ bool QProgressBarPrivate::repaintRequired() const
example, when using QNetworkAccessManager to download items when
they are unable to determine the size of the item being downloaded.
- \sa QProgressDialog, {fowler}{GUI Design Handbook: Progress Indicator}
+ \sa QProgressDialog
*/
/*!
@@ -317,7 +283,7 @@ void QProgressBar::setValue(int value)
return;
d->value = value;
emit valueChanged(value);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (isVisible()) {
QAccessibleValueChangeEvent event(this, value);
QAccessible::updateAccessibility(&event);
@@ -421,8 +387,8 @@ QSize QProgressBar::sizeHint() const
QStyleOptionProgressBar opt;
initStyleOption(&opt);
int cw = style()->pixelMetric(QStyle::PM_ProgressBarChunkWidth, &opt, this);
- QSize size = QSize(qMax(9, cw) * 7 + fm.horizontalAdvance(QLatin1Char('0')) * 4, fm.height() + 8);
- if (opt.orientation == Qt::Vertical)
+ QSize size = QSize(qMax(9, cw) * 7 + fm.horizontalAdvance(u'0') * 4, fm.height() + 8);
+ if (!(opt.state & QStyle::State_Horizontal))
size = size.transposed();
return style()->sizeFromContents(QStyle::CT_ProgressBar, &opt, size, this);
}
@@ -467,19 +433,19 @@ QString QProgressBar::text() const
QString result = d->format;
QLocale locale = d->locale; // Omit group separators for compatibility with previous versions that were non-localized.
locale.setNumberOptions(locale.numberOptions() | QLocale::OmitGroupSeparator);
- result.replace(QLatin1String("%m"), locale.toString(totalSteps));
- result.replace(QLatin1String("%v"), locale.toString(d->value));
+ result.replace("%m"_L1, locale.toString(totalSteps));
+ result.replace("%v"_L1, locale.toString(d->value));
// If max and min are equal and we get this far, it means that the
// progress bar has one step and that we are on that step. Return
// 100% here in order to avoid division by zero further down.
if (totalSteps == 0) {
- result.replace(QLatin1String("%p"), locale.toString(100));
+ result.replace("%p"_L1, locale.toString(100));
return result;
}
const auto progress = static_cast<int>((qint64(d->value) - d->minimum) * 100.0 / totalSteps);
- result.replace(QLatin1String("%p"), locale.toString(progress));
+ result.replace("%p"_L1, locale.toString(progress));
return result;
}
diff --git a/src/widgets/widgets/qprogressbar.h b/src/widgets/widgets/qprogressbar.h
index ec9686068c..96b2993ec2 100644
--- a/src/widgets/widgets/qprogressbar.h
+++ b/src/widgets/widgets/qprogressbar.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPROGRESSBAR_H
#define QPROGRESSBAR_H
@@ -111,7 +75,7 @@ Q_SIGNALS:
protected:
bool event(QEvent *e) override;
void paintEvent(QPaintEvent *) override;
- void initStyleOption(QStyleOptionProgressBar *option) const;
+ virtual void initStyleOption(QStyleOptionProgressBar *option) const;
private:
Q_DECLARE_PRIVATE(QProgressBar)
diff --git a/src/widgets/widgets/qpushbutton.cpp b/src/widgets/widgets/qpushbutton.cpp
index b0d3ba51f9..c180a08d62 100644
--- a/src/widgets/widgets/qpushbutton.cpp
+++ b/src/widgets/widgets/qpushbutton.cpp
@@ -1,46 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qapplication.h"
#include "qbitmap.h"
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
#if QT_CONFIG(dialog)
#include <private/qdialog_p.h>
#endif
@@ -62,7 +24,7 @@
#include "qdialogbuttonbox.h"
#endif
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
@@ -173,7 +135,7 @@ QT_BEGIN_NAMESPACE
and other API, and QPushButton provides GUI logic.
See QAbstractButton for more information about the API.
- \sa QToolButton, QRadioButton, QCheckBox, {fowler}{GUI Design Handbook: Push Button}
+ \sa QToolButton, QRadioButton, QCheckBox
*/
/*!
@@ -332,6 +294,8 @@ void QPushButton::initStyleOption(QStyleOptionButton *option) const
option->state |= QStyle::State_On;
if (!d->flat && !d->down)
option->state |= QStyle::State_Raised;
+ if (underMouse() && hasMouseTracking())
+ option->state.setFlag(QStyle::State_MouseOver, d->hovering);
option->text = d->text;
option->icon = d->icon;
option->iconSize = iconSize();
@@ -352,7 +316,7 @@ void QPushButton::setAutoDefault(bool enable)
bool QPushButton::autoDefault() const
{
Q_D(const QPushButton);
- if(d->autoDefault == QPushButtonPrivate::Auto)
+ if (d->autoDefault == QPushButtonPrivate::Auto)
return ( d->dialogParent() != nullptr );
return d->autoDefault;
}
@@ -370,7 +334,7 @@ void QPushButton::setDefault(bool enable)
}
#endif
update();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessible::State s;
s.defaultButton = true;
QAccessibleStateChangeEvent event(this, s);
@@ -418,17 +382,16 @@ QSize QPushButton::sizeHint() const
s = QStringLiteral("XXXX");
QFontMetrics fm = fontMetrics();
QSize sz = fm.size(Qt::TextShowMnemonic, s);
- if(!empty || !w)
+ if (!empty || !w)
w += sz.width();
- if(!empty || !h)
+ if (!empty || !h)
h = qMax(h, sz.height());
opt.rect.setSize(QSize(w, h)); // PM_MenuButtonIndicator depends on the height
#if QT_CONFIG(menu)
if (menu())
w += style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &opt, this);
#endif
- d->sizeHint = (style()->sizeFromContents(QStyle::CT_PushButton, &opt, QSize(w, h), this).
- expandedTo(QApplication::globalStrut()));
+ d->sizeHint = style()->sizeFromContents(QStyle::CT_PushButton, &opt, QSize(w, h), this);
return d->sizeHint;
}
@@ -509,6 +472,38 @@ void QPushButton::focusOutEvent(QFocusEvent *e)
#endif
}
+/*!
+ \reimp
+*/
+void QPushButton::mouseMoveEvent(QMouseEvent *e)
+{
+ Q_D(QPushButton);
+
+ if (testAttribute(Qt::WA_Hover)) {
+ bool hit = false;
+ if (underMouse())
+ hit = hitButton(e->position().toPoint());
+
+ if (hit != d->hovering) {
+ update(rect());
+ d->hovering = hit;
+ }
+ }
+
+ QAbstractButton::mouseMoveEvent(e);
+}
+
+/*!
+ \reimp
+*/
+bool QPushButton::hitButton(const QPoint &pos) const
+{
+ QStyleOptionButton option;
+ initStyleOption(&option);
+ const QRect bevel = style()->subElementRect(QStyle::SE_PushButtonBevel, &option, this);
+ return bevel.contains(pos);
+}
+
#if QT_CONFIG(menu)
/*!
Associates the popup menu \a menu with this push button. This
@@ -530,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());
@@ -567,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)
@@ -580,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()
@@ -612,7 +605,7 @@ QPoint QPushButtonPrivate::adjustedMenuPosition()
QPoint globalPos = q->mapToGlobal(rect.topLeft());
int x = globalPos.x();
int y = globalPos.y();
- const QRect availableGeometry = QDesktopWidgetPrivate::availableGeometry(q);
+ const QRect availableGeometry = QWidgetPrivate::availableScreenGeometry(q, q->mapToGlobal(rect.center()));
if (horizontal) {
if (globalPos.y() + rect.height() + menuSize.height() <= availableGeometry.bottom()) {
y += rect.height();
@@ -634,6 +627,13 @@ QPoint QPushButtonPrivate::adjustedMenuPosition()
#endif // QT_CONFIG(menu)
+void QPushButtonPrivate::init()
+{
+ Q_Q(QPushButton);
+ q->setAttribute(Qt::WA_MacShowFocusRect);
+ resetLayoutItemMargins();
+}
+
void QPushButtonPrivate::resetLayoutItemMargins()
{
Q_Q(QPushButton);
diff --git a/src/widgets/widgets/qpushbutton.h b/src/widgets/widgets/qpushbutton.h
index b02ba63d07..3c420b5313 100644
--- a/src/widgets/widgets/qpushbutton.h
+++ b/src/widgets/widgets/qpushbutton.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPUSHBUTTON_H
#define QPUSHBUTTON_H
@@ -93,17 +57,14 @@ protected:
void keyPressEvent(QKeyEvent *) override;
void focusInEvent(QFocusEvent *) override;
void focusOutEvent(QFocusEvent *) override;
- void initStyleOption(QStyleOptionButton *option) const;
+ void mouseMoveEvent(QMouseEvent *) override;
+ virtual void initStyleOption(QStyleOptionButton *option) const;
+ 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 439b6e35d6..0817589baf 100644
--- a/src/widgets/widgets/qpushbutton_p.h
+++ b/src/widgets/widgets/qpushbutton_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QPUSHBUTTON_P_H
#define QPUSHBUTTON_P_H
@@ -43,6 +7,8 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "private/qabstractbutton_p.h"
+#include <QtCore/qpointer.h>
+
QT_REQUIRE_CONFIG(pushbutton);
//
@@ -69,19 +35,21 @@ public:
QPushButtonPrivate()
: QAbstractButtonPrivate(QSizePolicy::PushButton), autoDefault(Auto),
- defaultButton(false), flat(false), menuOpen(false), lastAutoDefault(false) {}
+ defaultButton(false), flat(false), menuOpen(false), hovering(false),
+ lastAutoDefault(false)
+ {}
- inline void init() { resetLayoutItemMargins(); }
+ void init();
static QPushButtonPrivate* get(QPushButton *b) { return b->d_func(); }
#if QT_CONFIG(menu)
QPoint adjustedMenuPosition();
#endif
void resetLayoutItemMargins();
- void _q_popupPressed();
+ void popupPressed();
#if QT_CONFIG(dialog)
QDialog *dialogParent() const;
#else
- QDialog *dialogParent() const { return 0; };
+ QDialog *dialogParent() const { return nullptr; }
#endif
QPointer<QMenu> menu;
@@ -89,6 +57,7 @@ public:
uint defaultButton : 1;
uint flat : 1;
uint menuOpen : 1;
+ uint hovering : 1;
mutable uint lastAutoDefault : 1;
};
diff --git a/src/widgets/widgets/qradiobutton.cpp b/src/widgets/widgets/qradiobutton.cpp
index fd8922ed28..af1bd3f649 100644
--- a/src/widgets/widgets/qradiobutton.cpp
+++ b/src/widgets/widgets/qradiobutton.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qradiobutton.h"
#include "qapplication.h"
@@ -118,8 +82,7 @@ void QRadioButtonPrivate::init()
setDown(), isDown(), autoRepeat(), group(), setAutoRepeat(),
toggle(), pressed(), released(), clicked(), and toggled().
- \sa QPushButton, QToolButton, QCheckBox, {fowler}{GUI Design Handbook: Radio Button},
- {Group Box Example}
+ \sa QPushButton, QToolButton, QCheckBox
*/
@@ -195,8 +158,7 @@ QSize QRadioButton::sizeHint() const
false, text()).size();
if (!opt.icon.isNull())
sz = QSize(sz.width() + opt.iconSize.width() + 4, qMax(sz.height(), opt.iconSize.height()));
- d->sizeHint = (style()->sizeFromContents(QStyle::CT_RadioButton, &opt, sz, this).
- expandedTo(QApplication::globalStrut()));
+ d->sizeHint = style()->sizeFromContents(QStyle::CT_RadioButton, &opt, sz, this);
return d->sizeHint;
}
@@ -227,7 +189,7 @@ void QRadioButton::mouseMoveEvent(QMouseEvent *e)
if (testAttribute(Qt::WA_Hover)) {
bool hit = false;
if (underMouse())
- hit = hitButton(e->pos());
+ hit = hitButton(e->position().toPoint());
if (hit != d->hovering) {
update();
diff --git a/src/widgets/widgets/qradiobutton.h b/src/widgets/widgets/qradiobutton.h
index c6b5ddce84..7a59b186d1 100644
--- a/src/widgets/widgets/qradiobutton.h
+++ b/src/widgets/widgets/qradiobutton.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QRADIOBUTTON_H
#define QRADIOBUTTON_H
@@ -68,7 +32,7 @@ protected:
bool hitButton(const QPoint &) const override;
void paintEvent(QPaintEvent *) override;
void mouseMoveEvent(QMouseEvent *) override;
- void initStyleOption(QStyleOptionButton *button) const;
+ virtual void initStyleOption(QStyleOptionButton *button) const;
private:
diff --git a/src/widgets/widgets/qrubberband.cpp b/src/widgets/widgets/qrubberband.cpp
index af730f8023..e00f739ca7 100644
--- a/src/widgets/widgets/qrubberband.cpp
+++ b/src/widgets/widgets/qrubberband.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qbitmap.h"
#include "qevent.h"
diff --git a/src/widgets/widgets/qrubberband.h b/src/widgets/widgets/qrubberband.h
index c683c24a18..76d60b642b 100644
--- a/src/widgets/widgets/qrubberband.h
+++ b/src/widgets/widgets/qrubberband.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QRUBBERBAND_H
#define QRUBBERBAND_H
@@ -79,7 +43,7 @@ protected:
void showEvent(QShowEvent *) override;
void resizeEvent(QResizeEvent *) override;
void moveEvent(QMoveEvent *) override;
- void initStyleOption(QStyleOptionRubberBand *option) const;
+ virtual void initStyleOption(QStyleOptionRubberBand *option) const;
private:
Q_DECLARE_PRIVATE(QRubberBand)
diff --git a/src/widgets/widgets/qscrollarea.cpp b/src/widgets/widgets/qscrollarea.cpp
index ce08e3439a..efbf4da07f 100644
--- a/src/widgets/widgets/qscrollarea.cpp
+++ b/src/widgets/widgets/qscrollarea.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qscrollarea.h"
#include "private/qscrollarea_p.h"
@@ -127,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
*/
@@ -196,7 +156,23 @@ void QScrollAreaPrivate::updateScrollBars()
if (resizable) {
if ((widget->layout() ? widget->layout()->hasHeightForWidth() : widget->sizePolicy().hasHeightForWidth())) {
QSize p_hfw = p.expandedTo(min).boundedTo(max);
- int h = widget->heightForWidth( p_hfw.width() );
+ int h = widget->heightForWidth(p_hfw.width());
+ // If the height we calculated requires a vertical scrollbar,
+ // then we need to constrain the width and calculate the height again,
+ // otherwise we end up flipping the scrollbar on and off all the time.
+ if (vbarpolicy == Qt::ScrollBarAsNeeded) {
+ int vbarWidth = vbar->sizeHint().width();
+ QSize m_hfw = m.expandedTo(min).boundedTo(max);
+ // is there any point in searching?
+ if (widget->heightForWidth(m_hfw.width() - vbarWidth) <= m.height()) {
+ while (h > m.height() && vbarWidth) {
+ --vbarWidth;
+ --m_hfw.rwidth();
+ h = widget->heightForWidth(m_hfw.width());
+ }
+ }
+ max = QSize(m_hfw.width(), qMax(m_hfw.height(), h));
+ }
min = QSize(p_hfw.width(), qMax(p_hfw.height(), h));
}
}
@@ -490,14 +466,14 @@ void QScrollArea::ensureWidgetVisible(QWidget *childWidget, int xmargin, int yma
if (focusRect.width() > visibleRect.width())
d->hbar->setValue(focusRect.center().x() - d->viewport->width() / 2);
else if (focusRect.right() > visibleRect.right())
- d->hbar->setValue(focusRect.right() - d->viewport->width());
+ d->hbar->setValue(focusRect.right() - d->viewport->width() + 1);
else if (focusRect.left() < visibleRect.left())
d->hbar->setValue(focusRect.left());
if (focusRect.height() > visibleRect.height())
d->vbar->setValue(focusRect.center().y() - d->viewport->height() / 2);
else if (focusRect.bottom() > visibleRect.bottom())
- d->vbar->setValue(focusRect.bottom() - d->viewport->height());
+ d->vbar->setValue(focusRect.bottom() - d->viewport->height() + 1);
else if (focusRect.top() < visibleRect.top())
d->vbar->setValue(focusRect.top());
}
diff --git a/src/widgets/widgets/qscrollarea.h b/src/widgets/widgets/qscrollarea.h
index 6d252821c5..7486a121ea 100644
--- a/src/widgets/widgets/qscrollarea.h
+++ b/src/widgets/widgets/qscrollarea.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSCROLLAREA_H
#define QSCROLLAREA_H
diff --git a/src/widgets/widgets/qscrollarea_p.h b/src/widgets/widgets/qscrollarea_p.h
index 26335285a4..a599fa8c36 100644
--- a/src/widgets/widgets/qscrollarea_p.h
+++ b/src/widgets/widgets/qscrollarea_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSCROLLAREA_P_H
#define QSCROLLAREA_P_H
@@ -56,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 2ce1d50c86..789cffba99 100644
--- a/src/widgets/widgets/qscrollbar.cpp
+++ b/src/widgets/widgets/qscrollbar.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qapplication.h"
#include "qcursor.h"
@@ -44,12 +8,16 @@
#include "qscrollbar.h"
#include "qstyle.h"
#include "qstyleoption.h"
+#include "qstylepainter.h"
#if QT_CONFIG(menu)
#include "qmenu.h"
#endif
+
#include <QtCore/qelapsedtimer.h>
+#include <QtCore/qpointer.h>
+
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
#include <limits.h>
@@ -175,7 +143,7 @@ QT_BEGIN_NAMESPACE
\li Up/Down move a vertical scroll bar by one single step.
\li PageUp moves up one page.
\li PageDown moves down one page.
- \li Home moves to the start (mininum).
+ \li Home moves to the start (minimum).
\li End moves to the end (maximum).
\endlist
@@ -187,7 +155,7 @@ QT_BEGIN_NAMESPACE
Most GUI styles use the pageStep() value to calculate the size of the
slider.
- \sa QScrollArea, QSlider, QDial, QSpinBox, {fowler}{GUI Design Handbook: Scroll Bar}, {Sliders Example}
+ \sa QScrollArea, QSlider, QDial, QSpinBox, {Sliders Example}
*/
bool QScrollBarPrivate::updateHoverControl(const QPoint &pos)
@@ -224,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();
@@ -235,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();
@@ -319,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;
}
@@ -376,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);
@@ -448,8 +422,7 @@ QSize QScrollBar::sizeHint() const
else
size = QSize(scrollBarExtent, scrollBarExtent * 2 + scrollBarSliderMin);
- return style()->sizeFromContents(QStyle::CT_ScrollBar, &opt, size, this)
- .expandedTo(QApplication::globalStrut());
+ return style()->sizeFromContents(QStyle::CT_ScrollBar, &opt, size, this);
}
/*!\reimp */
@@ -469,14 +442,19 @@ bool QScrollBar::event(QEvent *event)
case QEvent::HoverLeave:
case QEvent::HoverMove:
if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d_func()->updateHoverControl(he->pos());
+ 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();
}
@@ -526,7 +504,7 @@ void QScrollBar::wheelEvent(QWheelEvent *event)
void QScrollBar::paintEvent(QPaintEvent *)
{
Q_D(QScrollBar);
- QPainter p(this);
+ QStylePainter p(this);
QStyleOptionSlider opt;
initStyleOption(&opt);
opt.subControls = QStyle::SC_All;
@@ -537,7 +515,7 @@ void QScrollBar::paintEvent(QPaintEvent *)
} else {
opt.activeSubControls = (QStyle::SubControl)d->hoverControl;
}
- style()->drawComplexControl(QStyle::CC_ScrollBar, &opt, &p, this);
+ p.drawComplexControl(QStyle::CC_ScrollBar, opt);
}
/*!
@@ -554,18 +532,19 @@ void QScrollBar::mousePressEvent(QMouseEvent *e)
nullptr, this);
QStyleOptionSlider opt;
initStyleOption(&opt);
+ opt.keyboardModifiers = e->modifiers();
if (d->maximum == d->minimum // no range
|| (e->buttons() & (~e->button())) // another button was clicked before
- || !(e->button() == Qt::LeftButton || (midButtonAbsPos && e->button() == Qt::MidButton)))
+ || !(e->button() == Qt::LeftButton || (midButtonAbsPos && e->button() == Qt::MiddleButton)))
return;
- d->pressedControl = style()->hitTestComplexControl(QStyle::CC_ScrollBar, &opt, e->pos(), this);
+ d->pressedControl = style()->hitTestComplexControl(QStyle::CC_ScrollBar, &opt, e->position().toPoint(), this);
d->pointerOutsidePressedControl = false;
QRect sr = style()->subControlRect(QStyle::CC_ScrollBar, &opt,
QStyle::SC_ScrollBarSlider, this);
- QPoint click = e->pos();
+ QPoint click = e->position().toPoint();
QPoint pressValue = click - sr.center() + sr.topLeft();
d->pressValue = d->orientation == Qt::Horizontal ? d->pixelPosToRangeValue(pressValue.x()) :
d->pixelPosToRangeValue(pressValue.y());
@@ -576,12 +555,12 @@ void QScrollBar::mousePressEvent(QMouseEvent *e)
if ((d->pressedControl == QStyle::SC_ScrollBarAddPage
|| d->pressedControl == QStyle::SC_ScrollBarSubPage)
- && ((midButtonAbsPos && e->button() == Qt::MidButton)
+ && ((midButtonAbsPos && e->button() == Qt::MiddleButton)
|| (style()->styleHint(QStyle::SH_ScrollBar_LeftClickAbsolutePosition, &opt, this)
&& e->button() == Qt::LeftButton))) {
int sliderLength = HORIZONTAL ? sr.width() : sr.height();
- setSliderPosition(d->pixelPosToRangeValue((HORIZONTAL ? e->pos().x()
- : e->pos().y()) - sliderLength / 2));
+ setSliderPosition(d->pixelPosToRangeValue((HORIZONTAL ? e->position().toPoint().x()
+ : e->position().toPoint().y()) - sliderLength / 2));
d->pressedControl = QStyle::SC_ScrollBarSlider;
d->clickOffset = sliderLength / 2;
}
@@ -632,18 +611,18 @@ void QScrollBar::mouseMoveEvent(QMouseEvent *e)
QStyleOptionSlider opt;
initStyleOption(&opt);
if (!(e->buttons() & Qt::LeftButton
- || ((e->buttons() & Qt::MidButton)
+ || ((e->buttons() & Qt::MiddleButton)
&& style()->styleHint(QStyle::SH_ScrollBar_MiddleClickAbsolutePosition, &opt, this))))
return;
if (d->pressedControl == QStyle::SC_ScrollBarSlider) {
- QPoint click = e->pos();
+ QPoint click = e->position().toPoint();
int newPosition = d->pixelPosToRangeValue((HORIZONTAL ? click.x() : click.y()) -d->clickOffset);
int m = style()->pixelMetric(QStyle::PM_MaximumDragDistance, &opt, this);
if (m >= 0) {
QRect r = rect();
r.adjust(-m, -m, m, m);
- if (! r.contains(e->pos()))
+ if (! r.contains(e->position().toPoint()))
newPosition = d->snapBackPosition;
}
setSliderPosition(newPosition);
@@ -651,7 +630,7 @@ void QScrollBar::mouseMoveEvent(QMouseEvent *e)
if (style()->styleHint(QStyle::SH_ScrollBar_RollBetweenButtons, &opt, this)
&& d->pressedControl & (QStyle::SC_ScrollBarAddLine | QStyle::SC_ScrollBarSubLine)) {
- QStyle::SubControl newSc = style()->hitTestComplexControl(QStyle::CC_ScrollBar, &opt, e->pos(), this);
+ QStyle::SubControl newSc = style()->hitTestComplexControl(QStyle::CC_ScrollBar, &opt, e->position().toPoint(), this);
if (newSc == d->pressedControl && !d->pointerOutsidePressedControl)
return; // nothing to do
if (newSc & (QStyle::SC_ScrollBarAddLine | QStyle::SC_ScrollBarSubLine)) {
@@ -668,7 +647,7 @@ void QScrollBar::mouseMoveEvent(QMouseEvent *e)
// stop scrolling when the mouse pointer leaves a control
// similar to push buttons
QRect pr = style()->subControlRect(QStyle::CC_ScrollBar, &opt, d->pressedControl, this);
- if (pr.contains(e->pos()) == d->pointerOutsidePressedControl) {
+ if (pr.contains(e->position().toPoint()) == d->pointerOutsidePressedControl) {
if ((d->pointerOutsidePressedControl = !d->pointerOutsidePressedControl)) {
d->pointerOutsidePressedControl = true;
setRepeatAction(SliderNoAction);
diff --git a/src/widgets/widgets/qscrollbar.h b/src/widgets/widgets/qscrollbar.h
index 171195fd24..9fd8f617ab 100644
--- a/src/widgets/widgets/qscrollbar.h
+++ b/src/widgets/widgets/qscrollbar.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSCROLLBAR_H
#define QSCROLLBAR_H
@@ -76,7 +40,7 @@ protected:
#ifndef QT_NO_CONTEXTMENU
void contextMenuEvent(QContextMenuEvent *) override;
#endif
- void initStyleOption(QStyleOptionSlider *option) const;
+ virtual void initStyleOption(QStyleOptionSlider *option) const;
private:
diff --git a/src/widgets/widgets/qscrollbar_p.h b/src/widgets/widgets/qscrollbar_p.h
index 8693495c6f..1c8d07608d 100644
--- a/src/widgets/widgets/qscrollbar_p.h
+++ b/src/widgets/widgets/qscrollbar_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSCROLLBAR_P_H
#define QSCROLLBAR_P_H
diff --git a/src/widgets/widgets/qsizegrip.cpp b/src/widgets/widgets/qsizegrip.cpp
index 2a4b4a0ad4..2500983450 100644
--- a/src/widgets/widgets/qsizegrip.cpp
+++ b/src/widgets/widgets/qsizegrip.cpp
@@ -1,59 +1,25 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qsizegrip.h"
#include "qapplication.h"
#include "qevent.h"
-#include "qpainter.h"
+#include "qstylepainter.h"
#include "qwindow.h"
#include <qpa/qplatformwindow.h>
#include "qstyle.h"
#include "qstyleoption.h"
#include "qlayout.h"
#include "qdebug.h"
-#include <QDesktopWidget>
#include <private/qwidget_p.h>
-#include <private/qdesktopwidget_p.h>
+#include "private/qapplication_p.h"
+#include <qpa/qplatformtheme.h>
#include <QtWidgets/qabstractscrollarea.h>
+#include <QtCore/qpointer.h>
+
QT_BEGIN_NAMESPACE
static QWidget *qt_sizegrip_topLevelWidget(QWidget* w)
@@ -109,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;
@@ -173,6 +139,10 @@ Qt::Corner QSizeGripPrivate::corner() const
On some platforms the size grip automatically hides itself when the
window is shown full screen or maximised.
+ \note On macOS, size grips are no longer part of the human interface
+ guideline, and won't show unless used in a QMdiSubWindow. Set another
+ style on size grips that you want to be visible in main windows.
+
\table 50%
\row \li \inlineimage fusion-statusbar-sizegrip.png Screenshot of a Fusion style size grip
\li A size grip widget at the bottom-right corner of a main window, shown in the
@@ -229,9 +199,8 @@ QSizeGrip::~QSizeGrip()
QSize QSizeGrip::sizeHint() const
{
QStyleOption opt(0);
- opt.init(this);
- return (style()->sizeFromContents(QStyle::CT_SizeGrip, &opt, QSize(13, 13), this).
- expandedTo(QApplication::globalStrut()));
+ opt.initFrom(this);
+ return style()->sizeFromContents(QStyle::CT_SizeGrip, &opt, QSize(13, 13), this);
}
/*!
@@ -245,11 +214,11 @@ void QSizeGrip::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
Q_D(QSizeGrip);
- QPainter painter(this);
+ QStylePainter painter(this);
QStyleOptionSizeGrip opt;
- opt.init(this);
+ opt.initFrom(this);
opt.corner = d->m_corner;
- style()->drawControl(QStyle::CE_SizeGrip, &opt, &painter, this);
+ painter.drawControl(QStyle::CE_SizeGrip, opt);
}
/*!
@@ -260,6 +229,29 @@ void QSizeGrip::paintEvent(QPaintEvent *event)
parameter.
*/
+static Qt::Edges edgesFromCorner(Qt::Corner corner)
+{
+ switch (corner) {
+ case Qt::TopLeftCorner: return Qt::TopEdge | Qt::LeftEdge;
+ case Qt::TopRightCorner: return Qt::TopEdge | Qt::RightEdge;
+ case Qt::BottomLeftCorner: return Qt::BottomEdge | Qt::LeftEdge;
+ case Qt::BottomRightCorner: return Qt::BottomEdge | Qt::RightEdge;
+ }
+ return Qt::Edges{};
+}
+
+static bool usePlatformSizeGrip(const QWidget *tlw)
+{
+ const QString &platformName = QGuiApplication::platformName();
+ if (platformName.contains(u"xcb")) // ### FIXME QTBUG-69716
+ return false;
+ if (tlw->testAttribute(Qt::WA_TranslucentBackground)
+ && platformName == u"windows") {
+ return false; // QTBUG-90628, flicker when using translucency
+ }
+ return true;
+}
+
void QSizeGrip::mousePressEvent(QMouseEvent * e)
{
if (e->button() != Qt::LeftButton) {
@@ -269,7 +261,7 @@ void QSizeGrip::mousePressEvent(QMouseEvent * e)
Q_D(QSizeGrip);
QWidget *tlw = qt_sizegrip_topLevelWidget(this);
- d->p = e->globalPos();
+ d->p = e->globalPosition().toPoint();
d->gotMousePress = true;
d->r = tlw->geometry();
@@ -279,10 +271,11 @@ void QSizeGrip::mousePressEvent(QMouseEvent * e)
&& tlw->windowHandle()
&& !(tlw->windowFlags() & Qt::X11BypassWindowManagerHint)
&& !tlw->testAttribute(Qt::WA_DontShowOnScreen)
- && !tlw->hasHeightForWidth()) {
+ && !tlw->hasHeightForWidth()
+ && usePlatformSizeGrip(tlw)) {
QPlatformWindow *platformWindow = tlw->windowHandle()->handle();
- const QPoint topLevelPos = mapTo(tlw, e->pos());
- d->m_platformSizeGrip = platformWindow && platformWindow->startSystemResize(topLevelPos, d->m_corner);
+ const Qt::Edges edges = edgesFromCorner(d->m_corner);
+ d->m_platformSizeGrip = platformWindow->startSystemResize(edges);
}
if (d->m_platformSizeGrip)
@@ -292,8 +285,12 @@ void QSizeGrip::mousePressEvent(QMouseEvent * e)
QRect availableGeometry;
bool hasVerticalSizeConstraint = true;
bool hasHorizontalSizeConstraint = true;
- if (tlw->isWindow())
- availableGeometry = QDesktopWidgetPrivate::availableGeometry(tlw);
+ if (tlw->isWindow()) {
+ if (QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::InteractiveResizeAcrossScreens).toBool())
+ availableGeometry = tlw->screen()->availableVirtualGeometry();
+ else
+ availableGeometry = QWidgetPrivate::availableScreenGeometry(tlw);
+ }
else {
const QWidget *tlwParent = tlw->parentWidget();
// Check if tlw is inside QAbstractScrollArea/QScrollArea.
@@ -362,7 +359,7 @@ void QSizeGrip::mouseMoveEvent(QMouseEvent * e)
if (!d->gotMousePress || tlw->testAttribute(Qt::WA_WState_ConfigPending))
return;
- QPoint np(e->globalPos());
+ QPoint np(e->globalPosition().toPoint());
// Don't extend beyond the available geometry; bound to dyMax and dxMax.
QSize ns;
@@ -454,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/qsizegrip.h b/src/widgets/widgets/qsizegrip.h
index 5285ffdfb8..c69b83e5d5 100644
--- a/src/widgets/widgets/qsizegrip.h
+++ b/src/widgets/widgets/qsizegrip.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSIZEGRIP_H
#define QSIZEGRIP_H
diff --git a/src/widgets/widgets/qslider.cpp b/src/widgets/widgets/qslider.cpp
index 161e4ba27a..e39521a2e9 100644
--- a/src/widgets/widgets/qslider.cpp
+++ b/src/widgets/widgets/qslider.cpp
@@ -1,44 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qslider.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
#include "qapplication.h"
@@ -46,6 +10,7 @@
#include "qpainter.h"
#include "qstyle.h"
#include "qstyleoption.h"
+#include "qstylepainter.h"
#include "private/qapplication_p.h"
#include "private/qabstractslider_p.h"
#include "qdebug.h"
@@ -91,6 +56,8 @@ void QSliderPrivate::resetLayoutItemMargins()
{
Q_Q(QSlider);
QStyleOptionSlider opt;
+ // ### This is (also) reached from the ctor which is unfortunate since a possible
+ // ### re-implementation of initStyleOption is then not called.
q->initStyleOption(&opt);
setLayoutItemMargins(QStyle::SE_SliderLayoutItem, &opt);
}
@@ -153,6 +120,13 @@ void QSlider::initStyleOption(QStyleOptionSlider *option) const
option->pageStep = d->pageStep;
if (d->orientation == Qt::Horizontal)
option->state |= QStyle::State_Horizontal;
+
+ if (d->pressedControl) {
+ option->activeSubControls = d->pressedControl;
+ option->state |= QStyle::State_Sunken;
+ } else {
+ option->activeSubControls = d->hoverControl;
+ }
}
bool QSliderPrivate::updateHoverControl(const QPoint &pos)
@@ -250,11 +224,11 @@ QStyle::SubControl QSliderPrivate::newHoverControl(const QPoint &pos)
\li Up/Down move a vertical slider by one single step.
\li PageUp moves up one page.
\li PageDown moves down one page.
- \li Home moves to the start (mininum).
+ \li Home moves to the start (minimum).
\li End moves to the end (maximum).
\endlist
- \sa QScrollBar, QSpinBox, QDial, {fowler}{GUI Design Handbook: Slider}, {Sliders Example}
+ \sa QScrollBar, QSpinBox, QDial, {Sliders Example}
*/
@@ -308,21 +282,15 @@ QSlider::~QSlider()
void QSlider::paintEvent(QPaintEvent *)
{
Q_D(QSlider);
- QPainter p(this);
+ QStylePainter p(this);
QStyleOptionSlider opt;
initStyleOption(&opt);
opt.subControls = QStyle::SC_SliderGroove | QStyle::SC_SliderHandle;
if (d->tickPosition != NoTicks)
opt.subControls |= QStyle::SC_SliderTickmarks;
- if (d->pressedControl) {
- opt.activeSubControls = d->pressedControl;
- opt.state |= QStyle::State_Sunken;
- } else {
- opt.activeSubControls = d->hoverControl;
- }
- style()->drawComplexControl(QStyle::CC_Slider, &opt, &p, this);
+ p.drawComplexControl(QStyle::CC_Slider, opt);
}
/*!
@@ -338,7 +306,7 @@ bool QSlider::event(QEvent *event)
case QEvent::HoverLeave:
case QEvent::HoverMove:
if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d->updateHoverControl(he->pos());
+ d->updateHoverControl(he->position().toPoint());
break;
case QEvent::StyleChange:
case QEvent::MacSizeChange:
@@ -372,7 +340,7 @@ void QSlider::mousePressEvent(QMouseEvent *ev)
const QPoint center = sliderRect.center() - sliderRect.topLeft();
// to take half of the slider off for the setSliderPosition call we use the center - topLeft
- setSliderPosition(d->pixelPosToRangeValue(d->pick(ev->pos() - center)));
+ setSliderPosition(d->pixelPosToRangeValue(d->pick(ev->position().toPoint() - center)));
triggerAction(SliderMove);
setRepeatAction(SliderNoAction);
d->pressedControl = QStyle::SC_SliderHandle;
@@ -381,11 +349,11 @@ void QSlider::mousePressEvent(QMouseEvent *ev)
QStyleOptionSlider opt;
initStyleOption(&opt);
d->pressedControl = style()->hitTestComplexControl(QStyle::CC_Slider,
- &opt, ev->pos(), this);
+ &opt, ev->position().toPoint(), this);
SliderAction action = SliderNoAction;
if (d->pressedControl == QStyle::SC_SliderGroove) {
const QRect sliderRect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
- int pressValue = d->pixelPosToRangeValue(d->pick(ev->pos() - sliderRect.center() + sliderRect.topLeft()));
+ int pressValue = d->pixelPosToRangeValue(d->pick(ev->position().toPoint() - sliderRect.center() + sliderRect.topLeft()));
d->pressValue = pressValue;
if (pressValue > d->value)
action = SliderPageStepAdd;
@@ -406,7 +374,7 @@ void QSlider::mousePressEvent(QMouseEvent *ev)
initStyleOption(&opt);
setRepeatAction(SliderNoAction);
QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
- d->clickOffset = d->pick(ev->pos() - sr.topLeft());
+ d->clickOffset = d->pick(ev->position().toPoint() - sr.topLeft());
update(sr);
setSliderDown(true);
}
@@ -423,9 +391,7 @@ void QSlider::mouseMoveEvent(QMouseEvent *ev)
return;
}
ev->accept();
- int newPosition = d->pixelPosToRangeValue(d->pick(ev->pos()) - d->clickOffset);
- QStyleOptionSlider opt;
- initStyleOption(&opt);
+ int newPosition = d->pixelPosToRangeValue(d->pick(ev->position().toPoint()) - d->clickOffset);
setSliderPosition(newPosition);
}
@@ -472,7 +438,7 @@ QSize QSlider::sizeHint() const
w = SliderLength;
h = thick;
}
- return style()->sizeFromContents(QStyle::CT_Slider, &opt, QSize(w, h), this).expandedTo(QApplication::globalStrut());
+ return style()->sizeFromContents(QStyle::CT_Slider, &opt, QSize(w, h), this);
}
/*!
diff --git a/src/widgets/widgets/qslider.h b/src/widgets/widgets/qslider.h
index f74f9c8576..9e28928c14 100644
--- a/src/widgets/widgets/qslider.h
+++ b/src/widgets/widgets/qslider.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSLIDER_H
#define QSLIDER_H
@@ -89,7 +53,7 @@ protected:
void mousePressEvent(QMouseEvent *ev) override;
void mouseReleaseEvent(QMouseEvent *ev) override;
void mouseMoveEvent(QMouseEvent *ev) override;
- void initStyleOption(QStyleOptionSlider *option) const;
+ virtual void initStyleOption(QStyleOptionSlider *option) const;
private:
diff --git a/src/widgets/widgets/qspinbox.cpp b/src/widgets/widgets/qspinbox.cpp
index 61ea81c892..73946d54a9 100644
--- a/src/widgets/widgets/qspinbox.cpp
+++ b/src/widgets/widgets/qspinbox.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 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 <private/qabstractspinbox_p.h>
#include <qspinbox.h>
@@ -51,6 +15,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
//#define QSPINBOX_QSBDEBUG
#ifdef QSPINBOX_QSBDEBUG
# define QSBDEBUG qDebug
@@ -166,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}
*/
@@ -191,17 +154,6 @@ public:
The new text is passed in \a text with prefix() and suffix().
*/
-#if QT_DEPRECATED_SINCE(5, 14)
-/*!
- \fn void QSpinBox::valueChanged(const QString &text)
-
- \overload
- \obsolete Use textChanged(QString) instead
-
- The new value is passed in \a text with prefix() and suffix().
-*/
-#endif
-
/*!
Constructs a spin box with 0 as minimum value and 99 as maximum value, a
step value of 1. The value is initially set to 0. It is parented to \a
@@ -529,7 +481,7 @@ QString QSpinBox::textFromValue(int value) const
QString str;
if (d->displayIntegerBase != 10) {
- const QLatin1String prefix = value < 0 ? QLatin1String("-") : QLatin1String();
+ const auto prefix = value < 0 ? "-"_L1 : ""_L1;
str = prefix + QString::number(qAbs(value), d->displayIntegerBase);
} else {
str = locale().toString(value);
@@ -663,17 +615,6 @@ void QSpinBox::fixup(QString &input) const
The new text is passed in \a text with prefix() and suffix().
*/
-#if QT_DEPRECATED_SINCE(5, 14)
-/*!
- \fn void QDoubleSpinBox::valueChanged(const QString &text);
-
- \overload
- \obsolete Use textChanged(QString) instead
-
- The new value is passed in \a text with prefix() and suffix().
-*/
-#endif
-
/*!
Constructs a spin box with 0.0 as minimum value and 99.99 as maximum value,
a step value of 1.0 and a precision of 2 decimal places. The value is
@@ -999,9 +940,8 @@ void QDoubleSpinBox::setDecimals(int decimals)
This virtual function is used by the spin box whenever it needs to
display the given \a value. The default implementation returns a string
containing \a value printed using QWidget::locale().toString(\a value,
- QLatin1Char('f'), decimals()) and will remove the thousand
- separator unless setGroupSeparatorShown() is set. Reimplementations may
- return anything.
+ \c u'f', decimals()) and will remove the thousand separator unless
+ setGroupSeparatorShown() is set. Reimplementations may return anything.
Note: QDoubleSpinBox does not call this function for
specialValueText() and that neither prefix() nor suffix() should
@@ -1081,7 +1021,7 @@ QSpinBoxPrivate::QSpinBoxPrivate()
value = minimum;
displayIntegerBase = 10;
singleStep = QVariant((int)1);
- type = QVariant::Int;
+ type = QMetaType::Int;
}
/*!
@@ -1095,12 +1035,6 @@ void QSpinBoxPrivate::emitSignals(EmitPolicy ep, const QVariant &old)
if (ep != NeverEmit) {
pendingEmit = false;
if (ep == AlwaysEmit || value != old) {
-#if QT_DEPRECATED_SINCE(5, 14)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit q->valueChanged(edit->displayText());
-QT_WARNING_POP
-#endif
emit q->textChanged(edit->displayText());
emit q->valueChanged(value.toInt());
}
@@ -1155,11 +1089,11 @@ QVariant QSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
int num = min;
if (max != min && (copy.isEmpty()
- || (min < 0 && copy == QLatin1String("-"))
- || (max >= 0 && copy == QLatin1String("+")))) {
+ || (min < 0 && copy == "-"_L1)
+ || (max >= 0 && copy == "+"_L1))) {
state = QValidator::Intermediate;
QSBDEBUG() << __FILE__ << __LINE__<< "num is set to" << num;
- } else if (copy.startsWith(QLatin1Char('-')) && min >= 0) {
+ } else if (copy.startsWith(u'-') && min >= 0) {
state = QValidator::Invalid; // special-case -0 will be interpreted as 0 and thus not be invalid with a range from 0-100
} else {
bool ok = false;
@@ -1168,11 +1102,11 @@ QVariant QSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
} else {
num = locale.toInt(copy, &ok);
if (!ok && (max >= 1000 || min <= -1000)) {
- const QChar sep = locale.groupSeparator();
- const QChar doubleSep[2] = {sep, sep};
- if (copy.contains(sep) && !copy.contains(QString(doubleSep, 2))) {
+ const QString sep(locale.groupSeparator());
+ const QString doubleSep = sep + sep;
+ if (copy.contains(sep) && !copy.contains(doubleSep)) {
QString copy2 = copy;
- copy2.remove(locale.groupSeparator());
+ copy2.remove(sep);
num = locale.toInt(copy2, &ok);
}
}
@@ -1238,7 +1172,7 @@ QDoubleSpinBoxPrivate::QDoubleSpinBoxPrivate()
value = minimum;
singleStep = QVariant(1.0);
decimals = 2;
- type = QVariant::Double;
+ type = QMetaType::Double;
}
/*!
@@ -1252,12 +1186,6 @@ void QDoubleSpinBoxPrivate::emitSignals(EmitPolicy ep, const QVariant &old)
if (ep != NeverEmit) {
pendingEmit = false;
if (ep == AlwaysEmit || value != old) {
-#if QT_DEPRECATED_SINCE(5, 14)
-QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED
- emit q->valueChanged(edit->displayText());
-QT_WARNING_POP
-#endif
emit q->textChanged(edit->displayText());
emit q->valueChanged(value.toDouble());
}
@@ -1314,21 +1242,26 @@ QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
const bool plus = max >= 0;
const bool minus = min <= 0;
+ const QString group(locale.groupSeparator());
+ const uint groupUcs = (group.isEmpty() ? 0 :
+ (group.size() > 1 && group.at(0).isHighSurrogate()
+ ? QChar::surrogateToUcs4(group.at(0), group.at(1))
+ : group.at(0).unicode()));
switch (len) {
case 0:
state = max != min ? QValidator::Intermediate : QValidator::Invalid;
goto end;
case 1:
if (copy.at(0) == locale.decimalPoint()
- || (plus && copy.at(0) == QLatin1Char('+'))
- || (minus && copy.at(0) == QLatin1Char('-'))) {
+ || (plus && copy.at(0) == u'+')
+ || (minus && copy.at(0) == u'-')) {
state = QValidator::Intermediate;
goto end;
}
break;
case 2:
if (copy.at(1) == locale.decimalPoint()
- && ((plus && copy.at(0) == QLatin1Char('+')) || (minus && copy.at(0) == QLatin1Char('-')))) {
+ && ((plus && copy.at(0) == u'+') || (minus && copy.at(0) == u'-'))) {
state = QValidator::Intermediate;
goto end;
}
@@ -1336,7 +1269,7 @@ QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
default: break;
}
- if (copy.at(0) == locale.groupSeparator()) {
+ if (groupUcs && copy.startsWith(group)) {
QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
state = QValidator::Invalid;
goto end;
@@ -1352,22 +1285,25 @@ QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
state = QValidator::Invalid;
goto end;
}
- for (int i=dec + 1; i<copy.size(); ++i) {
- if (copy.at(i).isSpace() || copy.at(i) == locale.groupSeparator()) {
+ for (int i = dec + 1; i < copy.size(); ++i) {
+ if (copy.at(i).isSpace()
+ || (groupUcs && QStringView{copy}.sliced(i).startsWith(group))) {
QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
state = QValidator::Invalid;
goto end;
}
}
} else {
- const QChar last = copy.at(len - 1);
- const QChar secondLast = copy.at(len - 2);
- if ((last == locale.groupSeparator() || last.isSpace())
- && (secondLast == locale.groupSeparator() || secondLast.isSpace())) {
+ const QChar last = copy.back();
+ const bool groupEnd = groupUcs && copy.endsWith(group);
+ const QStringView head(copy.constData(), groupEnd ? len - group.size() : len - 1);
+ const QChar secondLast = head.back();
+ if ((groupEnd || last.isSpace())
+ && ((groupUcs && head.endsWith(group)) || secondLast.isSpace())) {
state = QValidator::Invalid;
QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
goto end;
- } else if (last.isSpace() && (!locale.groupSeparator().isSpace() || secondLast.isSpace())) {
+ } else if (last.isSpace() && (!QChar::isSpace(groupUcs) || secondLast.isSpace())) {
state = QValidator::Invalid;
QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
goto end;
@@ -1381,26 +1317,32 @@ QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
QSBDEBUG() << __FILE__ << __LINE__ << locale << copy << num << ok;
if (!ok) {
- if (locale.groupSeparator().isPrint()) {
- if (max < 1000 && min > -1000 && copy.contains(locale.groupSeparator())) {
+ if (QChar::isPrint(groupUcs)) {
+ if (max < 1000 && min > -1000 && groupUcs && copy.contains(group)) {
state = QValidator::Invalid;
QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
goto end;
}
const int len = copy.size();
- for (int i=0; i<len- 1; ++i) {
- if (copy.at(i) == locale.groupSeparator() && copy.at(i + 1) == locale.groupSeparator()) {
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- state = QValidator::Invalid;
- goto end;
+ for (int i = 0; i < len - 1;) {
+ if (groupUcs && QStringView{copy}.sliced(i).startsWith(group)) {
+ if (QStringView(copy).mid(i + group.size()).startsWith(group)) {
+ QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
+ state = QValidator::Invalid;
+ goto end;
+ }
+ i += group.size();
+ } else {
+ i++;
}
}
QString copy2 = copy;
- copy2.remove(locale.groupSeparator());
+ if (groupUcs)
+ copy2.remove(group);
num = locale.toDouble(copy2, &ok);
- QSBDEBUG() << locale.groupSeparator() << num << copy2 << ok;
+ QSBDEBUG() << group << num << copy2 << ok;
if (!ok) {
state = QValidator::Invalid;
diff --git a/src/widgets/widgets/qspinbox.h b/src/widgets/widgets/qspinbox.h
index 762dd4a46a..38affecdbb 100644
--- a/src/widgets/widgets/qspinbox.h
+++ b/src/widgets/widgets/qspinbox.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSPINBOX_H
#define QSPINBOX_H
@@ -107,10 +71,6 @@ public Q_SLOTS:
Q_SIGNALS:
void valueChanged(int);
void textChanged(const QString &);
-#if QT_DEPRECATED_SINCE(5, 14)
- QT_DEPRECATED_X("Use textChanged(QString) instead")
- void valueChanged(const QString &);
-#endif
private:
Q_DISABLE_COPY(QSpinBox)
@@ -173,10 +133,6 @@ public Q_SLOTS:
Q_SIGNALS:
void valueChanged(double);
void textChanged(const QString &);
-#if QT_DEPRECATED_SINCE(5, 14)
- QT_DEPRECATED_X("Use textChanged(QString) instead")
- void valueChanged(const QString &);
-#endif
private:
Q_DISABLE_COPY(QDoubleSpinBox)
diff --git a/src/widgets/widgets/qsplashscreen.cpp b/src/widgets/widgets/qsplashscreen.cpp
index 70f05033ea..fcd09908cd 100644
--- a/src/widgets/widgets/qsplashscreen.cpp
+++ b/src/widgets/widgets/qsplashscreen.cpp
@@ -1,47 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 "qsplashscreen.h"
#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
#include "qpainter.h"
#include "qpixmap.h"
#include "qtextdocument.h"
@@ -71,9 +33,7 @@ public:
inline QSplashScreenPrivate();
- void setPixmap(const QPixmap &p, const QScreen *screen = nullptr);
-
- static const QScreen *screenFor(const QWidget *w);
+ void handlePaintEvent();
};
/*!
@@ -109,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
@@ -154,27 +114,10 @@ QSplashScreen::QSplashScreen(const QPixmap &pixmap, Qt::WindowFlags f)
QSplashScreen::QSplashScreen(QScreen *screen, const QPixmap &pixmap, Qt::WindowFlags f)
: QWidget(*(new QSplashScreenPrivate()), nullptr, Qt::SplashScreen | Qt::FramelessWindowHint | f)
{
- d_func()->setPixmap(pixmap, screen);
-}
-
-#if QT_DEPRECATED_SINCE(5, 15)
-/*!
- \overload
- \obsolete
-
- This function allows you to specify a parent for your splashscreen. The
- typical use for this constructor is if you have a multiple screens and
- prefer to have the splash screen on a different screen than your primary
- one. In that case pass the proper desktop() as the \a parent.
-*/
-QSplashScreen::QSplashScreen(QWidget *parent, const QPixmap &pixmap, Qt::WindowFlags f)
- : QWidget(*new QSplashScreenPrivate, parent, Qt::SplashScreen | Qt::FramelessWindowHint | f)
-{
- // Does an implicit repaint. Explicitly pass parent as QObject::parent()
- // is still 0 here due to QWidget's special handling.
- d_func()->setPixmap(pixmap, QSplashScreenPrivate::screenFor(parent));
+ Q_D(QSplashScreen);
+ d->setScreen(screen);
+ setPixmap(pixmap);
}
-#endif
/*!
Destructor.
@@ -260,28 +203,29 @@ 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);
-#if defined(Q_OS_WINRT)
- WaitForSingleObjectEx(GetCurrentThread(), TimeOutMs, false);
-#elif defined(Q_OS_WIN)
+ QCoreApplication::sendPostedEvents();
+#if defined(Q_OS_WIN)
Sleep(uint(TimeOutMs));
#else
struct timespec ts = { TimeOutMs / 1000, (TimeOutMs % 1000) * 1000 * 1000 };
nanosleep(&ts, nullptr);
#endif
}
- return window->isExposed();
+ return isMapped();
}
/*!
@@ -294,7 +238,7 @@ void QSplashScreen::finish(QWidget *mainWin)
if (mainWin) {
if (!mainWin->windowHandle())
mainWin->createWinId();
- waitForWindowExposed(mainWin->windowHandle());
+ waitForWidgetMapped(mainWin);
}
close();
}
@@ -305,63 +249,16 @@ void QSplashScreen::finish(QWidget *mainWin)
*/
void QSplashScreen::setPixmap(const QPixmap &pixmap)
{
- d_func()->setPixmap(pixmap, QSplashScreenPrivate::screenFor(this));
-}
-
-// In setPixmap(), resize and try to position on a screen according to:
-// 1) If the screen for the given widget is available, use that
-// 2) If a QDesktopScreenWidget is found in the parent hierarchy, use that (see docs on
-// QSplashScreen(QWidget *, QPixmap).
-// 3) If a widget with associated QWindow is found, use that
-// 4) When nothing can be found, try to center it over the cursor
-
-#if QT_DEPRECATED_SINCE(5, 15)
-static inline int screenNumberOf(const QDesktopScreenWidget *dsw)
-{
- auto desktopWidgetPrivate =
- static_cast<QDesktopWidgetPrivate *>(qt_widget_private(QApplication::desktop()));
- return desktopWidgetPrivate->screens.indexOf(const_cast<QDesktopScreenWidget *>(dsw));
-}
-#endif
-
-const QScreen *QSplashScreenPrivate::screenFor(const QWidget *w)
-{
- if (w && w->screen())
- return w->screen();
-
- for (const QWidget *p = w; p !=nullptr ; p = p->parentWidget()) {
-#if QT_DEPRECATED_SINCE(5, 15)
- if (auto dsw = qobject_cast<const QDesktopScreenWidget *>(p))
- return QGuiApplication::screens().value(screenNumberOf(dsw));
-#endif
- if (QWindow *window = p->windowHandle())
- return window->screen();
- }
-
-#if QT_CONFIG(cursor)
- // Note: We could rely on QPlatformWindow::initialGeometry() to center it
- // over the cursor, but not all platforms (namely Android) use that.
- if (QGuiApplication::screens().size() > 1) {
- if (auto screenAtCursor = QGuiApplication::screenAt(QCursor::pos()))
- return screenAtCursor;
- }
-#endif // cursor
- return QGuiApplication::primaryScreen();
-}
-
-void QSplashScreenPrivate::setPixmap(const QPixmap &p, const QScreen *screen)
-{
- Q_Q(QSplashScreen);
+ Q_D(QSplashScreen);
+ d->pixmap = pixmap;
+ setAttribute(Qt::WA_TranslucentBackground, pixmap.hasAlpha());
- pixmap = p;
- q->setAttribute(Qt::WA_TranslucentBackground, pixmap.hasAlpha());
+ const QRect r(QPoint(), pixmap.deviceIndependentSize().toSize());
+ resize(r.size());
- QRect r(QPoint(), pixmap.size() / pixmap.devicePixelRatio());
- q->resize(r.size());
- if (screen)
- q->move(screen->geometry().center() - r.center());
- if (q->isVisible())
- q->repaint();
+ move(screen()->geometry().center() - r.center());
+ if (isVisible())
+ repaint();
}
/*!
@@ -419,17 +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.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/qsplashscreen.h b/src/widgets/widgets/qsplashscreen.h
index 1877493fcf..2670e5c68b 100644
--- a/src/widgets/widgets/qsplashscreen.h
+++ b/src/widgets/widgets/qsplashscreen.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSPLASHSCREEN_H
#define QSPLASHSCREEN_H
@@ -56,10 +20,6 @@ class Q_WIDGETS_EXPORT QSplashScreen : public QWidget
public:
explicit QSplashScreen(const QPixmap &pixmap = QPixmap(), Qt::WindowFlags f = Qt::WindowFlags());
QSplashScreen(QScreen *screen, const QPixmap &pixmap = QPixmap(), Qt::WindowFlags f = Qt::WindowFlags());
-#if QT_DEPRECATED_SINCE(5, 15)
- QT_DEPRECATED_VERSION_X_5_15("Use the constructor taking a QScreen *")
- QSplashScreen(QWidget *parent, const QPixmap &pixmap = QPixmap(), Qt::WindowFlags f = Qt::WindowFlags());
-#endif
virtual ~QSplashScreen();
void setPixmap(const QPixmap &pixmap);
diff --git a/src/widgets/widgets/qsplitter.cpp b/src/widgets/widgets/qsplitter.cpp
index 090aa5cc8b..d0519a56a2 100644
--- a/src/widgets/widgets/qsplitter.cpp
+++ b/src/widgets/widgets/qsplitter.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qsplitter.h"
@@ -53,7 +17,6 @@
#include "qstyleoption.h"
#include "qtextstream.h"
#include "qvarlengtharray.h"
-#include "qvector.h"
#include "private/qlayoutengine_p.h"
#include "private/qsplitter_p.h"
#include "qtimer.h"
@@ -63,6 +26,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
//#define QSPLITTER_DEBUG
QSplitterPrivate::~QSplitterPrivate()
@@ -228,10 +193,9 @@ QSize QSplitterHandle::sizeHint() const
Q_D(const QSplitterHandle);
int hw = d->s->handleWidth();
QStyleOption opt(0);
- opt.init(d->s);
+ opt.initFrom(d->s);
opt.state = QStyle::State_None;
- return parentWidget()->style()->sizeFromContents(QStyle::CT_Splitter, &opt, QSize(hw, hw), d->s)
- .expandedTo(QApplication::globalStrut());
+ return parentWidget()->style()->sizeFromContents(QStyle::CT_Splitter, &opt, QSize(hw, hw), d->s);
}
/*!
@@ -291,10 +255,11 @@ bool QSplitterHandle::event(QEvent *event)
void QSplitterHandle::mouseMoveEvent(QMouseEvent *e)
{
Q_D(QSplitterHandle);
- if (!(e->buttons() & Qt::LeftButton))
+ if (!d->pressed)
return;
- int pos = d->pick(parentWidget()->mapFromGlobal(e->globalPos()))
- - d->mouseOffset;
+
+ const int pos = d->pick(parentWidget()->mapFromGlobal(e->globalPosition().toPoint()))
+ - d->mouseOffset;
if (opaqueResize()) {
moveSplitter(pos);
} else {
@@ -309,7 +274,7 @@ void QSplitterHandle::mousePressEvent(QMouseEvent *e)
{
Q_D(QSplitterHandle);
if (e->button() == Qt::LeftButton) {
- d->mouseOffset = d->pick(e->pos());
+ d->mouseOffset = d->pick(e->position().toPoint());
d->pressed = true;
update();
}
@@ -321,16 +286,18 @@ void QSplitterHandle::mousePressEvent(QMouseEvent *e)
void QSplitterHandle::mouseReleaseEvent(QMouseEvent *e)
{
Q_D(QSplitterHandle);
- if (!opaqueResize() && e->button() == Qt::LeftButton) {
- int pos = d->pick(parentWidget()->mapFromGlobal(e->globalPos()))
- - d->mouseOffset;
+ if (!d->pressed)
+ return;
+
+ if (!opaqueResize()) {
+ const int pos = d->pick(parentWidget()->mapFromGlobal(e->globalPosition().toPoint()))
+ - d->mouseOffset;
d->s->setRubberBand(-1);
moveSplitter(pos);
}
- if (e->button() == Qt::LeftButton) {
- d->pressed = false;
- update();
- }
+
+ d->pressed = false;
+ update();
}
/*!
@@ -394,7 +361,7 @@ void QSplitterPrivate::init()
void QSplitterPrivate::recalc(bool update)
{
Q_Q(QSplitter);
- int n = list.count();
+ int n = list.size();
/*
Splitter handles before the first visible widget or right
before a hidden widget must be hidden.
@@ -441,9 +408,9 @@ void QSplitterPrivate::recalc(bool update)
QSize minS = qSmartMinSize(s->widget);
minl += pick(minS);
- maxl += pick(s->widget->maximumSize());
+ maxl += pick(qSmartMaxSize(s->widget));
mint = qMax(mint, trans(minS));
- int tm = trans(s->widget->maximumSize());
+ int tm = trans(qSmartMaxSize(s->widget));
if (tm > 0)
maxt = qMin(maxt, tm);
}
@@ -484,8 +451,8 @@ void QSplitterPrivate::doResize()
{
Q_Q(QSplitter);
QRect r = q->contentsRect();
- int n = list.count();
- QVector<QLayoutStruct> a(n*2);
+ int n = list.size();
+ QList<QLayoutStruct> a(n * 2);
int i;
bool noStretchFactorsSet = true;
@@ -520,7 +487,7 @@ void QSplitterPrivate::doResize()
a[j].maximumSize = 0;
} else {
a[j].minimumSize = pick(qSmartMinSize(s->widget));
- a[j].maximumSize = pick(s->widget->maximumSize());
+ a[j].maximumSize = pick(qSmartMaxSize(s->widget));
a[j].empty = false;
bool stretch = noStretchFactorsSet;
@@ -582,7 +549,7 @@ void QSplitterPrivate::addContribution(int index, int *min, int *max, bool mayCo
if (mayCollapse || !s->collapsed)
*min += pick(qSmartMinSize(s->widget));
- *max += pick(s->widget->maximumSize());
+ *max += pick(qSmartMaxSize(s->widget));
}
}
@@ -598,7 +565,7 @@ int QSplitterPrivate::findWidgetJustBeforeOrJustAfter(int index, int delta, int
return index;
}
index += delta;
- } while (index >= 0 && index < list.count());
+ } while (index >= 0 && index < list.size());
return -1;
}
@@ -610,7 +577,7 @@ int QSplitterPrivate::findWidgetJustBeforeOrJustAfter(int index, int delta, int
void QSplitterPrivate::getRange(int index, int *farMin, int *min, int *max, int *farMax) const
{
Q_Q(const QSplitter);
- int n = list.count();
+ int n = list.size();
if (index <= 0 || index >= n)
return;
@@ -734,10 +701,15 @@ void QSplitterPrivate::setSizes_helper(const QList<int> &sizes, bool clampNegati
doResize();
}
+/*
+ Used by various methods inserting a widget to find out if we need to show the widget
+ explicitly, which we have to if the splitter is already visible, and if the widget hasn't
+ been explicitly hidden before inserting it.
+*/
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)
@@ -785,7 +757,7 @@ void QSplitterPrivate::setGeo(QSplitterLayoutStruct *sls, int p, int s, bool all
void QSplitterPrivate::doMove(bool backwards, int hPos, int index, int delta, bool mayCollapse,
int *positions, int *widths)
{
- if (index < 0 || index >= list.count())
+ if (index < 0 || index >= list.size())
return;
#ifdef QSPLITTER_DEBUG
@@ -805,7 +777,7 @@ void QSplitterPrivate::doMove(bool backwards, int hPos, int index, int delta, bo
int ws = backwards ? hPos - pick(s->rect.topLeft())
: pick(s->rect.bottomRight()) - hPos -hs + 1;
if (ws > 0 || (!s->collapsed && !mayCollapse)) {
- ws = qMin(ws, pick(w->maximumSize()));
+ ws = qMin(ws, pick(qSmartMaxSize(w)));
ws = qMax(ws, pick(qSmartMinSize(w)));
} else {
ws = 0;
@@ -855,7 +827,7 @@ QSplitterLayoutStruct *QSplitterPrivate::insertWidget(int index, QWidget *w)
Q_Q(QSplitter);
QSplitterLayoutStruct *sls = nullptr;
int i;
- int last = list.count();
+ int last = list.size();
for (i = 0; i < list.size(); ++i) {
QSplitterLayoutStruct *s = list.at(i);
if (s->widget == w) {
@@ -872,7 +844,7 @@ QSplitterLayoutStruct *QSplitterPrivate::insertWidget(int index, QWidget *w)
} else {
sls = new QSplitterLayoutStruct;
QSplitterHandle *newHandle = q->createHandle();
- newHandle->setObjectName(QLatin1String("qt_splithandle_") + w->objectName());
+ newHandle->setObjectName("qt_splithandle_"_L1 + w->objectName());
sls->handle = newHandle;
sls->widget = w;
w->lower();
@@ -1107,7 +1079,7 @@ void QSplitter::resizeEvent(QResizeEvent *)
void QSplitter::addWidget(QWidget *widget)
{
Q_D(QSplitter);
- insertWidget(d->list.count(), widget);
+ insertWidget(d->list.size(), widget);
}
/*!
@@ -1157,7 +1129,7 @@ QWidget *QSplitter::replaceWidget(int index, QWidget *widget)
return nullptr;
}
- if (index < 0 || index >= d->list.count()) {
+ if (index < 0 || index >= d->list.size()) {
qWarning("QSplitter::replaceWidget: Index %d out of range", index);
return nullptr;
}
@@ -1177,7 +1149,7 @@ QWidget *QSplitter::replaceWidget(int index, QWidget *widget)
QBoolBlocker b(d->blockChildAdd);
const QRect geom = current->geometry();
- const bool shouldShow = d->shouldShowWidget(current);
+ const bool wasHidden = current->isHidden();
s->widget = widget;
current->setParent(nullptr);
@@ -1187,14 +1159,15 @@ QWidget *QSplitter::replaceWidget(int index, QWidget *widget)
// should not change. Only set the geometry on the new widget
widget->setGeometry(geom);
widget->lower();
- widget->setVisible(shouldShow);
+ if (wasHidden)
+ widget->hide();
+ else if (d->shouldShowWidget(widget))
+ widget->show();
return current;
}
/*!
- \fn int QSplitter::indexOf(QWidget *widget) const
-
Returns the index in the splitter's layout of the specified \a widget,
or -1 if \a widget is not found. This also works for handles.
@@ -1204,12 +1177,12 @@ QWidget *QSplitter::replaceWidget(int index, QWidget *widget)
\sa count(), widget()
*/
-int QSplitter::indexOf(QWidget *w) const
+int QSplitter::indexOf(QWidget *widget) const
{
Q_D(const QSplitter);
for (int i = 0; i < d->list.size(); ++i) {
QSplitterLayoutStruct *s = d->list.at(i);
- if (s->widget == w || s->handle == w)
+ if (s->widget == widget || s->handle == widget)
return i;
}
return -1;
@@ -1269,7 +1242,7 @@ QWidget *QSplitter::widget(int index) const
int QSplitter::count() const
{
Q_D(const QSplitter);
- return d->list.count();
+ return d->list.size();
}
/*!
@@ -1290,16 +1263,18 @@ int QSplitter::count() const
void QSplitter::childEvent(QChildEvent *c)
{
Q_D(QSplitter);
- if (!c->child()->isWidgetType()) {
- if (Q_UNLIKELY(c->type() == QEvent::ChildAdded && qobject_cast<QLayout *>(c->child())))
- qWarning("Adding a QLayout to a QSplitter is not supported.");
- return;
- }
if (c->added()) {
+ if (!c->child()->isWidgetType()) {
+ if (Q_UNLIKELY(qobject_cast<QLayout *>(c->child())))
+ qWarning("Adding a QLayout to a QSplitter is not supported.");
+ return;
+ }
QWidget *w = static_cast<QWidget*>(c->child());
if (!d->blockChildAdd && !w->isWindow() && !d->findWidget(w))
- d->insertWidget_helper(d->list.count(), w, false);
+ d->insertWidget_helper(d->list.size(), w, false);
} else if (c->polished()) {
+ if (!c->child()->isWidgetType())
+ return;
QWidget *w = static_cast<QWidget*>(c->child());
if (!d->blockChildAdd && !w->isWindow() && d->shouldShowWidget(w))
w->show();
@@ -1339,7 +1314,7 @@ void QSplitter::setRubberBand(int pos)
QBoolBlocker b(d->blockChildAdd);
d->rubberBand = new QRubberBand(QRubberBand::Line, this);
// For accessibility to identify this special widget.
- d->rubberBand->setObjectName(QLatin1String("qt_rubberband"));
+ d->rubberBand->setObjectName("qt_rubberband"_L1);
}
const QRect newGeom = d->orient == Qt::Horizontal ? QRect(QPoint(pos + hw / 2 - rBord, r.y()), QSize(2 * rBord, r.height()))
@@ -1381,7 +1356,7 @@ bool QSplitter::event(QEvent *e)
}
/*!
- \fn QSplitter::splitterMoved(int pos, int index)
+ \fn void QSplitter::splitterMoved(int pos, int index)
This signal is emitted when the splitter handle at a particular \a
index has been moved to position \a pos.
@@ -1408,10 +1383,10 @@ void QSplitter::moveSplitter(int pos, int index)
{
Q_D(QSplitter);
QSplitterLayoutStruct *s = d->list.at(index);
- int farMin;
- int min;
- int max;
- int farMax;
+ int farMin = 0;
+ int min = 0;
+ int max = 0;
+ int farMax = 0;
#ifdef QSPLITTER_DEBUG
int debugp = pos;
@@ -1423,15 +1398,15 @@ void QSplitter::moveSplitter(int pos, int index)
qDebug() << "QSplitter::moveSplitter" << debugp << index << "adjusted" << pos << "oldP" << oldP;
#endif
- QVarLengthArray<int, 32> poss(d->list.count());
- QVarLengthArray<int, 32> ws(d->list.count());
+ QVarLengthArray<int, 32> poss(d->list.size());
+ QVarLengthArray<int, 32> ws(d->list.size());
bool upLeft;
d->doMove(false, pos, index, +1, (d->collapsible(s) && (pos > max)), poss.data(), ws.data());
d->doMove(true, pos, index - 1, +1, (d->collapsible(index - 1) && (pos < min)), poss.data(), ws.data());
upLeft = (pos < oldP);
- int wid, delta, count = d->list.count();
+ int wid, delta, count = d->list.size();
if (upLeft) {
wid = 0;
delta = 1;
@@ -1475,7 +1450,10 @@ void QSplitter::getRange(int index, int *min, int *max) const
int QSplitter::closestLegalPosition(int pos, int index)
{
Q_D(QSplitter);
- int x, i, n, u;
+ int x = 0;
+ int i = 0;
+ int n = 0;
+ int u = 0;
return d->adjustPos(pos, index, &u, &n, &i, &x);
}
@@ -1656,7 +1634,7 @@ void QSplitter::setHandleWidth(int width)
void QSplitter::changeEvent(QEvent *ev)
{
Q_D(QSplitter);
- if(ev->type() == QEvent::StyleChange)
+ if (ev->type() == QEvent::StyleChange)
d->updateHandles();
QFrame::changeEvent(ev);
}
@@ -1680,6 +1658,7 @@ QByteArray QSplitter::saveState() const
int version = 1;
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
+ stream.setVersion(QDataStream::Qt_5_0);
stream << qint32(SplitterMagic);
stream << qint32(version);
@@ -1721,6 +1700,7 @@ bool QSplitter::restoreState(const QByteArray &state)
int version = 1;
QByteArray sd = state;
QDataStream stream(&sd, QIODevice::ReadOnly);
+ stream.setVersion(QDataStream::Qt_5_0);
QList<int> list;
bool b;
qint32 i;
@@ -1771,7 +1751,7 @@ bool QSplitter::restoreState(const QByteArray &state)
void QSplitter::setStretchFactor(int index, int stretch)
{
Q_D(QSplitter);
- if (index <= -1 || index >= d->list.count())
+ if (index <= -1 || index >= d->list.size())
return;
QWidget *widget = d->list.at(index)->widget;
@@ -1781,40 +1761,6 @@ void QSplitter::setStretchFactor(int index, int stretch)
widget->setSizePolicy(sp);
}
-
-#if QT_DEPRECATED_SINCE(5, 13)
-/*!
- \relates QSplitter
- \obsolete
-
- Use \a ts << \a{splitter}.saveState() instead.
-*/
-
-QTextStream& operator<<(QTextStream& ts, const QSplitter& splitter)
-{
- ts << splitter.saveState() << Qt::endl;
- return ts;
-}
-
-/*!
- \relates QSplitter
- \obsolete
-
- Use \a ts >> \a{splitter}.restoreState() instead.
-*/
-
-QTextStream& operator>>(QTextStream& ts, QSplitter& splitter)
-{
- QString line = ts.readLine();
- line = line.simplified();
- line.replace(QLatin1Char(' '), QString());
- line = std::move(line).toUpper();
-
- splitter.restoreState(std::move(line).toLatin1());
- return ts;
-}
-#endif
-
QT_END_NAMESPACE
#include "moc_qsplitter.cpp"
diff --git a/src/widgets/widgets/qsplitter.h b/src/widgets/widgets/qsplitter.h
index 658914ae39..96c19be24d 100644
--- a/src/widgets/widgets/qsplitter.h
+++ b/src/widgets/widgets/qsplitter.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSPLITTER_H
#define QSPLITTER_H
@@ -128,12 +92,6 @@ private:
friend class QSplitterHandle;
};
-#if QT_DEPRECATED_SINCE(5, 13)
-QT_DEPRECATED_X("Use QSplitter::saveState() instead")
-Q_WIDGETS_EXPORT QTextStream& operator<<(QTextStream&, const QSplitter&);
-QT_DEPRECATED_X("Use QSplitter::restoreState() instead")
-Q_WIDGETS_EXPORT QTextStream& operator>>(QTextStream&, QSplitter&);
-#endif
class QSplitterHandlePrivate;
class Q_WIDGETS_EXPORT QSplitterHandle : public QWidget
diff --git a/src/widgets/widgets/qsplitter_p.h b/src/widgets/widgets/qsplitter_p.h
index 871406a51d..5d5723a957 100644
--- a/src/widgets/widgets/qsplitter_p.h
+++ b/src/widgets/widgets/qsplitter_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSPLITTER_P_H
#define QSPLITTER_P_H
@@ -54,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 a565d4ab4c..9cecee2ef8 100644
--- a/src/widgets/widgets/qstackedwidget.cpp
+++ b/src/widgets/widgets/qstackedwidget.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstackedwidget.h"
@@ -51,7 +15,6 @@ class QStackedWidgetPrivate : public QFramePrivate
public:
QStackedWidgetPrivate():layout(nullptr){}
QStackedLayout *layout;
- bool blockChildAdd;
};
/*!
@@ -135,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);
}
/*!
@@ -254,7 +219,7 @@ void QStackedWidget::setCurrentWidget(QWidget *widget)
\sa currentIndex(), widget()
*/
-int QStackedWidget::indexOf(QWidget *widget) const
+int QStackedWidget::indexOf(const QWidget *widget) const
{
return d_func()->layout->indexOf(widget);
}
diff --git a/src/widgets/widgets/qstackedwidget.h b/src/widgets/widgets/qstackedwidget.h
index 5508f905d4..49f2794ff4 100644
--- a/src/widgets/widgets/qstackedwidget.h
+++ b/src/widgets/widgets/qstackedwidget.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTACKEDWIDGET_H
#define QSTACKEDWIDGET_H
@@ -66,7 +30,7 @@ public:
QWidget *currentWidget() const;
int currentIndex() const;
- int indexOf(QWidget *) const;
+ int indexOf(const QWidget *) const;
QWidget *widget(int) const;
int count() const;
diff --git a/src/widgets/widgets/qstatusbar.cpp b/src/widgets/widgets/qstatusbar.cpp
index 4a1fef8b65..e398f52ac4 100644
--- a/src/widgets/widgets/qstatusbar.cpp
+++ b/src/widgets/widgets/qstatusbar.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qstatusbar.h"
@@ -54,7 +18,7 @@
#include "qmainwindow.h"
#endif
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
@@ -69,22 +33,27 @@ class QStatusBarPrivate : public QWidgetPrivate
public:
QStatusBarPrivate() {}
+ enum ItemCategory
+ {
+ Normal,
+ Permanent
+ };
+
struct SBItem {
- SBItem(QWidget* widget, int stretch, bool permanent)
- : s(stretch), w(widget), p(permanent) {}
- int s;
- QWidget * w;
- bool p;
+ QWidget *widget = nullptr;
+ int stretch = 0;
+ ItemCategory category = Normal;
+ bool isPermanent() const { return category == Permanent; }
};
- QList<SBItem *> items;
+ QList<SBItem> items;
QString tempItem;
- QBoxLayout * box;
- QTimer * timer;
+ QBoxLayout *box;
+ QTimer *timer;
#if QT_CONFIG(sizegrip)
- QSizeGrip * resizer;
+ QSizeGrip *resizer;
bool showSizeGrip;
#endif
@@ -94,8 +63,8 @@ public:
{
int i = items.size() - 1;
for (; i >= 0; --i) {
- SBItem *item = items.at(i);
- if (!(item && item->p))
+ const SBItem &item = items.at(i);
+ if (!item.isPermanent())
break;
}
return i;
@@ -122,7 +91,7 @@ public:
QRect QStatusBarPrivate::messageRect() const
{
Q_Q(const QStatusBar);
- bool rtl = q->layoutDirection() == Qt::RightToLeft;
+ const bool rtl = q->layoutDirection() == Qt::RightToLeft;
int left = 6;
int right = q->width() - 12;
@@ -136,18 +105,13 @@ QRect QStatusBarPrivate::messageRect() const
}
#endif
- for (int i=0; i<items.size(); ++i) {
- QStatusBarPrivate::SBItem* item = items.at(i);
- if (!item)
+ for (const auto &item : items) {
+ if (item.isPermanent() && item.widget->isVisible()) {
+ if (rtl)
+ left = qMax(left, item.widget->x() + item.widget->width() + 2);
+ else
+ right = qMin(right, item.widget->x() - 2);
break;
- if (item->p && item->w->isVisible()) {
- if (item->p) {
- if (rtl)
- left = qMax(left, item->w->x() + item->w->width() + 2);
- else
- right = qMin(right, item->w->x() - 2);
- }
- break;
}
}
return QRect(left, 0, right-left, q->height());
@@ -187,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
@@ -215,8 +179,7 @@ QRect QStatusBarPrivate::messageRect() const
\image fusion-statusbar-sizegrip.png A status bar shown in the Fusion widget style
- \sa QMainWindow, QStatusTipEvent, {fowler}{GUI Design Handbook:
- Status Bar}, {Application Example}
+ \sa QMainWindow, QStatusTipEvent
*/
@@ -246,9 +209,6 @@ QStatusBar::QStatusBar(QWidget * parent)
*/
QStatusBar::~QStatusBar()
{
- Q_D(QStatusBar);
- while (!d->items.isEmpty())
- delete d->items.takeFirst();
}
@@ -298,7 +258,7 @@ int QStatusBar::insertWidget(int index, QWidget *widget, int stretch)
return -1;
Q_D(QStatusBar);
- QStatusBarPrivate::SBItem* item = new QStatusBarPrivate::SBItem(widget, stretch, false);
+ QStatusBarPrivate::SBItem item{widget, stretch, QStatusBarPrivate::Normal};
int idx = d->indexToLastNonPermanentWidget();
if (Q_UNLIKELY(index < 0 || index > d->items.size() || (idx >= 0 && index > idx + 1))) {
@@ -311,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;
@@ -326,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()
*/
@@ -338,7 +298,6 @@ void QStatusBar::addPermanentWidget(QWidget * widget, int stretch)
insertPermanentWidget(d_func()->items.size(), widget, stretch);
}
-
/*!
\since 4.2
@@ -353,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()
*/
@@ -363,7 +322,7 @@ int QStatusBar::insertPermanentWidget(int index, QWidget *widget, int stretch)
return -1;
Q_D(QStatusBar);
- QStatusBarPrivate::SBItem* item = new QStatusBarPrivate::SBItem(widget, stretch, true);
+ QStatusBarPrivate::SBItem item{widget, stretch, QStatusBarPrivate::Permanent};
int idx = d->indexToLastNonPermanentWidget();
if (Q_UNLIKELY(index < 0 || index > d->items.size() || (idx >= 0 && index <= idx))) {
@@ -373,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;
@@ -395,23 +354,10 @@ void QStatusBar::removeWidget(QWidget *widget)
return;
Q_D(QStatusBar);
- bool found = false;
- QStatusBarPrivate::SBItem* item;
- for (int i=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item)
- break;
- if (item->w == widget) {
- d->items.removeAt(i);
- item->w->hide();
- delete item;
- 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.");
@@ -495,25 +441,22 @@ void QStatusBar::reformat()
int maxH = fontMetrics().height();
- int i;
- QStatusBarPrivate::SBItem* item;
- for (i=0,item=nullptr; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item || item->p)
+ qsizetype i;
+ for (i = 0; i < d->items.size(); ++i) {
+ const auto &item = d->items.at(i);
+ if (item.isPermanent())
break;
- l->addWidget(item->w, item->s);
- int itemH = qMin(qSmartMinSize(item->w).height(), item->w->maximumHeight());
+ l->addWidget(item.widget, item.stretch);
+ int itemH = qMin(qSmartMinSize(item.widget).height(), item.widget->maximumHeight());
maxH = qMax(maxH, itemH);
}
l->addStretch(0);
- for (item=nullptr; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item)
- break;
- l->addWidget(item->w, item->s);
- int itemH = qMin(qSmartMinSize(item->w).height(), item->w->maximumHeight());
+ for (; i < d->items.size(); ++i) {
+ const auto &item = d->items.at(i);
+ l->addWidget(item.widget, item.stretch);
+ int itemH = qMin(qSmartMinSize(item.widget).height(), item.widget->maximumHeight());
maxH = qMax(maxH, itemH);
}
#if QT_CONFIG(sizegrip)
@@ -551,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) {
@@ -577,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();
@@ -617,22 +560,20 @@ void QStatusBar::hideOrShow()
Q_D(QStatusBar);
bool haveMessage = !d->tempItem.isEmpty();
- QStatusBarPrivate::SBItem* item = nullptr;
- for (int i=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item || item->p)
+ for (const auto &item : std::as_const(d->items)) {
+ if (item.isPermanent())
break;
- if (haveMessage && item->w->isVisible()) {
- item->w->hide();
- item->w->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- } else if (!haveMessage && !item->w->testAttribute(Qt::WA_WState_ExplicitShowHide)) {
- item->w->show();
+ if (haveMessage && item.widget->isVisible()) {
+ item.widget->hide();
+ item.widget->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
+ } else if (!haveMessage && !item.widget->testAttribute(Qt::WA_WState_ExplicitShowHide)) {
+ item.widget->show();
}
}
emit messageChanged(d->tempItem);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
QAccessibleEvent event(this, QAccessible::NameChanged);
QAccessible::updateAccessibility(&event);
@@ -671,16 +612,15 @@ void QStatusBar::paintEvent(QPaintEvent *event)
opt.initFrom(this);
style()->drawPrimitive(QStyle::PE_PanelStatusBar, &opt, &p, this);
- for (int i=0; i<d->items.size(); ++i) {
- QStatusBarPrivate::SBItem* item = d->items.at(i);
- if (item && item->w->isVisible() && (!haveMessage || item->p)) {
- QRect ir = item->w->geometry().adjusted(-2, -1, 2, 1);
+ for (const auto &item : std::as_const(d->items)) {
+ if (item.widget->isVisible() && (!haveMessage || item.isPermanent())) {
+ QRect ir = item.widget->geometry().adjusted(-2, -1, 2, 1);
if (event->rect().intersects(ir)) {
QStyleOption opt(0);
opt.rect = ir;
opt.palette = palette();
opt.state = QStyle::State_None;
- style()->drawPrimitive(QStyle::PE_FrameStatusBarItem, &opt, &p, item->w);
+ style()->drawPrimitive(QStyle::PE_FrameStatusBarItem, &opt, &p, item.widget);
}
}
}
@@ -706,17 +646,13 @@ bool QStatusBar::event(QEvent *e)
{
Q_D(QStatusBar);
- if (e->type() == QEvent::LayoutRequest
- ) {
+ switch (e->type()) {
+ case QEvent::LayoutRequest: {
// Calculate new strut height and call reformat() if it has changed
int maxH = fontMetrics().height();
- QStatusBarPrivate::SBItem* item = nullptr;
- for (int i=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item)
- break;
- int itemH = qMin(qSmartMinSize(item->w).height(), item->w->maximumHeight());
+ for (const auto &item : std::as_const(d->items)) {
+ const int itemH = qMin(qSmartMinSize(item.widget).height(), item.widget->maximumHeight());
maxH = qMax(maxH, itemH);
}
@@ -729,18 +665,17 @@ bool QStatusBar::event(QEvent *e)
reformat();
else
update();
+ break;
}
- if (e->type() == QEvent::ChildRemoved) {
- QStatusBarPrivate::SBItem* item = nullptr;
- for (int i=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item)
- break;
- if (item->w == ((QChildEvent*)e)->child()) {
+ case QEvent::ChildRemoved:
+ for (int i = 0; i < d->items.size(); ++i) {
+ const auto &item = d->items.at(i);
+ if (item.widget == static_cast<QChildEvent *>(e)->child())
d->items.removeAt(i);
- delete item;
- }
}
+ break;
+ default:
+ break;
}
return QWidget::event(e);
diff --git a/src/widgets/widgets/qstatusbar.h b/src/widgets/widgets/qstatusbar.h
index 2492e8487f..2bf8e0c632 100644
--- a/src/widgets/widgets/qstatusbar.h
+++ b/src/widgets/widgets/qstatusbar.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QSTATUSBAR_H
#define QSTATUSBAR_H
@@ -83,7 +47,6 @@ protected:
void paintEvent(QPaintEvent *) override;
void resizeEvent(QResizeEvent *) override;
- // ### Qt 6: consider making reformat() and hideOrShow() private
void reformat();
void hideOrShow();
bool event(QEvent *) override;
diff --git a/src/widgets/widgets/qtabbar.cpp b/src/widgets/widgets/qtabbar.cpp
index a7b115a1bc..0b463840ae 100644
--- a/src/widgets/widgets/qtabbar.cpp
+++ b/src/widgets/widgets/qtabbar.cpp
@@ -1,49 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "private/qlayoutengine_p.h"
#if QT_CONFIG(itemviews)
#include "qabstractitemdelegate.h"
#endif
#include "qapplication.h"
-#include "qbitmap.h"
-#include "qcursor.h"
#include "qevent.h"
#include "qpainter.h"
#include "qstyle.h"
@@ -52,15 +14,17 @@
#if QT_CONFIG(tabwidget)
#include "qtabwidget.h"
#endif
+#if QT_CONFIG(tooltip)
#include "qtooltip.h"
+#endif
#if QT_CONFIG(whatsthis)
#include "qwhatsthis.h"
#endif
#include "private/qtextengine_p.h"
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
#include <qpa/qplatformnativeinterface.h>
#endif
@@ -70,6 +34,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
namespace {
class CloseButton : public QAbstractButton
{
@@ -81,7 +47,7 @@ public:
QSize sizeHint() const override;
QSize minimumSizeHint() const override
{ return sizeHint(); }
- void enterEvent(QEvent *event) override;
+ void enterEvent(QEnterEvent *event) override;
void leaveEvent(QEvent *event) override;
void paintEvent(QPaintEvent *event) override;
};
@@ -105,17 +71,9 @@ 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_OSX)
+#if defined(Q_OS_MACOS)
Q_Q(QTabBar);
// Extend the unified title and toolbar area to cover the tab bar iff
// 1) the tab bar is in document mode
@@ -137,6 +95,8 @@ void QTabBarPrivate::updateMacBorderMetrics()
}
QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
+ if (!nativeInterface)
+ return;
quintptr identifier = reinterpret_cast<quintptr>(q);
// Set geometry
@@ -170,7 +130,7 @@ void QTabBarPrivate::initBasicStyleOption(QStyleOptionTab *option, int tabIndex)
if (!option || (tabIndex < 0 || tabIndex >= totalTabs))
return;
- const QTabBarPrivate::Tab &tab = tabList.at(tabIndex);
+ const QTabBarPrivate::Tab &tab = *tabList.at(tabIndex);
option->initFrom(q);
option->state &= ~(QStyle::State_HasFocus | QStyle::State_MouseOver);
option->rect = q->tabRect(tabIndex);
@@ -208,7 +168,7 @@ void QTabBarPrivate::initBasicStyleOption(QStyleOptionTab *option, int tabIndex)
option->selectedPosition = QStyleOptionTab::NotAdjacent;
const bool paintBeginning = (tabIndex == firstVisible) || (dragInProgress && tabIndex == pressedIndex + 1);
- const bool paintEnd = (tabIndex == lastVisible - 1) || (dragInProgress && tabIndex == pressedIndex - 1);
+ const bool paintEnd = (tabIndex == lastVisible) || (dragInProgress && tabIndex == pressedIndex - 1);
if (paintBeginning) {
if (paintEnd)
option->position = QStyleOptionTab::OnlyOneTab;
@@ -229,8 +189,7 @@ void QTabBarPrivate::initBasicStyleOption(QStyleOptionTab *option, int tabIndex)
option->cornerWidgets |= QStyleOptionTab::RightCornerWidget;
}
#endif
- if (QStyleOptionTabV4 *optv4 = qstyleoption_cast<QStyleOptionTabV4 *>(option))
- optv4->tabIndex = tabIndex;
+ option->tabIndex = tabIndex;
}
/*!
@@ -316,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
@@ -405,12 +364,16 @@ void QTabBarPrivate::init()
{
Q_Q(QTabBar);
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()) {
@@ -421,7 +384,7 @@ void QTabBarPrivate::init()
#endif
q->setFocusPolicy(Qt::TabFocus);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
leftB->setAccessibleName(QTabBar::tr("Scroll Left"));
rightB->setAccessibleName(QTabBar::tr("Scroll Right"));
#endif
@@ -430,23 +393,13 @@ void QTabBarPrivate::init()
useScrollButtons = !q->style()->styleHint(QStyle::SH_TabBar_PreferNoArrows, nullptr, q);
}
-QTabBarPrivate::Tab *QTabBarPrivate::at(int index)
-{
- return validIndex(index)?&tabList[index]:nullptr;
-}
-
-const QTabBarPrivate::Tab *QTabBarPrivate::at(int index) const
-{
- return validIndex(index)?&tabList[index]:nullptr;
-}
-
int QTabBarPrivate::indexAtPos(const QPoint &p) const
{
Q_Q(const QTabBar);
if (q->tabRect(currentIndex).contains(p))
return currentIndex;
- for (int i = 0; i < tabList.count(); ++i)
- if (tabList.at(i).enabled && q->tabRect(i).contains(p))
+ for (int i = 0; i < tabList.size(); ++i)
+ if (tabList.at(i)->enabled && q->tabRect(i).contains(p))
return i;
return -1;
}
@@ -458,13 +411,12 @@ void QTabBarPrivate::layoutTabs()
QSize size = q->size();
int last, available;
int maxExtent;
- int i;
bool vertTabs = verticalTabs(shape);
int tabChainIndex = 0;
int hiddenTabs = 0;
Qt::Alignment tabAlignment = Qt::Alignment(q->style()->styleHint(QStyle::SH_TabBar_Alignment, nullptr, q));
- QVector<QLayoutStruct> tabChain(tabList.count() + 2);
+ QList<QLayoutStruct> tabChain(tabList.size() + 2);
// We put an empty item at the front and back and set its expansive attribute
// depending on tabAlignment and expanding.
@@ -487,20 +439,21 @@ void QTabBarPrivate::layoutTabs()
int minx = 0;
int x = 0;
int maxHeight = 0;
- for (i = 0; i < tabList.count(); ++i) {
- if (!tabList.at(i).visible) {
+ for (int i = 0; i < tabList.size(); ++i) {
+ const auto tab = tabList.at(i);
+ if (!tab->visible) {
++hiddenTabs;
continue;
}
QSize sz = q->tabSizeHint(i);
- tabList[i].maxRect = QRect(x, 0, sz.width(), sz.height());
+ tab->maxRect = QRect(x, 0, sz.width(), sz.height());
x += sz.width();
maxHeight = qMax(maxHeight, sz.height());
sz = q->minimumTabSizeHint(i);
- tabList[i].minRect = QRect(minx, 0, sz.width(), sz.height());
+ tab->minRect = QRect(minx, 0, sz.width(), sz.height());
minx += sz.width();
tabChain[tabChainIndex].init();
- tabChain[tabChainIndex].sizeHint = tabList.at(i).maxRect.width();
+ tabChain[tabChainIndex].sizeHint = tab->maxRect.width();
tabChain[tabChainIndex].minimumSize = sz.width();
tabChain[tabChainIndex].empty = false;
tabChain[tabChainIndex].expansive = true;
@@ -517,20 +470,21 @@ void QTabBarPrivate::layoutTabs()
int miny = 0;
int y = 0;
int maxWidth = 0;
- for (i = 0; i < tabList.count(); ++i) {
- if (!tabList.at(i).visible) {
+ for (int i = 0; i < tabList.size(); ++i) {
+ auto tab = tabList.at(i);
+ if (!tab->visible) {
++hiddenTabs;
continue;
}
QSize sz = q->tabSizeHint(i);
- tabList[i].maxRect = QRect(0, y, sz.width(), sz.height());
+ tab->maxRect = QRect(0, y, sz.width(), sz.height());
y += sz.height();
maxWidth = qMax(maxWidth, sz.width());
sz = q->minimumTabSizeHint(i);
- tabList[i].minRect = QRect(0, miny, sz.width(), sz.height());
+ tab->minRect = QRect(0, miny, sz.width(), sz.height());
miny += sz.height();
tabChain[tabChainIndex].init();
- tabChain[tabChainIndex].sizeHint = tabList.at(i).maxRect.height();
+ tabChain[tabChainIndex].sizeHint = tab->maxRect.height();
tabChain[tabChainIndex].minimumSize = sz.height();
tabChain[tabChainIndex].empty = false;
tabChain[tabChainIndex].expansive = true;
@@ -551,33 +505,33 @@ void QTabBarPrivate::layoutTabs()
&& (tabAlignment != Qt::AlignRight)
&& (tabAlignment != Qt::AlignJustify);
tabChain[tabChainIndex].empty = true;
- Q_ASSERT(tabChainIndex == tabChain.count() - 1 - hiddenTabs); // add an assert just to make sure.
+ Q_ASSERT(tabChainIndex == tabChain.size() - 1 - hiddenTabs); // add an assert just to make sure.
// Do the calculation
- qGeomCalc(tabChain, 0, tabChain.count(), 0, qMax(available, last), 0);
+ qGeomCalc(tabChain, 0, tabChain.size(), 0, qMax(available, last), 0);
// Use the results
hiddenTabs = 0;
- for (i = 0; i < tabList.count(); ++i) {
- if (!tabList.at(i).visible) {
- tabList[i].rect = QRect();
+ for (int i = 0; i < tabList.size(); ++i) {
+ auto tab = tabList.at(i);
+ if (!tab->visible) {
+ tab->rect = QRect();
++hiddenTabs;
continue;
}
const QLayoutStruct &lstruct = tabChain.at(i + 1 - hiddenTabs);
if (!vertTabs)
- tabList[i].rect.setRect(lstruct.pos, 0, lstruct.size, maxExtent);
+ tab->rect.setRect(lstruct.pos, 0, lstruct.size, maxExtent);
else
- tabList[i].rect.setRect(0, lstruct.pos, maxExtent, lstruct.size);
+ tab->rect.setRect(0, lstruct.pos, maxExtent, lstruct.size);
}
- if (useScrollButtons && tabList.count() && last > available) {
+ if (useScrollButtons && tabList.size() && last > available) {
const QRect scrollRect = normalizedScrollRect(0);
- scrollOffset = -scrollRect.left();
Q_Q(QTabBar);
QStyleOption opt;
- opt.init(q);
+ opt.initFrom(q);
QRect scrollButtonLeftRect = q->style()->subElementRect(QStyle::SE_TabBarScrollLeftButton, &opt, q);
QRect scrollButtonRightRect = q->style()->subElementRect(QStyle::SE_TabBarScrollRightButton, &opt, q);
int scrollButtonWidth = q->style()->pixelMetric(QStyle::PM_TabBarScrollButtonWidth, &opt, q);
@@ -610,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();
}
@@ -630,7 +583,12 @@ QRect QTabBarPrivate::normalizedScrollRect(int index)
// tab bar itself is in a different orientation.
Q_Q(QTabBar);
- QStyleOptionTabV4 opt;
+ // 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();
@@ -656,7 +614,7 @@ QRect QTabBarPrivate::normalizedScrollRect(int index)
}
bool tearTopVisible = index != 0 && topEdge != -scrollOffset;
- bool tearBottomVisible = index != tabList.size() - 1 && bottomEdge != tabList.constLast().rect.bottom() + 1 - scrollOffset;
+ bool tearBottomVisible = index != tabList.size() - 1 && bottomEdge != tabList.constLast()->rect.bottom() + 1 - scrollOffset;
if (tearTopVisible && !tearLeftRect.isNull())
topEdge = tearLeftRect.bottom() + 1;
if (tearBottomVisible && !tearRightRect.isNull())
@@ -687,7 +645,7 @@ QRect QTabBarPrivate::normalizedScrollRect(int index)
}
bool tearLeftVisible = index != 0 && leftEdge != -scrollOffset;
- bool tearRightVisible = index != tabList.size() - 1 && rightEdge != tabList.constLast().rect.right() + 1 - scrollOffset;
+ bool tearRightVisible = index != tabList.size() - 1 && rightEdge != tabList.constLast()->rect.right() + 1 - scrollOffset;
if (tearLeftVisible && !tearLeftRect.isNull())
leftEdge = tearLeftRect.right() + 1;
if (tearRightVisible && !tearRightRect.isNull())
@@ -709,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 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 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());
@@ -754,34 +720,34 @@ void QTabBarPrivate::layoutTab(int index)
Q_Q(QTabBar);
Q_ASSERT(index >= 0);
- Tab &tab = tabList[index];
+ const Tab *tab = tabList.at(index);
bool vertical = verticalTabs(shape);
- if (!(tab.leftWidget || tab.rightWidget))
+ if (!(tab->leftWidget || tab->rightWidget))
return;
- QStyleOptionTabV4 opt;
+ QStyleOptionTab opt;
q->initStyleOption(&opt, index);
- if (tab.leftWidget) {
+ if (tab->leftWidget) {
QRect rect = q->style()->subElementRect(QStyle::SE_TabBarTabLeftButton, &opt, q);
QPoint p = rect.topLeft();
if ((index == pressedIndex) || paintWithOffsets) {
if (vertical)
- p.setY(p.y() + tabList[index].dragOffset);
+ p.setY(p.y() + tab->dragOffset);
else
- p.setX(p.x() + tabList[index].dragOffset);
+ p.setX(p.x() + tab->dragOffset);
}
- tab.leftWidget->move(p);
+ tab->leftWidget->move(p);
}
- if (tab.rightWidget) {
+ if (tab->rightWidget) {
QRect rect = q->style()->subElementRect(QStyle::SE_TabBarTabRightButton, &opt, q);
QPoint p = rect.topLeft();
if ((index == pressedIndex) || paintWithOffsets) {
if (vertical)
- p.setY(p.y() + tab.dragOffset);
+ p.setY(p.y() + tab->dragOffset);
else
- p.setX(p.x() + tab.dragOffset);
+ p.setX(p.x() + tab->dragOffset);
}
- tab.rightWidget->move(p);
+ tab->rightWidget->move(p);
}
}
@@ -801,20 +767,20 @@ void QTabBarPrivate::autoHideTabs()
q->setVisible(q->count() > 1);
}
-void QTabBarPrivate::_q_closeTab()
+void QTabBarPrivate::closeTab()
{
Q_Q(QTabBar);
QObject *object = q->sender();
int tabToClose = -1;
QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition)q->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, q);
- for (int i = 0; i < tabList.count(); ++i) {
+ for (int i = 0; i < tabList.size(); ++i) {
if (closeSide == QTabBar::LeftSide) {
- if (tabList.at(i).leftWidget == object) {
+ if (tabList.at(i)->leftWidget == object) {
tabToClose = i;
break;
}
} else {
- if (tabList.at(i).rightWidget == object) {
+ if (tabList.at(i)->rightWidget == object) {
tabToClose = i;
break;
}
@@ -824,26 +790,29 @@ void QTabBarPrivate::_q_closeTab()
emit q->tabCloseRequested(tabToClose);
}
-void QTabBarPrivate::_q_scrollTabs()
+void QTabBarPrivate::scrollTabs()
{
Q_Q(QTabBar);
const QObject *sender = q->sender();
const bool horizontal = !verticalTabs(shape);
- const QRect scrollRect = normalizedScrollRect();
+ const QRect scrollRect = normalizedScrollRect().translated(scrollOffset, 0);
+
int i = -1;
if (sender == leftB) {
- for (i = tabList.count() - 1; i >= 0; --i) {
- int start = horizontal ? tabList.at(i).rect.left() : tabList.at(i).rect.top();
- if (start < scrollRect.left() + scrollOffset) {
+ for (i = tabList.size() - 1; i >= 0; --i) {
+ int start = horizontal ? tabList.at(i)->rect.left() : tabList.at(i)->rect.top();
+ if (start < scrollRect.left()) {
makeVisible(i);
return;
}
}
} else if (sender == rightB) {
- for (i = 0; i < tabList.count(); ++i) {
- int end = horizontal ? tabList.at(i).rect.right() : tabList.at(i).rect.bottom();
- if (end > scrollRect.right() + scrollOffset) {
+ for (i = 0; i < tabList.size(); ++i) {
+ const auto tabRect = tabList.at(i)->rect;
+ int start = horizontal ? tabRect.left() : tabRect.top();
+ int end = horizontal ? tabRect.right() : tabRect.bottom();
+ if (end > scrollRect.right() && start > scrollOffset) {
makeVisible(i);
return;
}
@@ -858,7 +827,7 @@ void QTabBarPrivate::refresh()
// be safe in case a subclass is also handling move with the tabs
if (pressedIndex != -1
&& movable
- && QGuiApplication::mouseButtons() == Qt::NoButton) {
+ && mouseButtons == Qt::NoButton) {
moveTabFinished(pressedIndex);
if (!validIndex(pressedIndex))
pressedIndex = -1;
@@ -919,7 +888,7 @@ void QTabBar::setShape(Shape shape)
\property QTabBar::drawBase
\brief defines whether or not tab bar should draw its base.
- If true then QTabBar draws a base in relation to the styles overlab.
+ If true then QTabBar draws a base in relation to the styles overlap.
Otherwise only the tabs are drawn.
\sa QStyle::pixelMetric(), QStyle::PM_TabBarBaseOverlap, QStyleOptionTabBarBase
@@ -962,7 +931,7 @@ int QTabBar::addTab(const QIcon& icon, const QString &text)
/*!
Inserts a new tab with text \a text at position \a index. If \a
- index is out of range, the new tab is appened. Returns the new
+ index is out of range, the new tab is appended. Returns the new
tab's index.
*/
int QTabBar::insertTab(int index, const QString &text)
@@ -986,36 +955,44 @@ int QTabBar::insertTab(int index, const QIcon& icon, const QString &text)
{
Q_D(QTabBar);
if (!d->validIndex(index)) {
- index = d->tabList.count();
- d->tabList.append(QTabBarPrivate::Tab(icon, text));
+ index = d->tabList.size();
+ d->tabList.append(new QTabBarPrivate::Tab(icon, text));
} else {
- d->tabList.insert(index, QTabBarPrivate::Tab(icon, text));
+ d->tabList.insert(index, new QTabBarPrivate::Tab(icon, text));
}
#ifndef QT_NO_SHORTCUT
- d->tabList[index].shortcutId = grabShortcut(QKeySequence::mnemonic(text));
+ d->tabList.at(index)->shortcutId = grabShortcut(QKeySequence::mnemonic(text));
#endif
d->firstVisible = qMax(qMin(index, d->firstVisible), 0);
- d->lastVisible = qMax(index, d->lastVisible);
d->refresh();
- if (d->tabList.count() == 1)
+ if (d->tabList.size() == 1)
setCurrentIndex(index);
- else if (index <= d->currentIndex) {
+ else if (index <= d->currentIndex)
++d->currentIndex;
+
+ if (index <= d->lastVisible)
++d->lastVisible;
- }
+ else
+ d->lastVisible = index;
if (d->closeButtonOnTabs) {
- QStyleOptionTabV4 opt;
+ QStyleOptionTab opt;
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);
}
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (d->tabList[i].lastTab >= index)
- ++d->tabList[i].lastTab;
+ for (const auto tab : std::as_const(d->tabList)) {
+ if (tab->lastTab >= index)
+ ++tab->lastTab;
+ }
+
+ if (tabAt(d->mousePosition) == index) {
+ d->hoverIndex = index;
+ d->hoverRect = tabRect(index);
}
tabInserted(index);
@@ -1033,30 +1010,32 @@ void QTabBar::removeTab(int index)
{
Q_D(QTabBar);
if (d->validIndex(index)) {
+ auto removedTab = d->tabList.at(index);
if (d->dragInProgress)
d->moveTabFinished(d->pressedIndex);
#ifndef QT_NO_SHORTCUT
- releaseShortcut(d->tabList.at(index).shortcutId);
+ releaseShortcut(d->tabList.at(index)->shortcutId);
#endif
- if (d->tabList[index].leftWidget) {
- d->tabList[index].leftWidget->hide();
- d->tabList[index].leftWidget->deleteLater();
- d->tabList[index].leftWidget = nullptr;
+ if (removedTab->leftWidget) {
+ removedTab->leftWidget->hide();
+ removedTab->leftWidget->deleteLater();
+ removedTab->leftWidget = nullptr;
}
- if (d->tabList[index].rightWidget) {
- d->tabList[index].rightWidget->hide();
- d->tabList[index].rightWidget->deleteLater();
- d->tabList[index].rightWidget = nullptr;
+ if (removedTab->rightWidget) {
+ removedTab->rightWidget->hide();
+ removedTab->rightWidget->deleteLater();
+ removedTab->rightWidget = nullptr;
}
- int newIndex = d->tabList[index].lastTab;
+ int newIndex = removedTab->lastTab;
d->tabList.removeAt(index);
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (d->tabList[i].lastTab == index)
- d->tabList[i].lastTab = -1;
- if (d->tabList[i].lastTab > index)
- --d->tabList[i].lastTab;
+ delete removedTab;
+ for (auto tab : std::as_const(d->tabList)) {
+ if (tab->lastTab == index)
+ tab->lastTab = -1;
+ if (tab->lastTab > index)
+ --tab->lastTab;
}
d->calculateFirstLastVisible(index, false, true);
@@ -1071,7 +1050,7 @@ void QTabBar::removeTab(int index)
case SelectPreviousTab:
if (newIndex > index)
newIndex--;
- if (d->validIndex(newIndex) && d->tabList.at(newIndex).visible)
+ if (d->validIndex(newIndex) && d->tabList.at(newIndex)->visible)
break;
Q_FALLTHROUGH();
case SelectRightTab:
@@ -1079,8 +1058,6 @@ void QTabBar::removeTab(int index)
break;
case SelectLeftTab:
newIndex = qBound(d->firstVisible, index-1, d->lastVisible);
- if (newIndex < 0)
- newIndex = 0;
break;
default:
break;
@@ -1088,9 +1065,12 @@ void QTabBar::removeTab(int index)
if (d->validIndex(newIndex)) {
// don't loose newIndex's old through setCurrentIndex
- int bump = d->tabList[newIndex].lastTab;
+ int bump = d->tabList.at(newIndex)->lastTab;
setCurrentIndex(newIndex);
- d->tabList[newIndex].lastTab = bump;
+ d->tabList.at(newIndex)->lastTab = bump;
+ } else {
+ // we had a valid current index, but there are no visible tabs left
+ emit currentChanged(-1);
}
} else {
emit currentChanged(-1);
@@ -1100,16 +1080,15 @@ void QTabBar::removeTab(int index)
}
d->refresh();
d->autoHideTabs();
- if (!d->hoverRect.isEmpty()) {
- for (int i = 0; i < d->tabList.count(); ++i) {
- const QRect area = tabRect(i);
- if (area.contains(mapFromGlobal(QCursor::pos()))) {
- d->hoverIndex = i;
- d->hoverRect = area;
- break;
- }
- }
+ if (d->hoverRect.isValid()) {
update(d->hoverRect);
+ d->hoverIndex = tabAt(d->mousePosition);
+ if (d->validIndex(d->hoverIndex)) {
+ d->hoverRect = tabRect(d->hoverIndex);
+ update(d->hoverRect);
+ } else {
+ d->hoverRect = QRect();
+ }
}
tabRemoved(index);
}
@@ -1158,7 +1137,7 @@ bool QTabBar::isTabVisible(int index) const
{
Q_D(const QTabBar);
if (d->validIndex(index))
- return d->tabList.at(index).visible;
+ return d->tabList.at(index)->visible;
return false;
}
@@ -1280,7 +1259,7 @@ void QTabBar::setTabIcon(int index, const QIcon & icon)
}
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
/*!
Sets the tool tip of the tab at position \a index to \a tip.
*/
@@ -1302,7 +1281,7 @@ QString QTabBar::tabToolTip(int index) const
return tab->toolTip;
return QString();
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
#if QT_CONFIG(whatsthis)
/*!
@@ -1423,17 +1402,30 @@ void QTabBar::setCurrentIndex(int index)
Q_D(QTabBar);
if (d->dragInProgress && d->pressedIndex != -1)
return;
+ if (d->currentIndex == index)
+ return;
int oldIndex = d->currentIndex;
- if (d->validIndex(index) && d->currentIndex != index) {
+ if (auto tab = d->at(index)) {
d->currentIndex = index;
+ // If the size hint depends on whether the tab is selected (for instance a style
+ // sheet rule that sets a bold font on the 'selected' tab) then we need to
+ // re-layout the entire tab bar. To minimize the cost, do that only if the
+ // size hint changes for the tab that becomes the current tab (the old current tab
+ // will most certainly do the same). QTBUG-6905
+ if (tabRect(index).size() != tabSizeHint(index))
+ d->layoutTabs();
update();
- d->makeVisible(index);
- d->tabList[index].lastTab = oldIndex;
- if (oldIndex >= 0 && oldIndex < count())
+ if (!isVisible())
+ d->layoutDirty = true;
+ else
+ d->makeVisible(index);
+ if (d->validIndex(oldIndex)) {
+ tab->lastTab = oldIndex;
d->layoutTab(oldIndex);
+ }
d->layoutTab(index);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (QAccessible::isActive()) {
if (hasFocus()) {
QAccessibleEvent focusEvent(this, QAccessible::Focus);
@@ -1486,7 +1478,7 @@ void QTabBar::setIconSize(const QSize &size)
int QTabBar::count() const
{
Q_D(const QTabBar);
- return d->tabList.count();
+ return d->tabList.size();
}
@@ -1498,12 +1490,11 @@ QSize QTabBar::sizeHint() const
if (d->layoutDirty)
const_cast<QTabBarPrivate*>(d)->layoutTabs();
QRect r;
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (d->tabList.at(i).visible)
- r = r.united(d->tabList.at(i).maxRect);
+ for (const auto tab : d->tabList) {
+ if (tab->visible)
+ r = r.united(tab->maxRect);
}
- QSize sz = QApplication::globalStrut();
- return r.size().expandedTo(sz);
+ return r.size();
}
/*!\reimp
@@ -1515,11 +1506,11 @@ QSize QTabBar::minimumSizeHint() const
const_cast<QTabBarPrivate*>(d)->layoutTabs();
if (!d->useScrollButtons) {
QRect r;
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (d->tabList.at(i).visible)
- r = r.united(d->tabList.at(i).minRect);
+ for (const auto tab : d->tabList) {
+ if (tab->visible)
+ r = r.united(tab->minRect);
}
- return r.size().expandedTo(QApplication::globalStrut());
+ return r.size();
}
if (verticalTabs(d->shape))
return QSize(sizeHint().width(), d->rightB->sizeHint().height() * 2 + 75);
@@ -1530,20 +1521,20 @@ QSize QTabBar::minimumSizeHint() const
// Compute the most-elided possible text, for minimumSizeHint
static QString computeElidedText(Qt::TextElideMode mode, const QString &text)
{
- if (text.length() <= 3)
+ if (text.size() <= 3)
return text;
- static const QLatin1String Ellipses("...");
+ static const auto Ellipses = "..."_L1;
QString ret;
switch (mode) {
case Qt::ElideRight:
- ret = text.leftRef(2) + Ellipses;
+ ret = QStringView{text}.left(2) + Ellipses;
break;
case Qt::ElideMiddle:
- ret = text.leftRef(1) + Ellipses + text.rightRef(1);
+ ret = QStringView{text}.left(1) + Ellipses + QStringView{text}.right(1);
break;
case Qt::ElideLeft:
- ret = Ellipses + text.rightRef(2);
+ ret = Ellipses + QStringView{text}.right(2);
break;
case Qt::ElideNone:
ret = text;
@@ -1560,11 +1551,11 @@ static QString computeElidedText(Qt::TextElideMode mode, const QString &text)
QSize QTabBar::minimumTabSizeHint(int index) const
{
Q_D(const QTabBar);
- QTabBarPrivate::Tab &tab = const_cast<QTabBarPrivate::Tab&>(d->tabList[index]);
- QString oldText = tab.text;
- tab.text = computeElidedText(d->elideMode, oldText);
+ QTabBarPrivate::Tab *tab = d->tabList.at(index);
+ QString oldText = tab->text;
+ tab->text = computeElidedText(d->elideMode, oldText);
QSize size = tabSizeHint(index);
- tab.text = oldText;
+ tab->text = oldText;
return size;
}
@@ -1576,9 +1567,9 @@ QSize QTabBar::tabSizeHint(int index) const
//Note: this must match with the computations in QCommonStylePrivate::tabLayout
Q_D(const QTabBar);
if (const QTabBarPrivate::Tab *tab = d->at(index)) {
- QStyleOptionTabV4 opt;
+ QStyleOptionTab opt;
d->initBasicStyleOption(&opt, index);
- opt.text = d->tabList.at(index).text;
+ opt.text = tab->text;
QSize iconSize = tab->icon.isNull() ? QSize(0, 0) : opt.iconSize;
int hframe = style()->pixelMetric(QStyle::PM_TabBarTabHSpace, &opt, this);
int vframe = style()->pixelMetric(QStyle::PM_TabBarTabVSpace, &opt, this);
@@ -1630,7 +1621,7 @@ QSize QTabBar::tabSizeHint(int index) const
*/
void QTabBar::tabInserted(int index)
{
- Q_UNUSED(index)
+ Q_UNUSED(index);
}
/*!
@@ -1641,7 +1632,7 @@ void QTabBar::tabInserted(int index)
*/
void QTabBar::tabRemoved(int index)
{
- Q_UNUSED(index)
+ Q_UNUSED(index);
}
/*!
@@ -1663,6 +1654,8 @@ void QTabBar::showEvent(QShowEvent *)
d->refresh();
if (!d->validIndex(d->currentIndex))
setCurrentIndex(0);
+ else
+ d->makeVisible(d->currentIndex);
d->updateMacBorderMetrics();
}
@@ -1679,52 +1672,53 @@ void QTabBar::hideEvent(QHideEvent *)
bool QTabBar::event(QEvent *event)
{
Q_D(QTabBar);
- if (event->type() == QEvent::HoverMove
- || event->type() == QEvent::HoverEnter) {
+ switch (event->type()) {
+ case QEvent::HoverMove:
+ case QEvent::HoverEnter: {
QHoverEvent *he = static_cast<QHoverEvent *>(event);
- if (!d->hoverRect.contains(he->pos())) {
- QRect oldHoverRect = d->hoverRect;
- bool cursorOverTabs = false;
- for (int i = 0; i < d->tabList.count(); ++i) {
- QRect area = tabRect(i);
- if (area.contains(he->pos())) {
- d->hoverIndex = i;
- d->hoverRect = area;
- cursorOverTabs = true;
- break;
- }
- }
- if (!cursorOverTabs) {
- d->hoverIndex = -1;
+ d->mousePosition = he->position().toPoint();
+ if (!d->hoverRect.contains(d->mousePosition)) {
+ if (d->hoverRect.isValid())
+ update(d->hoverRect);
+ d->hoverIndex = tabAt(d->mousePosition);
+ if (d->validIndex(d->hoverIndex)) {
+ d->hoverRect = tabRect(d->hoverIndex);
+ update(d->hoverRect);
+ } else {
d->hoverRect = QRect();
}
- if (he->oldPos() != QPoint(-1, -1))
- update(oldHoverRect);
- update(d->hoverRect);
}
return true;
- } else if (event->type() == QEvent::HoverLeave) {
- QRect oldHoverRect = d->hoverRect;
+ }
+ case QEvent::HoverLeave: {
+ d->mousePosition = {-1, -1};
+ if (d->hoverRect.isValid())
+ update(d->hoverRect);
d->hoverIndex = -1;
d->hoverRect = QRect();
- update(oldHoverRect);
+#if QT_CONFIG(wheelevent)
+ d->accumulatedAngleDelta = QPoint();
+#endif
return true;
-#ifndef QT_NO_TOOLTIP
- } else if (event->type() == QEvent::ToolTip) {
+ }
+#if QT_CONFIG(tooltip)
+ case QEvent::ToolTip:
if (const QTabBarPrivate::Tab *tab = d->at(tabAt(static_cast<QHelpEvent*>(event)->pos()))) {
if (!tab->toolTip.isEmpty()) {
QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), tab->toolTip, this);
return true;
}
}
-#endif // QT_NO_TOOLTIP
+ break;
+#endif // QT_CONFIG(tooltip)
#if QT_CONFIG(whatsthis)
- } else if (event->type() == QEvent::QueryWhatsThis) {
+ case QEvent::QEvent::QueryWhatsThis: {
const QTabBarPrivate::Tab *tab = d->at(d->indexAtPos(static_cast<QHelpEvent*>(event)->pos()));
if (!tab || tab->whatsThis.isEmpty())
event->ignore();
return true;
- } else if (event->type() == QEvent::WhatsThis) {
+ }
+ case QEvent::WhatsThis:
if (const QTabBarPrivate::Tab *tab = d->at(d->indexAtPos(static_cast<QHelpEvent*>(event)->pos()))) {
if (!tab->whatsThis.isEmpty()) {
QWhatsThis::showText(static_cast<QHelpEvent*>(event)->globalPos(),
@@ -1732,35 +1726,34 @@ bool QTabBar::event(QEvent *event)
return true;
}
}
+ break;
#endif // QT_CONFIG(whatsthis)
#ifndef QT_NO_SHORTCUT
- } else if (event->type() == QEvent::Shortcut) {
+
+ case QEvent::Shortcut: {
QShortcutEvent *se = static_cast<QShortcutEvent *>(event);
- for (int i = 0; i < d->tabList.count(); ++i) {
- const QTabBarPrivate::Tab *tab = &d->tabList.at(i);
+ for (int i = 0; i < d->tabList.size(); ++i) {
+ const QTabBarPrivate::Tab *tab = d->tabList.at(i);
if (tab->shortcutId == se->shortcutId()) {
setCurrentIndex(i);
return true;
}
}
+ }
+ break;
#endif
- } else if (event->type() == QEvent::MouseButtonDblClick) { // ### fixme Qt 6: move to mouseDoubleClickEvent(), here for BC reasons.
- const QPoint pos = static_cast<const QMouseEvent *>(event)->pos();
- const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
- || (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
- if (!isEventInCornerButtons)
- emit tabBarDoubleClicked(tabAt(pos));
- } else if (event->type() == QEvent::Move) {
+ case QEvent::Move:
d->updateMacBorderMetrics();
- return QWidget::event(event);
-
+ break;
#if QT_CONFIG(draganddrop)
- } else if (event->type() == QEvent::DragEnter) {
+
+ case QEvent::DragEnter:
if (d->changeCurrentOnDrag)
event->accept();
- } else if (event->type() == QEvent::DragMove) {
+ break;
+ case QEvent::DragMove:
if (d->changeCurrentOnDrag) {
- const int tabIndex = tabAt(static_cast<QDragMoveEvent *>(event)->pos());
+ const int tabIndex = tabAt(static_cast<QDragMoveEvent *>(event)->position().toPoint());
if (isTabEnabled(tabIndex) && d->switchTabCurrentIndex != tabIndex) {
d->switchTabCurrentIndex = tabIndex;
if (d->switchTabTimerId)
@@ -1769,11 +1762,23 @@ bool QTabBar::event(QEvent *event)
}
event->ignore();
}
- } else if (event->type() == QEvent::DragLeave || event->type() == QEvent::Drop) {
+ break;
+ case QEvent::DragLeave:
+ case QEvent::Drop:
d->killSwitchTabTimer();
event->ignore();
+ break;
#endif
+ case QEvent::MouseButtonPress:
+ case QEvent::MouseButtonRelease:
+ case QEvent::MouseMove:
+ d->mousePosition = static_cast<QMouseEvent *>(event)->position().toPoint();
+ d->mouseButtons = static_cast<QMouseEvent *>(event)->buttons();
+ break;
+ default:
+ break;
}
+
return QWidget::event(event);
}
@@ -1784,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);
@@ -1810,7 +1817,7 @@ void QTabBar::paintEvent(QPaintEvent *)
selected = d->pressedIndex;
const QRect scrollRect = d->normalizedScrollRect();
- for (int i = 0; i < d->tabList.count(); ++i)
+ for (int i = 0; i < d->tabList.size(); ++i)
optTabBase.tabBarRect |= tabRect(i);
optTabBase.selectedTabRect = tabRect(selected);
@@ -1818,66 +1825,91 @@ void QTabBar::paintEvent(QPaintEvent *)
if (d->drawBase)
p.drawPrimitive(QStyle::PE_FrameTabBarBase, optTabBase);
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (!d->at(i)->visible)
+ // the buttons might be semi-transparent or not fill their rect, but we don't
+ // want the tab underneath to shine through, so clip the button area; QTBUG-50866
+ if (d->leftB->isVisible() || d->rightB->isVisible()) {
+ QStyleOption opt;
+ opt.initFrom(this);
+ QRegion buttonRegion;
+ if (d->leftB->isVisible())
+ buttonRegion |= style()->subElementRect(QStyle::SE_TabBarScrollLeftButton, &opt, this);
+ if (d->rightB->isVisible())
+ buttonRegion |= style()->subElementRect(QStyle::SE_TabBarScrollRightButton, &opt, this);
+ if (!buttonRegion.isEmpty())
+ p.setClipRegion(QRegion(rect()) - buttonRegion);
+ }
+
+ for (int i = 0; i < d->tabList.size(); ++i) {
+ const auto tab = d->tabList.at(i);
+ if (!tab->visible)
continue;
- QStyleOptionTabV4 tab;
- initStyleOption(&tab, i);
- if (d->paintWithOffsets && d->tabList[i].dragOffset != 0) {
+ QStyleOptionTab tabOption;
+ initStyleOption(&tabOption, i);
+ if (d->paintWithOffsets && tab->dragOffset != 0) {
if (vertical) {
- tab.rect.moveTop(tab.rect.y() + d->tabList[i].dragOffset);
+ tabOption.rect.moveTop(tabOption.rect.y() + tab->dragOffset);
} else {
- tab.rect.moveLeft(tab.rect.x() + d->tabList[i].dragOffset);
+ tabOption.rect.moveLeft(tabOption.rect.x() + tab->dragOffset);
}
}
- if (!(tab.state & QStyle::State_Enabled)) {
- tab.palette.setCurrentColorGroup(QPalette::Disabled);
+ if (!(tabOption.state & QStyle::State_Enabled)) {
+ tabOption.palette.setCurrentColorGroup(QPalette::Disabled);
}
// If this tab is partially obscured, make a note of it so that we can pass the information
// along when we draw the tear.
- QRect tabRect = d->tabList[i].rect;
+ QRect tabRect = tab->rect;
int tabStart = vertical ? tabRect.top() : tabRect.left();
int tabEnd = vertical ? tabRect.bottom() : tabRect.right();
if (tabStart < scrollRect.left() + d->scrollOffset) {
cutLeft = i;
- cutTabLeft = tab;
+ cutTabLeft = tabOption;
} else if (tabEnd > scrollRect.right() + d->scrollOffset) {
cutRight = i;
- cutTabRight = tab;
+ cutTabRight = tabOption;
}
// Don't bother drawing a tab if the entire tab is outside of the visible tab bar.
- if ((!vertical && (tab.rect.right() < 0 || tab.rect.left() > width()))
- || (vertical && (tab.rect.bottom() < 0 || tab.rect.top() > height())))
+ if ((!vertical && (tabOption.rect.right() < 0 || tabOption.rect.left() > width()))
+ || (vertical && (tabOption.rect.bottom() < 0 || tabOption.rect.top() > height())))
continue;
- optTabBase.tabBarRect |= tab.rect;
+ optTabBase.tabBarRect |= tabOption.rect;
if (i == selected)
continue;
- p.drawControl(QStyle::CE_TabBarTab, tab);
+ p.drawControl(QStyle::CE_TabBarTab, tabOption);
}
// Draw the selected tab last to get it "on top"
if (selected >= 0) {
- QStyleOptionTabV4 tab;
- initStyleOption(&tab, selected);
- if (d->paintWithOffsets && d->tabList[selected].dragOffset != 0) {
+ 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)
- tab.rect.moveTop(tab.rect.y() + d->tabList[selected].dragOffset);
+ tabOption.rect.moveTop(tabOption.rect.y() + tab->dragOffset);
else
- tab.rect.moveLeft(tab.rect.x() + d->tabList[selected].dragOffset);
- }
- if (!d->dragInProgress)
- p.drawControl(QStyle::CE_TabBarTab, tab);
- else {
- int taboverlap = style()->pixelMetric(QStyle::PM_TabBarTabOverlap, nullptr, this);
- if (verticalTabs(d->shape))
- d->movingTab->setGeometry(tab.rect.adjusted(0, -taboverlap, 0, taboverlap));
- else
- d->movingTab->setGeometry(tab.rect.adjusted(-taboverlap, 0, taboverlap, 0));
+ tabOption.rect.moveLeft(tabOption.rect.x() + tab->dragOffset);
}
+
+ // 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.
@@ -1906,19 +1938,17 @@ void QTabBarPrivate::calculateFirstLastVisible(int index, bool visible, bool rem
} else {
if (remove || (index == firstVisible)) {
firstVisible = -1;
- for (int i = 0; i < tabList.count(); ++i) {
- if (tabList.at(i).visible) {
+ for (int i = 0; i < tabList.size(); ++i) {
+ if (tabList.at(i)->visible) {
firstVisible = i;
break;
}
}
- if (firstVisible < 0)
- firstVisible = 0;
}
if (remove || (index == lastVisible)) {
lastVisible = -1;
- for (int i = tabList.count() - 1; i >= 0; --i) {
- if (tabList.at(i).visible) {
+ for (int i = tabList.size() - 1; i >= 0; --i) {
+ if (tabList.at(i)->visible) {
lastVisible = i;
break;
}
@@ -1935,7 +1965,7 @@ void QTabBarPrivate::calculateFirstLastVisible(int index, bool visible, bool rem
int QTabBarPrivate::selectNewCurrentIndexFrom(int fromIndex)
{
int newindex = -1;
- for (int i = fromIndex; i < tabList.count(); ++i) {
+ for (int i = fromIndex; i < tabList.size(); ++i) {
if (at(i)->visible && at(i)->enabled) {
newindex = i;
break;
@@ -1982,53 +2012,57 @@ void QTabBar::moveTab(int from, int to)
|| !d->validIndex(to))
return;
+ auto &fromTab = *d->tabList.at(from);
+ auto &toTab = *d->tabList.at(to);
+
bool vertical = verticalTabs(d->shape);
int oldPressedPosition = 0;
if (d->pressedIndex != -1) {
// Record the position of the pressed tab before reordering the tabs.
- oldPressedPosition = vertical ? d->tabList[d->pressedIndex].rect.y()
- : d->tabList[d->pressedIndex].rect.x();
+ oldPressedPosition = vertical ? d->tabList.at(d->pressedIndex)->rect.y()
+ : d->tabList.at(d->pressedIndex)->rect.x();
}
// Update the locations of the tabs first
int start = qMin(from, to);
int end = qMax(from, to);
- int width = vertical ? d->tabList[from].rect.height() : d->tabList[from].rect.width();
+ int width = vertical ? fromTab.rect.height() : fromTab.rect.width();
if (from < to)
width *= -1;
bool rtl = isRightToLeft();
for (int i = start; i <= end; ++i) {
if (i == from)
continue;
+ auto &tab = *d->tabList.at(i);
if (vertical)
- d->tabList[i].rect.moveTop(d->tabList[i].rect.y() + width);
+ tab.rect.moveTop(tab.rect.y() + width);
else
- d->tabList[i].rect.moveLeft(d->tabList[i].rect.x() + width);
+ tab.rect.moveLeft(tab.rect.x() + width);
int direction = -1;
if (rtl && !vertical)
direction *= -1;
- if (d->tabList[i].dragOffset != 0)
- d->tabList[i].dragOffset += (direction * width);
+ if (tab.dragOffset != 0)
+ tab.dragOffset += (direction * width);
}
if (vertical) {
if (from < to)
- d->tabList[from].rect.moveTop(d->tabList[to].rect.bottom() + 1);
+ fromTab.rect.moveTop(toTab.rect.bottom() + 1);
else
- d->tabList[from].rect.moveTop(d->tabList[to].rect.top() - width);
+ fromTab.rect.moveTop(toTab.rect.top() - width);
} else {
if (from < to)
- d->tabList[from].rect.moveLeft(d->tabList[to].rect.right() + 1);
+ fromTab.rect.moveLeft(toTab.rect.right() + 1);
else
- d->tabList[from].rect.moveLeft(d->tabList[to].rect.left() - width);
+ fromTab.rect.moveLeft(toTab.rect.left() - width);
}
// Move the actual data structures
d->tabList.move(from, to);
// update lastTab locations
- for (int i = 0; i < d->tabList.count(); ++i)
- d->tabList[i].lastTab = d->calculateNewPosition(from, to, d->tabList[i].lastTab);
+ for (const auto tab : std::as_const(d->tabList))
+ tab->lastTab = d->calculateNewPosition(from, to, tab->lastTab);
// update external variables
int previousIndex = d->currentIndex;
@@ -2037,7 +2071,8 @@ void QTabBar::moveTab(int from, int to)
// If we are in the middle of a drag update the dragStartPosition
if (d->pressedIndex != -1) {
d->pressedIndex = d->calculateNewPosition(from, to, d->pressedIndex);
- int newPressedPosition = vertical ? d->tabList[d->pressedIndex].rect.top() : d->tabList[d->pressedIndex].rect.left();
+ const auto pressedTab = d->tabList.at(d->pressedIndex);
+ int newPressedPosition = vertical ? pressedTab->rect.top() : pressedTab->rect.left();
int diff = oldPressedPosition - newPressedPosition;
if (isRightToLeft() && !vertical)
diff *= -1;
@@ -2069,15 +2104,15 @@ void QTabBarPrivate::slide(int from, int to)
q->setUpdatesEnabled(true);
int postLocation = vertical ? q->tabRect(to).y() : q->tabRect(to).x();
int length = postLocation - preLocation;
- tabList[to].dragOffset -= length;
- tabList[to].startAnimation(this, ANIMATION_DURATION);
+ tabList.at(to)->dragOffset -= length;
+ tabList.at(to)->startAnimation(this, ANIMATION_DURATION);
}
void QTabBarPrivate::moveTab(int index, int offset)
{
if (!validIndex(index))
return;
- tabList[index].dragOffset = offset;
+ tabList.at(index)->dragOffset = offset;
layoutTab(index); // Make buttons follow tab
q_func()->update();
}
@@ -2088,7 +2123,7 @@ void QTabBar::mousePressEvent(QMouseEvent *event)
{
Q_D(QTabBar);
- const QPoint pos = event->pos();
+ const QPoint pos = event->position().toPoint();
const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
|| (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
if (!isEventInCornerButtons) {
@@ -2104,18 +2139,18 @@ void QTabBar::mousePressEvent(QMouseEvent *event)
if (d->pressedIndex != -1 && d->movable)
d->moveTabFinished(d->pressedIndex);
- d->pressedIndex = d->indexAtPos(event->pos());
+ d->pressedIndex = d->indexAtPos(event->position().toPoint());
if (d->validIndex(d->pressedIndex)) {
QStyleOptionTabBarBase optTabBase;
- optTabBase.init(this);
+ optTabBase.initFrom(this);
optTabBase.documentMode = d->documentMode;
if (event->type() == style()->styleHint(QStyle::SH_TabBar_SelectMouseType, &optTabBase, this))
setCurrentIndex(d->pressedIndex);
else
repaint(tabRect(d->pressedIndex));
if (d->movable) {
- d->dragStartPosition = event->pos();
+ d->dragStartPosition = event->position().toPoint();
}
}
}
@@ -2133,7 +2168,7 @@ void QTabBar::mouseMoveEvent(QMouseEvent *event)
// Start drag
if (!d->dragInProgress && d->pressedIndex != -1) {
- if ((event->pos() - d->dragStartPosition).manhattanLength() > QApplication::startDragDistance()) {
+ if ((event->position().toPoint() - d->dragStartPosition).manhattanLength() > QApplication::startDragDistance()) {
d->dragInProgress = true;
d->setupMovableTab();
}
@@ -2145,11 +2180,11 @@ void QTabBar::mouseMoveEvent(QMouseEvent *event)
bool vertical = verticalTabs(d->shape);
int dragDistance;
if (vertical) {
- dragDistance = (event->pos().y() - d->dragStartPosition.y());
+ dragDistance = (event->position().toPoint().y() - d->dragStartPosition.y());
} else {
- dragDistance = (event->pos().x() - d->dragStartPosition.x());
+ dragDistance = (event->position().toPoint().x() - d->dragStartPosition.x());
}
- d->tabList[d->pressedIndex].dragOffset = dragDistance;
+ d->tabList.at(d->pressedIndex)->dragOffset = dragDistance;
QRect startingRect = tabRect(d->pressedIndex);
if (vertical)
@@ -2181,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();
}
@@ -2206,14 +2242,14 @@ void QTabBarPrivate::setupMovableTab()
else
grabRect.adjust(-taboverlap, 0, taboverlap, 0);
- QPixmap grabImage(grabRect.size() * q->devicePixelRatioF());
- grabImage.setDevicePixelRatio(q->devicePixelRatioF());
+ QPixmap grabImage(grabRect.size() * q->devicePixelRatio());
+ grabImage.setDevicePixelRatio(q->devicePixelRatio());
grabImage.fill(Qt::transparent);
QStylePainter p(&grabImage, q);
- QStyleOptionTabV4 tab;
+ QStyleOptionTab tab;
q->initStyleOption(&tab, pressedIndex);
- tab.position = QStyleOptionTab::OnlyOneTab;
+ tab.position = QStyleOptionTab::Moving;
if (verticalTabs(shape))
tab.rect.moveTopLeft(QPoint(0, taboverlap));
else
@@ -2226,10 +2262,11 @@ void QTabBarPrivate::setupMovableTab()
movingTab->raise();
// Re-arrange widget order to avoid overlaps
- if (tabList[pressedIndex].leftWidget)
- tabList[pressedIndex].leftWidget->raise();
- if (tabList[pressedIndex].rightWidget)
- tabList[pressedIndex].rightWidget->raise();
+ const auto &pressedTab = *tabList.at(pressedIndex);
+ if (pressedTab.leftWidget)
+ pressedTab.leftWidget->raise();
+ if (pressedTab.rightWidget)
+ pressedTab.rightWidget->raise();
if (leftB)
leftB->raise();
if (rightB)
@@ -2243,17 +2280,18 @@ void QTabBarPrivate::moveTabFinished(int index)
bool cleanup = (pressedIndex == index) || (pressedIndex == -1) || !validIndex(index);
bool allAnimationsFinished = true;
#if QT_CONFIG(animation)
- for(int i = 0; allAnimationsFinished && i < tabList.count(); ++i) {
- const Tab &t = tabList.at(i);
- if (t.animation && t.animation->state() == QAbstractAnimation::Running)
+ for (const auto tab : std::as_const(tabList)) {
+ if (tab->animation && tab->animation->state() == QAbstractAnimation::Running) {
allAnimationsFinished = false;
+ break;
+ }
}
#endif // animation
if (allAnimationsFinished && cleanup) {
- if(movingTab)
+ if (movingTab)
movingTab->setVisible(false); // We might not get a mouse release
- for (int i = 0; i < tabList.count(); ++i) {
- tabList[i].dragOffset = 0;
+ for (auto tab : std::as_const(tabList)) {
+ tab->dragOffset = 0;
}
if (pressedIndex != -1 && movable) {
pressedIndex = -1;
@@ -2264,7 +2302,7 @@ void QTabBarPrivate::moveTabFinished(int index)
} else {
if (!validIndex(index))
return;
- tabList[index].dragOffset = 0;
+ tabList.at(index)->dragOffset = 0;
}
q->update();
}
@@ -2280,19 +2318,21 @@ void QTabBar::mouseReleaseEvent(QMouseEvent *event)
}
if (d->movable && d->dragInProgress && d->validIndex(d->pressedIndex)) {
- int length = d->tabList[d->pressedIndex].dragOffset;
+ int length = d->tabList.at(d->pressedIndex)->dragOffset;
int width = verticalTabs(d->shape)
? tabRect(d->pressedIndex).height()
: tabRect(d->pressedIndex).width();
int duration = qMin(ANIMATION_DURATION,
(qAbs(length) * ANIMATION_DURATION) / width);
- d->tabList[d->pressedIndex].startAnimation(d, duration);
+ d->tabList.at(d->pressedIndex)->startAnimation(d, duration);
d->dragInProgress = false;
d->movingTab->setVisible(false);
d->dragStartPosition = QPoint();
}
- int i = d->indexAtPos(event->pos()) == d->pressedIndex ? d->pressedIndex : -1;
+ // mouse release event might happen outside the tab, so keep the pressed index
+ int oldPressedIndex = d->pressedIndex;
+ int i = d->indexAtPos(event->position().toPoint()) == d->pressedIndex ? d->pressedIndex : -1;
d->pressedIndex = -1;
QStyleOptionTabBarBase optTabBase;
optTabBase.initFrom(this);
@@ -2301,8 +2341,22 @@ void QTabBar::mouseReleaseEvent(QMouseEvent *event)
(style()->styleHint(QStyle::SH_TabBar_SelectMouseType, &optTabBase, this) == QEvent::MouseButtonRelease);
if (selectOnRelease)
setCurrentIndex(i);
- if (!selectOnRelease || !d->validIndex(i) || d->currentIndex == i)
- repaint(tabRect(i));
+ if (d->validIndex(oldPressedIndex))
+ update(tabRect(oldPressedIndex));
+}
+
+/*!\reimp
+ */
+void QTabBar::mouseDoubleClickEvent(QMouseEvent *event)
+{
+ Q_D(QTabBar);
+ const QPoint pos = event->position().toPoint();
+ const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
+ || (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
+ if (!isEventInCornerButtons)
+ emit tabBarDoubleClicked(tabAt(pos));
+
+ mousePressEvent(event);
}
/*!\reimp
@@ -2323,16 +2377,61 @@ void QTabBar::keyPressEvent(QKeyEvent *event)
#if QT_CONFIG(wheelevent)
void QTabBar::wheelEvent(QWheelEvent *event)
{
-#ifndef Q_OS_MAC
Q_D(QTabBar);
- int delta = (qAbs(event->angleDelta().x()) > qAbs(event->angleDelta().y()) ?
- event->angleDelta().x() : event->angleDelta().y());
- int offset = delta > 0 ? -1 : 1;
- d->setCurrentNextEnabledIndex(offset);
- QWidget::wheelEvent(event);
-#else
- Q_UNUSED(event)
-#endif
+ if (style()->styleHint(QStyle::SH_TabBar_AllowWheelScrolling)) {
+ const bool wheelVertical = qAbs(event->angleDelta().y()) > qAbs(event->angleDelta().x());
+ const bool tabsVertical = verticalTabs(d->shape);
+ if (event->device()->capabilities().testFlag(QInputDevice::Capability::PixelScroll)) {
+ // For wheels/touch pads with pixel precision, scroll the tab bar if
+ // it has the right orientation.
+ int delta = 0;
+ if (tabsVertical == wheelVertical)
+ delta = wheelVertical ? event->pixelDelta().y() : event->pixelDelta().x();
+ if (layoutDirection() == Qt::RightToLeft)
+ delta = -delta;
+ if (delta && d->validIndex(d->lastVisible)) {
+ const int oldScrollOffset = d->scrollOffset;
+ const QRect lastTabRect = d->tabList.at(d->lastVisible)->rect;
+ const QRect scrollRect = d->normalizedScrollRect(d->lastVisible);
+ int scrollRectExtent = scrollRect.right();
+ if (!d->leftB->isVisible())
+ scrollRectExtent += tabsVertical ? d->leftB->height() : d->leftB->width();
+ if (!d->rightB->isVisible())
+ scrollRectExtent += tabsVertical ? d->rightB->height() : d->rightB->width();
+
+ const int maxScrollOffset = qMax((tabsVertical ?
+ lastTabRect.bottom() :
+ lastTabRect.right()) - scrollRectExtent, 0);
+ d->scrollOffset = qBound(0, d->scrollOffset - delta, maxScrollOffset);
+ d->leftB->setEnabled(d->scrollOffset > -scrollRect.left());
+ d->rightB->setEnabled(maxScrollOffset > d->scrollOffset);
+ if (oldScrollOffset != d->scrollOffset) {
+ event->accept();
+ update();
+ return;
+ }
+ }
+ } else {
+ d->accumulatedAngleDelta += event->angleDelta();
+ const int xSteps = d->accumulatedAngleDelta.x() / QWheelEvent::DefaultDeltasPerStep;
+ const int ySteps = d->accumulatedAngleDelta.y() / QWheelEvent::DefaultDeltasPerStep;
+ int offset = 0;
+ if (xSteps > 0 || ySteps > 0) {
+ offset = -1;
+ d->accumulatedAngleDelta = QPoint();
+ } else if (xSteps < 0 || ySteps < 0) {
+ offset = 1;
+ d->accumulatedAngleDelta = QPoint();
+ }
+ const int oldCurrentIndex = d->currentIndex;
+ d->setCurrentNextEnabledIndex(offset);
+ if (oldCurrentIndex != d->currentIndex) {
+ event->accept();
+ return;
+ }
+ }
+ QWidget::wheelEvent(event);
+ }
}
#endif // QT_CONFIG(wheelevent)
@@ -2340,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;
}
@@ -2393,7 +2492,7 @@ void QTabBar::timerEvent(QTimerEvent *event)
This property controls how items are elided when there is not
enough space to show them for a given tab bar size.
- By default the value is style dependent.
+ By default the value is style-dependent.
\sa QTabWidget::elideMode, usesScrollButtons, QStyle::SH_TabBar_ElideMode
*/
@@ -2422,7 +2521,7 @@ void QTabBar::setElideMode(Qt::TextElideMode mode)
When there are too many tabs in a tab bar for its size, the tab bar can either choose
to expand its size or to add buttons that allow you to scroll through the tabs.
- By default the value is style dependant.
+ By default the value is style-dependent.
\sa elideMode, QTabWidget::usesScrollButtons, QStyle::SH_TabBar_PreferNoArrows
*/
@@ -2469,24 +2568,25 @@ void QTabBar::setTabsClosable(bool closable)
d->closeButtonOnTabs = closable;
ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, this);
if (!closable) {
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (closeSide == LeftSide && d->tabList[i].leftWidget) {
- d->tabList[i].leftWidget->deleteLater();
- d->tabList[i].leftWidget = nullptr;
+ for (auto tab : std::as_const(d->tabList)) {
+ if (closeSide == LeftSide && tab->leftWidget) {
+ tab->leftWidget->deleteLater();
+ tab->leftWidget = nullptr;
}
- if (closeSide == RightSide && d->tabList[i].rightWidget) {
- d->tabList[i].rightWidget->deleteLater();
- d->tabList[i].rightWidget = nullptr;
+ if (closeSide == RightSide && tab->rightWidget) {
+ tab->rightWidget->deleteLater();
+ tab->rightWidget = nullptr;
}
}
} else {
bool newButtons = false;
- for (int i = 0; i < d->tabList.count(); ++i) {
+ for (int i = 0; i < d->tabList.size(); ++i) {
if (tabButton(i, closeSide))
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)
@@ -2676,10 +2776,11 @@ void QTabBar::setChangeCurrentOnDrag(bool change)
/*!
Sets \a widget on the tab \a index. The widget is placed
- on the left or right hand side depending upon the \a position.
+ on the left or right hand side depending on the \a position.
\since 4.5
- Any previously set widget in \a position is hidden.
+ Any previously set widget in \a position is hidden. Setting \a widget
+ to \nullptr will hide the current widget at \a position.
The tab bar will take ownership of the widget and so all widgets set here
will be deleted by the tab bar when it is destroyed unless you separately
@@ -2690,7 +2791,7 @@ void QTabBar::setChangeCurrentOnDrag(bool change)
void QTabBar::setTabButton(int index, ButtonPosition position, QWidget *widget)
{
Q_D(QTabBar);
- if (index < 0 || index >= d->tabList.count())
+ if (index < 0 || index >= d->tabList.size())
return;
if (widget) {
widget->setParent(this);
@@ -2698,14 +2799,15 @@ void QTabBar::setTabButton(int index, ButtonPosition position, QWidget *widget)
widget->lower();
widget->show();
}
+ auto &tab = *d->tabList.at(index);
if (position == LeftSide) {
- if (d->tabList[index].leftWidget)
- d->tabList[index].leftWidget->hide();
- d->tabList[index].leftWidget = widget;
+ if (tab.leftWidget)
+ tab.leftWidget->hide();
+ tab.leftWidget = widget;
} else {
- if (d->tabList[index].rightWidget)
- d->tabList[index].rightWidget->hide();
- d->tabList[index].rightWidget = widget;
+ if (tab.rightWidget)
+ tab.rightWidget->hide();
+ tab.rightWidget = widget;
}
d->layoutTabs();
d->refresh();
@@ -2719,15 +2821,14 @@ void QTabBar::setTabButton(int index, ButtonPosition position, QWidget *widget)
QWidget *QTabBar::tabButton(int index, ButtonPosition position) const
{
Q_D(const QTabBar);
- if (index < 0 || index >= d->tabList.count())
- return nullptr;
- if (position == LeftSide)
- return d->tabList.at(index).leftWidget;
- else
- return d->tabList.at(index).rightWidget;
+ if (const auto tab = d->at(index)) {
+ return position == LeftSide ? tab->leftWidget
+ : tab->rightWidget;
+ }
+ return nullptr;
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
/*!
Sets the accessibleName of the tab at position \a index to \a name.
*/
@@ -2753,7 +2854,7 @@ QString QTabBar::accessibleTabName(int index) const
return tab->accessibleName;
return QString();
}
-#endif // QT_NO_ACCESSIBILITY
+#endif // QT_CONFIG(accessibility)
CloseButton::CloseButton(QWidget *parent)
: QAbstractButton(parent)
@@ -2762,7 +2863,7 @@ CloseButton::CloseButton(QWidget *parent)
#ifndef QT_NO_CURSOR
setCursor(Qt::ArrowCursor);
#endif
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
setToolTip(tr("Close Tab"));
#endif
resize(sizeHint());
@@ -2776,7 +2877,7 @@ QSize CloseButton::sizeHint() const
return QSize(width, height);
}
-void CloseButton::enterEvent(QEvent *event)
+void CloseButton::enterEvent(QEnterEvent *event)
{
if (isEnabled())
update();
@@ -2794,7 +2895,7 @@ void CloseButton::paintEvent(QPaintEvent *)
{
QPainter p(this);
QStyleOption opt;
- opt.init(this);
+ opt.initFrom(this);
opt.state |= QStyle::State_AutoRaise;
if (isEnabled() && underMouse() && !isChecked() && !isDown())
opt.state |= QStyle::State_Raised;
@@ -2816,12 +2917,12 @@ void CloseButton::paintEvent(QPaintEvent *)
#if QT_CONFIG(animation)
void QTabBarPrivate::Tab::TabBarAnimation::updateCurrentValue(const QVariant &current)
{
- priv->moveTab(priv->tabList.indexOf(*tab), current.toInt());
+ priv->moveTab(priv->tabList.indexOf(tab), current.toInt());
}
void QTabBarPrivate::Tab::TabBarAnimation::updateState(QAbstractAnimation::State newState, QAbstractAnimation::State)
{
- if (newState == Stopped) priv->moveTabFinished(priv->tabList.indexOf(*tab));
+ if (newState == Stopped) priv->moveTabFinished(priv->tabList.indexOf(tab));
}
#endif
diff --git a/src/widgets/widgets/qtabbar.h b/src/widgets/widgets/qtabbar.h
index c49c12f38c..2759d5a318 100644
--- a/src/widgets/widgets/qtabbar.h
+++ b/src/widgets/widgets/qtabbar.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTABBAR_H
#define QTABBAR_H
@@ -63,7 +27,8 @@ class Q_WIDGETS_EXPORT QTabBar: public QWidget
Q_PROPERTY(Qt::TextElideMode elideMode READ elideMode WRITE setElideMode)
Q_PROPERTY(bool usesScrollButtons READ usesScrollButtons WRITE setUsesScrollButtons)
Q_PROPERTY(bool tabsClosable READ tabsClosable WRITE setTabsClosable)
- Q_PROPERTY(SelectionBehavior selectionBehaviorOnRemove READ selectionBehaviorOnRemove WRITE setSelectionBehaviorOnRemove)
+ Q_PROPERTY(SelectionBehavior selectionBehaviorOnRemove READ selectionBehaviorOnRemove
+ WRITE setSelectionBehaviorOnRemove)
Q_PROPERTY(bool expanding READ expanding WRITE setExpanding)
Q_PROPERTY(bool movable READ isMovable WRITE setMovable)
Q_PROPERTY(bool documentMode READ documentMode WRITE setDocumentMode)
@@ -103,10 +68,10 @@ public:
void moveTab(int from, int to);
bool isTabEnabled(int index) const;
- void setTabEnabled(int index, bool);
+ void setTabEnabled(int index, bool enabled);
bool isTabVisible(int index) const;
- void setTabVisible(int index, bool);
+ void setTabVisible(int index, bool visible);
QString tabText(int index) const;
void setTabText(int index, const QString &text);
@@ -118,9 +83,9 @@ public:
void setTabIcon(int index, const QIcon &icon);
Qt::TextElideMode elideMode() const;
- void setElideMode(Qt::TextElideMode);
+ void setElideMode(Qt::TextElideMode mode);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
void setTabToolTip(int index, const QString &tip);
QString tabToolTip(int index) const;
#endif
@@ -175,7 +140,7 @@ public:
bool changeCurrentOnDrag() const;
void setChangeCurrentOnDrag(bool change);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QString accessibleTabName(int index) const;
void setAccessibleTabName(int index, const QString &name);
#endif
@@ -202,25 +167,24 @@ protected:
void showEvent(QShowEvent *) override;
void hideEvent(QHideEvent *) override;
void paintEvent(QPaintEvent *) override;
- void mousePressEvent (QMouseEvent *) override;
- void mouseMoveEvent (QMouseEvent *) override;
- void mouseReleaseEvent (QMouseEvent *) override;
+ void mousePressEvent(QMouseEvent *) override;
+ void mouseMoveEvent(QMouseEvent *) override;
+ void mouseReleaseEvent(QMouseEvent *) override;
+ void mouseDoubleClickEvent(QMouseEvent *) override;
#if QT_CONFIG(wheelevent)
void wheelEvent(QWheelEvent *event) override;
#endif
void keyPressEvent(QKeyEvent *) override;
void changeEvent(QEvent *) override;
void timerEvent(QTimerEvent *event) override;
- void initStyleOption(QStyleOptionTab *option, int tabIndex) const;
+ virtual void initStyleOption(QStyleOptionTab *option, int tabIndex) const;
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
friend class QAccessibleTabBar;
#endif
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 ac4cbd32a8..d76f439bd7 100644
--- a/src/widgets/widgets/qtabbar_p.h
+++ b/src/widgets/widgets/qtabbar_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTABBAR_P_H
#define QTABBAR_P_H
@@ -65,6 +29,7 @@
#define ANIMATION_DURATION 250
#include <qstyleoption.h>
+#include <utility>
QT_REQUIRE_CONFIG(tabbar);
@@ -88,41 +53,75 @@ class Q_WIDGETS_EXPORT QTabBarPrivate : public QWidgetPrivate
Q_DECLARE_PUBLIC(QTabBar)
public:
QTabBarPrivate()
- :currentIndex(-1), pressedIndex(-1), firstVisible(0), lastVisible(-1), shape(QTabBar::RoundedNorth), layoutDirty(false),
- drawBase(true), scrollOffset(0), hoverIndex(-1), elideModeSetByUser(false), useScrollButtonsSetByUser(false), expanding(true), closeButtonOnTabs(false),
- selectionBehaviorOnRemove(QTabBar::SelectRightTab), paintWithOffsets(true), movable(false),
- dragInProgress(false), documentMode(false), autoHide(false), changeCurrentOnDrag(false),
- switchTabCurrentIndex(-1), switchTabTimerId(0), movingTab(nullptr)
- {}
-
- int currentIndex;
- int pressedIndex;
- int firstVisible;
- int lastVisible;
- QTabBar::Shape shape;
- bool layoutDirty;
- bool drawBase;
- int scrollOffset;
+ : layoutDirty(false), drawBase(true), elideModeSetByUser(false), useScrollButtons(false),
+ useScrollButtonsSetByUser(false), expanding(true), closeButtonOnTabs(false),
+ paintWithOffsets(true), movable(false), dragInProgress(false), documentMode(false),
+ autoHide(false), changeCurrentOnDrag(false)
+ {}
+ ~QTabBarPrivate()
+ {
+ qDeleteAll(tabList);
+ }
+
+ QRect hoverRect;
+ QPoint dragStartPosition;
+ QPoint mousePosition = {-1, -1};
+#if QT_CONFIG(wheelevent)
+ QPoint accumulatedAngleDelta;
+#endif
+ QSize iconSize;
+ QToolButton* rightB = nullptr; // right or bottom
+ QToolButton* leftB = nullptr; // left or top
+ QMovableTabWidget *movingTab = nullptr;
+ int hoverIndex = -1;
+ int switchTabCurrentIndex = -1;
+ int switchTabTimerId = 0;
+ Qt::TextElideMode elideMode = Qt::ElideNone;
+ QTabBar::SelectionBehavior selectionBehaviorOnRemove = QTabBar::SelectRightTab;
+ QTabBar::Shape shape = QTabBar::RoundedNorth;
+ Qt::MouseButtons mouseButtons = Qt::NoButton;
+
+ int currentIndex = -1;
+ int pressedIndex = -1;
+ int firstVisible = 0;
+ int lastVisible = -1;
+ int scrollOffset = 0;
+
+ bool layoutDirty : 1;
+ bool drawBase : 1;
+ bool elideModeSetByUser : 1;
+ bool useScrollButtons : 1;
+ bool useScrollButtonsSetByUser : 1;
+ bool expanding : 1;
+ bool closeButtonOnTabs : 1;
+ bool paintWithOffsets : 1;
+ bool movable : 1;
+ bool dragInProgress : 1;
+ bool documentMode : 1;
+ bool autoHide : 1;
+ bool changeCurrentOnDrag : 1;
struct Tab {
inline Tab(const QIcon &ico, const QString &txt)
- : enabled(true) , visible(true), shortcutId(0), text(txt), icon(ico),
- leftWidget(nullptr), rightWidget(nullptr), lastTab(-1), dragOffset(0)
-#if QT_CONFIG(animation)
- , animation(nullptr)
-#endif // animation
- {}
- bool operator==(const Tab &other) const { return &other == this; }
- bool enabled;
- bool visible;
- int shortcutId;
+ : text(txt), icon(ico), enabled(true), visible(true)
+ {
+ }
+ /*
+ Tabs are managed by instance; they are not the same even
+ if all properties are the same.
+ */
+ Q_DISABLE_COPY_MOVE(Tab);
+
QString text;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
QString toolTip;
#endif
#if QT_CONFIG(whatsthis)
QString whatsThis;
#endif
+#if QT_CONFIG(accessibility)
+ QString accessibleName;
+#endif
QIcon icon;
QRect rect;
QRect minRect;
@@ -130,16 +129,15 @@ public:
QColor textColor;
QVariant data;
- QWidget *leftWidget;
- QWidget *rightWidget;
- int lastTab;
- int dragOffset;
-#ifndef QT_NO_ACCESSIBILITY
- QString accessibleName;
-#endif
+ QWidget *leftWidget = nullptr;
+ QWidget *rightWidget = nullptr;
+ int shortcutId = 0;
+ int lastTab = -1;
+ int dragOffset = 0;
+ uint enabled : 1;
+ uint visible : 1;
#if QT_CONFIG(animation)
- ~Tab() { delete animation; }
struct TabBarAnimation : public QVariantAnimation {
TabBarAnimation(Tab *t, QTabBarPrivate *_priv) : tab(t), priv(_priv)
{ setEasingCurve(QEasingCurve::InOutQuad); }
@@ -151,15 +149,16 @@ public:
//these are needed for the callbacks
Tab *tab;
QTabBarPrivate *priv;
- } *animation;
+ };
+ std::unique_ptr<TabBarAnimation> animation;
void startAnimation(QTabBarPrivate *priv, int duration) {
if (!priv->isAnimated()) {
- priv->moveTabFinished(priv->tabList.indexOf(*this));
+ priv->moveTabFinished(priv->tabList.indexOf(this));
return;
}
if (!animation)
- animation = new TabBarAnimation(this, priv);
+ animation = std::make_unique<TabBarAnimation>(this, priv);
animation->setStartValue(dragOffset);
animation->setEndValue(0);
animation->setDuration(duration);
@@ -167,10 +166,10 @@ public:
}
#else
void startAnimation(QTabBarPrivate *priv, int duration)
- { Q_UNUSED(duration); priv->moveTabFinished(priv->tabList.indexOf(*this)); }
+ { Q_UNUSED(duration); priv->moveTabFinished(priv->tabList.indexOf(this)); }
#endif // animation
};
- QList<Tab> tabList;
+ QList<Tab*> tabList;
mutable QHash<QString, QSize> textSizes;
void calculateFirstLastVisible(int index, bool visible, bool remove);
@@ -179,24 +178,19 @@ public:
void slide(int from, int to);
void init();
- Tab *at(int index);
- const Tab *at(int index) const;
+ inline Tab *at(int index) { return tabList.value(index, nullptr); }
+ inline const Tab *at(int index) const { return tabList.value(index, nullptr); }
int indexAtPos(const QPoint &p) const;
inline bool isAnimated() const { Q_Q(const QTabBar); return q->style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, q) > 0; }
- inline bool validIndex(int index) const { return index >= 0 && index < tabList.count(); }
+ inline bool validIndex(int index) const { return index >= 0 && index < tabList.size(); }
void setCurrentNextEnabledIndex(int offset);
- QToolButton* rightB; // right or bottom
- QToolButton* leftB; // left or top
-
- void _q_scrollTabs();
- void _q_closeTab();
+ void scrollTabs();
+ void closeTab();
void moveTab(int index, int offset);
void moveTabFinished(int index);
- QRect hoverRect;
- int hoverIndex;
void refresh();
void layoutTabs();
@@ -212,28 +206,7 @@ public:
void initBasicStyleOption(QStyleOptionTab *option, int tabIndex) const;
void makeVisible(int index);
- QSize iconSize;
- Qt::TextElideMode elideMode;
- bool elideModeSetByUser;
- bool useScrollButtons;
- bool useScrollButtonsSetByUser;
- bool expanding;
- bool closeButtonOnTabs;
- QTabBar::SelectionBehavior selectionBehaviorOnRemove;
-
- QPoint dragStartPosition;
- bool paintWithOffsets;
- bool movable;
- bool dragInProgress;
- bool documentMode;
- bool autoHide;
- bool changeCurrentOnDrag;
-
- int switchTabCurrentIndex;
- int switchTabTimerId;
-
- QMovableTabWidget *movingTab;
// shared by tabwidget and qtabbar
static void initStyleBaseOption(QStyleOptionTabBarBase *optTabBase, QTabBar *tabbar, QSize size)
{
@@ -241,7 +214,7 @@ public:
tabOverlap.shape = tabbar->shape();
int overlap = tabbar->style()->pixelMetric(QStyle::PM_TabBarBaseOverlap, &tabOverlap, tabbar);
QWidget *theParent = tabbar->parentWidget();
- optTabBase->init(tabbar);
+ optTabBase->initFrom(tabbar);
optTabBase->shape = tabbar->shape();
optTabBase->documentMode = tabbar->documentMode();
if (theParent && overlap > 0) {
@@ -272,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 f0bfe67e3a..5e7c266ef6 100644
--- a/src/widgets/widgets/qtabwidget.cpp
+++ b/src/widgets/widgets/qtabwidget.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtabwidget.h"
@@ -44,8 +8,6 @@
#include "private/qtabbar_p.h"
#include "qapplication.h"
#include "qbitmap.h"
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
#include "qevent.h"
#include "qlayout.h"
#include "qstackedwidget.h"
@@ -57,6 +19,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
/*!
\class QTabWidget
\brief The QTabWidget class provides a stack of tabbed widgets.
@@ -192,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
{
@@ -228,14 +192,14 @@ void QTabWidgetPrivate::init()
Q_Q(QTabWidget);
stack = new QStackedWidget(q);
- stack->setObjectName(QLatin1String("qt_tabwidget_stackedwidget"));
+ stack->setObjectName("qt_tabwidget_stackedwidget"_L1);
stack->setLineWidth(0);
// 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(QLatin1String("qt_tabwidget_tabbar"));
+ tabBar->setObjectName("qt_tabwidget_tabbar"_L1);
tabBar->setDrawBase(false);
q->setTabBar(tabBar);
@@ -471,7 +435,7 @@ int QTabWidget::insertTab(int index, QWidget *w, const QString &label)
int QTabWidget::insertTab(int index, QWidget *w, const QIcon& icon, const QString &label)
{
Q_D(QTabWidget);
- if(!w)
+ if (!w)
return -1;
index = d->stack->insertWidget(index, w);
d->tabs->insertTab(index, icon, label);
@@ -612,7 +576,7 @@ void QTabWidget::setTabVisible(int index, bool visible)
Only the horizontal element of the \a corner will be used.
- Passing 0 shows no widget in the corner.
+ Passing \nullptr shows no widget in the corner.
Any previously set corner widget is hidden.
@@ -721,7 +685,7 @@ void QTabWidget::setCurrentIndex(int index)
Returns the index position of the page occupied by the widget \a
w, or -1 if the widget cannot be found.
*/
-int QTabWidget::indexOf(QWidget* w) const
+int QTabWidget::indexOf(const QWidget *w) const
{
Q_D(const QTabWidget);
return d->stack->indexOf(w);
@@ -756,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();
}
@@ -788,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)
@@ -796,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);
@@ -804,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);
@@ -880,7 +844,7 @@ QSize QTabWidget::sizeHint() const
if (d->leftCornerWidget)
lc = d->leftCornerWidget->sizeHint();
- if(d->rightCornerWidget)
+ if (d->rightCornerWidget)
rc = d->rightCornerWidget->sizeHint();
if (!d->dirty) {
QTabWidget *that = const_cast<QTabWidget*>(this);
@@ -899,13 +863,12 @@ QSize QTabWidget::sizeHint() const
if (usesScrollButtons())
t = t.boundedTo(QSize(200,200));
else
- t = t.boundedTo(QDesktopWidgetPrivate::size());
+ t = t.boundedTo(QGuiApplication::primaryScreen()->virtualGeometry().size());
}
QSize sz = basicSize(d->pos == North || d->pos == South, lc, rc, s, t);
- return style()->sizeFromContents(QStyle::CT_TabWidget, &opt, sz, this)
- .expandedTo(QApplication::globalStrut());
+ return style()->sizeFromContents(QStyle::CT_TabWidget, &opt, sz, this);
}
@@ -919,9 +882,9 @@ QSize QTabWidget::minimumSizeHint() const
Q_D(const QTabWidget);
QSize lc(0, 0), rc(0, 0);
- if(d->leftCornerWidget)
+ if (d->leftCornerWidget)
lc = d->leftCornerWidget->minimumSizeHint();
- if(d->rightCornerWidget)
+ if (d->rightCornerWidget)
rc = d->rightCornerWidget->minimumSizeHint();
if (!d->dirty) {
QTabWidget *that = const_cast<QTabWidget*>(this);
@@ -938,8 +901,7 @@ QSize QTabWidget::minimumSizeHint() const
initStyleOption(&opt);
opt.palette = palette();
opt.state = QStyle::State_None;
- return style()->sizeFromContents(QStyle::CT_TabWidget, &opt, sz, this)
- .expandedTo(QApplication::globalStrut());
+ return style()->sizeFromContents(QStyle::CT_TabWidget, &opt, sz, this);
}
/*!
@@ -953,13 +915,12 @@ int QTabWidget::heightForWidth(int width) const
opt.state = QStyle::State_None;
QSize zero(0,0);
- const QSize padding = style()->sizeFromContents(QStyle::CT_TabWidget, &opt, zero, this)
- .expandedTo(QApplication::globalStrut());
+ const QSize padding = style()->sizeFromContents(QStyle::CT_TabWidget, &opt, zero, this);
QSize lc(0, 0), rc(0, 0);
if (d->leftCornerWidget)
lc = d->leftCornerWidget->sizeHint();
- if(d->rightCornerWidget)
+ if (d->rightCornerWidget)
rc = d->rightCornerWidget->sizeHint();
if (!d->dirty) {
QTabWidget *that = const_cast<QTabWidget*>(this);
@@ -971,7 +932,7 @@ int QTabWidget::heightForWidth(int width) const
if (usesScrollButtons())
t = t.boundedTo(QSize(200,200));
else
- t = t.boundedTo(QDesktopWidgetPrivate::size());
+ t = t.boundedTo(QGuiApplication::primaryScreen()->virtualSize());
}
const bool tabIsHorizontal = (d->pos == North || d->pos == South);
@@ -984,7 +945,7 @@ int QTabWidget::heightForWidth(int width) const
QSize s(stackWidth, stackHeight);
QSize contentSize = basicSize(tabIsHorizontal, lc, rc, s, t);
- return (contentSize + padding).expandedTo(QApplication::globalStrut()).height();
+ return (contentSize + padding).height();
}
@@ -1178,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;
}
@@ -1212,7 +1173,7 @@ int QTabWidget::count() const
return d->tabs->count();
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
/*!
Sets the tab tool tip for the page at position \a index to \a tip.
@@ -1235,7 +1196,7 @@ QString QTabWidget::tabToolTip(int index) const
Q_D(const QTabWidget);
return d->tabs->tabToolTip(index);
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
#if QT_CONFIG(whatsthis)
/*!
@@ -1271,7 +1232,7 @@ QString QTabWidget::tabWhatsThis(int index) const
*/
void QTabWidget::tabInserted(int index)
{
- Q_UNUSED(index)
+ Q_UNUSED(index);
}
/*!
@@ -1282,7 +1243,7 @@ void QTabWidget::tabInserted(int index)
*/
void QTabWidget::tabRemoved(int index)
{
- Q_UNUSED(index)
+ Q_UNUSED(index);
}
/*!
@@ -1348,7 +1309,7 @@ void QTabWidget::setIconSize(const QSize &size)
This property controls how items are elided when there is not
enough space to show them for a given tab bar size.
- By default the value is style dependant.
+ By default the value is style dependent.
\sa QTabBar::elideMode, usesScrollButtons, QStyle::SH_TabBar_ElideMode
*/
@@ -1371,7 +1332,7 @@ void QTabWidget::setElideMode(Qt::TextElideMode mode)
When there are too many tabs in a tab bar for its size, the tab bar can either choose
to expand its size or to add buttons that allow you to scroll through the tabs.
- By default the value is style dependant.
+ By default the value is style dependent.
\sa elideMode, QTabBar::usesScrollButtons, QStyle::SH_TabBar_PreferNoArrows
*/
@@ -1446,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 e6b3f93303..c813f8d921 100644
--- a/src/widgets/widgets/qtabwidget.h
+++ b/src/widgets/widgets/qtabwidget.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTABWIDGET_H
#define QTABWIDGET_H
@@ -80,18 +44,18 @@ public:
void removeTab(int index);
bool isTabEnabled(int index) const;
- void setTabEnabled(int index, bool);
+ void setTabEnabled(int index, bool enabled);
bool isTabVisible(int index) const;
- void setTabVisible(int index, bool);
+ void setTabVisible(int index, bool visible);
QString tabText(int index) const;
- void setTabText(int index, const QString &);
+ void setTabText(int index, const QString &text);
QIcon tabIcon(int index) const;
void setTabIcon(int index, const QIcon & icon);
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
void setTabToolTip(int index, const QString & tip);
QString tabToolTip(int index) const;
#endif
@@ -104,13 +68,13 @@ public:
int currentIndex() const;
QWidget *currentWidget() const;
QWidget *widget(int index) const;
- int indexOf(QWidget *widget) const;
+ int indexOf(const QWidget *widget) const;
int count() const;
enum TabPosition { North, South, West, East };
Q_ENUM(TabPosition)
TabPosition tabPosition() const;
- void setTabPosition(TabPosition);
+ void setTabPosition(TabPosition position);
bool tabsClosable() const;
void setTabsClosable(bool closeable);
@@ -132,7 +96,7 @@ public:
QWidget * cornerWidget(Qt::Corner corner = Qt::TopRightCorner) const;
Qt::TextElideMode elideMode() const;
- void setElideMode(Qt::TextElideMode);
+ void setElideMode(Qt::TextElideMode mode);
QSize iconSize() const;
void setIconSize(const QSize &size);
@@ -171,15 +135,12 @@ protected:
void setTabBar(QTabBar *);
void changeEvent(QEvent *) override;
bool event(QEvent *) override;
- void initStyleOption(QStyleOptionTabWidgetFrame *option) const;
+ virtual void initStyleOption(QStyleOptionTabWidgetFrame *option) const;
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 d0ccd435b3..2c01ed2b26 100644
--- a/src/widgets/widgets/qtextbrowser.cpp
+++ b/src/widgets/widgets/qtextbrowser.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 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 "qtextbrowser.h"
#include "qtextedit_p.h"
@@ -44,13 +8,9 @@
#include <qapplication.h>
#include <private/qapplication_p.h>
#include <qevent.h>
-#include <qdesktopwidget.h>
#include <qdebug.h>
#include <qabstracttextdocumentlayout.h>
#include "private/qtextdocumentlayout_p.h"
-#if QT_CONFIG(textcodec)
-#include <qtextcodec.h>
-#endif
#include <qpainter.h>
#include <qdir.h>
#if QT_CONFIG(whatsthis)
@@ -58,9 +18,21 @@
#endif
#include <qtextobject.h>
#include <qdesktopservices.h>
+#include <qstringconverter.h>
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
+static inline bool shouldEnableInputMethod(QTextBrowser *texbrowser)
+{
+#if defined (Q_OS_ANDROID)
+ return !texbrowser->isReadOnly() || (texbrowser->textInteractionFlags() & Qt::TextSelectableByMouse);
+#else
+ return !texbrowser->isReadOnly();
+#endif
+}
+
Q_LOGGING_CATEGORY(lcBrowser, "qt.text.browser")
class QTextBrowserPrivate : public QTextEditPrivate
@@ -74,6 +46,11 @@ public:
, lastKeypadScrollValue(-1)
#endif
{}
+ ~QTextBrowserPrivate()
+ {
+ for (const QMetaObject::Connection &connection : connections)
+ QObject::disconnect(connection);
+ }
void init();
@@ -92,13 +69,13 @@ public:
HistoryEntry history(int i) const
{
if (i <= 0)
- if (-i < stack.count())
- return stack[stack.count()+i-1];
+ if (-i < stack.size())
+ return stack[stack.size()+i-1];
else
return HistoryEntry();
else
- if (i <= forwardStack.count())
- return forwardStack[forwardStack.count()-i];
+ if (i <= forwardStack.size())
+ return forwardStack[forwardStack.size()-i];
else
return HistoryEntry();
}
@@ -131,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);
@@ -152,20 +129,26 @@ public:
QTextCursor prevFocus;
int lastKeypadScrollValue;
#endif
+ void emitHighlighted(const QUrl &url)
+ {
+ Q_Q(QTextBrowser);
+ emit q->highlighted(url);
+ }
+ std::array<QMetaObject::Connection, 3> connections;
};
-Q_DECLARE_TYPEINFO(QTextBrowserPrivate::HistoryEntry, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QTextBrowserPrivate::HistoryEntry, Q_RELOCATABLE_TYPE);
QString QTextBrowserPrivate::findFile(const QUrl &name) const
{
QString fileName;
- if (name.scheme() == QLatin1String("qrc")) {
- fileName = QLatin1String(":/") + name.path();
+ if (name.scheme() == "qrc"_L1) {
+ fileName = ":/"_L1 + name.path();
} else if (name.scheme().isEmpty()) {
fileName = name.path();
} else {
#if defined(Q_OS_ANDROID)
- if (name.scheme() == QLatin1String("assets"))
- fileName = QLatin1String("assets:") + name.path();
+ if (name.scheme() == "assets"_L1)
+ fileName = "assets:"_L1 + name.path();
else
#endif
fileName = name.toLocalFile();
@@ -177,9 +160,9 @@ QString QTextBrowserPrivate::findFile(const QUrl &name) const
if (QFileInfo(fileName).isAbsolute())
return fileName;
- for (QString path : qAsConst(searchPaths)) {
- if (!path.endsWith(QLatin1Char('/')))
- path.append(QLatin1Char('/'));
+ for (QString path : std::as_const(searchPaths)) {
+ if (!path.endsWith(u'/'))
+ path.append(u'/');
path.append(fileName);
if (QFileInfo(path).isReadable())
return path;
@@ -196,7 +179,7 @@ QUrl QTextBrowserPrivate::resolveUrl(const QUrl &url) const
// For the second case QUrl can merge "#someanchor" with "foo.html"
// correctly to "foo.html#someanchor"
if (!(currentURL.isRelative()
- || (currentURL.scheme() == QLatin1String("file")
+ || (currentURL.scheme() == "file"_L1
&& !QFileInfo(currentURL.toLocalFile()).isAbsolute()))
|| (url.hasFragment() && url.path().isEmpty())) {
return currentURL.resolved(url);
@@ -213,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;
@@ -234,11 +217,11 @@ void QTextBrowserPrivate::_q_activateAnchor(const QString &href)
#ifndef QT_NO_DESKTOPSERVICES
bool isFileScheme =
- url.scheme() == QLatin1String("file")
+ url.scheme() == "file"_L1
#if defined(Q_OS_ANDROID)
- || url.scheme() == QLatin1String("assets")
+ || url.scheme() == "assets"_L1
#endif
- || url.scheme() == QLatin1String("qrc");
+ || url.scheme() == "qrc"_L1;
if ((openExternalLinks && !isFileScheme && !url.isRelative())
|| (url.isRelative() && !currentURL.isRelative() && !isFileScheme)) {
QDesktopServices::openUrl(url);
@@ -254,26 +237,22 @@ void QTextBrowserPrivate::_q_activateAnchor(const QString &href)
q->setSource(url);
}
-void QTextBrowserPrivate::_q_highlightLink(const QString &anchor)
+void QTextBrowserPrivate::highlightLink(const QString &anchor)
{
- Q_Q(QTextBrowser);
if (anchor.isEmpty()) {
#ifndef QT_NO_CURSOR
if (viewport->cursor().shape() != Qt::PointingHandCursor)
oldCursor = viewport->cursor();
viewport->setCursor(oldCursor);
#endif
- emit q->highlighted(QUrl());
- emit q->highlighted(QString());
+ emitHighlighted(QUrl());
} else {
#ifndef QT_NO_CURSOR
viewport->setCursor(Qt::PointingHandCursor);
#endif
const QUrl url = resolveUrl(anchor);
- emit q->highlighted(url);
- // convenience to ease connecting to QStatusBar::showMessage(const QString &)
- emit q->highlighted(url.toString());
+ emitHighlighted(url);
}
}
@@ -297,9 +276,9 @@ void QTextBrowserPrivate::setSource(const QUrl &url, QTextDocument::ResourceType
QString fileName = url.fileName();
if (type == QTextDocument::UnknownResource) {
#if QT_CONFIG(textmarkdownreader)
- if (fileName.endsWith(QLatin1String(".md")) ||
- fileName.endsWith(QLatin1String(".mkd")) ||
- fileName.endsWith(QLatin1String(".markdown")))
+ if (fileName.endsWith(".md"_L1) ||
+ fileName.endsWith(".mkd"_L1) ||
+ fileName.endsWith(".markdown"_L1))
type = QTextDocument::MarkdownResource;
else
#endif
@@ -310,27 +289,26 @@ void QTextBrowserPrivate::setSource(const QUrl &url, QTextDocument::ResourceType
if (url.isValid()
&& (newUrlWithoutFragment != currentUrlWithoutFragment || forceLoadOnSourceChange)) {
QVariant data = q->loadResource(type, resolveUrl(url));
- if (data.type() == QVariant::String) {
+ if (data.userType() == QMetaType::QString) {
txt = data.toString();
- } else if (data.type() == QVariant::ByteArray) {
+ } else if (data.userType() == QMetaType::QByteArray) {
+ QByteArray ba = data.toByteArray();
if (type == QTextDocument::HtmlResource) {
-#if QT_CONFIG(textcodec)
- QByteArray ba = data.toByteArray();
- QTextCodec *codec = Qt::codecForHtml(ba);
- txt = codec->toUnicode(ba);
-#else
- txt = data.toString();
-#endif
+ auto decoder = QStringDecoder::decoderForHtml(ba);
+ if (!decoder.isValid())
+ // fall back to utf8
+ decoder = QStringDecoder(QStringDecoder::Utf8);
+ txt = decoder(ba);
} else {
- txt = QString::fromUtf8(data.toByteArray());
+ txt = QString::fromUtf8(ba);
}
}
if (Q_UNLIKELY(txt.isEmpty()))
qWarning("QTextBrowser: No document for %s", url.toString().toLatin1().constData());
if (q->isVisible()) {
- const QStringRef firstTag = txt.leftRef(txt.indexOf(QLatin1Char('>')) + 1);
- if (firstTag.startsWith(QLatin1String("<qt")) && firstTag.contains(QLatin1String("type")) && firstTag.contains(QLatin1String("detail"))) {
+ const QStringView firstTag = QStringView{txt}.left(txt.indexOf(u'>') + 1);
+ if (firstTag.startsWith("<qt"_L1) && firstTag.contains("type"_L1) && firstTag.contains("detail"_L1)) {
#ifndef QT_NO_CURSOR
QGuiApplication::restoreOverrideCursor();
#endif
@@ -383,8 +361,7 @@ void QTextBrowserPrivate::setSource(const QUrl &url, QTextDocument::ResourceType
}
#ifdef QT_KEYPAD_NAVIGATION
lastKeypadScrollValue = vbar->value();
- emit q->highlighted(QUrl());
- emit q->highlighted(QString());
+ emitHighlighted(QUrl());
#endif
#ifndef QT_NO_CURSOR
@@ -506,7 +483,7 @@ void QTextBrowserPrivate::keypadMove(bool next)
// up e.g. 110%
// Obviously if a link is entirely visible, we still
// focus it.
- if(bothViewRects.contains(desiredRect)
+ if (bothViewRects.contains(desiredRect)
|| bothViewRects.adjusted(0, visibleLinkAmount, 0, -visibleLinkAmount).intersects(desiredRect)) {
focusIt = true;
@@ -535,7 +512,7 @@ void QTextBrowserPrivate::keypadMove(bool next)
if (!focusIt && prevFocus.hasSelection()) {
QRectF desiredRect = control->selectionRect(prevFocus);
// XXX this may be better off also using the visibleLinkAmount value
- if(newViewRect.intersects(desiredRect)) {
+ if (newViewRect.intersects(desiredRect)) {
focusedPos = scrollYOffset;
focusIt = true;
anchorToFocus = prevFocus;
@@ -559,8 +536,7 @@ void QTextBrowserPrivate::keypadMove(bool next)
// Ensure that the new selection is highlighted.
const QString href = control->anchorAtCursor();
QUrl url = resolveUrl(href);
- emit q->highlighted(url);
- emit q->highlighted(url.toString());
+ emitHighlighted(url);
} else {
// Scroll
vbar->setValue(scrollYOffset);
@@ -575,8 +551,7 @@ void QTextBrowserPrivate::keypadMove(bool next)
hbar->setValue(savedXOffset);
vbar->setValue(scrollYOffset);
- emit q->highlighted(QUrl());
- emit q->highlighted(QString());
+ emitHighlighted(QUrl());
}
}
#endif
@@ -619,8 +594,7 @@ void QTextBrowserPrivate::restoreHistoryEntry(const HistoryEntry &entry)
Q_Q(QTextBrowser);
const QString href = prevFocus.charFormat().anchorHref();
QUrl url = resolveUrl(href);
- emit q->highlighted(url);
- emit q->highlighted(url.toString());
+ emitHighlighted(url);
#endif
}
@@ -699,14 +673,17 @@ void QTextBrowserPrivate::init()
#ifndef QT_NO_CURSOR
viewport->setCursor(oldCursor);
#endif
- q->setAttribute(Qt::WA_InputMethodEnabled, !q->isReadOnly());
+ 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),
+ };
}
/*!
@@ -813,13 +790,6 @@ void QTextBrowser::reload()
setSource(s, d->currentType);
}
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
-void QTextBrowser::setSource(const QUrl &url)
-{
- setSource(url, QTextDocument::UnknownResource);
-}
-#endif
-
/*!
Attempts to load the document at the given \a url with the specified \a type.
@@ -835,14 +805,12 @@ void QTextBrowser::setSource(const QUrl &url, QTextDocument::ResourceType type)
doSetSource(url, type);
}
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
/*!
Attempts to load the document at the given \a url with the specified \a type.
setSource() calls doSetSource. In Qt 5, setSource(const QUrl &url) was virtual.
In Qt 6, doSetSource() is virtual instead, so that it can be overridden in subclasses.
*/
-#endif
void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type)
{
Q_D(QTextBrowser);
@@ -869,11 +837,11 @@ void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type
entry.vpos = 0;
d->stack.push(entry);
- emit backwardAvailable(d->stack.count() > 1);
+ emit backwardAvailable(d->stack.size() > 1);
if (!d->forwardStack.isEmpty() && d->forwardStack.top().url == url) {
d->forwardStack.pop();
- emit forwardAvailable(d->forwardStack.count() > 0);
+ emit forwardAvailable(d->forwardStack.size() > 0);
} else {
d->forwardStack.clear();
emit forwardAvailable(false);
@@ -914,7 +882,7 @@ void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type
being the new source.
Source changes happen both programmatically when calling
- setSource(), forward(), backword() or home() or when the user
+ setSource(), forward(), backward() or home() or when the user
clicks on links or presses the equivalent key sequences.
*/
@@ -925,15 +893,6 @@ void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type
anchor is passed in \a link.
*/
-/*! \fn void QTextBrowser::highlighted(const QString &link)
- \overload
-
- Convenience signal that allows connecting to a slot
- that takes just a QString, like for example QStatusBar's
- message().
-*/
-
-
/*!
\fn void QTextBrowser::anchorClicked(const QUrl &link)
@@ -956,14 +915,14 @@ void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type
void QTextBrowser::backward()
{
Q_D(QTextBrowser);
- if (d->stack.count() <= 1)
+ if (d->stack.size() <= 1)
return;
// Update the history entry
d->forwardStack.push(d->createHistoryEntry());
d->stack.pop(); // throw away the old version of the current entry
d->restoreHistoryEntry(d->stack.top()); // previous entry
- emit backwardAvailable(d->stack.count() > 1);
+ emit backwardAvailable(d->stack.size() > 1);
emit forwardAvailable(true);
emit historyChanged();
}
@@ -1127,8 +1086,7 @@ bool QTextBrowser::focusNextPrevChild(bool next)
if (d->prevFocus != d->control->textCursor() && d->control->textCursor().hasSelection()) {
const QString href = d->control->anchorAtCursor();
QUrl url = d->resolveUrl(href);
- emit highlighted(url);
- emit highlighted(url.toString());
+ emitHighlighted(url);
}
d->prevFocus = d->control->textCursor();
#endif
@@ -1136,8 +1094,7 @@ bool QTextBrowser::focusNextPrevChild(bool next)
} else {
#ifdef QT_KEYPAD_NAVIGATION
// We assume we have no highlight now.
- emit highlighted(QUrl());
- emit highlighted(QString());
+ emitHighlighted(QUrl());
#endif
}
return QTextEdit::focusNextPrevChild(next);
@@ -1171,7 +1128,7 @@ void QTextBrowser::paintEvent(QPaintEvent *e)
depending on the resource type:
\table
- \header \li ResourceType \li QVariant::Type
+ \header \li ResourceType \li QMetaType::Type
\row \li QTextDocument::HtmlResource \li QString or QByteArray
\row \li QTextDocument::ImageResource \li QImage, QPixmap or QByteArray
\row \li QTextDocument::StyleSheetResource \li QString or QByteArray
@@ -1208,7 +1165,7 @@ QVariant QTextBrowser::loadResource(int /*type*/, const QUrl &name)
bool QTextBrowser::isBackwardAvailable() const
{
Q_D(const QTextBrowser);
- return d->stack.count() > 1;
+ return d->stack.size() > 1;
}
/*!
@@ -1295,7 +1252,7 @@ QString QTextBrowser::historyTitle(int i) const
int QTextBrowser::forwardHistoryCount() const
{
Q_D(const QTextBrowser);
- return d->forwardStack.count();
+ return d->forwardStack.size();
}
/*!
@@ -1306,7 +1263,7 @@ int QTextBrowser::forwardHistoryCount() const
int QTextBrowser::backwardHistoryCount() const
{
Q_D(const QTextBrowser);
- return d->stack.count()-1;
+ return d->stack.size()-1;
}
/*!
diff --git a/src/widgets/widgets/qtextbrowser.h b/src/widgets/widgets/qtextbrowser.h
index 33e5b3980c..f8e9c0c301 100644
--- a/src/widgets/widgets/qtextbrowser.h
+++ b/src/widgets/widgets/qtextbrowser.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTEXTBROWSER_H
#define QTEXTBROWSER_H
@@ -90,12 +54,7 @@ public:
void setOpenLinks(bool open);
public Q_SLOTS:
-#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
- virtual void setSource(const QUrl &name);
- void setSource(const QUrl &name, QTextDocument::ResourceType type);
-#else
void setSource(const QUrl &name, QTextDocument::ResourceType type = QTextDocument::UnknownResource);
-#endif
virtual void backward();
virtual void forward();
virtual void home();
@@ -107,7 +66,6 @@ Q_SIGNALS:
void historyChanged();
void sourceChanged(const QUrl &);
void highlighted(const QUrl &);
- void highlighted(const QString &);
void anchorClicked(const QUrl &);
protected:
@@ -119,17 +77,11 @@ protected:
virtual void focusOutEvent(QFocusEvent *ev) override;
virtual bool focusNextPrevChild(bool next) override;
virtual void paintEvent(QPaintEvent *e) override;
-#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
- virtual
-#endif
- void doSetSource(const QUrl &name, QTextDocument::ResourceType type = QTextDocument::UnknownResource);
+ virtual void doSetSource(const QUrl &name, QTextDocument::ResourceType type = QTextDocument::UnknownResource);
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 10de7d0b9e..90884dd438 100644
--- a/src/widgets/widgets/qtextedit.cpp
+++ b/src/widgets/widgets/qtextedit.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 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 "qtextedit_p.h"
#if QT_CONFIG(lineedit)
@@ -58,7 +22,7 @@
#endif
#include <qstyle.h>
#include <qtimer.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include <qaccessible.h>
#endif
#include "private/qtextdocumentlayout_p.h"
@@ -79,7 +43,11 @@ QT_BEGIN_NAMESPACE
static inline bool shouldEnableInputMethod(QTextEdit *textedit)
{
+#if defined (Q_OS_ANDROID)
+ return !textedit->isReadOnly() || (textedit->textInteractionFlags() & Qt::TextSelectableByMouse);
+#else
return !textedit->isReadOnly();
+#endif
}
class QTextEditControl : public QWidgetTextControl
@@ -120,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;
@@ -129,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();
@@ -155,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
@@ -202,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();
@@ -220,19 +203,19 @@ void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
viewport->update(r);
}
-void QTextEditPrivate::_q_cursorPositionChanged()
+void QTextEditPrivate::cursorPositionChanged()
{
Q_Q(QTextEdit);
emit q->cursorPositionChanged();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleTextCursorEvent event(q, q->textCursor().position());
QAccessible::updateAccessibility(&event);
#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()) {
@@ -244,8 +227,8 @@ void QTextEditPrivate::_q_hoveredBlockWithMarkerChanged(const QTextBlock &block)
}
}
viewport->setCursor(cursor);
-}
#endif
+}
void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode)
{
@@ -270,7 +253,7 @@ void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::Mo
vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
}
}
- control->setTextCursor(cursor);
+ control->setTextCursor(cursor, moveMode == QTextCursor::KeepAnchor);
}
#if QT_CONFIG(scrollbar)
@@ -294,7 +277,7 @@ static QSize documentSize(QWidgetTextControl *control)
return docSize;
}
-void QTextEditPrivate::_q_adjustScrollbars()
+void QTextEditPrivate::adjustScrollbars()
{
if (ignoreAutomaticScrollbarAdjustment)
return;
@@ -344,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();
@@ -572,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, {Application Example},
+ \sa QTextDocument, QTextCursor,
{Syntax Highlighter Example}, {Rich Text Processing}
*/
@@ -580,8 +563,9 @@ void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
\property QTextEdit::plainText
\since 4.3
- This property gets and sets the text editor's contents as plain
- text. Previous contents are removed and undo/redo history is reset
+ \brief the text editor's contents as plain text.
+
+ Previous contents are removed and undo/redo history is reset
when the property is set. currentCharFormat() is also reset, unless
textCursor() is already at the beginning of the document.
@@ -598,7 +582,7 @@ void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
/*!
\property QTextEdit::undoRedoEnabled
- \brief whether undo and redo are enabled
+ \brief whether undo and redo are enabled.
Users are only able to undo or redo actions if this property is
true, and if there is an action that can be undone (or redone).
@@ -685,7 +669,7 @@ qreal QTextEdit::fontPointSize() const
QString QTextEdit::fontFamily() const
{
Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().fontFamily();
+ return d->control->textCursor().charFormat().fontFamilies().toStringList().value(0, QString());
}
/*!
@@ -744,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();
}
/*!
@@ -877,7 +862,7 @@ QTextCursor QTextEdit::textCursor() const
void QTextEdit::setFontFamily(const QString &fontFamily)
{
QTextCharFormat fmt;
- fmt.setFontFamily(fontFamily);
+ fmt.setFontFamilies({fontFamily});
mergeCurrentCharFormat(fmt);
}
@@ -1095,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);
}
@@ -1272,6 +1265,7 @@ QString QTextEdit::toHtml() const
The default is \c MarkdownDialectGitHub.
\sa plainText, html, QTextDocument::toMarkdown(), QTextDocument::setMarkdown()
+ \since 5.14
*/
#endif
@@ -1401,8 +1395,8 @@ void QTextEdit::keyPressEvent(QKeyEvent *e)
const QString text = e->text();
if (cursor.atBlockStart()
&& (d->autoFormatting & AutoBulletList)
- && (text.length() == 1)
- && (text.at(0) == QLatin1Char('-') || text.at(0) == QLatin1Char('*'))
+ && (text.size() == 1)
+ && (text.at(0) == u'-' || text.at(0) == u'*')
&& (!cursor.currentList())) {
d->createAutoBulletList();
@@ -1450,8 +1444,10 @@ void QTextEdit::keyPressEvent(QKeyEvent *e)
*/
void QTextEdit::keyReleaseEvent(QKeyEvent *e)
{
-#ifdef QT_KEYPAD_NAVIGATION
Q_D(QTextEdit);
+ if (!isReadOnly())
+ d->handleSoftwareInputPanel();
+#ifdef QT_KEYPAD_NAVIGATION
if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!e->isAutoRepeat() && e->key() == Qt::Key_Back
&& d->deleteAllTimer.isActive()) {
@@ -1502,10 +1498,10 @@ void QTextEdit::resizeEvent(QResizeEvent *e)
QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
if (!doc->pageSize().isNull()
- && alignmentProperty.type() == QVariant::Bool
+ && alignmentProperty.userType() == QMetaType::Bool
&& !alignmentProperty.toBool()) {
- d->_q_adjustScrollbars();
+ d->adjustScrollbars();
return;
}
}
@@ -1514,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()
@@ -1536,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 +1543,7 @@ void QTextEditPrivate::relayoutDocument()
width = lineWrapColumnOrWidth;
else if (lineWrap == QTextEdit::NoWrap) {
QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
- if (alignmentProperty.type() == QVariant::Bool && !alignmentProperty.toBool()) {
+ if (alignmentProperty.userType() == QMetaType::Bool && !alignmentProperty.toBool()) {
width = 0;
}
@@ -1575,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.
//
@@ -1588,7 +1584,7 @@ void QTextEditPrivate::relayoutDocument()
&& usedSize.height() <= viewport->height())
return;
- _q_adjustScrollbars();
+ adjustScrollbars();
}
void QTextEditPrivate::paint(QPainter *p, QPaintEvent *e)
@@ -1626,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.
*/
@@ -1636,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();
@@ -1676,7 +1668,7 @@ void QTextEdit::mouseMoveEvent(QMouseEvent *e)
{
Q_D(QTextEdit);
d->inDrag = false; // paranoia
- const QPoint pos = e->pos();
+ const QPoint pos = e->position().toPoint();
d->sendControlEvent(e);
if (!(e->buttons() & Qt::LeftButton))
return;
@@ -1699,7 +1691,7 @@ void QTextEdit::mouseReleaseEvent(QMouseEvent *e)
d->autoScrollTimer.stop();
ensureCursorVisible();
}
- if (!isReadOnly() && rect().contains(e->pos()))
+ if (!isReadOnly() && rect().contains(e->position().toPoint()))
d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
d->clickCausedFocus = 0;
}
@@ -1770,7 +1762,7 @@ void QTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
void QTextEdit::dragMoveEvent(QDragMoveEvent *e)
{
Q_D(QTextEdit);
- d->autoScrollDragPos = e->pos();
+ d->autoScrollDragPos = e->position().toPoint();
if (!d->autoScrollTimer.isActive())
d->autoScrollTimer.start(100, this);
d->sendControlEvent(e);
@@ -1800,6 +1792,10 @@ void QTextEdit::inputMethodEvent(QInputMethodEvent *e)
setEditFocus(true);
#endif
d->sendControlEvent(e);
+ const bool emptyEvent = e->preeditString().isEmpty() && e->commitString().isEmpty()
+ && e->attributes().isEmpty();
+ if (emptyEvent)
+ return;
ensureCursorVisible();
}
@@ -1827,25 +1823,29 @@ QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant argume
{
Q_D(const QTextEdit);
switch (query) {
- case Qt::ImHints:
- case Qt::ImInputItemClipRectangle:
+ case Qt::ImEnabled:
+ return isEnabled() && !isReadOnly();
+ case Qt::ImHints:
+ case Qt::ImInputItemClipRectangle:
return QWidget::inputMethodQuery(query);
+ case Qt::ImReadOnly:
+ return isReadOnly();
default:
break;
}
const QPointF offset(-d->horizontalOffset(), -d->verticalOffset());
- switch (argument.type()) {
- case QVariant::RectF:
+ switch (argument.userType()) {
+ case QMetaType::QRectF:
argument = argument.toRectF().translated(-offset);
break;
- case QVariant::PointF:
+ case QMetaType::QPointF:
argument = argument.toPointF() - offset;
break;
- case QVariant::Rect:
+ case QMetaType::QRect:
argument = argument.toRect().translated(-offset.toPoint());
break;
- case QVariant::Point:
+ case QMetaType::QPoint:
argument = argument.toPoint() - offset;
break;
default:
@@ -1853,14 +1853,14 @@ QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant argume
}
const QVariant v = d->control->inputMethodQuery(query, argument);
- switch (v.type()) {
- case QVariant::RectF:
+ switch (v.userType()) {
+ case QMetaType::QRectF:
return v.toRectF().translated(offset);
- case QVariant::PointF:
+ case QMetaType::QPointF:
return v.toPointF() + offset;
- case QVariant::Rect:
+ case QMetaType::QRect:
return v.toRect().translated(offset.toPoint());
- case QVariant::Point:
+ case QMetaType::QPoint:
return v.toPoint() + offset.toPoint();
default:
break;
@@ -1913,7 +1913,7 @@ void QTextEdit::changeEvent(QEvent *e)
if (e->type() == QEvent::ApplicationFontChange
|| e->type() == QEvent::FontChange) {
d->control->document()->setDefaultFont(font());
- } else if(e->type() == QEvent::ActivationChange) {
+ } else if (e->type() == QEvent::ActivationChange) {
if (!isActiveWindow())
d->autoScrollTimer.stop();
} else if (e->type() == QEvent::EnabledChange) {
@@ -2052,33 +2052,18 @@ void QTextEdit::setOverwriteMode(bool overwrite)
d->control->setOverwriteMode(overwrite);
}
-#if QT_DEPRECATED_SINCE(5, 10)
-/*!
- \property QTextEdit::tabStopWidth
- \brief the tab stop width in pixels
- \since 4.1
- \deprecated in Qt 5.10. Use tabStopDistance instead.
-
- By default, this property contains a value of 80 pixels.
-*/
-
-int QTextEdit::tabStopWidth() const
-{
- return qRound(tabStopDistance());
-}
-
-void QTextEdit::setTabStopWidth(int width)
-{
- setTabStopDistance(width);
-}
-#endif
-
/*!
\property QTextEdit::tabStopDistance
\brief the tab stop distance in pixels
\since 5.10
By default, this property contains a value of 80 pixels.
+
+ Do not set a value less than the \l {QFontMetrics::}{horizontalAdvance()}
+ of the QChar::VisualTabCharacter character, otherwise the tab-character
+ will be drawn incompletely.
+
+ \sa QTextOption::ShowTabsAndSpaces, QTextDocument::defaultTextOption
*/
qreal QTextEdit::tabStopDistance() const
@@ -2120,7 +2105,7 @@ void QTextEdit::setCursorWidth(int width)
\brief whether the text edit accepts rich text insertions by the user
\since 4.1
- When this propery is set to false text edit will accept only
+ When this property is set to false text edit will accept only
plain text input from the user. For example through clipboard or drag and drop.
This property's default is true.
@@ -2244,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)
@@ -2401,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);
}
@@ -2609,38 +2594,20 @@ bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
}
/*!
- \fn bool QTextEdit::find(const QRegExp &exp, QTextDocument::FindFlags options)
-
- \since 5.3
- \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 QRegExp::caseSensitivity instead.
-
- Returns \c true if a match was found and changes the cursor to select the match;
- otherwise returns \c false.
-*/
-#ifndef QT_NO_REGEXP
-bool QTextEdit::find(const QRegExp &exp, QTextDocument::FindFlags options)
-{
- Q_D(QTextEdit);
- return d->control->find(exp, options);
-}
-#endif
-
-/*!
\fn bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
\since 5.13
\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)
@@ -2704,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 5c8a3c7793..421eb9136b 100644
--- a/src/widgets/widgets/qtextedit.h
+++ b/src/widgets/widgets/qtextedit.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 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 QTEXTEDIT_H
#define QTEXTEDIT_H
@@ -79,13 +43,11 @@ class Q_WIDGETS_EXPORT QTextEdit : public QAbstractScrollArea
#endif
Q_PROPERTY(QString plainText READ toPlainText WRITE setPlainText DESIGNABLE false)
Q_PROPERTY(bool overwriteMode READ overwriteMode WRITE setOverwriteMode)
-#if QT_DEPRECATED_SINCE(5, 10)
- Q_PROPERTY(int tabStopWidth READ tabStopWidth WRITE setTabStopWidth)
-#endif
Q_PROPERTY(qreal tabStopDistance READ tabStopDistance WRITE setTabStopDistance)
Q_PROPERTY(bool acceptRichText READ acceptRichText WRITE setAcceptRichText)
Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
+ Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags
+ WRITE setTextInteractionFlags)
Q_PROPERTY(QTextDocument *document READ document WRITE setDocument DESIGNABLE false)
Q_PROPERTY(QString placeholderText READ placeholderText WRITE setPlaceholderText)
public:
@@ -166,9 +128,6 @@ public:
void setWordWrapMode(QTextOption::WrapMode policy);
bool find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
-#ifndef QT_NO_REGEXP
- bool find(const QRegExp &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
-#endif
#if QT_CONFIG(regularexpression)
bool find(const QRegularExpression &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#endif
@@ -198,11 +157,6 @@ public:
bool overwriteMode() const;
void setOverwriteMode(bool overwrite);
-#if QT_DEPRECATED_SINCE(5, 10)
- QT_DEPRECATED int tabStopWidth() const;
- QT_DEPRECATED void setTabStopWidth(int width);
-#endif
-
qreal tabStopDistance() const;
void setTabStopDistance(qreal distance);
@@ -326,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 f7b4d15318..7dd7d9c107 100644
--- a/src/widgets/widgets/qtextedit_p.h
+++ b/src/widgets/widgets/qtextedit_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTEXTEDIT_P_H
#define QTEXTEDIT_P_H
@@ -69,6 +33,8 @@
#include "private/qwidgettextcontrol_p.h"
+#include <array>
+
QT_REQUIRE_CONFIG(textedit);
QT_BEGIN_NAMESPACE
@@ -79,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();
@@ -102,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();
@@ -130,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 f35c02f2fb..5e5ef8e8d5 100644
--- a/src/widgets/widgets/qtoolbar.cpp
+++ b/src/widgets/widgets/qtoolbar.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtoolbar.h"
@@ -43,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>
@@ -50,6 +17,7 @@
#if QT_CONFIG(menubar)
#include <qmenubar.h>
#endif
+#include <qmimedata.h>
#if QT_CONFIG(rubberband)
#include <qrubberband.h>
#endif
@@ -60,8 +28,9 @@
#include <qtimer.h>
#include <private/qwidgetaction_p.h>
#include <private/qmainwindowlayout_p.h>
+#include <private/qhighdpiscaling_p.h>
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
#include <qpa/qplatformnativeinterface.h>
#endif
@@ -75,6 +44,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
// qmainwindow.cpp
extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
@@ -140,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);
}
@@ -152,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)
@@ -207,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()
@@ -247,8 +237,8 @@ bool QToolBarPrivate::mousePressEvent(QMouseEvent *event)
Q_Q(QToolBar);
QStyleOptionToolBar opt;
q->initStyleOption(&opt);
- if (q->style()->subElementRect(QStyle::SE_ToolBarHandle, &opt, q).contains(event->pos()) == false) {
-#ifdef Q_OS_OSX
+ if (q->style()->subElementRect(QStyle::SE_ToolBarHandle, &opt, q).contains(event->position().toPoint()) == false) {
+#ifdef Q_OS_MACOS
// When using the unified toolbar on OS X, the user can click and
// drag between toolbar contents to move the window. Make this work by
// implementing the standard mouse-dragging code and then call
@@ -272,17 +262,24 @@ bool QToolBarPrivate::mousePressEvent(QMouseEvent *event)
if (!layout->movable())
return true;
- initDrag(event->pos());
+ initDrag(event->position().toPoint());
return true;
}
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;
} else {
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
if (!macWindowDragging)
return false;
macWindowDragging = false;
@@ -298,7 +295,7 @@ bool QToolBarPrivate::mouseMoveEvent(QMouseEvent *event)
Q_Q(QToolBar);
if (!state) {
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
if (!macWindowDragging)
return false;
QWidget *w = q->window();
@@ -317,19 +314,24 @@ bool QToolBarPrivate::mouseMoveEvent(QMouseEvent *event)
Q_ASSERT(layout != nullptr);
if (layout->pluggingWidget == nullptr
- && (event->pos() - state->pressPos).manhattanLength() > QApplication::startDragDistance()) {
+ && (event->position().toPoint() - state->pressPos).manhattanLength() > QApplication::startDragDistance()) {
const bool wasDragging = state->dragging;
const bool moving = !q->isWindow() && (orientation == Qt::Vertical ?
- event->x() >= 0 && event->x() < q->width() :
- event->y() >= 0 && event->y() < q->height());
+ event->position().toPoint().x() >= 0 && event->position().toPoint().x() < q->width() :
+ event->position().toPoint().y() >= 0 && event->position().toPoint().y() < q->height());
startDrag(moving);
if (!moving && !wasDragging)
q->grabMouse();
}
+ if (!state) {
+ q->releaseMouse();
+ return true;
+ }
+
if (state->dragging) {
- QPoint pos = event->globalPos();
+ QPoint pos = event->globalPosition().toPoint();
// if we are right-to-left, we move so as to keep the right edge the same distance
// from the mouse
if (q->isLeftToRight())
@@ -338,14 +340,19 @@ bool QToolBarPrivate::mouseMoveEvent(QMouseEvent *event)
pos += QPoint(state->pressPos.x() - q->width(), -state->pressPos.y());
q->move(pos);
- layout->hover(state->widgetItem, event->globalPos());
+ layout->hover(state->widgetItem, event->globalPosition().toPoint());
} else if (state->moving) {
const QPoint rtl(q->width() - state->pressPos.x(), state->pressPos.y()); //for RTL
const QPoint globalPressPos = q->mapToGlobal(q->isRightToLeft() ? rtl : state->pressPos);
int pos = 0;
- QPoint delta = event->globalPos() - 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 {
@@ -388,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
@@ -411,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, {Application Example}
+ \sa QToolButton, QMenu, QAction
*/
/*!
@@ -737,117 +748,6 @@ void QToolBar::clear()
}
/*!
- Creates a new action with the given \a text. This action is added to
- the end of the toolbar.
-*/
-QAction *QToolBar::addAction(const QString &text)
-{
- QAction *action = new QAction(text, this);
- addAction(action);
- return action;
-}
-
-/*!
- \overload
-
- Creates a new action with the given \a icon and \a text. This
- action is added to the end of the toolbar.
-*/
-QAction *QToolBar::addAction(const QIcon &icon, const QString &text)
-{
- QAction *action = new QAction(icon, text, this);
- addAction(action);
- return action;
-}
-
-/*!
- \overload
-
- Creates a new action with the given \a text. This action is added to
- the end of the toolbar. The action's \l{QAction::triggered()}{triggered()}
- signal is connected to \a member in \a receiver.
-*/
-QAction *QToolBar::addAction(const QString &text,
- const QObject *receiver, const char* member)
-{
- QAction *action = new QAction(text, this);
- QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
- addAction(action);
- return action;
-}
-
-/*!
- \overload
-
- Creates a new action with the given \a icon and \a text. This
- action is added to the end of the toolbar. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to \a
- member in \a receiver.
-*/
-QAction *QToolBar::addAction(const QIcon &icon, const QString &text,
- const QObject *receiver, const char* member)
-{
- QAction *action = new QAction(icon, text, this);
- QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
- addAction(action);
- return action;
-}
-
-/*!\fn template<typename Functor> QAction *QToolBar::addAction(const QString &text, Functor functor)
-
- \since 5.6
-
- \overload
-
- Creates a new action with the given \a text. This action is added to
- the end of the toolbar. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a functor.
-*/
-
-/*!\fn template<typename Functor> QAction *QToolBar::addAction(const QString &text, const QObject *context, Functor functor)
-
- \since 5.6
-
- \overload
-
- Creates a new action with the given \a text. This action is added
- to the end of the toolbar. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a functor. The \a functor can be a pointer to a member function
- in the \a context object.
-
- If the \a context object is destroyed, the \a functor will not be called.
-*/
-
-/*!\fn template<typename Functor> QAction *QToolBar::addAction(const QIcon &icon, const QString &text, Functor functor)
-
- \since 5.6
-
- \overload
-
- Creates a new action with the given \a icon and \a text. This
- action is added to the end of the toolbar. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a functor.
-*/
-
-/*!\fn template<typename Functor> QAction *QToolBar::addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor)
-
- \since 5.6
-
- \overload
-
- Creates a new action with the given \a icon and \a text. This
- action is added to the end of the toolbar. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a functor. The \a functor can be a pointer to a member function
- of the \a context object.
-
- If the \a context object is destroyed, the \a functor will not be called.
-*/
-
-/*!
Adds a separator to the end of the toolbar.
\sa insertSeparator()
@@ -1073,17 +973,18 @@ static bool waitForPopup(QToolBar *tb, QWidget *popup)
if (menu == nullptr)
return false;
- QAction *action = menu->menuAction();
- QList<QWidget*> widgets = action->associatedWidgets();
- for (int i = 0; i < widgets.count(); ++i) {
- if (waitForPopup(tb, widgets.at(i)))
- return true;
+ const QAction *action = menu->menuAction();
+ for (auto object : action->associatedObjects()) {
+ if (QWidget *widget = qobject_cast<QWidget*>(object)) {
+ if (waitForPopup(tb, widget))
+ return true;
+ }
}
return false;
}
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
static void enableMacToolBar(QToolBar *toolbar, bool enable)
{
QPlatformNativeInterface *nativeInterface = QApplication::platformNativeInterface();
@@ -1122,7 +1023,7 @@ bool QToolBar::event(QEvent *event)
Q_FALLTHROUGH();
case QEvent::Show:
d->toggleViewAction->setChecked(event->type() == QEvent::Show);
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
enableMacToolBar(this, event->type() == QEvent::Show);
#endif
emit visibilityChanged(event->type() == QEvent::Show);
@@ -1149,7 +1050,7 @@ bool QToolBar::event(QEvent *event)
QHoverEvent *e = static_cast<QHoverEvent*>(event);
QStyleOptionToolBar opt;
initStyleOption(&opt);
- if (style()->subElementRect(QStyle::SE_ToolBarHandle, &opt, this).contains(e->pos()))
+ if (style()->subElementRect(QStyle::SE_ToolBarHandle, &opt, this).contains(e->position().toPoint()))
setCursor(Qt::SizeAllCursor);
else
unsetCursor();
@@ -1163,7 +1064,7 @@ bool QToolBar::event(QEvent *event)
case QEvent::Leave:
if (d->state != nullptr && d->state->dragging) {
#ifdef Q_OS_WIN
- // This is a workaround for loosing the mouse on Vista.
+ // This is a workaround for losing the mouse on Vista.
QPoint pos = QCursor::pos();
QMouseEvent fake(QEvent::MouseMove, mapFromGlobal(pos), pos, Qt::NoButton,
QGuiApplication::mouseButtons(), QGuiApplication::keyboardModifiers());
@@ -1183,6 +1084,7 @@ bool QToolBar::event(QEvent *event)
d->layout->setExpanded(false);
break;
}
+ break;
default:
break;
}
diff --git a/src/widgets/widgets/qtoolbar.h b/src/widgets/widgets/qtoolbar.h
index 6aaf59cafd..fbad25c7c9 100644
--- a/src/widgets/widgets/qtoolbar.h
+++ b/src/widgets/widgets/qtoolbar.h
@@ -1,47 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDYNAMICTOOLBAR_H
#define QDYNAMICTOOLBAR_H
#include <QtWidgets/qtwidgetsglobal.h>
-#include <QtWidgets/qaction.h>
+#include <QtGui/qaction.h>
#include <QtWidgets/qwidget.h>
QT_REQUIRE_CONFIG(toolbar);
@@ -60,8 +24,10 @@ class Q_WIDGETS_EXPORT QToolBar : public QWidget
Q_OBJECT
Q_PROPERTY(bool movable READ isMovable WRITE setMovable NOTIFY movableChanged)
- Q_PROPERTY(Qt::ToolBarAreas allowedAreas READ allowedAreas WRITE setAllowedAreas NOTIFY allowedAreasChanged)
- Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation NOTIFY orientationChanged)
+ Q_PROPERTY(Qt::ToolBarAreas allowedAreas READ allowedAreas WRITE setAllowedAreas
+ NOTIFY allowedAreasChanged)
+ Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation
+ NOTIFY orientationChanged)
Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize NOTIFY iconSizeChanged)
Q_PROPERTY(Qt::ToolButtonStyle toolButtonStyle READ toolButtonStyle WRITE setToolButtonStyle
NOTIFY toolButtonStyleChanged)
@@ -88,58 +54,13 @@ public:
void clear();
using QWidget::addAction;
+#if QT_WIDGETS_REMOVED_SINCE(6, 3)
QAction *addAction(const QString &text);
QAction *addAction(const QIcon &icon, const QString &text);
QAction *addAction(const QString &text, const QObject *receiver, const char* member);
QAction *addAction(const QIcon &icon, const QString &text,
const QObject *receiver, const char* member);
-#ifdef Q_CLANG_QDOC
- template<typename Functor>
- QAction *addAction(const QString &text, Functor functor);
- template<typename Functor>
- QAction *addAction(const QString &text, const QObject *context, Functor functor);
- template<typename Functor>
- QAction *addAction(const QIcon &icon, const QString &text, Functor functor);
- template<typename Functor>
- QAction *addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor);
-#else
- // addAction(QString): Connect to a QObject slot / functor or function pointer (with context)
- template<class Obj, typename Func1>
- inline typename std::enable_if<!std::is_same<const char*, Func1>::value
- && QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::type
- addAction(const QString &text, const Obj *object, Func1 slot)
- {
- QAction *result = addAction(text);
- connect(result, &QAction::triggered, object, std::move(slot));
- return result;
- }
- // addAction(QString): Connect to a functor or function pointer (without context)
- template <typename Func1>
- inline QAction *addAction(const QString &text, Func1 slot)
- {
- QAction *result = addAction(text);
- connect(result, &QAction::triggered, slot);
- return result;
- }
- // addAction(QString): Connect to a QObject slot / functor or function pointer (with context)
- template<class Obj, typename Func1>
- inline typename std::enable_if<!std::is_same<const char*, Func1>::value
- && QtPrivate::IsPointerToTypeDerivedFromQObject<Obj*>::Value, QAction *>::type
- addAction(const QIcon &actionIcon, const QString &text, const Obj *object, Func1 slot)
- {
- QAction *result = addAction(actionIcon, text);
- connect(result, &QAction::triggered, object, std::move(slot));
- return result;
- }
- // addAction(QIcon, QString): Connect to a functor or function pointer (without context)
- template <typename Func1>
- inline QAction *addAction(const QIcon &actionIcon, const QString &text, Func1 slot)
- {
- QAction *result = addAction(actionIcon, text);
- connect(result, &QAction::triggered, slot);
- return result;
- }
-#endif // !Q_CLANG_QDOC
+#endif
QAction *addSeparator();
QAction *insertSeparator(QAction *before);
@@ -181,7 +102,7 @@ protected:
void changeEvent(QEvent *event) override;
void paintEvent(QPaintEvent *event) override;
bool event(QEvent *event) override;
- void initStyleOption(QStyleOptionToolBar *option) const;
+ virtual void initStyleOption(QStyleOptionToolBar *option) const;
private:
diff --git a/src/widgets/widgets/qtoolbar_p.h b/src/widgets/widgets/qtoolbar_p.h
index 8cb5850903..2561cd8f64 100644
--- a/src/widgets/widgets/qtoolbar_p.h
+++ b/src/widgets/widgets/qtoolbar_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDYNAMICTOOLBAR_P_H
#define QDYNAMICTOOLBAR_P_H
@@ -53,7 +17,7 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include "qtoolbar.h"
-#include "QtWidgets/qaction.h"
+#include "QtGui/qaction.h"
#include "private/qwidget_p.h"
#include <QtCore/qbasictimer.h>
@@ -74,7 +38,7 @@ public:
allowedAreas(Qt::AllToolBarAreas), orientation(Qt::Horizontal),
toolButtonStyle(Qt::ToolButtonIconOnly),
layout(nullptr), state(nullptr)
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
, macWindowDragging(false)
#endif
{ }
@@ -106,7 +70,7 @@ public:
};
DragState *state;
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
bool macWindowDragging;
QPoint macWindowDragPressPosition;
#endif
diff --git a/src/widgets/widgets/qtoolbararealayout.cpp b/src/widgets/widgets/qtoolbararealayout.cpp
index 493c094cc1..54c21b6038 100644
--- a/src/widgets/widgets/qtoolbararealayout.cpp
+++ b/src/widgets/widgets/qtoolbararealayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <QWidgetItem>
#include <QToolBar>
@@ -106,7 +70,7 @@ QToolBarAreaLayoutLine::QToolBarAreaLayoutLine(Qt::Orientation orientation)
QSize QToolBarAreaLayoutLine::sizeHint() const
{
int a = 0, b = 0;
- for (int i = 0; i < toolBarItems.count(); ++i) {
+ for (int i = 0; i < toolBarItems.size(); ++i) {
const QToolBarAreaLayoutItem &item = toolBarItems.at(i);
if (item.skip())
continue;
@@ -126,7 +90,7 @@ QSize QToolBarAreaLayoutLine::sizeHint() const
QSize QToolBarAreaLayoutLine::minimumSize() const
{
int a = 0, b = 0;
- for (int i = 0; i < toolBarItems.count(); ++i) {
+ for (int i = 0; i < toolBarItems.size(); ++i) {
const QToolBarAreaLayoutItem &item = toolBarItems[i];
if (item.skip())
continue;
@@ -150,7 +114,7 @@ void QToolBarAreaLayoutLine::fitLayout()
int space = pick(o, rect.size());
int extra = qMax(0, space - min);
- for (int i = 0; i < toolBarItems.count(); ++i) {
+ for (int i = 0; i < toolBarItems.size(); ++i) {
QToolBarAreaLayoutItem &item = toolBarItems[i];
if (item.skip())
continue;
@@ -173,7 +137,7 @@ void QToolBarAreaLayoutLine::fitLayout()
// calculate the positions from the sizes
int pos = 0;
- for (int i = 0; i < toolBarItems.count(); ++i) {
+ for (int i = 0; i < toolBarItems.size(); ++i) {
QToolBarAreaLayoutItem &item = toolBarItems[i];
if (item.skip())
continue;
@@ -187,7 +151,7 @@ void QToolBarAreaLayoutLine::fitLayout()
bool QToolBarAreaLayoutLine::skip() const
{
- for (int i = 0; i < toolBarItems.count(); ++i) {
+ for (int i = 0; i < toolBarItems.size(); ++i) {
if (!toolBarItems.at(i).skip())
return false;
}
@@ -219,7 +183,7 @@ QToolBarAreaLayoutInfo::QToolBarAreaLayoutInfo(QInternal::DockPosition pos)
QSize QToolBarAreaLayoutInfo::sizeHint() const
{
int a = 0, b = 0;
- for (int i = 0; i < lines.count(); ++i) {
+ for (int i = 0; i < lines.size(); ++i) {
const QToolBarAreaLayoutLine &l = lines.at(i);
if (l.skip())
continue;
@@ -239,7 +203,7 @@ QSize QToolBarAreaLayoutInfo::sizeHint() const
QSize QToolBarAreaLayoutInfo::minimumSize() const
{
int a = 0, b = 0;
- for (int i = 0; i < lines.count(); ++i) {
+ for (int i = 0; i < lines.size(); ++i) {
const QToolBarAreaLayoutLine &l = lines.at(i);
if (l.skip())
continue;
@@ -264,9 +228,9 @@ void QToolBarAreaLayoutInfo::fitLayout()
bool reverse = dockPos == QInternal::RightDock || dockPos == QInternal::BottomDock;
- int i = reverse ? lines.count() - 1 : 0;
+ int i = reverse ? lines.size() - 1 : 0;
for (;;) {
- if ((reverse && i < 0) || (!reverse && i == lines.count()))
+ if ((reverse && i < 0) || (!reverse && i == lines.size()))
break;
QToolBarAreaLayoutLine &l = lines[i];
@@ -309,10 +273,10 @@ void QToolBarAreaLayoutInfo::insertItem(QToolBar *before, QLayoutItem *item)
return;
}
- for (int j = 0; j < lines.count(); ++j) {
+ for (int j = 0; j < lines.size(); ++j) {
QToolBarAreaLayoutLine &line = lines[j];
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == before) {
line.toolBarItems.insert(k, item);
return;
@@ -323,17 +287,17 @@ void QToolBarAreaLayoutInfo::insertItem(QToolBar *before, QLayoutItem *item)
void QToolBarAreaLayoutInfo::removeToolBar(QToolBar *toolBar)
{
- for (int j = 0; j < lines.count(); ++j) {
+ for (int j = 0; j < lines.size(); ++j) {
QToolBarAreaLayoutLine &line = lines[j];
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
QToolBarAreaLayoutItem &item = line.toolBarItems[k];
if (item.widgetItem->widget() == toolBar) {
delete item.widgetItem;
item.widgetItem = nullptr;
line.toolBarItems.removeAt(k);
- if (line.toolBarItems.isEmpty() && j < lines.count() - 1)
+ if (line.toolBarItems.isEmpty() && j < lines.size() - 1)
lines.removeAt(j);
return;
@@ -351,10 +315,10 @@ void QToolBarAreaLayoutInfo::insertToolBarBreak(QToolBar *before)
return;
}
- for (int j = 0; j < lines.count(); ++j) {
+ for (int j = 0; j < lines.size(); ++j) {
QToolBarAreaLayoutLine &line = lines[j];
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == before) {
if (k == 0)
return;
@@ -372,10 +336,10 @@ void QToolBarAreaLayoutInfo::insertToolBarBreak(QToolBar *before)
void QToolBarAreaLayoutInfo::removeToolBarBreak(QToolBar *before)
{
- for (int j = 0; j < lines.count(); ++j) {
+ for (int j = 0; j < lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = lines.at(j);
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == before) {
if (k != 0)
return;
@@ -402,12 +366,12 @@ void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos)
pos -= rect.top();
//here we actually update the preferredSize for the line containing the toolbar so that we move it
- for (int j = 0; j < lines.count(); ++j) {
+ for (int j = 0; j < lines.size(); ++j) {
QToolBarAreaLayoutLine &line = lines[j];
int previousIndex = -1;
int minPos = 0;
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
QToolBarAreaLayoutItem &current = line.toolBarItems[k];
if (current.widgetItem->widget() == toolbar) {
int newPos = current.pos;
@@ -419,7 +383,7 @@ void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos)
} else {
//we check the max value for the position (until everything at the right is "compressed")
int maxPos = pick(o, rect.size());
- for(int l = k; l < line.toolBarItems.count(); ++l) {
+ for(int l = k; l < line.toolBarItems.size(); ++l) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(l);
if (!item.skip()) {
maxPos -= pick(o, item.minimumSize());
@@ -487,7 +451,7 @@ QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance)
// Since we're comparing p with item.pos, we put them in the same coordinate system.
const int p = pick(o, pos - rect.topLeft());
- for (int j = 0; j < lines.count(); ++j) {
+ for (int j = 0; j < lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = lines.at(j);
if (line.skip())
continue;
@@ -495,7 +459,7 @@ QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance)
continue;
int k = 0;
- for (; k < line.toolBarItems.count(); ++k) {
+ for (; k < line.toolBarItems.size(); ++k) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
if (item.skip())
continue;
@@ -521,7 +485,7 @@ QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance)
*minDistance = dist;
QList<int> result;
- result << lines.count() << 0;
+ result << lines.size() << 0;
return result;
}
}
@@ -531,9 +495,9 @@ QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance)
bool QToolBarAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *item)
{
- Q_ASSERT(path.count() == 2);
+ Q_ASSERT(path.size() == 2);
int j = path.first();
- if (j == lines.count())
+ if (j == lines.size())
lines.append(QToolBarAreaLayoutLine(o));
QToolBarAreaLayoutLine &line = lines[j];
@@ -576,7 +540,7 @@ void QToolBarAreaLayoutInfo::clear()
QRect QToolBarAreaLayoutInfo::itemRect(const QList<int> &path) const
{
- Q_ASSERT(path.count() == 2);
+ Q_ASSERT(path.size() == 2);
int j = path.at(0);
int k = path.at(1);
@@ -734,10 +698,10 @@ QLayoutItem *QToolBarAreaLayout::itemAt(int *x, int index) const
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
if ((*x)++ == index)
return line.toolBarItems.at(k).widgetItem;
}
@@ -754,10 +718,10 @@ QLayoutItem *QToolBarAreaLayout::takeAt(int *x, int index)
for (int i = 0; i < QInternal::DockCount; ++i) {
QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
QToolBarAreaLayoutLine &line = dock.lines[j];
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
if ((*x)++ == index) {
QLayoutItem *result = line.toolBarItems.takeAt(k).widgetItem;
if (line.toolBarItems.isEmpty())
@@ -776,10 +740,10 @@ void QToolBarAreaLayout::deleteAllLayoutItems()
for (int i = 0; i < QInternal::DockCount; ++i) {
QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
QToolBarAreaLayoutLine &line = dock.lines[j];
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
QToolBarAreaLayoutItem &item = line.toolBarItems[k];
if (!item.gap)
delete item.widgetItem;
@@ -794,10 +758,10 @@ QInternal::DockPosition QToolBarAreaLayout::findToolBar(const QToolBar *toolBar)
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == toolBar)
return static_cast<QInternal::DockPosition>(i);
}
@@ -885,12 +849,12 @@ void QToolBarAreaLayout::apply(bool animate)
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
if (line.skip())
continue;
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
if (item.skip() || item.gap)
continue;
@@ -943,10 +907,10 @@ bool QToolBarAreaLayout::toolBarBreak(QToolBar *toolBar) const
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == toolBar)
return j > 0 && k == 0;
}
@@ -961,25 +925,25 @@ void QToolBarAreaLayout::getStyleOptionInfo(QStyleOptionToolBar *option, QToolBa
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
if (line.toolBarItems.at(k).widgetItem->widget() == toolBar) {
- if (line.toolBarItems.count() == 1)
+ if (line.toolBarItems.size() == 1)
option->positionWithinLine = QStyleOptionToolBar::OnlyOne;
else if (k == 0)
option->positionWithinLine = QStyleOptionToolBar::Beginning;
- else if (k == line.toolBarItems.count() - 1)
+ else if (k == line.toolBarItems.size() - 1)
option->positionWithinLine = QStyleOptionToolBar::End;
else
option->positionWithinLine = QStyleOptionToolBar::Middle;
- if (dock.lines.count() == 1)
+ if (dock.lines.size() == 1)
option->positionOfLine = QStyleOptionToolBar::OnlyOne;
else if (j == 0)
option->positionOfLine = QStyleOptionToolBar::Beginning;
- else if (j == dock.lines.count() - 1)
+ else if (j == dock.lines.size() - 1)
option->positionOfLine = QStyleOptionToolBar::End;
else
option->positionOfLine = QStyleOptionToolBar::Middle;
@@ -1000,10 +964,10 @@ QList<int> QToolBarAreaLayout::indexOf(QWidget *toolBar) const
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
if (!item.gap && item.widgetItem->widget() == toolBar) {
found = true;
@@ -1052,10 +1016,10 @@ QList<int> QToolBarAreaLayout::currentGapIndex() const
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines[j];
- for (int k = 0; k < line.toolBarItems.count(); k++) {
+ for (int k = 0; k < line.toolBarItems.size(); k++) {
if (line.toolBarItems[k].gap) {
QList<int> result;
result << i << j << k;
@@ -1069,7 +1033,7 @@ QList<int> QToolBarAreaLayout::currentGapIndex() const
bool QToolBarAreaLayout::insertGap(const QList<int> &path, QLayoutItem *item)
{
- Q_ASSERT(path.count() == 3);
+ Q_ASSERT(path.size() == 3);
const int i = path.first();
Q_ASSERT(i >= 0 && i < QInternal::DockCount);
return docks[i].insertGap(path.mid(1), item);
@@ -1077,7 +1041,7 @@ bool QToolBarAreaLayout::insertGap(const QList<int> &path, QLayoutItem *item)
void QToolBarAreaLayout::remove(const QList<int> &path)
{
- Q_ASSERT(path.count() == 3);
+ Q_ASSERT(path.size() == 3);
QToolBarAreaLayoutInfo &dock = docks[path.at(0)];
QToolBarAreaLayoutLine &line = dock.lines[path.at(1)];
line.toolBarItems.removeAt(path.at(2));
@@ -1090,10 +1054,10 @@ void QToolBarAreaLayout::remove(QLayoutItem *item)
for (int i = 0; i < QInternal::DockCount; ++i) {
QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
QToolBarAreaLayoutLine &line = dock.lines[j];
- for (int k = 0; k < line.toolBarItems.count(); k++) {
+ for (int k = 0; k < line.toolBarItems.size(); k++) {
if (line.toolBarItems[k].widgetItem == item) {
line.toolBarItems.removeAt(k);
if (line.toolBarItems.isEmpty())
@@ -1114,15 +1078,15 @@ void QToolBarAreaLayout::clear()
QToolBarAreaLayoutItem *QToolBarAreaLayout::item(const QList<int> &path)
{
- Q_ASSERT(path.count() == 3);
+ Q_ASSERT(path.size() == 3);
if (path.at(0) < 0 || path.at(0) >= QInternal::DockCount)
return nullptr;
QToolBarAreaLayoutInfo &info = docks[path.at(0)];
- if (path.at(1) < 0 || path.at(1) >= info.lines.count())
+ if (path.at(1) < 0 || path.at(1) >= info.lines.size())
return nullptr;
QToolBarAreaLayoutLine &line = info.lines[path.at(1)];
- if (path.at(2) < 0 || path.at(2) >= line.toolBarItems.count())
+ if (path.at(2) < 0 || path.at(2) >= line.toolBarItems.size())
return nullptr;
return &(line.toolBarItems[path.at(2)]);
}
@@ -1154,7 +1118,7 @@ QLayoutItem *QToolBarAreaLayout::plug(const QList<int> &path)
QLayoutItem *QToolBarAreaLayout::unplug(const QList<int> &path, QToolBarAreaLayout *other)
{
//other needs to be update as well
- Q_ASSERT(path.count() == 3);
+ Q_ASSERT(path.size() == 3);
QToolBarAreaLayoutItem *item = this->item(path);
Q_ASSERT(item);
@@ -1172,7 +1136,7 @@ QLayoutItem *QToolBarAreaLayout::unplug(const QList<int> &path, QToolBarAreaLayo
if (!previous.skip()) {
//we need to check if it has a previous element and a next one
//the previous will get its size changed
- for (int j = path.at(2) + 1; j < line.toolBarItems.count(); ++j) {
+ for (int j = path.at(2) + 1; j < line.toolBarItems.size(); ++j) {
const QToolBarAreaLayoutItem &next = line.toolBarItems.at(j);
if (!next.skip()) {
newExtraSpace = next.pos - previous.pos - pick(line.o, previous.sizeHint());
@@ -1257,19 +1221,19 @@ void QToolBarAreaLayout::saveState(QDataStream &stream) const
int lineCount = 0;
for (int i = 0; i < QInternal::DockCount; ++i)
- lineCount += docks[i].lines.count();
+ lineCount += docks[i].lines.size();
stream << lineCount;
for (int i = 0; i < QInternal::DockCount; ++i) {
const QToolBarAreaLayoutInfo &dock = docks[i];
- for (int j = 0; j < dock.lines.count(); ++j) {
+ for (int j = 0; j < dock.lines.size(); ++j) {
const QToolBarAreaLayoutLine &line = dock.lines.at(j);
- stream << i << line.toolBarItems.count();
+ stream << i << int(line.toolBarItems.size());
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
+ for (int k = 0; k < line.toolBarItems.size(); ++k) {
const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
QWidget *widget = const_cast<QLayoutItem*>(item.widgetItem)->widget();
QString objectName = widget->objectName();
@@ -1353,7 +1317,7 @@ bool QToolBarAreaLayout::restoreState(QDataStream &stream, const QList<QToolBar*
}
QToolBar *toolBar = nullptr;
- for (int x = 0; x < toolBars.count(); ++x) {
+ for (int x = 0; x < toolBars.size(); ++x) {
if (toolBars.at(x)->objectName() == objectName) {
toolBar = toolBars.takeAt(x);
break;
@@ -1364,10 +1328,14 @@ bool QToolBarAreaLayout::restoreState(QDataStream &stream, const QList<QToolBar*
}
if (applyingLayout) {
+ // Clear the previous widgetItem for the toolBar, so that it's
+ // assigned correctly in QWidgetItemV2 constructor.
+ auto *toolBarPrivate = QWidgetPrivate::get(toolBar);
+ toolBarPrivate->widgetItem = nullptr;
item.widgetItem = new QWidgetItemV2(toolBar);
toolBar->setOrientation(floating ? ((shown & 2) ? Qt::Vertical : Qt::Horizontal) : dock.o);
toolBar->setVisible(shown & 1);
- toolBar->d_func()->setWindowState(floating, true, rect);
+ toolBar->d_func()->setWindowState(floating, false, rect);
item.preferredSize = item.size;
line.toolBarItems.append(item);
diff --git a/src/widgets/widgets/qtoolbararealayout_p.h b/src/widgets/widgets/qtoolbararealayout_p.h
index 5df95a3038..4318f206f3 100644
--- a/src/widgets/widgets/qtoolbararealayout_p.h
+++ b/src/widgets/widgets/qtoolbararealayout_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTOOLBARAREALAYOUT_P_H
#define QTOOLBARAREALAYOUT_P_H
@@ -112,7 +76,7 @@ Q_DECLARE_TYPEINFO(QToolBarAreaLayoutItem, Q_PRIMITIVE_TYPE);
class QToolBarAreaLayoutLine
{
public:
- QToolBarAreaLayoutLine() {} // for QVector, don't use
+ QToolBarAreaLayoutLine() { } // for QList, don't use
QToolBarAreaLayoutLine(Qt::Orientation orientation);
QSize sizeHint() const;
@@ -124,9 +88,9 @@ public:
QRect rect;
Qt::Orientation o;
- QVector<QToolBarAreaLayoutItem> toolBarItems;
+ QList<QToolBarAreaLayoutItem> toolBarItems;
};
-Q_DECLARE_TYPEINFO(QToolBarAreaLayoutLine, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QToolBarAreaLayoutLine, Q_RELOCATABLE_TYPE);
class QToolBarAreaLayoutInfo
{
@@ -151,13 +115,13 @@ public:
QRect itemRect(const QList<int> &path) const;
int distance(const QPoint &pos) const;
- QVector<QToolBarAreaLayoutLine> lines;
+ QList<QToolBarAreaLayoutLine> lines;
QRect rect;
Qt::Orientation o;
QInternal::DockPosition dockPos;
bool dirty;
};
-Q_DECLARE_TYPEINFO(QToolBarAreaLayoutInfo, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(QToolBarAreaLayoutInfo, Q_RELOCATABLE_TYPE);
class QToolBarAreaLayout
{
diff --git a/src/widgets/widgets/qtoolbarextension.cpp b/src/widgets/widgets/qtoolbarextension.cpp
index bbe7eddaa4..350a900457 100644
--- a/src/widgets/widgets/qtoolbarextension.cpp
+++ b/src/widgets/widgets/qtoolbarextension.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtoolbarextension_p.h"
#include <qevent.h>
@@ -45,11 +9,13 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
QToolBarExtension::QToolBarExtension(QWidget *parent)
: QToolButton(parent)
, m_orientation(Qt::Horizontal)
{
- setObjectName(QLatin1String("qt_toolbar_ext_button"));
+ setObjectName("qt_toolbar_ext_button"_L1);
setAutoRaise(true);
setOrientation(m_orientation);
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
@@ -59,11 +25,11 @@ QToolBarExtension::QToolBarExtension(QWidget *parent)
void QToolBarExtension::setOrientation(Qt::Orientation o)
{
QStyleOption opt;
- opt.init(this);
+ 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;
}
@@ -81,7 +47,9 @@ void QToolBarExtension::paintEvent(QPaintEvent *)
QSize QToolBarExtension::sizeHint() const
{
- int ext = style()->pixelMetric(QStyle::PM_ToolBarExtensionExtent);
+ QStyleOption opt;
+ opt.initFrom(this);
+ const int ext = style()->pixelMetric(QStyle::PM_ToolBarExtensionExtent, &opt, this);
return QSize(ext, ext);
}
diff --git a/src/widgets/widgets/qtoolbarextension_p.h b/src/widgets/widgets/qtoolbarextension_p.h
index 146e0e58c1..c2afd3fc62 100644
--- a/src/widgets/widgets/qtoolbarextension_p.h
+++ b/src/widgets/widgets/qtoolbarextension_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDYNAMICTOOLBAREXTENSION_P_H
#define QDYNAMICTOOLBAREXTENSION_P_H
diff --git a/src/widgets/widgets/qtoolbarlayout.cpp b/src/widgets/widgets/qtoolbarlayout.cpp
index 93aded6876..cc842e2657 100644
--- a/src/widgets/widgets/qtoolbarlayout.cpp
+++ b/src/widgets/widgets/qtoolbarlayout.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 <qapplication.h>
#include <qaction.h>
@@ -48,7 +12,7 @@
#include <qmenu.h>
#include <qdebug.h>
#include <qmath.h>
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
#include <qpa/qplatformnativeinterface.h>
#endif
@@ -168,14 +132,14 @@ void QToolBarLayout::addItem(QLayoutItem*)
QLayoutItem *QToolBarLayout::itemAt(int index) const
{
- if (index < 0 || index >= items.count())
+ if (index < 0 || index >= items.size())
return nullptr;
return items.at(index);
}
QLayoutItem *QToolBarLayout::takeAt(int index)
{
- if (index < 0 || index >= items.count())
+ if (index < 0 || index >= items.size())
return nullptr;
QToolBarItem *item = items.takeAt(index);
@@ -198,7 +162,7 @@ QLayoutItem *QToolBarLayout::takeAt(int index)
void QToolBarLayout::insertAction(int index, QAction *action)
{
index = qMax(0, index);
- index = qMin(items.count(), index);
+ index = qMin(items.size(), index);
QToolBarItem *item = createItem(action);
if (item) {
@@ -207,9 +171,9 @@ void QToolBarLayout::insertAction(int index, QAction *action)
}
}
-int QToolBarLayout::indexOf(const QGuiAction *action) const
+int QToolBarLayout::indexOf(const QAction *action) const
{
- for (int i = 0; i < items.count(); ++i) {
+ for (int i = 0; i < items.size(); ++i) {
if (items.at(i)->action == action)
return i;
}
@@ -218,7 +182,7 @@ int QToolBarLayout::indexOf(const QGuiAction *action) const
int QToolBarLayout::count() const
{
- return items.count();
+ return items.size();
}
bool QToolBarLayout::isEmpty() const
@@ -282,10 +246,10 @@ void QToolBarLayout::updateGeomArray() const
that->expanding = false;
that->empty = false;
- QVector<QLayoutStruct> a(items.count() + 1); // + 1 for the stretch
+ QList<QLayoutStruct> a(items.size() + 1); // + 1 for the stretch
int count = 0;
- for (int i = 0; i < items.count(); ++i) {
+ for (int i = 0; i < items.size(); ++i) {
QToolBarItem *item = items.at(i);
QSize max = item->maximumSize();
@@ -332,7 +296,7 @@ void QToolBarLayout::updateGeomArray() const
rpick(o, that->minSize) += handleExtent;
that->minSize += QSize(pick(Qt::Horizontal, margins), pick(Qt::Vertical, margins));
- if (items.count() > 1)
+ if (items.size() > 1)
rpick(o, that->minSize) += spacing + extensionExtent;
rpick(o, that->hint) += handleExtent;
@@ -348,7 +312,7 @@ static bool defaultWidgetAction(QToolBarItem *item)
void QToolBarLayout::updateMacBorderMetrics()
{
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
if (!tb)
return;
@@ -460,15 +424,15 @@ bool QToolBarLayout::layoutActions(const QSize &size)
if (space <= 0)
return false; // nothing to do.
- if(popupMenu)
+ if (popupMenu)
popupMenu->clear();
bool ranOutOfSpace = false;
int rows = 0;
int rowPos = perp(o, rect.topLeft()) + perp(o, QSize(margins.top(), margins.left()));
int i = 0;
- while (i < items.count()) {
- QVector<QLayoutStruct> a = geomArray;
+ while (i < items.size()) {
+ QList<QLayoutStruct> a = geomArray;
int start = i;
int size = 0;
@@ -477,7 +441,7 @@ bool QToolBarLayout::layoutActions(const QSize &size)
int count = 0;
int maximumSize = 0;
bool expansiveRow = false;
- for (; i < items.count(); ++i) {
+ for (; i < items.size(); ++i) {
if (a[i].empty)
continue;
@@ -548,7 +512,7 @@ bool QToolBarLayout::layoutActions(const QSize &size)
}
if (!expanded) {
- for (int j = i; j < items.count(); ++j) {
+ for (int j = i; j < items.size(); ++j) {
QToolBarItem *item = items.at(j);
if (!item->widget()->isHidden())
hideWidgets << item->widget();
@@ -573,9 +537,9 @@ bool QToolBarLayout::layoutActions(const QSize &size)
extension->setEnabled(popupMenu == nullptr || !extensionMenuContainsOnlyWidgetActions);
// we have to do the show/hide here, because it triggers more calls to setGeometry :(
- for (int i = 0; i < showWidgets.count(); ++i)
+ for (int i = 0; i < showWidgets.size(); ++i)
showWidgets.at(i)->show();
- for (int i = 0; i < hideWidgets.count(); ++i)
+ for (int i = 0; i < hideWidgets.size(); ++i)
hideWidgets.at(i)->hide();
return ranOutOfSpace;
@@ -602,7 +566,7 @@ QSize QToolBarLayout::expandedSize(const QSize &size) const
int total_w = 0;
int count = 0;
- for (int x = 0; x < items.count(); ++x) {
+ for (int x = 0; x < items.size(); ++x) {
if (!geomArray[x].empty) {
total_w += (count == 0 ? 0 : spacing) + geomArray[x].minimumSize;
++count;
@@ -623,12 +587,12 @@ QSize QToolBarLayout::expandedSize(const QSize &size) const
int w = 0;
int h = 0;
int i = 0;
- while (i < items.count()) {
+ while (i < items.size()) {
int count = 0;
int size = 0;
int prev = -1;
int rowHeight = 0;
- for (; i < items.count(); ++i) {
+ for (; i < items.size(); ++i) {
if (geomArray[i].empty)
continue;
diff --git a/src/widgets/widgets/qtoolbarlayout_p.h b/src/widgets/widgets/qtoolbarlayout_p.h
index 1a406a3d29..a7d3810d61 100644
--- a/src/widgets/widgets/qtoolbarlayout_p.h
+++ b/src/widgets/widgets/qtoolbarlayout_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTOOLBARLAYOUT_P_H
#define QTOOLBARLAYOUT_P_H
@@ -54,7 +18,7 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtWidgets/qlayout.h>
#include <private/qlayoutengine_p.h>
-#include <QVector>
+#include <QList>
QT_REQUIRE_CONFIG(toolbar);
@@ -96,7 +60,7 @@ public:
QSize sizeHint() const override;
void insertAction(int index, QAction *action);
- int indexOf(const QGuiAction *action) const;
+ int indexOf(const QAction *action) const;
using QLayout::indexOf; // bring back the hidden members
bool layoutActions(const QSize &size);
@@ -118,7 +82,7 @@ private:
QList<QToolBarItem*> items;
QSize hint, minSize;
bool dirty, expanding, empty, expandFlag;
- QVector<QLayoutStruct> geomArray;
+ QList<QLayoutStruct> geomArray;
QRect handRect;
QToolBarExtension *extension;
diff --git a/src/widgets/widgets/qtoolbarseparator.cpp b/src/widgets/widgets/qtoolbarseparator.cpp
index 92cd08317a..0e70c21361 100644
--- a/src/widgets/widgets/qtoolbarseparator.cpp
+++ b/src/widgets/widgets/qtoolbarseparator.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtoolbarseparator_p.h"
diff --git a/src/widgets/widgets/qtoolbarseparator_p.h b/src/widgets/widgets/qtoolbarseparator_p.h
index 60b51a28cb..d43c241015 100644
--- a/src/widgets/widgets/qtoolbarseparator_p.h
+++ b/src/widgets/widgets/qtoolbarseparator_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QDYNAMICTOOLBARSEPARATOR_P_H
#define QDYNAMICTOOLBARSEPARATOR_P_H
diff --git a/src/widgets/widgets/qtoolbox.cpp b/src/widgets/widgets/qtoolbox.cpp
index 4767394842..e0fac9be0f 100644
--- a/src/widgets/widgets/qtoolbox.cpp
+++ b/src/widgets/widgets/qtoolbox.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtoolbox.h"
@@ -47,15 +11,17 @@
#include <qscrollarea.h>
#include <qstyle.h>
#include <qstyleoption.h>
+#if QT_CONFIG(tooltip)
#include <qtooltip.h>
+#endif
#include <qabstractbutton.h>
-#include <private/qmemory_p.h>
-
#include "qframe_p.h"
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
class QToolBoxButton : public QAbstractButton
{
Q_OBJECT
@@ -96,7 +62,7 @@ public:
inline void setText(const QString &text) { button->setText(text); }
inline void setIcon(const QIcon &is) { button->setIcon(is); }
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
inline void setToolTip(const QString &tip) { button->setToolTip(tip); }
inline QString toolTip() const { return button->toolTip(); }
#endif
@@ -189,8 +155,7 @@ QSize QToolBoxButton::sizeHint() const
}
QSize textSize = fontMetrics().size(Qt::TextShowMnemonic, text()) + QSize(0, 8);
- QSize total(iconSize.width() + textSize.width(), qMax(iconSize.height(), textSize.height()));
- return total.expandedTo(QApplication::globalStrut());
+ return QSize(iconSize.width() + textSize.width(), qMax(iconSize.height(), textSize.height()));
}
QSize QToolBoxButton::minimumSizeHint() const
@@ -348,11 +313,11 @@ int QToolBox::insertItem(int index, QWidget *widget, const QIcon &icon, const QS
Q_D(QToolBox);
connect(widget, SIGNAL(destroyed(QObject*)), this, SLOT(_q_widgetDestroyed(QObject*)));
- auto newPage = qt_make_unique<QToolBoxPrivate::Page>();
+ auto newPage = std::make_unique<QToolBoxPrivate::Page>();
auto &c = *newPage;
c.widget = widget;
c.button = new QToolBoxButton(this);
- c.button->setObjectName(QLatin1String("qt_toolbox_toolboxbutton"));
+ c.button->setObjectName("qt_toolbox_toolboxbutton"_L1);
connect(c.button, SIGNAL(clicked()), this, SLOT(_q_buttonClicked()));
c.sv = new QScrollArea(this);
@@ -559,7 +524,7 @@ QWidget *QToolBox::widget(int index) const
exist.
*/
-int QToolBox::indexOf(QWidget *widget) const
+int QToolBox::indexOf(const QWidget *widget) const
{
Q_D(const QToolBox);
const QToolBoxPrivate::Page *c = (widget ? d->page(widget) : nullptr);
@@ -639,7 +604,7 @@ void QToolBox::setItemIcon(int index, const QIcon &icon)
c->setIcon(icon);
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
/*!
Sets the tooltip of the item at position \a index to \a toolTip.
*/
@@ -651,7 +616,7 @@ void QToolBox::setItemToolTip(int index, const QString &toolTip)
if (c)
c->setToolTip(toolTip);
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
/*!
Returns \c true if the item at position \a index is enabled; otherwise returns \c false.
@@ -688,7 +653,7 @@ QIcon QToolBox::itemIcon(int index) const
return (c ? c->icon() : QIcon());
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
/*!
Returns the tooltip of the item at position \a index, or an
empty string if \a index is out of range.
@@ -700,7 +665,7 @@ QString QToolBox::itemToolTip(int index) const
const QToolBoxPrivate::Page *c = d->page(index);
return (c ? c->toolTip() : QString());
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
/*! \reimp */
void QToolBox::showEvent(QShowEvent *e)
@@ -712,7 +677,7 @@ void QToolBox::showEvent(QShowEvent *e)
void QToolBox::changeEvent(QEvent *ev)
{
Q_D(QToolBox);
- if(ev->type() == QEvent::StyleChange)
+ if (ev->type() == QEvent::StyleChange)
d->updateTabs();
QFrame::changeEvent(ev);
}
@@ -725,7 +690,7 @@ void QToolBox::changeEvent(QEvent *ev)
*/
void QToolBox::itemInserted(int index)
{
- Q_UNUSED(index)
+ Q_UNUSED(index);
}
/*!
@@ -736,7 +701,7 @@ void QToolBox::itemInserted(int index)
*/
void QToolBox::itemRemoved(int index)
{
- Q_UNUSED(index)
+ Q_UNUSED(index);
}
/*! \reimp */
diff --git a/src/widgets/widgets/qtoolbox.h b/src/widgets/widgets/qtoolbox.h
index 2796631b94..a295dad2fd 100644
--- a/src/widgets/widgets/qtoolbox.h
+++ b/src/widgets/widgets/qtoolbox.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTOOLBOX_H
#define QTOOLBOX_H
@@ -76,7 +40,7 @@ public:
void setItemIcon(int index, const QIcon &icon);
QIcon itemIcon(int index) const;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
void setItemToolTip(int index, const QString &toolTip);
QString itemToolTip(int index) const;
#endif
@@ -84,7 +48,7 @@ public:
int currentIndex() const;
QWidget *currentWidget() const;
QWidget *widget(int index) const;
- int indexOf(QWidget *widget) const;
+ int indexOf(const QWidget *widget) const;
int count() const;
public Q_SLOTS:
diff --git a/src/widgets/widgets/qtoolbutton.cpp b/src/widgets/widgets/qtoolbutton.cpp
index 127960b23c..e0775afd26 100644
--- a/src/widgets/widgets/qtoolbutton.cpp
+++ b/src/widgets/widgets/qtoolbutton.cpp
@@ -1,47 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qtoolbutton.h"
#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <private/qdesktopwidget_p.h>
#include <qdrawutil.h>
#include <qevent.h>
#include <qicon.h>
@@ -49,7 +11,9 @@
#include <qpointer.h>
#include <qstyle.h>
#include <qstyleoption.h>
+#if QT_CONFIG(tooltip)
#include <qtooltip.h>
+#endif
#if QT_CONFIG(mainwindow)
#include <qmainwindow.h>
#endif
@@ -67,20 +31,22 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
class QToolButtonPrivate : public QAbstractButtonPrivate
{
Q_DECLARE_PUBLIC(QToolButton)
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;
@@ -169,8 +135,7 @@ bool QToolButtonPrivate::hasMenu() const
with actions used in other parts of the main window.
\endtable
- \sa QPushButton, QToolBar, QMainWindow, QAction,
- {fowler}{GUI Design Handbook: Push Button}
+ \sa QPushButton, QToolBar, QMainWindow, QAction
*/
/*!
@@ -222,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);
@@ -244,7 +211,6 @@ void QToolButton::initStyleOption(QStyleOptionToolButton *option) const
Q_D(const QToolButton);
option->initFrom(this);
- bool forceNoText = false;
option->iconSize = iconSize(); //default value
#if QT_CONFIG(toolbar)
@@ -255,8 +221,7 @@ void QToolButton::initStyleOption(QStyleOptionToolButton *option) const
}
#endif // QT_CONFIG(toolbar)
- if (!forceNoText)
- option->text = d->text;
+ option->text = d->text;
option->icon = d->icon;
option->arrowType = d->arrowType;
if (d->down)
@@ -308,7 +273,7 @@ void QToolButton::initStyleOption(QStyleOptionToolButton *option) const
option->toolButtonStyle = Qt::ToolButtonIconOnly;
}
- if (d->icon.isNull() && d->arrowType == Qt::NoArrow && !forceNoText) {
+ if (d->icon.isNull() && d->arrowType == Qt::NoArrow) {
if (!d->text.isEmpty())
option->toolButtonStyle = Qt::ToolButtonTextOnly;
else if (option->toolButtonStyle != Qt::ToolButtonTextOnly)
@@ -350,7 +315,7 @@ QSize QToolButton::sizeHint() const
if (opt.toolButtonStyle != Qt::ToolButtonIconOnly) {
QSize textSize = fm.size(Qt::TextShowMnemonic, text());
- textSize.setWidth(textSize.width() + fm.horizontalAdvance(QLatin1Char(' '))*2);
+ textSize.setWidth(textSize.width() + fm.horizontalAdvance(u' ') * 2);
if (opt.toolButtonStyle == Qt::ToolButtonTextUnderIcon) {
h += 4 + textSize.height();
if (textSize.width() > w)
@@ -369,8 +334,7 @@ QSize QToolButton::sizeHint() const
if (d->popupMode == MenuButtonPopup)
w += style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &opt, this);
- d->sizeHint = style()->sizeFromContents(QStyle::CT_ToolButton, &opt, QSize(w, h), this).
- expandedTo(QApplication::globalStrut());
+ d->sizeHint = style()->sizeFromContents(QStyle::CT_ToolButton, &opt, QSize(w, h), this);
return d->sizeHint;
}
@@ -473,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)
@@ -518,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()))
@@ -528,7 +493,7 @@ void QToolButtonPrivate::_q_actionTriggered()
/*!
\reimp
*/
-void QToolButton::enterEvent(QEvent * e)
+void QToolButton::enterEvent(QEnterEvent * e)
{
Q_D(QToolButton);
if (d->autoRaise)
@@ -602,7 +567,7 @@ void QToolButton::mousePressEvent(QMouseEvent *e)
if (e->button() == Qt::LeftButton && (d->popupMode == MenuButtonPopup)) {
QRect popupr = style()->subControlRect(QStyle::CC_ToolButton, &opt,
QStyle::SC_ToolButtonMenu, this);
- if (popupr.isValid() && popupr.contains(e->pos())) {
+ if (popupr.isValid() && popupr.contains(e->position().toPoint())) {
d->buttonPressed = QToolButtonPrivate::MenuButtonPressed;
showMenu();
return;
@@ -619,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;
}
/*!
@@ -629,7 +596,7 @@ void QToolButton::mouseReleaseEvent(QMouseEvent *e)
bool QToolButton::hitButton(const QPoint &pos) const
{
Q_D(const QToolButton);
- if(QAbstractButton::hitButton(pos))
+ if (QAbstractButton::hitButton(pos))
return (d->buttonPressed != QToolButtonPrivate::MenuButtonPressed);
return false;
}
@@ -705,7 +672,7 @@ void QToolButton::showMenu()
d->popupTimerDone();
}
-void QToolButtonPrivate::_q_buttonPressed()
+void QToolButtonPrivate::onButtonPressed()
{
Q_Q(QToolButton);
if (!hasMenu())
@@ -718,43 +685,17 @@ void QToolButtonPrivate::_q_buttonPressed()
q->showMenu();
}
-void QToolButtonPrivate::_q_buttonReleased()
+void QToolButtonPrivate::onButtonReleased()
{
popupTimer.stop();
}
-void QToolButtonPrivate::popupTimerDone()
+static QPoint positionMenu(const QToolButton *q, bool horizontal,
+ const QSize &sh)
{
- Q_Q(QToolButton);
- popupTimer.stop();
- if (!menuButtonDown && !down)
- return;
-
- menuButtonDown = true;
- QPointer<QMenu> actualMenu;
- bool mustDeleteActualMenu = false;
- if(menuAction) {
- actualMenu = menuAction->menu();
- } else if (defaultAction && defaultAction->menu()) {
- actualMenu = defaultAction->menu();
- } else {
- actualMenu = new QMenu(q);
- mustDeleteActualMenu = true;
- for(int i = 0; i < actions.size(); i++)
- actualMenu->addAction(actions.at(i));
- }
- repeat = q->autoRepeat();
- q->setAutoRepeat(false);
- bool horizontal = true;
-#if QT_CONFIG(toolbar)
- QToolBar *tb = qobject_cast<QToolBar*>(parent);
- if (tb && tb->orientation() == Qt::Vertical)
- horizontal = false;
-#endif
QPoint p;
const QRect rect = q->rect(); // Find screen via point in case of QGraphicsProxyWidget.
- QRect screen = QDesktopWidgetPrivate::availableGeometry(q->mapToGlobal(rect.center()));
- QSize sh = ((QToolButton*)(QMenu*)actualMenu)->receivers(SIGNAL(aboutToShow()))? QSize() : actualMenu->sizeHint();
+ const QRect screen = QWidgetPrivate::availableScreenGeometry(q, q->mapToGlobal(rect.center()));
if (horizontal) {
if (q->isRightToLeft()) {
if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.bottom()) {
@@ -786,26 +727,73 @@ void QToolButtonPrivate::popupTimerDone()
}
}
}
+
+ // 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;
+}
+
+void QToolButtonPrivate::popupTimerDone()
+{
+ Q_Q(QToolButton);
+ popupTimer.stop();
+ if (!menuButtonDown && !down)
+ return;
+
+ menuButtonDown = true;
+ QPointer<QMenu> actualMenu;
+ bool mustDeleteActualMenu = false;
+ if (menuAction) {
+ actualMenu = menuAction->menu();
+ } else if (defaultAction && defaultAction->menu()) {
+ actualMenu = defaultAction->menu();
+ } else {
+ actualMenu = new QMenu(q);
+ mustDeleteActualMenu = true;
+ for (int i = 0; i < actions.size(); i++)
+ actualMenu->addAction(actions.at(i));
+ }
+ repeat = q->autoRepeat();
+ q->setAutoRepeat(false);
+ bool horizontal = true;
+#if QT_CONFIG(toolbar)
+ QToolBar *tb = qobject_cast<QToolBar*>(parent);
+ if (tb && tb->orientation() == Qt::Vertical)
+ horizontal = false;
+#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)
- actualMenu->exec(p);
+
+ // QTBUG-78966, Delay positioning until after aboutToShow().
+ auto positionFunction = [q, horizontal](const QSize &sizeHint) {
+ return positionMenu(q, horizontal, sizeHint); };
+ const auto initialPos = positionFunction(actualMenu->sizeHint());
+ actualMenu->d_func()->exec(initialPos, nullptr, positionFunction);
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();
@@ -813,7 +801,7 @@ void QToolButtonPrivate::popupTimerDone()
q->setAutoRepeat(true);
}
-void QToolButtonPrivate::_q_updateButtonDown()
+void QToolButtonPrivate::updateButtonDown()
{
Q_Q(QToolButton);
menuButtonDown = false;
@@ -823,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))
@@ -933,10 +921,10 @@ void QToolButton::setDefaultAction(QAction *action)
// If iconText() is generated from text(), we need to escape any '&'s so they
// don't turn into shortcuts
if (QActionPrivate::get(action)->iconText.isEmpty())
- buttonText.replace(QLatin1String("&"), QLatin1String("&&"));
+ buttonText.replace("&"_L1, "&&"_L1);
setText(buttonText);
setIcon(action->icon());
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
setToolTip(action->toolTip());
#endif
#if QT_CONFIG(statustip)
@@ -972,7 +960,15 @@ QAction *QToolButton::defaultAction() const
return d->defaultAction;
}
-
+/*!
+ \reimp
+ */
+void QToolButton::checkStateSet()
+{
+ Q_D(QToolButton);
+ if (d->defaultAction && d->defaultAction->isCheckable())
+ d->defaultAction->setChecked(isChecked());
+}
/*!
\reimp
@@ -994,7 +990,7 @@ bool QToolButton::event(QEvent *event)
case QEvent::HoverLeave:
case QEvent::HoverMove:
if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d_func()->updateHoverControl(he->pos());
+ d_func()->updateHoverControl(he->position().toPoint());
break;
default:
break;
diff --git a/src/widgets/widgets/qtoolbutton.h b/src/widgets/widgets/qtoolbutton.h
index 52bd2d5f7a..72429620ad 100644
--- a/src/widgets/widgets/qtoolbutton.h
+++ b/src/widgets/widgets/qtoolbutton.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QTOOLBUTTON_H
#define QTOOLBUTTON_H
@@ -112,26 +76,19 @@ protected:
void paintEvent(QPaintEvent *) override;
void actionEvent(QActionEvent *) override;
- void enterEvent(QEvent *) override;
+ void enterEvent(QEnterEvent *) override;
void leaveEvent(QEvent *) override;
void timerEvent(QTimerEvent *) override;
void changeEvent(QEvent *) override;
bool hitButton(const QPoint &pos) const override;
+ void checkStateSet() override;
void nextCheckState() override;
- void initStyleOption(QStyleOptionToolButton *option) const;
+ virtual void initStyleOption(QStyleOptionToolButton *option) const;
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 cec6ba1dea..d45215dee3 100644
--- a/src/widgets/widgets/qwidgetanimator.cpp
+++ b/src/widgets/widgets/qwidgetanimator.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qwidgetanimator_p.h"
@@ -55,7 +19,7 @@ QWidgetAnimator::QWidgetAnimator(QMainWindowLayout *layout)
: m_mainWindowLayout(layout)
#endif
{
- Q_UNUSED(layout)
+ Q_UNUSED(layout);
}
void QWidgetAnimator::abort(QWidget *w)
@@ -93,7 +57,7 @@ void QWidgetAnimator::animate(QWidget *widget, const QRect &_final_geometry, boo
animate = animate && !r.isNull() && !_final_geometry.isNull();
- // might make the wigdet go away by sending it to negative space
+ // might make the widget go away by sending it to negative space
const QRect final_geometry = _final_geometry.isValid() || widget->isWindow() ? _final_geometry :
QRect(QPoint(-500 - widget->width(), -500 - widget->height()), widget->size());
@@ -109,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/qwidgetanimator_p.h b/src/widgets/widgets/qwidgetanimator_p.h
index 9d08d03593..c7af3855b0 100644
--- a/src/widgets/widgets/qwidgetanimator_p.h
+++ b/src/widgets/widgets/qwidgetanimator_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIDGET_ANIMATOR_P_H
#define QWIDGET_ANIMATOR_P_H
diff --git a/src/widgets/widgets/qwidgetlinecontrol.cpp b/src/widgets/widgets/qwidgetlinecontrol.cpp
index 9dd61c2c6a..ce1b8706ae 100644
--- a/src/widgets/widgets/qwidgetlinecontrol.cpp
+++ b/src/widgets/widgets/qwidgetlinecontrol.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qwidgetlinecontrol_p.h"
@@ -49,7 +13,7 @@
#endif
#include <qpa/qplatformtheme.h>
#include <qstylehints.h>
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
@@ -98,7 +62,7 @@ void QWidgetLineControl::updateDisplayText(bool forceUpdate)
if (m_echoMode == QLineEdit::Password) {
str.fill(m_passwordCharacter);
- if (m_passwordEchoTimer != 0 && m_cursor > 0 && m_cursor <= m_text.length()) {
+ if (m_passwordEchoTimer != 0 && m_cursor > 0 && m_cursor <= m_text.size()) {
int cursor = m_cursor - 1;
QChar uc = m_text.at(cursor);
str[cursor] = uc;
@@ -118,11 +82,10 @@ void QWidgetLineControl::updateDisplayText(bool forceUpdate)
// drawing boxes when using fonts that don't have glyphs for such
// characters)
QChar* uc = str.data();
- for (int i = 0; i < (int)str.length(); ++i) {
+ 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);
}
@@ -278,7 +241,7 @@ void QWidgetLineControl::clear()
{
int priorState = m_undoState;
m_selstart = 0;
- m_selend = m_text.length();
+ m_selend = m_text.size();
removeSelectedText();
separate();
finishChange(priorState, /*update*/false, /*edited*/false);
@@ -322,7 +285,7 @@ void QWidgetLineControl::setSelection(int start, int length)
if (start == m_selstart && start + length == m_selend && m_cursor == m_selend)
return;
m_selstart = start;
- m_selend = qMin(start + length, (int)m_text.length());
+ m_selend = qMin(start + length, (int)m_text.size());
m_cursor = m_selend;
} else if (length < 0){
if (start == m_selend && start + length == m_selstart && m_cursor == m_selstart)
@@ -365,7 +328,7 @@ void QWidgetLineControl::init(const QString &txt)
m_textLayout.setCacheEnabled(true);
m_text = txt;
updateDisplayText();
- m_cursor = m_text.length();
+ m_cursor = m_text.size();
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
m_keyboardScheme = theme->themeHint(QPlatformTheme::KeyboardScheme).toInt();
m_passwordMaskDelay = theme->themeHint(QPlatformTheme::PasswordMaskDelay).toInt();
@@ -419,7 +382,7 @@ QRect QWidgetLineControl::rectForPos(int pos) const
int w = m_cursorWidth;
int ch = l.height() + 1;
- return QRect(cix-5, 0, w+9, ch);
+ return QRect(cix - 5, 0, w + 9, ch);
}
/*!
@@ -527,14 +490,14 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event)
if (echoMode() == QLineEdit::PasswordEchoOnEdit && !passwordEchoEditing()) {
updatePasswordEchoEditing(true);
m_selstart = 0;
- m_selend = m_text.length();
+ m_selend = m_text.size();
}
removeSelectedText();
}
int c = m_cursor; // cursor position after insertion of commit string
if (event->replacementStart() <= 0)
- c += event->commitString().length() - qMin(-event->replacementStart(), event->replacementLength());
+ c += event->commitString().size() - qMin(-event->replacementStart(), event->replacementLength());
m_cursor += event->replacementStart();
if (m_cursor < 0)
@@ -550,15 +513,15 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event)
internalInsert(event->commitString());
cursorPositionChanged = true;
} else {
- m_cursor = qBound(0, c, m_text.length());
+ m_cursor = qBound(0, c, m_text.size());
}
for (int i = 0; i < event->attributes().size(); ++i) {
const QInputMethodEvent::Attribute &a = event->attributes().at(i);
if (a.type == QInputMethodEvent::Selection) {
- m_cursor = qBound(0, a.start + a.length, m_text.length());
+ m_cursor = qBound(0, a.start + a.length, m_text.size());
if (a.length) {
- m_selstart = qMax(0, qMin(a.start, m_text.length()));
+ m_selstart = qMax(0, qMin(a.start, m_text.size()));
m_selend = m_cursor;
if (m_selend < m_selstart) {
qSwap(m_selstart, m_selend);
@@ -573,12 +536,26 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event)
}
}
#ifndef QT_NO_IM
- setPreeditArea(m_cursor, event->preeditString());
+ // in NoEcho mode, the cursor is always at the beginning of the lineedit
+ switch (m_echoMode) {
+ case QLineEdit::NoEcho:
+ setPreeditArea(0, QString());
+ break;
+ case QLineEdit::Password: {
+ QString preeditString = event->preeditString();
+ preeditString.fill(m_passwordCharacter);
+ setPreeditArea(m_cursor, preeditString);
+ break;
+ }
+ default:
+ setPreeditArea(m_cursor, event->preeditString());
+ break;
+ }
#endif //QT_NO_IM
const int oldPreeditCursor = m_preeditCursor;
- m_preeditCursor = event->preeditString().length();
+ m_preeditCursor = event->preeditString().size();
m_hideCursor = false;
- QVector<QTextLayout::FormatRange> formats;
+ QList<QTextLayout::FormatRange> formats;
formats.reserve(event->attributes().size());
for (int i = 0; i < event->attributes().size(); ++i) {
const QInputMethodEvent::Attribute &a = event->attributes().at(i);
@@ -627,7 +604,7 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event)
*/
void QWidgetLineControl::draw(QPainter *painter, const QPoint &offset, const QRect &clip, int flags)
{
- QVector<QTextLayout::FormatRange> selections;
+ QList<QTextLayout::FormatRange> selections;
if (flags & DrawSelections) {
QTextLayout::FormatRange o;
if (m_selstart < m_selend) {
@@ -669,7 +646,7 @@ void QWidgetLineControl::draw(QPainter *painter, const QPoint &offset, const QRe
void QWidgetLineControl::selectWordAtPos(int cursor)
{
int next = cursor + 1;
- if(next > end())
+ if (next > end())
--next;
int c = textLayout()->previousCursorPosition(next, QTextLayout::SkipWords);
moveCursor(c, false);
@@ -694,7 +671,7 @@ void QWidgetLineControl::selectWordAtPos(int cursor)
*/
bool QWidgetLineControl::finishChange(int validateFromState, bool update, bool edited)
{
- Q_UNUSED(update)
+ Q_UNUSED(update);
if (m_textDirty) {
// do validation
@@ -717,7 +694,7 @@ bool QWidgetLineControl::finishChange(int validateFromState, bool update, bool e
}
#endif
if (validateFromState >= 0 && wasValidInput && !m_validInput) {
- if (m_transactions.count())
+ if (m_transactions.size())
return false;
internalUndo(validateFromState);
m_history.erase(m_history.begin() + m_undoState, m_history.end());
@@ -741,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;
}
@@ -759,7 +736,7 @@ void QWidgetLineControl::internalSetText(const QString &txt, int pos, bool edite
QString oldText = m_text;
if (m_maskData) {
m_text = maskString(0, txt, true);
- m_text += clearString(m_text.length(), m_maxLength - m_text.length());
+ m_text += clearString(m_text.size(), m_maxLength - m_text.size());
if (edited && oldText == m_text)
emit inputRejected();
} else {
@@ -767,11 +744,11 @@ void QWidgetLineControl::internalSetText(const QString &txt, int pos, bool edite
}
m_history.clear();
m_modifiedState = m_undoState = 0;
- m_cursor = (pos < 0 || pos > m_text.length()) ? m_text.length() : pos;
+ m_cursor = (pos < 0 || pos > m_text.size()) ? m_text.size() : pos;
m_textDirty = (oldText != m_text);
const bool changed = finishChange(-1, true, edited);
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (changed) {
if (oldText.isEmpty()) {
QAccessibleTextInsertEvent event(accessibleObject(), 0, txt);
@@ -788,7 +765,7 @@ void QWidgetLineControl::internalSetText(const QString &txt, int pos, bool edite
}
}
#else
- Q_UNUSED(changed)
+ Q_UNUSED(changed);
#endif
}
@@ -804,7 +781,7 @@ void QWidgetLineControl::addCommand(const Command &cmd)
m_history.erase(m_history.begin() + m_undoState, m_history.end());
if (m_separator && m_undoState && m_history[m_undoState - 1].type != Separator)
- m_history.push_back(Command(Separator, m_cursor, 0, m_selstart, m_selend));
+ m_history.push_back(Command(Separator, m_cursor, u'\0', m_selstart, m_selend));
m_separator = false;
m_history.push_back(cmd);
@@ -836,40 +813,40 @@ void QWidgetLineControl::internalInsert(const QString &s)
m_passwordEchoTimer = startTimer(delay);
}
if (hasSelectedText())
- addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend));
+ addCommand(Command(SetSelection, m_cursor, u'\0', m_selstart, m_selend));
if (m_maskData) {
QString ms = maskString(m_cursor, s);
if (ms.isEmpty() && !s.isEmpty())
emit inputRejected();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleTextInsertEvent insertEvent(accessibleObject(), m_cursor, ms);
QAccessible::updateAccessibility(&insertEvent);
#endif
- for (int i = 0; i < (int) ms.length(); ++i) {
+ for (int i = 0; i < (int) ms.size(); ++i) {
addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1));
addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1));
}
- m_text.replace(m_cursor, ms.length(), ms);
- m_cursor += ms.length();
+ m_text.replace(m_cursor, ms.size(), ms);
+ m_cursor += ms.size();
m_cursor = nextMaskBlank(m_cursor);
m_textDirty = true;
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleTextCursorEvent event(accessibleObject(), m_cursor);
QAccessible::updateAccessibility(&event);
#endif
} else {
- int remaining = m_maxLength - m_text.length();
+ int remaining = m_maxLength - m_text.size();
if (remaining != 0) {
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleTextInsertEvent insertEvent(accessibleObject(), m_cursor, s);
QAccessible::updateAccessibility(&insertEvent);
#endif
m_text.insert(m_cursor, s.left(remaining));
- for (int i = 0; i < (int) s.left(remaining).length(); ++i)
+ for (int i = 0; i < (int) s.left(remaining).size(); ++i)
addCommand(Command(Insert, m_cursor++, s.at(i), -1, -1));
m_textDirty = true;
}
- if (s.length() > remaining)
+ if (s.size() > remaining)
emit inputRejected();
}
}
@@ -887,13 +864,13 @@ void QWidgetLineControl::internalInsert(const QString &s)
*/
void QWidgetLineControl::internalDelete(bool wasBackspace)
{
- if (m_cursor < (int) m_text.length()) {
+ if (m_cursor < (int) m_text.size()) {
cancelPasswordEchoTimer();
if (hasSelectedText())
- addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend));
+ addCommand(Command(SetSelection, m_cursor, u'\0', m_selstart, m_selend));
addCommand(Command((CommandType)((m_maskData ? 2 : 0) + (wasBackspace ? Remove : Delete)),
m_cursor, m_text.at(m_cursor), -1, -1));
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleTextRemoveEvent event(accessibleObject(), m_cursor, m_text.at(m_cursor));
QAccessible::updateAccessibility(&event);
#endif
@@ -918,11 +895,11 @@ void QWidgetLineControl::internalDelete(bool wasBackspace)
*/
void QWidgetLineControl::removeSelectedText()
{
- if (m_selstart < m_selend && m_selend <= (int) m_text.length()) {
+ if (m_selstart < m_selend && m_selend <= (int) m_text.size()) {
cancelPasswordEchoTimer();
separate();
int i ;
- addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend));
+ addCommand(Command(SetSelection, m_cursor, u'\0', m_selstart, m_selend));
if (m_selstart <= m_cursor && m_cursor < m_selend) {
// cursor is within the selection. Split up the commands
// to be able to restore the correct cursor position
@@ -934,7 +911,7 @@ void QWidgetLineControl::removeSelectedText()
for (i = m_selend-1; i >= m_selstart; --i)
addCommand (Command(RemoveSelection, i, m_text.at(i), -1, -1));
}
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
QAccessibleTextRemoveEvent event(accessibleObject(), m_selstart, m_text.mid(m_selstart, m_selend - m_selstart));
QAccessible::updateAccessibility(&event);
#endif
@@ -960,11 +937,10 @@ void QWidgetLineControl::removeSelectedText()
*/
void QWidgetLineControl::parseInputMask(const QString &maskFields)
{
- int delimiter = maskFields.indexOf(QLatin1Char(';'));
+ qsizetype delimiter = maskFields.indexOf(u';');
if (maskFields.isEmpty() || delimiter == 0) {
if (m_maskData) {
- delete [] m_maskData;
- m_maskData = nullptr;
+ m_maskData.reset();
m_maxLength = 32767;
internalSetText(QString(), -1, false);
}
@@ -972,47 +948,42 @@ void QWidgetLineControl::parseInputMask(const QString &maskFields)
}
if (delimiter == -1) {
- m_blank = QLatin1Char(' ');
+ m_blank = u' ';
m_inputMask = maskFields;
} else {
m_inputMask = maskFields.left(delimiter);
- m_blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : QLatin1Char(' ');
+ m_blank = (delimiter + 1 < maskFields.size()) ? maskFields[delimiter + 1] : u' ';
}
// calculate m_maxLength / m_maskData length
m_maxLength = 0;
- QChar c = 0;
bool escaped = false;
- for (int i=0; i<m_inputMask.length(); i++) {
- c = m_inputMask.at(i);
+ for (int i=0; i<m_inputMask.size(); i++) {
+ const auto c = m_inputMask.at(i);
if (escaped) {
++m_maxLength;
escaped = false;
continue;
}
- if (c == '\\') {
+ if (c == u'\\') {
escaped = true;
continue;
}
- if (c != QLatin1Char('\\') && c != QLatin1Char('!') &&
- c != QLatin1Char('<') && c != QLatin1Char('>') &&
- c != QLatin1Char('{') && c != QLatin1Char('}') &&
- c != QLatin1Char('[') && c != QLatin1Char(']'))
+ if (c != u'\\' && c != u'!' && c != u'<' && c != u'>' &&
+ c != u'{' && c != u'}' && c != u'[' && c != u']')
m_maxLength++;
}
- delete [] m_maskData;
- m_maskData = new MaskInputData[m_maxLength];
+ m_maskData = std::make_unique<MaskInputData[]>(m_maxLength);
MaskInputData::Casemode m = MaskInputData::NoCaseMode;
- c = 0;
bool s;
bool escape = false;
int index = 0;
- for (int i = 0; i < m_inputMask.length(); i++) {
- c = m_inputMask.at(i);
+ for (int i = 0; i < m_inputMask.size(); i++) {
+ const auto c = m_inputMask.at(i);
if (escape) {
s = true;
m_maskData[index].maskChar = c;
@@ -1020,13 +991,13 @@ void QWidgetLineControl::parseInputMask(const QString &maskFields)
m_maskData[index].caseMode = m;
index++;
escape = false;
- } else if (c == QLatin1Char('<')) {
- m = MaskInputData::Lower;
- } else if (c == QLatin1Char('>')) {
+ } else if (c == u'<') {
+ m = MaskInputData::Lower;
+ } else if (c == u'>') {
m = MaskInputData::Upper;
- } else if (c == QLatin1Char('!')) {
+ } else if (c == u'!') {
m = MaskInputData::NoCaseMode;
- } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) {
+ } else if (c != u'{' && c != u'}' && c != u'[' && c != u']') {
switch (c.unicode()) {
case 'A':
case 'a':
@@ -1114,23 +1085,23 @@ bool QWidgetLineControl::isValidInput(QChar key, QChar mask) const
return true;
break;
case '#':
- if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == m_blank)
+ if (key.isNumber() || key == u'+' || key == u'-' || key == m_blank)
return true;
break;
case 'B':
- if (key == QLatin1Char('0') || key == QLatin1Char('1'))
+ if (key == u'0' || key == u'1')
return true;
break;
case 'b':
- if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == m_blank)
+ if (key == u'0' || key == u'1' || key == m_blank)
return true;
break;
case 'H':
- if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')))
+ if (key.isNumber() || (key >= u'a' && key <= u'f') || (key >= u'A' && key <= u'F'))
return true;
break;
case 'h':
- if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == m_blank)
+ if (key.isNumber() || (key >= u'a' && key <= u'f') || (key >= u'A' && key <= u'F') || key == m_blank)
return true;
break;
default:
@@ -1160,7 +1131,7 @@ bool QWidgetLineControl::hasAcceptableInput(const QString &str) const
if (!m_maskData)
return true;
- if (str.length() != m_maxLength)
+ if (str.size() != m_maxLength)
return false;
for (int i=0; i < m_maxLength; ++i) {
@@ -1195,47 +1166,47 @@ QString QWidgetLineControl::maskString(int pos, const QString &str, bool clear)
QString s = QString::fromLatin1("");
int i = pos;
while (i < m_maxLength) {
- if (strIndex < str.length()) {
+ if (strIndex < str.size()) {
if (m_maskData[i].separator) {
s += m_maskData[i].maskChar;
- if (str[(int)strIndex] == m_maskData[i].maskChar)
+ if (str[strIndex] == m_maskData[i].maskChar)
strIndex++;
++i;
} else {
- if (isValidInput(str[(int)strIndex], m_maskData[i].maskChar)) {
+ if (isValidInput(str[strIndex], m_maskData[i].maskChar)) {
switch (m_maskData[i].caseMode) {
case MaskInputData::Upper:
- s += str[(int)strIndex].toUpper();
+ s += str[strIndex].toUpper();
break;
case MaskInputData::Lower:
- s += str[(int)strIndex].toLower();
+ s += str[strIndex].toLower();
break;
default:
- s += str[(int)strIndex];
+ s += str[strIndex];
}
++i;
} else {
// search for separator first
- int n = findInMask(i, true, true, str[(int)strIndex]);
+ int n = findInMask(i, true, true, str[strIndex]);
if (n != -1) {
- if (str.length() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[(int)strIndex]))) {
- s += fill.midRef(i, n - i + 1);
+ if (str.size() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[strIndex]))) {
+ s += QStringView{fill}.mid(i, n - i + 1);
i = n + 1; // update i to find + 1
}
} else {
// search for valid m_blank if not
- n = findInMask(i, true, false, str[(int)strIndex]);
+ n = findInMask(i, true, false, str[strIndex]);
if (n != -1) {
- s += fill.midRef(i, n - i);
+ s += QStringView{fill}.mid(i, n - i);
switch (m_maskData[n].caseMode) {
case MaskInputData::Upper:
- s += str[(int)strIndex].toUpper();
+ s += str[strIndex].toUpper();
break;
case MaskInputData::Lower:
- s += str[(int)strIndex].toLower();
+ s += str[strIndex].toLower();
break;
default:
- s += str[(int)strIndex];
+ s += str[strIndex];
}
i = n + 1; // updates i to find + 1
}
@@ -1286,7 +1257,7 @@ QString QWidgetLineControl::stripString(const QString &str) const
return str;
QString s;
- int end = qMin(m_maxLength, (int)str.length());
+ int end = qMin(m_maxLength, (int)str.size());
for (int i = 0; i < end; ++i)
if (m_maskData[i].separator)
s += m_maskData[i].maskChar;
@@ -1424,8 +1395,8 @@ void QWidgetLineControl::emitCursorPositionChanged()
if (m_cursor != m_lastCursorPos) {
const int oldLast = m_lastCursorPos;
m_lastCursorPos = m_cursor;
- cursorPositionChanged(oldLast, m_cursor);
-#ifndef QT_NO_ACCESSIBILITY
+ emit cursorPositionChanged(oldLast, m_cursor);
+#if QT_CONFIG(accessibility)
// otherwise we send a selection update which includes the cursor
if (!hasSelectedText()) {
QAccessibleTextCursorEvent event(accessibleObject(), m_cursor);
@@ -1473,7 +1444,7 @@ void QWidgetLineControl::complete(int key)
return;
int n = 0;
if (key == Qt::Key_Up || key == Qt::Key_Down) {
- if (textAfterSelection().length())
+ if (textAfterSelection().size())
return;
QString prefix = hasSelectedText() ? textBeforeSelection()
: text;
@@ -1662,10 +1633,12 @@ void QWidgetLineControl::processKeyEvent(QKeyEvent* event)
break;
#endif
if (!m_completer->currentCompletion().isEmpty() && hasSelectedText()
+ && !m_completer->completionPrefix().isEmpty()
&& textAfterSelection().isEmpty()) {
setText(m_completer->currentCompletion());
inlineCompletionAccepted = true;
}
+ break;
default:
break; // normal key processing
}
@@ -1837,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();
}
@@ -1948,10 +1926,15 @@ void QWidgetLineControl::processKeyEvent(QKeyEvent* event)
return;
}
- if (unknown)
+ if (unknown) {
event->ignore();
- else
+ } else {
+#ifndef QT_NO_CLIPBOARD
+ if (QApplication::clipboard()->supportsSelection())
+ copy(QClipboard::Selection);
+#endif
event->accept();
+ }
}
bool QWidgetLineControl::isUndoAvailable() const
diff --git a/src/widgets/widgets/qwidgetlinecontrol_p.h b/src/widgets/widgets/qwidgetlinecontrol_p.h
index a8fffd23dc..2ce0fe7d94 100644
--- a/src/widgets/widgets/qwidgetlinecontrol_p.h
+++ b/src/widgets/widgets/qwidgetlinecontrol_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 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 QWIDGETLINECONTROL_P_H
#define QWIDGETLINECONTROL_P_H
@@ -70,7 +34,11 @@
#include "qplatformdefs.h"
#include <vector>
+#include <memory>
+#ifdef Q_OS_WIN
+# include <qt_windows.h>
+#endif
#ifdef DrawText
# undef DrawText
#endif
@@ -110,9 +78,7 @@ public:
// password data to stay in the process memory, therefore we need
// to zero it out
if (m_echoMode != QLineEdit::Normal)
- m_text.fill('\0');
-
- delete [] m_maskData;
+ m_text.fill(u'\0');
}
void setAccessibleObject(QObject *object)
@@ -149,7 +115,7 @@ public:
bool isModified() const { return m_modifiedState != m_undoState; }
void setModified(bool modified) { m_modifiedState = modified ? -1 : m_undoState; }
- bool allSelected() const { return !m_text.isEmpty() && m_selstart == 0 && m_selend == (int)m_text.length(); }
+ bool allSelected() const { return !m_text.isEmpty() && m_selstart == 0 && m_selend == (int)m_text.size(); }
bool hasSelectedText() const { return !m_text.isEmpty() && m_selend > m_selstart; }
int width() const { return qRound(m_textLayout.lineAt(0).width()) + 1; }
@@ -165,6 +131,9 @@ public:
int selectionStart() const { return hasSelectedText() ? m_selstart : -1; }
int selectionEnd() const { return hasSelectedText() ? m_selend : -1; }
+#if defined (Q_OS_ANDROID)
+ bool isSelectableByMouse() const { return true; }
+#endif
bool inSelection(int x) const
{
if (m_selstart >= m_selend)
@@ -181,7 +150,7 @@ public:
}
int start() const { return 0; }
- int end() const { return m_text.length(); }
+ int end() const { return m_text.size(); }
#ifndef QT_NO_CLIPBOARD
void copy(QClipboard::Mode mode = QClipboard::Clipboard) const;
@@ -217,7 +186,7 @@ public:
void cursorWordBackward(bool mark) { moveCursor(m_textLayout.previousCursorPosition(m_cursor, QTextLayout::SkipWords), mark); }
void home(bool mark) { moveCursor(0, mark); }
- void end(bool mark) { moveCursor(m_text.length(), mark); }
+ void end(bool mark) { moveCursor(m_text.size(), mark); }
int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const;
QRect rectForPos(int pos) const;
@@ -262,7 +231,7 @@ public:
void backspace();
void del();
void deselect() { internalDeselect(); finishChange(); }
- void selectAll() { m_selstart = m_selend = m_cursor = 0; moveCursor(m_text.length(), true); }
+ void selectAll() { m_selstart = m_selend = m_cursor = 0; moveCursor(m_text.size(), true); }
void insert(const QString &);
void clear();
@@ -308,7 +277,7 @@ public:
#endif
int cursorPosition() const { return m_cursor; }
- void setCursorPosition(int pos) { if (pos <= m_text.length()) moveCursor(qMax(0, pos)); }
+ void setCursorPosition(int pos) { if (pos <= m_text.size()) moveCursor(qMax(0, pos)); }
bool hasAcceptableInput() const { return hasAcceptableInput(m_text); }
bool fixup();
@@ -318,8 +287,8 @@ public:
QString mask;
if (m_maskData) {
mask = m_inputMask;
- if (m_blank != QLatin1Char(' ')) {
- mask += QLatin1Char(';');
+ if (m_blank != u' ') {
+ mask += u';';
mask += m_blank;
}
}
@@ -354,11 +323,8 @@ public:
void setPasswordMaskDelay(int delay) { m_passwordMaskDelay = delay; }
Qt::LayoutDirection layoutDirection() const {
- if (m_layoutDirection == Qt::LayoutDirectionAuto) {
- if (m_text.isEmpty())
- return QGuiApplication::inputMethod()->inputDirection();
+ if (m_layoutDirection == Qt::LayoutDirectionAuto && !m_text.isEmpty())
return m_text.isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight;
- }
return m_layoutDirection;
}
void setLayoutDirection(Qt::LayoutDirection direction)
@@ -468,7 +434,7 @@ private:
};
QString m_inputMask;
QChar m_blank;
- MaskInputData *m_maskData;
+ std::unique_ptr<MaskInputData[]> m_maskData;
// undo/redo handling
enum CommandType { Separator, Insert, Remove, Delete, RemoveSelection, DeleteSelection, SetSelection };
@@ -550,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/qwidgetresizehandler.cpp b/src/widgets/widgets/qwidgetresizehandler.cpp
index 9dbba12aba..b7ee494e99 100644
--- a/src/widgets/widgets/qwidgetresizehandler.cpp
+++ b/src/widgets/widgets/qwidgetresizehandler.cpp
@@ -1,48 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 "qwidgetresizehandler_p.h"
#include "qframe.h"
#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include <private/qdesktopwidget_p.h>
+#include "private/qwidget_p.h"
#include "qcursor.h"
#if QT_CONFIG(sizegrip)
#include "qsizegrip.h"
@@ -53,51 +16,44 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
#define RANGE 4
static bool resizeHorizontalDirectionFixed = false;
static bool resizeVerticalDirectionFixed = false;
-// ### fixme: Qt 6: No longer export QWidgetResizeHandler and remove "Move"
-// functionality. Currently, only the resize functionality is used by QDockWidget.
-// Historically, the class was used in Qt 3's QWorkspace (predecessor to QMdiArea).
-
QWidgetResizeHandler::QWidgetResizeHandler(QWidget *parent, QWidget *cw)
: QObject(parent), widget(parent), childWidget(cw ? cw : parent),
- fw(0), extrahei(0), buttonDown(false), moveResizeMode(false), sizeprotect(true), movingEnabled(true)
+ fw(0), extrahei(0), buttonDown(false), active(false)
{
mode = Nowhere;
widget->setMouseTracking(true);
QFrame *frame = qobject_cast<QFrame*>(widget);
range = frame ? frame->frameWidth() : RANGE;
range = qMax(RANGE, range);
- activeForMove = activeForResize = true;
+ enabled = true;
widget->installEventFilter(this);
}
-void QWidgetResizeHandler::setActive(Action ac, bool b)
+void QWidgetResizeHandler::setEnabled(bool b)
{
- if (ac & Move)
- activeForMove = b;
- if (ac & Resize)
- activeForResize = b;
+ if (b == enabled)
+ return;
- if (!isActive())
+ enabled = b;
+ if (!enabled)
setMouseCursor(Nowhere);
}
-bool QWidgetResizeHandler::isActive(Action ac) const
+bool QWidgetResizeHandler::isEnabled() const
{
- bool b = false;
- if (ac & Move) b = activeForMove;
- if (ac & Resize) b |= activeForResize;
-
- return b;
+ return enabled;
}
bool QWidgetResizeHandler::eventFilter(QObject *o, QEvent *ee)
{
- if (!isActive()
+ if (!isEnabled()
|| (ee->type() != QEvent::MouseButtonPress
&& ee->type() != QEvent::MouseButtonRelease
&& ee->type() != QEvent::MouseMove
@@ -120,41 +76,30 @@ bool QWidgetResizeHandler::eventFilter(QObject *o, QEvent *ee)
if (w->isMaximized())
break;
const QRect widgetRect = widget->rect().marginsAdded(QMargins(range, range, range, range));
- const QPoint cursorPoint = widget->mapFromGlobal(e->globalPos());
+ const QPoint cursorPoint = widget->mapFromGlobal(e->globalPosition().toPoint());
if (!widgetRect.contains(cursorPoint))
return false;
if (e->button() == Qt::LeftButton) {
buttonDown = false;
emit activate();
- bool me = movingEnabled;
- movingEnabled = (me && o == widget);
mouseMoveEvent(e);
- movingEnabled = me;
buttonDown = true;
- moveOffset = widget->mapFromGlobal(e->globalPos());
+ moveOffset = widget->mapFromGlobal(e->globalPosition().toPoint());
invertedMoveOffset = widget->rect().bottomRight() - moveOffset;
- if (mode == Center) {
- if (movingEnabled)
- return true;
- } else {
+ if (mode != Center)
return true;
- }
}
} break;
case QEvent::MouseButtonRelease:
if (w->isMaximized())
break;
if (static_cast<QMouseEvent *>(ee)->button() == Qt::LeftButton) {
- moveResizeMode = false;
+ active = false;
buttonDown = false;
widget->releaseMouse();
widget->releaseKeyboard();
- if (mode == Center) {
- if (movingEnabled)
- return true;
- } else {
+ if (mode != Center)
return true;
- }
}
break;
case QEvent::MouseMove: {
@@ -162,16 +107,9 @@ bool QWidgetResizeHandler::eventFilter(QObject *o, QEvent *ee)
break;
QMouseEvent *e = static_cast<QMouseEvent *>(ee);
buttonDown = buttonDown && (e->buttons() & Qt::LeftButton); // safety, state machine broken!
- bool me = movingEnabled;
- movingEnabled = (me && o == widget && (buttonDown || moveResizeMode));
mouseMoveEvent(e);
- movingEnabled = me;
- if (mode == Center) {
- if (movingEnabled)
- return true;
- } else {
+ if (mode != Center)
return true;
- }
} break;
case QEvent::KeyPress:
keyPressEvent(static_cast<QKeyEvent *>(ee));
@@ -192,8 +130,8 @@ bool QWidgetResizeHandler::eventFilter(QObject *o, QEvent *ee)
void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e)
{
- QPoint pos = widget->mapFromGlobal(e->globalPos());
- if (!moveResizeMode && !buttonDown) {
+ QPoint pos = widget->mapFromGlobal(e->globalPosition().toPoint());
+ if (!active && !buttonDown) {
if (pos.y() <= range && pos.x() <= range)
mode = TopLeft;
else if (pos.y() >= widget->height()-range && pos.x() >= widget->width()-range)
@@ -215,7 +153,7 @@ void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e)
else
mode = Nowhere;
- if (widget->isMinimized() || !isActive(Resize))
+ if (widget->isMinimized() || !isEnabled())
mode = Center;
#ifndef QT_NO_CURSOR
setMouseCursor(mode);
@@ -223,7 +161,7 @@ void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e)
return;
}
- if (mode == Center && !movingEnabled)
+ if (mode == Center)
return;
if (widget->testAttribute(Qt::WA_WState_ConfigPending))
@@ -231,15 +169,15 @@ void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e)
QPoint globalPos = (!widget->isWindow() && widget->parentWidget()) ?
- widget->parentWidget()->mapFromGlobal(e->globalPos()) : e->globalPos();
+ widget->parentWidget()->mapFromGlobal(e->globalPosition().toPoint()) : e->globalPosition().toPoint();
if (!widget->isWindow() && !widget->parentWidget()->rect().contains(globalPos)) {
if (globalPos.x() < 0)
globalPos.rx() = 0;
if (globalPos.y() < 0)
globalPos.ry() = 0;
- if (sizeprotect && globalPos.x() > widget->parentWidget()->width())
+ if (globalPos.x() > widget->parentWidget()->width())
globalPos.rx() = widget->parentWidget()->width();
- if (sizeprotect && globalPos.y() > widget->parentWidget()->height())
+ if (globalPos.y() > widget->parentWidget()->height())
globalPos.ry() = widget->parentWidget()->height();
}
@@ -247,8 +185,8 @@ void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e)
QPoint pp = globalPos - moveOffset;
// Workaround for window managers which refuse to move a tool window partially offscreen.
- if (QGuiApplication::platformName() == QLatin1String("xcb")) {
- const QRect desktop = QDesktopWidgetPrivate::availableGeometry(widget);
+ if (QGuiApplication::platformName() == "xcb"_L1) {
+ const QRect desktop = QWidgetPrivate::availableScreenGeometry(widget);
pp.rx() = qMax(pp.x(), desktop.left());
pp.ry() = qMax(pp.y(), desktop.top());
p.rx() = qMin(p.x(), desktop.right());
@@ -300,9 +238,6 @@ void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e)
case Right:
geom = QRect(widget->geometry().topLeft(), QPoint(p.x(), widget->geometry().bottom())) ;
break;
- case Center:
- geom.moveTopLeft(pp);
- break;
default:
break;
}
@@ -314,10 +249,7 @@ void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e)
if (geom != widget->geometry() &&
(widget->isWindow() || widget->parentWidget()->rect().intersects(geom))) {
- if (mode == Center)
- widget->move(geom.topLeft());
- else
- widget->setGeometry(geom);
+ widget->setGeometry(geom);
}
}
@@ -361,7 +293,7 @@ void QWidgetResizeHandler::setMouseCursor(MousePosition m)
void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
{
- if (!isMove() && !isResize())
+ if (!isResizing())
return;
bool is_control = e->modifiers() & Qt::ControlModifier;
int delta = is_control?1:8;
@@ -369,7 +301,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
switch (e->key()) {
case Qt::Key_Left:
pos.rx() -= delta;
- if (pos.x() <= QDesktopWidgetPrivate::geometry().left()) {
+ if (pos.x() <= QGuiApplication::primaryScreen()->virtualGeometry().left()) {
if (mode == TopLeft || mode == BottomLeft) {
moveOffset.rx() += delta;
invertedMoveOffset.rx() += delta;
@@ -378,7 +310,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
invertedMoveOffset.rx() -= delta;
}
}
- if (isResize() && !resizeHorizontalDirectionFixed) {
+ if (isResizing() && !resizeHorizontalDirectionFixed) {
resizeHorizontalDirectionFixed = true;
if (mode == BottomRight)
mode = BottomLeft;
@@ -394,7 +326,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
break;
case Qt::Key_Right:
pos.rx() += delta;
- if (pos.x() >= QDesktopWidgetPrivate::geometry().right()) {
+ if (pos.x() >= QGuiApplication::primaryScreen()->virtualGeometry().right()) {
if (mode == TopRight || mode == BottomRight) {
moveOffset.rx() += delta;
invertedMoveOffset.rx() += delta;
@@ -403,7 +335,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
invertedMoveOffset.rx() -= delta;
}
}
- if (isResize() && !resizeHorizontalDirectionFixed) {
+ if (isResizing() && !resizeHorizontalDirectionFixed) {
resizeHorizontalDirectionFixed = true;
if (mode == BottomLeft)
mode = BottomRight;
@@ -419,7 +351,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
break;
case Qt::Key_Up:
pos.ry() -= delta;
- if (pos.y() <= QDesktopWidgetPrivate::geometry().top()) {
+ if (pos.y() <= QGuiApplication::primaryScreen()->virtualGeometry().top()) {
if (mode == TopLeft || mode == TopRight) {
moveOffset.ry() += delta;
invertedMoveOffset.ry() += delta;
@@ -428,7 +360,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
invertedMoveOffset.ry() -= delta;
}
}
- if (isResize() && !resizeVerticalDirectionFixed) {
+ if (isResizing() && !resizeVerticalDirectionFixed) {
resizeVerticalDirectionFixed = true;
if (mode == BottomLeft)
mode = TopLeft;
@@ -444,7 +376,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
break;
case Qt::Key_Down:
pos.ry() += delta;
- if (pos.y() >= QDesktopWidgetPrivate::geometry().bottom()) {
+ if (pos.y() >= QGuiApplication::primaryScreen()->virtualGeometry().bottom()) {
if (mode == BottomLeft || mode == BottomRight) {
moveOffset.ry() += delta;
invertedMoveOffset.ry() += delta;
@@ -453,7 +385,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
invertedMoveOffset.ry() -= delta;
}
}
- if (isResize() && !resizeVerticalDirectionFixed) {
+ if (isResizing() && !resizeVerticalDirectionFixed) {
resizeVerticalDirectionFixed = true;
if (mode == TopLeft)
mode = BottomLeft;
@@ -471,7 +403,7 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
case Qt::Key_Return:
case Qt::Key_Enter:
case Qt::Key_Escape:
- moveResizeMode = false;
+ active = false;
widget->releaseMouse();
widget->releaseKeyboard();
buttonDown = false;
@@ -485,10 +417,10 @@ void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
void QWidgetResizeHandler::doResize()
{
- if (!activeForResize)
+ if (!enabled)
return;
- moveResizeMode = true;
+ active = true;
moveOffset = widget->mapFromGlobal(QCursor::pos());
if (moveOffset.x() < widget->width()/2) {
if (moveOffset.y() < widget->height()/2)
@@ -513,23 +445,6 @@ void QWidgetResizeHandler::doResize()
resizeVerticalDirectionFixed = false;
}
-void QWidgetResizeHandler::doMove()
-{
- if (!activeForMove)
- return;
-
- mode = Center;
- moveResizeMode = true;
- moveOffset = widget->mapFromGlobal(QCursor::pos());
- invertedMoveOffset = widget->rect().bottomRight() - moveOffset;
-#ifndef QT_NO_CURSOR
- widget->grabMouse(Qt::SizeAllCursor);
-#else
- widget->grabMouse();
-#endif
- widget->grabKeyboard();
-}
-
QT_END_NAMESPACE
#include "moc_qwidgetresizehandler_p.cpp"
diff --git a/src/widgets/widgets/qwidgetresizehandler_p.h b/src/widgets/widgets/qwidgetresizehandler_p.h
index df3ac7cb8a..d7780a55e6 100644
--- a/src/widgets/widgets/qwidgetresizehandler_p.h
+++ b/src/widgets/widgets/qwidgetresizehandler_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// 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 QWIDGETRESIZEHANDLER_P_H
#define QWIDGETRESIZEHANDLER_P_H
@@ -62,34 +26,22 @@ QT_BEGIN_NAMESPACE
class QMouseEvent;
class QKeyEvent;
-class Q_WIDGETS_EXPORT QWidgetResizeHandler : public QObject
+class QWidgetResizeHandler : public QObject
{
Q_OBJECT
public:
- enum Action {
- Move = 0x01,
- Resize = 0x02,
- Any = Move|Resize
- };
-
explicit QWidgetResizeHandler(QWidget *parent, QWidget *cw = nullptr);
- void setActive(bool b) { setActive(Any, b); }
- void setActive(Action ac, bool b);
- bool isActive() const { return isActive(Any); }
- bool isActive(Action ac) const;
- void setMovingEnabled(bool b) { movingEnabled = b; }
- bool isMovingEnabled() const { return movingEnabled; }
+ void setEnabled(bool b);
+ bool isEnabled() const;
bool isButtonDown() const { return buttonDown; }
void setExtraHeight(int h) { extrahei = h; }
- void setSizeProtection(bool b) { sizeprotect = b; }
void setFrameWidth(int w) { fw = w; }
void doResize();
- void doMove();
Q_SIGNALS:
void activate();
@@ -117,19 +69,13 @@ private:
int fw;
int extrahei;
int range;
- uint buttonDown :1;
- uint moveResizeMode :1;
- uint activeForResize :1;
- uint sizeprotect :1;
- uint movingEnabled :1;
- uint activeForMove :1;
+ uint buttonDown :1;
+ uint active :1;
+ uint enabled :1;
void setMouseCursor(MousePosition m);
- bool isMove() const {
- return moveResizeMode && mode == Center;
- }
- bool isResize() const {
- return moveResizeMode && !isMove();
+ bool isResizing() const {
+ return active && mode != Center;
}
};
diff --git a/src/widgets/widgets/qwidgettextcontrol.cpp b/src/widgets/widgets/qwidgettextcontrol.cpp
index 49a1a02867..6dcaeee0c8 100644
--- a/src/widgets/widgets/qwidgettextcontrol.cpp
+++ b/src/widgets/widgets/qwidgettextcontrol.cpp
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 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 "qwidgettextcontrol_p.h"
#include "qwidgettextcontrol_p_p.h"
@@ -50,16 +14,17 @@
#include <qdrag.h>
#endif
#include <qclipboard.h>
-#if QT_CONFIG(menu)
-#include <qmenu.h>
-#endif
#include <qstyle.h>
#include <qtimer.h>
#include "private/qapplication_p.h"
#include "private/qtextdocumentlayout_p.h"
#include "private/qabstracttextdocumentlayout_p.h"
+#if QT_CONFIG(menu)
+#include "private/qmenu_p.h"
+#endif
#include "qtextdocument.h"
#include "private/qtextdocument_p.h"
+#include "private/qtextdocumentfragment_p.h"
#include "qtextlist.h"
#include "private/qwidgettextcontrol_p.h"
#if QT_CONFIG(style_stylesheet)
@@ -84,7 +49,9 @@
#include <qurl.h>
#include <qdesktopservices.h>
#include <qinputmethod.h>
+#if QT_CONFIG(tooltip)
#include <qtooltip.h>
+#endif
#include <qstyleoption.h>
#if QT_CONFIG(lineedit)
#include <QtWidgets/qlineedit.h>
@@ -96,10 +63,9 @@
#include "private/qapplication_p.h"
#include "private/qshortcutmap_p.h"
#include <qkeysequence.h>
-#define ACCEL_KEY(k) ((!QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus) \
- && QGuiApplication::styleHints()->showShortcutsInContextMenus()) \
+#define ACCEL_KEY(k) (!QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus) \
&& !QGuiApplicationPrivate::instance()->shortcutMap.hasShortcutForKeySequence(k) ? \
- QLatin1Char('\t') + QKeySequence(k).toString(QKeySequence::NativeText) : QString())
+ u'\t' + QKeySequence(k).toString(QKeySequence::NativeText) : QString())
#else
#define ACCEL_KEY(k) QString()
@@ -109,6 +75,8 @@
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
// could go into QTextCursor...
static QTextLine currentTextLine(const QTextCursor &cursor)
{
@@ -445,25 +413,30 @@ void QWidgetTextControlPrivate::setContent(Qt::TextFormat format, const QString
if (!doc) {
if (document) {
doc = document;
- clearDocument = false;
} else {
palette = QApplication::palette("QWidgetTextControl");
doc = new QTextDocument(q);
}
+ clearDocument = false;
_q_documentLayoutChanged();
cursor = QTextCursor(doc);
// #### doc->documentLayout()->setPaintDevice(viewport);
- QObject::connect(doc, SIGNAL(contentsChanged()), q, SLOT(_q_updateCurrentCharFormatAndSelection()));
- QObject::connect(doc, SIGNAL(cursorPositionChanged(QTextCursor)), q, SLOT(_q_emitCursorPosChanged(QTextCursor)));
- QObject::connect(doc, SIGNAL(documentLayoutChanged()), q, SLOT(_q_documentLayoutChanged()));
+ QObjectPrivate::connect(doc, &QTextDocument::contentsChanged, this,
+ &QWidgetTextControlPrivate::_q_updateCurrentCharFormatAndSelection);
+ QObjectPrivate::connect(doc, &QTextDocument::cursorPositionChanged, this,
+ &QWidgetTextControlPrivate::_q_emitCursorPosChanged);
+ QObjectPrivate::connect(doc, &QTextDocument::documentLayoutChanged, this,
+ &QWidgetTextControlPrivate::_q_documentLayoutChanged);
// convenience signal forwards
- QObject::connect(doc, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
- QObject::connect(doc, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
- QObject::connect(doc, SIGNAL(modificationChanged(bool)), q, SIGNAL(modificationChanged(bool)));
- QObject::connect(doc, SIGNAL(blockCountChanged(int)), q, SIGNAL(blockCountChanged(int)));
+ QObject::connect(doc, &QTextDocument::undoAvailable, q, &QWidgetTextControl::undoAvailable);
+ QObject::connect(doc, &QTextDocument::redoAvailable, q, &QWidgetTextControl::redoAvailable);
+ QObject::connect(doc, &QTextDocument::modificationChanged, q,
+ &QWidgetTextControl::modificationChanged);
+ QObject::connect(doc, &QTextDocument::blockCountChanged, q,
+ &QWidgetTextControl::blockCountChanged);
}
bool previousUndoRedoState = doc->isUndoRedoEnabled();
@@ -525,7 +498,8 @@ void QWidgetTextControlPrivate::setContent(Qt::TextFormat format, const QString
q->ensureCursorVisible();
emit q->cursorPositionChanged();
- QObject::connect(doc, SIGNAL(contentsChange(int,int,int)), q, SLOT(_q_contentsChanged(int,int,int)), Qt::UniqueConnection);
+ QObjectPrivate::connect(doc, &QTextDocument::contentsChange, this,
+ &QWidgetTextControlPrivate::_q_contentsChanged, Qt::UniqueConnection);
}
void QWidgetTextControlPrivate::startDrag()
@@ -605,7 +579,7 @@ void QWidgetTextControlPrivate::selectionChanged(bool forceEmitSelectionChanged
Q_Q(QWidgetTextControl);
if (forceEmitSelectionChanged) {
emit q->selectionChanged();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (q->parent() && q->parent()->isWidgetType()) {
QAccessibleTextSelectionEvent ev(q->parent(), cursor.anchor(), cursor.position());
QAccessible::updateAccessibility(&ev);
@@ -628,7 +602,7 @@ void QWidgetTextControlPrivate::selectionChanged(bool forceEmitSelectionChanged
&& (cursor.position() != lastSelectionPosition
|| cursor.anchor() != lastSelectionAnchor)))) {
emit q->selectionChanged();
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
if (q->parent() && q->parent()->isWidgetType()) {
QAccessibleTextSelectionEvent ev(q->parent(), cursor.anchor(), cursor.position());
QAccessible::updateAccessibility(&ev);
@@ -669,7 +643,7 @@ void QWidgetTextControlPrivate::_q_emitCursorPosChanged(const QTextCursor &someC
void QWidgetTextControlPrivate::_q_contentsChanged(int from, int charsRemoved, int charsAdded)
{
-#ifndef QT_NO_ACCESSIBILITY
+#if QT_CONFIG(accessibility)
Q_Q(QWidgetTextControl);
if (QAccessible::isActive() && q->parent() && q->parent()->isWidgetType()) {
@@ -681,7 +655,7 @@ void QWidgetTextControlPrivate::_q_contentsChanged(int from, int charsRemoved, i
QString newText = tmp.selectedText();
// always report the right number of removed chars, but in lack of the real string use spaces
- QString oldText = QString(charsRemoved, QLatin1Char(' '));
+ QString oldText = QString(charsRemoved, u' ');
QAccessibleEvent *ev = nullptr;
if (charsRemoved == 0) {
@@ -695,9 +669,9 @@ void QWidgetTextControlPrivate::_q_contentsChanged(int from, int charsRemoved, i
delete ev;
}
#else
- Q_UNUSED(from)
- Q_UNUSED(charsRemoved)
- Q_UNUSED(charsAdded)
+ Q_UNUSED(from);
+ Q_UNUSED(charsRemoved);
+ Q_UNUSED(charsAdded);
#endif
}
@@ -705,10 +679,12 @@ void QWidgetTextControlPrivate::_q_documentLayoutChanged()
{
Q_Q(QWidgetTextControl);
QAbstractTextDocumentLayout *layout = doc->documentLayout();
- QObject::connect(layout, SIGNAL(update(QRectF)), q, SIGNAL(updateRequest(QRectF)));
- QObject::connect(layout, SIGNAL(updateBlock(QTextBlock)), q, SLOT(_q_updateBlock(QTextBlock)));
- QObject::connect(layout, SIGNAL(documentSizeChanged(QSizeF)), q, SIGNAL(documentSizeChanged(QSizeF)));
-
+ QObject::connect(layout, &QAbstractTextDocumentLayout::update, q,
+ &QWidgetTextControl::updateRequest);
+ QObjectPrivate::connect(layout, &QAbstractTextDocumentLayout::updateBlock, this,
+ &QWidgetTextControlPrivate::_q_updateBlock);
+ QObject::connect(layout, &QAbstractTextDocumentLayout::documentSizeChanged, q,
+ &QWidgetTextControl::documentSizeChanged);
}
void QWidgetTextControlPrivate::setCursorVisible(bool visible)
@@ -921,7 +897,7 @@ QTextDocument *QWidgetTextControl::document() const
return d->doc;
}
-void QWidgetTextControl::setTextCursor(const QTextCursor &cursor)
+void QWidgetTextControl::setTextCursor(const QTextCursor &cursor, bool selectionClipboard)
{
Q_D(QWidgetTextControl);
d->cursorIsFocusIndicator = false;
@@ -935,6 +911,13 @@ void QWidgetTextControl::setTextCursor(const QTextCursor &cursor)
d->repaintOldAndNewSelection(oldSelection);
if (posChanged)
emit cursorPositionChanged();
+
+#ifndef QT_NO_CLIPBOARD
+ if (selectionClipboard)
+ d->setClipboardSelection();
+#else
+ Q_UNUSED(selectionClipboard);
+#endif
}
QTextCursor QWidgetTextControl::textCursor() const
@@ -984,20 +967,23 @@ 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();
}
void QWidgetTextControl::processEvent(QEvent *e, const QPointF &coordinateOffset, QWidget *contextWidget)
{
- QMatrix m;
- m.translate(coordinateOffset.x(), coordinateOffset.y());
- processEvent(e, m, contextWidget);
+ QTransform t;
+ t.translate(coordinateOffset.x(), coordinateOffset.y());
+ processEvent(e, t, contextWidget);
}
-void QWidgetTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget *contextWidget)
+void QWidgetTextControl::processEvent(QEvent *e, const QTransform &transform, QWidget *contextWidget)
{
Q_D(QWidgetTextControl);
if (d->interactionFlags == Qt::NoTextInteraction) {
@@ -1038,23 +1024,23 @@ void QWidgetTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget
break;
case QEvent::MouseButtonPress: {
QMouseEvent *ev = static_cast<QMouseEvent *>(e);
- d->mousePressEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(),
- ev->buttons(), ev->globalPos());
+ d->mousePressEvent(ev, ev->button(), transform.map(ev->position().toPoint()), ev->modifiers(),
+ ev->buttons(), ev->globalPosition().toPoint());
break; }
case QEvent::MouseMove: {
QMouseEvent *ev = static_cast<QMouseEvent *>(e);
- d->mouseMoveEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(),
- ev->buttons(), ev->globalPos());
+ d->mouseMoveEvent(ev, ev->button(), transform.map(ev->position().toPoint()), ev->modifiers(),
+ ev->buttons(), ev->globalPosition().toPoint());
break; }
case QEvent::MouseButtonRelease: {
QMouseEvent *ev = static_cast<QMouseEvent *>(e);
- d->mouseReleaseEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(),
- ev->buttons(), ev->globalPos());
+ d->mouseReleaseEvent(ev, ev->button(), transform.map(ev->position().toPoint()), ev->modifiers(),
+ ev->buttons(), ev->globalPosition().toPoint());
break; }
case QEvent::MouseButtonDblClick: {
QMouseEvent *ev = static_cast<QMouseEvent *>(e);
- d->mouseDoubleClickEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(),
- ev->buttons(), ev->globalPos());
+ d->mouseDoubleClickEvent(ev, ev->button(), transform.map(ev->position().toPoint()), ev->modifiers(),
+ ev->buttons(), ev->globalPosition().toPoint());
break; }
case QEvent::InputMethod:
d->inputMethodEvent(static_cast<QInputMethodEvent *>(e));
@@ -1062,7 +1048,7 @@ void QWidgetTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget
#ifndef QT_NO_CONTEXTMENU
case QEvent::ContextMenu: {
QContextMenuEvent *ev = static_cast<QContextMenuEvent *>(e);
- d->contextMenuEvent(ev->globalPos(), matrix.map(ev->pos()), contextWidget);
+ d->contextMenuEvent(ev->globalPos(), transform.map(ev->pos()), contextWidget);
break; }
#endif // QT_NO_CONTEXTMENU
case QEvent::FocusIn:
@@ -1074,13 +1060,13 @@ void QWidgetTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget
d->isEnabled = e->isAccepted();
break;
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
case QEvent::ToolTip: {
QHelpEvent *ev = static_cast<QHelpEvent *>(e);
- d->showToolTip(ev->globalPos(), matrix.map(ev->pos()), contextWidget);
+ d->showToolTip(ev->globalPos(), transform.map(ev->pos()), contextWidget);
break;
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
#if QT_CONFIG(draganddrop)
case QEvent::DragEnter: {
@@ -1094,13 +1080,13 @@ void QWidgetTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget
break;
case QEvent::DragMove: {
QDragMoveEvent *ev = static_cast<QDragMoveEvent *>(e);
- if (d->dragMoveEvent(e, ev->mimeData(), matrix.map(ev->pos())))
+ if (d->dragMoveEvent(e, ev->mimeData(), transform.map(ev->position().toPoint())))
ev->acceptProposedAction();
break;
}
case QEvent::Drop: {
QDropEvent *ev = static_cast<QDropEvent *>(e);
- if (d->dropEvent(ev->mimeData(), matrix.map(ev->pos()), ev->dropAction(), ev->source()))
+ if (d->dropEvent(ev->mimeData(), transform.map(ev->position().toPoint()), ev->dropAction(), ev->source()))
ev->acceptProposedAction();
break;
}
@@ -1109,32 +1095,32 @@ void QWidgetTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget
#if QT_CONFIG(graphicsview)
case QEvent::GraphicsSceneMousePress: {
QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
- d->mousePressEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(), ev->buttons(),
+ d->mousePressEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
ev->screenPos());
break; }
case QEvent::GraphicsSceneMouseMove: {
QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
- d->mouseMoveEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(), ev->buttons(),
+ d->mouseMoveEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
ev->screenPos());
break; }
case QEvent::GraphicsSceneMouseRelease: {
QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
- d->mouseReleaseEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(), ev->buttons(),
+ d->mouseReleaseEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
ev->screenPos());
break; }
case QEvent::GraphicsSceneMouseDoubleClick: {
QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
- d->mouseDoubleClickEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(), ev->buttons(),
+ d->mouseDoubleClickEvent(ev, ev->button(), transform.map(ev->pos()), ev->modifiers(), ev->buttons(),
ev->screenPos());
break; }
case QEvent::GraphicsSceneContextMenu: {
QGraphicsSceneContextMenuEvent *ev = static_cast<QGraphicsSceneContextMenuEvent *>(e);
- d->contextMenuEvent(ev->screenPos(), matrix.map(ev->pos()), contextWidget);
+ d->contextMenuEvent(ev->screenPos(), transform.map(ev->pos()), contextWidget);
break; }
case QEvent::GraphicsSceneHoverMove: {
QGraphicsSceneHoverEvent *ev = static_cast<QGraphicsSceneHoverEvent *>(e);
- d->mouseMoveEvent(ev, Qt::NoButton, matrix.map(ev->pos()), ev->modifiers(),Qt::NoButton,
+ d->mouseMoveEvent(ev, Qt::NoButton, transform.map(ev->pos()), ev->modifiers(),Qt::NoButton,
ev->screenPos());
break; }
@@ -1148,12 +1134,12 @@ void QWidgetTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget
break;
case QEvent::GraphicsSceneDragMove: {
QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
- if (d->dragMoveEvent(e, ev->mimeData(), matrix.map(ev->pos())))
+ if (d->dragMoveEvent(e, ev->mimeData(), transform.map(ev->pos())))
ev->acceptProposedAction();
break; }
case QEvent::GraphicsSceneDrop: {
QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
- if (d->dropEvent(ev->mimeData(), matrix.map(ev->pos()), ev->dropAction(), ev->source()))
+ if (d->dropEvent(ev->mimeData(), transform.map(ev->pos()), ev->dropAction(), ev->source()))
ev->accept();
break; }
#endif // QT_CONFIG(graphicsview)
@@ -1224,6 +1210,9 @@ void QWidgetTextControlPrivate::keyPressEvent(QKeyEvent *e)
if (e == QKeySequence::SelectAll) {
e->accept();
q->selectAll();
+#ifndef QT_NO_CLIPBOARD
+ setClipboardSelection();
+#endif
return;
}
#ifndef QT_NO_CLIPBOARD
@@ -1272,7 +1261,7 @@ void QWidgetTextControlPrivate::keyPressEvent(QKeyEvent *e)
// example)
repaintSelection();
- if (e->key() == Qt::Key_Backspace && !(e->modifiers() & ~Qt::ShiftModifier)) {
+ if (e->key() == Qt::Key_Backspace && !(e->modifiers() & ~(Qt::ShiftModifier | Qt::GroupSwitchModifier))) {
QTextBlockFormat blockFmt = cursor.blockFormat();
QTextList *list = cursor.currentList();
if (list && cursor.atBlockStart() && !cursor.hasSelection()) {
@@ -1290,7 +1279,7 @@ void QWidgetTextControlPrivate::keyPressEvent(QKeyEvent *e)
}
#ifndef QT_NO_SHORTCUT
else if (e == QKeySequence::InsertParagraphSeparator) {
- cursor.insertBlock();
+ insertParagraphSeparator();
e->accept();
goto accept;
} else if (e == QKeySequence::InsertLineSeparator) {
@@ -1375,6 +1364,10 @@ process:
accept:
+#ifndef QT_NO_CLIPBOARD
+ setClipboardSelection();
+#endif
+
e->accept();
cursorOn = true;
@@ -1413,16 +1406,14 @@ QRectF QWidgetTextControlPrivate::rectForPosition(int position) const
if (relativePos == preeditPos)
relativePos += preeditCursor;
else if (relativePos > preeditPos)
- relativePos += layout->preeditAreaText().length();
+ relativePos += layout->preeditAreaText().size();
}
QTextLine line = layout->lineForTextPosition(relativePos);
int cursorWidth;
{
bool ok = false;
-#ifndef QT_NO_PROPERTIES
cursorWidth = docLayout->property("cursorWidth").toInt(&ok);
-#endif
if (!ok)
cursorWidth = 1;
}
@@ -1436,7 +1427,7 @@ QRectF QWidgetTextControlPrivate::rectForPosition(int position) const
if (relativePos < line.textLength() - line.textStart())
w = line.cursorToX(relativePos + 1) - x;
else
- w = QFontMetrics(block.layout()->font()).horizontalAdvance(QLatin1Char(' ')); // in sync with QTextLine::draw()
+ w = QFontMetrics(block.layout()->font()).horizontalAdvance(u' '); // in sync with QTextLine::draw()
}
r = QRectF(layoutPos.x() + x, layoutPos.y() + line.y(),
cursorWidth + w, line.height());
@@ -1792,7 +1783,7 @@ void QWidgetTextControlPrivate::mouseReleaseEvent(QEvent *e, Qt::MouseButton but
#ifndef QT_NO_CLIPBOARD
setClipboardSelection();
selectionChanged(true);
- } else if (button == Qt::MidButton
+ } else if (button == Qt::MiddleButton
&& (interactionFlags & Qt::TextEditable)
&& QGuiApplication::clipboard()->supportsSelection()) {
setCursorPosition(pos);
@@ -1830,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);
}
}
}
@@ -1912,7 +1914,7 @@ bool QWidgetTextControlPrivate::sendMouseEventToInputContext(
QTextLayout *layout = cursor.block().layout();
int cursorPos = q->hitTest(pos, Qt::FuzzyHit) - cursor.position();
- if (cursorPos < 0 || cursorPos > layout->preeditAreaText().length())
+ if (cursorPos < 0 || cursorPos > layout->preeditAreaText().size())
cursorPos = -1;
if (cursorPos >= 0) {
@@ -1941,6 +1943,12 @@ void QWidgetTextControlPrivate::contextMenuEvent(const QPoint &screenPos, const
if (!menu)
return;
menu->setAttribute(Qt::WA_DeleteOnClose);
+
+ if (auto *widget = qobject_cast<QWidget *>(parent)) {
+ if (auto *window = widget->window()->windowHandle())
+ QMenuPrivate::get(menu)->topData()->initialScreen = window->screen();
+ }
+
menu->popup(screenPos);
#endif
}
@@ -2019,7 +2027,7 @@ bool QWidgetTextControlPrivate::dropEvent(const QMimeData *mimeData, const QPoin
void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
{
Q_Q(QWidgetTextControl);
- if (!(interactionFlags & Qt::TextEditable) || cursor.isNull()) {
+ if (!(interactionFlags & (Qt::TextEditable | Qt::TextSelectableByMouse)) || cursor.isNull()) {
e->ignore();
return;
}
@@ -2027,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();
@@ -2063,10 +2076,10 @@ void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
QTextLayout *layout = block.layout();
if (isGettingInput)
layout->setPreeditArea(cursor.position() - block.position(), e->preeditString());
- QVector<QTextLayout::FormatRange> overrides;
+ QList<QTextLayout::FormatRange> overrides;
overrides.reserve(e->attributes().size());
const int oldPreeditCursor = preeditCursor;
- preeditCursor = e->preeditString().length();
+ preeditCursor = e->preeditString().size();
hideCursor = false;
for (int i = 0; i < e->attributes().size(); ++i) {
const QInputMethodEvent::Attribute &a = e->attributes().at(i);
@@ -2083,9 +2096,9 @@ void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
o.format = f;
// Make sure list is sorted by start index
- QVector<QTextLayout::FormatRange>::iterator it = overrides.end();
+ QList<QTextLayout::FormatRange>::iterator it = overrides.end();
while (it != overrides.begin()) {
- QVector<QTextLayout::FormatRange>::iterator previous = it - 1;
+ QList<QTextLayout::FormatRange>::iterator previous = it - 1;
if (o.start >= previous->start) {
overrides.insert(it, o);
break;
@@ -2101,9 +2114,9 @@ void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
if (cursor.charFormat().isValid()) {
int start = cursor.position() - block.position();
- int end = start + e->preeditString().length();
+ int end = start + e->preeditString().size();
- QVector<QTextLayout::FormatRange>::iterator it = overrides.begin();
+ QList<QTextLayout::FormatRange>::iterator it = overrides.begin();
while (it != overrides.end()) {
QTextLayout::FormatRange range = *it;
int rangeStart = range.start;
@@ -2174,12 +2187,12 @@ QVariant QWidgetTextControl::inputMethodQuery(Qt::InputMethodQuery property, QVa
QTextCursor tmpCursor = d->cursor;
int localPos = d->cursor.position() - block.position();
QString result = block.text().mid(localPos);
- while (result.length() < maxLength) {
+ while (result.size() < maxLength) {
int currentBlock = tmpCursor.blockNumber();
tmpCursor.movePosition(QTextCursor::NextBlock);
if (tmpCursor.blockNumber() == currentBlock)
break;
- result += QLatin1Char('\n') + tmpCursor.block().text();
+ result += u'\n' + tmpCursor.block().text();
}
return QVariant(result);
}
@@ -2200,11 +2213,11 @@ QVariant QWidgetTextControl::inputMethodQuery(Qt::InputMethodQuery property, QVa
}
QString result;
while (numBlocks) {
- result += tmpCursor.block().text() + QLatin1Char('\n');
+ result += tmpCursor.block().text() + u'\n';
tmpCursor.movePosition(QTextCursor::NextBlock);
--numBlocks;
}
- result += block.text().midRef(0, localPos);
+ result += QStringView{block.text()}.mid(0, localPos);
return QVariant(result);
}
default:
@@ -2236,6 +2249,7 @@ void QWidgetTextControlPrivate::focusEvent(QFocusEvent *e)
#endif
} else {
setCursorVisible(false);
+ cursorOn = false;
if (cursorIsFocusIndicator
&& e->reason() != Qt::ActiveWindowFocusReason
@@ -2290,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())
@@ -2448,24 +2462,16 @@ void QWidgetTextControl::setOverwriteMode(bool overwrite)
int QWidgetTextControl::cursorWidth() const
{
-#ifndef QT_NO_PROPERTIES
Q_D(const QWidgetTextControl);
return d->doc->documentLayout()->property("cursorWidth").toInt();
-#else
- return 1;
-#endif
}
void QWidgetTextControl::setCursorWidth(int width)
{
Q_D(QWidgetTextControl);
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(width);
-#else
if (width == -1)
- width = QApplication::style()->pixelMetric(QStyle::PM_TextCursorWidth);
+ width = QApplication::style()->pixelMetric(QStyle::PM_TextCursorWidth, nullptr, qobject_cast<QWidget *>(parent()));
d->doc->documentLayout()->setProperty("cursorWidth", width);
-#endif
d->repaintCursor();
}
@@ -2488,12 +2494,12 @@ void QWidgetTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelectio
Q_D(QWidgetTextControl);
QMultiHash<int, int> hash;
- for (int i = 0; i < d->extraSelections.count(); ++i) {
+ for (int i = 0; i < d->extraSelections.size(); ++i) {
const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(i);
hash.insert(esel.cursor.anchor(), i);
}
- for (int i = 0; i < selections.count(); ++i) {
+ for (int i = 0; i < selections.size(); ++i) {
const QTextEdit::ExtraSelection &sel = selections.at(i);
const auto it = hash.constFind(sel.cursor.anchor());
if (it != hash.cend()) {
@@ -2512,7 +2518,7 @@ void QWidgetTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelectio
emit updateRequest(r);
}
- for (QHash<int, int>::iterator it = hash.begin(); it != hash.end(); ++it) {
+ for (auto it = hash.cbegin(); it != hash.cend(); ++it) {
const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(it.value());
QRectF r = selectionRect(esel.cursor);
if (esel.format.boolProperty(QTextFormat::FullWidthSelection)) {
@@ -2522,8 +2528,8 @@ void QWidgetTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelectio
emit updateRequest(r);
}
- d->extraSelections.resize(selections.count());
- for (int i = 0; i < selections.count(); ++i) {
+ d->extraSelections.resize(selections.size());
+ for (int i = 0; i < selections.size(); ++i) {
d->extraSelections[i].cursor = selections.at(i).cursor;
d->extraSelections[i].format = selections.at(i).format;
}
@@ -2533,7 +2539,7 @@ QList<QTextEdit::ExtraSelection> QWidgetTextControl::extraSelections() const
{
Q_D(const QWidgetTextControl);
QList<QTextEdit::ExtraSelection> selections;
- const int numExtraSelections = d->extraSelections.count();
+ const int numExtraSelections = d->extraSelections.size();
selections.reserve(numExtraSelections);
for (int i = 0; i < numExtraSelections; ++i) {
QTextEdit::ExtraSelection sel;
@@ -2668,6 +2674,7 @@ void QWidgetTextControl::print(QPagedPaintDevice *printer) const
if (!d->cursor.hasSelection())
return;
tempDoc = new QTextDocument(const_cast<QTextDocument *>(doc));
+ tempDoc->setResourceProvider(doc->resourceProvider());
tempDoc->setMetaInformation(QTextDocument::DocumentTitle, doc->metaInformation(QTextDocument::DocumentTitle));
tempDoc->setPageSize(doc->pageSize());
tempDoc->setDefaultFont(doc->defaultFont());
@@ -2696,8 +2703,8 @@ bool QWidgetTextControl::canInsertFromMimeData(const QMimeData *source) const
if (d->acceptRichText)
return (source->hasText() && !source->text().isEmpty())
|| source->hasHtml()
- || source->hasFormat(QLatin1String("application/x-qrichtext"))
- || source->hasFormat(QLatin1String("application/x-qt-richtext"));
+ || source->hasFormat("application/x-qrichtext"_L1)
+ || source->hasFormat("application/x-qt-richtext"_L1);
else
return source->hasText() && !source->text().isEmpty();
}
@@ -2710,26 +2717,33 @@ void QWidgetTextControl::insertFromMimeData(const QMimeData *source)
bool hasData = false;
QTextDocumentFragment fragment;
+#if QT_CONFIG(textmarkdownreader)
+ 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;
+ } else
+#endif
#ifndef QT_NO_TEXTHTMLPARSER
- if (source->hasFormat(QLatin1String("application/x-qrichtext")) && d->acceptRichText) {
+ if (source->hasFormat("application/x-qrichtext"_L1) && d->acceptRichText) {
// x-qrichtext is always UTF-8 (taken from Qt3 since we don't use it anymore).
- const QString richtext = QLatin1String("<meta name=\"qrichtext\" content=\"1\" />")
- + QString::fromUtf8(source->data(QLatin1String("application/x-qrichtext")));
+ const QString richtext = "<meta name=\"qrichtext\" content=\"1\" />"_L1
+ + QString::fromUtf8(source->data("application/x-qrichtext"_L1));
fragment = QTextDocumentFragment::fromHtml(richtext, d->doc);
hasData = true;
} else if (source->hasHtml() && d->acceptRichText) {
fragment = QTextDocumentFragment::fromHtml(source->html(), d->doc);
hasData = true;
- } else {
- QString text = source->text();
+ }
+#endif // QT_NO_TEXTHTMLPARSER
+ if (!hasData) {
+ const QString text = source->text();
if (!text.isNull()) {
fragment = QTextDocumentFragment::fromPlainText(text);
hasData = true;
}
}
-#else
- fragment = QTextDocumentFragment::fromPlainText(source->text());
-#endif // QT_NO_TEXTHTMLPARSER
if (hasData)
d->cursor.insertFragment(fragment);
@@ -2947,7 +2961,7 @@ void QWidgetTextControlPrivate::activateLinkUnderCursor(QString href)
emit q_func()->linkActivated(href);
}
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
void QWidgetTextControlPrivate::showToolTip(const QPoint &globalPos, const QPointF &pos, QWidget *contextWidget)
{
const QString toolTip = q_func()->cursorForPosition(pos).charFormat().toolTip();
@@ -2955,7 +2969,7 @@ void QWidgetTextControlPrivate::showToolTip(const QPoint &globalPos, const QPoin
return;
QToolTip::showText(globalPos, toolTip, contextWidget);
}
-#endif // QT_NO_TOOLTIP
+#endif // QT_CONFIG(tooltip)
bool QWidgetTextControlPrivate::isPreediting() const
{
@@ -3145,19 +3159,6 @@ bool QWidgetTextControl::find(const QString &exp, QTextDocument::FindFlags optio
return true;
}
-#ifndef QT_NO_REGEXP
-bool QWidgetTextControl::find(const QRegExp &exp, QTextDocument::FindFlags options)
-{
- Q_D(QWidgetTextControl);
- QTextCursor search = d->doc->find(exp, d->cursor, options);
- if (search.isNull())
- return false;
-
- setTextCursor(search);
- return true;
-}
-#endif
-
#if QT_CONFIG(regularexpression)
bool QWidgetTextControl::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
{
@@ -3190,6 +3191,49 @@ QString QWidgetTextControl::toMarkdown(QTextDocument::MarkdownFeatures features)
}
#endif
+void QWidgetTextControlPrivate::insertParagraphSeparator()
+{
+ // clear blockFormat properties that the user is unlikely to want duplicated:
+ // - don't insert <hr/> automatically
+ // - the next paragraph after a heading should be a normal paragraph
+ // - remove the bottom margin from the last list item before appending
+ // - the next checklist item after a checked item should be unchecked
+ auto blockFmt = cursor.blockFormat();
+ auto charFmt = cursor.charFormat();
+ blockFmt.clearProperty(QTextFormat::BlockTrailingHorizontalRulerWidth);
+ if (blockFmt.hasProperty(QTextFormat::HeadingLevel)) {
+ blockFmt.clearProperty(QTextFormat::HeadingLevel);
+ charFmt = QTextCharFormat();
+ }
+ if (cursor.currentList()) {
+ auto existingFmt = cursor.blockFormat();
+ existingFmt.clearProperty(QTextBlockFormat::BlockBottomMargin);
+ cursor.setBlockFormat(existingFmt);
+ if (blockFmt.marker() == QTextBlockFormat::MarkerType::Checked)
+ blockFmt.setMarker(QTextBlockFormat::MarkerType::Unchecked);
+ }
+
+ // After a blank line, reset block and char formats. I.e. you can end a list,
+ // block quote, etc. by hitting enter twice, and get back to normal paragraph style.
+ if (cursor.block().text().isEmpty() &&
+ !cursor.blockFormat().hasProperty(QTextFormat::BlockTrailingHorizontalRulerWidth) &&
+ !cursor.blockFormat().hasProperty(QTextFormat::BlockCodeLanguage)) {
+ blockFmt = QTextBlockFormat();
+ const bool blockFmtChanged = (cursor.blockFormat() != blockFmt);
+ charFmt = QTextCharFormat();
+ cursor.setBlockFormat(blockFmt);
+ cursor.setCharFormat(charFmt);
+ // If the user hit enter twice just to get back to default format,
+ // don't actually insert a new block. But if the user then hits enter
+ // yet again, the block format will not change, so we will insert a block.
+ // This is what many word processors do.
+ if (blockFmtChanged)
+ return;
+ }
+
+ cursor.insertBlock(blockFmt, charFmt);
+}
+
void QWidgetTextControlPrivate::append(const QString &text, Qt::TextFormat format)
{
QTextCursor tmp(doc);
@@ -3416,16 +3460,19 @@ void QUnicodeControlCharacterMenu::menuActionTriggered()
QStringList QTextEditMimeData::formats() const
{
if (!fragment.isEmpty())
- return QStringList() << QString::fromLatin1("text/plain") << QString::fromLatin1("text/html")
+ return QStringList() << u"text/plain"_s << u"text/html"_s
+#if QT_CONFIG(textmarkdownwriter)
+ << u"text/markdown"_s
+#endif
#ifndef QT_NO_TEXTODFWRITER
- << QString::fromLatin1("application/vnd.oasis.opendocument.text")
+ << u"application/vnd.oasis.opendocument.text"_s
#endif
;
else
return QMimeData::formats();
}
-QVariant QTextEditMimeData::retrieveData(const QString &mimeType, QVariant::Type type) const
+QVariant QTextEditMimeData::retrieveData(const QString &mimeType, QMetaType type) const
{
if (!fragment.isEmpty())
setup();
@@ -3436,7 +3483,10 @@ void QTextEditMimeData::setup() const
{
QTextEditMimeData *that = const_cast<QTextEditMimeData *>(this);
#ifndef QT_NO_TEXTHTMLPARSER
- that->setData(QLatin1String("text/html"), fragment.toHtml("utf-8").toUtf8());
+ that->setData("text/html"_L1, fragment.toHtml().toUtf8());
+#endif
+#if QT_CONFIG(textmarkdownwriter)
+ that->setData("text/markdown"_L1, fragment.toMarkdown().toUtf8());
#endif
#ifndef QT_NO_TEXTODFWRITER
{
@@ -3444,7 +3494,7 @@ void QTextEditMimeData::setup() const
QTextDocumentWriter writer(&buffer, "ODF");
writer.write(fragment);
buffer.close();
- that->setData(QLatin1String("application/vnd.oasis.opendocument.text"), buffer.data());
+ that->setData("application/vnd.oasis.opendocument.text"_L1, buffer.data());
}
#endif
that->setText(fragment.toPlainText());
diff --git a/src/widgets/widgets/qwidgettextcontrol_p.h b/src/widgets/widgets/qwidgettextcontrol_p.h
index 1f06aa0b97..9df4c0c810 100644
--- a/src/widgets/widgets/qwidgettextcontrol_p.h
+++ b/src/widgets/widgets/qwidgettextcontrol_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 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 QWIDGETTEXTCONTROL_P_H
#define QWIDGETTEXTCONTROL_P_H
@@ -93,9 +57,11 @@ class Q_WIDGETS_EXPORT QWidgetTextControl : public QInputControl
Q_PROPERTY(bool overwriteMode READ overwriteMode WRITE setOverwriteMode)
Q_PROPERTY(bool acceptRichText READ acceptRichText WRITE setAcceptRichText)
Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
+ Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags
+ WRITE setTextInteractionFlags)
Q_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
- Q_PROPERTY(bool ignoreUnusedNavigationEvents READ ignoreUnusedNavigationEvents WRITE setIgnoreUnusedNavigationEvents)
+ Q_PROPERTY(bool ignoreUnusedNavigationEvents READ ignoreUnusedNavigationEvents
+ WRITE setIgnoreUnusedNavigationEvents)
public:
explicit QWidgetTextControl(QObject *parent = nullptr);
explicit QWidgetTextControl(const QString &text, QObject *parent = nullptr);
@@ -105,7 +71,7 @@ public:
void setDocument(QTextDocument *document);
QTextDocument *document() const;
- void setTextCursor(const QTextCursor &cursor);
+ void setTextCursor(const QTextCursor &cursor, bool selectionClipboard = false);
QTextCursor textCursor() const;
void setTextInteractionFlags(Qt::TextInteractionFlags flags);
@@ -117,9 +83,6 @@ public:
QTextCharFormat currentCharFormat() const;
bool find(const QString &exp, QTextDocument::FindFlags options = { });
-#ifndef QT_NO_REGEXP
- bool find(const QRegExp &exp, QTextDocument::FindFlags options = { });
-#endif
#if QT_CONFIG(regularexpression)
bool find(const QRegularExpression &exp, QTextDocument::FindFlags options = { });
#endif
@@ -252,7 +215,7 @@ public:
QPalette palette() const;
void setPalette(const QPalette &pal);
- virtual void processEvent(QEvent *e, const QMatrix &matrix, QWidget *contextWidget = nullptr);
+ virtual void processEvent(QEvent *e, const QTransform &transform, QWidget *contextWidget = nullptr);
void processEvent(QEvent *e, const QPointF &coordinateOffset = QPointF(), QWidget *contextWidget = nullptr);
// control methods
@@ -277,13 +240,8 @@ protected:
private:
Q_DISABLE_COPY_MOVE(QWidgetTextControl)
- Q_PRIVATE_SLOT(d_func(), void _q_updateCurrentCharFormatAndSelection())
- Q_PRIVATE_SLOT(d_func(), void _q_emitCursorPosChanged(const QTextCursor &))
Q_PRIVATE_SLOT(d_func(), void _q_deleteSelected())
Q_PRIVATE_SLOT(d_func(), void _q_copyLink())
- Q_PRIVATE_SLOT(d_func(), void _q_updateBlock(const QTextBlock &))
- Q_PRIVATE_SLOT(d_func(), void _q_documentLayoutChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_contentsChanged(int, int, int))
};
@@ -311,13 +269,18 @@ public:
virtual QStringList formats() const override;
protected:
- virtual QVariant retrieveData(const QString &mimeType, QVariant::Type type) const override;
+ virtual QVariant retrieveData(const QString &mimeType, QMetaType type) const override;
private:
void setup() const;
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
diff --git a/src/widgets/widgets/qwidgettextcontrol_p_p.h b/src/widgets/widgets/qwidgettextcontrol_p_p.h
index c77a31bedf..955a70ecad 100644
--- a/src/widgets/widgets/qwidgettextcontrol_p_p.h
+++ b/src/widgets/widgets/qwidgettextcontrol_p_p.h
@@ -1,41 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2019 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 QWIDGETTEXTCONTROL_P_P_H
#define QWIDGETTEXTCONTROL_P_P_H
@@ -73,8 +37,9 @@ class QAbstractScrollArea;
class QWidgetTextControlPrivate : public QObjectPrivate
{
- Q_DECLARE_PUBLIC(QWidgetTextControl)
public:
+ Q_DECLARE_PUBLIC(QWidgetTextControl)
+
QWidgetTextControlPrivate();
bool cursorMoveKeyEvent(QKeyEvent *e);
@@ -171,13 +136,14 @@ public:
void activateLinkUnderCursor(QString href = QString());
-#ifndef QT_NO_TOOLTIP
+#if QT_CONFIG(tooltip)
void showToolTip(const QPoint &globalPos, const QPointF &pos, QWidget *contextWidget);
#endif
bool isPreediting() const;
void commitPreedit();
+ void insertParagraphSeparator();
void append(const QString &text, Qt::TextFormat format = Qt::AutoText);
QTextDocument *doc;
@@ -217,7 +183,7 @@ public:
int preeditCursor;
bool hideCursor; // used to hide the cursor in the preedit area
- QVector<QAbstractTextDocumentLayout::Selection> extraSelections;
+ QList<QAbstractTextDocumentLayout::Selection> extraSelections;
QPalette palette;
bool hasFocus;
diff --git a/src/widgets/widgets/widgets.pri b/src/widgets/widgets/widgets.pri
deleted file mode 100644
index 55804c5aaf..0000000000
--- a/src/widgets/widgets/widgets.pri
+++ /dev/null
@@ -1,371 +0,0 @@
-# Qt widgets module
-
-HEADERS += \
- widgets/qframe.h \
- widgets/qframe_p.h \
- widgets/qabstractscrollarea.h \
- widgets/qabstractscrollarea_p.h \
- widgets/qfocusframe.h \
- widgets/qwidgetanimator_p.h
-
-SOURCES += \
- widgets/qframe.cpp \
- widgets/qabstractscrollarea.cpp \
- widgets/qfocusframe.cpp \
- widgets/qwidgetanimator.cpp
-
-qtConfig(abstractbutton) {
- HEADERS += \
- widgets/qabstractbutton.h \
- widgets/qabstractbutton_p.h
-
- SOURCES += \
- widgets/qabstractbutton.cpp
-}
-
-qtConfig(abstractslider) {
- HEADERS += \
- widgets/qabstractslider.h \
- widgets/qabstractslider_p.h
-
- SOURCES += \
- widgets/qabstractslider.cpp
-}
-
-qtConfig(buttongroup) {
- HEADERS += \
- widgets/qbuttongroup.h \
- widgets/qbuttongroup_p.h
-
- SOURCES += widgets/qbuttongroup.cpp
-}
-
-qtConfig(calendarwidget) {
- HEADERS += widgets/qcalendarwidget.h
- SOURCES += widgets/qcalendarwidget.cpp
-}
-
-qtConfig(checkbox) {
- HEADERS += \
- widgets/qcheckbox.h
-
- SOURCES += \
- widgets/qcheckbox.cpp
-}
-
-qtConfig(combobox) {
- HEADERS += \
- widgets/qcombobox.h \
- widgets/qcombobox_p.h
-
- SOURCES += widgets/qcombobox.cpp
-}
-
-qtConfig(commandlinkbutton) {
- HEADERS += \
- widgets/qcommandlinkbutton.h
-
- SOURCES += \
- widgets/qcommandlinkbutton.cpp
-}
-
-qtConfig(datetimeedit) {
- HEADERS += \
- widgets/qdatetimeedit.h \
- widgets/qdatetimeedit_p.h
-
- SOURCES += \
- widgets/qdatetimeedit.cpp
-}
-
-qtConfig(dial) {
- HEADERS += widgets/qdial.h
- SOURCES += widgets/qdial.cpp
-}
-
-qtConfig(dockwidget) {
- HEADERS += \
- widgets/qdockwidget.h \
- widgets/qdockwidget_p.h \
- widgets/qdockarealayout_p.h
-
- SOURCES += \
- widgets/qdockwidget.cpp \
- widgets/qdockarealayout.cpp
-}
-
-qtConfig(effects) {
- HEADERS += widgets/qeffects_p.h
- SOURCES += widgets/qeffects.cpp
-}
-
-qtConfig(fontcombobox) {
- HEADERS += widgets/qfontcombobox.h
- SOURCES += widgets/qfontcombobox.cpp
-}
-
-qtConfig(groupbox) {
- HEADERS += widgets/qgroupbox.h
- SOURCES += widgets/qgroupbox.cpp
-}
-
-qtConfig(keysequenceedit) {
- HEADERS += \
- widgets/qkeysequenceedit.h \
- widgets/qkeysequenceedit_p.h
-
- SOURCES += widgets/qkeysequenceedit.cpp
-}
-
-qtConfig(label) {
- HEADERS += \
- widgets/qlabel.h \
- widgets/qlabel_p.h
-
- SOURCES += \
- widgets/qlabel.cpp
-}
-
-qtConfig(lcdnumber) {
- HEADERS += \
- widgets/qlcdnumber.h
-
- SOURCES += \
- widgets/qlcdnumber.cpp
-}
-
-qtConfig(lineedit) {
- HEADERS += \
- widgets/qlineedit.h \
- widgets/qlineedit_p.h \
- widgets/qwidgetlinecontrol_p.h
-
- SOURCES += \
- widgets/qlineedit_p.cpp \
- widgets/qlineedit.cpp \
- widgets/qwidgetlinecontrol.cpp
-}
-
-qtConfig(mainwindow) {
- HEADERS += \
- widgets/qmainwindow.h \
- widgets/qmainwindowlayout_p.h
-
- SOURCES += \
- widgets/qmainwindow.cpp \
- widgets/qmainwindowlayout.cpp
-}
-
-qtConfig(mdiarea) {
- HEADERS += \
- widgets/qmdiarea.h \
- widgets/qmdiarea_p.h \
- widgets/qmdisubwindow.h \
- widgets/qmdisubwindow_p.h
-
- SOURCES += \
- widgets/qmdiarea.cpp \
- widgets/qmdisubwindow.cpp
-}
-
-qtConfig(menu) {
- HEADERS += \
- widgets/qmenu.h \
- widgets/qmenu_p.h
-
- SOURCES += widgets/qmenu.cpp
-}
-
-qtConfig(menubar) {
- HEADERS += \
- widgets/qmenubar.h \
- widgets/qmenubar_p.h
-
- SOURCES += widgets/qmenubar.cpp
-}
-
-qtConfig(progressbar) {
- HEADERS += widgets/qprogressbar.h
- SOURCES += widgets/qprogressbar.cpp
-}
-
-qtConfig(pushbutton) {
- HEADERS += \
- widgets/qpushbutton.h \
- widgets/qpushbutton_p.h
-
- SOURCES += \
- widgets/qpushbutton.cpp
-}
-
-qtConfig(radiobutton) {
- HEADERS += \
- widgets/qradiobutton.h
-
- SOURCES += \
- widgets/qradiobutton.cpp
-}
-
-qtConfig(resizehandler) {
- HEADERS += widgets/qwidgetresizehandler_p.h
- SOURCES += widgets/qwidgetresizehandler.cpp
-}
-
-qtConfig(dialogbuttonbox) {
- HEADERS += \
- widgets/qdialogbuttonbox.h
-
- SOURCES += \
- widgets/qdialogbuttonbox.cpp
-}
-
-qtConfig(rubberband) {
- HEADERS += widgets/qrubberband.h
- SOURCES += widgets/qrubberband.cpp
-}
-
-qtConfig(scrollarea) {
- HEADERS += \
- widgets/qscrollarea.h \
- widgets/qscrollarea_p.h
-
- SOURCES += widgets/qscrollarea.cpp
-}
-
-qtConfig(scrollbar) {
- HEADERS += \
- widgets/qscrollbar.h \
- widgets/qscrollbar_p.h
-
- SOURCES += widgets/qscrollbar.cpp
-}
-
-qtConfig(sizegrip) {
- HEADERS += widgets/qsizegrip.h
- SOURCES += widgets/qsizegrip.cpp
-}
-
-qtConfig(slider) {
- HEADERS += widgets/qslider.h
- SOURCES += widgets/qslider.cpp
-}
-
-qtConfig(spinbox) {
- HEADERS += \
- widgets/qabstractspinbox.h \
- widgets/qabstractspinbox_p.h \
- widgets/qspinbox.h
-
- SOURCES += \
- widgets/qabstractspinbox.cpp \
- widgets/qspinbox.cpp
-}
-
-qtConfig(splashscreen) {
- HEADERS += \
- widgets/qsplashscreen.h
-
- SOURCES += \
- widgets/qsplashscreen.cpp
-}
-
-qtConfig(splitter) {
- HEADERS += \
- widgets/qsplitter.h \
- widgets/qsplitter_p.h
-
- SOURCES += widgets/qsplitter.cpp
-}
-
-qtConfig(stackedwidget) {
- HEADERS += widgets/qstackedwidget.h
- SOURCES += widgets/qstackedwidget.cpp
-}
-
-qtConfig(statusbar) {
- HEADERS += widgets/qstatusbar.h
- SOURCES += widgets/qstatusbar.cpp
-}
-
-qtConfig(tabbar) {
- HEADERS += \
- widgets/qtabbar.h \
- widgets/qtabbar_p.h
-
- SOURCES += widgets/qtabbar.cpp
-}
-
-qtConfig(textedit) {
- HEADERS += \
- widgets/qplaintextedit.h \
- widgets/qplaintextedit_p.h \
- widgets/qtextedit.h \
- widgets/qtextedit_p.h
-
- SOURCES += \
- widgets/qplaintextedit.cpp \
- widgets/qtextedit.cpp
-}
-
-qtConfig(textbrowser) {
- HEADERS += widgets/qtextbrowser.h
- SOURCES += widgets/qtextbrowser.cpp
-}
-
-qtConfig(tabwidget) {
- HEADERS += widgets/qtabwidget.h
- SOURCES += widgets/qtabwidget.cpp
-}
-
-qtConfig(toolbar) {
- HEADERS += \
- widgets/qtoolbar.h \
- widgets/qtoolbar_p.h \
- widgets/qtoolbararealayout_p.h \
- widgets/qtoolbarlayout_p.h \
- widgets/qtoolbarseparator_p.h
-
- SOURCES += \
- widgets/qtoolbar.cpp \
- widgets/qtoolbarlayout.cpp \
- widgets/qtoolbararealayout.cpp \
- widgets/qtoolbarseparator.cpp
-}
-
-qtConfig(toolbox) {
- HEADERS += widgets/qtoolbox.h
- SOURCES += widgets/qtoolbox.cpp
-}
-
-qtConfig(toolbutton) {
- HEADERS += \
- widgets/qtoolbutton.h \
- widgets/qtoolbarextension_p.h
-
- SOURCES += \
- widgets/qtoolbutton.cpp \
- widgets/qtoolbarextension.cpp
-}
-
-qtConfig(widgettextcontrol) {
- HEADERS += \
- widgets/qwidgettextcontrol_p.h \
- widgets/qwidgettextcontrol_p_p.h
-
- SOURCES += \
- widgets/qwidgettextcontrol.cpp
-}
-
-macx {
- HEADERS += \
- widgets/qmacnativewidget_mac.h \
- widgets/qmaccocoaviewcontainer_mac.h
-
- OBJECTIVE_SOURCES += \
- widgets/qmacnativewidget_mac.mm \
- widgets/qmaccocoaviewcontainer_mac.mm
-
- qtConfig(menu)|qtConfig(menubar) {
- SOURCES += widgets/qmenu_mac.mm
- }
-}