主要思路:
1:将窗体设为Qt::FramelessWindowHint(去掉标题栏)。
2:用一幅有部分区域是透明的图片作为程序的界面,并将图片透明的地方设为穿透。
3:重载程序的鼠标事件。
运行时截图(浅绿色的是桌面背景)
源代码:
- #include <QtGui>
- class IrregularWidget : public QWidget
- {
- Q_OBJECT
- public:
- IrregularWidget(QWidget *parent = 0);
- protected:
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void paintEvent(QPaintEvent *event);
- void enterEvent(QEvent *event);
- void leaveEvent(QEvent *event);
- private:
- QPoint m_CurrentPos;
- QPixmap m_Pixmap;
- };
- IrregularWidget::IrregularWidget(QWidget *parent)
- : QWidget(parent, Qt::FramelessWindowHint)
- {
- setWindowTitle("Irregular widget");
- //加载一幅有部分区域是透明的图片作为程序的界面
- m_Pixmap.load("delete.png");
- resize( m_Pixmap.size() );
- //不规则窗口的关键,将图片透明的地方设为穿透
- setMask( m_Pixmap.mask() );
- }
- void IrregularWidget::mousePressEvent(QMouseEvent *event)
- {
- //按住左键可以托动窗口,按下右键关闭程序
- if(event->button() == Qt::LeftButton)
- {
- m_CurrentPos = event->globalPos() - frameGeometry().topLeft();
- event->accept();
- }
- else if(event->button() == Qt::RightButton)
- close();
- }
- void IrregularWidget::mouseMoveEvent(QMouseEvent *event)
- {
- if (event->buttons() && Qt::LeftButton)
- {
- move(event->globalPos() - m_CurrentPos);
- event->accept();
- }
- }
- void IrregularWidget::paintEvent(QPaintEvent *event)
- {
- QPainter painter(this);
- painter.drawPixmap(0, 0, m_Pixmap);
- }
- void IrregularWidget::leaveEvent(QEvent *event)
- {
- //鼠标离开窗口时是普通的指针
- setCursor(Qt::ArrowCursor);
- }
- void IrregularWidget::enterEvent(QEvent *event)
- {
- //鼠标留在窗口上时是一个手指
- setCursor(Qt::PointingHandCursor);
- }
- #include "main.moc"
- int main(int argc, char *argv[])
- {
- QApplication app(argc, argv);
- IrregularWidget *widget = new IrregularWidget;
- widget->show();
- return app.exec();
- }
http://blog.csdn.net/small_qch/article/details/7054750