mirror-chatterino2/src/widgets/helper/ComboBoxItemDelegate.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

70 lines
1.9 KiB
C++
Raw Normal View History

2018-06-26 14:09:39 +02:00
#include "ComboBoxItemDelegate.hpp"
2018-04-27 01:11:09 +02:00
#include <QComboBox>
2018-04-27 01:11:09 +02:00
namespace chatterino {
2018-04-27 01:11:09 +02:00
ComboBoxItemDelegate::ComboBoxItemDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
2018-04-27 01:11:09 +02:00
ComboBoxItemDelegate::~ComboBoxItemDelegate()
{
}
2018-04-27 01:11:09 +02:00
QWidget *ComboBoxItemDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QVariant data = index.data(Qt::UserRole + 1);
2018-04-27 01:11:09 +02:00
if (data.type() != QVariant::StringList)
{
return QStyledItemDelegate::createEditor(parent, option, index);
}
2018-04-27 01:11:09 +02:00
QComboBox *combo = new QComboBox(parent);
combo->addItems(data.toStringList());
return combo;
}
2018-04-27 01:11:09 +02:00
void ComboBoxItemDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
if (QComboBox *cb = qobject_cast<QComboBox *>(editor))
{
// get the index of the text in the combobox that matches the current
// value of the itenm
QString currentText = index.data(Qt::EditRole).toString();
int cbIndex = cb->findText(currentText);
2018-04-27 01:11:09 +02:00
// if it is valid, adjust the combobox
if (cbIndex >= 0)
{
cb->setCurrentIndex(cbIndex);
}
}
else
{
QStyledItemDelegate::setEditorData(editor, index);
}
}
2018-04-27 01:11:09 +02:00
void ComboBoxItemDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
if (QComboBox *cb = qobject_cast<QComboBox *>(editor))
{
2018-04-27 01:11:09 +02:00
// save the current text of the combo box as the current value of the
// item
model->setData(index, cb->currentText(), Qt::EditRole);
}
2018-04-27 01:11:09 +02:00
else
{
2018-04-27 01:11:09 +02:00
QStyledItemDelegate::setModelData(editor, model, index);
}
2018-04-27 01:11:09 +02:00
}
} // namespace chatterino