如何在两个类之间连接函数
how to connect function between two classes
我在两个文件中有两个不同的类:
class Game: public QGraphicsView()
class Window: public QMainWindow()
{
public: Window();
Game *game;
public slots: void test() {game = new Game();};
}
Window.cpp
我使用 test() 函数启动一个新游戏:
Window::Window() {test();}
现在在Game.cpp
我创建了一个带有两个QPushButton
的QMessageBox
QMessageBox *box= new QMessageBox();
QPushButton *btYES = box->addButton(tr("YES"),QMessageBox::ActionRole);
QPushButton *btNO = box->addButton(tr("NO"),QMessageBox::ActionRole);
box->exec();
if (box->clickedButton() == btYES) {Window::test();}
if (box->clickedButton() == btNO) {close();}
如您所见,我想将函数test()
连接到Game.cpp
内部的btYES
,但该功能位于Window.cpp
内部,其功能是启动新游戏。
可以这样做吗?
QPushButton 在按下/释放时会发出事件
因此,您可以将释放的信号连接到插槽:
connect(button, SIGNAL(released()), windowClass, SLOT(handleButton()));
在您的情况下,您需要跨类发送它,因此您可能需要分两步完成。
在游戏中:
// connect the button to a local slot
connect(btYES, SIGNAL(released()), this, SLOT(handleYesButton()));
// in the slot emit a signal - declare the signal in the header
game::handleYesButton()
{
emit userChoiceYes();
}
在窗口中
// connect the signal in game to a your slot:
connect(game, SIGNAL(userChoiceYes()), this, SLOT(test()));
然后,当 btnYes 被按下/释放时,释放的信号被发出 - 你在handleYesButton()中拾取它并发出你自己的信号,你的窗口类连接到该信号并在test()中处理它
基于@code_fodder答案,但你甚至不需要另一个插槽,加上 QPushButton 的基本信号是 clicked()
.这是文档:
按钮在被 鼠标、空格键或通过键盘快捷键。连接到此信号 以执行按钮的操作。按钮也提供较少 常用信号,例如 pressed() 和 release()。
首先,无需在类Game
中添加另一个插槽,只需将按钮的信号clicked()
连接到另一个信号:
connect(btYES, SIGNAL(clicked()), this, SIGNAL(btYesClicked()));
现在,当您按下按钮 btYes
时,会发出来自类Game
的信号。现在,您只需将此信号连接到类Window
中的插槽test()
:
connect(game, SIGNAL(btYesClicked()), this, SLOT(test()));
相关文章:
- 给定两个偶数,求出它们之间所有偶数的平方和
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 如何在两个 boost::multi_arrays (C++) 之间执行数学运算?
- 查找字符在两个索引之间出现的次数
- 如何使用 OpenCV 解码在两个 UWP 应用之间发送的图像字节?
- C++两个源文件之间共享的枚举的静态实例
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 以天C++为单位的两个时间戳之间的差异
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 通过插槽和信号在不同线程中的两个qt对象之间进行通信
- 在C++中查找两个向量之间最相似的值
- 两个有符号数字之间的距离
- Directx 12 :在两个进程之间共享图形内存
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 是否有一种标准方法来计算两个 asctime() 值之间的天数
- 如何找到两个棋盘平面之间的角度?
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 将两个数字替换为给定数组中介于两个之间的单个数字
- 如何在两个其他两个之间设置工具栏