[Solved]Reduce duplicate codes of connect
-
I always deal with codes like these
connection
@
connect(ui->slider_interval_, SIGNAL(valueChanged(int)), this, SLOT(change_spinbox_pae_interval(int)));
connect(ui->spinbox_interval_, SIGNAL(valueChanged(int)), this, SLOT(change_slider_pae_interval(int)));
@slot
@
void colorBalanceWidget::change_slider_pae_interval(int value)
{
if(ui->slider_interval_->value() != ui->spinbox_interval_->value()){
ui->slider_min_slope_->setValue(value);
}
}void colorBalanceWidget::change_spinbox_pae_interval(int value)
{
if(ui->slider_interval_->value() != ui->spinbox_interval_->value()){
ui->spinbox_interval_->setValue(value);
}
}
@Do you have a solution to avoid these duplicate codes?
The best I can do is encapsulate the codes and call them
in different slots.Thanks@
template<typename T, typename U, typenmae V, typename W>
void set_value(T *fir, U *sec, V *target, W value)
{
if(fir->value() != sec->value()){
target->setValue(value);
}
}@don't looks like a good solution
-
Are you trying to use one slot for multiple purposes?
To get around this issue I have created my signals with a "signal type" variable (not actually that name) then you can effectively use the same slot for many purposes (if that is what you want to do)
For example the signal function could be like:
@some_signal(eSomeEnumType type, int val);@The slot would take the same types:
@void slot_to_do_thing(eSomeEnumType type, int val)
{
// (if you have many options use switch)
if (eSlider == type)
{
do thing to slider....
}
else if (eSpin == type)
{
do thing to spinbox
}
}@Edit:
Forgot to add: You could even pass in your template type in if you wanted to reduce the if/switch statements. Note: if this is a signal sent between different threads you have to register the eNum/Template type with the following line of code (I usually stick this in at start-up time:
@qRegisterMetaType<someTypeOrEnum>("someTypeOrEnum");@ -
it's safe to do to the following:
@
connect(ui->slider_interval_, SIGNAL(valueChanged(int)), ui->spinbox_interval_, SLOT(setValue(int)));
connect(ui->spinbox_interval_, SIGNAL(valueChanged(int)), ui->slider_interval_, SLOT(serValue(int)));
@
you wont start a infinite loop with such connect-statements ;)
Since Qt already only triggers the signals only when the value changes.