【发布时间】:2016-04-10 15:50:46
【问题描述】:
我是 Qt 新手,我正在尝试运行一个循环,该循环将使用 QPainter 更新 QWidget。简而言之,我试图运行一个无限循环,在单击按钮时刷新 QWidget(比如 start game)。然后我想在点击另一个按钮时停止循环(比如结束游戏)。我也想听听任何更好的方法来获得这个功能。
在我的 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()
{
}
【问题讨论】:
-
请在问题中提供MCVE。
-
完成!谢谢你告诉我
标签: c++ macos qt signals-slots