Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect Qt action with a function

Tags:

c++

qt

qt-signals

I am trying to make a Qt-based GUI, and I want to connect one menu item with a function, I meant that after click on a menu item this function will be called. I tried it like this, but it doesn`t work, after click on menu idem I do not see my cout print. What I am doing wrong?

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    map my_map;

    connect(ui->actionSave_Map, SIGNAL(triggered()), this, SLOT(saveMap()));

}

void MainWindow::saveMap(map& my_map)
{
    std::cout << "clicked to save" << std::endl;
    my_map.saveMap();
}

.h file

#include <QMainWindow>
#include "map.h"

namespace Ui
{
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void setMapPreferences();
    void generateMap();
    void drawMap();

public slots:
    void saveMap(map& my_map);

private:
    Ui::MainWindow *ui;


};

#endif // MAINWINDOW_H

in console there is an error after click :

Object::connect: No such slot MainWindow::saveMap(map& my_map) in ../map_generator/mainwindow.cpp:19

1 Answers

In that case, it is simple when use lambada. Replace:

connect(ui->actionSave_Map, SIGNAL(triggered()), this, SLOT(saveMap()));

with

connect(ui->actionSave_Map, &QAction::triggered, [=]() {
  saveMap(my_map);
});

after that, sure you add QMAKE_CXXFLAGS += -std=c++0x to your .pro file

like image 192
tanhieu Avatar answered Dec 24 '25 01:12

tanhieu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!