QT程序快捷键的最佳解决方案

QT框架中提供了很多的实现快捷键的方法,比如拦截键盘事件,可以用来处理快捷键,但是这种办法有时候程序复杂的时候会失效,索引笔者建议使用另外一种办法,使用Qt提供的QAction来实现快捷键,这方法需要注意几点,

第一点,QAction需要与快捷键绑定,

normalAction->setShortcut(QKeySequence::Cancel);

第二点,QAction必须与程序主窗口或者需要接收快捷键的窗口绑定。

	normalAction->setParent(this);

第四点,就是在QAction的triggered信号的回调函数里处理相关的事务。

并且快捷键的创建和 信号槽的绑定最好放在程序的主窗口,切忌把快捷键放在多个窗口中处理,这样后期的维护很复杂的。 

初始化创建的地方

void LiveClientMainWidget::createActions()
{
	QAction * normalAction = new QAction("&normal", this);

	this->addAction(normalAction);

	normalAction->setParent(this);
	normalAction->setProperty("ID", "normal");
	normalAction->setShortcut(QKeySequence::Cancel);

	connect(normalAction, SIGNAL(triggered(bool)), this, SLOT(onTriggered(bool)));
	//connect(minAction, &QAction::triggered, this, [=]() {
	//	this->showNormal();
	//});
	
	QAction *minAction = new QAction("&min", this);

	this->addAction(minAction);

	minAction->setParent(this);
	minAction->setProperty("ID", "min");
	minAction->setShortcut(QKeySequence::Backspace);

	connect(minAction, SIGNAL(triggered(bool)), this, SLOT(onTriggered(bool)));
	//connect(minAction, &QAction::triggered, this, [=]() {
	//	this->showNormal();
	//});


	QAction * closeAction = new QAction("&close", this);

	this->addAction(closeAction);

	closeAction->setParent(this);
	closeAction->setProperty("ID", "close");
	closeAction->setShortcut(tr("Ctrl+F4"));

	//bool check = connect(closeAction, &QAction::triggered, this, [=]() {
	//	qApp->quit();
	//});

	connect(closeAction, SIGNAL(triggered(bool)), this, SLOT(onTriggered(bool)));



	QAction * helpAction = new QAction("&help", this);

	this->addAction(helpAction);

	helpAction->setParent(this);
	helpAction->setProperty("ID", "help");
	helpAction->setShortcut(QKeySequence(Qt::Key_F1));

	//connect(helpAction, &QAction::triggered, this, [=](){

	//});

	connect(helpAction, SIGNAL(triggered(bool)), this, SLOT(onTriggered(bool)));
}

槽函数的实现

void LiveClientMainWidget::onTriggered(bool checked /*= false*/)
{
	QAction * senderAction = dynamic_cast <QAction *>(sender());
	QString id = senderAction->property("ID").toString();
	if (id == "normal")
	{
		this->showNormal();
	}
	else if (id == "min")
	{
		this->showMinimized();
	}
	else if (id == "close")
	{
		qApp->quit(); //退出 
	}
	else if (id == "help")
	{ 
		//help,帮助信息。
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42101997/article/details/84336137