just started using qt, looked through docs, google, examples, etc.. trying to find simple examples(working mind you) that showed how to do (imho) simple things, by themselves. well i stumbled upon my answer and i was wondering if this approach would cause an issue later as the code becomes more complex. there are more includes than needed for this example, but this is direct from working code. mainwindow.h: i added
private slots:
void vpkButton_clicked();
and after Ui::MainWindow *ui; i added QLineEdit *vpkPathTxt; in mainwindow.cpp: after
ui->setupUi(this);
i added
connect( this->ui->vpkButton, SIGNAL( clicked() ), this, SLOT(vpkButton_clicked()) );
to connect my ui button to the proper slot, the issue was getting the string from vpkButton_clicked() to display in the line edit i made in the designer, what ended up working for me was adding this next:
vpkPathTxt = this->ui->vpkPathTxt;
the function in my main.cpp became very easy: (QString declarations at top outside voids)
void MainWindow::vpkButton_clicked()
{
vpkName = QFileDialog::getOpenFileName(this,
tr("Open VPK File"), "~/", tr("VPK Files (*_dir.vpk)"));
vpkPathTxt->setText(vpkName);
qDebug() << vpkName;
}
the reason i am ask is because it seems a little too easy to be reliable, and the fact that i havent seen it done like this, any input welcome thankyou
One problem with your slot is that you don't consider the case where the user discards the "open file" dialog. In this case, the function
QFileDialog::getOpenFileName
returns a null QString, so you should only proceed with your logic if the return value was not a null string:The second problem is as follows and I made some assumptions since I don't see your full code:
I guess you want to load a file using the file name the user has chosen in the dialog. But you set the file name in the line edit too, which the user can edit by hand. I also guess that the actual file loading happens in a different step (i.e. after clicking another button), so after the user has edited the file name by hand in the line edit it won't be the same than in your local variable
vpkName
.When loading the file I'd read the contents of the line edit instead of the variable
vpkName
so the edit made by hand will be respected.A different method is to also watch for editing of the line edit and reflect the changes in your variable too. Then it will be ok to read the variable instead of the line edit when loading the file later on.