void MyWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { QDrag *drag = new QDrag(this); QMimeData *mimeData = new QMimeData; mimeData->setText("Hello World!"); drag->setMimeData(mimeData); drag->exec(Qt::CopyAction); } }
void MyWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton && event->pos().x() >= label->x() && event->pos().y() >= label->y()) { QDrag *drag = new QDrag(this); QMimeData *mimeData = new QMimeData; mimeData->setImageData(label->pixmap()->toImage()); drag->setPixmap(*label->pixmap()); drag->setMimeData(mimeData); drag->exec(Qt::MoveAction); } }This code starts a drag operation when the user presses the left mouse button on a QLabel widget that contains an image. It creates a QDrag object, sets a QMimeData object with the image data, and executes the drag operation with move action while displaying the pixmap of the QLabel widget. Package Library: Qt Core Library (QtCore) and Qt GUI Module (QtGui)