close
Qt 5.0 以後connection更新, 可以將slot設定為 function, 而非一定要是QObject, 且slot 可以有更加靈活的用法 (並非一定要有相對應parameter之slot function, 其他成員函式亦可執行):
New: connecting to QObject member
Here's Qt 5's new way to connect two QObjects and pass non-string objects:
connect( sender, &Sender::valueChanged, receiver, &Receiver::updateValue );
Pros
- Compile time check of the existence of the signals and slot, of the types, or if the Q_OBJECT is missing.
- Argument can be by typedefs or with different namespace specifier, and it works.
- Possibility to automatically cast the types if there is implicit conversion (e.g. from QString to QVariant)
- It is possible to connect to any member function of QObject, not only slots.
Cons
- More complicated syntax? (you need to specify the type of your object)
- Very complicated syntax in cases of overloads? (see below)
- Default arguments in slot is not supported anymore.
New: connecting to simple function
The new syntax can even connect to functions, not just QObjects:
connect( sender, &Sender::valueChanged, someFunction );
Pros
- Can be used with std::bind:
connect( sender, &Sender::valueChanged, std::bind( &Receiver::updateValue, receiver, "senderValue", std::placeholders::_1 ) );
- Can be used with C++11 lambda expressions:
connect( sender, &Sender::valueChanged, [=]( const QString &newValue ) { receiver->updateValue( "senderValue", newValue ); } );
Cons
- There is no automatic disconnection when the 'receiver' is destroyed because it's a functor with no QObject. However, since 5.2 there is an overload which adds a "context object". When that object is destroyed, the connection is broken (the context is also used for the thread affinity: the lambda will be called in the thread of the event loop of the object used as context).
官網網址如下:
http://doc.qt.io/qt-5/signalsandslots.html
https://wiki.qt.io/New_Signal_Slot_Syntax
自建Model:
可用於QML中的ListView, 如此就不會限制於只能用簡單QStringList對應的ModelData
可自訂data role (兩種以上data role的model)
範例如下
http://doc-snapshots.qt.io/qt5-5.11/qtquick-models-objectlistmodel-example.html
全站熱搜
留言列表