使用Qt和C ++

时间:2015-10-30 21:00:08

标签: c++ qt qpixmap

我有一个问题,我无法使用互联网解决。我有标签,我在上面设置像素图。我把它放在主窗口(小部件)也是按钮(QPushButton)。我想这样做:

  1. 如果我点击按钮,那么此像素图将连续绘制圆圈
  2. 如果我单击此按钮一秒钟,则必须通过函数pause()
  3. 停止绘图

    第二个很简单,它是空插槽:

    void pause() {}
    

    但起初我尝试使用循环

    while(true)
        draw();
    

    但它崩溃了一个程序(循环)。

    知道怎么解决吗?

2 个答案:

答案 0 :(得分:3)

You should never block the main thread. This will cause the OS to consider your application has hanged. In fact it is a good practice to move any code, whose execution takes more than 50 milliseconds to another thread to keep the main thread responsive, especially in the case of Qt, where it is also the GUI thread.

You should use an event driven approach, which will not block the thread.

class YourClass : public QObject { // QObject or derived
    Q_OBJECT
public:
    YourClass() { connect(&timer, &Timer::timeout, this, &YourClass::draw); }
public slots:
    void start() { timer.start(33); }
    void pause() { timer.stop(); }
private:
    QTimer timer;
    void draw() { ... }
};

When start() is invoked, draw() will be called every 33 miliseconds. pause() will effectively stop that until start() is invoked again. You can control the rate at which draw() is invoked by adjusting the timer's interval, by default it is 0, which in the case of drawing is overkill, you should adjust for a desired framers per second. In the example above, the it is 33 milliseconds, or roughly 30 FPS.

答案 1 :(得分:2)

然后你应该用一段时间间隔调用draw(),而不是用它暂停整个GUI线程。

为此,有QTimer

QTimer timer; // should be a member, a pointer optionally - you then do new Qtimer(this);
connect(&timer, &QTimer::timeout, draw);
timer.start(500); // in milliseconds
// assuming you are calling this from member function of QObject-deriving class
// and draw is a non-member function

如果您知道要进行连接,可以将其连接到任何地方......

可以使用QThread完成同样的操作并将其置于该循环中。

无论如何,我不知道空pause()如何停止绘图。 Aren你再次停止你的申请?只需timer.stop();