class FitnessView(QtGui.QMainWindow): """ This will be the class that displays and updates the UI. """ day_renamed = QtCore.Signal(str, str) def __init__(self): super(FitnessView, self).__init__() self.build_ui() def build_ui(self): self.ui = Ui_Form() self.ui.setupUi(self) @QtCore.Slot(str) def add_day_label(self, string): new_day = QtGui.QTableWidgetItem(string) self.ui.day_table.setRowCount(self.ui.day_table.rowCount() + 1) self.ui.day_table.setItem(self.ui.day_table.rowCount() - 1, 0, new_day) @QtCore.Slot() def rename_prompt(self): current_item_text = self.ui.day_table.currentItem().text() new_text, ok = QtGui.QInputDialog.getText(self, 'Rename day', 'Enter new name') if ok: self.day_renamed.emit(current_item_text, new_text) def day_renamed(self, new_text): print "In here!"
def __init__(self): super().__init__() self._ui=MainFormUI() self._ui.setupUi(self) self._value="0" self._last_value="0" self._op="" self._append_period = False # 数字键 self._ui.btn1.clicked.connect(self.onBtn1Clicked) self._ui.btn2.clicked.connect(self.onBtn2Clicked) self._ui.btn3.clicked.connect(self.onBtn3Clicked) self._ui.btn4.clicked.connect(self.onBtn4Clicked) self._ui.btn5.clicked.connect(self.onBtn5Clicked) self._ui.btn6.clicked.connect(self.onBtn6Clicked) self._ui.btn7.clicked.connect(self.onBtn7Clicked) self._ui.btn8.clicked.connect(self.onBtn8Clicked) self._ui.btn9.clicked.connect(self.onBtn9Clicked) self._ui.btn0.clicked.connect(self.onBtn0Clicked) # 清除键 self._ui.btnClear.clicked.connect(self.onBtnClearClicked) self._ui.btnCE.clicked.connect(self.onBtnCEClicked) self._ui.btnBackspace.clicked.connect(self.onBtnBackspaceClicked) # 符号键 self._ui.btnSign.clicked.connect(self.onBtnSignClicked) # 小数点 self._ui.btnPeriod.clicked.connect(self.onBtnPeriodClicked) # 加减乘除 self._ui.btnAdd.clicked.connect(self.onBtnAddClicked) self._ui.btnMinus.clicked.connect(self.onBtnMinusClicked) self._ui.btnMultiply.clicked.connect(self.onBtnMultiplyClicked) self._ui.btnDivide.clicked.connect(self.onBtnDivideClicked) self._ui.btnResult.clicked.connect(self.onBtnResultClicked) # 函数 self._ui.btnSin.clicked.connect(self.onBtnSinClicked) self._ui.btnCos.clicked.connect(self.onBtnCosClicked) self._ui.btnTan.clicked.connect(self.onBtnTanClicked) self._ui.btnCtg.clicked.connect(self.onBtnCtgClicked) self._ui.btnSec.clicked.connect(self.onBtnSecClicked) self._ui.btnArcsin.clicked.connect(self.onBtnArcsinClicked) self._ui.btnArccos.clicked.connect(self.onBtnArccosClicked) self._ui.btnArctan.clicked.connect(self.onBtnArctanClicked) self._ui.btnArcctg.clicked.connect(self.onBtnArcctgClicked) self._ui.btnLog.clicked.connect(self.onBtnLogClicked) self._ui.btnLn.clicked.connect(self.onBtnLnClicked) self._ui.btnFactorial.clicked.connect(self.onBtnFactorialClicked) # 内存管理 self._ui.btnMemoryAdd.clicked.connect(self.onBtnMemoryAddClicked) self._ui.btnReadMemory.clicked.connect(self.onBtnReadMemoryClicked) self._ui.btnClearMemory.clicked.connect(self.onBtnClearMemoryClicked)
def __init__(self): super().__init__() self._ui = MainWindowUi() self._ui.setupUi(self) self._game_timer = QtCore.QTimer() self._game_timer.timeout.connect(self.on_game_update) self._game_timer.start(100) self._clock_timer = QtCore.QTimer() self._clock_timer.timeout.connect(self.on_clock_update) self._clock_timer.start(1000) self._start_time = datetime.now() # 初始化难度 self._ui.cbDifficulty.addItem("简单", 1) self._ui.cbDifficulty.addItem("中等", 2) self._ui.cbDifficulty.addItem("较难", 4) self._ui.cbDifficulty.addItem("高级", 8) self._ui.cbDifficulty.setCurrentText("简单") self._base_speed = 2 self._ui.cbDifficulty.currentIndexChanged.connect( self.on_difficulty_changed) # 设置主显示区 self._scene = QtWidgets.QGraphicsScene() self._scene.setSceneRect(0, 0, 600, 650) self._ui.main_view.setScene(self._scene) # 加入小球 self._balls: List[MyBallItem] = [] for i in range(10): x = random.randint(0, self.width() - BALL_SIZE) y = 0 color = QtGui.QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) ball = MyBallItem(x, y, BALL_SIZE, color) ball.clicked.connect(self.on_ball_clicked) speed = self._base_speed + random.randint(0, self._base_speed) ball.setSpeed(speed) self._scene.addItem(ball) self._balls.append(ball) self._life = 5 self._score = 0 self._ui.txtScore.setText(f"{self._score}") self._ui.txtLife.setText(f"{self._life}") # 打开鼠标位置监控 self.setMouseTracking(True) self._ui.main_view.setMouseTracking(True)
def __init__(self, parent=None): # QtGui.QWidget.__init__(self, parent) # from PyQt4 import QString self.ui = Ui_Form() self.ui.setupUi(self, [ (_('Reset'), self.reset), (_('Measuring mode'), self.setMeasuringMode), (_('Distance to measure in X axis'), self.askWantedX), (_('Distance to measure in Y axis'), self.askWantedY), (_('Calibrate Y axis'), self.calY), (_('Calibrate X axis'), self.calX), (_('Finish calibration'), self.finishCal), (_('Save calibration'), self.saveRatio), (_('Allow calibration'), self.allowCalibrate), ]) print 'main widget: ', self.centralWidget() self.centralWidget().setMouseTracking(True) # mode of working self.mode = Mode(self, ("MEASURING", "CAL_X", "CAL_Y")) # storing programs options self.options = Options() # object that manages all other objects :) self.mediator = Mediator(self.cursor(), self) # distance the user wants the device to travel self.wantedX, self.wantedY = 0.0, 0.0 self.setMeasuringMode() # set default values self.reset()
def __init__(self, parent=None): # QtGui.QWidget.__init__(self, parent) # from PyQt4 import QString self.ui = Ui_Form() self.ui.setupUi(self, [ (_('Reset'), self.reset), (_('Measuring mode'), self.setMeasuringMode), (_('Distance to measure in X axis'), self.askWantedX), (_('Distance to measure in Y axis'), self.askWantedY), (_('Calibrate Y axis'), self.calY), (_('Calibrate X axis'), self.calX), (_('Finish calibration'), self.finishCal), (_('Save calibration'), self.saveRatio), (_('Allow calibration'), self.allowCalibrate), ]) print 'main widget: ',self.centralWidget() self.centralWidget().setMouseTracking(True) # mode of working self.mode = Mode(self, ("MEASURING", "CAL_X", "CAL_Y")) # storing programs options self.options = Options() # object that manages all other objects :) self.mediator = Mediator(self.cursor(), self) # distance the user wants the device to travel self.wantedX, self.wantedY = 0.0, 0.0 self.setMeasuringMode() # set default values self.reset()
class MainFrame(QtWidgets.QWidget): def __init__(self): super().__init__() self._ui=MainFormUI() self._ui.setupUi(self) self._value="0" self._last_value="0" self._op="" self._append_period = False # 数字键 self._ui.btn1.clicked.connect(self.onBtn1Clicked) self._ui.btn2.clicked.connect(self.onBtn2Clicked) self._ui.btn3.clicked.connect(self.onBtn3Clicked) self._ui.btn4.clicked.connect(self.onBtn4Clicked) self._ui.btn5.clicked.connect(self.onBtn5Clicked) self._ui.btn6.clicked.connect(self.onBtn6Clicked) self._ui.btn7.clicked.connect(self.onBtn7Clicked) self._ui.btn8.clicked.connect(self.onBtn8Clicked) self._ui.btn9.clicked.connect(self.onBtn9Clicked) self._ui.btn0.clicked.connect(self.onBtn0Clicked) # 清除键 self._ui.btnClear.clicked.connect(self.onBtnClearClicked) self._ui.btnCE.clicked.connect(self.onBtnCEClicked) self._ui.btnBackspace.clicked.connect(self.onBtnBackspaceClicked) # 符号键 self._ui.btnSign.clicked.connect(self.onBtnSignClicked) # 小数点 self._ui.btnPeriod.clicked.connect(self.onBtnPeriodClicked) # 加减乘除 self._ui.btnAdd.clicked.connect(self.onBtnAddClicked) self._ui.btnMinus.clicked.connect(self.onBtnMinusClicked) self._ui.btnMultiply.clicked.connect(self.onBtnMultiplyClicked) self._ui.btnDivide.clicked.connect(self.onBtnDivideClicked) self._ui.btnResult.clicked.connect(self.onBtnResultClicked) # 函数 self._ui.btnSin.clicked.connect(self.onBtnSinClicked) self._ui.btnCos.clicked.connect(self.onBtnCosClicked) self._ui.btnTan.clicked.connect(self.onBtnTanClicked) self._ui.btnCtg.clicked.connect(self.onBtnCtgClicked) self._ui.btnSec.clicked.connect(self.onBtnSecClicked) self._ui.btnArcsin.clicked.connect(self.onBtnArcsinClicked) self._ui.btnArccos.clicked.connect(self.onBtnArccosClicked) self._ui.btnArctan.clicked.connect(self.onBtnArctanClicked) self._ui.btnArcctg.clicked.connect(self.onBtnArcctgClicked) self._ui.btnLog.clicked.connect(self.onBtnLogClicked) self._ui.btnLn.clicked.connect(self.onBtnLnClicked) self._ui.btnFactorial.clicked.connect(self.onBtnFactorialClicked) # 内存管理 self._ui.btnMemoryAdd.clicked.connect(self.onBtnMemoryAddClicked) self._ui.btnReadMemory.clicked.connect(self.onBtnReadMemoryClicked) self._ui.btnClearMemory.clicked.connect(self.onBtnClearMemoryClicked) def updateValue(self,value:str): if "E-" in value: value = "0" if len(value)>15: value = value[:15] self._value = value self._ui.displayFrame.setText(value) def appendDigit(self,digit): if self._op!="": self.clearCurrentValue() self.updateValue(digit) return if len(self._value)>=15: return if self._append_period: self._value += '.' self._append_period = False if self._value == '0' : self.updateValue(digit) else: self.updateValue(self._value+digit) def onBtn1Clicked(self): self.appendDigit("1") def onBtn2Clicked(self): self.appendDigit("2") def onBtn3Clicked(self): self.appendDigit("3") def onBtn4Clicked(self): self.appendDigit("4") def onBtn5Clicked(self): self.appendDigit("5") def onBtn6Clicked(self): self.appendDigit("6") def onBtn7Clicked(self): self.appendDigit("7") def onBtn8Clicked(self): self.appendDigit("8") def onBtn9Clicked(self): self.appendDigit("9") def onBtn0Clicked(self): self.appendDigit("0") def onBtnClearClicked(self): self._last_value="0" self._op = "" self.updateMemory("0") self.clearCurrentValue() def onBtnCEClicked(self): self.clearCurrentValue() def clearCurrentValue(self): self._append_period = False self.updateValue("0") def onBtnBackspaceClicked(self): if len(self._value)>1: self.updateValue(self._value[0:-1]) else: self.clearCurrentValue() def onBtnSignClicked(self): if self._value == '0': return if self._value[0]=='-': self.updateValue(self._value[1:]) else: self.updateValue("+"+self._value) def onBtnPeriodClicked(self): if self._append_period: return if '.' in self._value: return self._append_period = True def doOperation(self,op): if self._op!="": self.onBtnResultClicked() self._last_value = self._value self._append_period = False self._op=op def onBtnAddClicked(self): self.doOperation("+") def onBtnMinusClicked(self): self.doOperation("-") def onBtnMultiplyClicked(self): self.doOperation("*") def onBtnDivideClicked(self): self.doOperation("/") def onBtnResultClicked(self): if self._op=="": return v1=Decimal(self._last_value) v2=Decimal(self._value) if self._op == '+': result = v1+v2 if self._op == '-': result = v1-v2 if self._op == '*': result = v1*v2 if self._op == '/': result = v1/v2 self._append_period = False self._op = "" self.updateValue(str(result)) def onBtnSinClicked(self): self._append_period = False self._op="" v=Decimal(sin(float(self._value))) self.updateValue(str(v)) def onBtnCosClicked(self): self._append_period = False self._op="" v=Decimal(cos(float(self._value))) self.updateValue(str(v)) def onBtnTanClicked(self): self._append_period = False self._op="" v=Decimal(tan(float(self._value))) self.updateValue(str(v)) def onBtnCtgClicked(self): self._append_period = False self._op="" v=1/Decimal(tan(float(self._value))) self.updateValue(str(v)) def onBtnSecClicked(self): self._append_period = False self._op="" v=1/Decimal(cos(float(self._value))) self.updateValue(str(v)) def onBtnArcsinClicked(self): self._append_period = False self._op="" v=Decimal(asin(float(self._value))) self.updateValue(str(v)) def onBtnArccosClicked(self): self._append_period = False self._op="" v=Decimal(acos(float(self._value))) self.updateValue(str(v)) def onBtnArctanClicked(self): self._append_period = False self._op="" v=Decimal(atan(float(self._value))) self.updateValue(str(v)) def onBtnArcctgClicked(self): self._append_period = False self._op="" v=Decimal(pi/2-atan(float(self._value))) self.updateValue(str(v)) def onBtnLogClicked(self): self._append_period = False self._op="" v=Decimal(self._value) if v>0: v=v.log10() self.updateValue(str(v)) def onBtnLnClicked(self): self._append_period = False self._op="" v=float(self._value) if v>0: v = Decimal(log(v)) self.updateValue(str(v)) def onBtnFactorialClicked(self): if "." in self._value or "-" in self._value: return self._append_period = False self._op="" v=factorial(int(self._value)) self.updateValue(str(v)) def updateMemory(self,value:str): self._ui.displayFrame._memory = value self._ui.displayFrame.update() def onBtnMAddClicked(self): v1=Decimal(self._ui.displayFrame._memory) v2=Decimal(self._value) result = v1+v2 self.updateMemory(str(result)) def onBtnMemoryAddClicked(self): if self._value == '0': return v1=Decimal(self._ui.displayFrame._memory) v2=Decimal(self._value) result = v1+v2 self.updateMemory(str(result)) def onBtnReadMemoryClicked(self): self._append_period = False self.updateValue(self._ui.displayFrame._memory) def onBtnClearMemoryClicked(self): self.updateMemory("0")
def build_ui(self): self.ui = Ui_Form() self.ui.setupUi(self)
class MyForm(QtGui.QMainWindow): def modeChanged(self, mode): self.showInfoMessage(mode) pass def setMeasuringMode(self): self.mode.setMode("MEASURING") for i in (4,5,6,7): self.ui.menu.deactivate(i) self.calibration=None self.reset() def showInfoMessage(self, mes): u"""shows info message""" QtGui.QMessageBox.information(self, programName, mes, QtGui.QMessageBox.Ok) def setDistance(self, distance): u"""called by the mediator when the distance changes updates fields distX and distY calls updateUi""" self.distX, self.distY = distance[0], distance[1] self.updateUi() def updateUi(self): u"""updates UI based on distX and distY values""" # global distance ran over detector in both axis formatedDistanceX, formatedDistanceY = "%.3F" % self.distX, "%.3F" % self.distY # natively show the distance ran over the detector textX, textY = formatedDistanceX, formatedDistanceY # update info about if self.mode.getMode() == "MEASURING": pass # the calibrated axis doesn't show the global way ran elif self.mode.getMode() == "CAL_X": textX = _("calibration") elif self.mode.getMode() == "CAL_Y": textY = _("calibration") self.textX = "<font color=red size=4><b>" + textX + "</b></font>" # fill the data into labels from PyQt4 import Qt # showing total distance ran over cursor self.ui.lbWayX.setText(textX) self.ui.lbWayY.setText(textY) # calculate the remaining distance and show it remainingX = self.wantedX - self.distX remainingY = self.wantedY - self.distY self.ui.lbRemainingX.setText("%3.3F"%remainingX) self.ui.lbRemainingY.setText("%3.3F"%remainingY) # show the distance user wants to measure self.ui.lbWantedX.setText("%3.3F"%self.wantedX) self.ui.lbWantedY.setText("%3.3F"%self.wantedY) # show info about current working mode self.ui.lbMode.setText(str(self.mode.getMode())) def __init__(self, parent=None): # QtGui.QWidget.__init__(self, parent) # from PyQt4 import QString self.ui = Ui_Form() self.ui.setupUi(self, [ (_('Reset'), self.reset), (_('Measuring mode'), self.setMeasuringMode), (_('Distance to measure in X axis'), self.askWantedX), (_('Distance to measure in Y axis'), self.askWantedY), (_('Calibrate Y axis'), self.calY), (_('Calibrate X axis'), self.calX), (_('Finish calibration'), self.finishCal), (_('Save calibration'), self.saveRatio), (_('Allow calibration'), self.allowCalibrate), ]) print 'main widget: ',self.centralWidget() self.centralWidget().setMouseTracking(True) # mode of working self.mode = Mode(self, ("MEASURING", "CAL_X", "CAL_Y")) # storing programs options self.options = Options() # object that manages all other objects :) self.mediator = Mediator(self.cursor(), self) # distance the user wants the device to travel self.wantedX, self.wantedY = 0.0, 0.0 self.setMeasuringMode() # set default values self.reset() def reset(self): u"""resets ui and mediator, loads ratio from file (if was calibrated at runtime and not saved, then calibration data will be lost, sets distance to 0""" # distance travelled by the input device in the measurements units (defalutly milimeters) self.distX, self.distY = 0.0, 0.0 self.mediator.reset() self.mediator.storeRatio(self.options.getRatio()) self.updateUi() def askWanted(self, axis): text, ok = QtGui.QInputDialog.getText(self, programName, _('Distance to measure in %s axis:')%axis) name = {'X':'wantedX', 'Y':'wantedY'} try: # force converting to float text="%s.0" % text distance = float(eval(text)) setattr(self, name[axis], distance) except: self.showInfoMessage(_("You entered inproper number. You can use arithmetic operators (+, -, * /)")) self.updateUi() def askWantedX(self):self.askWanted('X') def askWantedY(self):self.askWanted('Y') def allowCalibrate(self): text, ok = QtGui.QInputDialog.getText(self, programName, _("""Enter below "SUWMIARKA". It is protection against accidentally changing of the calibration configuration. Entering word other than "SUWMIARKA" or pressing Cancel key simply returns to the mail menu and doesn't allow calibration. If you choose to allow calibrating, and then with any cause you would like to turn off allowing calibration, choose option """) +_('Measuring mode')) if ok: if text == "SUWMIARKA": for i in (4,5): self.ui.menu.activate(i) def saveRatio(self): u"""saves ratio to a file""" try: self.options.saveRatio() # if some problems occurred, show the info message except: self.showInfoMessage(_("Error during saving calibration data to file.")) # else show message that everything was ok else: self.showInfoMessage(_("Calibration data saved correctly")) def finishCal(self): u"""calculates the ratio of the calibrated axis, saves it to the options object (not to a file!!)""" if self.calibration == None: self.showInfoMessage("Blad programu") elif self.calibration in ('X','Y'): #TODO: tu jest odwolanie do mediatora, koniecznie ustaw odpowiednie metody !! if self.calibration =='X': przesuniecie = self.mediator.coordCounter.ticksX else: przesuniecie = self.mediator.coordCounter.ticksY self.showInfoMessage(_("General distance in axis %s: %s"%(self.calibration, przesuniecie))) text, ok = QtGui.QInputDialog.getText(self, programName, _('Enter distance the input device has moved: ')) if ok: calc = przesuniecie / float(text) if self.calibration == 'X': self.options.xRatio = calc elif self.calibration =='Y': self.options.yRatio = calc self.showInfoMessage(_("Ticks on milimeter in axis ")+self.calibration+_(" is: %s")%calc) self.calibration = None self.setMeasuringMode() self.ui.menu.activate(7) def cal(self, axis): u"""starts calibrating an axis""" self.ui.menu.activate(6) reply = QtGui.QMessageBox.information(self, programName, _("Starting calibration of axis: %s")%axis, QtGui.QMessageBox.Ok) if reply == QtGui.QMessageBox.Ok: self.reset() self.calibration = axis def calX(self): self.mode.setMode("CAL_X") self.cal('X') def calY(self): self.mode.setMode("CAL_Y") self.cal('Y') def keyPressEvent(self, event): proc = {'A':self.ui.menu.keyUp,'Z':self.ui.menu.keyDown,'K':self.ui.menu.executeMethod} if type(event) == QtGui.QKeyEvent: char = chr(event.key()) print 'char: ',char if char in proc: proc[char]() def mouseMoveEvent(self, event): try: self.mediator.coordChanged() except TickException, e: QtGui.QMessageBox.information(self, "", _("Inproper reading from input device."), QtGui.QMessageBox.Ok) self.reset()
def __init__(self): super(MyWindow, self).__init__() self.ui = Ui_Form() self.ui.setupUi(self)
class MyWindow(QtWidgets.QMainWindow): def __init__(self): super(MyWindow, self).__init__() self.ui = Ui_Form() self.ui.setupUi(self)
class MyForm(QtGui.QMainWindow): def modeChanged(self, mode): self.showInfoMessage(mode) pass def setMeasuringMode(self): self.mode.setMode("MEASURING") for i in (4, 5, 6, 7): self.ui.menu.deactivate(i) self.calibration = None self.reset() def showInfoMessage(self, mes): u"""shows info message""" QtGui.QMessageBox.information(self, programName, mes, QtGui.QMessageBox.Ok) def setDistance(self, distance): u"""called by the mediator when the distance changes updates fields distX and distY calls updateUi""" self.distX, self.distY = distance[0], distance[1] self.updateUi() def updateUi(self): u"""updates UI based on distX and distY values""" # global distance ran over detector in both axis formatedDistanceX, formatedDistanceY = "%.3F" % self.distX, "%.3F" % self.distY # natively show the distance ran over the detector textX, textY = formatedDistanceX, formatedDistanceY # update info about if self.mode.getMode() == "MEASURING": pass # the calibrated axis doesn't show the global way ran elif self.mode.getMode() == "CAL_X": textX = _("calibration") elif self.mode.getMode() == "CAL_Y": textY = _("calibration") self.textX = "<font color=red size=4><b>" + textX + "</b></font>" # fill the data into labels from PyQt4 import Qt # showing total distance ran over cursor self.ui.lbWayX.setText(textX) self.ui.lbWayY.setText(textY) # calculate the remaining distance and show it remainingX = self.wantedX - self.distX remainingY = self.wantedY - self.distY self.ui.lbRemainingX.setText("%3.3F" % remainingX) self.ui.lbRemainingY.setText("%3.3F" % remainingY) # show the distance user wants to measure self.ui.lbWantedX.setText("%3.3F" % self.wantedX) self.ui.lbWantedY.setText("%3.3F" % self.wantedY) # show info about current working mode self.ui.lbMode.setText(str(self.mode.getMode())) def __init__(self, parent=None): # QtGui.QWidget.__init__(self, parent) # from PyQt4 import QString self.ui = Ui_Form() self.ui.setupUi(self, [ (_('Reset'), self.reset), (_('Measuring mode'), self.setMeasuringMode), (_('Distance to measure in X axis'), self.askWantedX), (_('Distance to measure in Y axis'), self.askWantedY), (_('Calibrate Y axis'), self.calY), (_('Calibrate X axis'), self.calX), (_('Finish calibration'), self.finishCal), (_('Save calibration'), self.saveRatio), (_('Allow calibration'), self.allowCalibrate), ]) print 'main widget: ', self.centralWidget() self.centralWidget().setMouseTracking(True) # mode of working self.mode = Mode(self, ("MEASURING", "CAL_X", "CAL_Y")) # storing programs options self.options = Options() # object that manages all other objects :) self.mediator = Mediator(self.cursor(), self) # distance the user wants the device to travel self.wantedX, self.wantedY = 0.0, 0.0 self.setMeasuringMode() # set default values self.reset() def reset(self): u"""resets ui and mediator, loads ratio from file (if was calibrated at runtime and not saved, then calibration data will be lost, sets distance to 0""" # distance travelled by the input device in the measurements units (defalutly milimeters) self.distX, self.distY = 0.0, 0.0 self.mediator.reset() self.mediator.storeRatio(self.options.getRatio()) self.updateUi() def askWanted(self, axis): text, ok = QtGui.QInputDialog.getText( self, programName, _('Distance to measure in %s axis:') % axis) name = {'X': 'wantedX', 'Y': 'wantedY'} try: # force converting to float text = "%s.0" % text distance = float(eval(text)) setattr(self, name[axis], distance) except: self.showInfoMessage( _("You entered inproper number. You can use arithmetic operators (+, -, * /)" )) self.updateUi() def askWantedX(self): self.askWanted('X') def askWantedY(self): self.askWanted('Y') def allowCalibrate(self): text, ok = QtGui.QInputDialog.getText( self, programName, _("""Enter below "SUWMIARKA". It is protection against accidentally changing of the calibration configuration. Entering word other than "SUWMIARKA" or pressing Cancel key simply returns to the mail menu and doesn't allow calibration. If you choose to allow calibrating, and then with any cause you would like to turn off allowing calibration, choose option """ ) + _('Measuring mode')) if ok: if text == "SUWMIARKA": for i in (4, 5): self.ui.menu.activate(i) def saveRatio(self): u"""saves ratio to a file""" try: self.options.saveRatio() # if some problems occurred, show the info message except: self.showInfoMessage( _("Error during saving calibration data to file.")) # else show message that everything was ok else: self.showInfoMessage(_("Calibration data saved correctly")) def finishCal(self): u"""calculates the ratio of the calibrated axis, saves it to the options object (not to a file!!)""" if self.calibration == None: self.showInfoMessage("Blad programu") elif self.calibration in ('X', 'Y'): #TODO: tu jest odwolanie do mediatora, koniecznie ustaw odpowiednie metody !! if self.calibration == 'X': przesuniecie = self.mediator.coordCounter.ticksX else: przesuniecie = self.mediator.coordCounter.ticksY self.showInfoMessage( _("General distance in axis %s: %s" % (self.calibration, przesuniecie))) text, ok = QtGui.QInputDialog.getText( self, programName, _('Enter distance the input device has moved: ')) if ok: calc = przesuniecie / float(text) if self.calibration == 'X': self.options.xRatio = calc elif self.calibration == 'Y': self.options.yRatio = calc self.showInfoMessage( _("Ticks on milimeter in axis ") + self.calibration + _(" is: %s") % calc) self.calibration = None self.setMeasuringMode() self.ui.menu.activate(7) def cal(self, axis): u"""starts calibrating an axis""" self.ui.menu.activate(6) reply = QtGui.QMessageBox.information( self, programName, _("Starting calibration of axis: %s") % axis, QtGui.QMessageBox.Ok) if reply == QtGui.QMessageBox.Ok: self.reset() self.calibration = axis def calX(self): self.mode.setMode("CAL_X") self.cal('X') def calY(self): self.mode.setMode("CAL_Y") self.cal('Y') def keyPressEvent(self, event): proc = { 'A': self.ui.menu.keyUp, 'Z': self.ui.menu.keyDown, 'K': self.ui.menu.executeMethod } if type(event) == QtGui.QKeyEvent: char = chr(event.key()) print 'char: ', char if char in proc: proc[char]() def mouseMoveEvent(self, event): try: self.mediator.coordChanged() except TickException, e: QtGui.QMessageBox.information( self, "", _("Inproper reading from input device."), QtGui.QMessageBox.Ok) self.reset()
class MainWindow(QtWidgets.QWidget): def __init__(self): super().__init__() self._ui = MainWindowUi() self._ui.setupUi(self) self._game_timer = QtCore.QTimer() self._game_timer.timeout.connect(self.on_game_update) self._game_timer.start(100) self._clock_timer = QtCore.QTimer() self._clock_timer.timeout.connect(self.on_clock_update) self._clock_timer.start(1000) self._start_time = datetime.now() # 初始化难度 self._ui.cbDifficulty.addItem("简单", 1) self._ui.cbDifficulty.addItem("中等", 2) self._ui.cbDifficulty.addItem("较难", 4) self._ui.cbDifficulty.addItem("高级", 8) self._ui.cbDifficulty.setCurrentText("简单") self._base_speed = 2 self._ui.cbDifficulty.currentIndexChanged.connect( self.on_difficulty_changed) # 设置主显示区 self._scene = QtWidgets.QGraphicsScene() self._scene.setSceneRect(0, 0, 600, 650) self._ui.main_view.setScene(self._scene) # 加入小球 self._balls: List[MyBallItem] = [] for i in range(10): x = random.randint(0, self.width() - BALL_SIZE) y = 0 color = QtGui.QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) ball = MyBallItem(x, y, BALL_SIZE, color) ball.clicked.connect(self.on_ball_clicked) speed = self._base_speed + random.randint(0, self._base_speed) ball.setSpeed(speed) self._scene.addItem(ball) self._balls.append(ball) self._life = 5 self._score = 0 self._ui.txtScore.setText(f"{self._score}") self._ui.txtLife.setText(f"{self._life}") # 打开鼠标位置监控 self.setMouseTracking(True) self._ui.main_view.setMouseTracking(True) # self.setAttribute(QtCore.Qt.WA_MouseNoMask) def on_difficulty_changed(self, index): self._base_speed = self._ui.cbDifficulty.itemData(index) for j in range(10): self.reset_ball(self._balls[j]) def update_score(self, score): self._score = score self._ui.txtScore.setText(f"{self._score}") def update_life(self, life): self._life = life self._ui.txtLife.setText(f"{self._life}") def on_ball_clicked(self): ball: MyBallItem = self.sender() self.update_score(self._score + 1) self.reset_ball(ball) self._game_timer.stop() if self._score == 150 and self._ui.cbDifficulty.currentIndex() <= 2: self._ui.cbDifficulty.setCurrentIndex(3) elif self._score == 100 and self._ui.cbDifficulty.currentIndex() <= 1: QtWidgets.QMessageBox.information(self, "祝贺", "恭喜你过关了,增加难度,再继续!") self._ui.cbDifficulty.setCurrentIndex(2) elif self._score == 50 and self._ui.cbDifficulty.currentIndex() == 0: QtWidgets.QMessageBox.information(self, "加油", "太棒了,再射中50个你就过关了,增加难度,再继续!") self._ui.cbDifficulty.setCurrentIndex(1) elif self._score == 25 and self._ui.cbDifficulty.currentIndex() == 0: QtWidgets.QMessageBox.information(self, "鼓励", "好样的,继续努力!") self._game_timer.start(100) def reset_ball(self, ball: MyBallItem): ball.setX(random.randint(0, self._scene.width() - BALL_SIZE)) ball.setY(0) ball.setSpeed(self._base_speed + random.randint(0, self._base_speed)) color = QtGui.QColor(random.randint(0, 200), random.randint(0, 200), random.randint(0, 200)) ball.setColor(color) def on_game_update(self): for i in range(10): ball = self._balls[i] if ball.y() > self._scene.height(): if self._life == 0: self._game_timer.stop() QtWidgets.QMessageBox.information(self, "闯关失败", "你失败了,别灰心,降低难度,请重来!") index = self._ui.cbDifficulty.currentIndex() if index > 0: index -= 1 self._ui.cbDifficulty.setCurrentIndex(index) self.update_score(0) self.update_life(5) for j in range(10): self.reset_ball(self._balls[j]) self._start_time = datetime.now() self._game_timer.start(100) self.update_life(self._life - 1) self.reset_ball(ball) continue color = ball.color() color = QtGui.QColor(color.red() * 0.99, color.green() * 0.99, color.blue() * 0.99) ball.setColor(color) ball.moveBy(0, ball.speed()) def on_clock_update(self): now = datetime.now() delta = now - self._start_time hours, minutes, seconds = delta.seconds // 3600, delta.seconds // 60, delta.seconds % 60 self._ui.txtTime.setText(f"{hours:02d}:{minutes:02d}:{seconds:02d}") self._ui.point_frame.update() def mouseMoveEvent(self, e: QtGui.QMouseEvent) -> None: p = QtCore.QPoint(e.x(), e.y()) p = self.mapToGlobal(p) x, y = p.x(), p.y() p = QtCore.QPoint(self._ui.point_frame.width() / 2, self._ui.point_frame.height() / 2) p = self._ui.point_frame.mapToGlobal(p) x1, y1 = p.x(), p.y() a = math.atan2(y1 - y, x - x1) * 180 / math.pi self._ui.point_frame._angle = a self._ui.point_frame.update()