Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
morphmenu.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3// Qt-Security score:significant reason:default
4
5#include "morphmenu_p.h"
10#include "layoutinfo_p.h"
12
13#include <QtDesigner/qextensionmanager.h>
14#include <QtDesigner/container.h>
15#include <QtDesigner/abstractformwindow.h>
16#include <QtDesigner/abstractformeditor.h>
17#include <QtDesigner/abstractlanguage.h>
18#include <QtDesigner/abstractwidgetdatabase.h>
19#include <QtDesigner/abstractmetadatabase.h>
20#include <QtDesigner/propertysheet.h>
21
22#include <QtWidgets/qwidget.h>
23#include <QtWidgets/qmenu.h>
24#include <QtWidgets/qapplication.h>
25#include <QtWidgets/qlayout.h>
26#include <QtGui/qundostack.h>
27#include <QtWidgets/qsplitter.h>
28
29#include <QtWidgets/qframe.h>
30#include <QtWidgets/qgroupbox.h>
31#include <QtWidgets/qtabwidget.h>
32#include <QtWidgets/qstackedwidget.h>
33#include <QtWidgets/qtoolbox.h>
34#include <QtWidgets/qabstractitemview.h>
35#include <QtWidgets/qabstractbutton.h>
36#include <QtWidgets/qabstractspinbox.h>
37#include <QtWidgets/qtextedit.h>
38#include <QtWidgets/qplaintextedit.h>
39#include <QtWidgets/qlabel.h>
40
41#include <QtGui/qaction.h>
42
43#include <QtCore/qstringlist.h>
44#include <QtCore/qmap.h>
45#include <QtCore/qvariant.h>
46#include <QtCore/qdebug.h>
47
48Q_DECLARE_METATYPE(QWidgetList)
49
50QT_BEGIN_NAMESPACE
51
52using namespace Qt::StringLiterals;
53
54// Helpers for the dynamic properties that store Z/Widget order
55static const char widgetOrderPropertyC[] = "_q_widgetOrder";
56static const char zOrderPropertyC[] = "_q_zOrder";
57
58/* Morphing in Designer:
59 * It is possible to morph:
60 * - Non-Containers into similar widgets by category
61 * - Simple page containers into similar widgets or page-based containers with
62 * a single page (in theory also into a QLayoutWidget, but this might
63 * not always be appropriate).
64 * - Page-based containers into page-based containers or simple containers if
65 * they have just one page
66 * [Page based containers meaning here having a container extension]
67 * Morphing types are restricted to the basic Qt types. Morphing custom
68 * widgets is considered risky since they might have unmanaged layouts
69 * or the like.
70 *
71 * Requirements:
72 * - The widget must be on a non-laid out parent or in a layout managed
73 * by Designer
74 * - Its child widgets must be non-laid out or in a layout managed
75 * by Designer
76 * Note that child widgets can be
77 * - On the widget itself in the case of simple containers
78 * - On several pages in the case of page-based containers
79 * This is what is called 'childContainers' in the code (the widget itself
80 * or the list of container extension pages).
81 *
82 * The Morphing process encompasses:
83 * - Create a target widget and apply properties as far as applicable
84 * If the target widget has a container extension, add a sufficient
85 * number of pages.
86 * - Transferring the child widgets over to the new childContainers.
87 * In the case of a managed layout on a childContainer, this is simply
88 * set on the target childContainer, which is a new Qt 4.5
89 * functionality.
90 * - Replace the widget itself in the parent layout
91 */
92
93namespace qdesigner_internal {
94
99
100// Determine category of a widget
102{
103 // Simple containers: Exact match
104 const QMetaObject *mo = w->metaObject();
105 if (mo == &QWidget::staticMetaObject || mo == &QFrame::staticMetaObject || mo == &QGroupBox::staticMetaObject || mo == &QLayoutWidget::staticMetaObject)
107 if (mo == &QTabWidget::staticMetaObject || mo == &QStackedWidget::staticMetaObject || mo == &QToolBox::staticMetaObject)
108 return MorphPageContainer;
109 if (qobject_cast<const QAbstractItemView*>(w))
110 return MorphItemView;
111 if (qobject_cast<const QAbstractButton *>(w))
112 return MorphButton;
113 if (qobject_cast<const QAbstractSpinBox *>(w))
114 return MorphSpinBox;
115 if (qobject_cast<const QPlainTextEdit *>(w) || qobject_cast<const QTextEdit*>(w))
116 return MorphTextEdit;
117
118 return MorphCategoryNone;
119}
120
121/* Return the similar classes of a category. This is currently restricted
122 * to the known Qt classes with no precautions to parse the Widget Database
123 * (which is too risky, custom classes might have container extensions
124 * or non-managed layouts, etc.). */
125
127{
128 static QMap<MorphCategory, QStringList> candidateCache;
129 auto it = candidateCache.find(cat);
130 if (it == candidateCache.end()) {
131 it = candidateCache.insert(cat, QStringList());
132 QStringList &l = it.value();
133 switch (cat) {
135 break;
136 case MorphSimpleContainer:
137 // Do not generally allow to morph into a layout.
138 // This can be risky in case of container pages,etc.
139 l << u"QWidget"_s << u"QFrame"_s << u"QGroupBox"_s;
140 break;
141 case MorphPageContainer:
142 l << u"QTabWidget"_s << u"QStackedWidget"_s << u"QToolBox"_s;
143 break;
144 case MorphItemView:
145 l << u"QListView"_s << u"QListWidget"_s
146 << u"QTreeView"_s << u"QTreeWidget"_s
147 << u"QTableView"_s << u"QTableWidget"_s
148 << u"QColumnView"_s;
149 break;
150 case MorphButton:
151 l << u"QCheckBox"_s << u"QRadioButton"_s
152 << u"QPushButton"_s << u"QToolButton"_s
153 << u"QCommandLinkButton"_s;
154 break;
155 case MorphSpinBox:
156 l << u"QDateTimeEdit"_s << u"QDateEdit"_s
157 << u"QTimeEdit"_s
158 << u"QSpinBox"_s << u"QDoubleSpinBox"_s;
159 break;
160 case MorphTextEdit:
161 l << u"QTextEdit"_s << u"QPlainTextEdit"_s << u"QTextBrowser"_s;
162 break;
163 }
164 }
165 return it.value();
166}
167
168// Return the widgets containing the children to be transferred to. This is the
169// widget itself in most cases, except for QDesignerContainerExtension cases
170static QWidgetList childContainers(const QDesignerFormEditorInterface *core, QWidget *w)
171{
172 if (const QDesignerContainerExtension *ce = qt_extension<QDesignerContainerExtension*>(core->extensionManager(), w)) {
173 QWidgetList children;
174 if (const int count = ce->count()) {
175 for (int i = 0; i < count; i++)
176 children.push_back(ce->widget(i));
177 }
178 return children;
179 }
180 QWidgetList self;
181 self.push_back(w);
182 return self;
183}
184
185// Suggest a suitable objectname for the widget to be morphed into
186// Replace the class name parts: 'xxFrame' -> 'xxGroupBox', 'frame' -> 'groupBox'
187static QString suggestObjectName(const QString &oldClassName, const QString &newClassName, const QString &oldName)
188{
189 QString oldClassPart = oldClassName;
190 QString newClassPart = newClassName;
191 if (oldClassPart.startsWith(u'Q'))
192 oldClassPart.remove(0, 1);
193 if (newClassPart.startsWith(u'Q'))
194 newClassPart.remove(0, 1);
195
196 QString newName = oldName;
197 newName.replace(oldClassPart, newClassPart);
198 oldClassPart[0] = oldClassPart.at(0).toLower();
199 newClassPart[0] = newClassPart.at(0).toLower();
200 newName.replace(oldClassPart, newClassPart);
201 return newName;
202}
203
204// Find the label whose buddy the widget is.
205QLabel *buddyLabelOf(QDesignerFormWindowInterface *fw, QWidget *w)
206{
207 const auto labelList = fw->findChildren<QLabel*>();
208 for (QLabel *label : labelList)
209 if (label->buddy() == w)
210 return label;
211 return nullptr;
212}
213
214// Replace widgets in a widget-list type dynamic property of the parent
215// used for Z-order, etc.
217 QWidget *oldWidget, QWidget *newWidget,
218 const char *name)
219{
220 QWidgetList list = qvariant_cast<QWidgetList>(parentWidget->property(name));
221 const int index = list.indexOf(oldWidget);
222 if (index != -1) {
223 list.replace(index, newWidget);
224 parentWidget->setProperty(name, QVariant::fromValue(list));
225 }
226}
227
228/* Morph a widget into another class. Use the static addMorphMacro() to
229 * add a respective command sequence to the undo stack as it emits signals
230 * which cause other commands to be added. */
232{
234public:
235
238
239 // Convenience to add a morph command sequence macro
240 static bool addMorphMacro(QDesignerFormWindowInterface *formWindow, QWidget *w, const QString &newClass);
241
242 bool init(QWidget *widget, const QString &newClassName);
243
244 QString newWidgetName() const { return m_afterWidget->objectName(); }
245
248
249 static QStringList candidateClasses(QDesignerFormWindowInterface *fw, QWidget *w);
250
251private:
252 static bool canMorph(QDesignerFormWindowInterface *fw, QWidget *w, int *childContainerCount = nullptr, MorphCategory *cat = nullptr);
253 void morph(QWidget *before, QWidget *after);
254
255 QWidget *m_beforeWidget;
256 QWidget *m_afterWidget;
257};
258
259bool MorphWidgetCommand::addMorphMacro(QDesignerFormWindowInterface *fw, QWidget *w, const QString &newClass)
260{
261 MorphWidgetCommand *morphCmd = new MorphWidgetCommand(fw);
262 if (!morphCmd->init(w, newClass)) {
263 qWarning("*** Unable to create a MorphWidgetCommand");
264 delete morphCmd;
265 return false;
266 }
267 QLabel *buddyLabel = buddyLabelOf(fw, w);
268 // Need a macro since it adds further commands
269 QUndoStack *us = fw->commandHistory();
270 us->beginMacro(morphCmd->text());
271 // Have the signal slot/buddy editors add their commands to delete widget
272 if (FormWindowBase *fwb = qobject_cast<FormWindowBase*>(fw))
273 fwb->emitWidgetRemoved(w);
274
275 const QString newWidgetName = morphCmd->newWidgetName();
276 us->push(morphCmd);
277
278 // restore buddy using the QByteArray name.
279 if (buddyLabel) {
280 SetPropertyCommand *buddyCmd = new SetPropertyCommand(fw);
281 buddyCmd->init(buddyLabel, u"buddy"_s, QVariant(newWidgetName.toUtf8()));
282 us->push(buddyCmd);
283 }
284 us->endMacro();
285 return true;
286}
287
288MorphWidgetCommand::MorphWidgetCommand(QDesignerFormWindowInterface *formWindow) :
289 QDesignerFormWindowCommand(QString(), formWindow),
290 m_beforeWidget(nullptr),
291 m_afterWidget(nullptr)
292{
293}
294
296
297bool MorphWidgetCommand::init(QWidget *widget, const QString &newClassName)
298{
299 QDesignerFormWindowInterface *fw = formWindow();
300 QDesignerFormEditorInterface *core = fw->core();
301
302 if (!canMorph(fw, widget))
303 return false;
304
305 const QString oldClassName = WidgetFactory::classNameOf(core, widget);
306 const QString oldName = widget->objectName();
307 //: MorphWidgetCommand description
308 setText(QApplication::translate("Command", "Morph %1/'%2' into %3").arg(oldClassName, oldName, newClassName));
309
310 m_beforeWidget = widget;
311 m_afterWidget = core->widgetFactory()->createWidget(newClassName, fw);
312 if (!m_afterWidget)
313 return false;
314
315 // Set object name. Do not unique it (as to maintain it).
316 m_afterWidget->setObjectName(suggestObjectName(oldClassName, newClassName, oldName));
317
318 // If the target has a container extension, we add enough new pages to take
319 // up the children of the before widget
320 if (QDesignerContainerExtension* c = qt_extension<QDesignerContainerExtension*>(core->extensionManager(), m_afterWidget)) {
321 if (const auto pageCount = childContainers(core, m_beforeWidget).size()) {
322 const QString containerName = m_afterWidget->objectName();
323 for (qsizetype i = 0; i < pageCount; ++i) {
324 QString name = containerName;
325 name += "Page"_L1;
326 name += QString::number(i + 1);
327 QWidget *page = core->widgetFactory()->createWidget(u"QWidget"_s);
328 page->setObjectName(name);
329 fw->ensureUniqueObjectName(page);
330 c->addWidget(page);
331 core->metaDataBase()->add(page);
332 }
333 }
334 }
335
336 // Copy over applicable properties
337 const QDesignerPropertySheetExtension *beforeSheet = qt_extension<QDesignerPropertySheetExtension*>(core->extensionManager(), widget);
338 QDesignerPropertySheetExtension *afterSheet = qt_extension<QDesignerPropertySheetExtension*>(core->extensionManager(), m_afterWidget);
339 const int count = beforeSheet->count();
340 for (int i = 0; i < count; i++)
341 if (beforeSheet->isVisible(i) && beforeSheet->isChanged(i)) {
342 const QString name = beforeSheet->propertyName(i);
343 if (name != "objectName"_L1) {
344 const int afterIndex = afterSheet->indexOf(name);
345 if (afterIndex != -1 && afterSheet->isVisible(afterIndex) && afterSheet->propertyGroup(afterIndex) == beforeSheet->propertyGroup(i)) {
346 afterSheet->setProperty(i, beforeSheet->property(i));
347 afterSheet->setChanged(i, true);
348 } else {
349 // Some mismatch. The rest won't match, either
350 break;
351 }
352 }
353 }
354 return true;
355}
356
358{
359 morph(m_beforeWidget, m_afterWidget);
360}
361
363{
364 morph(m_afterWidget, m_beforeWidget);
365}
366
367void MorphWidgetCommand::morph(QWidget *before, QWidget *after)
368{
369 QDesignerFormWindowInterface *fw = formWindow();
370
371 fw->unmanageWidget(before);
372
373 const QRect oldGeom = before->geometry();
374 QWidget *parent = before->parentWidget();
375 Q_ASSERT(parent);
376 /* Morphing consists of main 2 steps
377 * 1) Move over children (laid out, non-laid out)
378 * 2) Register self with new parent (laid out, non-laid out) */
379
380 // 1) Move children. Loop over child containers
381 QWidgetList beforeChildContainers = childContainers(fw->core(), before);
382 QWidgetList afterChildContainers = childContainers(fw->core(), after);
383 Q_ASSERT(beforeChildContainers.size() == afterChildContainers.size());
384 const auto childContainerCount = beforeChildContainers.size();
385 for (qsizetype i = 0; i < childContainerCount; ++i) {
386 QWidget *beforeChildContainer = beforeChildContainers.at(i);
387 QWidget *afterChildContainer = afterChildContainers.at(i);
388 if (QLayout *childLayout = beforeChildContainer->layout()) {
389 // Laid-out: Move the layout (since 4.5)
390 afterChildContainer->setLayout(childLayout);
391 } else {
392 // Non-Laid-out: Reparent, move over
393 for (QObject *o : beforeChildContainer->children()) {
394 if (o->isWidgetType()) {
395 QWidget *w = static_cast<QWidget*>(o);
396 if (fw->isManaged(w)) {
397 const QRect geom = w->geometry();
398 w->setParent(afterChildContainer);
399 w->setGeometry(geom);
400 }
401 }
402 }
403 }
404 afterChildContainer->setProperty(widgetOrderPropertyC, beforeChildContainer->property(widgetOrderPropertyC));
405 afterChildContainer->setProperty(zOrderPropertyC, beforeChildContainer->property(zOrderPropertyC));
406 }
407
408 // 2) Replace the actual widget in the parent layout
409 after->setGeometry(oldGeom);
410 if (QLayout *containingLayout = LayoutInfo::managedLayout(fw->core(), parent)) {
411 LayoutHelper *lh = LayoutHelper::createLayoutHelper(LayoutInfo::layoutType(fw->core(), containingLayout));
412 Q_ASSERT(lh);
413 lh->replaceWidget(containingLayout, before, after);
414 delete lh;
415 } else if (QSplitter *splitter = qobject_cast<QSplitter *>(parent)) {
416 const int index = splitter->indexOf(before);
417 before->hide();
418 before->setParent(nullptr);
419 splitter->insertWidget(index, after);
420 after->setParent(parent);
421 after->setGeometry(oldGeom);
422 } else {
423 before->hide();
424 before->setParent(nullptr);
425 after->setParent(parent);
426 after->setGeometry(oldGeom);
427 }
428
429 // Check various properties: Z order, form tab order
432
433 QDesignerMetaDataBaseItemInterface *formItem = fw->core()->metaDataBase()->item(fw);
434 QWidgetList tabOrder = formItem->tabOrder();
435 const int tabIndex = tabOrder.indexOf(before);
436 if (tabIndex != -1) {
437 tabOrder.replace(tabIndex, after);
438 formItem->setTabOrder(tabOrder);
439 }
440
441 after->show();
442 fw->manageWidget(after);
443
444 fw->clearSelection(false);
445 fw->selectWidget(after);
446}
447
448/* Check if morphing is possible. It must be a valid category and the parent/
449 * child relationships must be either non-laidout or directly on
450 * Designer-managed layouts. */
451bool MorphWidgetCommand::canMorph(QDesignerFormWindowInterface *fw, QWidget *w, int *ptrToChildContainerCount, MorphCategory *ptrToCat)
452{
453 if (ptrToChildContainerCount)
454 *ptrToChildContainerCount = 0;
455 const MorphCategory cat = category(w);
456 if (ptrToCat)
457 *ptrToCat = cat;
458 if (cat == MorphCategoryNone)
459 return false;
460
461 QDesignerFormEditorInterface *core = fw->core();
462 // Don't know how to fiddle class names in Jambi..
463 if (qt_extension<QDesignerLanguageExtension *>(core->extensionManager(), core))
464 return false;
465 if (!fw->isManaged(w) || w == fw->mainContainer())
466 return false;
467 // Check the parent relationship. We accept only managed parent widgets
468 // with a single, managed layout in which widget is a member.
469 QWidget *parent = w->parentWidget();
470 if (parent == nullptr)
471 return false;
472 if (QLayout *pl = LayoutInfo::managedLayout(core, parent))
473 if (pl->indexOf(w) < 0 || !core->metaDataBase()->item(pl))
474 return false;
475 // Check Widget database
476 const QDesignerWidgetDataBaseInterface *wdb = core->widgetDataBase();
477 const int wdbindex = wdb->indexOfObject(w);
478 if (wdbindex == -1)
479 return false;
480 const bool isContainer = wdb->item(wdbindex)->isContainer();
481 if (!isContainer)
482 return true;
483 // Check children. All child containers must be non-laid-out or have managed layouts
484 const QWidgetList pages = childContainers(core, w);
485 const auto pageCount = pages.size();
486 if (ptrToChildContainerCount)
487 *ptrToChildContainerCount = pageCount;
488 if (pageCount) {
489 for (qsizetype i = 0; i < pageCount; ++i)
490 if (QLayout *cl = pages.at(i)->layout())
491 if (!core->metaDataBase()->item(cl))
492 return false;
493 }
494 return true;
495}
496
497QStringList MorphWidgetCommand::candidateClasses(QDesignerFormWindowInterface *fw, QWidget *w)
498{
499 int childContainerCount;
500 MorphCategory cat;
501 if (!canMorph(fw, w, &childContainerCount, &cat))
502 return QStringList();
503
504 QStringList rc = classesOfCategory(cat);
505 switch (cat) {
506 // Frames, etc can always be morphed into one-page page containers
507 case MorphSimpleContainer:
508 rc += classesOfCategory(MorphPageContainer);
509 break;
510 // Multipage-Containers can be morphed into simple containers if they
511 // have 1 page.
512 case MorphPageContainer:
513 if (childContainerCount == 1)
514 rc += classesOfCategory(MorphSimpleContainer);
515 break;
516 default:
517 break;
518 }
519 return rc;
520}
521
522// MorphMenu
527
533
539
541{
543}
544
546{
547 m_widget = nullptr;
548 m_formWindow = nullptr;
549
550 // Clear menu
551 if (m_subMenuAction) {
553 m_menu->clear();
554 }
555
556 // Checks: Must not be main container
557 if (w == fw->mainContainer())
558 return false;
559
561 if (c.isEmpty())
562 return false;
563
564 // Pull up
565 m_widget = w;
568
569 if (!m_subMenuAction) {
570 m_subMenuAction = new QAction(tr("Morph into"), this);
571 m_menu = new QMenu;
573 }
574
575 // Add actions
576 for (const auto &className : c) {
577 if (className != oldClassName) {
579 this, [this, className] { this->slotMorph(className); });
580 }
581 }
583 return true;
584}
585
586} // namespace qdesigner_internal
587
588QT_END_NAMESPACE
friend class QWidget
Definition qpainter.h:432
static LayoutHelper * createLayoutHelper(int type)
static QStringList candidateClasses(QDesignerFormWindowInterface *fw, QWidget *w)
bool init(QWidget *widget, const QString &newClassName)
void undo() override
Reverts a change to the document.
void redo() override
Applies a change to the document.
static bool addMorphMacro(QDesignerFormWindowInterface *formWindow, QWidget *w, const QString &newClass)
static const char widgetOrderPropertyC[]
Definition morphmenu.cpp:55
static const char zOrderPropertyC[]
Definition morphmenu.cpp:56
Auxiliary methods to store/retrieve settings.
static QStringList classesOfCategory(MorphCategory cat)
static QString suggestObjectName(const QString &oldClassName, const QString &newClassName, const QString &oldName)
QLabel * buddyLabelOf(QDesignerFormWindowInterface *fw, QWidget *w)
static QWidgetList childContainers(const QDesignerFormEditorInterface *core, QWidget *w)
static MorphCategory category(const QWidget *w)
static void replaceWidgetListDynamicProperty(QWidget *parentWidget, QWidget *oldWidget, QWidget *newWidget, const char *name)