连接QTreeWidgetItem时出错

时间:2013-09-27 14:31:20

标签: c++ qt qtreewidget

我收到以下代码的编译错误。我不能在树项上使用信号:

class MyClass : public QObject
{
    Q_OBJECT

public:
    int Grow();

public slots:
    void AddSubtree(QTreeWidgetItem *_jobItem, int _column);

private:
    void AddSubtree(QTreeWidgetItem *_jobItem, const QString &_filePath);
};

int MyClass::Grow()
{
    ...
    foreach(QFileInfo fileInfo, filesList)
    {
        if(fileInfo.isDir())
        {
            const QString tag = fileInfo.fileName();

            QTreeWidgetItem* item = new QTreeWidgetItem();
            item->setText(0, tag);

            // This works, but it is performance critical! Do it on demand
            //AddRunSubtree(item, fileInfo.filePath());

            // Load this tag's subtree on demand when clicked (error on this line)
            QObject::connect(item, SIGNAL(itemClicked(QTreeWidgetItem*, int col)),
                             this, SLOT(AddSubtree(QTreeWidgetItem*, int col)));

            parentItem->addChild(item);
        }
    }
}

void MyClass::AddSubtree(QTreeWidgetItem *_jobItem, int _column)
{
    //...
}

void MyClass::AddSubtree(QTreeWidgetItem *_jobItem, const QString &_filePath)
{
    //...
}

我收到此编译时错误:

error: no matching function for call to 'MyClass::connect(QTreeWidgetItem*&, const char*, MyClass* const, const char*)'

Candidates are:

c:\Qt\4.8.5\src\corelib\kernel\qobject.h:204: static bool QObject::connect(const QObject*, const char*, const QObject*, const char*, Qt::ConnectionType)
c:\Qt\4.8.5\src\corelib\kernel\qobject.h:204: note:   no known conversion for argument 1 from 'QTreeWidgetItem*' to 'const QObject*'

c:\Qt\4.8.5\src\corelib\kernel\qobject.h:217: static bool QObject::connect(const QObject*, const QMetaMethod&, const QObject*, const QMetaMethod&, Qt::ConnectionType)
c:\Qt\4.8.5\src\corelib\kernel\qobject.h:217: note:   no known conversion for argument 1 from 'QTreeWidgetItem*' to 'const QObject*'

c:\Qt\4.8.5\src\corelib\kernel\qobject.h:337: bool QObject::connect(const QObject*, const char*, const char*, Qt::ConnectionType) const
c:\Qt\4.8.5\src\corelib\kernel\qobject.h:337: note:   no known conversion for argument 1 from 'QTreeWidgetItem*' to 'const QObject*'

查看QTreeWidgetItem的定义,它实际上并不是从QObject派生的。这是否意味着我无法选择树枝产生信号?

如果有可能,我的代码出了什么问题?

为什么错误消息包含'MyClass :: connect'而不是'QObject :: connect'?

平台:
Qt 4.8.5
的MinGW /克++
Windows 7

2 个答案:

答案 0 :(得分:2)

QTreeWidgetItem不从QObject继承,因此它意味着它不支持信号/插槽。

void itemClicked(QTreeWidgetItem*, int)是来自QTreeWidget的信号,所以你需要这样做:

QObject::connect(treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this, SLOT(AddSubtree(QTreeWidgetItem*, int)));

另外小注意事项 - 您只需要在构造函数中创建此连接一次,而不是每次添加项目。

答案 1 :(得分:1)

您使用错误的类作为连接的发件人。您正在使用某个项目,而您应该使用QTableWidget本身。

如果切换到该设置,并设置连接一次,则会调用您的插槽。