PDA

View Full Version : connect two buttons...



xxxollixxx
6th December 2013, 14:05
Hi Guys,

Hopefully I have a simple Question about Signals and Slot's. I wrote a little program with two buttons(A and B). So button A is an openfiledialog, which open the current dir and allows to select a file. Button B should get the filename from A and reads that file on clicked() into a string.
At this moment I dont know how to pass the filename or position to B. I guess it should be possible with the connect() function?!? Or maybe set some global value?

My code looks like this:

void Mainwindow:: on_A_clicked()
{
QString file=QFiledialog::getOpenFileName(
this,
("select a file"),
"c:/qt/",
("All files (*.*)"));
}

void Mainwindow:: on_B_clicked()
{
QFile file; // <--- how to get "file" accepted here?
file.open(QIODevice::Readonly);
...
}

Best regards,

Olli

sulliwk06
6th December 2013, 14:18
Well you're going to have to store the file name somewhere, presumably in a private QString that both buttons have access to.

What i usually do when I'm using a button for an open file dialog is set up a QLineEdit next to it and when they select the file I populate the line edit with the filename. Then when the second button is clicked you can get the filename from the line edit.

Santosh Reddy
6th December 2013, 14:19
Store the file name in a member variable inside MainWindow, and read it from on_B_clicked().

xxxollixxx
6th December 2013, 15:04
just for understanding: I need to set a member variable to "public:" in "Mainwindow.h"? Can it also be "private:"?

Or is it also ok to define this in mainwindow.cpp?

Added after 10 minutes:

Ok I'll try this:

QString file; //I guess this should be global?

void Mainwindow:: on_A_clicked()
{
QString file=QFiledialog::getOpenFileName(
this,
("select a file"),
"c:/qt/",
("All files (*.*)"));
}

void Mainwindow:: on_B_clicked()
{
qDebug() << file; //empty now :(
QFile file;
file.open(QIODevice::Readonly);
...
}

Do I need to set the file name to the QString file too? If yes, please give a hint how -.-

Olli

anda_skoa
6th December 2013, 15:34
just for understanding: I need to set a member variable to "public:" in "Mainwindow.h"? Can it also be "private:"?

Yes, can be private as well. That is actually what sulliwk06 suggested.



Or is it also ok to define this in mainwindow.cpp?

mainwindow.h inside the class declaration.



QString file; //I guess this should be global?

Better as a member of Mainwindow



void Mainwindow:: on_A_clicked()
{
QString file=QFiledialog::getOpenFileName(

This creates a local variable with the same name, "hiding" the variable you actually want to use

Cheers,
_