I have the following code adapted from here which works by right justifying shortcuts in QMenu. It works well when no StyleSheet is applied.
but when I add the line app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
it never works.
from PyQt5 import QtCore, QtGui, QtWidgets
class MenuProxyStyle(QtWidgets.QProxyStyle):
def drawControl(self, element, option, painter, widget=None):
shortcut = ""
if element == QtWidgets.QStyle.CE_MenuItem:
vals = option.text.split("\t")
if len(vals) == 2:
text, shortcut = vals
option.text = text
super(MenuProxyStyle, self).drawControl(element, option, painter, widget)
if shortcut:
margin = 10 # QStyleHelper::dpiScaled(5)
return self.proxy().drawItemText(painter, option.rect.adjusted(margin, 0, -margin, 0),
QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter,
option.palette, option.state & QtWidgets.QStyle.State_Enabled,
shortcut, QtGui.QPalette.Text)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
menu = QtWidgets.QMenu("File", self)
self.menuBar().addMenu(menu)
# create icons
data = [("Absolute", "Ctrl+Alt+C"),
("Relative", "Ctrl+Shift+C"),
("Copy", "Ctrl+C")]
for text, shortcut in data:
action = QtWidgets.QAction(self)
action.setText(text+"\t"+shortcut)
menu.addAction(action)
if __name__ == '__main__':
import sys, qdarkstyle
app = QtWidgets.QApplication(sys.argv)
app.setStyle(MenuProxyStyle())
app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
I would like to know how to combine QStyle with QStyleSheet?