【问题标题】:Is it possible to emit a Qt signal from a const method?是否可以从 const 方法发出 Qt 信号?
【发布时间】:2011-08-12 11:49:58
【问题描述】:

特别是,我正在为 QWizard 实现一个 QWizardPage(“MyWizardPage”),并且我想从我的 QWizardPage::nextId 虚拟方法的覆盖中发出一个信号(“sigLog”)。

像这样:

class MyWizardPage
    : public QWizardPage
{
    Q_OBJECT
public:
    MyWizardPage();
    virtual int nextId() const;
Q_SIGNALS:
    void sigLog(QString text);
};

int MyWizardPage::nextId() const
{
    Q_EMIT sigLog("Something interesting happened");
}

但是当我尝试这个时,我在 Q_EMIT 行得到以下编译错误:

错误 1 ​​错误 C2662:“MyWizardPage::sigLog”:无法将“this”指针从“const MyWizardPage”转换为“MyWizardPage &”

【问题讨论】:

    标签: qt signals-slots


    【解决方案1】:

    可以通过在信号声明中添加“const”来从 const 方法发出信号,如下所示:

    void sigLog(QString text) const;
    

    我对此进行了测试,它确实编译并运行,即使您自己实际上并没有将信号作为普通方法实现(即 Qt 可以接受)。

    【讨论】:

    • 我试过了,但我无法连接到这样的信号。
    【解决方案2】:

    您可以尝试创建另一个类,将其声明为您的向导页面的朋友,并将其作为可变成员添加到向导中。之后你可以发出它的信号而不是向导的信号。

    class ConstEmitter: public QObject
    {
       Q_OBJECT
       ...
       friend class MyWizardPage;
     Q_SIGNALS:
        void sigLog(QString text);
    
    };
    
    class MyWizardPage
        : public QWizardPage
    {
        Q_OBJECT
    public:
        MyWizardPage();
    protected:
        mutable CostEmitter m_emitter;
    Q_SIGNALS:
        void sigLog(QString text);
    };
    
    int MyWizardPage::nextId() const
    {
        Q_EMIT m_emitter.sigLog("Something interesting happened");
    }
    
    MyWizardPage::MyWizardPage()
    {
      connect(&m_emitter,SIGNAL(sigLog(QString)),this,SIGNAL(sigLog(QString)));
    }
    

    或者你可以使用

    int MyWizardPage::nextId() const
    {
        Q_EMIT const_cast<MyWizardPage*>(this)->sigLog("Something interesting happened");
    }
    

    这是不推荐的方式,因为 const_cast 是一种 hack,但它要短得多:)

    【讨论】:

    • 感谢您提供有趣的解决方法。我找到了更简单的解决方案(请参阅我的答案),但我肯定会使用您的建议。
    • 是的,你的解决方案更好:)))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多