我有一个主窗口类,其中包含一个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不会被调用。让我知道是否需要包含我的头文件。
现在你明白为什么张贴代码*非常重要*。第二次看到它时,这个错误显而易见。 –