How disable QMouseMoveEvent of QPushButton in user-defined titlebar ?



  • When i design a titlebar myself, the QPushButton of Minimize,Maxmize,Close in the titlebar will also trigger QMouseMoveEvent which I don't want.

    void TitleBar::mousePressEvent(QMouseEvent *event)
    {
        if(event->button() == Qt::LeftButton){    
            relativePos = event->pos();
        }
    }
    
    void TitleBar::mouseMoveEvent(QMouseEvent *event)
    {    
        emit moveMainWindow(event->globalPos() - relativePos);
    }
    

    Source code: https://github.com/sonichy/NeteaseMusic

    替代文字



  • @sonichy

    You can simply set the flag to handle it. like this:

    // in titlebar.h
        bool isClicked{false};
        void mouseReleaseEvent(QMouseEvent *event);
    
    // in titlebar.cpp
    void TitleBar::mousePressEvent(QMouseEvent *event)
    {
        if(event->button() == Qt::LeftButton){
            //qDebug() << "mousePress" << event->pos();
            relativePos = event->pos();
            isClicked = true;
        }
    }
    
    void TitleBar::mouseMoveEvent(QMouseEvent *event)
    {
        //qDebug() << event->globalPos() << "-" << relativePos << "=" << event->globalPos() - relativePos;
        if (isClicked)
            emit moveMainWindow(event->globalPos() - relativePos);
    }
    
    void TitleBar::mouseReleaseEvent(QMouseEvent *event)
    {
        Q_UNUSED(event)
        isClicked = false;
    }
    
    


  • You could use an eventFilter (http://doc.qt.io/archives/qt-4.8/qobject.html#eventFilter).

    Most of the time, just using mousePressEvent is better if it's enough for what you want.
    But if you need to be able to check which item is receiving an event, you can check it by testing the QObject * argument in the eventFilter method.



  • @Andeol Under your advice, I solved the problem!

    TitleBar::TitleBar(QWidget *parent) : QWidget(parent)
    {
        ...
        pushButton_minimize->installEventFilter(this);
        pushButton_maximize->installEventFilter(this);
        pushButton_close->installEventFilter(this);
        ...
    }
    
    bool TitleBar::eventFilter(QObject *obj, QEvent *event)
    {
        if ( (obj == pushButton_minimize || obj == pushButton_maximize || obj == pushButton_close) && event->type() == QEvent::MouseMove ) {
            return true;    // filter
        } else {
            return false;
        }
        // pass the event on to the parent class
        return QWidget::eventFilter(obj, event);
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.