我想摆脱我的应用程序的标题和边框,但为此我需要能够通过在 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/