Search code examples
c++qtsignals-slots

Can't use slots in connect qt


When I run my project I can't use train_button to add lines in text. Because of I got this error:

QObject::connect: No such slot QTextEdit::onClick()

I try to solve it, but searched only information about adding Q_OBJECT, but I got this. My project is standart Qt Widget Application.

.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>
#include <QTextEdit>
#include <QString>
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

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

~MainWindow();

public slots:
void onClick(){
    text->append("first\nsecond");
}

private:
QPushButton *train_button;
QTextEdit *text;
Ui::MainWindow *ui;
//QString a = "sdfsdfsdfsdf";
};

# endif // MAINWINDOW_H

.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

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

ui->setupUi(this);
this->setFixedSize(800,600);

text = new QTextEdit(this);
train_button = new QPushButton(this);
text->setGeometry(50,50,500,500);
text->setPlaceholderText("Here we go ...");

train_button->setText("example");
train_button->setGeometry(600,50,100,50);

train_button->setStyleSheet( "background-color: rgb(0, 255, 0);border-style: inset;border-width: 0px;border-radius: 5px;border-color: beige;font: bold 14px;min-width: 10em; padding: 2px;" );

connect(train_button,SIGNAL(clicked()),text,SLOT(onClick();));
}

MainWindow::~MainWindow()
{
delete train_button;
delete solver_button;
delete text;
delete ui;
}

I use QMake version 3.0 using Qt version 5.2.1.


Solution

  • The error is quite clear:

    No such slot QTextEdit::onClick()

    The documentation is clear as well. QTextEdit has no onClick slot anywhere.

    It's not clear what you're trying to do. In any case, you aren't doing it correctly: you cannot connect an inexistent slot to a signal.


    By looking at your code, I see that you defined onClick as a member function of MainWindow.
    Therefore probably this is what you want:

    connect(train_button, &QPushButton::clicked, this, &MainWindow::onClick); 
    

    That is, probably you want to attach a slot of the class MainWindow to the button, not a slot of a QTextEdit.