Unavailable Ui properties - c++

I've been trying to implement a project in C++ using Qt Creator – this is Qt Creator 3.3.1 (opensource) based on Qt Creator 5.4.1. I use Ubuntu 14.04.
I've found some tutorials of which the subject was simillar to what I wanted to create, so I've been studying the code and trying to fit it to my needs. This is the GUI Project. I've been also dealing with this project to learn more C++, OOP. I did 2 forms.
The project consists of 3 classes for now. One class includes a form to gather some information about persons – it works. The main class includes QtableWidget to present the details about the persons from the database in the table, I also implemented the method to find persons (also in the main class), searching by Surnames – in form I used QlineEdit to do it.
But I need another form to edit the information about the strict person. I decided to implement the form to edit the information in another class. There occurred the problem, because to edit the information about the strict person, I need to be able to read what I typed into the gap of QlineEdit and then to make a search in the database using this information (from the QlineEdit which is included in the form of the main class).
The issue is that, in the second class (to edit) when I use a construction in the constructor as: QString Surname = ui->name_of_the_gap->text(); - where ”name_of_the_gap” is the name of the gap which includes the surname that I want to use but it happens to be unavailable for this UI (the ui in the class in which there is this form to edit information).
I have tried to use inheritance but non of it works. Could I please ask you to direct me / point me out how should I do it / what should I change?
Below I will present you the pieces of the code:
addrecord.h
#ifndef ADDRECORD_H
#define ADDRECORD_H
#include <QDialog>
#include <QtSql/qsqldatabase.h>
#include <QtSql/QSqlError>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/qsqldriver.h>
#include <QtSql/QSqlDriverPlugin>
#include <QtSql/qsqldriverplugin.h>
#include <QSqlQuery>
#include <QDebug>
#include <QString>
#include <QMessageBox>
namespace Ui {
class AddRecord;
}
class AddRecord : public QDialog
{
Q_OBJECT
public:
explicit AddRecord(QWidget *parent = 0);
~AddRecord();
private slots:
void on_btnQuit_clicked();
void on_btnAdd_clicked();
private:
Ui::AddRecord *ui;
};
**/*addrecord.h*/**
editrecord.h
#ifndef EDITRECORD_H
#define EDITRECORD_H
#include <QDialog>
//#include "mainwindow.h"
//#include "addrecord.h"
#include <QLineEdit>
namespace Ui {
class EditRecord;
}
class EditRecord : public QDialog
//class EditRecord : public MainWindow
{
Q_OBJECT
public:
explicit EditRecord(QWidget *parent = 0);
~EditRecord();
Ui::EditRecord *eui;
private slots:
void on_btnQuit_clicked();
private:
//Ui::EditRecord *ui;
//Ui::EditRecord *ui;
//Ui::MainWindow *mui;
QLineEdit *searchSurnameEdit;
};
#endif // EDITRECORD_H
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "addrecord.h"
#include "editrecord.h"
#include <QMainWindow>
#include <QtCore>
#include <QtGui>
#include <QSql>
#include <QtSql/qsqldatabase.h>
#include <QtSql/QSqlError>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/qsqldriver.h>
#include <QtSql/QSqlDriverPlugin>
#include <QtSql/qsqldriverplugin.h>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlRecord>
#include <QSqlTableModel>
#include <QModelIndexList>
#include <QTableView>
#include "editrecord.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
Ui::MainWindow *ui;
void fillTable();
private slots:
void on_tableWidget_cellChanged(int row, int column);
void on_btnQuit_clicked();
void on_btnAdd_clicked();
void on_btnSearchSurname_clicked();
void on_btnEditData_clicked();
private:
bool loading;
//Ui::MainWindow *ui;
QStandardItemModel *model;
QSqlDatabase *myDb;
QSqlTableModel *empmodel;
QItemSelectionModel *selection;
QTableView *view;
QModelIndexList indexes;
QSqlQuery *q;
//EditRecord *editrecord;
};
#endif // MAINWINDOW_H
addrecord.cpp
#include "addrecord.h"
#include "ui_addrecord.h"
AddRecord::AddRecord(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddRecord)
{
ui->setupUi(this);
}
AddRecord::~AddRecord()
{
delete ui;
}
void AddRecord::on_btnQuit_clicked()
{
this->close();
}
void AddRecord::on_btnAdd_clicked()
{
QSqlDatabase db1 = QSqlDatabase::addDatabase("QMYSQL");
db1.setHostName("localhost");
db1.setDatabaseName("dbname");
db1.setUserName("user");
db1.setPassword(„passwd");
db1.open();
QString gkUserid,name,second_name,surname,date_of_birth,NIP,street,postalcode,desc,telefhone,mobile_phone,email,sex,city;
name = ui->nameEdit->text();
second_name = ui->secondNameEdit->text();
surname = ui->surnameEdit->text();
date_of_birth = ui->dateofBirthEdit->text();
NIP = ui->nipEdit->text();
street = ui->streetEdit->text();
postalcode = ui->postalCodeEdit->text();
desc = ui->descEdit->acceptRichText();
telefhone = ui->telephoneEdit->text();
mobile_phone = ui->mobilePhoneEdit->text();
email = ui->eMailEdit->text();
sex = ui->sexEdit->text();
city = ui->cityEdit->text();
if(!db1.open()){
qDebug()<<"Failed to open database";
return;
} else {
qDebug()<<"OK";
}
QSqlQuery query("qt_mysql");
query.prepare("INSERT INTO gkUsers VALUES (:gkUserid,:name,:second_name,:surname,:date_of_birth,:NIP,:street,:postal_code,:desc,:telephone,:mobile_phone,:email,:sex,:city)");
query.bindValue(":name",name);
query.bindValue(":second_name",second_name);
query.bindValue(":surname",surname);
query.bindValue(":date_of_birth",date_of_birth);
query.bindValue(":NIP",NIP);
query.bindValue(":street",street);
query.bindValue(":postal_code",postal_code);
query.bindValue(":desc",desc);
query.bindValue(":telephone",telephone);
query.bindValue(":mobile_phone",mobile_phone);
query.bindValue(":email",email);
query.bindValue(":sex",sex);
query.bindValue(":city",city);
if(query.exec()){
QMessageBox::critical(this,tr("Save"),tr("Saved"));
db1.close();
ui->nameEdit->setText("");
ui->secondNameEdit->setText("");
ui->surnameEdit->setText("");
ui->dateofbirthEdit->setText("");
ui->nipEdit->setText("");
ui->streetEdit->setText("");
ui->postalCodeEdit->setText("");
ui->descEdit->acceptRichText();
ui->telephoneEdit->setText("");
ui->mobilephoneEdit->setText("");
ui->eMailEdit->setText("");
ui->sexEdit->setText("");
ui->cityEdit->setText("");
} else {
QMessageBox::critical(this,tr("Error"),query.lastError().text());
}
}
editrecord.cpp
#include "editrecord.h"
#include "ui_editrecord.h"
#include "mainwindow.h"
EditRecord::EditRecord(QWidget *parent):
// MainWindow(),
QDialog(parent),
//eui(new Ui::EditRecord), MainWindow(parent)
eui(new Ui::EditRecord)
{
eui->setupUi(this);
//ui->setupUi(mui->placeholder);
// EditRecord(Ui::MainWindow *ui)
//QString Surname = ui->szukajNazwiskoEdit->text();
// eui->setupUi(ui.placeholder);
}
EditRecord::~EditRecord()
{
delete eui;
}
void EditRecord::on_btnZamknij_clicked()
{
this->close();
}
**/*editrecord.cpp*/**
**/*main.cpp*/**
#include "mainwindow.h"
#include "editrecord.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
EditRecord e; //added
w.show();
return a.exec();
}
**/*main.cpp*/**
**/*mainwindow.cpp*/**
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "addrecord.h"
#include <QSql>
#include <QtSql/qsqldatabase.h>
#include <QtSql/QSqlError>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/qsqldriver.h>
#include <QtSql/QSqlDriverPlugin>
#include <QtSql/qsqldriverplugin.h>
#include <QSqlQuery>
#include <QString>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QSqlDatabase myDb = QSqlDatabase::addDatabase("QMYSQL");
myDb.setHostName("localhost");
myDb.setDatabaseName("db");
myDb.setUserName("user");
myDb.setPassword("passwd");
myDb.open();
qDebug()<<myDb.open();
ui->tableWidget->hideColumn(0);
fillTable();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::fillTable()
{
loading = true;
int num_rows, r, c;
//QSqlQuery q(myDb);
QSqlQuery q;
//get the number of rows
if(!q.exec("SELECT count(gkUserid) as num_rows FROM gkUsers")) qDebug()<< q.lastError().text();
q.first();
num_rows = q.value(0).toInt();
ui->tableWidget->setRowCount(num_rows);
ui->tableWidget->setMaximumWidth(1700);
ui->tableWidget->setMaximumHeight(300);
if(!q.exec("SELECT gkUserid, name, second_name, surname, date_of_birth, NIP, street, postalcode, desc, telephone, mobile_phone, email, sex, city FROM gkUsers ORDER BY gkUserid")) qDebug() << q.lastError().text();
for(r = 0, q.first(); q.isValid(); q.next(), ++r)
{
//for(c = 0; c < q.numRowsAffected(); ++c)
for(c = 0; c < 14; ++c)
{
ui->tableWidget->setItem(r,c, new QTableWidgetItem(q.value(c).toString()));
}
}
loading = false;
}
void MainWindow::on_tableWidget_cellChanged(int row, int column)
{
//int id = ui->tableWidget->item(row, 0)->text().toInt();
if (loading) return;
QSqlQuery q;
q.prepare("UPDATE gkUsers SET name = :i, second_name = :d_i, surname = :n, date_of_birth = :d_u, NIP = :N, street = :u, postal_code = :k, opis = :o, telephone = :t, mobile_phone = :t_k, email = :e, sex = :p, city = :m WHERE gkUserid = :gkUserid");
q.bindValue(":i", ui->tableWidget->item(row, 1)->text());
q.bindValue(":d_i",ui->tableWidget->item(row, 2)->text());
q.bindValue(":n", ui->tableWidget->item(row, 3)->text());
q.bindValue(":d_u", ui->tableWidget->item(row, 4)->text());
q.bindValue(":N", ui->tableWidget->item(row, 5)->text());
q.bindValue(":u", ui->tableWidget->item(row, 6)->text());
q.bindValue(":k", ui->tableWidget->item(row, 7)->text());
q.bindValue(":o", ui->tableWidget->item(row, 8)->text());
q.bindValue(":t", ui->tableWidget->item(row, 9)->text());
q.bindValue(":t_k", ui->tableWidget->item(row, 10)->text());
q.bindValue(":e", ui->tableWidget->item(row, 11)->text());
q.bindValue(":p", ui->tableWidget->item(row, 12)->text());
q.bindValue(":m", ui->tableWidget->item(row, 13)->text());
q.bindValue(":gkUserid", ui->tableWidget->item(row, 0)->text().toInt());
if(!q.exec()) qDebug() << q.lastError().text();
fillTable();
}
void MainWindow::on_btnQuit_clicked()
{
this->close();
}
void MainWindow::on_btnAdd_clicked()
{
//QMainWindow window;
//AddRecord * addrecord = new AddRecord(this);
AddRecord addrecord;
addrecord.setModal(true);
addrecord.exec();
}
void MainWindow::on_btnSearchSurname_clicked()
{
QString Surname = ui->searchSurnameEdit->text();
qDebug()<<Surname;
QSqlDatabase myDb = QSqlDatabase::addDatabase("QMYSQL");
myDb.setHostName("localhost");
myDb.setDatabaseName("db");
myDb.setUserName("user");
myDb.setPassword("passwd");
qDebug()<<myDb.open();
if(!myDb.open()){
qDebug()<<"There is no connection to DB";
return;
}
QSqlQuery qry;
if(qry.exec("SELECT gkUserid, name, second_name, surname, date_of_birth, NIP, street, postal_code, desc, telephone, mobile_phone, email, sex, city FROM gkUsers WHERE surname = \'" + Surname + "\'"))
{
if(qry.next()){
QString msg1 = qry.value(1).toString();
QString msg2 = qry.value(2).toString();
QString msg3 = qry.value(3).toString();
QString msg4 = qry.value(4).toString();
QString msg5 = qry.value(5).toString();
QString msg6 = qry.value(6).toString();
QString msg7 = qry.value(7).toString();
QString msg8 = qry.value(8).toString();
QString msg9 = qry.value(9).toString();
QString msg10 = qry.value(10).toString();
QString msg11 = qry.value(11).toString();
QString msg12 = qry.value(12).toString();
QString msg13 = qry.value(13).toString();
QString msg14 = qry.value(14).toString();
QString msg15 = qry.value(15).toString();
ui->nameEdit->setText(msg1);
ui->surnameEdit->setText(msg3);
ui->dateofbirthEdit->setText(msg4);
ui->nipEdit->setText(msg5);
ui->telEdit->setText(msg9);
ui->sexEdit->setText(msg12);
ui->mobileEdit->setText(msg10);
ui->streetEdit->setText(msg5);
ui->cityEdit->setText(msg13);
ui->descEdit->setText(msg8);
myDb.close();
} else {
qDebug()<<"Something went wrong";
}
}
}
void MainWindow::on_btnEditData_clicked()
{
EditRecord editrecord;
editrecord.setModal(true);
editrecord.exec();
//editrecord = new EditRecord(this);
//editrecord->show();
}
mydelegate.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = MyDelegate
TEMPLATE = app
QT += sql
SOURCES += main.cpp\
mainwindow.cpp \
addrecord.cpp \
editrecord.cpp
HEADERS += mainwindow.h \
addrecord.h \
editrecord.h
FORMS += mainwindow.ui \
addrecord.ui \
editrecord.ui \
edit_record.ui

It's because each class has its own Ui which represents the specific UI elements you've defined for that Form and not others. So in EditRecord class you can't access ui->name_of_the_gap, because no such thing is defined in the EditRecord form. The fact that it's been defined for your other class, is irrelevant here, because you have no access to it.
The solution is to get whatever info you need (in your case, the text that has been entered in the QLineEdit of MainWindow) before showing the EditRecord and then pass that value to EditRecord. In other words, you have to get the value from QLineEdit when you can access it and pass that value, instead of trying to access that QLineEdit when you can't.
For doing this you have to pass that value to the constructor of you EditForm. The changes you need are like this:
//In editrecord.h:
explicit EditRecord(QString surname, QWidget *parent = 0);
//In editrecord.cpp:
EditRecord::EditRecord(QString surname, QWidget *parent):
QDialog(parent),
eui(new Ui::EditRecord)
{
eui->setupUi(this);
//Now you have access to 'surname'. Do whatever you need to do with it.
//...
}
//In maitwindow.cpp:
void MainWindow::on_btnEditData_clicked()
{
QString surname = ui->name_of_the_gap->text();
EditRecord editrecord(surname);
editrecord.setModal(true);
editrecord.exec();
}
Note that you can also send the ui this way too, but it's considered bad in OOP.

Related

menu bar functionalities aren't working in Qt

so i am writing a simple video player program and i did the same steps as the lesson i am taking but when i run the program and click on functionalities like end (which is close()) and open (open file) they dont work, i used the slot triggering as per the lesson although i saw different ways of using the menubar here but i must follow this format, here is my code:
header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QVideoWidget>
#include <QStyle>
#include <QMediaPlayer>
#include <QFileDialog >
namespace Ui {
class videoWidget;
}
class videoWidget : public QMainWindow
{
Q_OBJECT
QMediaPlayer *meinPlayer;
QPushButton *playButton;
QPushButton *stopButton;
public:
explicit videoWidget(QWidget *parent = 0);
~videoWidget();
private slots:
void listeUndTitelAktualisieren();
void on_action_End_triggered();
void on_action_ffnen_triggered();
void on_action_Stop_triggered();
void on_action_PlayBack_triggered();
void on_action_Pause_triggered();
private:
Ui::videoWidget *ui;
};
#endif // MAINWINDOW_H
cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
videoWidget::videoWidget(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::videoWidget)
{
ui->setupUi(this);
meinPlayer = new QMediaPlayer(this);
meinPlayer->setMedia(QUrl::fromLocalFile("/beispiele/topologien.wmv"));
meinPlayer->play();
}
void videoWidget::listeUndTitelAktualisieren()
{
QString titel = meinPlayer->media().canonicalUrl().toLocalFile();
ui->listWidget->addItem(titel);
this->setWindowTitle("Multimedia-Player – " + titel);
connect(meinPlayer, SIGNAL(mediaChanged(QMediaContent)), this, SLOT(listeUndTitelAktualisieren()));
}
void videoWidget::on_action_End_triggered()
{
this->close();
}
void videoWidget::on_action_ffnen_triggered()
{
QFileDialog *meinDialog = new QFileDialog(this);
meinDialog->setAcceptMode(QFileDialog::AcceptOpen);
meinDialog->setWindowTitle("Datei öffnen");
meinDialog->setNameFilters(QStringList() << "Videos (*.mp4 *.wmv)" << "Audios (*.mp3)" << "Alle Dateien (*.*)");
meinDialog->setDirectory(QDir::currentPath());
meinDialog->setFileMode(QFileDialog::ExistingFile);
if (meinDialog->exec() == QDialog::Accepted) {
QString datei = meinDialog->selectedFiles().first();
meinPlayer->setMedia(QUrl::fromLocalFile(datei));
/*QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Image"), "/home/jana", tr("Video & Audio Files (*.mp3 *.mp4 *.wmv)"));
*/
meinPlayer->play();
}
}
void videoWidget::on_action_Stop_triggered()
{
meinPlayer->pause();
}
void videoWidget::on_action_PlayBack_triggered()
{
meinPlayer->play();
}
void videoWidget::on_action_Pause_triggered()
{
meinPlayer->pause();
}
am pretty sure this instruction here:
connect(meinPlayer, SIGNAL(mediaChanged(QMediaContent)), this, SLOT(listeUndTitelAktualisieren()));
is not located where it should coz you are connecting the signal toa slot INSIDE of the SLOT implementation....
try moving that to the constructor of dein videoWidget

Global variable pass the null value

I'm try to pass string value from mainwindow.cpp to userdetails.cpp. I had been used global variable. When the program run it does not pass the variable value to the userdetails.cpp. When I use qDebug( globelusername.toLatin1() ) it does not show any value. What is the error in this code? globelusername mean, the global variable.
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() );
You are not setting globelusername. instead, you are creating a local variable with the following line:
QString globelusername = username; //globlevariable
remove the variable type before setting the value:
globelusername = username; //globlevariable

Qt C++ class does not name a type

I´m trying to put a ComboBox ater a query and put the results into a QtableView.
My query works and the table view shows the results, my combobox receive the first column elements but...
When I try to make a new query on on_comboBox_pedido_currentIndexChanged, my query results is always empty.
I tried to put my "Login teste" declaration class as public and appears "'Login' does not name a type"
This is my pedidos.h . I tried do create a public teste here!!!
#ifndef PEDIDOS_H
#define PEDIDOS_H
#include <QDialog>
#include <QTableView>
#include <QtWidgets>
namespace Ui {
class Pedidos;
}
class Pedidos : public QDialog
{
Q_OBJECT
public:
Login teste; // not working - "does not name a type" error
explicit Pedidos(QWidget *parent = 0);
~Pedidos();
private slots:
void on_pushButton_load_pedidos_clicked();
void on_comboBox_pedido_currentIndexChanged(const QString &arg1);
private:
Ui::Pedidos *ui;
};
#endif // PEDIDOS_H
And this is my pedidos.cpp
#include "login.h"
#include "pedidos.h"
#include "ui_pedidos.h"
Pedidos::Pedidos(QWidget *parent) :
QDialog(parent),
ui(new Ui::Pedidos)
{
ui->setupUi(this);
Login conn;
if(!conn.connOpen())
ui->label_pedidos_conn->setText("Falha na conexão ao Database");
else{
ui->label_pedidos_conn->setText("Database Ok");
conn.connClose();
}
}
Pedidos::~Pedidos()
{
delete ui;
}
void Pedidos::on_pushButton_load_pedidos_clicked()
{
Login conn;
QSqlQueryModel *modal=new QSqlQueryModel();
QSqlQuery *qry=new QSqlQuery(conn.mydb);
qry->prepare("SELECT pedido.id_pedido, usuarios.nome_user, endereco.bairro, \
pedido.id_user, pedido.data FROM pedido \
INNER JOIN usuarios ON pedido.id_user=usuarios.id_user \
INNER JOIN endereco ON pedido.id_endereco=endereco.id_endereco \
WHERE pedido.status=0");
qry->exec();
qDebug() << qry->lastError().text();
modal->setQuery(*qry);
modal->setHeaderData(0, Qt::Horizontal, "Pedido");
modal->setHeaderData(1, Qt::Horizontal, "Usuário");
modal->setHeaderData(2, Qt::Horizontal, "Bairro");
ui->tableView_pedidos->setModel(modal);
ui->comboBox_pedido->setModel(modal); // My ComboBox here!
ui->tableView_pedidos->resizeRowsToContents();
ui->tableView_pedidos->resizeColumnsToContents();
ui->tableView_pedidos->setColumnHidden(3, true);
ui->tableView_pedidos->setColumnHidden(4, true);
while(qry->next()){
QString usuario = qry->value(0).toString();
qDebug() << "id:" << usuario;
}
//qDebug() << (modal->rowCount());
}
void Pedidos::on_comboBox_pedido_currentIndexChanged(const QString &arg1)
{
QString id_pedido=ui->comboBox_pedido->currentText();
qDebug() << id_pedido;
QSqlQueryModel *modal2=new QSqlQueryModel();
//works until here...if uncomment any line from here nok
Login meudb; // this line uncommented, query on pushbutton is not working ( blank )
//QSqlQuery *qry=new QSqlQuery(meudb.mydb);
//meudb.connClose();
}
If I comment the line "Login meudb", the query results is ok.
So I tried to create a global "Login teste" to replace my local "Login conn".
I read many articles here.
Thanks in advance
Try this in your file pedidos.h :
#ifndef PEDIDOS_H
#define PEDIDOS_H
#include <QDialog>
#include <QTableView>
#include <QtWidgets>
class Login;
...

Is it possible to rename a qt sub window?

I set up a sub windwow in the QMdiArea of my mainwindow. Then I made a QDialog in which I want the user to enter the title name for the Sub window. But I always get an error when trying to Change the windowTitle() to that variable.
Is there any way to update the windowTitle()?
moduleName.cpp
#include "stdafx.h"
#include "moduleName.h"
#include "iwb4.h"
#include <Windows.h>
#include <QtGui/QAction>
#include <qdom.h>
#include <qmdiarea.h>
#include "ui_module_name.h"
#include "ui_iwb4.h"
#include <qmdisubwindow.h>
moduleName::moduleName(QDialog *parent)
: QDialog(parent)
{
ui.setupUi(this);
show();
// connect ok button to save the module name
connect(ui.okButton, SIGNAL(pressed()), this, SLOT(okClicked()));
}
moduleName::~moduleName()
{
}
void moduleName::okClicked()
{
iwb4 iwb;
QTextDocument* tName = ui.textEdit->document();
iwb.p_name = tName->toPlainText();
moduleName::close();
iwb.name();
}
moduleName.h
#ifndef MODULENAME_H
#define MODULENAME_H
#include <QtGui/QWidget>
#include "ui_module_name.h"
class moduleName : public QDialog
{
Q_OBJECT
public:
moduleName(QDialog *parent = 0);
~moduleName();
public slots:
void okClicked();
protected:
Ui::Dialog ui;
};
#endif // MODULENAME_H
iwb4.cpp
#include "stdafx.h"
#include "iwb4.h"
#include <Windows.h>
#include "ui_iwb4.h"
#include <QtGui/QAction>
#include <qdom.h>
#include <qmdiarea.h>
#include "ui_module_name.h"
#include "moduleName.h"
#include <qmdisubwindow.h>
iwb4::iwb4(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
iwb4::showMaximized();
p_name = " ";
// new module button
connect(ui.actionNewModule, SIGNAL(triggered()), this, SLOT(makeModule()));
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
iwb4::~iwb4()
{
}
void iwb4::newModule(QString name)
{
m_file = new QFile("C:\\Users\\Hanna\\Desktop\\iwb\\Projekt\\iwb4\\iwb4\\Datenmodell\\module.xml");
m_file->open(QFile::ReadWrite | QFile::Text);
QDomDocument doc;
doc.setContent(m_file);
m_file->close();
m_dockWidget = new QDockWidget(m_parent);
m_dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea);
m_dockWidget->showMaximized();
m_dockWidget->setTitleBarWidget(new QWidget());
m_pTableWidget = new QTableWidget(m_dockWidget);
m_dockWidget->setWidget(m_pTableWidget);
addDockWidget(Qt::LeftDockWidgetArea, m_dockWidget);
m_pTableWidget->setRowCount(10);
QDomElement elem = doc.documentElement();
m_pTableWidget->setColumnCount(elem.childNodes().count());
for (int i = 0; i < elem.childNodes().count(); i++)
{
QString header = elem.childNodes().at(i).toElement().attribute("Name");
m_TableHeader += header;
}
m_pTableWidget->setHorizontalHeaderLabels(m_TableHeader);
m_pTableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
m_pTableWidget->verticalHeader()->setVisible(false);
m_pTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
m_pTableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
m_pTableWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_pTableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_pTableWidget->setShowGrid(true);
m_pTableWidget->resizeColumnsToContents();
m_pTableWidget->resizeRowsToContents();
m_pTableWidget->setMaximumWidth(400);
m_pTableWidget->setMaximumHeight(300);
connect( m_pTableWidget, SIGNAL( cellDoubleClicked (int, int) ),
this, SLOT( cellSelected( int, int ) ) );
}
void iwb4::makeModule()
{
QString name;
name = p_name;
newModule(name);
QDockWidget *dock = m_dockWidget;
m_subWindow = ui.mdiArea->addSubWindow(dock);
ui.mdiArea->DontMaximizeSubWindowOnActivation;
dock->show();
dock->activateWindow();
// make rename option in right click menu
QMenu *menu = m_subWindow->systemMenu();
rename = new QAction(tr("Rename"),menu);
menu->addAction(rename);
connect(rename, SIGNAL(triggered()), this, SLOT(newName()));
}
void iwb4::newName()
{
moduleName* p_nameDialog = new moduleName();
}
void iwb4::name()
{
QString name = p_name;
m_subWindow->setWindowTitle(name);
}
iwb4.h
#ifndef IWB4_H
#define IWB4_H
#include <QtGui/QMainWindow>
#include "ui_iwb4.h"
class iwb4 : public QMainWindow
{
Q_OBJECT
public:
iwb4(QWidget *parent = 0, Qt::WFlags flags = 0);
~iwb4();
private:
private slots:
void makeModule();
public slots:
void newName();
public:
void newModule(QString name);
void name();
QFile* m_file;
QDockWidget* m_dockWidget;
QTableWidget* m_pTableWidget;
QMdiSubWindow* m_subWindow;
QStringList m_TableHeader;
QString p_name;
QAction *rename;
protected:
Ui::iwb4Class ui;
};
#endif // IWB4_H
Thanks for your help.
windowTitle() returns a copy, so this line is useless (you are modifying the copy only):
window->windowTitle() = name;
Instead, just use setWindowTitle directly:
window->setWindowTitle(name);
windowTitle() simply returns just another copy of the title of the window, so changing it does not change the title you want to change.
If you need to change the title, then directly use setWindowTitle(name); .
window->setWindowTitle(window->windowTitle()); is useless statement, because you set the title of window to its original title again.
void iwb4::name()
{
QString name;
name = p_name;
QMdiSubWindow* window;
window = m_subWindow;
window->windowTitle() = name;
window->setWindowTitle(window->windowTitle());
}
window->windowTitle( ) is a getter.
window->setWindowTitle( ) is a setter.
The getters job is to get you the value whereas the setters job is to update the value.
So running this will work:
void iwb4::name()
{
QString name;
name = "MyNewWindowName";
m_subWindow->setWindowTitle( name );
}
You have the same problem here:
void iwb4::makeModule()
{
QString name;
name = p_name;
newModule(name);
QDockWidget *dock = m_dockWidget;
m_subWindow = ui.mdiArea->addSubWindow(dock);
ui.mdiArea->DontMaximizeSubWindowOnActivation;
ui.mdiArea->windowTitle() = name;
ui.mdiArea->setWindowTitle(ui.mdiArea->windowTitle());
dock->show();
dock->activateWindow();
// make rename option in right click menu
QMenu *menu = m_subWindow->systemMenu();
rename = new QAction(tr("Rename"),menu);
menu->addAction(rename);
connect(rename, SIGNAL(triggered()), this, SLOT(newName()));
}
Change it to:
void iwb4::makeModule()
{
QString name;
name = p_name;
newModule(name);
QDockWidget *dock = m_dockWidget;
m_subWindow = ui.mdiArea->addSubWindow(dock);
ui.mdiArea->DontMaximizeSubWindowOnActivation;
//ui.mdiArea->windowTitle() = name; // <--
ui.mdiArea->setWindowTitle(name); // <--
dock->show();
dock->activateWindow();
// make rename option in right click menu
QMenu *menu = m_subWindow->systemMenu();
rename = new QAction(tr("Rename"),menu);
menu->addAction(rename);
connect(rename, SIGNAL(triggered()), this, SLOT(newName()));
}

Cannot get QString data from another header file

I have a login window where users input some text.
login.cpp:
#include "login.h"
#include "ui_login.h"
#include "mainwindow.h"
login::login(QWidget *parent) :
QDialog(parent),
ui(new Ui::login)
{
ui->setupUi(this);
this->setFixedSize(320,212);
connect(ui->_login, SIGNAL(clicked()), this, SLOT(rLogin()));
connect(ui->_close, SIGNAL(clicked()), this, SLOT(rClose()));
}
login::~login()
{
delete ui;
}
void login::rLogin()
{
prefix = ui->_prefix->text();
site = ui->_site->text();
dbname = ui->_database->text();
user = ui->_username->text();
QString pass = ui->_password->text();
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(site);
db.setDatabaseName(prefix + dbname);
db.setUserName(prefix + user);
db.setPassword(pass);
bool logged = db.open();
if (logged) {
rOpen();
} else {
int warning = QMessageBox::warning(this, tr("Hostel ERP Error"),
tr("Could not connect to database.\n"
"Please check your inputs."),
QMessageBox::Ok);
}
}
void login::rOpen()
{
mainwindow* openwindow = new mainwindow();
openwindow->show();
this->close();
}
void login::rClose()
{
this->close();
}
prefix, site, dbname, and user are defined as QString in login.h
login.h:
#ifndef LOGIN_H
#define LOGIN_H
#include <QDialog>
namespace Ui {
class login;
}
class login : public QDialog
{
Q_OBJECT
public:
explicit login(QWidget *parent = 0);
void rOpen();
QString prefix;
QString site;
QString dbname;
QString user;
~login();
I am trying to access prefix, site, dbname, and user from mainwindow.cpp
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QMessageBox>
#include <QPushButton>
#include <QAction>
#include <QMainWindow>
#include <QSqlRecord>
#include <login.h>
namespace Ui {
class mainwindow;
}
class mainwindow : public QMainWindow
{
Q_OBJECT
public:
explicit mainwindow(QWidget *parent = 0);
void rPopulate();
QPushButton *button;
login * log;
~mainwindow();
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "login.h"
#include "newbooking.h"
#include <qaction.h>
//somecode
login *log = new login;
QString table_schema = log->prefix + log->dbname;
however both log->prefix and log->dbname are empty. There is default text in ui->_prefix->text(); and ui->_database->text(); so they shouldn't be empty.
You are likely trying to access mainwindow::log i.e the log that is a member of mainwindow. You probably call rLogin on this function.
However you are getting empty values because you are creating a new object which has default values.
login *log = new login;
This line is part of the problem I assume. We wont know more before you show us how you call rLogin, but you want to check from the same object that you call it on.
Needed to declare QString as global var at the top of login.h in between #include "mainwindow.h" and login::login(QWidget *parent):, then in login.cpp define the QStrings.
eg. login.h
#include ...
extern QString site; //this
login::login(QWidget *parent) :
login.cpp
#include ...
QString example; //this
login::login(QWidget *parent) :
after that you can simply call them from whatever file you want. Silly me.