Qt 设置某个属性为Dialog的透明窗口一直附着在另一个窗口前方,考虑多种可能影响因素,源码实现
时间: 2023-10-02 11:05:14 浏览: 174
在 Qt 中设置一个透明的对话框窗口并让它附着在另一个窗口前方可以通过以下步骤实现:
1. 创建一个新的对话框窗口,并将其设置为透明。
```c++
QDialog *dialog = new QDialog(parent);
dialog->setWindowFlags(Qt::FramelessWindowHint);
dialog->setAttribute(Qt::WA_TranslucentBackground);
```
2. 将该对话框窗口的父窗口设置为前方窗口。
```c++
dialog->setParent(frontWindow);
```
3. 在前方窗口的事件过滤器中处理鼠标事件,使用户能够拖动对话框窗口。
```c++
bool FrontWindow::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress && obj == this) {
dragStartPosition = static_cast<QMouseEvent*>(event)->pos();
}
if (event->type() == QEvent::MouseMove && obj == this) {
if (!dragStartPosition.isNull()) {
QPoint pos = mapToGlobal(static_cast<QMouseEvent*>(event)->pos()) - dragStartPosition;
dialog->move(pos);
}
}
if (event->type() == QEvent::MouseButtonRelease && obj == this) {
dragStartPosition = QPoint();
}
return QObject::eventFilter(obj, event);
}
```
完整的源代码如下:
```c++
#include <QtWidgets>
class FrontWindow : public QWidget
{
public:
FrontWindow(QWidget *parent = nullptr) : QWidget(parent)
{
setFixedSize(300, 200);
setStyleSheet("background-color: lightblue;");
installEventFilter(this);
}
protected:
bool eventFilter(QObject *obj, QEvent *event) override
{
if (event->type() == QEvent::MouseButtonPress && obj == this) {
dragStartPosition = static_cast<QMouseEvent*>(event)->pos();
}
if (event->type() == QEvent::MouseMove && obj == this) {
if (!dragStartPosition.isNull()) {
QPoint pos = mapToGlobal(static_cast<QMouseEvent*>(event)->pos()) - dragStartPosition;
dialog->move(pos);
}
}
if (event->type() == QEvent::MouseButtonRelease && obj == this) {
dragStartPosition = QPoint();
}
return QObject::eventFilter(obj, event);
}
private:
QDialog *dialog = nullptr;
QPoint dragStartPosition;
void createDialog()
{
dialog = new QDialog(this);
dialog->setWindowFlags(Qt::FramelessWindowHint);
dialog->setAttribute(Qt::WA_TranslucentBackground);
dialog->setFixedSize(200, 100);
dialog->setStyleSheet("background-color: rgba(255, 255, 255, 100);");
dialog->move(mapToGlobal(rect().center() - dialog->rect().center()));
dialog->show();
}
void showEvent(QShowEvent *event) override
{
if (!dialog) {
createDialog();
}
QWidget::showEvent(event);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
FrontWindow frontWindow;
frontWindow.show();
return app.exec();
}
```
在上面的代码中,我们创建了一个前方窗口 `FrontWindow`,并实现了一个事件过滤器来处理鼠标事件。在该窗口的 `showEvent` 中创建了一个透明的对话框窗口 `dialog`,并将其父窗口设置为前方窗口。在前方窗口的事件过滤器中处理鼠标事件,将鼠标事件传递给对话框窗口并实现拖动。
阅读全文