c++ - QT通过单击菜单栏c++移动整个窗口/应用程序

标签 c++ qt

我想摆脱我的应用程序的标题和边框,但为此我需要能够通过在 menuBar 上拖动来移动窗口。我发现的两种方法是:

void TopMenuBar::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void TopMenuBar::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - dragPosition);
        event->accept();
    }
}

但是,如果我把它放在 MainWindow 中,无论您点击什么,它都会四处移动,如果我把它放在自定义 QMenuBar 中,它只会在窗口内移动菜单栏。我还尝试在对象之间做一些信号和槽技巧(比如将 mousePressEvent 保留在 menuBar 中,将 mouseMoveEvent 保留在 MainWindow 中),但趋势是窗口将“跳转”到鼠标指针所在的位置,而不是平滑地移动它。

还有其他人对此有解决方案吗?

环境是Windows

最佳答案

这肯定会起作用 - 刚刚检查过。在 MainWindow 构造函数中调用 ui->menuBar->installEventFilter(this);

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->menuBar)
    {
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
            if (mouse_event->button() == Qt::LeftButton)
            {
                dragPosition = mouse_event->globalPos() - frameGeometry().topLeft();
                return false;
            }
        }
        else if (event->type() == QEvent::MouseMove)
        {
            QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
            if (mouse_event->buttons() & Qt::LeftButton)
            {
                move(mouse_event->globalPos() - dragPosition);
                return false;
            }
        }


    }
    return false;
}

关于c++ - QT通过单击菜单栏c++移动整个窗口/应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41162621/

相关文章:

c++ - C++ 模板是否可以针对改进代码的条件执行此操作?

c++ - 在VC++中获取读访问冲突异常如何处理这个异常?

c++ - 从样式表更改为默认样式

qt - 将QDomElement转换为QString/Container类

c++ - QAbstractListModel 的子类只能作为 QML 中的父类(super class)使用

c++ - 在 Q_OBJECT 的子类中提供 Q_PROPERTY 会导致错误 1

c++ - 为什么要这样进行乘法?

c++ - 需要在 C++ 中创建多个动态数组

c++ - 编译时如何使用外部模板参数

c++ - QProcess::execute ("clear") 问题