A K
A K

Reputation: 110

How to pass a widget object to a function in Qt?

I am fairly new to Qt and would be grateful if anyone could help me with this issue. I am using Qt Creator and created a form with a PlainTextEdit. I am trying to use an if statement to validate the text entered in this text box. I made a function like the following

void validateText (QPlainTextEdit *myWidget)
{
    if ((myWidget->toPlainText().endsWith("1")) ||
        (myWidget->toPlainText().endsWith("2")) ||
        (myWidget->toPlainText().endsWith("3")) ||
        (myWidget->toPlainText().endsWith("4")) ||
        (myWidget->toPlainText().endsWith("5")) ||
        (myWidget->toPlainText().endsWith("6")) ||
        (myWidget->toPlainText().endsWith("7")) ||
        (myWidget->toPlainText().endsWith("8")) ||
        (myWidget->toPlainText().endsWith("9")) ||
        (myWidget->toPlainText().endsWith("0"))
    )
    {
        qDebug() << "Integer entered";
    }
    else
    {
        qDebug() << "Non-integer entered";
    }
}

However, when I call this function from the on_plainTextEdit_textChanged() slot, I get an error:

undefined reference to validateText(QPlainTextEdit*)

Currently, I have this code so far in the textchanged slot:

void Options::on_plainTextEdit_textChanged()
{
    validateText(qobject_cast<QPlainTextEdit*>(qApp->widgetAt(180,30)));
}

As you can see I am trying to get a reference to the object itself and pass it on to the function but I am having issues with this. Am I doing something wrong, or is there an easier way of passing a widget object to a function in Qt?

Upvotes: 2

Views: 2915

Answers (1)

A K
A K

Reputation: 110

Alright, as suggested by Daniel in the comments, I added a validator class and that fixed the issue I was having. Here is the code for anyone having the same problem in the future.

validator.cpp

...
Validator::Validator(QPlainTextEdit *textEdit)
{
    this->myWidget = textEdit;
}
void Validator::validateText ()
{
    if (   (myWidget->toPlainText().endsWith("1")) ||
           (myWidget->toPlainText().endsWith("2")) ||
           (myWidget->toPlainText().endsWith("3")) ||
           (myWidget->toPlainText().endsWith("4")) ||
           (myWidget->toPlainText().endsWith("5")) ||
           (myWidget->toPlainText().endsWith("6")) ||
           (myWidget->toPlainText().endsWith("7")) ||
           (myWidget->toPlainText().endsWith("8")) ||
           (myWidget->toPlainText().endsWith("9")) ||
           (myWidget->toPlainText().endsWith("0"))
        )
    {
        qDebug() << "Integer entered";
    }
    else
    {
        qDebug() << "Non-integer entered";
    }
}

And the function call

void Options::on_plainTextEdit_textChanged()
{
    Validator* val = new Validator(ui->plainTextEdit);
    val->validateText();
}

This completely skipped the need to cast from QWidget to a QPlainTextEdit or any of that nonsense.

Upvotes: 3

Related Questions