简体   繁体   中英

How would you access a widget from a function in another file in Qt?

I'm developing a project, and I first began making it without GUI, but now I'm porting it to Qt, but I have a problem.

I have my "old" implementation in a separate file, and I try to access the MainWindow widget from it, in order to output to a QTextBrowser, but I'm not able to do so.

In mainwindow.cpp I have this:

void MainWindow::addString(char* text)  
     {  
     std::string input = text;  
     ui->textBrowser->append(QString::fromStdString(input));  
     return;  
     }  

In mainwindow.h:

class MainWindow : public QMainWindow  
     {
     Q_OBJECT
     public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    private slots:
    void on_showWelcome_triggered();
    void on_showArithmetic_triggered();
    private:
    Ui::MainWindow *ui;
    public slots:
    void btnResolveClicked();
    void btnClearClicked();
    void hideAll();
    void addString(char* output);
    };
    #endif // MAINWINDOW_H

And in simple_mode.cpp:

void test()  
     {
     MainWindow *gui = new MainWindow;
     gui->addString("WORKS");
     MainWindow:: = gui;  
     }

However this doesnt append "WORKS" to the textbrowser, which is what I need, I think it adds it to another instance of text browser which isnt the same as the mainwindow.

EDIT: What I wanted to do was appending a line of text directly from simple_mode.cpp to the textbrowser. By the way, simple_mode was written without any Qt aid, that's why I used std strings, and currently the textbrowser widget acts as a virtual terminal output screen, and instead of using printf like I did before, I wanted to append lines to the textbrowser. However I already found my way through, I don't need this now.

I needed help

It's really hard to tell what do you want to achieve and pieces of code do not cover all possible erroneous areas (ie where's the MainWindow constructor's definition?). Also, the formatting is terrible - please use idents and consistent bracing style.

My advice is simply call show on MainWindow instance. Unless you don't mess up ui initialization in MainWindow constructor, this snippet should be enough. If it is not - supply us with missing pieces of code.

void test()  
{
    MainWindow *gui = new MainWindow;
    gui->addString("WORKS");
    gui->show();
}

As a side note, your addString method should look like this:

void MainWindow::addString(char* text)
{
    ui->textBrowser->append(QString::fromAscii(text));
}

Return statement is completely unnecessary, and assigning text to std::string is likely to cause unnecessary memory allocation. It's not like it is the end of the world, but it's really, really bad practice for a C++ programmer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM