美文网首页Qt
使用QT实现可以拖动的按钮

使用QT实现可以拖动的按钮

作者: wuguandong | 来源:发表于2019-08-28 13:00 被阅读0次

    效果演示

    实现步骤

    思路:
    创建DragPushButton类继承自QPushButton,重写mousePressEventmouseMoveEvent方法。

    1. dragpushbutton.h文件

    #ifndef DRAGPUSHBUTTON_H
    #define DRAGPUSHBUTTON_H
    
    #include <QWidget>
    #include <QPushButton>
    #include <QMouseEvent>
    #include <QDebug>
    
    class DragPushButton : public QPushButton
    {
        Q_OBJECT
    public:
        explicit DragPushButton(QWidget *parent = nullptr);
    
    protected:
        void mousePressEvent(QMouseEvent *event);
        void mouseMoveEvent(QMouseEvent *event);
    
    private:
        QPoint pressPoint;
    };
    
    #endif // DRAGPUSHBUTTON_H
    

    2. dragpushbutton.cpp文件

    #pragma execution_character_set("utf-8")
    #include "dragpushbutton.h"
    
    DragPushButton::DragPushButton(QWidget *parent) : QPushButton(parent){}
    
    void DragPushButton::mousePressEvent(QMouseEvent *event)
    {
        if(event->button() == Qt::LeftButton){
            this->raise(); //将此按钮移动到顶层显示
            this->pressPoint = event->pos();
        }
    }
    
    void DragPushButton::mouseMoveEvent(QMouseEvent *event)
    {
        if(event->buttons() == Qt::LeftButton){
            this->move(this->mapToParent(event->pos() - this->pressPoint));
    
            //防止按钮移出父窗口
            if(this->mapToParent(this->rect().topLeft()).x() <= 0){
                this->move(0, this->pos().y());
            }
            if(this->mapToParent(this->rect().bottomRight()).x() >= this->parentWidget()->rect().width()){
                this->move(this->parentWidget()->rect().width() - this->width(), this->pos().y());
            }
            if(this->mapToParent(this->rect().topLeft()).y() <= 0){
                this->move(this->pos().x(), 0);
            }
            if(this->mapToParent(this->rect().bottomRight()).y() >= this->parentWidget()->rect().height()){
                this->move(this->pos().x(), this->parentWidget()->rect().height() - this->height());
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:使用QT实现可以拖动的按钮

        本文链接:https://www.haomeiwen.com/subject/ffppectx.html