我在实现带有可通过拖放重新排序的自定义项的 QListWidget 时遇到问题。问题是当我快速双击(非常短的拖放)某个项目时,该项目有时会从 QListWidget 中消失。
这是我的小部件的构造函数:
ListPopisiDragDrop::ListPopisiDragDrop(QWidget *parent) :
QListWidget(parent)
{
setSelectionMode(QAbstractItemView::SingleSelection);
setDragEnabled(true);
viewport()->setAcceptDrops(true);
setDefaultDropAction(Qt::MoveAction);
setDropIndicatorShown(true);
setDragDropMode(QAbstractItemView::InternalMove);
}
还有放置事件:
void ListPopisiDragDrop::dropEvent(QDropEvent *event){
int startRow=currentIndex().row();
QListWidget::dropEvent(event);
int endRow=currentIndex().row();
//more code...
}
自定义项目是通过实现 QAbstractItemDelegate 中的 Paint() 和 sizeHint() 函数来创建的。
当出现项目消失的问题时,甚至不会调用 dropEvent。
我真的不知道发生了什么,也不知道我是否做错了什么。如有任何帮助,我们将不胜感激。
谢谢!
编辑: 我正在 Symbian S60 第 5 版手机上运行该应用程序。
编辑2: 如果我将此行添加到构造函数中:
setDragDropOverwriteMode(true);
列表中的项目仍然消失,但空行保留在原来的位置。
编辑3: 我添加了以下代码来查看发生了什么:
bool ListPopisiDragDrop::event(QEvent *e){
qDebug()<<"new event, type: "<<e->type()<<", listCount: "<<this->count();
QListWidget::event(e);
}
当调用 drop 事件时,我还打印了“drop event”。这给了我以下输出:
...
[Qt Message] new event, type: 12 , listCount: 2
[Qt Message] new event, type: 12 , listCount: 2
[Qt Message] new event, type: 68 , listCount: 2
[Qt Message] DROPEVENT
[Qt Message] new event, type: 71 , listCount: 2
[Qt Message] new event, type: 12 , listCount: 2
[Qt Message] new event, type: 12 , listCount: 2
[Qt Message] new event, type: 68 , listCount: 2
[Qt Message] DROPEVENT
[Qt Message] new event, type: 71 , listCount: 2
[Qt Message] new event, type: 12 , listCount: 2
[Qt Message] new event, type: 12 , listCount: 2
[Qt Message] new event, type: 12 , listCount: 2
[Qt Message] new event, type: 68 , listCount: 2
[Qt Message] new event, type: 12 , listCount: 1
[Qt Message] new event, type: 12 , listCount: 1
[Qt Message] new event, type: 1 , listCount: 1
...
如您所见,在事件类型 68 之后,listCount 从 2 更改为 1(一项消失)。我还是没明白问题出在哪里......
编辑4: 即使我不使用自定义项目,我也会有相同的行为。还是不明白哪里出了问题。
编辑5: 在移动设备上测试时,甚至 [1] 中的示例也具有相同的行为。会不会是Qt版本的问题?我正在使用 Qt for Symbian 设备版本 4.6.3...
[1]http://www.java2s.com/Code/Cpp/Qt/QListWidgetdraganddrop.htm
最佳答案
我可以想到这种行为的两个原因:信号 itemDoubleClicked 在您的 QListWidget 中的某处处理并做了一些意想不到的事情,或者当源和目标相同时,dropEvent 中的“更多代码”做了一些不好的事情(您可以检查是否startRow 等于 endRow,在这种情况下不执行任何操作)。
编辑:
这个程序适合您吗:
#include <QApplication>
#include <QListWidget>
int main(int argc, char **argv)
{
QApplication a(argc, argv);
QListWidget lw;
for(int i = 1; i < 10; ++i)
lw.addItem(new QListWidgetItem(QString("Item %1").arg(i)));
lw.setDragEnabled(true); // ***
lw.viewport()->setAcceptDrops(true); // ***
lw.setDefaultDropAction(Qt::MoveAction); // ***
lw.setDropIndicatorShown(true); // ***
lw.setDragDropMode(QAbstractItemView::InternalMove);
lw.show();
a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
a.exec();
}
可以删除三颗星的行。这个程序适用于 Windows XP 和 Qt 4.7.1,用 VS2010 编译。
关于qt - QListWidget 拖放项目从 Symbian 列表中消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4536439/