【发布时间】:2020-10-24 11:24:13
【问题描述】:
我正在使用信号槽做简单的程序,如果我在一个计数器中增加或减少值,它将通过使用槽和信号在其他计数器中增加和减少。 我将插槽设为私有,因此我们不能从外部使用它们并从简单方法(非插槽)调用信号。 qt哲学中的正常实现吗?我不喜欢 Increment() 方法和 releaseIncrement() 做同样的工作,我能以某种方式避免这种情况吗?将插槽保持私有状态是否正常?这是我的代码:
#ifndef COUNTER_H
#define COUNTER_H
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter(int startValue);
int Increment();
int Decrement();
void printValue();
private slots:
void releaseIncrement();
void releaseDecrement();
signals:
void wasIncremented();
void wasDecremented();
private:
int m_count;
};
#endif // COUNTER_H
#include "counter.h"
#include <iostream>
Counter::Counter(int startValue)
{
m_count = startValue;
}
void Counter::printValue()
{
std::cout <<"value is: " <<m_count <<std::endl;
}
int Counter::Increment()
{
m_count++;
std::cout <<"m_count was incremented by Increment() method. Now m_count is: " <<m_count <<std::endl;
emit wasIncremented();
return m_count;
}
int Counter::Decrement()
{
m_count--;
std::cout <<"m_count was decremented by Decrement() method. Now m_count is: " <<m_count <<std::endl;
emit wasDecremented();
return m_count;
}
void Counter::releaseIncrement()
{
m_count++;
std::cout <<"m_count was incremented by releaseIncrement() slot. Now m_count is: " <<m_count <<std::endl;
}
void Counter::releaseDecrement()
{
std::cout <<"m_count was decremented by releaseDecrement() method. Now m_count is: " <<m_count <<std::endl;
m_count--;
}
int main()
{
Counter a(0);
Counter b(10);
QObject::connect(&a, SIGNAL(wasIncremented()), &b, SLOT(releaseIncrement()));
QObject::connect(&b, SIGNAL(wasIncremented()), &a, SLOT(releaseIncrement()));
QObject::connect(&a, SIGNAL(wasDecremented()), &b, SLOT(releaseDecrement()));
QObject::connect(&b, SIGNAL(wasDecremented()), &a, SLOT(releaseDecrement()));
}```
【问题讨论】:
-
我不清楚你所说的“释放”是什么意思。您可以做的一种简化是让
Increment直接调用releaseIncrement。但我仍然不明白目标是什么。 -
@drescherjm 但是如果我将发射信号放在插槽方法中,它将是无限循环。所以我把它们分成简单的发射方法和不发射的槽。很奇怪吗?
-
@drescherjm 我的错,已编辑。我的意思是如果我将删除 Increment() 和 Decrement() 并将发射器放在插槽中,我将获得无限循环。就像在 a 上使用 releaseIncrement() 时一样,然后在 b 上调用 releaseIncrement() 调用 wasIncremented() 并在 a 上调用 releaseIncrement() 等等......
-
ADV 你的cmets是针对我的吗?如果是这样,你误解了我的建议。我会写它作为答案。