1.QTimer::singleShot如何传参、2.QMetaObject::invokeMethod如何用函数传值

1.QTimer::singleShot如何传参

        QString p = "pink";
        QTimer::singleShot(1000, this, [&,p](){
            print(p);
        }
        );
        同理可以传多个参数

优势:可以传入多个的参数

2.QMetaObject::invokeMethod如何用函数传值

    QString d = "prr";
    QMetaObject::invokeMethod(obj, [&,d](){
        obj->print(d);
    });

优势:

1.无需依赖QObject*, const char *member, arg1, arg2,arg3的方法

2.对象函数参数变化,函数名变化时,可以在编译时报错

上面都用到了lamda函数,但是lamda函数本身会有额外的内存开销,最多为旧代码的5倍,尽量用QString或者qt自带的小变量

测试对象的构造和析构,定义下面用例

static int sqr = 0;
class XString{
public:
    XString()
    {
        key = ++ sqr;
        qDebug() << __FUNCTION__ << __LINE__ << key;
    }
    XString(const XString &other)
    {
        key = ++ sqr;
        this->pink = other.pink;
        qDebug() << __FUNCTION__ << __LINE__ << key;
    }

    ~XString(){
        qDebug() << __FUNCTION__ << __LINE__ << key;
    }

    QString getPink() const { return pink; }
    void setPink(const QString &value){ pink = value; }

private:
    QString pink;
    int key;
};
class XObject : public QObject {
    Q_OBJECT

public:
    XObject(XString m, QObject *parent = nullptr)
        : QObject(parent),m(m) {}

    XString m;
public slots:
    void trigger(){emit signal_trgg(m);}
signals:
    void signal_trgg(XString p);
};

 

用例1
XString p;
p.setPink("pink");
QTimer::singleShot(1000, this, [&,p](){
    //this的函数
}
);
运行:
XString 18 1
XString 24 2
XString 24 3
XString 24 4
XString 24 5
~XString 28 4
~XString 28 3
~XString 28 2
~XString 28 1
~XString 28 5

用例2
XThread *thread = new XThread(this);
XString p;
p.setPink("pink");
XObject *o = new XObject(p, 0);
connect(o, SIGNAL(signal_trgg(XString)), this, SLOT(print(XString)));
connect(thread, SIGNAL(finished()), o, SLOT(deleteLater()));
QTimer::singleShot(1000, o, SLOT(trigger()));
o->moveToThread(thread);
thread->start();
运行:
XString 18 1
XString 24 2
XString 24 3
~XString 28 2
~XString 28 1
XString 24 4
XString 24 5
~XString 28 4
~XString 28 5
~XString 28 3

多线程的调用
XString d;
d.setPink("prr");
qDebug() << __LINE__ << d.getPink() << QThread::currentThreadId();
QMetaObject::invokeMethod(obj, [&,d](){
    qDebug() << __LINE__ << d.getPink() << QThread::currentThreadId();
});
运行:
XString 18 1
63 "prr" 0x1fa0
XString 24 2
XString 24 3
XString 24 4
~XString 28 3
~XString 28 2
65 "prr" 0x27dc
~XString 28 1
~XString 28 4

 

你可能感兴趣的:(Qt)