qt5 信號槽新語法遇到重載的問題

假如使用了qt5 信號槽新語法:

    QObject::connect(&newspaper, &Newspaper::newPaper,&reader,    &Reader::receiveNewspaper);

 

信號有重載的時候,比如兩個信號

void newPaper(const QString &name, const QDate &date);

void newPaper(const QString &name)

會出現編譯錯誤:

..\control\mainwindow.cpp(57): error C2664: “bool QObject::disconnect(const QMetaObject::Connection &)”: 無法將參數 2 從“overloaded-function”轉換爲“const char *”

..\control\mainwindow.cpp(57): note: 上下文不允許消除重載函數的歧義

 

Qt4的信號槽語法因爲帶了參數,所以沒有問題:

QObject::connect(&newspaper, SIGNAL(newPaper(QString, QDate)),&reader, SLOT(receiveNewspaper(QString, QDate)));

而新的信號槽的語法沒有參數,當函數重載,編譯器不知道要取哪一個函數的地址。所以我們需要指明是哪一個函數。

如下,定義一個 名爲 newPaperNameDate的類函數指針:

void (Newspaper:: *newPaperNameDate)(const QString, const QDate) = &Newspaper::newPaper;
QObject::connect(&newspaper, newPaperNameDate,
&reader, &Reader::receiveNewspaper);

也可以寫在一行:

QObject::connect(&newspaper,
static_cast<void (Newspaper:: *)(const QString, const QDate)>(&Newspaper::newPaper),
&reader,&Reader::receiveNewspaper);

同理:當槽函數有重載時,也必須指出是那個槽函數,如下:

QObject::connect(&newspaper,
static_cast<void (Newspaper:: *)(const QString, const QDate)>(&Newspaper::newPaper),
&reader,
static_cast<void (Reader:: *)(const QString, const QDate)>(&Reader::receiveNewspaper));

 

上面使用到的是類函數指針,類函數指針簡單使用方式如下:

class CA
{  
public:  
    int caAdd(int a, int b) {return a+b;}  
    int caMinus(int a, int b){return a-b;};  
};  


//定義類函數指針類型
    typedef int (CA::*PtrCaFuncTwo)(int ,int);  

//指針賦值
    PtrCaFuncTwo pFunction = &CA::caAdd;  
  
//使用指針,注意使用括號
    CA ab;  
    int c = (ab.*pFunction) (1,2);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章