c++ - 在按钮点击时控制 qt 中的循环

标签 c++ macos qt signals-slots

我是 Qt 的新手,我正在尝试运行一个将使用 QPainter 更新 QWidget 的循环。简而言之,我试图运行一个无限循环,在单击按钮时刷新 QWidget(比如 开始游戏)。然后我想在点击另一个按钮时停止循环(比如结束游戏)。我还想听听有关获得此功能的更好方法。

在我的 MainWindow 类中,我想启动一个包含 Game 类对象的线程。当 game->start_game() 方法被调用时,无限循环开始。我想在单击按钮时开始循环。然后循环应该在点击另一个按钮“结束”时退出。

//main_wid is the central widget of my MainWindow
QPushButton* btn_start = new QPushButton("start", main_wid);
QPushButton* btn_end = new QPushButton("end", main_wid);
//thread, game are private variables in my MainComponent class
thread = new QThread;
game = new Game(10);
game->moveToThread(thread);

//on btn_start click, the thread start in run_thread() method
connect(btn_start, SIGNAL(clicked(bool)), this, SLOT(run_thread()));
//on thread->start(), I call start_game() slot in the Game class which runs an infinite loop
connect(thread, SIGNAL(started()), game, SLOT(start_game()));

//here i want to connect clicked(bool) of btn_end to a method in game class 
//such that i can break the loop in start_game() method.
//.......??

我的游戏类:

class Game : public QObject
{
Q_OBJECT
public:
Game(int n);
~Game();

public slots:
void start_game();
void end_game();

signals:
void finish_game();

private:
int num;
};

Game类方法的定义:

Game::Game(int n)
{
    num = n;
}

void Game::start_game()
{
    int i = 0;
    while(true)
    {
    cout << "game loop started:" << i++ << endl;
    }
    //emit finish_thread();
}

 void Game::end_game()
{
    cout << "*************************end**************************" << endl;
    emit finish_game();
}

Game::~Game()
{

}

最佳答案

您的三角形绘制在 z=-2 处。由于您似乎从未设置投影矩阵,因此它将保留在同一位置并且 OpenGL 将沿所有三个维度裁剪 [-1,1] 范围之外的任何内容(无论是什么你旋转它的角度,因为它会围绕原点旋转,所以它会始终保持距离原点 2 个单位的距离。

当您学习 OpenGL 时,您应该意识到您正在使用的大部分 GL 功能在近十年内都已被弃用。在现代 GL 中,这些功能已完全删除。你的书看起来非常过时了。我只能建议改为学习现代 OpenGL。

关于c++ - 在按钮点击时控制 qt 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531932/

相关文章:

C++ 方法覆盖

macos - 无法在 Mac OSX 10.10 Yosemite 上安装 parse.com 命令行工具

macos - postgres 创建数据库;列 'dataconfig' 不存在

macos - mac 10.11.5 上的 docker + haproxy 不起作用

c++ - 在 Qt 5.5 中持续检查主循环

Qt QListView - 上下文菜单?

c++ - 为什么 XGetWindowProperty 返回 null?

php - 在 Qt C++ 中使用 openssl 解码和编码文本

c++ - 找到三个整数中最大值的最有效方法

Qt Installer Framework Controller 函数未被调用