Qt拖拽事件简单实现

1.相关说明

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

2.相关界面

Qt拖拽事件简单实现_第1张图片 

Qt拖拽事件简单实现_第2张图片

3.相关代码

#include "widget.h"
#include "ui_widget.h"
#include 
#include 
#include 

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

你可能感兴趣的:(Qt6,qt6.3)