【发布时间】:2020-10-05 21:22:43
【问题描述】:
我正在尝试将字符串值从 mainwindow.cpp 传递给 userdetails.cpp。我一直使用全局变量。当程序运行时,它会显示错误消息“Undefined references to globelusername”。 globelusername 表示全局变量名。代码有什么错误?
主窗口.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "register.h"
#include "userdetails.h"
//#include <QtSql>
//#include <QSqlDatabase>
//#include <QMessageBox>
extern QString globelusername;
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
主窗口.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui ->loginusername->setPlaceholderText("Username");
ui ->loginpassword->setPlaceholderText("Password");
QString username = ui ->loginusername ->text();
QString globelusername = username;
return ;//
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
//open new registration in new window
hide();
regist = new Register(this);
regist ->show();
}
void MainWindow::on_pushButton_2_clicked()
{
//database connection
.....
QString username = ui ->loginusername ->text();
QString password = ui ->loginpassword ->text();
if(db.open()){
//query create
QSqlQuery query(QSqlDatabase::database("MyConnect"));
query.prepare(QString("SELECT * FROM user_reg_elec WHERE username = :username AND password = :password"));
query.bindValue(":username", username);
query.bindValue(":password", password);
QString globelusername = username; //globlevariable
}
userdetails.cpp
#include "userdetails.h"
#include "ui_userdetails.h"
#include <QSqlError>
#include "mainwindow.h"
Userdetails::Userdetails(QWidget *parent) :
QDialog(parent),
ui(new Ui::Userdetails)
{
ui->setupUi(this);
}
Userdetails::~Userdetails()
{
}
void Userdetails::on_pushButton_4_clicked()
{
{
// database connection
........
QString abc = globelusername;
【问题讨论】:
-
你首先不应该为此使用全局变量。
-
此外,您正在使用 qt,为什么不避开整个全局,并在您需要的事件上尝试一个信号/插槽?但事实上,你仍然应该定义你的全局,在你声明它之后:)
-
没有理由这样做...您正在创建具有循环依赖关系的意大利面条代码...
-
知道了。谢谢
标签: c++ string qt parameters qstring