我在Qt5中制作了一个无框窗口。现在,我需要指定一些可拖动区域(QFrame)来移动窗口。如果我像时钟示例中那样定义mouseMoveEvent()和mousePressEvent(),窗口就会变得完全可拖动......
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton)
{
move(event->globalPos() - dragPos);
event->accept();
}
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
dragPos = event->globalPos() - frameGeometry().topLeft();
event->accept();
}
}
我应该用mouseMoveEvent()和mousePressEvent()创建一个QFrame子类吗?
如果是,怎么样?
答案 0 :(得分:2)
您可以使用事件过滤器,在这种情况下,可以在不进行子类化的情况下完成此任务:
QPoint dragPos;//somewhere
//...
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == ui->frame && event->type() == QEvent::MouseButtonPress)
{
QMouseEvent *ev = static_cast<QMouseEvent *>(event);
if (ev->buttons() & Qt::LeftButton)
{
dragPos = ev->globalPos() - ui->frame->geometry().topLeft();
}
}
if (obj == ui->frame && event->type() == QEvent::MouseMove)
{
QMouseEvent *ev = static_cast<QMouseEvent *>(event);
if (ev->buttons() & Qt::LeftButton)
{
ui->frame->move(ev->globalPos() - dragPos);
}
}
return QObject::eventFilter(obj, event);
}
要使用eventFilter
,您还应该:
protected:
bool eventFilter(QObject *obj, QEvent *event);//in header
和
qApp->installEventFilter(this);//in constructor
使用此代码,我可以轻松拖动ui->frame