[Qt-interest] QAbstractSlider usage

Ferenc Stelcz ferenc at stelcz.hu
Tue May 26 17:10:09 CEST 2009


Ole Streicher wrote:
> Hi,
> 
> I have a question regarding the use of a QAbstractSlider (QScrollBar,
> QSlider): In my program, I have several ways to zoom something (f.e. a
> diagram), one is a QSlider; the other an editable line. What I need now is to
> connect the combobox as well as the slider to my zoom function, and to
> update the other element with it. 
> 
> How can one avoid this signal ping-pong between different widgets? 
> 
[...]

Hello Ole!

Small theoretical workaround (haven't tried it, so may be wrong):

Make your own QLineEdit subclass and
- add a slot called inputEntered()
- add a signal, let's call it valueEntered(int).

Introduce a private member variable in your class (lets call it 
currentZoom) which holds the value of the current zoom.
Add
- a signal to your class called updateMyWidgets(int)
- a slot to your class called doUpdateWidgets(int)

Now create one single one doMyZoom slot which accepts an integer value 
as parameter. FYI: AFAIK QSlider only accepts integer values, so if you 
enter a floating point/double value in your lineedit, it will be 
rounded/truncated.

As next,
connect(slider, SIGNAL(valueChanged(int)), yourwidget, SLOT(doMyZoom(int))

connect(lineedit, SIGNAL(editingFinished(), lineedit, SLOT(inputEntered()));

connect(lineedit, SIGNAL(valueEntered(int)), yourwidget, SLOT(doMyZoom(int))

connect(yourwidget, SIGNAL(updateMyWidgets(int)), yourwidget, 
SLOT(doUpdateWidgets(int)))

Add a simple check to your doMyZoom(int zoom) like this:

if(currentZoom != zoom)
{
	do zooming etc...
	
	currentZoom = zoom;

	emit(updateMyWidgets(currentZoom));
}

Implement the slot inputEntered() as follows:

void YourClass::inputEntered()
{
	bool ok = false;
	int val = (lineedit->text()).toInt(&ok, 10);
	if(ok)
	{
		emit(valueEntered(val));
	}
}

Implement doUpdateWidgets(int value) as follows:

void YourClass::doUpdateWidgets(int value)
{
	QString zoomText = QString::number(value, 10);

	if(zoomText != lineedit->displayText())
	{
		lineedit->setText(zoomText);
	}
	
	if(slider->value() != value)
	{
		slider->setValue(value);
	}
}

Seems a bit complicated to me, am a bit tired right now :) but anyways: HTH

--
Ferenc Stelcz
Junior Software Engineer

Banyan Technologies LLC.



More information about the Qt-interest-old mailing list