如何在QT的其他小部件中调用创建的小部件对象

How to call created widget object in other widgets in QT

本文关键字:小部 调用 对象 创建 其他 QT      更新时间:2023-10-16

在我的应用程序中,我有三个小部件,我在main()函数中为所有小部件创建了对象,但我不知道如何在其他小部件中调用创建的对象,请指导我,我这样创建对象:

#include <QtGui/QApplication>
#include "widget.h"
#include "one.h"
#include "two.h"
int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  Widget *w = new Widget();
  One *one = new One();
  Two *two = new Two();
  w->show();
  return a.exec();
}

创建的对象如何调用其他小部件?

您不应该'调用'它们,而是通过Qt信号槽机制连接它们:

class One : public QObject {... boilerplate omitted
public slots:
   void slotWithVoid(){ emit slotWithInt(1); }
signals:
   void signalWithInt(int); // filled in by Qt moc
};
// note: give your widgets an owner
auto *w = new QButton(&app);
auto *one = new One(&app);
auto *two = new Two(&app);
connect(w, &QButton::click,
        one, &One::slotWithVoid);
connect(one, &One::signalWithInt,
        two, &Two::slotWithInt);

现在当一些事情发生(例如按钮点击),Qt事件系统将照顾你的对象被调用在正确的顺序,从正确的线程,安全等…