码迷,mamicode.com
首页 > Windows程序 > 详细

Qt自绘窗体

时间:2015-04-15 00:45:50      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:

也许大部分情况下我们不需要自己手动绘制一个窗体,大部分可以通过图片来实现,本篇仅以学习的态度来初略的理解Qt界面的自定义绘制功能。

 

本篇将实现以下功能:

1、绘制一个椭圆形

2、支持界面的移动操作

3、Esc退出

头文件:

  1: #include <QDialog>
  2: 
  3: class DrawDialog : public QDialog
  4: {
  5:     Q_OBJECT
  6: 
  7: public:
  8:     explicit DrawDialog(QWidget *parent = 0);
  9:     void mousePressEvent(QMouseEvent *event);
 10:     void mouseMoveEvent(QMouseEvent *event);
 11:     void paintEvent(QPaintEvent *event) ;
 12:     void keyPressEvent( QKeyEvent * event );
 13: private:
 14:     QPoint m_CurrentPos;
 15: };

 

实现:

  1: DrawDialog::DrawDialog(QWidget *parent) :
  2:     QDialog(parent)
  3: {
  4:     //让程序无边框
  5:     setWindowFlags( Qt::FramelessWindowHint );
  6:     //让程序背景透明
  7:     setAttribute(Qt::WA_TranslucentBackground, true);
  8: }
  9: 
 10: void DrawDialog::mousePressEvent(QMouseEvent *event)
 11: {
 12:     //当鼠标左键按下时,记录当前位置
 13:     if(event->button() == Qt::LeftButton)
 14:     {
 15:         m_CurrentPos = event->globalPos() - frameGeometry().topLeft();
 16:         event->accept();
 17:     }
 18:     QDialog::mousePressEvent(event);
 19: }
 20: void DrawDialog::mouseMoveEvent(QMouseEvent *event)
 21: {
 22:     //支持窗体移动
 23:     if (event->buttons() & Qt::LeftButton)
 24:     {
 25:         move(event->globalPos() - m_CurrentPos);
 26:         event->accept();
 27:     }
 28:     QDialog::mouseMoveEvent(event);
 29: }
 30: 
 31: //绘制图形
 32: void DrawDialog::paintEvent(QPaintEvent *event)
 33: {
 34:     QPainter painter(this);
 35:     //反走样
 36:     painter.setRenderHint(QPainter::Antialiasing,true);
 37: 
 38:     painter.setPen( QPen(Qt::black, 2) );
 39:     painter.setBrush( Qt::black );
 40:     QRect rect(10,10,200,260);
 41:     //绘制一个鸭蛋
 42:     painter.drawEllipse(rect);
 43: }
 44: 
 45:  void DrawDialog::keyPressEvent( QKeyEvent * event )
 46:  {
 47:      //按下esc键时,关闭
 48:      if(event->key() == Qt::Key_Escape)
 49:      {
 50:          close();
 51:      }
 52:  }

 

 

图片效果(背景是我的桌面)

技术分享

Qt自绘窗体

标签:

原文地址:http://www.cnblogs.com/lingluotianya/p/4427225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!