Reputation: 25
I want to pass data between MainWindow and Widget where I draw graph. In MainWindow I load a data, do few things and create dynamic array.
I don't know how to do this between two files mainwindow.cpp and drawwidget.cpp
This is my Code:
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <fstream>
#include <iostream>
#include <iomanip>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
wyczyscpkt(Tab_pkt);
wyczysc(Tab_we);
delete ui;
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
private slots:
void on_saveimageButton_clicked();
//other functions
public slots:
private:
Ui::MainWindow *ui;
//my functions
public slots:
};
#endif // MAINWINDOW_H
drawwidget.cpp:
DrawWidget::DrawWidget(QWidget *parent) :
QWidget(parent)
{
}
void DrawWidget::paint(QPainter &painter, struct *myarray) //here I need pass array from mainwindow.cpp
{
//drawing function
}
void DrawWidget::savePng()
{
//save image function
}
drawwidget.h:
#ifndef DRAWWIDGET_H
#define DRAWWIDGET_H
#include <QWidget>
#include "mainwindow.h"
class DrawWidget : public QWidget
{
Q_OBJECT
public:
explicit DrawWidget(QWidget *parent = 0);
protected:
void paintEvent(QPaintEvent *);
void paint(QPainter &painter);
void savePng();
};
#endif // DRAWWIDGET_H
Upvotes: 1
Views: 4276
Reputation: 4005
You have to include
#include "drawwidget.h"
your DrawWidget in MainWindow. After that you can instantiate a DrawWidget Object and use it.
Upvotes: 0
Reputation: 5472
You can use signals and slots in passing data between two QObject
based classes (like QMainWindow and QWidget) which don't know anything about each other.
Q_DECLARE_METATYPE
in order to pass it in a signal parameter.Example:
typedef struct
{
} MyStruct;
Q_DECLARE_METATYPE(MyStruct);
class MainWindow : public QMainWindow
{
Q_OBJECT
signals:
void dataChanged(const MyStruct &struct);
};
class DrawWidget : public QWidget
{
Q_OBJECT
public slots:
void handleData(const MyStruct &struct);
};
Let's say you instantiate your objects in your main(). You can connect the MainWindow signal to DrawWidget slot like this:
MainWindow m;
DrawWidget d;
QObject::connect(&m, SIGNAL(dataChanged(const MyStruct &)),
&d, SLOT(handleData(const MyStruct &)));
When you have your data ready in your MainWindow you emit the signal with the data struct as a parameter.
There is a good explanation of signals and slots here.
Upvotes: 2