PDA

View Full Version : Subclassing QLabel



Maluko_Da_Tola
26th August 2010, 23:52
Hi,

I am trying to sublass QLabel to create a label capable of handling mouse click events. The following code works fine:


#include <QtGui>

class MyLabel : public QLabel
{
Q_OBJECT
public:
protected:
virtual void mousePressEvent(QMouseEvent *event)
{
if (event->button()==Qt::LeftButton)
{
qWarning() << Q_FUNC_INFO;
}
}
};


#include "main.moc"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyLabel l;
l.setText("foo bar");
l.show();
return app.exec();
}


What I don't understand is, when I try to define MyLabel class in a seperate header file, Qt does not compile anymore! Why is this happening?

Thank you

norobro
27th August 2010, 00:23
What errors do you get?

You don't need to "#include main.moc" if you have the class in a separate file.

Urthas
28th August 2010, 01:35
Really, you ought not to define functions in header files. You can, but inline functions are normally reserved for very short functions, such as one-line "getters" or "setters" (although they in turn raise interesting OO-design questions). Your function is small, but best to form good habits now. In addition, most of the time, event-handling code should propagate the event after you do your custom work by including a call to the parent class code, as follows (for this case):



...
QLabel::mousePressEvent(event);
} // end function


This may or may not be what you want but is *usually* appropriate.