Search code examples
qtvariablesstylesheet

how to use a variable that contains a file path in qt StyleSheet


any way to use a qstring variable that contains a file path in stylesheet like that for example

connect(ui->comboBox, SIGNAL(currentIndexChanged(QString)),
ui->listWidget ,SLOT(setStyleSheet("border-image: url("QString");")));

Solution

  • I guess you have access to Qt 5 and C++11, then you can use a lambda Slot, but since QComboBox::currentIndexChanged is overloaded it gets a little complicated to use the QString overload.

    Try this, I used the QString::arg method to build your CSS string, that is usually more readable then simple string concatenation. It simply replaces %1 with the first argument.

    connect(comboBox, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
        [=](const QString &imagePath) { 
            ui->listWidget->setStyleSheet(QString("border-image: url(\"%1\");").arg(imagePath));
    });