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

时间:2020-04-18 21:20:01

标签: c++ qt

我具有以下功能,可将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 (*)())中。

这是我第一次使用函数指针进行实​​验,因此任何人都可以指出我的错误方向,或者如果可行的话,也可以是实现代码的更好方法。

预先感谢

2 个答案:

答案 0 :(得分:2)

要将信号与功能连接,您需要使用"New" Signal Slot Syntax

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

如果要连接到成员函数,则可以使用lambda。支持的最简单方法是使用std::function

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

答案 1 :(得分:1)

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

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

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

void Transmit::setWindow() {
    connectButton(SLOT(clear()));
}

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

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

void Transmit::setWindow() {
    connectButton(myobject, SLOT(clear()));
}