问题
I am about to program a small desktop application to capture the working times of my fellow co-workers. It must be customized to our needs, therefore a commercial solution is not an option (+ we have no money).
I am using Qt (5.11.2) and C++. I have a MainWindow (first window UI) that uses auto-completion to get the information (ID, Names, Group Leaders, ...) from a sqlite3 database and fill the QLineEdits. This part is working just fine. Now, I have created a second window UI to capture the actual working times for the employee. I would like to present the user in this second window with the name and the ID of the employee whose working time is being caputured. These informations should be retrieved from the first window class.
I have tried to make the name variable public in my first window class but for some reason I couln't access the variable in my second window class, and I have also tried to use getters and setters, but to no avail. When I use getters and setters, I can manually insert a string in the setter and it is working. But I would like to get the value of the string from a lineEdit from the first window (see small code snippet)
QString tabname_temp = ui->lineEdit_Tabname->text(); // get name from lineEditf; from first window UI
I would like to work with this tabname_temp variable and use it to show in a label with this string value in the second UI window class.
The getters and setters in the first window class looked like this:
public:
void setName(QString name);
QString getName() const {return name;}
private:
QString name;
The implementation of the setName looked like this:
void MainWindow::setName(QString name){
this->name = name;
}
Long hours of google fu were to no avail. I am sure, I miss something crucial here. I hope I made clear what I am looking for. Please let me know if and how I can improve this question.
EDIT: This is how I create the second window UI (mainwindow.h):
private:
Ui::MainWindow *ui;
WindowActivity *activityWindow; // second window
This is my code from mainwindow.cpp:
void MainWindow::on_Btn_Activity_clicked()
{
activityWindow = new WindowActivity(this);
activityWindow->resize(700,700);
activityWindow->show();
}
回答1:
I have tried to make the name variable public in my first window class but for some reason I couln't access the variable in my second window class
This is a wrong approach. MainWindow
should see (know about) WindowActivity
, not the other way around.
To access the value of ui->lineEdit_Tabname
within the WindowActivity
class, do the following:
Add a public
setName
method toWindowActivity
void setName(const QString &name);
Call
WindowActivity::setName
afteractivityWindow = new WindowActivity(this);
like thisactivityWindow->setName(ui->lineEdit_Tabname->text());
来源:https://stackoverflow.com/questions/53316749/how-to-access-qstring-value-from-one-class-window-ui-in-another-class