2014-01-13 28 views
1

我有這樣的代碼:的Qt的QObject :: connnect()函數不能連接

class MyListView : public QListView 
{ 
public: 
    MyListView(); 
    ~MyListView(); 

public slots: 
    void insertData(); 
    void deleteData(); 
    void showData(); 

private: 
    QStringListModel *model; 
    QListView *listView; 
}; 

而且構造是這樣的:

MyListView :: MyListView() 
{ 
    QStringList data; 
    data << "Letter A" << "Letter B" << "Letter C"; 
    model = new QStringListModel; 
    model->setStringList(data); 

    listView = new QListView; 
    listView->setModel(model); 

    /* the three buttons */ 
    QPushButton *insertBtn = new QPushButton(QObject::tr("insert"),this); 
    QObject::connect(insertBtn,SIGNAL(clicked()),this,SLOT(insertData())); 
    QPushButton *deleteBtn = new QPushButton(QObject::tr("delete"),this); 
    QObject::connect(deleteBtn,SIGNAL(clicked()),this,SLOT(deleteData())); 
    QPushButton *showBtn = new QPushButton(QObject::tr("show"),this); 
    QObject::connect(showBtn,SIGNAL(clicked()),this,SLOT(showData())); 

    /* layout */ 
    QHBoxLayout *btnLayout = new QHBoxLayout; 
    btnLayout->addWidget(insertBtn); 
    btnLayout->addWidget(deleteBtn); 
    btnLayout->addWidget(showBtn); 
    QVBoxLayout *mainLayout = new QVBoxLayout(this); 
    mainLayout->addWidget(listView); 
    mainLayout->addLayout(btnLayout); 
    setLayout(mainLayout); 

} 

所以我想按鈕連接到插槽的功能,但是當我編譯它,我得到的錯誤信息爲:

QObject::connect: No such slot QListView::insertData() 

我認爲問題來自連接f在這種情況下,「這個」不是正確的指針,有什麼幫助?提前致謝。

回答

2

您需要添加Q_OBJECT宏在MyListView

從Qt的API文檔:

Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.

所以,它應該是:

class MyListView : public QListView 
{ 
    Q_OBJECT 
public: 
    ... 
} 
+0

貌似而QListView是QObject的不同,因爲當我按照你的建議添加「Q_OBJECT」時,我得到一個新的錯誤:「未定義的引用''爲MyListView'的vtable」。 – zhoudingjiang

+0

聽起來像是與我無關的問題,您可能想要轉貼更新後的代碼 – tinkertime

+0

您是否在添加Q_OBJECT宏後運行qmake_? – Zlatomir

相關問題