传递函数指针-我做错了什么



我有以下函数将ui文件上的按钮与类中的函数链接起来。

void Window::connectButton() {
connect(ui->pushButton, SIGNAL(released()), this, SLOT(clear()));
}

我实际想要实现的是将按钮与派生类中的函数链接起来。我不能重用上面的connect()函数,因为我不能从派生类访问ui->pushButton。所以我最终得到的是:

void Window::connectButton(void (*func)(void)) {
connect(ui->pushButton, SIGNAL(released()), this, SLOT(func()));
}

如果有用的话,这个函数在派生类中实现为:

void Transmit::setWindow() {
windowTitle();
setWindowSize();
connectButton(clear);
//clear is a redefined function for the derived class
//inherited from the Window class
}

我不断收到这样的问题,说func没有在connectButton(void (*)())函数中使用,func2不能传递到connectButton(void (*)())中。

这是我第一次使用函数指针进行实验,这样任何人都可以为我指明错误的方向,或者,如果更可行的话,可以找到更好的代码实现方式。

提前感谢

要将信号与函数连接,需要使用"New"signal Slot Syntax

void Window::connectButton(void (*func)(void)) {
connect(ui->pushButton, &QPushButton::released, func);
}

如果您想连接到成员函数,那么您可以使用lambdas。支持这一点的最简单方法是使用std::function

void Window::connectButton(std::function<void()> func) {
connect(ui->pushButton, &QPushButton::released, func);
}

我不知道func2是什么,但更直接的问题是Qt的SLOT()宏实际上根本不使用函数指针,而是将func()作为一个char常量。

最简单的方法是将SLOT()-宏移动到调用函数,即:

void Window::connectButton(const char* method) {
connect(ui->pushButton, SIGNAL(released()), this, method);
}
void Transmit::setWindow() {
connectButton(SLOT(clear()));
}

以上假设Window::connectButton()中的this实际上是指您要调用clear()的对象。否则,您将使用:

void Window::connectButton(QObject* receiver, const char* method) {
connect(ui->pushButton, SIGNAL(released()), receiver, method);
}
void Transmit::setWindow() {
connectButton(myobject, SLOT(clear()));
}

最新更新