如何从其他形式修改mainform.ui组件,反之亦然

时间:2018-10-26 12:45:41

标签: c++ qt

如何从其他形式修改mainform.ui组件(Qlabels,comboBox等),反之亦然。 例如:1-mainform.ui有一个按钮(即所谓的“ button1”),当我单击button1时,我想禁用位于otherform.ui中的按钮(即所谓的“ button2”) 2-当我单击otherform.ui的button2时,我想清除位于mainform.ui中的comboBox

在ex#1中:我不知道如何使用方式引用otherform.ui。 obj.ui.button2.disabled();编译器告诉我一个错误!。

在ex#2中:在otherform.cpp中,我引用mainform.ui,在运行应用程序时创建对象类型mainform,(mainform obj;),然后创建obj.ui.comboBox.clear();。 ,错误说> mainform * ui是私有的,所以我进入mainform.h并将其公开,那么就没有错误的信号发生,但是什么也没有发生。

有人可以帮助我吗?对不起,我的英语。

1 个答案:

答案 0 :(得分:0)

您可以使用SIGNAL和SLOT机制将鼠标单击从一种形式发送到另一种形式。唯一需要的是,您所引用的表单必须被视为“ Q_Object”。

示例

表格1

#include <QObject>                  //must include this

class Form1 : public QObject
{
 Q_OBJECT                            //must include this 

 public:
    Form1(){ connect(&btn1, SIGNAL(clicked()), this, SLOT(clicked_btn1())); }

 private:
    QPushButton btn1;

 public slots:                       /*slots are methods which are triggered when 
                                       signals are emitted */
    void disable_btn(){btn1.disable();}
    void clicked_btn1(){emit btn1_signal();}//signals are triggered by 'emit'

 signals:                           /*signals are events waiting to be triggered*/
    void btn1_signal();

};

表格2

#include <QObject>                  //must include this

class Form2 : public QObject
{
 Q_OBJECT                            //must include this 

 public:
    Form2(){ connect(&btn2, SIGNAL(clicked()), this, SLOT(clicked_btn2())); }

 private:
    QPushButton btn2;
    QComboBox cmb;

 public slots:                       /*slots are methods which are triggered when 
                                       signals are emitted */
    void clear_cmb(){cmb.clear();}
    void clicked_btn2(){emit btn2_signal();}//signals are triggered by 'emit'

 signals:                           /*signals are events waiting to be triggered*/
    void btn2_signal();

;     };

主要

//include all the header files of form1 and form2
//include <QObject> file and Q_OBJECT

Form1 *form_1 = new Form1();
Form2 *form_2 = new Form2();

//connecting signals from one form to slots of another form
connect(form_1, SIGNAL(btn1_signal()), form_2, SLOT(disable_btn()))
connect(form_2, SIGNAL(btn2_signal()), form_1, SLOT(clear_cmb()))

因此,这是通过单击另一个对象内的按钮来禁用一个对象的按钮的方式。

由于这是一个重要的话题,因此这是Qt的链接,其中包含更多说明和简单示例 http://doc.qt.io/archives/qt-4.8/signalsandslots.html