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
paletteeditor.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
6
7#include <qdesigner_utils_p.h>
8#include <iconloader_p.h>
9#include <qtcolorbutton_p.h>
10
11#include <private/formbuilderextra_p.h>
12#include <private/ui4_p.h>
13
14#include <QtDesigner/abstractformeditor.h>
15#include <QtDesigner/abstractformwindowmanager.h>
16
17#include <QtWidgets/qfiledialog.h>
18#include <QtWidgets/qmessagebox.h>
19#include <QtWidgets/qpushbutton.h>
20#include <QtWidgets/qtoolbutton.h>
21#include <QtWidgets/qlabel.h>
22#include <QtWidgets/qmenu.h>
23#include <QtWidgets/qheaderview.h>
24#include <QtWidgets/qstyle.h>
25
26#include <QtGui/qaction.h>
27#if QT_CONFIG(clipboard)
28# include <QtGui/qclipboard.h>
29#endif
30#include <QtGui/qguiapplication.h>
31#include <QtGui/qpainter.h>
32#include <QtGui/qscreen.h>
33
34#include <QtCore/qfile.h>
35#include <QtCore/qmetaobject.h>
36#include <QtCore/qsavefile.h>
37#include <QtCore/qxmlstream.h>
38
39#include <memory>
40
41QT_BEGIN_NAMESPACE
42
43using namespace Qt::StringLiterals;
44
45namespace qdesigner_internal {
46
47enum { BrushRole = 33 };
48
49PaletteEditor::PaletteEditor(QDesignerFormEditorInterface *core, QWidget *parent) :
50 QDialog(parent),
51 m_paletteModel(new PaletteModel(this)),
52 m_core(core)
53{
54 ui.setupUi(this);
55 auto saveButton = ui.buttonBox->addButton(tr("Save..."), QDialogButtonBox::ActionRole);
56 connect(saveButton, &QPushButton::clicked, this, &PaletteEditor::save);
57 auto loadButton = ui.buttonBox->addButton(tr("Load..."), QDialogButtonBox::ActionRole);
58 connect(loadButton, &QPushButton::clicked, this, &PaletteEditor::load);
59
60 connect(ui.buildButton, &QtColorButton::colorChanged,
61 this, &PaletteEditor::buildButtonColorChanged);
62 connect(ui.activeRadio, &QAbstractButton::clicked,
63 this, &PaletteEditor::activeRadioClicked);
64 connect(ui.inactiveRadio, &QAbstractButton::clicked,
65 this, &PaletteEditor::inactiveRadioClicked);
66 connect(ui.disabledRadio, &QAbstractButton::clicked,
67 this, &PaletteEditor::disabledRadioClicked);
68 connect(ui.computeRadio, &QAbstractButton::clicked,
69 this, &PaletteEditor::computeRadioClicked);
70 connect(ui.detailsRadio, &QAbstractButton::clicked,
71 this, &PaletteEditor::detailsRadioClicked);
72
73 ui.paletteView->setModel(m_paletteModel);
74 ui.previewGroupBox->setTitle(tr("Preview (%1)").arg(style()->objectName()));
75 updatePreviewPalette();
76 updateStyledButton();
77 ui.paletteView->setModel(m_paletteModel);
78 ColorDelegate *delegate = new ColorDelegate(core, this);
79 ui.paletteView->setItemDelegate(delegate);
80 ui.paletteView->setEditTriggers(QAbstractItemView::AllEditTriggers);
81 connect(m_paletteModel, &PaletteModel::paletteChanged,
82 this, &PaletteEditor::paletteChanged);
83 ui.paletteView->setSelectionBehavior(QAbstractItemView::SelectRows);
84 ui.paletteView->setDragEnabled(true);
85 ui.paletteView->setDropIndicatorShown(true);
86 ui.paletteView->setRootIsDecorated(false);
87 ui.paletteView->setColumnHidden(2, true);
88 ui.paletteView->setColumnHidden(3, true);
89 ui.paletteView->setContextMenuPolicy(Qt::CustomContextMenu);
90 connect(ui.paletteView, &QWidget::customContextMenuRequested,
91 this, &PaletteEditor::viewContextMenuRequested);
92
93 const auto itemRect = ui.paletteView->visualRect(m_paletteModel->index(0, 0));
94 const int minHeight = qMin(itemRect.height() * QPalette::NColorRoles,
95 (screen()->geometry().height() * 2) / 3);
96 ui.paletteView->setMinimumSize({itemRect.width() * 4, minHeight});
97}
98
99PaletteEditor::~PaletteEditor() = default;
100
102{
103 return m_editPalette;
104}
105
106void PaletteEditor::setPalette(const QPalette &palette)
107{
108 m_editPalette = palette;
109 for (int r = 0; r < static_cast<int>(QPalette::NColorRoles); ++r) {
110 for (int g = 0; g < static_cast<int>(QPalette::NColorGroups); ++g) {
111 const auto role = static_cast<QPalette::ColorRole>(r);
112 const auto group = static_cast<QPalette::ColorGroup>(g);
113 if (!palette.isBrushSet(group, role))
114 m_editPalette.setBrush(group, role, m_parentPalette.brush(group, role));
115 }
116 }
117 m_editPalette.setResolveMask(palette.resolveMask());
118 updatePreviewPalette();
119 updateStyledButton();
120 m_paletteUpdated = true;
121 if (!m_modelUpdated)
122 m_paletteModel->setPalette(m_editPalette, m_parentPalette);
123 m_paletteUpdated = false;
124}
125
126void PaletteEditor::setPalette(const QPalette &palette, const QPalette &parentPalette)
127{
128 m_parentPalette = parentPalette;
129 setPalette(palette);
130}
131
132void PaletteEditor::buildButtonColorChanged()
133{
134 buildPalette();
135}
136
137void PaletteEditor::activeRadioClicked()
138{
139 m_currentColorGroup = QPalette::Active;
140 updatePreviewPalette();
141}
142
143void PaletteEditor::inactiveRadioClicked()
144{
145 m_currentColorGroup = QPalette::Inactive;
146 updatePreviewPalette();
147}
148
149void PaletteEditor::disabledRadioClicked()
150{
151 m_currentColorGroup = QPalette::Disabled;
152 updatePreviewPalette();
153}
154
155void PaletteEditor::computeRadioClicked()
156{
157 if (m_compute)
158 return;
159 ui.paletteView->setColumnHidden(2, true);
160 ui.paletteView->setColumnHidden(3, true);
161 m_compute = true;
162 m_paletteModel->setCompute(true);
163}
164
165void PaletteEditor::detailsRadioClicked()
166{
167 if (!m_compute)
168 return;
169 const int w = ui.paletteView->columnWidth(1);
170 ui.paletteView->setColumnHidden(2, false);
171 ui.paletteView->setColumnHidden(3, false);
172 QHeaderView *header = ui.paletteView->header();
173 header->resizeSection(1, w / 3);
174 header->resizeSection(2, w / 3);
175 header->resizeSection(3, w / 3);
176 m_compute = false;
177 m_paletteModel->setCompute(false);
178}
179
180void PaletteEditor::paletteChanged(const QPalette &palette)
181{
182 m_modelUpdated = true;
183 if (!m_paletteUpdated)
184 setPalette(palette);
185 m_modelUpdated = false;
186}
187
188void PaletteEditor::buildPalette()
189{
190 const QColor btn = ui.buildButton->color();
191 const QPalette temp = QPalette(btn);
192 setPalette(temp);
193}
194
195void PaletteEditor::updatePreviewPalette()
196{
197 const QPalette::ColorGroup g = currentColorGroup();
198 // build the preview palette
199 const QPalette currentPalette = palette();
200 QPalette previewPalette;
201 for (int i = QPalette::WindowText; i < QPalette::NColorRoles; i++) {
202 const QPalette::ColorRole r = static_cast<QPalette::ColorRole>(i);
203 const QBrush &br = currentPalette.brush(g, r);
204 previewPalette.setBrush(QPalette::Active, r, br);
205 previewPalette.setBrush(QPalette::Inactive, r, br);
206 previewPalette.setBrush(QPalette::Disabled, r, br);
207 }
208 ui.previewFrame->setPreviewPalette(previewPalette);
209
210 const bool enabled = g != QPalette::Disabled;
211 ui.previewFrame->setEnabled(enabled);
212 ui.previewFrame->setSubWindowActive(g != QPalette::Inactive);
213}
214
215void PaletteEditor::updateStyledButton()
216{
217 ui.buildButton->setColor(palette().color(QPalette::Active, QPalette::Button));
218}
219
220QPalette PaletteEditor::getPalette(QDesignerFormEditorInterface *core, QWidget* parent, const QPalette &init,
221 const QPalette &parentPal, int *ok)
222{
223 PaletteEditor dlg(core, parent);
224 QPalette parentPalette(parentPal);
225 for (int r = 0; r < static_cast<int>(QPalette::NColorRoles); ++r) {
226 for (int g = 0; g < static_cast<int>(QPalette::NColorGroups); ++g) {
227 const auto role = static_cast<QPalette::ColorRole>(r);
228 const auto group = static_cast<QPalette::ColorGroup>(g);
229 if (!init.isBrushSet(group, role))
230 parentPalette.setBrush(group, role, init.brush(group, role));
231 }
232 }
233 dlg.setPalette(init, parentPalette);
234
235 const int result = dlg.exec();
236 if (ok) *ok = result;
237
238 return result == QDialog::Accepted ? dlg.palette() : init;
239}
240
241void PaletteEditor::viewContextMenuRequested(QPoint pos)
242{
243 const auto index = ui.paletteView->indexAt(pos);
244 if (!index.isValid())
245 return;
246 auto brush = m_paletteModel->brushAt(index);
247 const auto color = brush.color();
248 if (!m_contextMenu) {
249 m_contextMenu = new QMenu(this);
250 m_lighterAction = m_contextMenu->addAction(tr("Lighter"));
251 m_darkerAction = m_contextMenu->addAction(tr("Darker"));
252 m_copyColorAction = m_contextMenu->addAction(QString());
253 }
254 const auto rgb = color.rgb() & 0xffffffu;
255 const bool isBlack = rgb == 0u;
256 m_lighterAction->setEnabled(rgb != 0xffffffu);
257 m_darkerAction->setDisabled(isBlack);
258 m_copyColorAction->setText(tr("Copy color %1").arg(color.name()));
259 auto action = m_contextMenu->exec(ui.paletteView->viewport()->mapToGlobal(pos));
260 if (!action)
261 return;
262 if (action == m_copyColorAction) {
263#if QT_CONFIG(clipboard)
264 QGuiApplication::clipboard()->setText(color.name());
265#endif
266 return;
267 }
268 // Fall through to darker/lighter. Note: black cannot be made lighter due
269 // to QTBUG-9343.
270 enum : int { factor = 120 };
271 const QColor newColor = action == m_darkerAction
272 ? color.darker(factor)
273 : (isBlack ? QColor(0x404040u) : color.lighter(factor));
274 brush.setColor(newColor);
275 m_paletteModel->setData(index, QVariant(brush), BrushRole);
276}
277
278static inline QString paletteFilter()
279{
280 return PaletteEditor::tr("QPalette UI file (*.xml)");
281}
282
283static bool savePalette(const QString &fileName, const QPalette &pal, QString *errorMessage)
284{
285 QSaveFile file;
286 file.setFileName(fileName);
287 if (!file.open(QIODevice::WriteOnly)) {
288 *errorMessage = PaletteEditor::tr("Cannot open %1 for writing: %2")
289 .arg(QDir::toNativeSeparators(fileName), file.errorString());
290 return false;
291 }
292 {
293 std::unique_ptr<DomPalette> domPalette(QFormBuilderExtra::savePalette(pal));
294 QXmlStreamWriter writer(&file);
295 writer.setAutoFormatting(true);
296 writer.setAutoFormattingIndent(1);
297 writer.writeStartDocument();
298 domPalette->write(writer);
299 writer.writeEndDocument();
300 }
301 const bool result = file.commit();
302 if (!result) {
303 *errorMessage = PaletteEditor::tr("Cannot write %1: %2")
304 .arg(QDir::toNativeSeparators(fileName), file.errorString());
305 }
306 return result;
307}
308
309static QString msgCannotReadPalette(const QString &fileName, const QXmlStreamReader &reader,
310 const QString &why)
311{
312 return PaletteEditor::tr("Cannot read palette from %1:%2:%3")
313 .arg(QDir::toNativeSeparators(fileName)).arg(reader.lineNumber()).arg(why);
314}
315
316static inline QString msgCannotReadPalette(const QString &fileName, const QXmlStreamReader &reader)
317{
318 return msgCannotReadPalette(fileName, reader, reader.errorString());
319}
320
321static bool loadPalette(const QString &fileName, QPalette *pal, QString *errorMessage)
322{
323 QFile file(fileName);
324 if (!file.open(QIODevice::ReadOnly)) {
325 *errorMessage = PaletteEditor::tr("Cannot open %1 for reading: %2")
326 .arg(QDir::toNativeSeparators(fileName), file.errorString());
327 return false;
328 }
329 QXmlStreamReader reader(&file);
330 if (!reader.readNextStartElement()) {
331 *errorMessage = msgCannotReadPalette(fileName, reader);
332 return false;
333 }
334 if (reader.name() != "palette"_L1) {
335 const auto why = PaletteEditor::tr("Invalid element \"%1\", expected \"palette\".")
336 .arg(reader.name().toString());
337 *errorMessage = msgCannotReadPalette(fileName, reader, why);
338 return false;
339 }
340 auto domPalette = std::make_unique<DomPalette>();
341 domPalette->read(reader);
342 if (reader.hasError()) {
343 *errorMessage = msgCannotReadPalette(fileName, reader);
344 return false;
345 }
346 *pal = QFormBuilderExtra::loadPalette(domPalette.get());
347 return true;
348}
349
350void PaletteEditor::save()
351{
352 QFileDialog dialog(this, tr("Save Palette"), QString(), paletteFilter());
353 dialog.setAcceptMode(QFileDialog::AcceptSave);
354 dialog.setDefaultSuffix(u"xml"_s);
355 while (dialog.exec() == QDialog::Accepted) {
356 QString errorMessage;
357 if (savePalette(dialog.selectedFiles().constFirst(), palette(), &errorMessage))
358 break;
359 QMessageBox::warning(this, tr("Error Writing Palette"), errorMessage);
360 }
361}
362
363void PaletteEditor::load()
364{
365 QFileDialog dialog(this, tr("Load Palette"), QString(), paletteFilter());
366 dialog.setAcceptMode(QFileDialog::AcceptOpen);
367 while (dialog.exec() == QDialog::Accepted) {
368 QPalette pal;
369 QString errorMessage;
370 if (loadPalette(dialog.selectedFiles().constFirst(), &pal, &errorMessage)) {
371 setPalette(pal);
372 break;
373 }
374 QMessageBox::warning(this, tr("Error Reading Palette"), errorMessage);
375 }
376}
377
378//////////////////////
379// Column 0: Role name and reset button. Uses a boolean value indicating
380// whether the role is modified for the edit role.
381// Column 1: Color group Active
382// Column 2: Color group Inactive (visibility depending on m_compute/detail radio group)
383// Column 3: Color group Disabled
384
385PaletteModel::PaletteModel(QObject *parent) :
386 QAbstractTableModel(parent)
387{
388 const QMetaObject *meta = metaObject();
389 const int index = meta->indexOfProperty("colorRole");
390 const QMetaProperty p = meta->property(index);
391 const QMetaEnum e = p.enumerator();
392 m_roleEntries.reserve(QPalette::NColorRoles);
393 for (int r = QPalette::WindowText; r < QPalette::NColorRoles; r++) {
394 const auto role = static_cast<QPalette::ColorRole>(r);
395 if (role != QPalette::NoRole)
396 m_roleEntries.append({QLatin1StringView(e.key(r)), role});
397 }
398}
399
400int PaletteModel::rowCount(const QModelIndex &) const
401{
402 return m_roleEntries.size();
403}
404
405int PaletteModel::columnCount(const QModelIndex &) const
406{
407 return 4;
408}
409
410QBrush PaletteModel::brushAt(const QModelIndex &index) const
411{
412 return m_palette.brush(columnToGroup(index.column()), roleAt(index.row()));
413}
414
415// Palette resolve mask with all group bits for a row/role
416quint64 PaletteModel::rowMask(const QModelIndex &index) const
417{
418 return paletteResolveMask(roleAt(index.row()));
419}
420
421QVariant PaletteModel::data(const QModelIndex &index, int role) const
422{
423 if (!index.isValid())
424 return QVariant();
425 if (index.row() < 0 || index.row() >= m_roleEntries.size())
426 return QVariant();
427 if (index.column() < 0 || index.column() >= 4)
428 return QVariant();
429
430 if (index.column() == 0) { // Role name/bold print if changed
431 if (role == Qt::DisplayRole)
432 return m_roleEntries.at(index.row()).name;
433 if (role == Qt::EditRole)
434 return (rowMask(index) & m_palette.resolveMask()) != 0;
435 return QVariant();
436 }
437 if (role == Qt::ToolTipRole)
438 return brushAt(index).color().name();
439 if (role == BrushRole)
440 return brushAt(index);
441 return QVariant();
442}
443
444bool PaletteModel::setData(const QModelIndex &index, const QVariant &value, int role)
445{
446 if (!index.isValid())
447 return false;
448
449 const int row = index.row();
450 const auto colorRole = roleAt(row);
451
452 if (index.column() != 0 && role == BrushRole) {
453 const QBrush br = qvariant_cast<QBrush>(value);
454 const QPalette::ColorGroup g = columnToGroup(index.column());
455 m_palette.setBrush(g, colorRole, br);
456
457 QModelIndex idxBegin = PaletteModel::index(row, 0);
458 QModelIndex idxEnd = PaletteModel::index(row, 3);
459 if (m_compute) {
460 m_palette.setBrush(QPalette::Inactive, colorRole, br);
461 switch (colorRole) {
462 case QPalette::WindowText:
463 case QPalette::Text:
464 case QPalette::ButtonText:
465 case QPalette::Base:
466 break;
467 case QPalette::Dark:
468 m_palette.setBrush(QPalette::Disabled, QPalette::WindowText, br);
469 m_palette.setBrush(QPalette::Disabled, QPalette::Dark, br);
470 m_palette.setBrush(QPalette::Disabled, QPalette::Text, br);
471 m_palette.setBrush(QPalette::Disabled, QPalette::ButtonText, br);
472 idxBegin = PaletteModel::index(0, 0);
473 idxEnd = PaletteModel::index(m_roleEntries.size() - 1, 3);
474 break;
475 case QPalette::Window:
476 m_palette.setBrush(QPalette::Disabled, QPalette::Base, br);
477 m_palette.setBrush(QPalette::Disabled, QPalette::Window, br);
478 idxBegin = PaletteModel::index(rowOf(QPalette::Base), 0);
479 break;
480 case QPalette::Highlight:
481 //m_palette.setBrush(QPalette::Disabled, QPalette::Highlight, c.dark(120));
482 break;
483 default:
484 m_palette.setBrush(QPalette::Disabled, colorRole, br);
485 break;
486 }
487 }
488 emit paletteChanged(m_palette);
489 emit dataChanged(idxBegin, idxEnd);
490 return true;
491 }
492 if (index.column() == 0 && role == Qt::EditRole) {
493 auto mask = m_palette.resolveMask();
494 const bool isMask = qvariant_cast<bool>(value);
495 const auto bitMask = rowMask(index);
496 if (isMask) {
497 mask |= bitMask;
498 } else {
499 m_palette.setBrush(QPalette::Active, colorRole,
500 m_parentPalette.brush(QPalette::Active, colorRole));
501 m_palette.setBrush(QPalette::Inactive, colorRole,
502 m_parentPalette.brush(QPalette::Inactive, colorRole));
503 m_palette.setBrush(QPalette::Disabled, colorRole,
504 m_parentPalette.brush(QPalette::Disabled, colorRole));
505
506 mask &= ~bitMask;
507 }
508 m_palette.setResolveMask(mask);
509 emit paletteChanged(m_palette);
510 const QModelIndex idxEnd = PaletteModel::index(row, 3);
511 emit dataChanged(index, idxEnd);
512 return true;
513 }
514 return false;
515}
516
517Qt::ItemFlags PaletteModel::flags(const QModelIndex &index) const
518{
519 if (!index.isValid())
520 return Qt::ItemIsEnabled;
521 return Qt::ItemIsEditable | Qt::ItemIsEnabled;
522}
523
524QVariant PaletteModel::headerData(int section, Qt::Orientation orientation,
525 int role) const
526{
527 if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
528 if (section == 0)
529 return tr("Color Role");
530 if (section == groupToColumn(QPalette::Active))
531 return tr("Active");
532 if (section == groupToColumn(QPalette::Inactive))
533 return tr("Inactive");
534 if (section == groupToColumn(QPalette::Disabled))
535 return tr("Disabled");
536 }
537 return QVariant();
538}
539
541{
542 return m_palette;
543}
544
545void PaletteModel::setPalette(const QPalette &palette, const QPalette &parentPalette)
546{
547 m_parentPalette = parentPalette;
548 m_palette = palette;
549 const QModelIndex idxBegin = index(0, 0);
550 const QModelIndex idxEnd = index(m_roleEntries.size() - 1, 3);
551 emit dataChanged(idxBegin, idxEnd);
552}
553
554QPalette::ColorGroup PaletteModel::columnToGroup(int index) const
555{
556 if (index == 1)
557 return QPalette::Active;
558 if (index == 2)
559 return QPalette::Inactive;
560 return QPalette::Disabled;
561}
562
563int PaletteModel::groupToColumn(QPalette::ColorGroup group) const
564{
565 if (group == QPalette::Active)
566 return 1;
567 if (group == QPalette::Inactive)
568 return 2;
569 return 3;
570}
571
572int PaletteModel::rowOf(QPalette::ColorRole role) const
573{
574 for (qsizetype row = 0, size = m_roleEntries.size(); row < size; ++row) {
575 if (m_roleEntries.at(row).role == role)
576 return row;
577 }
578 return -1;
579}
580
581//////////////////////////
582
583BrushEditor::BrushEditor(QDesignerFormEditorInterface *core, QWidget *parent) :
584 QWidget(parent),
585 m_button(new QtColorButton(this)),
586 m_core(core)
587{
588 QLayout *layout = new QHBoxLayout(this);
589 layout->setContentsMargins(QMargins());
590 layout->addWidget(m_button);
591 connect(m_button, &QtColorButton::colorChanged, this, &BrushEditor::brushChanged);
592 setFocusProxy(m_button);
593}
594
595void BrushEditor::setBrush(const QBrush &brush)
596{
597 m_button->setColor(brush.color());
598 m_changed = false;
599}
600
602{
603 return QBrush(m_button->color());
604}
605
606void BrushEditor::brushChanged()
607{
608 m_changed = true;
609 emit changed(this);
610}
611
612bool BrushEditor::changed() const
613{
614 return m_changed;
615}
616
617//////////////////////////
618
619RoleEditor::RoleEditor(QWidget *parent) :
620 QWidget(parent),
621 m_label(new QLabel(this))
622{
623 QHBoxLayout *layout = new QHBoxLayout(this);
624 layout->setContentsMargins(QMargins());
625 layout->setSpacing(0);
626
627 layout->addWidget(m_label);
628 m_label->setAutoFillBackground(true);
629 m_label->setIndent(3); // ### hardcode it should have the same value of textMargin in QItemDelegate
630 setFocusProxy(m_label);
631
632 QToolButton *button = new QToolButton(this);
633 button->setToolButtonStyle(Qt::ToolButtonIconOnly);
634 button->setIcon(createIconSet("resetproperty.png"_L1));
635 button->setIconSize(QSize(8,8));
636 button->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::MinimumExpanding));
637 layout->addWidget(button);
638 connect(button, &QAbstractButton::clicked, this, &RoleEditor::emitResetProperty);
639}
640
641void RoleEditor::setLabel(const QString &label)
642{
643 m_label->setText(label);
644}
645
646void RoleEditor::setEdited(bool on)
647{
648 QFont font;
649 if (on)
650 font.setBold(on);
651 m_label->setFont(font);
652 m_edited = on;
653}
654
655bool RoleEditor::edited() const
656{
657 return m_edited;
658}
659
660void RoleEditor::emitResetProperty()
661{
662 setEdited(false);
663 emit changed(this);
664}
665
666//////////////////////////
667ColorDelegate::ColorDelegate(QDesignerFormEditorInterface *core, QObject *parent) :
668 QStyledItemDelegate(parent),
669 m_core(core)
670{
671}
672
673QWidget *ColorDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &,
674 const QModelIndex &index) const
675{
676 QWidget *ed = nullptr;
677 if (index.column() == 0) {
678 RoleEditor *editor = new RoleEditor(parent);
679 connect(editor, &RoleEditor::changed, this, &ColorDelegate::commitData);
680 //editor->setFocusPolicy(Qt::NoFocus);
681 //editor->installEventFilter(const_cast<ColorDelegate *>(this));
682 ed = editor;
683 } else {
684 BrushEditor *editor = new BrushEditor(m_core, parent);
685 connect(editor, QOverload<QWidget *>::of(&BrushEditor::changed),
686 this, &ColorDelegate::commitData);
687 editor->setFocusPolicy(Qt::NoFocus);
688 editor->installEventFilter(const_cast<ColorDelegate *>(this));
689 ed = editor;
690 }
691 return ed;
692}
693
694void ColorDelegate::setEditorData(QWidget *ed, const QModelIndex &index) const
695{
696 if (index.column() == 0) {
697 const bool mask = qvariant_cast<bool>(index.model()->data(index, Qt::EditRole));
698 RoleEditor *editor = static_cast<RoleEditor *>(ed);
699 editor->setEdited(mask);
700 const QString colorName = qvariant_cast<QString>(index.model()->data(index, Qt::DisplayRole));
701 editor->setLabel(colorName);
702 } else {
703 const QBrush br = qvariant_cast<QBrush>(index.model()->data(index, BrushRole));
704 BrushEditor *editor = static_cast<BrushEditor *>(ed);
705 editor->setBrush(br);
706 }
707}
708
709void ColorDelegate::setModelData(QWidget *ed, QAbstractItemModel *model,
710 const QModelIndex &index) const
711{
712 if (index.column() == 0) {
713 RoleEditor *editor = static_cast<RoleEditor *>(ed);
714 const bool mask = editor->edited();
715 model->setData(index, mask, Qt::EditRole);
716 } else {
717 BrushEditor *editor = static_cast<BrushEditor *>(ed);
718 if (editor->changed()) {
719 QBrush br = editor->brush();
720 model->setData(index, br, BrushRole);
721 }
722 }
723}
724
725void ColorDelegate::updateEditorGeometry(QWidget *ed,
726 const QStyleOptionViewItem &option, const QModelIndex &index) const
727{
728 QStyledItemDelegate::updateEditorGeometry(ed, option, index);
729 ed->setGeometry(ed->geometry().adjusted(0, 0, -1, -1));
730}
731
732void ColorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt,
733 const QModelIndex &index) const
734{
735 QStyleOptionViewItem option = opt;
736 const bool mask = qvariant_cast<bool>(index.model()->data(index, Qt::EditRole));
737 if (index.column() == 0 && mask) {
738 option.font.setBold(true);
739 }
740 QBrush br = qvariant_cast<QBrush>(index.model()->data(index, BrushRole));
741 if (br.style() == Qt::LinearGradientPattern ||
742 br.style() == Qt::RadialGradientPattern ||
743 br.style() == Qt::ConicalGradientPattern) {
744 painter->save();
745 painter->translate(option.rect.x(), option.rect.y());
746 painter->scale(option.rect.width(), option.rect.height());
747 QGradient gr = *(br.gradient());
748 gr.setCoordinateMode(QGradient::LogicalMode);
749 br = QBrush(gr);
750 painter->fillRect(0, 0, 1, 1, br);
751 painter->restore();
752 } else {
753 painter->save();
754 painter->setBrushOrigin(option.rect.x(), option.rect.y());
755 painter->fillRect(option.rect, br);
756 painter->restore();
757 }
758 QStyledItemDelegate::paint(painter, option, index);
759
760
761 const QColor color = static_cast<QRgb>(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &option));
762 const QPen oldPen = painter->pen();
763 painter->setPen(QPen(color));
764
765 painter->drawLine(option.rect.right(), option.rect.y(),
766 option.rect.right(), option.rect.bottom());
767 painter->drawLine(option.rect.x(), option.rect.bottom(),
768 option.rect.right(), option.rect.bottom());
769 painter->setPen(oldPen);
770}
771
772QSize ColorDelegate::sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const
773{
774 return QStyledItemDelegate::sizeHint(opt, index) + QSize(4, 4);
775}
776}
777
778QT_END_NAMESPACE
void setBrush(const QBrush &brush)
QSize sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const override
This pure abstract function must be reimplemented if you want to provide custom rendering.
void paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const override
This pure abstract function must be reimplemented if you want to provide custom rendering.
void setPalette(const QPalette &palette)
void setPalette(const QPalette &palette, const QPalette &parentPalette)
QBrush brushAt(const QModelIndex &index) const
QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const override
Returns the data for the given role and section in the header with the specified orientation.
int columnCount(const QModelIndex &parent=QModelIndex()) const override
Returns the number of columns for the children of the given parent.
int rowCount(const QModelIndex &parent=QModelIndex()) const override
Returns the number of rows under the given parent.
quint64 rowMask(const QModelIndex &index) const
QVariant data(const QModelIndex &index, int role) const override
Returns the data stored under the given role for the item referred to by the index.
bool setData(const QModelIndex &index, const QVariant &value, int role) override
Sets the role data for the item at index to value.
Qt::ItemFlags flags(const QModelIndex &index) const override
Returns the item flags for the given index.
void setPalette(const QPalette &palette, const QPalette &parentPalette)
Auxiliary methods to store/retrieve settings.
static QString paletteFilter()
static bool savePalette(const QString &fileName, const QPalette &pal, QString *errorMessage)
static QString msgCannotReadPalette(const QString &fileName, const QXmlStreamReader &reader)
static QString msgCannotReadPalette(const QString &fileName, const QXmlStreamReader &reader, const QString &why)
static bool loadPalette(const QString &fileName, QPalette *pal, QString *errorMessage)