简化代码:
#include "dialog.h"
#include "ui_dialog.h"
#include "mainwindow.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_clicked()
{
ui->lineEdit->text();
// Needs code here to update the table in the mainwindow file. But i cannot access the mainwindows table object...
close();
}
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionadd_triggered()
{
Dialog *dialog = new Dialog(this);
dialog->show();
}
我尝试过“包含”适当的文件。我尝试从对话框文件(我评论过的地方)访问 Table 对象,但没有任何乐趣。
对象在单独的文件中定义这一事实是无关紧要的:当您的程序运行时,它们将存储在执行该程序的第一台机器的内存中,并且应该能够相互访问:您所需要的只是让您的对象之一“意识到”对方。
如果您真正想要的是在单独的
QDialog
中输入文本(即不使用 delegate 也不使用 index 小部件,则两者之间的简单信号/槽连接即可。Dialog
类更干净,因为对象只需要访问它们的子级,而不是访问它们的“表兄弟”。
MainWindow
了解Dialog
;事实上,这是创建指向 Dialog
实例的指针的地方。有了这些知识,您需要的是:
dialog.h
中,创建一个采用 QString
/QString
引用作为参数的信号:class Dialog {
Q_OBJECT
public:
// Your methods go here
public slots:
void on_pushButton_clicked();
signals:
void text_added(const QString&);
};
mainwindow.h
中,创建上述信号将触发的插槽。它需要以 QString
作为参数:class MainWindow {
Q_OBJECT
public:
// Your methods go here
public slots:
void on_actionadd_triggered();
void on_dialog_text_added(const QString&);
};
mainwindow.cpp
中,定义插槽并将对话信号连接到它:void MainWindow::on_actionadd_triggered()
{
Dialog *dialog = new Dialog(this);
connect(dialog, &Dialog::text_added, this, &MainWindow::on_dialog_text_added);
dialog->show();
}
void MainWindow::on_dialog_text_added(const QString& text)
{
// Here goes the instruction, for instance:
// QAbstractItemModel* model = ui->Table->model();
// model ->setData(model ->index(...), text, Qt::EditRole);
}