1. 程式人生 > >很多人以為 connect 和 disconnect 應該像 new 和 delete 一樣成對出現 這是錯誤的(只要 sender 或 receiver 其中之一不存在了,connect 會自動失效。QObject::connect 函數是線程安全的)

很多人以為 connect 和 disconnect 應該像 new 和 delete 一樣成對出現 這是錯誤的(只要 sender 或 receiver 其中之一不存在了,connect 會自動失效。QObject::connect 函數是線程安全的)

應該 sed connect slot 命令 a-z 其中 cti event

其實我寫文章也是邊查資料邊編輯的

有時候是怕自己的闡述不嚴謹,有時候是怕自己重復造輪子

就像有些人不停的教大家QLabel QDialog QWidget 個人是不屑的


命令模式

用 Qt‘s Undo Framework 來舉例最恰當不過了

QUndoCommand Class 裏簡單介紹了下用法

class AppendText : public QUndoCommand
{
public:
    AppendText(QString *doc, const QString &text)
        : m_document(doc), m_text(text) { setText("append text"); }
    virtual void undo()
        { m_document->chop(m_text.length()); }
    virtual void redo()
        { m_document->append(m_text); }
private:
    QString *m_document;
    QString m_text;
};

Qt Undo Framework 裏詳細描述了4個類的用法和註意點

Qt Undo Framework Demo 裏翻譯了官方的一個例子


觀察者模式

這個自然是用 Qt 的 signal-slots 機制來舉例了

DevBean Tech World 豆子是很早的 Qt 博主,這篇文章也寫的很詳細,就不狗尾續貂了

一般大家都喜歡大談特談 QObject::connect 函數的前4個參數

其實第五個參數才值得被討論討論

Threading Basics

You’re doing it wrong…(QThread with SIGNAL-SLOT)

Threads Events QObjects

QThreads general usage

Threading without the headache - Qt Blog

接下來可以談談的是 connect 裏的參數類型,必須是可以轉義成 QVariant 的類型

如果用了自定義類型,需要通過 qRegisterMetaType 或 Q_DECLARE_METATYPE 來註冊

Differences between String-Based and Functor-Based Connections

然後可以一提的是 QObject::connect 函數是線程安全的

Reentrancy and Thread-Safety

最後可以說說 connect 和 lambda 的結合,這是 Qt5 的特性

connect(action, &QAction::triggered, engine, [=]() {
    engine->processAction(action->text()); });

順便說下 disconnect 函數

這個函數不要在析構函數裏顯示的去調用它

很多人以為 connect 和 disconnect 應該像 new 和 delete 一樣成對出現

這是錯誤的

只要 sender 或 receiver 其中之一不存在了,connect 會自動失效

https://zhuanlan.zhihu.com/p/32138947

很多人以為 connect 和 disconnect 應該像 new 和 delete 一樣成對出現 這是錯誤的(只要 sender 或 receiver 其中之一不存在了,connect 會自動失效。QObject::connect 函數是線程安全的)