Question

Is it possible to be used as an argument QString in SLOT macro? PS. I mean a simple solution .. Not as in QMetaObject::connectSlotsByName().

Was it helpful?

Solution

No you cannot pass QString to SLOT macro. But you can use QString for connect. Also connect cannot take QString, so you have to convert it to const char *. Simple example is:

QString slotName = SLOT(clicked());
connect(ui->pushButton, SIGNAL(clicked()), qPrintable(slotName));

SLOT just stringifies passed parameter and concatenate it with 1:

# define SLOT(a)     qFlagLocation("1"#a QLOCATION)

If you don't want to use SLOT it's possible to write code like this:

QString slotName = QString::number(QSLOT_CODE) + "clicked()";

OTHER TIPS

This is raw code from my current project. It parses chat commands like /me customtext and calls cmd_me( const QString& params ); slot. To introduce new command it's enough to create private slot with void cmd_*( const QString& ); signature.

Here is code:

void ConsoleController::onCommand( const QString& cmd )
    {
        if ( cmd.length() < 1 )
            return ;
        if ( cmd[0] != '/' )
            return ;

        const QMetaObject *meta = metaObject();

        int posParam = cmd.indexOf( ' ' );
        if ( posParam == -1 )
            posParam = cmd.length();
        const QString command = cmd.mid( 1, posParam - 1 ).toLower();
        const QString params = cmd.mid( posParam + 1 );
        const QString slotName = QString( "cmd_%1( const QString& )" ).arg( command );
        const QString normalizedSlotName = QMetaObject::normalizedSignature( slotName.toStdString().c_str() );

        for ( int i = 0; i < meta->methodCount(); i++ )
        {
            QMetaMethod method = meta->method( i );
            if ( method.methodType() != QMetaMethod::Slot )
                continue;

            const QString signature = method.signature();
            if ( normalizedSlotName == signature )
            {
                method.invoke( this, Q_ARG( QString, params ) );
                return ;
            }
        }

        log( QString( "Command \"%1\" not recognized, type /help to list all available commands" ).arg( command ) );
    }

You can take an idea and adapt it for your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top