我的问题如下:
有aQTableView
和aQStandardItemModel
这样使用:
ui->tableView->setModel(model);
model->setItem(myrow, mycolumn, myQStandardItem);
和一个组合框委托:
ComboBoxDelegate* mydelegate = new ComboBoxDelegate();
ui->tableView->setItemDelegateForColumn(mycolumn,mydelegate);
每次更改表格单元格的值(通过组合框)时,我都需要捕获新值和刚刚修改的单元格的索引。我dataChaged
以这种方式使用与模型关联的信号:
connect(model,SIGNAL(dataChanged(QModelIndex&,QModelIndex&)),this,SLOT(GetChangedValue(QModelIndex&)));
但它不起作用,GetChangedValue
尽管组合框已更改其值,但它从不调用该方法。我跳过任何步骤吗?
下面是代码ComboBoxDelegate
:
class ComboBoxDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
ComboBoxDelegate(QVector<QString>& ItemsToCopy,QObject *parent = 0);
~ComboBoxDelegate();
void setItemData(QVector<QString>& ItemsToCopy);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const ;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
private:
QVector<QString> Items;
};
ComboBoxDelegate::ComboBoxDelegate(QVector<QString>& ItemsToCopy,QObject *parent)
:QStyledItemDelegate(parent)
{
setItemData(ItemsToCopy);
}
ComboBoxDelegate::~ComboBoxDelegate()
{
}
QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QComboBox* editor = new QComboBox(parent);
editor->setEditable(true);
for (int i = 0; i < Items.size(); ++i)
{
editor->addItem(Items[i]);
}
editor->setStyleSheet("combobox-popup: 0;");
return editor;
}
void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
QString currentText = index.data(Qt::EditRole).toString();
int cbIndex = comboBox->findText(currentText);
comboBox->setCurrentIndex(cbIndex);
}
void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
model->setData(index, comboBox->currentText(), Qt::EditRole);
}
void ComboBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
void ComboBoxDelegate::setItemData(QVector<QString>& ItemsToCopy)
{
for (int row = 0; row < ItemsToCopy.size(); ++row)
{
Items.push_back(ItemsToCopy[row]);
}
}