使用Qt,我知道private slots意味着当直接调用时,插槽是私有的,但是connect()仍然可以允许信号连接到插槽,无论是私有的、公共的,或者我猜是受保护的。
那么,有没有一种方法可以让一个插槽真正成为私有的,这样只能在一个类中进行连接呢?我在这里想的是,因为QTimer::singleShot调用了一个槽,但是我想调用的函数,我不想在类之外被访问。我相信还有其他原因,但这是目前我发现的主要原因。
发布于 2012-06-21 19:09:17
如果你真的想强制这样做,并且你认为适当的文档不能解决这个问题,那么可以将插槽添加到一个额外的类中,这个类有一个私有构造函数,并将调用传递给你的真正的类。
class PrivateSlotClass : public QObject
{
Q_OBJECT
friend class YourRealClass;
PrivateSlotClass( YourRealClass ) : QObject( YourRealClass ){}
private slots:
void theSlot(){ static_cast<YourRealClass*>(parent())->theFunction();
};
class YourRealClass : public QObject
{
public:
YourRealClass();
friend class PrivateSlotClass;
private:
void theFunction();
};
YourRealClass::YourRealClass(){
PrivateSlotClass* myPrivateSlot = new PrivateSlotClass(this);
QTimer::singleShot( 50, myPrivateSlot, SLOT(theSlot()) );
}
void YourRealClass::theFunction()
{
/* your slot code here */
}发布于 2012-06-21 19:07:33
只需使用timerEvent和startTimer代替slot和QTimer::singleShot即可。
发布于 2012-06-21 19:41:22
我认为可以向您的槽和相应的信号中再添加一个参数,如下所示:
...
private slots:
void slot(..., QObject* sender = 0);
...
void YourClass::slot(..., QObject* sender)
{
if (sender != (QObject*)this)
{
/* do nothing or raise an exception or do whatever you want */
}
...
}当然,它不会让你的插槽“完全”私有,但它不会让你的代码在收到来自对象外部的信号后被执行。
https://stackoverflow.com/questions/11136689
复制相似问题