Qt 拖动事件

文章目录

  • [1 自定义控件 TextEdit](#1 自定义控件 TextEdit)
  • [2 实现打开文件功能](#2 实现打开文件功能)
  • [3 实现鼠标滚轮放大字体](#3 实现鼠标滚轮放大字体)

QEvent::DragEnter

当拖动文件进入到窗口/控件中时,触发该事件,它对应的子类是QDragEnterEvent

QEvent::DragLeave

当拖动文件离开窗口/控件时,触发该事件,它对应的子类是QDragLeaveEvent

QEvent::DragMove

当拖动文件在窗口/控件中移动时,触发该事件,它对应的子类是QDragMoveEvent

QEvent::Drop

当拖动文件在窗口/控件中移动时,触发该事件,它对应的子类是QDragMoveEvent

1 自定义控件 TextEdit

自定义一个标签控件TextEditx,让它继承自QTextEdit,然后重写拖放相关的函数。

添加自定义控件类TextEditX ,在 texteditx.h 文件中

c++ 复制代码
// TextEditX.h
protected:
    // 重写父类的方法
    void dragEnterEvent(QDragEnterEvent *e);
    void dragMoveEvent(QDragMoveEvent *e);
    void dragLeaveEvent(QDragLeaveEvent *e);
    void dropEvent(QDropEvent *e);

在texteditx.cpp 文件中

c++ 复制代码
// TextEditX.cpp
TextEditX::TextEditX(QWidget *parent) : QTextEdit{parent} {
    // 部件将接受鼠标拖放事件
    this->setAcceptDrops(true);
}

void TextEditX::dragEnterEvent(QDragEnterEvent *e) {
    qDebug() << "dragEnterEvent";
    // 默认情况下,窗口部件不接受拖动
    e->acceptProposedAction();
}

void TextEditX::dragMoveEvent(QDragMoveEvent *e) {
    qDebug() << "dragMoveEvent";
}

void TextEditX::dragLeaveEvent(QDragLeaveEvent *e) {
    qDebug() << "dragLeaveEvent";
}

void TextEditX::dropEvent(QDropEvent *e) {
    qDebug() << "dropEvent";
}

2 实现打开文件功能

在texteditx.cpp文件中

c++ 复制代码
// texteditx.cpp
void TextEditX::dropEvent(QDropEvent *e) {
    qDebug() << "dropEvent";
    QList<QUrl> urls = e->mimeData()->urls();
    if (urls.isEmpty()) {
        return;
    }
    // 获取这个文件名
    QString fileName = urls.first().toLocalFile();
    qDebug() << urls.first() << "\n" << fileName;

    // 打开文件
    QFile file(fileName);

    // 打开失败返回 false
    if (file.open(QIODevice::ReadOnly)) {
        setPlainText(file.readAll());
    }
}

3 实现鼠标滚轮放大字体

在 texteditx.h 文件中

c++ 复制代码
protected:
    // 重写滚轮事件
    void wheelEvent(QWheelEvent *e);

在 texteditx.cpp 文件中

c++ 复制代码
void TextEditX::wheelEvent(QWheelEvent *e) {
    if (QApplication::keyboardModifiers() == Qt::ControlModifier) {
        if (e->angleDelta().y() > 0) {
            // 滚轮远离使用者, 进行放大
            this->zoomIn();
        } else {
            // 滚轮靠近使用者, 进行缩小
            this->zoomOut();
        }
    } else {
        // 调用父类的实现, 否则无法实现文本的上下滚动
        QTextEdit::wheelEvent(e);
    }
}
相关推荐
geovindu12 分钟前
python:DecisionTree
开发语言·后端·python·算法
ShineWinsu41 分钟前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
geovindu2 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
闻缺陷则喜何志丹2 小时前
【数论】P10136 [USACO24JAN] Cowlendar S|普及+
c++·数学·数论·洛谷
apcipot_rain3 小时前
某游戏公司C++游开实习 机试复盘
c++·游戏
炸膛坦客5 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++
夜不会漫长6 小时前
C++:C++11特性
开发语言·c++·算法
apcipot_rain7 小时前
C++转java日记(13)
java·开发语言
郝学胜-神的一滴7 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
吃我一窝jio8 小时前
Python与Redis集合深度解析
开发语言·redis·笔记·python