0

Являюсь новичком в сфере 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", ибо это не удовлетворяло условию. Как можно исправить эту проблему?

1 ответ 1

3

У QLineEdit нет сигнала QLineEdit::text. QLineEdit при изменении текста генерирует сигнал textChanged(const QString &name), который можно обработать слотами:

public slots:
    void setName(const QString &name);
    void setPassword(const QString &password);

Поэтому строчки:

connect(ui.login, &QLineEdit::textChanged, &user, &User::setName);
connect(ui.password, &QLineEdit::textChanged, &user, &User::setPassword);

Надо перенести в конструктор вместо:

connect(ui.login, &QLineEdit::text, this, &QtWidgetsApplication::inputUserName);
connect(ui.password, &QLineEdit::text, this, &QtWidgetsApplication::inputPassword);

Соответственно, данные методы не нужны:

void QtWidgetsApplication::inputUserName()
void QtWidgetsApplication::inputPassword()

Метод QtWidgetsApplication::inputUser() желательно сделать слотом.

2
  • Спасибо огромное, теперь всё заработало. 24 июл 2021 в 6:16
  • @АнатолийЧехов если данный ответ, помог решить вашу проблему, то пожалуйста выберите его как "Правильный ответ", нажав на галочку слева от ответа. 2 авг 2021 в 18:58

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.