QMetaObject 调用重载运算符

QMetaObject invoke on overloaded operators

有没有人试过在 QObject 上调用重载运算符 <<。

例如我有一个class

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

    Q_INVOKABLE virtual void operator<<(char p);

};

当我尝试像这样调用它时出现错误:

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

ErrorMessage 将是:没有这样的方法 Worker::operator<<(char)(char)

QMetaObject::invokeMethoddocs 中所述:

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') );

这应该足够了,尽管我以前从未见过 invokeMethod 用于运算符。

编辑

看来 moc 无法将运算符注册到元对象系统中,调用:

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

会return-1。最好的办法是将 operator<< 放在基础 class 中,使其成为非虚拟的,并让它调用新的虚拟 Q_INVOKABLE 方法或槽。派生的 classes 将重新实现也可以通过元对象系统调用的新方法。