QT窗口阴影+拖动
QT
去除默认边框,为界面添加阴影,实现拖动效果。只是示例,没有完成关闭等按钮,根据具体情况添加,可以使用ui设计画一个。
#include <QApplication>
#include <QWidget>
#include <QPoint>
#include <QMouseEvent>
#include <QGraphicsDropShadowEffect>
#include <QVBoxLayout>
class Window:public QWidget
{
Q_OBJECT
public:
Window(QWidget* parent=nullptr){
this->setWindowFlags(Qt::FramelessWindowHint);
this->setAttribute(Qt::WA_TranslucentBackground);
// this->setContentsMargins(3,5,5,3); /*左上右下*/
QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
shadow_effect->setOffset(0, 0);
shadow_effect->setColor(Qt::black);
shadow_effect->setBlurRadius(25);
QWidget* container = new QWidget(this);
container->setFixedSize(480,360);
container->setStyleSheet("background-color:red;");
container->setGraphicsEffect(shadow_effect);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(container);
this->setLayout(layout);
}
protected:
void mousePressEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
/* 计算鼠标点击位置相对于窗口内部的偏移量*/
m_offset = event->globalPosition().toPoint() - frameGeometry().topLeft();
event->accept();
}
}
void mouseMoveEvent(QMouseEvent *event) override {
if (event->buttons() & Qt::LeftButton) {
/* 移动窗口 */
move(event->globalPosition().toPoint() - m_offset);
event->accept();
}
}
private:
QPoint m_offset;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Window w;
w.show();
return a.exec();
}
#include "main.moc"
效果