[英]Qt How to Prevent dropping item FROM application TO Windows File Explorer
我正在寻找一种干净且跨平台的方法来防止将项目从Qt应用程序拖放到Windows File Explorer(或其他等效于OS)。
下图显示了所需的行为:
我没有运气在网上找到示例或一起找到变通办法,但是似乎有一个设计良好且实现良好的解决方案随处可见,这是一个足够常见的用例。
我尝试过但没有的工作:
检测阻力并杀死它:
这是很棘手的(并且暂时无法使用),我希望您能为我提供一个更优雅的解决方案。
(更新-尝试更改mimeType,但Windows File Explorer仍然接受删除)
将MIME类型更改为自定义类型:
QTreeView
带有拖放功能的小部件”是带有QFileSystemModel
模型的QFileSystemModel
QFileSystemModel
并覆盖mimeTypes()
函数,如下面的代码 qDebug()
输出中,看起来好像正确设置了mimeType,但是Windows File Explorer仍然接受drop:/ QStringList MyFileSystemModel::mimeTypes() const { QStringList customMimeTypes; customMimeTypes << QString("UnicornsAndRainbows/uri-list"); qDebug() << "customMimeTypes: " << customMimeTypes; return customMimeTypes; }
如果有机会,请告诉我。
谢谢! :)
德米特里·索佐诺夫(Dmitry Sazonov)给出了正确的答案。 我将在下面解释如何实现它。 德米特里(Dmitry),如果您想要信任的话,请将其发布为答案,而不是发表评论,以便我接受。
实际上,我不得不修改QTreeView::mouseMoveEvent()
和QTreeView::dropEvent()
时,基于Dmitry的建议在问题更新上做错了什么是重写QFileSystemModel::mimeTypes()
QTreeView::dropEvent()
。
//---------------------------------------------------------
void MyTreeView::mouseMoveEvent( QMouseEvent *event )
{
if( !(event->buttons() & Qt::LeftButton) )
{
return; // we only care about left mouse drags at the moment
}
if( (event->pos() - dragStartPosition).manhattanLength() < QApplication::startDragDistance() )
{
return; // a buffer when calculating waht qualifies as a "drag event"
}
QDrag *drag = new QDrag( this );
QMimeData *mimeData = new QMimeData();
QByteArray data;
const QStringList selectedPaths = this->getSelectedPaths(); // custom helper method
foreach( QString path, selectedPaths )
{
data.append( path ).append( ";" ); // using ';' as path deliminator
}
data.chop( 1 );
//--- this sets the custom MIME Type filter
mimeData->setData( CUSTOM_MIMETYPE_STRING, data );
drag->setMimeData( mimeData );
Qt::DropAction dropAction = drag->exec( Qt::CopyAction );
}
//---------------------------------------------------------
void MyTreeView::dropEvent( QDropEvent *event )
{
// ...
QList<QByteArray> paths;
//--- this filters based on our custom MIME Type
paths = event->mimeData()->data( CUSTOM_MIMETYPE_STRING ).split(';');
foreach( QByteArray path, paths )
{
// do something with the file paths
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.