如何在qt中从另一个类调用函数

how to call function from another class in qt?

本文关键字:另一个 调用 函数 qt      更新时间:2023-10-16

这是我的代码:

主窗口.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "secd.h"

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::on_actionSettings_triggered()
{
secD secdialog;
secdialog.setModal(true);
secdialog.exec();
}

void function1()  //this function I need to call from secd.cpp
{
//do something   
}

secd.cpp:

#include "secd.h"
#include "ui_secd.h"
#include <QMessageBox>
#include "mainwindow.h"

secD::secD(QWidget *parent) :
QDialog(parent),
ui(new Ui::secD)
{
ui->setupUi(this);
}
secD::~secD()
{
delete ui;
}
void secD::on_buttonBox_accepted()
{
QMessageBox msgBox;
msgBox.setWindowTitle("About");
msgBox.exec();
function1();  //how to call this function?
}

所以我需要从主窗口.cpp中的secd.cpp函数1((调用我该怎么做?也许有连接、信号和插槽?但我不懂那些文件。

函数的原型应该直接或在头文件中声明:


#include "secd.h"
#include "ui_secd.h"
#include <QMessageBox>
#include "mainwindow.h"
void function1();    // <---------------------------
secD::secD(QWidget *parent) :
QDialog(parent),
ui(new Ui::secD)
{
ui->setupUi(this);
}
secD::~secD()
{
delete ui;
}
void secD::on_buttonBox_accepted()
{
QMessageBox msgBox;
msgBox.setWindowTitle("About");
msgBox.exec();
function1();  //how to call this function?
}