È possibile creare una sottoclasse QTableView
per poter accedere alla funzione state()
, che purtroppo è protetta. Tuttavia, non l'ho provato.
Se si dispone già di una sottoclasse QStyledItemDelegate
, è possibile utilizzarla per tracciare se un editor è attualmente aperto. Tuttavia, non è possibile utilizzare solo setEditorData
/setModelData
, perché setModelData
non verrà chiamato, quando l'utente annulla la modifica. Invece, puoi tenere traccia della creazione e della distruzione dell'editor stesso.
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);
};
Attuazione:
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)--;
}
In alcuni casi, ad esempio quando si passa all'elemento successivo nell'albero usando i tasti cursore, Qt creerà prima il nuovo editor e quindi distruggerà quello vecchio. Quindi, m_editorCount
deve essere un numero intero anziché un valore bool.
Sfortunatamente, createEditor()
è una funzione const
.Pertanto, non è possibile creare un int
-member. Invece, crea un puntatore a int
e usalo.
Solo una nota, penso che intendessi * mutevole *, non * volatile *. –
@Caleb - Hai ragione. Modificato - e grazie per averlo indicato. –
Come già indicato da Florian Kusche nella sua risposta, questo non funziona perché setModelData() viene chiamato solo se la modifica viene eseguita, ma non se è annullata. – emkey08