shapewidget.h
#ifndef SHAPEWIDGET_H #define SHAPEWIDGET_H #include <QtGui> class QPoint; class ShapeWidget : public QWidget { Q_OBJECT public: ShapeWidget(QWidget *parent = 0, Qt::WFlags flags = 0); ~ShapeWidget(); protected: void mousePressEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); private: QPoint dragPosition; }; #endif // SHAPEWIDGET_H
shapewidget.cpp
#include "shapewidget.h" #include <QPixmap> #include <QBitmap> ShapeWidget::ShapeWidget(QWidget *parent, Qt::WFlags flags) : QWidget(parent, flags) { QPixmap pix; //实例化一个位图对象 pix.load("images/tux.png", 0, Qt::AvoidDither| Qt::ThresholdDither | Qt::ThresholdAlphaDither); //加载掩码图像 resize(pix.size()); //设置图像的大小 setMask(pix.mask()); //抠除图像的白色区域实现不规则窗体 QPalette plt; //实例化调色板 plt.setBrush(QPalette::Window, QBrush(pix)); //将调色板的画刷设置为掩码位图,在不规则窗体上显示出掩码位图 setPalette(plt); //按调色板信息设置窗体 } ShapeWidget::~ShapeWidget() { } void ShapeWidget::mousePressEvent(QMouseEvent * event) { if (event->button() == Qt::LeftButton) { dragPosition = event->globalPos() - frameGeometry().topLeft(); event->accept(); } if (event->button() == Qt::RightButton) { close(); } } void ShapeWidget::mouseMoveEvent(QMouseEvent * event) { if (event->buttons() & Qt::LeftButton) { move(event->globalPos() - dragPosition); event->accept(); } }
shapewidget.cpp中第30行的frameGeometry().topLeft()仍然表示整个窗体的左上角,而不是所见不规则窗体的左上角。