2012-02-01 478 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(作爲一個小白,我不允許直接嵌入圖片進入後)。

我希望這是有幫助的。