首页 > 解决方案 > 如何修复 QObject::connect: No such slot.. 将发送者连接到同一类中的插槽时

问题描述

我正在编写一个程序,它创建一个只接受数字的 QLineEdit,并且当它拒绝不是数字的输入时,应该将背景变成某种任意颜色。如果输入被接受,它将再次将背景变为白色。现在我需要将 QLineEdit 的 inputRejected 和 textEdited 事件分别连接到 randomcolor() 和 white() ,但是连接给我带来了麻烦,我不知道如何解决它。

这是我第一次使用 connect 并且我在许多论坛中一直在尝试我在那里找到的不同语法。

#include <QtWidgets>

class OnlyNumbers : QLineEdit {
   public:
        static int spawn(int argc, char *argv[]){
            QApplication app(argc, argv);
            OnlyNumbers P;
            return app.exec();
        }
        OnlyNumbers() : QLineEdit() {
            this->setValidator(new QIntValidator());
            QObject::connect(this, SIGNAL(inputRejected()), this, SLOT(randomcolor()));
            QObject::connect(this, SIGNAL(&QLineEdit::textEdited(const QString)), this, SLOT(&OnlyNumbers::white()));
            QRegExp rx("[0-9]*");            QValidator *validator = new QRegExpValidator(rx, this);
            this->setValidator(validator);
            this->show();

        }
    public slots:
        void randomcolor(){
            this->setStyleSheet("QLineEdit { background: rgb(std::rand()%256, rand()%256, rand()%256); selection-background-color: rgb(rand()%256, rand()%256, rand()%256); }");
        }
        void white(){
            this->setStyleSheet("QLineEdit { background: rgb(255, 255, 255); selection-background-color: rgb(233, 99, 0); }");
        }
};

int main(int argc, char *argv[])
{
    return OnlyNumbers::spawn(argc, argv);
}

QObject::connect: 没有这样的插槽 QLineEdit::randomcolor()

QObject::connect: 没有这样的信号 QLineEdit::&QLineEdit::textEdited(const QString)

这些是我得到的错误,我不知道如何处理它们,因为对于他们来说,这两个是存在的。可悲的是,我无法更好地描述我的问题,因为我不知道更多。

已解决:问题是,我没有在 onlynumbers.h 和 onlynumbers.cpp 中单独调用定义和声明。此外,我不能将 std::rand()%256 放入字符串中,我需要拆分字符串并将其与转换为 qstring 的所有数字连接起来。:D 感谢您的帮助。你给了我继续谷歌搜索的动力。

标签: c++qtqt5

解决方案


你忘Q_OBJECT了你的课。例如:

class OnlyNumbers : QLineEdit {
    Q_OBJECT    
    ...

请参阅QObject上的文档:

请注意,对于任何实现信号、槽或属性的对象,Q_OBJECT 宏都是必需的。

如果没有宏,元编译器根本不会生成类中声明的插槽/信号所需的信息。

此外,在Q_OBJECT添加之后,您应该重新运行qmake您的项目,因为实际上会在 makefile 中qmake生成对的调用。Meta-Object Compiler (moc)moc的文档对此进行了解释:

每当运行 qmake 时,它​​都会解析项目的头文件并生成 make 规则来为那些包含 Q_OBJECT 宏的文件调用 moc。

同样如评论中所述 -SIGNAL/SLOT宏是旧的基于字符串的实现,切换到新的编译时检查连接有很多好处 - 请参阅New Signal Slot Syntax and Differences between String-Based and Functor-Based Connections


推荐阅读