开发者

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)); 开发者_Go百科 
     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 (i.e. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜