Manipulating QT Ui with different source files

﹥>﹥吖頭↗ 提交于 2019-12-06 15:57:10

Try this:

class Functions; // Forward declaration    
class myWidget : public QWidget
{
    Q_OBJECT
public:
    explicit myWidget(QWidget *parent = 0);
    ~myWidget();

private slots:
    void on_pushButton_clicked();

private:
    Ui::myWidget *ui;
    Functions*fun;  // member ptr
    friend class Functions; // allow access to private members
};

And implementation:

[...]
#include "Functions.h"

myWidget::myWidget(QWidget *parent) :
   QWidget(parent),
   ui(new Ui::myWidget),
   fun(new Functions(this))   // initializer list
{
    ui->setupUi(this);
}

myWidget::~myWidget()
{
    delete ui;
    delete fun;  // we new'ed it so we have to delete it!
}

void myWidget::on_pushButton_clicked()
{
    fun->doIt(); // call to the function
}

The Function.h

[...]

class myWidget; // Forward declaration

class Functions
{
public:
    Functions(myWidget *wid);
    void doIt();
private:
    myWidget *widget; // Member pointer to the main widget
};

And the Function.cpp

[...]

#include "ui_mywidget.h"         
#include "myWidget.h"

Functions::Functions(myWidget *wid):widget(wid) // init the ptr
{
}

void Function::doIt()            
{
   widget->ui->listWidget->addItem("SomeItem"); // add the items
}

You probably need to include both "myWidget.h" and "ui_mywidget.h" in your functions.cpp file. You need the first to know what myWidget is, in order to access it's ui member variable. You need the second to know what the ui variable contains.

Something along these lines should work, although probably not as you expect:

#include "functions.h"
#include "myWidget.h"
#include "ui_mywidget.h"

Functions::Functions()
{
    // The following line creates a new widget, and does not use any existing
    // widgets (like you probably expect it to).
    myWidget *ModUi = new myWidget;
    ModUi->ui->listWidget->addItem("SomeItem");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!