如果“测试”是类或结构有了解主窗口对象或特别是关于它的子对象TextBrowser。
Ui在MainWindow构造函数中创建,所以在使用它之前必须创建它。
而且除了这是一个不好的做法,做你想做的事,更好的解决方案是连接从测试类的主窗口
时隙信号(即必须继承自QObject)如此糟糕的做法看起来:
//main.cpp
#include "test.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//instance of MainWindow
MainWindow w; // here constructor of MainWindow creates ui and all the childs
w.show();
//instance of test struct
test t;
//behind the design mode is creation of code with objects that you can create "manually" typing them
//to see the ui additional files just press Ctrl and mouse click (for example) on function ui->setupUi(this) in MainWindow constructor
//it's automatically generated code for ui created according to what you've created in design mode
//so here textBrowser pointer of object t is points to textBroswer of ui of object w
t.textBrowserFromTestStruct = w.findChild<QTextBrowser*>("textBrowser");
//get error if object f ui has no QTextBrowser named textBrowser
Q_ASSERT(t.textBrowserFromTestStruct);
//invoke t object function to append text to f textBrowser 10 times
for(int i = 0; i < 10; ++i)
t.TextAp("Hello World ");
return a.exec();
}
//test.h
#ifndef TEST_H
#define TEST_H
#include "mainwindow.h"
#include <QTextBrowser>
struct test
{
QTextBrowser *textBrowserFromTestStruct;
public:
void TextAp(QString text){textBrowserFromTestStruct->append(text);}
};
#endif // TEST_H
//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();
Ui::MainWindow *getUI(){return ui;}
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
//mainwindow.cpp
#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_pushButton_clicked()
{
}
阅读有关信号和插槽的信息和插槽以获取您想要的信号和插槽的自己的解决方案。当然了解更多关于C++的理论知道什么是类和结构的私有成员,命名空间和范围是什么
你必须指向一个变量,而不是类名。什么是'Ui :: MainWindow'和它的外观? – vahancho
- >必须指向该类的一个对象,并且似乎您正在直接使用该类。 – acostela
如果遇到奇怪的崩溃,请粘贴main函数的代码。 – RobbieE