1

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

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/g++
Windows 7

4

2 回答 2

2

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

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

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

还要注意 - 您只需要创建一次此连接(在构造函数中),而不是在每次添加项目时。

于 2013-09-27T14:54:19.993 回答
1

您为连接的发送者使用了错误的类。您正在使用一个项目,而您应该使用它QTableWidget本身。

如果你切换到那个,并且你设置了一次连接,你的插槽将被调用。

于 2013-09-27T19:30:05.270 回答