1
votes

I want to make a button to stay pushed after a click. So I made a slot make_pushed which I try to use for that purpose. The button which was clicked on is identified by QObject::sender() method. But something goes wrong since it doesn't work.

 QPushButton * size=new QPushButton("size",this);    
 connect(size, SIGNAL(clicked()), this, SLOT(make_pushed()));
 void Window4::make_pushed()
{
  QObject* sender = this->sender();
  QPushButton* button = qobject_cast<QPushButton*>(sender);
   button->setDown(true);
   button->setText("Yep");
}


class Window4 : public QWidget
{
public:
   Window4(QWidget * parent=0);
private slots:
   void make_pushed();
 };

There's a mistake in application output "QObject::connect: No such slot QWidget::make_pushed() in" , although everything compiles and the window appears. The problem is the slot is apparently not found, although it is in the same cpp file and in the header. And therefore when clicked, the botton neigher changes its text nor stays pushed.

1
what doesn't work? what are you expecting? what did you see?user3528438
what is Windows4? how is make_pushed declared in the header? did you do Q_OBJECTS? did you do Q_SLOTS? which QT version?user3528438
Are the first two lines inside the Window4 class somewhere? If so its probably that you're missing Q_OBJECT definition, and possibly also not moc'ing, Window4.David
Thank you! That was the case. Added Q_OBJECT, made run qmake and it worked.parsecer

1 Answers

2
votes

You just forgot Q_OBJECT macro in class declaration http://doc.qt.io/qt-5/qobject.html:

Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.

http://doc.qt.io/qt-5/qobject.html#Q_OBJECT:

The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system.

Note: This macro requires the class to be a subclass of QObject. Use Q_GADGET instead of Q_OBJECT to enable the meta object system's support for enums in a class that is not a QObject subclass.

Just use it like this every time you subclass QObject/QWidget/...:

#include <QObject>

class Counter : public QObject
{
    Q_OBJECT
    
    // ...
}