Qt:如何使半透明,无窗,无铬窗口可拖动

Qt: How to make translucent, windowless, chromeless window draggable?

本文关键字:窗口 拖动 无窗 何使 半透明 Qt      更新时间:2023-10-16

我有一个基于半透明图像的窗口:

import QtQuick 1.1
import QtWebKit 1.1
  Image {
       source: "qrc:/assets/bg.png"
  }

主窗口中有类似的东西

#include "mainwindow.h"
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent)
    {
      setAttribute(Qt::WA_TranslucentBackground);
      setStyleSheet("background:transparent;");
      /* turn off window decorations */
      setWindowFlags(Qt::FramelessWindowHint);
      ui = new QDeclarativeView;
      ui->setSource(QUrl("qrc:/assets/ui.qml"));
      setCentralWidget(ui);
    }
    MainWindow::~MainWindow()
    {
        delete ui;
    }

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtDeclarative/QDeclarativeView>
namespace Ui {
    class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    QDeclarativeView *ui;
};
 #endif // MAINWINDOW_H

我想知道如何使我的窗口可在屏幕上拖动(用户按下图像和药物窗口..)?

重新实现mousePressEvent()mouseReleaseEvent()知道用户何时按住鼠标,然后重新实现mouseMoveEvent()如果用户按住鼠标,则移动小部件。

// **Untested code**
protected:
    virtual void mousePressEvent(QMouseEvent *event) { _mouseIsDown = true; }
    virtual void mouseReleaseEvent(QMouseEvent *event) { _mouseIsDown = false; }
    virtual void mouseMoveEvent(QMouseEvent *event) { if(_mouseIsDown) { move(event->pos() + globalPos()); } }
#include <QMouseEvent>
#include <Qpoint>
class MainWindow : public QMainWindow{
    ...
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    QPoint LastPoint;
    QPoint LastTopLeft;
    void mousePressEvent(QMouseEvent *event)
    {
        if (event->button() == Qt::LeftButton) {
             QPoint Point=event->globalPos();
             LastTopLeft=this->frameGeometry().topLeft();
             LastPoint=Point;
        }
    }
    void mouseMoveEvent(QMouseEvent *event)
    {
        if ((event->buttons() & Qt::LeftButton)) {
             const QPoint Point=event->globalPos();
             QPoint offset=Point-LastPoint;
             this->move(LastTopLeft+offset);
    }
    }
    ...
}

在我删除前两个声明后,它对我有用。