I've currently studied QT and have to face the problem of passing member function pointer to SLOT macro. Here is the part of code:
main.cpp:
#include <iostream>
#include <QApplication>
#include "vMainMenu.hpp"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
try{
MainMenu* menu = new MainMenu{};
menu->show();
}
catch(const std::exception& e)
std::cerr << e.what() << '\n';
return app.exec();
}
vMainMenu.hpp:
#pragma once
#include <QDialog>
#include <QtWidgets>
#include "vMainMenu.hpp"
class MainMenu : public QDialog
{
Q_OBJECT
public:
MainMenu(QWidget *parent = nullptr){
m_Layout = new QVBoxLayout{};
showMainMenu();
};
virtual ~MainMenu();
private slots:
void showMainMenu(){
addButton(tr("&One player"), &MainMenu::showOPMenu);
addButton(tr("&Network"), &MainMenu::showNWMenu);
setLayout(m_Layout);
m_Layout->update();
};
void showOPMenu(){};
void showNWMenu(){};
private:
void addButton(const QString& str, void(MainMenu::*fn)()){
QPushButton* btn = new QPushButton{str};
// more button config ...
m_Layout->addWidget(btn);
QObject::connect(btn, SIGNAL (clicked()), this, SLOT(fn)); // this metod doesn`t work
}
QVBoxLayout *m_Layout;
};
CMakeLists.txt:
cmake_minimum_required(VERSION 3.8)
project(proj)
set(CMAKE_CXX_STANDARD 17)
find_package(Qt5Core REQUIRED)
find_package(Qt5Gui REQUIRED)
find_package(Qt5Widgets REQUIRED)
QT5_WRAP_CPP(MOC_Files vMainMenu.hpp)
add_library(forms SHARED${MOC_Files})
target_link_libraries(forms Qt5::Core)
target_link_libraries(forms Qt5::Gui)
target_link_libraries(forms Qt5::Widgets)
set(SOURCE_FILES main.cpp)
add_executable(proj ${SOURCE_FILES})
target_link_libraries(proj forms)
Is there a method to modify addButton
function to receive a pointer to the nonstatic member function (or some other way) and push it to SLOT macro. I tried to send it as a parameter. The program has been built, but when it runs, it throws an error:
QObject::connect: Parentheses expected, slot MainMenu::fn ...
I understand that it tries to interpret 'fn' as MainMenu::fn, but Is there a method or some kind of abstraction over member-function to read by SLOT macro?
I have already read this QT SLOT: Pointer to Member Function error post but when I tried to use that method, the program has been built, but when it runs, it throws an error:
No such slot MainMenu::callSlot(fn)