PDA

View Full Version : Writing custom slot method based on QT example 1&2



kaydknight
26th January 2007, 03:34
Hi, I have a question. I've been studying through tutorials under Qt. What I notice is that when you want to implement your custom slots, you have to create a custom widget and implement the slot methods inside the class.

But what if I want to create my own slots without having a need to create a class? Based on the simple example below, without creating a custom widget class, I want to implement a custom slot method "customMethod".


#include <QApplication>
#include <QPushButton>
#include <QObject>

// I want to implement a method called customMethod here
// tried void QApplication::customMethod() but didn't work
void customMethod()
{
//I want to do something here.
}

int main(int argc, char* argv[])
{
QApplication app(argc,argv);
QPushButton button("Quit");
QObject::connect(button,SIGNAL(clicked()), &app,SLOT(customMethod()));
button.show();

return app.exec();
}

I'm guessing that I can't do the above, and I have to create custom widget class or something. What I was thinking, for example, is there a way, based on above coding to add my own about messagebox, using QMessageBox::information(//parameters).

Thanks in advance!

e8johan
26th January 2007, 07:10
There is no need to create a custom widget, but you will have to put your slot in a class inheriting QObject and including the Q_OBJECT macro. This is because slots are based on the meta data system, and only QObjects has meta objects.

Since QWidget inherits QObject it has a is-a relations. I.e. QWidget is-a QObject thus has a meta object.