【问题标题】:signal points to slot in struct信号指向结构中的插槽
【发布时间】:2018-07-19 15:17:30
【问题描述】:

我希望将信号连接到结构内的插槽。我的结构看起来像:

//Header file

struct someStruct {
    public:
        int index;

    public slots:
        void someSlot();
};

QList<someStruct*> mListOfStructs;

然后我创建一个按钮,将其clicked() 信号转发给someSlot 函数。

//Source file

QPushButton *cmd = new QPushButton();
grd->addWidget(cmd, 3, 2, Qt::AlignCenter);
//grd is a QGridLayout somewhere inside the gui. I can see it and also the button.

现在将 clicked() 事件与特定结构内的插槽连接不起作用。

connect(cmd, SIGNAL(clicked()), mListOfStructs[3], SLOT(someSlot()));

一些消息来源告诉我,我必须添加一个元对象或某事。我试过了,但没有成功。也许你知道得更多。

我可能会使用How to connect in Qt signal and slot in dynamically added buttons to get in slot index of added button? 作为解决方法。

【问题讨论】:

  • 除此之外,您忘记了 Q_OBJECT 结构定义中的 Q_OBJECT 宏。
  • @G.M.信号槽需要Q_OBJECT:D,是的。也许是让它发挥作用的第一步。
  • ...我没有通过。现在实施解决方法:(
  • 什么?为什么不?你得到什么错误?
  • @ΦXocę 웃 Пepeúpa ツ 将public slots: 放在public: 之后出现错误:Parse error at ";" -> [moc_popupMessages.cpp] Error 1 和将public: 放在public: 之后出现错误:public slots38@33 987654339@ -> [moc_bla.o] Error 1

标签: qt struct connection signals-slots


【解决方案1】:

您的结构需要 Q_Object 元属性才能发出信号并接收插槽事件...

struct testStruct : public QObject
{
    Q_OBJECT
    public:
        int index;
        testStruct():index(0){}

    public slots:
        void someSlot()
        {
            qDebug() << "slot called!";
        }
};

之后就可以正常连接了:

testStruct *ts= new testStruct;
connect(this, SIGNAL(someSignal()), ts, SLOT(someSlot()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2013-11-13
    • 2018-12-06
    • 2022-08-03
    相关资源
    最近更新 更多