bool ColorDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) { if ( event->type() == QEvent::MouseButtonRelease && index.data().canConvert<QColor>()) { QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event); if ( mouse_event->button() == Qt::LeftButton && ( index.flags() & Qt::ItemIsEditable) ) { ColorDialog *editor = new ColorDialog(const_cast<QWidget*>(option.widget)); connect(this, &QObject::destroyed, editor, &QObject::deleteLater); editor->setMinimumSize(editor->sizeHint()); auto original_color = index.data().value<QColor>(); editor->setColor(original_color); auto set_color = [model, index](const QColor& color){ model->setData(index, QVariant(color)); }; connect(editor, &ColorDialog::colorSelected, this, set_color); editor->show(); } return true; } return QAbstractItemDelegate::editorEvent(event, model, option, index); }
void ColorDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { if (index.data().canConvert<QColor>()) { ColorDialog *selector = qobject_cast<ColorDialog*>(editor); selector->setColor(qvariant_cast<QColor>(index.data())); } else QStyledItemDelegate::setEditorData(editor, index); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); ColorListWidget c; c.show(); ColorDialog w; w.setColor(QColor(64,172,143,128)); w.show(); /*QPixmap p(w.size()); w.render(&p); p.save("screenshot.png");*/ return a.exec(); }