Qt拖拽事件简单实现

发布时间:2024年01月20日

1.相关说明

重写resizeEvent(这个按需重写)、dragEnterEvent(拖拽事件函数)、dropEvent(放下事件函数),可以将本地图片拖拽到label标签中

2.相关界面

?

3.相关代码

#include "widget.h"
#include "ui_widget.h"
#include <QDragEnterEvent>
#include <QMimeData>
#include <QFileInfo>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setAcceptDrops(true);
    ui->plainTextEdit->setAcceptDrops(false);
    ui->label->setAcceptDrops(false);
    ui->label->setScaledContents(true);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::resizeEvent(QResizeEvent *event)
{
    QSize sz = ui->plainTextEdit->size();
    ui->plainTextEdit->move(5, 5);
    ui->label->move(5, sz.height()+10);
    ui->plainTextEdit->resize(this->width()-10, sz.height());
    ui->label->resize(this->width()-10, this->height()-sz.height()-20);
    event->accept();
}

void Widget::dropEvent(QDropEvent *event)
{
    QString fullPath = event->mimeData()->urls().at(0).path();
    fullPath = fullPath.right(fullPath.length()-1);
    QPixmap pixmap(fullPath);
    ui->label->setPixmap(pixmap);
    event->accept();
}

void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    ui->plainTextEdit->clear();
    ui->plainTextEdit->appendPlainText("dragEvent事件,mimeData的format:");
    for(auto &item : event->mimeData()->formats()){
        ui->plainTextEdit->appendPlainText(item);
    }
    ui->plainTextEdit->appendPlainText("dragEvent事件,mimeData的urls:");
    for(auto &item : event->mimeData()->urls()){
        ui->plainTextEdit->appendPlainText(item.path());
    }
    if(event->mimeData()->hasUrls()){
        QString filename = event->mimeData()->urls().at(0).fileName();
        QFileInfo fileInfo(filename);
        QString ex = fileInfo.suffix().toUpper();
        if(ex == "JPG"){
            event->acceptProposedAction();
        } else {
            event->ignore();
        }
    } else {
        event->ignore();
    }
}

文章来源:https://blog.csdn.net/hdsHDS6/article/details/135709362
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。