您可以继承QTableView
以便能够访问不幸保护的state()
函数。但是,我没有尝试过。
如果您已有QStyledItemDelegate
子类,则可以使用它来跟踪编辑器当前是否处于打开状态。但是,您不能只使用setEditorData
/setModelData
,因为setModelData
不会在用户取消编辑时调用。相反,您可以跟踪编辑器本身的创建和销毁。
class MyItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
MyItemDelegate(QObject* parent = nullptr);
~MyItemDelegate();
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;
bool isEditorOpen() const { return *m_editorCount > 0; }
protected:
int* m_editorCount;
protected slots:
void onEditorDestroyed(QObject* obj);
};
实现:
MyItemDelegate::MyItemDelegate(QObject* parent) :
QStyledItemDelegate(parent)
{
m_editorCount = new int;
*m_editorCount = 0;
}
MyItemDelegate::~MyItemDelegate()
{
delete m_editorCount;
}
QWidget* MyItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
// create an editor, can be changed as needed
QWidget* editor = QStyledItemDelegate::createEditor(parent, option, index);
connect(editor, SIGNAL(destroyed(QObject*)), SLOT(onEditorDestroyed(QObject*)));
printf("editor %p created\n", (void*) editor);
(*m_editorCount)++;
return editor;
}
void MyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
...
}
void MyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
...
}
void MyItemDelegate::onEditorDestroyed(QObject* obj)
{
printf("editor %p destroyed\n", (void*) obj);
(*m_editorCount)--;
}
在某些情况下,例如当使用光标键移动到树中的下一个项目时,Qt将首先创建新的编辑器,然后销毁旧的编辑器。因此,m_editorCount
必须是一个整数而不是bool。
不幸的是,createEditor()
是一个const
函数。因此,你不能创建一个int
-member。相反,创建一个指向int
并使用它。
只是一个说明,我认为你的意思是* mutable *,而不是* volatile *。 – 2010-08-13 18:19:33
@Caleb - 你说得对。改变 - 并感谢指出。 – 2010-08-13 19:16:26
正如他在答复中指出,由弗洛里安Kusche,这不起作用,因为setModelData()如果编辑承诺只叫,但如果它的取消。 – emkey08 2014-03-29 12:53:48