2012-02-01 272 views
1

我想知道是否有人知道如何为一个按钮设置多个快捷方式。例如,我有一个QPushButton,我想链接到Return键和Enter键(键盘和数字键盘)。setShortcut的多个键盘快捷键

如果设计师,我放在快捷栏:

Return, Enter 

只有输入响应,而不是返回。

我也曾尝试只设置在设计师和我的源代码的回报,我把在:

ui.searchButton->setShortcut(tr("Enter")); 

这也似乎只响应输入(数字键盘)不会返回(键盘)。

有谁知道如何设置多个QPushButton快捷方式?仅供参考我正在使用Qt4.7。

回答

1

似乎是一个小的解决方法,但您可以使用QAction设置多个shortcuts on it并将其连接到您的QPushButton。 (类似的,您可以创建多个QShortcut对象并将它们连接到按钮。)

1

我不使用QtCreator,所以这里有2个代码解决方案,我会遇到这个问题。



对于这些情况我覆盖keyPressEvent(主窗口的例如或者你想要的快捷方式来定)。

页眉:

protected: 
    virtual void keyPressEvent(QKeyEvent* e); 

来源:

void main_window::keyPressEvent(QKeyEvent* e) 
{ 
    switch(e->key()) 
    { 
    case Qt::Key_Enter: 
    case Qt::Key_Return: 
     // do what you want, for example: 
     QMessageBox::information(this, 
      "Success", 
      "Let me guess, you pressed the return key or the enter key."); 
     break; 
    default: 
     ; 
    } 

    QMainWindow::keyPressEvent(e); 
} 

2.
我觉得还可以创建和连接多个QShortcut ojects。 只需创建所需的所有快捷方式,并将它们的activated -Signal连接到要接收快捷方式的对象的插槽。

1

作为qt noob,我正在寻找一种方法将多个快捷方式添加到一个按钮。这里的答案很有帮助,但我仍然不得不拼命把所有的东西放在一起。所以我想我会在这里发表完整的答案,希望能帮助其他跟随我的新手们。

我很抱歉这是用PyQt编写的,但我相信它会传达出这个想法。

# Create and setup a "Find Next" button 
find_next_btn = QtGui.QPushButton("  Find &Next") 
# setupButton is a small custom method to streamline setting up many buttons. See below. 
setupButton(find_next_btn, 150, "Icons/arrow_right_cr.png", 30, 20, "RTL") 
find_next_btn.setToolTip("Search DOWN the tree") 
find_next_btn.clicked.connect(find_next) 
# find_next is the method executed when the button is pressed 

# Create an action for the additional shortcuts. Alt+N is already set 
# by "&" in "Find &Next" 
find_next_ret_act = QtGui.QAction(self, triggered=find_next_btn.animateClick) 
find_next_ret_act.setShortcut(QtGui.QKeySequence("Return")) 

find_next_enter_act = QtGui.QAction(self, triggered=find_next_btn.animateClick) 
find_next_enter_act.setShortcut(QtGui.QKeySequence("Enter")) 

# Now add (connect) these actions to the push button 
find_next_btn.addActions([find_next_ret_act, find_next_enter_act]) 


# A method to streamline setting up multiple buttons 
def setupButton(button, btn_w, image=None, icon_w=None, icon_h=None, layout_dir=None): 
    button.setFixedWidth(btn_w) 
    if image != None:    
     icon = QtGui.QIcon() 
     icon.addPixmap(QtGui.QPixmap(image)) 
     button.setIcon(icon) 
    if icon_w != None: 
     button.setIconSize(QtCore.QSize(icon_w, icon_h)) 
    if layout_dir == "RTL": 
     find_next_btn.setLayoutDirection(QtCore.Qt.RightToLeft) 

下面是导致按钮:http://i.stack.imgur.com/tb5Mh.png(作为一个小白,我不允许直接嵌入图片进入后)。

我希望这是有帮助的。