Qt:如何制作半透明,无窗,无窗的可拖动窗户?

时间:2012-04-19 13:13:43

标签: c++ qt window qml

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

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

我想知道如何让我的窗口可以在屏幕上拖动(用户按下图像和毒品窗口......)?

3 个答案:

答案 0 :(得分:1)

重新实现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()); } }

答案 1 :(得分:0)

#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);
    }
    }
    ...
}

答案 2 :(得分:0)

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