如果「測試」是類或結構有了解主窗口對象或特別是關於它的子對象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