我有一個主窗口類,其中包含一個QSplitter小部件(以及其他小部件)。此拆分器的內容由另一個類中的小部件填充。Qt連接信號插槽
這裏面其他Widgwt我有一個佈局的QPushButton稱爲test_btn加入我也有在頭文件中定義的函數public slots:
下稱爲test_function其具有在cpp文件相應的代碼:
cout << "Test!" << endl;
我嘗試調用這個函數使用下面的代碼:
connect(test_btn, SIGNAL(clicked()), SLOT(test_function()));
的部件和按鈕出現預期中的應用程序,但是當我點擊它沒有任何反應。
如果我同connect
代碼添加到它的工作原理主窗口(調用從主窗口中的測試功能),即
connect(cc_point.test_btn, SIGNAL(clicked()), SLOT(main_win_test_function()));
我不能從其他類調用測試功能,除非我叫它from main_win_test_function()
我知道我錯過了connect語句中的'receiver widget',雖然它沒有在主窗口類中工作,編譯時也沒有出現任何錯誤。
我是否需要在other_class
中定義父項或其他項?
main_window.cpp:
main_window::main_window()
{
add_splitter();
QGridLayout *window_layout = new QGridLayout;
window_layout->setSpacing(0);
window_layout->setContentsMargins(0, 0, 0, 0);
window_layout->addWidget(splitter1, 0, 0);
set_layout(window_layout);
}
void main_window::add_splitter()
{
other_class oc_point;
splitter1 = new QSplitter(Qt::Horizontal);
splitter1->addWidget(oc_point.oc_widget);
}
other_class.cpp:
other_class:other_class()
{
oc_widget = new QWidget;
QGridLayout *other_layout = new QGridLayout(oc_widget);
test_btn = new QPushButton;
test_btn->setText("Test Button");
connect(test_btn, SIGNAL(clicked()), test_btn->parent(), SLOT(test_function());
other_layout->addWidget(test_btn);
}
void other_class::test_function()
{
cout << "Test output" << endl;
}
main.cpp中:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
main_window window;
window.resize(1100, 700);
window.setWindowTitle("Qt Test");
window.setWindowIcon(QIcon (":/images/icon_1.png"));
window.setMinimumHeight(500);
window.show();
return app.exec();
}
正如我上面提到的,這一切就正常工作的創建窗口並顯示小部件,但當單擊按鈕時,test_function不會被調用。讓我知道是否需要包含我的頭文件。
現在你明白爲什麼張貼代碼*非常重要*。第二次看到它時,這個錯誤顯而易見。 –