Ace Ace - 27 days ago 8
C++ Question

Qt - signals and slots in 2 classes

I am "playing" with signals and slots in Qt.
I made 2 classes (MainWindow,DatabaseManager)

databasemanager.h

class DatabaseManager : public QObject
{
Q_OBJECT
QSqlDatabase database;
public:
DatabaseManager();
signals:
void TextSignal(const QString);
};


databasemanager.cpp

DatabaseManager::DatabaseManager()
{
database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName("database.sqlite");

if( !database.open() )
qDebug() << "Cannot open connection with database";
else
{
emit TextSignal("Connected");
qDebug() << "Connected";
}
}


mainwindow.h

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private slots:
void WriteText(const QString text);

private:
Ui::MainWindow *ui;
DatabaseManager db;
};


mainwindow.cpp

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(&db,SIGNAL(TextSignal(QString)),this,SLOT(WriteText(QString)) );
}

void MainWindow::WriteText(const QString text)
{
ui->textEdit->append(text);
}


And here is my question - What am I doing wrong?
While debugging text "Connected" is printed in Debug Window but it is not showed in textEdit.

Answer

db object's constructor called before (even before mainWindow constructor and setupUi).

private: Ui::MainWindow *ui; DatabaseManager db;

QObject::connect(&db,SIGNAL(TextSignal(QString)),this,SLOT(WriteText(QString))

Signal was emitted before connect and before creation of ui->textEdit.

Comments