yxngboypolo
yxngboypolo

Reputation: 11

Connect button to a function QT c++

I'm trying to connect a button to a function and after countless amounts of searches I couldn't find anything.

I could use a on_button_clicked(goto slot) function but I plan on re-assigning the button to run more code, so I decided to use the connect() class but when I run the application nothing happens when I type into the text box and click the game_user_input_submit button I have created, and im not sure if it is even calling the function.

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QtCore>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    user_name_set = false;
    ui->game_chat_box->append("hi"); // a text edit box i created
    if(user_name_set == false)
    {
        connect(ui->game_user_input_submit, SIGNAL(clicked()), SLOT(setUsername()));
    }

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setUsername()
{
    username =  ui->game_user_input->text(); // get text from line edit i created
    user_name_set = true;
    ui->game_chat_box->append("BOT: Welcome " + username);
}

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QString>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    void setUsername();
    ~MainWindow();

private slots:
    //void on_game_user_input_submit_clicked();

private:
    bool user_name_set = false;
    QString username;
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

oh and I'm kinda new to programming c++ in general so if anybody does give me some usefull information I might need it to explain it to me, sorry

Upvotes: 0

Views: 3639

Answers (1)

lostbard
lostbard

Reputation: 5220

connect should be of the form:

connect(object_pointer,  signal_name, slot_name)

In your case, you are setting the slot name to setUsername() which is not a slot - it is just a public function.

Your mainwindow.h should be:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QString>

namespace Ui {
  class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void setUsername();

private:
    bool user_name_set = false;
    QString username;
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

Upvotes: 3

Related Questions