C++优雅之旅

探索C++

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  15 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks
  本文大部分内容转自七星重剑的在Qt窗口里用D3D画转动的三角形一文,加上点滴个人研究笔记。
  先上个自己的运行结果图吧:
 

  现在的问题是只有“脏”了才画,也就是才去调用如下的method;不是三角形没动,是动了但是没画出来,我们看不见。
1 void QD3DWidget::paintEvent(QPaintEvent *)
2 {
3     if (updatesEnabled())
4     {
5         d3dDraw();
6     }
7 }


  用个timer去解决这个问题?

  这老外的帖子对我帮助很大,不搞下面的两条整个QD3DWidget都看不到:

    Using Direct3D 9 with Qt - flicker problem

   According to the Qt docs, if you want to use GDI or Direct3D on Windows with Qt, you need to:

  1) Override QWidget::paintEngine to return NULL
  2) Call QWidget::setAttribute(Qt::WA_PaintOnScreen, true) 

  完整代码:
D3D相关代码

 1 // QD3DWidget.h
 2 
 3 #pragma once
 4 
 5 #include <Qt/qwidget.h>
 6 
 7 class QD3DWidget : public QWidget
 8 {
 9     Q_OBJECT
10 
11 public:
12     QD3DWidget(QWidget* parent = 0);
13    ~QD3DWidget();
14 
15    QPaintEngine* paintEngine() const;
16 
17 protected:
18     virtual void initializeD3D();
19     virtual void paintD3D();
20 
21     void paintEvent(QPaintEvent *);
22 
23     virtual void d3dInit();
24     virtual void d3dDraw();
25 
26     bool initialized() const {return m_bInit;}
27 
28     void MsgBox();
29 private:
30     bool m_bInit;
31 };

 1 // QD3DWidget.cpp
 2 
 3 #include "QtD3DWidget.h"
 4 #include "D3D.h"
 5 #include <qtimer.h>
 6 
 7 void QD3DWidget::MsgBox()
 8 {
 9     QMessageBox mb(this);
10 
11     mb.exec();
12 }
13 
14 QD3DWidget::QD3DWidget(QWidget* parent /* = 0 */) : QWidget(parent), m_bInit(false)
15 {
16     resize(QSize(400300));
17     setAttribute(Qt::WA_PaintOnScreen, true);
18     
19     QTimer *timer = new QTimer(this);
20     connect(timer, SIGNAL(timeout()), this, SLOT(update()));
21     timer->start(20);
22 }
23 
24 QD3DWidget::~QD3DWidget()
25 {
26    
27 }
28 
29 void QD3DWidget::initializeD3D()
30 {
31     InitD3D(winId());
32     InitVB();
33 
34     m_bInit = true;
35 }
36 
37 void QD3DWidget::paintD3D()
38 {
39     Render();
40 }
41 
42 void QD3DWidget::paintEvent(QPaintEvent *)
43 {
44     if (updatesEnabled())
45     {
46         d3dDraw();
47     }
48 }
49 
50 void QD3DWidget::d3dInit()
51 {
52     initializeD3D();
53 }
54 
55 void QD3DWidget::d3dDraw()
56 {
57     if (!initialized())
58     {
59         d3dInit();
60     }
61 
62     paintD3D();
63 }
64 
65 QPaintEngine* QD3DWidget::paintEngine() const
66 {
67     return NULL;
68 }

   红字部分是根据原作者的文章自己研究后加上去的,现在的代码已经可以实现窗体中三角型的转动,关键就是利用定时器每隔20ms强制窗体重绘(update()),因为不太熟悉Qt,搞了半天才知道是update这个函数。

   用如下测试代码就可以得到开头的结果画面:
 1 #include "stdafx.h"
 2 #include "QtD3DWidget.h"
 3 #include <qapplication.h>
 4 
 5 int _tmain(int argc, char* argv[])
 6 {
 7     QApplication app(argc, argv);
 8 
 9     QD3DWidget* d3dWidget = new QD3DWidget();
10 
11     d3dWidget->show();
12 
13     return app.exec();
14 }
  
posted on 2009-05-13 06:40 林公子 阅读(12405) 评论(0)  编辑 收藏 引用 所属分类: Qt

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理