在QT 5中拖动QWidget [英] Dragging a QWidget in QT 5

查看:257
本文介绍了在QT 5中拖动QWidget的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须做一些像iOS界面,3x3字段的图标,可以拖动来改变他们的位置,然后记住它在XML文件中。我决定使用Grid类(QWidget是父类)作为容器,我自己的clas从QWidget继承为元素。现在我正在尝试学习如何执行拖放为QWidget下降,但似乎你只能放在一个QWidget上,但是拖动它是不可能的。
是真的还是只是被阻止?我该如何移动这个东西? x.x

I have to make something like iOS interface, 3x3 field of icons that can be dragged to change their position, and then remember it in XML file. I decided to use Grid class (QWidget is parent) as a container and my own clas inherited from QWidget as elements. Now I'm trying to learn how to perform a drag & drop for QWidget, but it seems like you are only able to drop onto a QWidget, but it's impossible to drag it. Is it true or just I'm being retard? How do I move this thing? x.x

推荐答案

拖动窗口小部件并不那么容易。很多编码你必须自己做。

Dragging a widget isn't that easy. Plenty of coding you have to do yourself.

Qt文档

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton
        && iconLabel->geometry().contains(event->pos())) {

        QDrag *drag = new QDrag(this);
        QMimeData *mimeData = new QMimeData;

        mimeData->setText(commentEdit->toPlainText());
        drag->setMimeData(mimeData);
        drag->setPixmap(iconPixmap);

        Qt::DropAction dropAction = drag->exec();
        ...
    }
}

这意味着,您的小部件收到要拖动的消息,例如像一个mousepress,它必须创建一个QDrag对象。

This means, when your widget receives a message that it is to be dragged, e.g. like with a mousepress, it has to create a QDrag object.

在QDrag对象中,您可以设置一个pixmap,代表您拖动的小部件。如果您现在隐藏您的小部件,那么看起来好像您的鼠标指针抓住小部件。

In the QDrag object you can set a pixmap, which represents your dragged widget. If you hide your widget at this point, it looks like as if your mouse pointer 'took' the widget.

此外,您需要一个QMimeData对象。在这个你可以放入各种数据,这描述你的小部件。在您的用例中,允许您识别您的部件。因为,这里是困难的部分:你必须做自己的移动。

Additionally you need a QMimeData object. In this you can put all kinds of data, which describes your widget. In your use case something which allows you to identify your widget. Because, and here comes the difficult part: You have to do the moving yourself.

作为网格的父级的窗口小部件接收删除事件,并从mime数据读取,该窗口小部件希望我移动。从QDropEvent可以看出要移动的部件。这就是你必须编写的代码:实际重新定位你的网格布局。并且不要忘记更新xml。

The widget, which is the grid's parent, receives the drop event and reads from the mime data, which widget wishes to me moved. From the QDropEvent it gets the point where the widget is to be moved. That's what you have to code: The actual repositioning in your grid layout. And don't forget to update the xml.

这篇关于在QT 5中拖动QWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆