我尝试将字符串值从主窗口.cpp传递给用户详细信息.cpp。我被使用了全局变量。当程序运行时,它会显示错误消息">未定义对 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
}
用户详细信息.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;
此行
extern QString globelusername;
只是声明一个全局变量,但不定义它。
您必须在其中一个.cpp文件中定义它(例如在主窗口中.cpp(:
#include "mainwindow.h"
#include "ui_mainwindow.h"
QString globelusername;
// ...
您在头文件的顶部声明了一个全局变量
extern QString globelusername;
但你从来没有定义过它。
你在函数中有局部定义,但这些变量不是你可能认为你要分配的全局变量。 它们只是临时变量,当函数的封闭范围返回时消失:
QString globelusername = username; //globlevariable
要解决此问题,请在mainwindow.cpp
顶部定义以下内容:
#include "mainwindow.h"
#include "ui_mainwindow.h"
QString globelusername; // add this line
MainWindow::MainWindow(QWidget *parent)
然后在您在函数中定义 globelusername 的所有地方将其更改为仅引用顶部的变量(即删除 QString 类型声明,以便编译器知道它是一个赋值而不是一个新变量(
globelusername = username;
你正在射击自己的脚,
仔细查看MainWindows.h
包含Userdetails.h
,用户详细信息包括一个 MainWindows.h,这在软件开发中称为循环依赖项,非常非常糟糕!
相反,在主窗口中将 Qstring 定义为成员对象/变量,并在 UserDetails 类中定义一个 setter,然后在 mainWindows 中将其作为参数传递:
in uderDetail
Userdetails::setName(const QString& name)
{
this->name=name;
}
并在主窗口中
MainWindow::foo()
{
this->myUserDetails->setName(this->name);
}
后来做
this->myUserDetails->show(); //exec() or similar