qt::popup怎么跟随父窗口
时间: 2024-01-10 22:05:12 浏览: 119
您可以使用`QPopupWindow`类来实现弹出窗口,并使其跟随父窗口移动。首先,您需要创建一个`QPopupWindow`对象并将其设置为父窗口的子窗口。然后,您可以通过重写父窗口的`moveEvent`事件来更新弹出窗口的位置。
以下是一个示例代码片段,演示如何实现弹出窗口跟随父窗口移动:
```cpp
#include <QMainWindow>
#include <QPopupWindow>
#include <QMoveEvent>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
// 创建弹出窗口
popupWindow = new QPopupWindow(this);
popupWindow->setGeometry(100, 100, 200, 100);
// 设置弹出窗口样式
// ...
// 显示弹出窗口
popupWindow->show();
}
protected:
void moveEvent(QMoveEvent *event) override
{
// 获取父窗口的位置
QPoint parentPos = this->pos();
// 更新弹出窗口的位置
popupWindow->move(parentPos.x() + 50, parentPos.y() + 50);
QMainWindow::moveEvent(event);
}
private:
QPopupWindow *popupWindow;
};
```
在这个示例中,`MainWindow`类继承自`QMainWindow`,并重写了`moveEvent`事件。在`moveEvent`事件中,我们获取父窗口的位置,并根据需要更新弹出窗口的位置(这里的示例是在父窗口的右下方偏移50个单位)。请根据您的实际需求修改位置的计算方式。
注意,`QPopupWindow`是一个自定义的子窗口类,您需要根据自己的需求进行实现。另外,记得在适当的时候销毁弹出窗口对象,避免内存泄漏。
阅读全文
相关推荐


















