Qt QItemDelegate提交数据并关闭鼠标编辑器离开视图控件(listView)

问题描述:

当鼠标离开它时,我有一个关闭listView的编辑器的问题。我设法解决了我的问题。这对我并不明显,所以我决定发布我的解决方案:Qt QItemDelegate提交数据并关闭鼠标编辑器离开视图控件(listView)

在委托头文件中,Ive创建了一个编辑器小部件指针,并且在构造函数中,我给了他Q_NULLPTR的值。

//in header file of Delegate 
mutable QWidget *myCustomWidget; 

//in the source file of Delegate 
MyItemDelegate::MyItemDelegate(QObject *parent) : QStyledItemDelegate(parent), 
    myCustomWidget(Q_NULLPTR) 
{ 
} 

然后在createEditor:

QWidget *MyItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const 
{ 
myCustomWidget= new KontaktForm(parent); 
myCustomWidget->autoFillBackground(); 

return myCustomWidget; 
} 

在MyListView头文件我已经创建了一个信号saveToModelFromEditor();和emited在

void MyListView::leaveEvent(QEvent *event) 
{ 
emit saveToModelFromEditor(); 

QListView::leaveEvent(event); 
} 

的功能commitData到模型中的信号,并关闭编辑器,如果有人想它关闭:

void MyItemDelegate::commitAndSaveData() 
{ 
if(kontaktForm!=Q_NULLPTR){ 

// after testing the UI I've decided, that the editor should remain open, and just commit data 

emit commitData(kontaktForm); 

// emit closeEditor(kontaktForm); 
} 
} 

最后我用信号和槽机制连接信号从listView到编辑器中的插槽

connect(treeView,SIGNAL(saveToModelFromEditor()),itemDelegate,SLOT(commitAndSaveData())); 

我有来自不同社区(VoidRealms脸书组)的帮助。

希望这可以帮助这里的人。

在委托头文件中,我创建了一个编辑器小部件指针,在构造函数中,我给了他Q_NULLPTR的值。

//in header file of Delegate 
mutable QWidget *myCustomWidget; 

//in the source file of Delegate 
MyItemDelegate::MyItemDelegate(QObject *parent) : QStyledItemDelegate(parent), 
    myCustomWidget(Q_NULLPTR) 
{ 
} 

然后在createEditor:

QWidget *MyItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const 
{ 
myCustomWidget= new KontaktForm(parent); 
myCustomWidget->autoFillBackground(); 

return myCustomWidget; 
} 

在MyListView头文件我已经创建了一个信号saveToModelFromEditor();和emited在

void MyListView::leaveEvent(QEvent *event) 
{ 
emit saveToModelFromEditor(); 

QListView::leaveEvent(event); 
} 

的功能commitData到模型中的信号,并关闭编辑器,如果有人想它关闭:

void MyItemDelegate::commitAndSaveData() 
{ 
if(kontaktForm!=Q_NULLPTR){ 

// after testing the UI I've decided, that the editor should remain open, and just commit data 

emit commitData(kontaktForm); 

// emit closeEditor(kontaktForm); 
} 
} 

最后我用信号和槽机制连接信号从listView到编辑器中的插槽

connect(treeView,SIGNAL(saveToModelFromEditor()),itemDelegate,SLOT(commitAndSaveData())); 

我从不同的社区(VoidRealms facebook group)得到了帮助。

希望这可以帮助这里的人。