I have the following function to link a button on a ui file with a function within the class.
void Window::connectButton() {
connect(ui->pushButton, SIGNAL(released()), this, SLOT(clear()));
}
What I actually want to achieve is to link the button with a function in a derived class. I can't reuse the connect()
function above because I cannot access ui->pushButton
from the derived class. So what I ended up with was this:
void Window::connectButton(void (*func)(void)) {
connect(ui->pushButton, SIGNAL(released()), this, SLOT(func()));
}
In case it's useful, this function is implemented in the derived class as:
void Transmit::setWindow() {
windowTitle();
setWindowSize();
connectButton(clear);
//clear is a redefined function for the derived class
//inherited from the Window class
}
I keep on getting the issue saying that func
is not used in the connectButton(void (*)())
function and that func2
cannot be passed into connectButton(void (*)())
.
This is my first experiment with function pointers so can anyone point me in the direction of my mistakes or, if more viable, a better way of implementing the code.
Thanks in advance
To connect a signal with a function, you need to use the "New" Signal Slot Syntax
void Window::connectButton(void (*func)(void)) {
connect(ui->pushButton, &QPushButton::released, func);
}
If you want to connect to member functions, then you can use lambdas. The easiest way to support that is by using std::function
void Window::connectButton(std::function<void()> func) {
connect(ui->pushButton, &QPushButton::released, func);
}
I have no idea what func2
is, but the more immediate problem is that Qt's SLOT()
macro is not actually working with function pointers at all, but it's really taking func()
as a char constant.
Easiest way out will be to move the SLOT()
-macro to the calling function, ie:
void Window::connectButton(const char* method) {
connect(ui->pushButton, SIGNAL(released()), this, method);
}
void Transmit::setWindow() {
connectButton(SLOT(clear()));
}
The above is assuming that this
in Window::connectButton()
actually refers to the object that you want to call clear()
on. Otherwise, you'd use:
void Window::connectButton(QObject* receiver, const char* method) {
connect(ui->pushButton, SIGNAL(released()), receiver, method);
}
void Transmit::setWindow() {
connectButton(myobject, SLOT(clear()));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.