1.相关说明
重写resizeEvent(这个按需重写)、dragEnterEvent(拖拽事件函数)、dropEvent(放下事件函数),可以将本地图片拖拽到label标签中
2.相关界面
文章来源:https://www.toymoban.com/news/detail-807796.html
文章来源地址https://www.toymoban.com/news/detail-807796.html
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();
}
}
到了这里,关于Qt拖拽事件简单实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!