是否可以从 const 方法发出 Qt 信号?
特别是,我正在为 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 &”
In particular, I am implementing a QWizardPage ("MyWizardPage") for a QWizard, and I want to emit a signal ("sigLog") from my override of the QWizardPage::nextId virtual method.
Like so:
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");
}
But when I try this, I get the following compile error on the Q_EMIT line:
Error 1 error C2662: 'MyWizardPage::sigLog' : cannot convert 'this' pointer from 'const MyWizardPage' to 'MyWizardPage &'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过在信号声明中添加“const”,可以从 const 方法发出信号,如下所示:
我测试了这个,它确实编译并运行,即使您实际上没有实现自己将信号作为正常方法(即 Qt 可以接受)。
It is possible to emit a signal from a const method by adding "const" to the signal declaration, like so:
I tested this and it does compile and run, even though you don't actually implement the signal as a normal method yourself (i.e. Qt is okay with it).
您可以尝试创建另一个类,将其声明为向导页面的友元,并将其作为可变成员添加到向导中。之后你可以发出它的信号而不是向导的信号。
或者你可能只是使用
不推荐的方式,因为 const_cast 是一个 hack,但它要短得多:)
You may try to create another class , declare it as friend for your wizard page and add to wizard as a mutable member. after that you may emit it's signal instead of wizard's.
or you may just use
that is not recommended way, because const_cast is a hack, but it's much shorter :)