【发布时间】:2019-06-30 13:31:59
【问题描述】:
我正在编写一个程序,它创建一个只接受数字的 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: No such slot QLineEdit::randomcolor()
QObject::connect: 没有这样的信号 QLineEdit::&QLineEdit::textEdited(const QString)
这些是我得到的错误,我不知道如何处理它们,因为对于他们来说,这两个是存在的。遗憾的是,我无法更好地描述我的问题,因为我不知道更多。
已解决:问题是,我没有在 onlynumbers.h 和 onlynumbers.cpp 中单独调用定义和声明。此外,我不能将 std::rand()%256 放入字符串中,我需要拆分字符串并将其与所有转换为 qstring 的数字连接起来。 :D 感谢您的帮助。你给了我继续谷歌搜索的动力。
【问题讨论】:
-
用
QObject::connect(this, SIGNAL(textEdited(const QString)), this, SLOT(white()));替换QObject::connect(this, SIGNAL(&QLineEdit::textEdited(const QString)), this, SLOT(&OnlyNumbers::white()));你似乎在混合Qt4 和Qt5 连接方法。 -
您真的不应该再将旧的基于字符串的信号/插槽连接语法与
SIGNAL和SLOT宏一起使用。最好使用新的 - compile time checked, pointer to member function based syntax。它既安全又快捷。 -
你也可以使用Qt5语法
QObject::connect(this, &QLineEdit::textEdited, this,&OnlyNumbers::white);