-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathQtPropertyEditor.cpp
1175 lines (1098 loc) · 53 KB
/
QtPropertyEditor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* --------------------------------------------------------------------------------
* Author: Marcel Paz Goldschen-Ohm
* Email: [email protected]
* -------------------------------------------------------------------------------- */
#include "QtPropertyEditor.h"
#include <QAbstractButton>
#include <QApplication>
#include <QComboBox>
#include <QEvent>
#include <QHeaderView>
#include <QLineEdit>
#include <QMenu>
#include <QMessageBox>
#include <QMetaObject>
#include <QMetaType>
#include <QMouseEvent>
#include <QPushButton>
#include <QRegularExpression>
#include <QScrollBar>
#include <QStylePainter>
#include <QToolButton>
#include <QSpacerItem>
namespace QtPropertyEditor
{
static MetaTypeRegistration<QtPushButtonActionWrapper> thisInstantiationRegistersQtPushButtonActionWrapperWithQt;
QList<QByteArray> getPropertyNames(QObject *object)
{
QList<QByteArray> propertyNames = getMetaPropertyNames(*object->metaObject());
foreach(const QByteArray &dynamicPropertyName, object->dynamicPropertyNames()) {
propertyNames << dynamicPropertyName;
}
return propertyNames;
}
QList<QByteArray> getMetaPropertyNames(const QMetaObject &metaObject)
{
QList<QByteArray> propertyNames;
int numProperties = metaObject.propertyCount();
for(int i = 0; i < numProperties; ++i) {
const QMetaProperty metaProperty = metaObject.property(i);
propertyNames << QByteArray(metaProperty.name());
}
return propertyNames;
}
QList<QByteArray> getNoninheritedPropertyNames(QObject *object)
{
QList<QByteArray> propertyNames = getPropertyNames(object);
QList<QByteArray> superPropertyNames = getMetaPropertyNames(*object->metaObject()->superClass());
foreach(const QByteArray &superPropertyName, superPropertyNames) {
propertyNames.removeOne(superPropertyName);
}
return propertyNames;
}
QObject* descendant(QObject *object, const QByteArray &pathToDescendantObject)
{
// Get descendent object specified by "path.to.descendant", where "path", "to" and "descendant"
// are the object names of objects with the parent->child relationship object->path->to->descendant.
if(!object || pathToDescendantObject.isEmpty())
return 0;
if(pathToDescendantObject.contains('.')) {
QList<QByteArray> descendantObjectNames = pathToDescendantObject.split('.');
foreach(QByteArray name, descendantObjectNames) {
object = object->findChild<QObject*>(QString(name));
if(!object)
return 0; // Invalid path to descendant object.
}
return object;
}
return object->findChild<QObject*>(QString(pathToDescendantObject));
}
QSize getTableSize(const QTableView *table)
{
int w = table->verticalHeader()->width() + 4; // +4 seems to be needed
int h = table->horizontalHeader()->height() + 4;
for(int i = 0; i < table->model()->columnCount(); i++)
w += table->columnWidth(i);
for(int i = 0; i < table->model()->rowCount(); i++)
h += table->rowHeight(i);
return QSize(w, h);
}
void QtAbstractPropertyModel::setProperties(const QString &str)
{
// str = "name0: header0, name1, name2, name3: header3 ..."
propertyNames.clear();
propertyHeaders.clear();
// QStringList fields = str.split(",", QString::SkipEmptyParts);
QStringList fields = str.split(",", Qt::SkipEmptyParts);
foreach(const QString &field, fields) {
if(!field.trimmed().isEmpty())
addProperty(field);
}
}
void QtAbstractPropertyModel::addProperty(const QString &str)
{
// "name" OR "name: header"
if(str.contains(":")) {
int pos = str.indexOf(":");
QByteArray propertyName = str.left(pos).trimmed().toUtf8();
QString propertyHeader = str.mid(pos+1).trimmed();
propertyNames.push_back(propertyName);
propertyHeaders[propertyName] = propertyHeader;
} else {
QByteArray propertyName = str.trimmed().toUtf8();
propertyNames.push_back(propertyName);
}
}
const QMetaProperty QtAbstractPropertyModel::metaPropertyAtIndex(const QModelIndex &index) const
{
QObject *object = objectAtIndex(index);
if(!object)
return QMetaProperty();
QByteArray propertyName = propertyNameAtIndex(index);
if(propertyName.isEmpty())
return QMetaProperty();
// Return metaObject with same name.
const QMetaObject *metaObject = object->metaObject();
int numProperties = metaObject->propertyCount();
for(int i = 0; i < numProperties; ++i) {
const QMetaProperty metaProperty = metaObject->property(i);
if(QByteArray(metaProperty.name()) == propertyName)
return metaProperty;
}
return QMetaProperty();
}
QVariant QtAbstractPropertyModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
if(role == Qt::DisplayRole || role == Qt::EditRole) {
QObject *object = objectAtIndex(index);
if(!object)
return QVariant();
QByteArray propertyName = propertyNameAtIndex(index);
if(propertyName.isEmpty())
return QVariant();
return object->property(propertyName.constData());
}
return QVariant();
}
bool QtAbstractPropertyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
if(role == Qt::EditRole) {
QObject *object = objectAtIndex(index);
if(!object)
return false;
QByteArray propertyName = propertyNameAtIndex(index);
if(propertyName.isEmpty())
return false;
bool result = object->setProperty(propertyName.constData(), value);
// Result will be FALSE for dynamic properties, which causes the tree view to lag.
// So make sure we still return TRUE in this case.
if(!result && object->dynamicPropertyNames().contains(propertyName))
return true;
return result;
}
return false;
}
Qt::ItemFlags QtAbstractPropertyModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if(!index.isValid())
return flags;
QObject *object = objectAtIndex(index);
if(!object)
return flags;
flags |= Qt::ItemIsEnabled;
flags |= Qt::ItemIsSelectable;
QByteArray propertyName = propertyNameAtIndex(index);
const QMetaProperty metaProperty = metaPropertyAtIndex(index);
if(metaProperty.isWritable() || object->dynamicPropertyNames().contains(propertyName))
flags |= Qt::ItemIsEditable;
return flags;
}
void QtPropertyTreeModel::Node::setObject(QObject *object, int maxChildDepth, const QList<QByteArray> &propertyNames)
{
this->object = object;
propertyName.clear();
qDeleteAll(children);
children.clear();
if(!object) return;
// Compiled properties (but exclude objectName as this is displayed for the object node itself).
const QMetaObject *metaObject = object->metaObject();
int numProperties = metaObject->propertyCount();
for(int i = 0; i < numProperties; ++i) {
const QMetaProperty metaProperty = metaObject->property(i);
QByteArray propertyName = QByteArray(metaProperty.name());
if(propertyNames.isEmpty() || propertyNames.contains(propertyName)) {
Node *node = new Node(this);
node->propertyName = propertyName;
children.append(node);
}
}
// Dynamic properties.
QList<QByteArray> dynamicPropertyNames = object->dynamicPropertyNames();
foreach(const QByteArray &propertyName, dynamicPropertyNames) {
if(propertyNames.isEmpty() || propertyNames.contains(propertyName)) {
Node *node = new Node(this);
node->propertyName = propertyName;
children.append(node);
}
}
// Child objects.
if(maxChildDepth > 0 || maxChildDepth == -1) {
if(maxChildDepth > 0)
--maxChildDepth;
QMap<QByteArray, QObjectList> childMap;
foreach(QObject *child, object->children()) {
childMap[QByteArray(child->metaObject()->className())].append(child);
}
for(auto it = childMap.begin(); it != childMap.end(); ++it) {
foreach(QObject *child, it.value()) {
Node *node = new Node(this);
node->setObject(child, maxChildDepth, propertyNames);
children.append(node);
}
}
}
}
QtPropertyTreeModel::Node* QtPropertyTreeModel::nodeAtIndex(const QModelIndex &index) const
{
try {
return static_cast<Node*>(index.internalPointer());
} catch(...) {
return NULL;
}
}
QObject* QtPropertyTreeModel::objectAtIndex(const QModelIndex &index) const
{
// If node is an object, return the node's object.
// Else if node is a property, return the parent node's object.
Node *node = nodeAtIndex(index);
if(!node) return NULL;
if(node->object) return node->object;
if(node->parent) return node->parent->object;
return NULL;
}
QByteArray QtPropertyTreeModel::propertyNameAtIndex(const QModelIndex &index) const
{
// If node is a property, return the node's property name.
// Else if node is an object, return "objectName".
Node *node = nodeAtIndex(index);
if(!node) return QByteArray();
if(!node->propertyName.isEmpty()) return node->propertyName;
return QByteArray();
}
QModelIndex QtPropertyTreeModel::index(int row, int column, const QModelIndex &parent) const
{
// Return a model index whose internal pointer references the appropriate tree node.
if(column < 0 || column >= 2 || !hasIndex(row, column, parent))
return QModelIndex();
const Node *parentNode = parent.isValid() ? nodeAtIndex(parent) : &_root;
if(!parentNode || row < 0 || row >= parentNode->children.size())
return QModelIndex();
Node *node = parentNode->children.at(row);
return node ? createIndex(row, column, node) : QModelIndex();
}
QModelIndex QtPropertyTreeModel::parent(const QModelIndex &index) const
{
// Return a model index for parent node (column must be 0).
if(!index.isValid())
return QModelIndex();
Node *node = nodeAtIndex(index);
if(!node)
return QModelIndex();
Node *parentNode = node->parent;
if(!parentNode || parentNode == &_root)
return QModelIndex();
int row = 0;
Node *grandparentNode = parentNode->parent;
if(grandparentNode)
row = grandparentNode->children.indexOf(parentNode);
return createIndex(row, 0, parentNode);
}
int QtPropertyTreeModel::rowCount(const QModelIndex &parent) const
{
// Return number of child nodes.
const Node *parentNode = parent.isValid() ? nodeAtIndex(parent) : &_root;
return parentNode ? parentNode->children.size() : 0;
}
int QtPropertyTreeModel::columnCount(const QModelIndex &parent) const
{
// Return 2 for name/value columns.
const Node *parentNode = parent.isValid() ? nodeAtIndex(parent) : &_root;
return (parentNode ? 2 : 0);
}
QVariant QtPropertyTreeModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
if(role == Qt::DisplayRole || role == Qt::EditRole) {
QObject *object = objectAtIndex(index);
if(!object)
return QVariant();
QByteArray propertyName = propertyNameAtIndex(index);
if(index.column() == 0) {
// Object's class name or else the property name.
if(propertyName.isEmpty())
return QVariant(object->metaObject()->className());
else if(propertyHeaders.contains(propertyName))
return QVariant(propertyHeaders[propertyName]);
else
return QVariant(propertyName);
} else if(index.column() == 1) {
// Object's objectName or else the property value.
if(propertyName.isEmpty())
return QVariant(object->objectName());
else
return object->property(propertyName.constData());
}
}
return QVariant();
}
bool QtPropertyTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
if(role == Qt::EditRole) {
QObject *object = objectAtIndex(index);
if(!object)
return false;
QByteArray propertyName = propertyNameAtIndex(index);
if(index.column() == 0) {
// Object class name or property name.
return false;
} else if(index.column() == 1) {
// Object's objectName or else the property value.
if(propertyName.isEmpty()) {
object->setObjectName(value.toString());
return true;
} else {
bool result = object->setProperty(propertyName.constData(), value);
// Result will be FALSE for dynamic properties, which causes the tree view to lag.
// So make sure we still return TRUE in this case.
if(!result && object->dynamicPropertyNames().contains(propertyName))
return true;
return result;
}
}
}
return false;
}
Qt::ItemFlags QtPropertyTreeModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if(!index.isValid())
return flags;
QObject *object = objectAtIndex(index);
if(!object)
return flags;
flags |= Qt::ItemIsEnabled;
flags |= Qt::ItemIsSelectable;
if(index.column() == 1) {
QByteArray propertyName = propertyNameAtIndex(index);
const QMetaProperty metaProperty = metaPropertyAtIndex(index);
if(metaProperty.isWritable() || object->dynamicPropertyNames().contains(propertyName) || objectAtIndex(index))
flags |= Qt::ItemIsEditable;
}
return flags;
}
QVariant QtPropertyTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(role == Qt::DisplayRole) {
if(orientation == Qt::Horizontal) {
if(section == 0)
return QVariant("Name");
else if(section == 1)
return QVariant("Value");
}
}
return QVariant();
}
QObject* QtPropertyTableModel::objectAtIndex(const QModelIndex &index) const
{
if(_objects.size() <= index.row())
return 0;
QObject *object = _objects.at(index.row());
// If property names are specified, check if name at column is a path to a child object property.
if(!propertyNames.isEmpty()) {
if(propertyNames.size() > index.column()) {
QByteArray propertyName = propertyNames.at(index.column());
if(propertyName.contains('.')) {
int pos = propertyName.lastIndexOf('.');
return descendant(object, propertyName.left(pos));
}
}
}
return object;
}
QByteArray QtPropertyTableModel::propertyNameAtIndex(const QModelIndex &index) const
{
// If property names are specified, return the name at column.
if(!propertyNames.isEmpty()) {
if(propertyNames.size() > index.column()) {
QByteArray propertyName = propertyNames.at(index.column());
if(propertyName.contains('.')) {
int pos = propertyName.lastIndexOf('.');
return propertyName.mid(pos + 1);
}
return propertyName;
}
return QByteArray();
}
// If property names are NOT specified, return the metaObject's property name at column.
QObject *object = objectAtIndex(index);
if(!object)
return QByteArray();
const QMetaObject *metaObject = object->metaObject();
int numProperties = metaObject->propertyCount();
if(numProperties > index.column())
return QByteArray(metaObject->property(index.column()).name());
// If column is greater than the number of metaObject properties, check for dynamic properties.
const QList<QByteArray> &dynamicPropertyNames = object->dynamicPropertyNames();
if(numProperties + dynamicPropertyNames.size() > index.column())
return dynamicPropertyNames.at(index.column() - numProperties);
return QByteArray();
}
QModelIndex QtPropertyTableModel::index(int row, int column, const QModelIndex &/* parent */) const
{
return createIndex(row, column);
}
QModelIndex QtPropertyTableModel::parent(const QModelIndex &/* index */) const
{
return QModelIndex();
}
int QtPropertyTableModel::rowCount(const QModelIndex &/* parent */) const
{
return _objects.size();
}
int QtPropertyTableModel::columnCount(const QModelIndex &/* parent */) const
{
// Number of properties.
if(!propertyNames.isEmpty())
return propertyNames.size();
if(_objects.isEmpty())
return 0;
QObject *object = _objects.at(0);
const QMetaObject *metaObject = object->metaObject();
return metaObject->propertyCount() + object->dynamicPropertyNames().size();
}
QVariant QtPropertyTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(role == Qt::DisplayRole) {
if(orientation == Qt::Vertical) {
return QVariant(section);
} else if(orientation == Qt::Horizontal) {
QByteArray propertyName = propertyNameAtIndex(createIndex(0, section));
QByteArray childPath;
if(propertyNames.size() > section) {
QByteArray pathToPropertyName = propertyNames.at(section);
if(pathToPropertyName.contains('.')) {
int pos = pathToPropertyName.lastIndexOf('.');
childPath = pathToPropertyName.left(pos + 1);
}
}
if(propertyHeaders.contains(propertyName))
return QVariant(childPath + propertyHeaders.value(propertyName));
return QVariant(childPath + propertyName);
}
}
return QVariant();
}
bool QtPropertyTableModel::insertRows(int row, int count, const QModelIndex &parent)
{
// Only valid if we have an object creator method.
if(!_objectCreator)
return false;
bool columnCountWillAlsoChange = _objects.isEmpty() && propertyNames.isEmpty();
beginInsertRows(parent, row, row + count - 1);
for(int i = row; i < row + count; ++i) {
QObject *object = _objectCreator();
_objects.insert(i, object);
}
endInsertRows();
if(row + count < _objects.size())
reorderChildObjectsToMatchRowOrder(row + count);
if(columnCountWillAlsoChange) {
beginResetModel();
endResetModel();
}
emit rowCountChanged();
return true;
}
bool QtPropertyTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
beginRemoveRows(parent, row, row + count - 1);
for(int i = row; i < row + count; ++i)
delete _objects.at(i);
QObjectList::iterator begin = _objects.begin() + row;
_objects.erase(begin, begin + count);
endRemoveRows();
emit rowCountChanged();
return true;
}
bool QtPropertyTableModel::moveRows(const QModelIndex &/*sourceParent*/, int sourceRow, int count, const QModelIndex &/*destinationParent*/, int destinationRow)
{
beginResetModel();
QObjectList objectsToMove;
for(int i = sourceRow; i < sourceRow + count; ++i)
objectsToMove.append(_objects.takeAt(sourceRow));
for(int i = 0; i < objectsToMove.size(); ++i) {
if(destinationRow + i >= _objects.size())
_objects.append(objectsToMove.at(i));
else
_objects.insert(destinationRow + i, objectsToMove.at(i));
}
endResetModel();
reorderChildObjectsToMatchRowOrder(sourceRow <= destinationRow ? sourceRow : destinationRow);
emit rowOrderChanged();
return true;
}
void QtPropertyTableModel::reorderChildObjectsToMatchRowOrder(int firstRow)
{
for(int i = firstRow; i < rowCount(); ++i) {
QObject *object = objectAtIndex(createIndex(i, 0));
if(object) {
QObject *parent = object->parent();
if(parent) {
object->setParent(NULL);
object->setParent(parent);
}
}
}
}
QWidget* QtPropertyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QVariant value = index.data(Qt::DisplayRole);
if(value.isValid()) {
if(value.typeId() == QVariant::Bool) {
// We want a check box, but instead of creating an editor widget we'll just directly
// draw the check box in paint() and handle mouse clicks in editorEvent().
// Here, we'll just return NULL to make sure that no editor is created when this cell is double clicked.
return NULL;
} else if(value.typeId() == QVariant::Double) {
// Return a QLineEdit to enter double values with arbitrary precision and scientific notation.
QLineEdit *editor = new QLineEdit(parent);
editor->setText(value.toString());
return editor;
} else if(value.typeId() == QVariant::Int) {
// We don't need to do anything special for an integer, we'll just use the default QSpinBox.
// However, we do need to check if it is an enum. If so, we'll use a QComboBox editor.
const QtAbstractPropertyModel *propertyModel = qobject_cast<const QtAbstractPropertyModel*>(index.model());
if(propertyModel) {
const QMetaProperty metaProperty = propertyModel->metaPropertyAtIndex(index);
if(metaProperty.isValid() && metaProperty.isEnumType()) {
const QMetaEnum metaEnum = metaProperty.enumerator();
int numKeys = metaEnum.keyCount();
if(numKeys > 0) {
QComboBox *editor = new QComboBox(parent);
for(int j = 0; j < numKeys; ++j) {
QByteArray key = QByteArray(metaEnum.key(j));
editor->addItem(QString(key));
}
QByteArray currentKey = QByteArray(metaEnum.valueToKey(value.toInt()));
editor->setCurrentText(QString(currentKey));
return editor;
}
}
}
} else if(value.typeId() == QVariant::Size ||
value.typeId() == QVariant::SizeF ||
value.typeId() == QVariant::Point ||
value.typeId() == QVariant::PointF ||
value.typeId() == QVariant::Rect ||
value.typeId() == QVariant::RectF) {
// Return a QLineEdit. Parsing will be done in displayText() and setEditorData().
QLineEdit *editor = new QLineEdit(parent);
editor->setText(displayText(value, QLocale()));
return editor;
} else if(value.typeId() == QVariant::UserType) {
if(value.canConvert<QtPushButtonActionWrapper>()) {
// We want a push button, but instead of creating an editor widget we'll just directly
// draw the button in paint() and handle mouse clicks in editorEvent().
// Here, we'll just return NULL to make sure that no editor is created when this cell is double clicked.
return NULL;
}
}
}
return QStyledItemDelegate::createEditor(parent, option, index);
}
void QtPropertyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QStyledItemDelegate::setEditorData(editor, index);
}
void QtPropertyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QVariant value = index.data(Qt::DisplayRole);
if(value.isValid()) {
if(value.typeId() == QVariant::Double) {
// Set model's double value data to numeric representation in QLineEdit editor.
// Conversion from text to number handled by QVariant.
QLineEdit *lineEditor = qobject_cast<QLineEdit*>(editor);
if(lineEditor) {
QVariant value = QVariant(lineEditor->text());
bool ok;
double dval = value.toDouble(&ok);
if(ok)
model->setData(index, QVariant(dval), Qt::EditRole);
return;
}
} else if(value.typeId() == QVariant::Int) {
// We don't need to do anything special for an integer.
// However, if it's an enum we'll set the data based on the QComboBox editor.
QComboBox *comboBoxEditor = qobject_cast<QComboBox*>(editor);
if(comboBoxEditor) {
QString selectedKey = comboBoxEditor->currentText();
const QtAbstractPropertyModel *propertyModel = qobject_cast<const QtAbstractPropertyModel*>(model);
if(propertyModel) {
const QMetaProperty metaProperty = propertyModel->metaPropertyAtIndex(index);
if(metaProperty.isValid() && metaProperty.isEnumType()) {
const QMetaEnum metaEnum = metaProperty.enumerator();
bool ok;
int selectedValue = metaEnum.keyToValue(selectedKey.toLatin1().constData(), &ok);
if(ok)
model->setData(index, QVariant(selectedValue), Qt::EditRole);
return;
}
}
// If we got here, we have a QComboBox editor but the property at index is not an enum.
}
} else if(value.typeId() == QVariant::Size) {
QLineEdit *lineEditor = qobject_cast<QLineEdit*>(editor);
if(lineEditor) {
// Parse formats: (w x h) or (w,h) or (w h) <== () are optional
QRegularExpression regex("\\s*\\(?\\s*(\\d+)\\s*[x,\\s]\\s*(\\d+)\\s*\\)?\\s*");
QRegularExpressionMatch match = regex.match(lineEditor->text().trimmed());
if(match.hasMatch() && match.capturedTexts().size() == 3) {
bool wok, hok;
int w = match.captured(1).toInt(&wok);
int h = match.captured(2).toInt(&hok);
if(wok && hok)
model->setData(index, QVariant(QSize(w, h)), Qt::EditRole);
}
}
} else if(value.typeId() == QVariant::SizeF) {
QLineEdit *lineEditor = qobject_cast<QLineEdit*>(editor);
if(lineEditor) {
// Parse formats: (w x h) or (w,h) or (w h) <== () are optional
QRegularExpression regex("\\s*\\(?\\s*([0-9\\+\\-\\.eE]+)\\s*[x,\\s]\\s*([0-9\\+\\-\\.eE]+)\\s*\\)?\\s*");
QRegularExpressionMatch match = regex.match(lineEditor->text().trimmed());
if(match.hasMatch() && match.capturedTexts().size() == 3) {
bool wok, hok;
double w = match.captured(1).toDouble(&wok);
double h = match.captured(2).toDouble(&hok);
if(wok && hok)
model->setData(index, QVariant(QSizeF(w, h)), Qt::EditRole);
}
}
} else if(value.typeId() == QVariant::Point) {
QLineEdit *lineEditor = qobject_cast<QLineEdit*>(editor);
if(lineEditor) {
// Parse formats: (x,y) or (x y) <== () are optional
QRegularExpression regex("\\s*\\(?\\s*(\\d+)\\s*[x,\\s]\\s*(\\d+)\\s*\\)?\\s*");
QRegularExpressionMatch match = regex.match(lineEditor->text().trimmed());
if(match.hasMatch() && match.capturedTexts().size() == 3) {
bool xok, yok;
int x = match.captured(1).toInt(&xok);
int y = match.captured(2).toInt(&yok);
if(xok && yok)
model->setData(index, QVariant(QPoint(x, y)), Qt::EditRole);
}
}
} else if(value.typeId() == QVariant::PointF) {
QLineEdit *lineEditor = qobject_cast<QLineEdit*>(editor);
if(lineEditor) {
// Parse formats: (x,y) or (x y) <== () are optional
QRegularExpression regex("\\s*\\(?\\s*([0-9\\+\\-\\.eE]+)\\s*[x,\\s]\\s*([0-9\\+\\-\\.eE]+)\\s*\\)?\\s*");
QRegularExpressionMatch match = regex.match(lineEditor->text().trimmed());
if(match.hasMatch() && match.capturedTexts().size() == 3) {
bool xok, yok;
double x = match.captured(1).toDouble(&xok);
double y = match.captured(2).toDouble(&yok);
if(xok && yok)
model->setData(index, QVariant(QPointF(x, y)), Qt::EditRole);
}
}
} else if(value.typeId() == QVariant::Rect) {
QLineEdit *lineEditor = qobject_cast<QLineEdit*>(editor);
if(lineEditor) {
// Parse formats: [Point,Size] or [Point Size] <== [] are optional
// Point formats: (x,y) or (x y) <== () are optional
// Size formats: (w x h) or (w,h) or (w h) <== () are optional
QRegularExpression regex("\\s*\\[?"
"\\s*\\(?\\s*(\\d+)\\s*[,\\s]\\s*(\\d+)\\s*\\)?\\s*"
"[,\\s]"
"\\s*\\(?\\s*(\\d+)\\s*[x,\\s]\\s*(\\d+)\\s*\\)?\\s*"
"\\]?\\s*");
QRegularExpressionMatch match = regex.match(lineEditor->text().trimmed());
if(match.hasMatch() && match.capturedTexts().size() == 5) {
bool xok, yok, wok, hok;
int x = match.captured(1).toInt(&xok);
int y = match.captured(2).toInt(&yok);
int w = match.captured(3).toInt(&wok);
int h = match.captured(4).toInt(&hok);
if(xok && yok && wok && hok)
model->setData(index, QVariant(QRect(x, y, w, h)), Qt::EditRole);
}
}
} else if(value.typeId() == QVariant::RectF) {
QLineEdit *lineEditor = qobject_cast<QLineEdit*>(editor);
if(lineEditor) {
// Parse formats: [Point,Size] or [Point Size] <== [] are optional
// Point formats: (x,y) or (x y) <== () are optional
// Size formats: (w x h) or (w,h) or (w h) <== () are optional
QRegularExpression regex("\\s*\\[?"
"\\s*\\(?\\s*([0-9\\+\\-\\.eE]+)\\s*[,\\s]\\s*([0-9\\+\\-\\.eE]+)\\s*\\)?\\s*"
"[,\\s]"
"\\s*\\(?\\s*([0-9\\+\\-\\.eE]+)\\s*[x,\\s]\\s*([0-9\\+\\-\\.eE]+)\\s*\\)?\\s*"
"\\]?\\s*");
QRegularExpressionMatch match = regex.match(lineEditor->text().trimmed());
if(match.hasMatch() && match.capturedTexts().size() == 5) {
bool xok, yok, wok, hok;
double x = match.captured(1).toDouble(&xok);
double y = match.captured(2).toDouble(&yok);
double w = match.captured(3).toDouble(&wok);
double h = match.captured(4).toDouble(&hok);
if(xok && yok && wok && hok)
model->setData(index, QVariant(QRectF(x, y, w, h)), Qt::EditRole);
}
}
// } else if(value.type() == QVariant::Color) {
// QLineEdit *lineEditor = qobject_cast<QLineEdit*>(editor);
// if(lineEditor) {
// // Parse formats: (r,g,b) or (r g b) or (r,g,b,a) or (r g b a) <== () are optional
// QRegularExpression regex("\\s*\\(?"
// "\\s*(\\d+)\\s*"
// "[,\\s]\\s*(\\d+)\\s*"
// "[,\\s]\\s*(\\d+)\\s*"
// "([,\\s]\\s*(\\d+)\\s*)?"
// "\\)?\\s*");
// QRegularExpressionMatch match = regex.match(lineEditor->text().trimmed());
// if(match.hasMatch() && (match.capturedTexts().size() == 4 || match.capturedTexts().size() == 5)) {
// bool rok, gok, bok, aok;
// int r = match.captured(1).toInt(&rok);
// int g = match.captured(2).toInt(&gok);
// int b = match.captured(3).toInt(&bok);
// if(match.capturedTexts().size() == 4) {
// if(rok && gok && bok)
// model->setData(index, QColor(r, g, b), Qt::EditRole);
// } else if(match.capturedTexts().size() == 5) {
// int a = match.captured(4).toInt(&aok);
// if(rok && gok && bok && aok)
// model->setData(index, QColor(r, g, b, a), Qt::EditRole);
// }
// }
// }
}
}
QStyledItemDelegate::setModelData(editor, model, index);
}
QString QtPropertyDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
if(value.isValid()) {
if(value.typeId() == QVariant::Size) {
// w x h
QSize size = value.toSize();
return QString::number(size.width()) + QString(" x ") + QString::number(size.height());
} else if(value.typeId() == QVariant::SizeF) {
// w x h
QSizeF size = value.toSizeF();
return QString::number(size.width()) + QString(" x ") + QString::number(size.height());
} else if(value.typeId() == QVariant::Point) {
// (x, y)
QPoint point = value.toPoint();
return QString("(")
+ QString::number(point.x()) + QString(", ") + QString::number(point.y())
+ QString(")");
} else if(value.typeId() == QVariant::PointF) {
// (x, y)
QPointF point = value.toPointF();
return QString("(")
+ QString::number(point.x()) + QString(", ") + QString::number(point.y())
+ QString(")");
} else if(value.typeId() == QVariant::Rect) {
// [(x, y), w x h]
QRect rect = value.toRect();
return QString("[(")
+ QString::number(rect.x()) + QString(", ") + QString::number(rect.y())
+ QString("), ")
+ QString::number(rect.width()) + QString(" x ") + QString::number(rect.height())
+ QString("]");
} else if(value.typeId() == QVariant::RectF) {
// [(x, y), w x h]
QRectF rect = value.toRectF();
return QString("[(")
+ QString::number(rect.x()) + QString(", ") + QString::number(rect.y())
+ QString("), ")
+ QString::number(rect.width()) + QString(" x ") + QString::number(rect.height())
+ QString("]");
// } else if(value.type() == QVariant::Color) {
// // (r, g, b, a)
// QColor color = value.value<QColor>();
// return QString("(")
// + QString::number(color.red()) + QString(", ") + QString::number(color.green()) + QString(", ")
// + QString::number(color.blue()) + QString(", ") + QString::number(color.alpha())
// + QString(")");
}
}
return QStyledItemDelegate::displayText(value, locale);
}
void QtPropertyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QVariant value = index.data(Qt::DisplayRole);
if(value.isValid()) {
if(value.typeId() == QVariant::Bool) {
bool checked = value.toBool();
QStyleOptionButton buttonOption;
buttonOption.state |= QStyle::State_Active; // Required!
buttonOption.state |= ((index.flags() & Qt::ItemIsEditable) ? QStyle::State_Enabled : QStyle::State_ReadOnly);
buttonOption.state |= (checked ? QStyle::State_On : QStyle::State_Off);
QRect checkBoxRect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &buttonOption); // Only used to get size of native checkbox widget.
buttonOption.rect = QStyle::alignedRect(option.direction, Qt::AlignLeft, checkBoxRect.size(), option.rect); // Our checkbox rect.
QApplication::style()->drawControl(QStyle::CE_CheckBox, &buttonOption, painter);
return;
} else if(value.typeId() == QVariant::Int) {
// We don't need to do anything special for an integer.
// However, if it's an enum want to render the key name instead of the value.
// This cannot be done in displayText() because we need the model index to get the key name.
const QtAbstractPropertyModel *propertyModel = qobject_cast<const QtAbstractPropertyModel*>(index.model());
if(propertyModel) {
const QMetaProperty metaProperty = propertyModel->metaPropertyAtIndex(index);
if(metaProperty.isValid() && metaProperty.isEnumType()) {
const QMetaEnum metaEnum = metaProperty.enumerator();
QByteArray currentKey = QByteArray(metaEnum.valueToKey(value.toInt()));
QStyleOptionViewItem itemOption(option);
initStyleOption(&itemOption, index);
itemOption.text = QString(currentKey);
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter);
return;
}
}
} else if(value.typeId() == QVariant::UserType) {
if(value.canConvert<QtPushButtonActionWrapper>()) {
QAction *action = value.value<QtPushButtonActionWrapper>().action;
QStyleOptionButton buttonOption;
buttonOption.state = QStyle::State_Active | QStyle::State_Raised;
//buttonOption.features = QStyleOptionButton::DefaultButton;
if(action) buttonOption.text = action->text();
buttonOption.rect = option.rect;
//buttonOption.rect = QRect(option.rect.x() + 5, option.rect.y() + 5, option.rect.width() - 10, option.rect.height() - 10);
QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonOption, painter);
return;
}
}
}
QStyledItemDelegate::paint(painter, option, index);
}
bool QtPropertyDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
QVariant value = index.data(Qt::DisplayRole);
if(value.isValid()) {
if(value.typeId() == QVariant::Bool) {
if(event->type() == QEvent::MouseButtonDblClick)
return false;
if(event->type() != QEvent::MouseButtonRelease)
return false;
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if(mouseEvent->button() != Qt::LeftButton)
return false;
//QStyleOptionButton buttonOption;
//QRect checkBoxRect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &buttonOption); // Only used to get size of native checkbox widget.
//buttonOption.rect = QStyle::alignedRect(option.direction, Qt::AlignLeft, checkBoxRect.size(), option.rect); // Our checkbox rect.
// option.rect ==> cell
// buttonOption.rect ==> check box
// Here, we choose to allow clicks anywhere in the cell to toggle the checkbox.
if(!option.rect.contains(mouseEvent->pos()))
return false;
bool checked = value.toBool();
QVariant newValue(!checked); // Toggle model's bool value.
bool success = model->setData(index, newValue, Qt::EditRole);
// Update entire table row just in case some other cell also refers to the same bool value.
// Otherwise, that other cell will not reflect the current state of the bool set via this cell.
if(success)
model->dataChanged(index.sibling(index.row(), 0), index.sibling(index.row(), model->columnCount()));
return success;
} else if(value.typeId() == QVariant::UserType) {
if(value.canConvert<QtPushButtonActionWrapper>()) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if(mouseEvent->button() != Qt::LeftButton)
return false;
if(!option.rect.contains(mouseEvent->pos()))
return false;
QAction *action = value.value<QtPushButtonActionWrapper>().action;
if(action) action->trigger();
return true;
}
}
}
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
QtPropertyTreeEditor::QtPropertyTreeEditor(QWidget *parent) : QTreeView(parent)
{
setItemDelegate(&_delegate);
setAlternatingRowColors(true);
setModel(&treeModel);
}
void QtPropertyTreeEditor::resizeColumnsToContents()
{
resizeColumnToContents(0);
resizeColumnToContents(1);
}
QtPropertyTableEditor::QtPropertyTableEditor(QWidget *parent) : QTableView(parent)
{
setItemDelegate(&_delegate);
setAlternatingRowColors(true);
setModel(&tableModel);
verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
setIsDynamic(_isDynamic);
// Draggable rows.
verticalHeader()->setSectionsMovable(_isDynamic);
connect(verticalHeader(), SIGNAL(sectionMoved(int, int, int)), this, SLOT(handleSectionMove(int, int, int)));
// Header context menus.
horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
verticalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(horizontalHeaderContextMenu(QPoint)));
connect(verticalHeader(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(verticalHeaderContextMenu(QPoint)));
// Custom corner button.
if(QAbstractButton *cornerButton = findChild<QAbstractButton*>()) {
cornerButton->installEventFilter(this);
}
}
void QtPropertyTableEditor::setIsDynamic(bool b)
{
_isDynamic = b;
// Dragging rows.
verticalHeader()->setSectionsMovable(_isDynamic);
// Corner button.
if(QAbstractButton *cornerButton = findChild<QAbstractButton*>()) {
if(_isDynamic) {
cornerButton->disconnect(SIGNAL(clicked()));
connect(cornerButton, SIGNAL(clicked()), this, SLOT(appendRow()));
cornerButton->setText("+");
cornerButton->setToolTip("Append row");
} else {
cornerButton->disconnect(SIGNAL(clicked()));
connect(cornerButton, SIGNAL(clicked()), this, SLOT(selectAll()));
cornerButton->setText("");
cornerButton->setToolTip("Select all");
}
// adjust the width of the vertical header to match the preferred corner button width
// (unfortunately QAbstractButton doesn't implement any size hinting functionality)
QStyleOptionHeader opt;
opt.text = cornerButton->text();
//opt.icon = cornerButton->icon();
/*