c++ - 如何修复 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 感谢您的帮助。你给了我继续谷歌搜索的动力。
解决方案
你忘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。
推荐阅读
- bash - grep 输出到 pip 安装
- heroku - MERN Stack - 在 Heroku 上部署时收到错误
- flutter - 如何控制flutter-headash的listview的高度
- javascript - 未捕获的 ReferenceError:未定义 GM_notification
- python - Jinja2,使用带有格式过滤器的地图,有什么诀窍?
- python - 是否有任何功能可以根据另一列文本中单词的存在情况在 pandas df 列中添加一些值?
- powershell - 通过网络部署和安装 MSI
- javascript - js中嵌套循环的左旋转操作
- firebase - Flutter:使用 Azure B2C 凭据登录 firebase,但使用自定义策略
- python - 如何使用 Python 遍历 XML 文件列表并附加某些字段?