我了解 OOP 中的抽象,如果我理解正确,那么这就是选择并仅关注对象的那些细节,这将使我们能够解决问题。但我也听说过抽象级别和简单的抽象,这不适用于OOP。我想澄清这些观点。
我有一个Keyboard类,其中绘制键盘,还有一个KeyEvent类,其中按键可视化。我需要当我按下 Alt + Shift 组合时,视觉键盘上的语言会发生变化。
我尝试完全清除键盘,删除所有元素,但是当我调用setupUI时它不会出现。
界面
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())
创建键盘.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)
Apostol Petr
Asked:
2024-03-07 23:16:26 +0800 CST
我不太明白这些概念到底有何不同,我将不胜感激。
GACHIK
Asked:
2023-12-24 20:43:35 +0800 CST
您需要创建一个大小为 m*n 的矩阵类,并配置魔术方法 __str__ ,以便在通过 print 输出时,对象以矩阵格式输出(长度为 m 的 n 行矩形)。我创建了一个类,但我不知道在哪里编写方法中另一行的翻译;我在 OOP 和类似事物方面经验很少。
class Matrix:
def __init__(self, n, m):
self.n = n#строки
self.m = m#столбцы
self.matrix = [[0]*cols]*rows
def __str__(self):
return f'{[[j for j in i] for i in self.matrix]}'
a = Matrix(3, 5)
print(a.n, a.m, a, sep='\n')
根据我的想法,它应该输出什么:
3
5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
它实际上得出的结论是:
3
5
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
XOF74
Asked:
2023-11-05 16:13:29 +0800 CST
class Unit
{
protected int _health;
protected int _damage;
public virtual void Attack(Unit unit)
{
unit.TakeDamage(_damage);//почему скелет вызывая метод передает аргументом поле _damage обьекта Archer?.. а не свое поле
}
public virtual void TakeDamage(int damage)
{
Console.WriteLine(damage);
if (damage >= _health)
{
_health = 0;
Die();
return;
}
_health -= damage;
}
protected virtual void Die() { }
}
class Skeleton : Unit
{
public Skeleton()
{
_health = 15;
_damage = 12;
}
public override void Attack(Unit unit)
{
Console.WriteLine("Скелет атакует.");
base.Attack(unit);
}
protected override void Die()
{
Console.WriteLine("Скелет убит.");
}
}
class Archer : Unit
{
public Archer()
{
_health = 50;
_damage = 15;
}
public override void Attack(Unit unit)
{
Console.WriteLine("Лучник атакует.");
base.Attack(unit);
}
protected override void Die()
{
Console.WriteLine("Лучник убит.");
}
}
class Program
{
static void Main(string[] args)
{
Archer archer = new Archer();
Skeleton skelet = new Skeleton();
archer.Attack(skelet);
archer.Attack(skelet);
}
}