How to pass QString variable to QFile?

946 views Asked by At

getData gets the chosen file from a QTreeView and displays it on label 'test', enables the 'Apply' button, which when clicked calls setTheme

void OptionsDialog::getData(const QModelIndex &index)
{
    QString selected = model2->filePath(index);
    ui->test->setText(selected);
    ui->pushButton_apply_theme->setEnabled(true);
}

void OptionsDialog::setTheme()
{
    //char *file = selected->toLatin1().data();
    //const std::string file = selected->toStdString();
    QFile qss(selected);
    qss.open(QFile::ReadOnly);
    qApp->setStyleSheet(qss.readAll());
    qss.close();
}

I can't seem to pass the filePath to QFile in the format it wants, commented lines are some attempts which failed. ' char *file = selected->toLatin1().data();' compiles but segfaults in use.

As is it fails with:

qt/optionsdialog.cpp: In member function ‘void OptionsDialog::setTheme()’:
qt/optionsdialog.cpp:176:23: error: no matching function for call to ‘QFile::QFile(QString*&)’
     QFile qss(selected);

Forgive me for I am used to python, this is driving me nuts, any help appreciated!

1

There are 1 answers

1
Zaiborg On BEST ANSWER

QString selected = model2->filePath(index); does not set the variable in the (maybe same named) member OptionsDialog::selected. This creates a new local variable.

If you have a member variable called selected then you should use it like this:

void OptionsDialog::getData(const QModelIndex &index)
{
    selected = model2->filePath(index);
    ...
}