1

Has anyone tried to invoke overloaded operator << on a QObject.

For example i have a class

class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0);

    Q_INVOKABLE virtual void operator<<(char p);

};

When i try to invoke it with like this i get an error:

QMetaObject::invokeMethod( &worker, QT_STRINGIFY2( operator<<(char) ), Qt::QueuedConnection, Q_ARG( char, 'a') );

ErrorMessage would be: No such method Worker::operator<<(char)(char)

GeneralFailure
  • 1,085
  • 3
  • 16
  • 32

1 Answers1

0

As noted in the docs for QMetaObject::invokeMethod:

You only need to pass the name of the signal or slot to this function, not the entire signature.

QMetaObject::invokeMethod( &worker,
                           "operator<<",
                           Qt::QueuedConnection,
                           Q_ARG( char, 'a') );

This should suffice, though I've never seen invokeMethod used on an operator before.

Edit

It appears that the moc cannot register operators into the meta-object system, calling:

qDebug() << worker.metaObject()->indexOfMethod( "operator<<" );

Will return -1. The best thing to do is put your operator<< in the base class, make it non-virtual, and have it call a new virtual Q_INVOKABLE method or slot. Derived classes would then reimplement the new method which can also be called through the meta-object system.

cmannett85
  • 21,725
  • 8
  • 76
  • 119
  • You were about the name of the function. Ordinary functions are called like that. I tried your suggestion and still doesn't work: QMetaObject::invokeMethod: No such method Worker::operator<<(char) – GeneralFailure Mar 25 '15 at 14:33
  • "You were about the name of the function. Ordinary functions are called like that." What? You can call operators directly so `(&worker)->operator<<( 'a' )` is legal. You asked about overloaded operators, what are the other overloads? (Add them to your question). – cmannett85 Mar 25 '15 at 15:02
  • Ahm sorry, bad english. I meant that you were right and this usually works for ordinary functions. However when you try it with overloaded operators it doesn't find the method. Maybe it has something to do with the moc and the << characters in the signature but it doesn't work for me. You can try this if you want and if it works and see for yourself. – GeneralFailure Mar 25 '15 at 15:11
  • @GeneralFailure You are right! I've added more info. – cmannett85 Mar 25 '15 at 15:31
  • Ok I will accept this strategy. However I am not sure that if in the base operator<< () when I am calling invokeMethod( this, 'othermethod', 'args' ), the metasystem will call the derived implementation of 'othermethod'. I am almost sure that it will, though :) – GeneralFailure Mar 25 '15 at 15:48
  • @GeneralFailure It will call the derived class. – cmannett85 Mar 25 '15 at 15:53