【问题标题】:QObject::connect: No such slot on QT [duplicate]QObject::connect:QT上没有这样的插槽[重复]
【发布时间】:2018-01-21 05:18:22
【问题描述】:

您好,我不知道为什么会出现此错误,我看到一个可能来自宏 Q_OBJECT 的网络,但在其他类上没有出现此问题。

我对 ram 使用相同的代码,我只调用了一次,这里唯一的区别是我为四个 CPU 调用了 4 次。

这是我的 CPP

qtCPUBar::qtCPUBar(int i)
{
    _i = i;
    auto *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(showCPU(_i)));
    timer->start(1000);

    showCPU(_i);
    resize(150, 60);
}

qtCPU::qtCPU()
{
    CPUStats info;

    info.updateInfo();

    if (info.getCoreAmount() >= 4) {
        auto *CPU1 = new qtCPUBar(0);
        auto *CPU2 = new qtCPUBar(1);
        auto *CPU3 = new qtCPUBar(3);
        auto *CPU4 = new qtCPUBar(4);
        auto *vbox6 = new QVBoxLayout();
        vbox6->addWidget(CPU1);
        vbox6->addWidget(CPU2);
        vbox6->addWidget(CPU3);
        vbox6->addWidget(CPU4);

        this->setLayout(vbox6);

    }
}

void qtCPUBar::showCPU(int i)
{
    CPUStats cpu;

    cpu.updateInfo();
    auto tot = cpu._CPUInfo._Frequence;
    auto la = (cpu.getInfo(i, CPUStats::CORE_USAGE)).back();

    auto res = 100 * la / tot;
    this->setValue(static_cast<int>(res));
}

这是我的HPP

#ifndef CPP_RUSH3_CPU_HPP
#define CPP_RUSH3_CPU_HPP


#include <QProgressBar>
#include <QtWidgets>

class qtCPUBar : public QProgressBar{
Q_OBJECT
public:
    virtual ~qtCPUBar() = default;

    qtCPUBar(int i);
private slots:
    void showCPU(int i);
private:
    int _i = 0;
};


struct qtCPU : public QWidget{
public:
    virtual ~qtCPU() = default;

    qtCPU();
};

#endif

【问题讨论】:

  • 你能发布你遇到的错误吗?
  • QObject::connect: No such slot qtCPUBar::showCPU(_i) in ... 第 18 行,该行是:connect(timer, SIGNAL(timeout()), this, SLOT(showCPU (_i)));
  • 不能这样传递参数。使用 lambda 并捕获 i

标签: c++ qt


【解决方案1】:

来自信号和插槽文档:

信号的签名必须与接收槽的签名匹配。 (事实上​​,一个槽的签名可能比它接收到的信号更短,因为它可以忽略额外的参数。)

您在连接时遇到了 2 个问题:

connect(timer, SIGNAL(timeout()), this, SLOT(showCPU(_i)));
  1. 您正在连接具有不同签名的信号和插槽。
  2. 在连接时,您将一个变量提供给插槽,而不是仅仅放置参数的类型。

因此,只需更改您的插槽签名即可解决您的问题:

//.h file
void showCPU();
...
// .cpp
connect(timer, SIGNAL(timeout()), this, SLOT(showCPU()));


编辑

正如 O'Neil 所建议的,您也可以使用 C++11 lambda 函数:

qtCPUBar::qtCPUBar(int i)
{
    ...
    _i = i;
    connect(timer, QTimer::timeout, this, [this]() { showCPU(_i); });
    ...
}

警告:它使用New Signal Slot Style

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 2010-10-09
    相关资源
    最近更新 更多