Qt signal and slot function parameters can only be based on Qt's basic types, such as QString, int, bool, etc. If you want to pass a custom type, it will not work by default.
Take the structure as an example below to realize the transfer of structure type data
head File:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QMetaType>
#include<QDebug>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
typedef struct
{
QString name;
QString color;
}MyStruct;
private slots:
void on_testBtn_clicked();
signals:
void AddDocItemSignalNew(MyStruct variant);
private slots:
void AddDocItemNew(MyStruct variant);
};
#endif // MAINWINDOW_H
cpp file
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qRegisterMetaType<MyStruct>("MyStruct");
connect(this, SIGNAL(AddDocItemSignalNew(MyStruct)),this, SLOT(AddDocItemNew(MyStruct)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_testBtn_clicked()
{
MyStruct myStruct;
myStruct.color = "red";
myStruct.name = "name";
emit AddDocItemSignalNew(myStruct);
}
void MainWindow::AddDocItemNew(MyStruct variant)
{
qDebug()<<variant.color<<variant.name;
}
Compared with the traditional int and other types, only increased
qRegisterMetaType<MyStruct>("MyStruct");
After packaging in this way, we can use Qt's signal and slot functions to pass custom data structures.