llsanketll
llsanketll

Reputation: 297

How to add clicked signal and slot to custom button in qt

I have a Box class that inherits from QPushButton. I want to have a onClick event on the button by using connect (SIGNAL and SLOT) and call a custom function onClick() declared in box.h

box.h
#ifndef BOX_H
#define BOX_H

#include <QPushButton>

class Box : public QPushButton {
public:
    Box(const QString& text, QWidget* parent = nullptr);
    void onClick();
};

#endif // BOX_H

//box.cpp
#include "box.h"

Box::Box(const QString& text, QWidget* parent)
    : QPushButton(text, parent)
{
    connect(this, SIGNAL(clicked()), SLOT(this->onClick()));
}

void Box::onClick()
{
    this->setText("Something");
}

Upvotes: 2

Views: 4071

Answers (1)

your box needs the label for defining slots

class Box : public QPushButton
{
    Q_OBJECT
    public:
        Box(const QString& text, QWidget* parent = nullptr);
    //may be public or private
    public slots:
    
        void onClick();
};

Upvotes: 4

Related Questions