Qt如何實現按住Ctrl鍵,點擊QSpinBox成倍加減

需求

有時候,一個QSpinBox,點擊上下加減,進行輸入值調節時候,一直一個小步長,調節太慢,一直一個大步長,調節又太粗糙。因此,就需要做一個快捷方式:比如,按住ctrl鍵,調節步長變大,鬆開ctrl鍵,調節步長恢復原小步長。
其實,最好的是重寫QSpinBox類。
下面講一下,簡單實現。

實現結果:

在這裏插入圖片描述

實現原理:

1.捕捉鍵盤事件;
2.在ctrl按鍵按下時,改變QSpinBox的步長。

xxx.h文件:

#ifndef TESTSPINBOX_H
#define TESTSPINBOX_H

#include <QtWidgets/QMainWindow>
#include "ui_testspinbox.h"
#include <QKeyEvent>

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);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章