Important: Please read the Qt Code of Conduct -

Call object by name from QString

  • Hi,

    in php it is possible and I think it might be possible in qt5 as well. The following code will not work, but should show what my idea is. I have a line edit with object name e_city on my window.

    QString name = "e_city";
    if (ui->name->text() == "")
                form_valid = false;

    Is there any way to let name be handled as e_city to let that code anyhow running.

  • @Philipp-DE said in Call object by name from QString:

    my idea is

    But why? :)

    Yes, it's kinda possible with findChild. You can get the widget by object name, but only if you have set one before.

    If you want to set your stylesheet after something else happened, you can use Signals & Slots and trigger your action to set your styles to your widget.

  • Hi,

    this was my idea:

    I have a formular with a lot of lineedits and I need to validate them. There are ca. 20 fields and I think it is not good to copy the same code for all fields.

    As I worked the last 15 years with PHP, there I would have created an array with the 20 name of the objects, then loop that array and run that code for all objects.

    I was wondering if that way would be in qt5 a good way as well.

    Of course I could write a function and call it 20x for each field.

    Maybe with that background you can tell me what the best way would be.

  • I have just seen the documentation. I think it would worked when I put all object Names in a StringList and then loop it in combination with findchild. But I am not sure if this is a good practise of programming in qt5.

  • Then why don't you create an array with the pointers of the line edits?
    I don't think it is necessary to store their object names instead of their pointers.

  • @Philipp-DE
    As @Bonnie has said you can explicitly put your line edits into an array to iterate through. I don't think you will need to look them up by object name since you just presumably want to validate all of them, but if you do you can always put them in dictionary/map if you really want speed.

    If you can't be bothered to create an array/map, just use

    QList<QLineEdit *> allLineEdits = parentWidget.findChildren<QLineEdit *>();

    to get a list/iterate through all QLineEdits off some parent.

  • I thanks for your help. This helps me to solv my problems.

Log in to reply