c++qtwindowmouseeventmove

How to move window using custom titleBar in Qt


I'm beginner in Qt and I want to drag and move Window using my own custom titleBar(QLabel).

The Qt code:

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    mpos = event->pos();
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) 
    {
        QPoint diff = event->pos() - mpos;
        QPoint newpos = this->pos() + diff;
        this->move(newpos);
    }
}

This code allow me to move window by mouse pressed on any QWidget but I want to move window by mouse pressed on QLabel.


Solution

  • I suggest you to use eventFilter to get event MousePress and MouseRelease:

    void MainApp::mousePressEvent(QMouseEvent *event)
    {
        current = event->pos();
    }
    
    void MainApp::mouseMoveEvent(QMouseEvent *event)
    {
        if(pressed)
            this->move(mapToParent(event->pos() - current));
    }
    
    bool MainApp::eventFilter(QObject *object, QEvent *event)
    {
        if (object == ui->label && event->type() == QEvent::MouseButtonPress)
        {
            pressed = true;
            return true;
        }
        if (object == ui->label && event->type() == QEvent::MouseButtonRelease)
        {
            pressed = false;
            return true;
        }
        else
            return false;
    }
    

    This is a sample project for your question on github download here.