Before, I was used to using button.clicked.connect(function)
to trigger a button and setting qss
by setStyleSheet()
(Eg:
QPushButton:pressed{background:#EAEAEA;}
). And the button will change background color when pressing button by clicking mouse and work as expected. However, Currently I'm using QShortcut
to trigger the button (Eg: QtCore.Qt.Key_Return
) but the button seems not to be affected by qss
.
The code that I've used:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
Form.setStyleSheet(""
"#Form {\n"
"background-color: rgb(255, 255, 255);\n"
"}\n"
"QPushButton:hover {\n"
"color: white;\n"
"background-color: rgb(255, 85, 127);\n"
"border-radius: 6px;\n"
"font-size:16px;\n"
"}\n"
"\n"
" QPushButton:pressed{\n"
"background:#EAEAEA;\n"
"color: black;\n"
"font-size:16px;\n"
"}")
self.frame = QtWidgets.QFrame(Form)
self.frame.setGeometry(QtCore.QRect(20, 20, 351, 241))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.pushButton = QtWidgets.QPushButton(self.frame)
self.pushButton.setGeometry(QtCore.QRect(130, 100, 93, 28))
self.pushButton.setObjectName("pushButton")
# old (be affected by qss (QPushButton:pressed) when clicking mouse)
# self.pushButton.clicked.connect(self.send_message)
# new (not to be affected by qss (QPushButton:pressed) when using Enter key)
send_message_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return), Form)
send_message_shortcut.activated.connect(self.send_message)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "PushButton"))
def send_message(self):
# do something here
print("send message")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
You are not seeing the "animation" because the button is not being pressed at all, but you can trigger it by using
QAbstractButton.animateClick
:This sets the button pressed (as in
setDown(True)
), then restores it after a default 100ms interval and sends bothreleased
andclicked
signals respectively. If you want a different time interval, use a lambda (or do it in your own method) and set the argument in ms.