Qt如何实现按住Ctrl键,点击QSpinBox成倍加减

需求

有时候,一个QSpinBox,点击上下加减,进行输入值调节时候,一直一个小步长,调节太慢,一直一个大步长,调节又太粗糙。因此,就需要做一个快捷方式:比如,按住ctrl键,调节步长变大,松开ctrl键,调节步长恢复原小步长。
其实,最好的是重写QSpinBox类。
下面讲一下,简单实现。

实现结果:

Qt如何实现按住Ctrl键,点击QSpinBox成倍加减_第1张图片

实现原理:

1.捕捉键盘事件;
2.在ctrl按键按下时,改变QSpinBox的步长。

xxx.h文件:

#ifndef TESTSPINBOX_H
#define TESTSPINBOX_H

#include 
#include "ui_testspinbox.h"
#include 

class testSpinBox : public QMainWindow
{
	Q_OBJECT

public:
	testSpinBox(QWidget *parent = 0);
	~testSpinBox();
protected:
	virtual void keyPressEvent(QKeyEvent* evt);
	virtual void keyReleaseEvent(QKeyEvent* evt);

private slots:
	void mySpinBoxChangedSlot(double);
private:
	Ui::testSpinBoxClass ui;
	const double CtrlStep = 10;
	bool _ctrl_pressed;
	double mSpinStep;
};

#endif // TESTSPINBOX_H

xxx.cpp文件

#include "testspinbox.h"

testSpinBox::testSpinBox(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	_ctrl_pressed = false;
	mSpinStep = ui.dsbox->singleStep();
	connect(ui.dsbox, SIGNAL(valueChanged(double)), this, SLOT(mySpinBoxChangedSlot(double)));
}

testSpinBox::~testSpinBox()
{

}

void testSpinBox::mySpinBoxChangedSlot(double value)
{	

	ui.textBrowser->append("Current Value: " + QString::number(value));
}

void testSpinBox::keyPressEvent(QKeyEvent* evt)
{
	if (evt->key() == Qt::Key_Control)
	{
		_ctrl_pressed = true;
		ui.textBrowser->append("Button Ctrl is Pressed... ");
		ui.dsbox->setSingleStep(CtrlStep);
	}
}
void testSpinBox::keyReleaseEvent(QKeyEvent* evt)
{
	if (evt->key() == Qt::Key_Control)
	{
		_ctrl_pressed = false;
		ui.textBrowser->append("Button Ctrl is Released... ");
		ui.dsbox->setSingleStep(mSpinStep);
	}
}

你可能感兴趣的:(Qt)