Qt4:连接插槽和其他形式的信号 [英] Qt4: connect slot and signal from other forms
问题描述
我有一个小问题。我想从MainWindow从AnotherWindow运行功能。我不能设置 connect()
。
I have a small problem. I want run function in MainWindow from AnotherWindow. I can't set connect()
for it.
Main class: MainWindow
Other form: AnotherWindow
Function in main class: setVariable(QString)
Function in other form: btnClicked()
我现在已连接按钮信号 clicked()
:
I have now connected button signal clicked()
:
// In AnotherWindow.cpp
connect(ui->btnOK, SIGNAL(clicked()), this, SLOT(btnOkClicked()));
// Function in same file
void interfaceWindow::btnOkClicked() {
/* Some actions - emit signal? */
this->close();
}
btnOkClicked()
被声明为私有时隙。
btnOkClicked()
are declared as private slot.
// In MainWindow.cpp
void MainWindow::setVariable(QString _var) {
this->var = _var;
}
setVariable(QString)
如何从AnotherForm发送变量(从 btnOkClicked()
函数)到MainWindow( setVariable(QString)
function)?如何以及在哪里必须发送信号和连接?
How I can send variable from AnotherForm (from btnOkClicked()
function) to MainWindow (setVariable(QString)
function) ? How and where I must send signal and make connection?
我读了有关信号和插槽,但我的代码不工作 - 我不粘贴在这里,因为它可怕的:)
I readed about signals and slots, but my code don't work - I don't paste it here because it's terrible :)
任何帮助Qt newbie?
Any help for Qt newbie?
推荐答案
需要在MainWindow中有一个AnotherWindow的引用,反之亦然。那么你需要以下的东西:
You need to have an reference of AnotherWindow in MainWindow OR vice versa. Then you need the following things:
// AnotherWindow.h
signals:
void buttonOkClickedSignal(QString var);
// AnotherWindow.cpp
void interfaceWindow::btnOkClicked() {
emit buttonOkClickedSignal("The button got clicked!");
this->close();
}
下一步取决于MainWindow是否引用AnotherWindow,反之亦然。您可以:
Next step varies based on whether MainWindow has reference to AnotherWindow or vice versa. You can either:
// AnotherWindow.cpp
connect(this, SIGNAL(buttonOkClickedSignal(QString), &mainWindow, SLOT(setVariable(QString)));
或:
// MainWindow.cpp
connect(&anotherWindow, SIGNAL(buttonOkClickedSignal(QString), this, (SLOT(setVariable(QString)));
如果你是通过信号调用槽,不管它是私有的还是公共的a href =http://qt-project.org/doc/qt-4.8/signalsandslots.html =nofollow> Qt Documentation )。
希望这有帮助。
If you are invoking the slot through signal it shouldn't matter whether it's private or public (see Qt Documentation). Hope this helps.
这篇关于Qt4:连接插槽和其他形式的信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!