我正在尝试将字符串值从MainWindow.cpp传递到UserDetails.cpp。 我用的是全局变量。 当程序运行时,它不会将变量值传递给UserDetails.cpp。 当我使用qDebug(GlobelUsername.toLatin1())时,它没有显示任何值。 这个代码的错误是什么? globelusername是指全局变量。
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "register.h"
#include "userdetails.h"
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();
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
QString globelusername;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui ->loginusername->setPlaceholderText("Username");
ui ->loginpassword->setPlaceholderText("Password");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_2_clicked()
{
//database connection
...........
QString username = ui ->loginusername ->text();
QString password = ui ->loginpassword ->text();
if(db.open()){
//query create
// QMessageBox::information(this, "Sucessfull ","Sucessfully Connect the Database");
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"
#include <iostream>
Userdetails::Userdetails(QWidget *parent) :
QDialog(parent),
ui(new Ui::Userdetails)
{
ui->setupUi(this);
}
Userdetails::~Userdetails()
{
}
void Userdetails::on_pushButton_4_clicked()
{
{
// database connection
...........
qDebug(globelusername.toLatin1() );
您没有设置GlobelUserName。 相反,您正在创建一个具有以下行的局部变量:
QString globelusername = username; //globlevariable
在设置值之前删除变量类型:
globelusername = username; //globlevariable