Drag and Drop QWidget in QT 5

I need to do something like an iOS interface, a 3x3 icon field that you can drag to reposition them and then remember it in an XML file. I decided to use the Grid class (QWidget is parent) as a container and my own classes inherited from QWidget as elements. Now I'm trying to learn how to drag and drop for a QWidget, but it looks like you can only put on a QWidget, but it cannot be dragged. Is this true or is they just holding me back? How do I move this thing? xx

+6
source share
3 answers

Dragging a widget is not so simple. You need to do a lot of coding.

From Qt Docs :

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(); ... } } 

This means that when your widget receives a message about dragging it, for example, like using the mouse, it should create a QDrag object.

In the QDrag object, you can set a pixmap representing your draggable widget. If you hide your widget at this moment, it looks as if your mouse pointer β€œtook” the widget.

In addition, you need a QMimeData object. In this you can put all kinds of data that describe your widget. In your case, use something that allows you to identify your widget. Because, and here comes the difficult part: you must move yourself.

The widget that is the parent of the grid receives the drop event and reads from the mime data that the widget wishes me to move. From QDropEvent, it gets the point at which the widget should move. This is what you need to code: the actual move in the grid layout. And do not forget to update xml.

+3
source

do the trick then you can also drag the QWidget,

 QPixmap *widgetPixmap = new QPixmap; yourWidget->render(widgetPixmap); // rendering the current widget to t_iconTPixmap 

Now use widgetPixmap as pixmap for yourDragObject->setPixmap();

For instance,

 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()); QPixmap *widgetPixmap = new QPixmap; yourWidget->render(widgetPixmap); drag->setMimeData(mimeData); drag->setPixmap(widgetPixmap); Qt::DropAction dropAction = drag->exec(); ... } } 
+3
source

The Qt wiki contains a QtQuick example on how to emulate an iOS icon interface with less than 80 lines of code.

You can find it here .

0
source

Source: https://habr.com/ru/post/951962/


All Articles