Являюсь новичком в сфере QT и пытаюсь практиковаться. Дошло до сигналов и слотов. Перейду к сути.
У меня есть класс User
(User.h):
class User : public QObject
{
Q_OBJECT
public:
static int counter;
explicit User(QObject *parent = nullptr);
~User();
QString getName();
QString getPassword();
int getAge();
public slots:
void setName(QString name);
void setPassword(QString password);
void setAge(int age);
protected:
QString name_;
QString password_;
int *id_;
int age_;
};
User.cpp
#include "User.h"
User::User(QObject* parent) :
QObject(parent)
{
counter++;
id_ = new int(counter);
}
User::~User()
{
delete id_;
}
QString User::getName()
{
return name_;
}
QString User::getPassword()
{
return password_;
}
int User::getAge()
{
return age_;
}
void User::setName(QString name) {
name_ = name;
}
void User::setPassword(QString password) {
password_ = password;
}
void User::setAge(int age) {
age_ = age;
}
int User::counter = 0;
Через QLineEdit
(введенную строку), нужно изменить состояние элементов в классе(name_
, password_
, age_
).
Хедер класса QtWidgetsAppilication
:
#pragma once
#include <QtWidgets/QMainWindow>
#include <qmessagebox.h>
#include "ui_QtWidgetsApplication.h"
#include "User.h"
class QtWidgetsApplication : public QMainWindow
{
Q_OBJECT
public:
QtWidgetsApplication(QWidget *parent = Q_NULLPTR);
void inputUser();
public slots:
void inputUserName();
void inputPassword();
private:
Ui::QtWidgetsApplicationClass ui;
User user;
};
(Знаю, что User user это было плохой идеей)
QtWidgetsApplication.cpp
#include "QtWidgetsApplication.h"
QtWidgetsApplication::QtWidgetsApplication(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
connect(ui.input, &QPushButton::clicked, this, &QtWidgetsApplication::inputUser);
connect(ui.login, &QLineEdit::text, this, &QtWidgetsApplication::inputUserName);
connect(ui.password, &QLineEdit::text, this, &QtWidgetsApplication::inputPassword);
}
void QtWidgetsApplication::inputUserName()
{
QObject::connect(ui.login, &QLineEdit::textChanged, &user, &User::setName);
}
void QtWidgetsApplication::inputPassword()
{
QObject::connect(ui.password, &QLineEdit::textChanged, &user, &User::setPassword);
}
void QtWidgetsApplication::inputUser()
{
if (user.getName() == "John" && user.getPassword() == "1234") {
QMessageBox::information(this, "Programm", "You are our employee!");
}
else {
QMessageBox::warning(this, "Program", "ERROR!");
}
}
Прочёл про сигналы и слоты, и я использовал такой синтаксис:
QObject::connect(ui.password, &QLineEdit::textChanged, &user, &User::setPassword);
Однако, значения у меня не менялись, а когда дошло до проверки, то компилятор вместо значения видел мусор и выдавал "ERROR"
, ибо это не удовлетворяло условию. Как можно исправить эту проблему?