QDataWidgetMapper 是一个稍微不同的东西。这是一种使用自定义控件从模型(例如 QStandardItemModel)中显示一个项目的方法。您可以阅读更多关于它的信息here,并附上快照和如何实现快照的示例。
虽然它确实很酷,但我认为这不是您想要的。主要是因为您指定要以列表格式查看项目。但是,您可以在一个简单的列表中显示所有项目,双击它将使用 QDataWidgetMapper 打开一个对话框。在这种情况下,您需要对 QListView/QListWidget 做的就是实现双击事件。
不过,我个人不喜欢额外窗口给用户带来的额外负担。我更喜欢谨慎使用弹出窗口。但是,如果您喜欢这种方法,请继续。 This 是另一个非常不错的 QDataWidgetMapper 示例。
我的首选方法仍然是使用 QTableView,并为需要专门编辑的列提供委托。 Here 是模型/视图的所有东西的一个很好的演练。所以如果你决定使用 QListView 或 QTableView 它会给你一个很好的开始。它还讨论了如何创建代表以根据需要编辑字段。
那么,如何创建自定义委托?基本上,您只需从 QItemDelegate 继承。上面的链接中有一些示例,但我会强调一些要点。
QWidget *ComboBoxDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/* option */,
const QModelIndex &index) const
{
QComboBox *editor = new QComboBox (parent);
// Add items to the combobox here.
// You can use the QModelIndex passed above to access the model
// Add find out what country was selected, and therefore what cities
// need to be listed in the combobox
return editor;
}
void ComboBoxDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
int value = index.model()->data(index, Qt::EditRole).toInt();
QComboBox *comboBox= static_cast<QComboBox *>(editor);
int _SelectedItem = // Figure out which is the currently selected index;
comboBox->setCurrentIndex(_SelectedItem);
}
void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QComboBox *comboBox= static_cast<QComboBox *>(editor);
comboBox->interpretText();
int value = comboBox->currentIndex();
// Translate the current index to whatever you actually want to
// set in your model.
model->setData(index, value, Qt::EditRole);
}
填补我在示例中留下的空白,您就有了您的代表。
现在,如何在 QTableView 中使用它:
您可以为表格的特定列设置委托,如下所示:
setItemDelegateForColumn(_ColumnIndex, new ComboBoxDelegate(_YourTableModel));
而且,如果您想阻止某些列可编辑:
_YourTableModel->setColumnEditable(_ColumnIndex, false);
设置好模型后,其他一切都应自行处理。
希望对您有所帮助。