当用户释放 Ctrl + C 时,我想调用一些自定义复制代码。在 Ctrl 之前释放 C 时,Qt会发送与QKeySequence::Copy
匹配的键事件。在 C 之前释放 Ctrl 时,释放事件不匹配。
当使用 Ctrl 进行密钥释放事件时,有没有办法查看 C 是否仍然被按下?
当我不首先处理 Ctrl 时,事件会被传递并且它会进行常规复制,这正是我不希望发生的事情。
bool
MyWidget::eventFilter(QObject* object, QEvent* event)
{
// the text edit box filters its events through here
if (object == m_text_edit_box)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *key_event = static_cast<QKeyEvent*>(event);
if (key_event->matches(QKeySequence::Copy))
{
// don't do anything and don't pass along event
return true;
}
}
else if (event->type() == QEvent::KeyRelease)
{
QKeyEvent *key_event = static_cast<QKeyEvent*>(event);
if (key_event->matches(QKeySequence::Copy))
{
// we only get in here if 'c' is released before ctrl
callCustomCopy();
return true;
}
}
}
// pass along event
return false;
}
答案 0 :(得分:1)
您可以专门查询字母“C”和元键“Ctrl”,而不是依赖于key_even-&gt; matches()。您当然可以在keydown事件存储中找到eventfilter的对象中,keydown序列与副本匹配的事实。
这个(未经测试的)可能对您有用,请注意静态变量应该是包含它的类的成员变量,这在本示例的上下文中看起来更清楚。您想要完成的确切逻辑可能需要在事件之间传递更多状态信息。
bool MyWidget::eventFilter(QObject* object, QEvent* event)
{
// Remember state between events
static foundCopy = false;
// the text edit box filters its events through here
if (object == m_text_edit_box)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *key_event = static_cast<QKeyEvent*>(event);
if (key_event->matches(QKeySequence::Copy))
{
foundCopy = true;
// don't do anything and don't pass along event
return true;
}
else
{
foundCopy = false;
// This is another sequence, ignore and pass event
// Note that this will trigger with ctrl+c+a and others
}
}
else if (event->type() == QEvent::KeyRelease)
{
QKeyEvent *key_event = static_cast<QKeyEvent*>(event);
if (foundCopy)
{
callCustomCopy();
foundCopy = false;
return true;
}
// This should keep the system copy from triggering
if (key_event->matches(QKeySequence::Copy))
{
return true;
}
}
}
// pass along event
return false;
}
另一种方法是收集当前时间按下的所有按键的实际状态,然后当释放一个按键时,查看仍按下哪些按键。
从UI的角度来看,请记住所有键盘操作都是在按下时执行的(例如打字,粘贴窗口),一般情况下执行释放操作可能会使用户感到困惑,特别是当有可见的结果时行动。我无法从你的例子中看出你想要完成什么。