Изменить раскладку визуальной клавиатуры
У меня есть класс Keyboard в котором рисуется клавиатура и класс KeyEvent, в котором визуализируется нажатие на клавиши. Мне нужно чтобы при нажатии на комбинацию alt + shift, поменялся язык на визуальной клавиатуре.
Пробовал полностью очищать клавиатуру, удаляя все элементы, но при вызове setupUI она не появляется.
interface
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
QFont, QFontDatabase, QGradient, QIcon,
QImage, QKeySequence, QLinearGradient, QPainter,
QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QFrame, QMainWindow, QSizePolicy,
QVBoxLayout, QWidget)
from create_keyboard import Keyboard
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(750, 443)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.verticalLayout = QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(u"verticalLayout")
self.main_frame = QFrame(self.centralwidget)
self.main_frame.setObjectName(u"main_frame")
self.main_frame.setFrameShape(QFrame.StyledPanel)
self.main_frame.setFrameShadow(QFrame.Raised)
self.verticalLayout_2 = QVBoxLayout(self.main_frame)
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.Keyboard = Keyboard(self.main_frame)
self.Keyboard.setObjectName(u"Keyboard")
self.Keyboard.setFrameShape(QFrame.StyledPanel)
self.Keyboard.setFrameShadow(QFrame.Raised)
self.verticalLayout_2.addWidget(self.Keyboard)
self.verticalLayout.addWidget(self.main_frame)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
# retranslateUi
class Test(QMainWindow, Ui_MainWindow):
def __init__(self):
super(Test, self).__init__()
self.setupUi(self)
self.installEventFilter(self.Keyboard.events)
if __name__ == "__main__":
from sys import argv, exit
app = QApplication(argv)
window = Test()
window.show()
exit(app.exec())
create_keyboard.py
from PySide6.QtCore import QSize, Qt
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QSizePolicy, QSpacerItem, QVBoxLayout
from key_events import KeyEvent
class Keyboard(QFrame):
ru = ['', 'Ё', '1 !', '2 "', '3 №', '4 ;', '5 %', '6 :', '7 ?', '8 *', '9 (', '0 )', '- _', '= +', 'BackSpace', '',
'', 'Tab', 'Й', 'Ц', 'У', 'К', 'Е', 'Н', 'Г', 'Ш', 'Щ', 'З', 'Х', 'Ъ', '\\ /', '',
'', 'Caps', 'Ф', 'Ы', 'В', 'А', 'П', 'Р', 'О', 'Л', 'Д', 'Ж', 'Э', 'Enter', '',
'', 'Shift', 'Я', 'Ч', 'С', 'М', 'И', 'Т', 'Ь', 'Б', 'Ю', '. ,', 'LShift', '',
'', 'Alt', 'Space', '']
eng = ['', '` ~', '1 !', '2 @', '3 #', '4 $', '5 %', '6 ^', '7 &', '8 *', '9 (', '0 )', '- _', '= +', 'BackSpace', '',
'', 'Tab', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[ {', '] }', '\\ |', '',
'', 'Caps', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', '; :', '\' "', 'Enter', '',
'', 'Shift', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ', <', '. >', '/ ?', 'LShift', '',
'', 'Alt', 'Space', '']
symbols = '~!@#$%^&*()_+\\{}:"<>?!"№;%:?*()_+/,|'
sizes = {'BackSpace': (100, 140), 'Tab': (80, 110), '\\ /': (70, 100),
'\\ |': (70, 100), 'Caps': (100, 130), 'Enter': (100, 155),
'Shift': (130, 170), 'LShift': (130, 190), 'Space': (400, 550)}
def __init__(self, parent=None):
super().__init__(parent)
self.setMaximumSize(QSize(16777215, 385))
self.keys = None
self.setupUI('ru')
self.events = KeyEvent(self)
def setupUI(self, lang):
self.keys = self.ru if lang == 'ru' else self.eng
lines = {'Line_1': self.keys[:16], 'Line_2': self.keys[16:32], 'Line_3': self.keys[32:47],
'Line_4': self.keys[47:61], 'Line_5': self.keys[61:]}
self.verticalLayout = QVBoxLayout(self)
self.verticalLayout.setSpacing(5)
self.verticalLayout.setObjectName(u"verticalLayout")
self.verticalLayout.setContentsMargins(10, 0, 10, 0)
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
for i, ln in enumerate(lines.keys()):
line = QFrame(self)
line.setObjectName(ln)
horizontalLayout = QHBoxLayout(line)
horizontalLayout.setSpacing(5)
horizontalLayout.setObjectName(f"horizontalLayout_{i}")
horizontalLayout.setContentsMargins(0, 0, 0, 0)
for key in lines[ln]:
if not key:
horizontalSpacer = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
horizontalLayout.addItem(horizontalSpacer)
continue
label = QLabel(line)
if key[-1] in self.symbols:
label.setObjectName(f'Key_{key[0]}')
else:
label.setObjectName(f'Key_{key}')
sizePolicy.setHeightForWidth(label.sizePolicy().hasHeightForWidth())
label.setSizePolicy(sizePolicy)
label.setText(key)
if key in self.sizes.keys():
minimal, maximum = self.sizes[key]
label.setMinimumSize(QSize(minimal, 50))
label.setMaximumSize(QSize(maximum, 70))
else:
label.setMinimumSize(QSize(50, 50))
label.setMaximumSize(70, 70)
label.setAlignment(Qt.AlignCenter)
horizontalLayout.addWidget(label)
for index, key in enumerate(lines[ln]):
if key:
if (ln == 'Line_1' and index == 14 or ln == 'Line_2' and index in (1, 14)
or ln == 'Line_3' and index in (1, 13) or ln == 'Line_4' and index in (1, 12)):
horizontalLayout.setStretch(index, 3)
else:
horizontalLayout.setStretch(index, 1)
if ln == 'Line_5':
horizontalLayout.setStretch(0, 4)
horizontalLayout.setStretch(1, 1)
horizontalLayout.setStretch(2, 8)
horizontalLayout.setStretch(3, 4)
self.verticalLayout.addWidget(line)
key_events.py
from PySide6.QtCore import Qt, QObject
from PySide6.QtGui import QKeyEvent
from PySide6.QtWidgets import QLabel
from ctypes import WinDLL
def _get_capslock_state():
hllDll = WinDLL("User32.dll")
VK_CAPITAL = 0x14
return hllDll.GetKeyState(VK_CAPITAL) != 0
class KeyEvent(QObject):
keys = {Qt.Key_Backspace: "BackSpace", Qt.Key_Return: "Enter", Qt.Key_Space: "Space",
Qt.Key_Tab: "Tab", Qt.Key_Alt: "Alt"}
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
self.caps_on = _get_capslock_state()
self.system_button = False
if self.caps_on:
self._search_button('Caps').setStyleSheet(u'background-color: #999999')
def eventFilter(self, watched, event):
if event.type() == QKeyEvent.KeyPress:
key: QKeyEvent = event
# Изменить клавиатуру здесь
if key.modifiers() is Qt.AltModifier | Qt.ShiftModifier:
pass
if key.nativeScanCode() == 54:
self._search_button('LShift').setStyleSheet(u'background-color: #999999')
if key.nativeScanCode() == 42:
self._search_button('Shift').setStyleSheet(u'background-color: #999999')
for k, v in self.keys.items():
if key.key() == k:
self._search_button(v).setStyleSheet(u'background-color: #999999')
self.system_button = True
if key.key() == Qt.Key_CapsLock and not self.caps_on:
self._search_button('Caps').setStyleSheet(u'background-color: #999999')
self.caps_on = True
return True
elif key.key() == Qt.Key_CapsLock and self.caps_on:
self._search_button('Caps').setStyleSheet(u'background-color: none')
self.caps_on = False
if not self.system_button:
if key.modifiers() == Qt.ShiftModifier and key.text():
self._search_button(self._translate(key.text())).setStyleSheet(u'background-color: #999999')
if key.modifiers() == Qt.NoModifier and key.text():
self._search_button(key.text().upper()).setStyleSheet(u'background-color: #999999')
if event.type() == QKeyEvent.KeyRelease:
key: QKeyEvent = event
if key.nativeScanCode() == 54:
self._search_button('LShift').setStyleSheet(u'background-color: none')
if key.nativeScanCode() == 42:
self._search_button('Shift').setStyleSheet(u'background-color: none')
for k, v in self.keys.items():
if key.key() == k:
self._search_button(v).setStyleSheet(u'background-color: none')
self.system_button = False
return True
if key.modifiers() == Qt.ShiftModifier and key.text():
self._search_button(self._translate(key.text())).setStyleSheet(u'background-color: none')
if key.modifiers() == Qt.NoModifier and key.text():
self._search_button(self._translate(key.text()).upper()).setStyleSheet(u'background-color: none')
return super().eventFilter(watched, event)
def _search_button(self, name):
buttons = self.parent.findChildren(QLabel)
for btn in buttons:
name_button = btn.objectName().split('_')[1]
if name_button == name:
return btn
def _translate(self, text):
if self.parent.keys == self.parent.eng:
maketrans = text.maketrans('~!@#$%^&*()_+|{}:"<>?', '`1234567890-=\\[];\',./')
else:
maketrans = text.maketrans('!"№;%:?*()_+/,', '1234567890-=\\.')
return text.translate(maketrans)
Ответы (1 шт):
Автор решения: Devik
→ Ссылка
Создал функцию которая удаляет всю клавиатуру и отрисовывает ее заново.
Так же переместил строку self.verticalLayout = QVBoxLayout(self) из stupUI() в инициализацию.
Теперь все прекрасно работает.
def change_layout(self):
for i in self.findChildren(QFrame):
i.setParent(None)
del i
self.switch = True
self.setupUI()