def __init__(self, master, address, min_val, max_val, name, cb_read, docstring="", cb_write=None): super().__init__(master) # Callbacks self.cb_read = cb_read self.cb_write = cb_write # Widgets l_addr = QLabel(hex(address), self) l_addr.setEnabled(False) l_name = QLabel(name, self) l_name.setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.field = InputField(self, min_val, max_val) self.field.setFixedWidth(77) self.field.set_callback_value_changed(self._update_gui_value) self.b_read = QPushButton("Read", self) self.b_read.setFixedSize(55, 28) self.b_read.clicked.connect(self.read) self.b_write = QPushButton("Write", self) self.b_write.setFixedSize(55, 28) self.b_write.setEnabled(False) if self.cb_write is not None: self.b_write.clicked.connect(self.write) self.field.set_callback_value_valid(self.b_write.setEnabled) self.field.set_callback_return_pressed(self.write) else: self.field.set_read_only(True) # Layout grid = QHBoxLayout() grid.addWidget(l_addr) grid.addWidget(l_name) grid.addSpacing(5) grid.addWidget(self.field) grid.addWidget(self.b_read) grid.addWidget(self.b_write) grid.setStretch(1, 1) grid.setContentsMargins(0, 0, 0, 0) self.setLayout(grid) # Members self.address = address self.device_value = None self.gui_value = self.field.get_value() self._std_style = "QPushButton {}" self._bold_style = "QPushButton { font: bold; }" # Init self._update_boldness() if len(docstring) > 0: l_name.setToolTip(docstring)
def __init__(self, width, height): self.z = 15 self.coordinates = ['37.620070', '55.753630'] # Долгота (lon), Широта (lat) self.pts = list() self.type_layer = 'map' self.org = '' self.buttons = pygame.sprite.Group() self.l_btn = LayersButton(self.buttons, self) self.reset_btn = ResetButton(self.buttons, 10, 49, 'Сброс поискового результата', self) self.search = InputField(self) self.btn_search = SearchButton(self.buttons, self.search.outer_rect.x + 10 + self.search.outer_rect.width, self.search.outer_rect.y, self, self.search) self.postal_code_btn = CheckButton(self.buttons, self) self.info = InfoField('') self.last_search = '' self.map = Map(self.coordinates, self.z, self.pts, self.type_layer) self.get_map() self.w, self.h = width, height pygame.init() self.screen = pygame.display.set_mode((width, height)) pygame.display.flip()
class WidgetRegisterEntry(QWidget): def __init__(self, master, address, min_val, max_val, name, cb_read, docstring="", cb_write=None): super().__init__(master) # Callbacks self.cb_read = cb_read self.cb_write = cb_write # Widgets l_addr = QLabel(hex(address), self) l_addr.setEnabled(False) l_name = QLabel(name, self) l_name.setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.field = InputField(self, min_val, max_val) self.field.setFixedWidth(77) self.field.set_callback_value_changed(self._update_gui_value) self.b_read = QPushButton("Read", self) self.b_read.setFixedSize(55, 28) self.b_read.clicked.connect(self.read) self.b_write = QPushButton("Write", self) self.b_write.setFixedSize(55, 28) self.b_write.setEnabled(False) if self.cb_write is not None: self.b_write.clicked.connect(self.write) self.field.set_callback_value_valid(self.b_write.setEnabled) self.field.set_callback_return_pressed(self.write) else: self.field.set_read_only(True) # Layout grid = QHBoxLayout() grid.addWidget(l_addr) grid.addWidget(l_name) grid.addSpacing(5) grid.addWidget(self.field) grid.addWidget(self.b_read) grid.addWidget(self.b_write) grid.setStretch(1, 1) grid.setContentsMargins(0, 0, 0, 0) self.setLayout(grid) # Members self.address = address self.device_value = None self.gui_value = self.field.get_value() self._std_style = "QPushButton {}" self._bold_style = "QPushButton { font: bold; }" # Init self._update_boldness() if len(docstring) > 0: l_name.setToolTip(docstring) def read(self): try: try: self.device_value = self.cb_read(self.address) self.field.set_value(self.device_value) except ValueError: print("Value read from device at address", self.address, "is out of range") raise except (ValueError, OneWireDataMissing): self.device_value = None self.field.clear() finally: self._update_gui_value(self.field.get_value()) def write(self): if self.b_write.isEnabled(): if self.cb_write(self.address, self.gui_value): self.device_value = self.gui_value self._update_boldness() def set_gui_value(self, value): try: self.field.set_value(value) except ValueError: self.field.clear() finally: self._update_gui_value(self.field.get_value()) def get_gui_value(self): return self.gui_value def _update_gui_value(self, value): self.gui_value = value self._update_boldness() def _update_boldness(self): if self.device_value is None: self.b_read.setStyleSheet(self._bold_style) self.b_write.setStyleSheet(self._std_style) else: self.b_read.setStyleSheet(self._std_style) if self.device_value != self.gui_value: self.b_write.setStyleSheet(self._bold_style) else: self.b_write.setStyleSheet(self._std_style)
from PySide2.QtCore import QCoreApplication from PySide2.QtGui import QShowEvent from PySide2.QtWidgets import QApplication from input_field import InputField from utils import bind_callback if __name__ == "__main__": # create this before working with any Qt widgets app = QApplication() # create the floating input field input_field = InputField() # calling input_field.show() directly is not thread safe and breaks in windows, so use events instead def show_input_field(): QCoreApplication.postEvent(input_field, QShowEvent()) # set the key binding, so that the input field appears, when pressing Ctrl-Alt-J bind_callback("Ctrl-Alt-J", show_input_field) # start the Qt event loop app.exec_()
def test(self): # Initialize pygame pygame.init() # Define the colors we will use in RGB format BLACK = pygame.Color('black') WHITE = pygame.Color('white') BLUE = pygame.Color('blue') GREEN = pygame.Color('green') RED = pygame.Color('red') # Set the height, width and caption of the screen size = [550, 425] global screen screen = pygame.display.set_mode(size) pygame.display.set_caption("Example") # Loop until the user clicks the close button. done = False clock = pygame.time.Clock() # Create 2 buttons btn1 = Button('Play', BLACK, RED, (50, 25), (200, 50), self.print_clicked) btn2 = Button('Load Save Point', WHITE, GREEN, (50, 125), (200, 50), self.print_clicked, 24) # Create 1 input field inp_fld1 = InputField('Enter Name', BLUE, WHITE, (50, 225), (200, 50), lambda obj: self.enter_field(obj), len_cap = 12, focus=True) inp_fld2 = InputField('Enter Color', BLUE, WHITE, (50, 325), (200, 50), lambda obj: self.enter_field(obj), len_cap = 12) response = "" # Create 4 special buttons if file is present try: button_pic = pygame.image.load('prettybuttons.png') spc_btn1 = SpecialButton(button_pic, (275, 25), (226, 75), (8, 92), self.print_clicked, hover_offset=(240, 0), press_offset=(480, 0), disable_offset=(720, 0)) spc_btn2 = SpecialButton(button_pic, (275, 125), (226, 75), (8, 428), self.print_clicked, hover_offset=(240, 0), press_offset=(480, 0), disable_offset=(720, 0)) spc_btn3 = SpecialButton(button_pic, (275, 225), (226, 75), (8, 680), self.print_clicked, hover_offset=(240, 0), press_offset=(480, 0), disable_offset=(720, 0)) spc_btn4 = SpecialButton(button_pic, (275, 325), (226, 75), (8, 848), self.print_clicked, hover_offset=(240, 0), press_offset=(480, 0), disable_offset=(720, 0)) spc_btn1.disable() except: print "Unable to test special buttons: 'prettybuttons.png' missing" while not done: # Limit fps to 30 clock.tick(30) # Check for applicable events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() else: for widg in PgxtraWidget._pgutility.get_widgets(): widg.check_event(event) # Iterate through all widgets and draw them for widg in PgxtraWidget._pgutility.get_widgets(): widg.draw(screen) # Display all drawn items to the screen pygame.display.flip()
class MapWindow(object): LON_STEP, LAT_STEP = 0.02, 0.008 def __init__(self, width, height): self.z = 15 self.coordinates = ['37.620070', '55.753630'] # Долгота (lon), Широта (lat) self.pts = list() self.type_layer = 'map' self.org = '' self.buttons = pygame.sprite.Group() self.l_btn = LayersButton(self.buttons, self) self.reset_btn = ResetButton(self.buttons, 10, 49, 'Сброс поискового результата', self) self.search = InputField(self) self.btn_search = SearchButton(self.buttons, self.search.outer_rect.x + 10 + self.search.outer_rect.width, self.search.outer_rect.y, self, self.search) self.postal_code_btn = CheckButton(self.buttons, self) self.info = InfoField('') self.last_search = '' self.map = Map(self.coordinates, self.z, self.pts, self.type_layer) self.get_map() self.w, self.h = width, height pygame.init() self.screen = pygame.display.set_mode((width, height)) pygame.display.flip() def update_map(self): self.map = Map(self.coordinates, self.z, self.pts, self.type_layer) self.get_map() def update(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) if event.type == pygame.KEYDOWN: if event.key == pygame.K_PAGEUP: self.z = self.z + 1 if self.z < 19 else 19 self.update_map() if event.key == pygame.K_PAGEDOWN: self.z = self.z - 1 if self.z > 2 else 2 self.update_map() if event.key == pygame.K_DOWN: lat = self.LAT_STEP * math.pow(2, 15 - self.z) lat = 70 + float(self.coordinates[1]) if float(self.coordinates[1]) - lat < -70 else lat self.coordinates = self.coordinates[0], str(float(self.coordinates[1]) - lat) self.update_map() if event.key == pygame.K_UP: lat = self.LAT_STEP * math.pow(2, 15 - self.z) lat = 70 - float(self.coordinates[1]) if float(self.coordinates[1]) + lat > 70 else lat self.coordinates = self.coordinates[0], str(float(self.coordinates[1]) + lat) self.update_map() if event.key == pygame.K_LEFT: lon = self.LON_STEP * math.pow(2, 15 - self.z) lon = 160 + float(self.coordinates[0]) if float(self.coordinates[0]) - lon < -160 else lon self.coordinates = str(float(self.coordinates[0]) - lon), self.coordinates[1] self.update_map() if event.key == pygame.K_RIGHT: lon = self.LON_STEP * math.pow(2, 15 - self.z) lon = 160 - float(self.coordinates[0]) if float(self.coordinates[0]) + lon > 160 else lon self.coordinates = str(float(self.coordinates[0]) + lon), self.coordinates[1] self.update_map() if event.type == pygame.MOUSEMOTION: pass if event.type == pygame.MOUSEBUTTONDOWN: btns_array = [self.postal_code_btn.rect.collidepoint(event.pos[0], event.pos[1]), self.l_btn.rect.collidepoint(event.pos[0], event.pos[1]), self.search.outer_rect.collidepoint(event.pos[0], event.pos[1]), self.reset_btn.rect.collidepoint(event.pos[0], event.pos[1]), self.btn_search.rect.collidepoint(event.pos[0], event.pos[1])] btns_array.extend([x.rect.collidepoint(event.pos[0], event.pos[1]) for x in self.l_btn.layers_buttons]) if not any(btns_array): step_lon, step_lat, upper_corner_left = self.get_step() coordinates = [str(float(upper_corner_left[0]) + step_lon * event.pos[0]), str(float(upper_corner_left[1]) - step_lat * event.pos[1])] if event.button == 1: self.reset_search() self.append_pt(coordinates[0], coordinates[1]) self.search_object(','.join(x for x in coordinates), type_of_request='click') elif event.button == 3: self.reset_search() data = self.map.search_org(coordinates) if data is not None: self.org = data.get('name', '') org_coordinates = data.get('coordinates') self.append_pt(org_coordinates[0], org_coordinates[1]) self.search_object(','.join(data.get('coordinates')), type_of_request='click', org=True) self.l_btn.update(event) self.search.update(event) self.btn_search.update(event) self.reset_btn.update(event) self.postal_code_btn.update(event) def draw(self): self.screen.blit(pygame.image.load(os.path.join('map_parts/', self.map.name)), (0, 0)) self.l_btn.draw(self.screen) self.search.draw(self.screen) self.btn_search.draw(self.screen) self.reset_btn.draw(self.screen) self.info.draw(self.screen) self.postal_code_btn.draw(self.screen) pygame.display.flip() self.update() def get_step(self): lon = self.LON_STEP * math.pow(2, 15 - self.z) / 1.55 lat = self.LAT_STEP * math.pow(2, 15 - self.z) / 1.47 upper_corner_right = str(float(self.coordinates[0]) + lon), str(float(self.coordinates[1]) + lat) lower_corner_left = str(float(self.coordinates[0]) - lon), str(float(self.coordinates[1]) - lat) upper_corner_left = str(float(self.coordinates[0]) - lon), str(float(self.coordinates[1]) + lat) step_lon = abs(float(lower_corner_left[0]) - float(upper_corner_right[0])) / self.w step_lat = abs(float(lower_corner_left[1]) - float(upper_corner_right[1])) / self.h return step_lon, step_lat, upper_corner_left def append_pt(self, lon, lat): self.pts.append('{},{},round'.format(lon, lat)) def reset_search(self): self.pts.clear() self.org = '' self.last_search = '' self.info.change_address('') self.update_map() def update_search(self): self.search_object(self.last_search) def search_object(self, text, type_of_request=None, org=False): if text != '': self.last_search = text if type_of_request is None: self.pts.clear() self.search.text = '' data = get_object_info(get_response(text)) if data is not None: coords = data.get('coordinates')[0], data.get('coordinates')[1] self.append_pt(coords[0], coords[1]) self.coordinates = coords if self.postal_code_btn.state: if org: self.info.change_address('{}, {}. Индекс: {}'.format(data.get('address'), self.org, data.get('postal_code'))) else: self.info.change_address('{}. Индекс: {}'.format(data.get('address'), data.get('postal_code'))) else: if org: self.info.change_address('{}, {}'.format(data.get('address'), self.org)) else: self.info.change_address(data.get('address')) else: data = get_object_info(get_response(text)) if data is not None: self.coordinates = text.split(',') if self.postal_code_btn.state: if org: self.info.change_address('{}, {}. Индекс: {}'.format(data.get('address'), self.org, data.get('postal_code'))) else: self.info.change_address('{}. Индекс: {}'.format(data.get('address'), data.get('postal_code'))) else: if org: self.info.change_address('{}, {}'.format(data.get('address'), self.org)) else: self.info.change_address(data.get('address')) self.update_map() def get_map(self): try: self.map.get_map() except BaseException as e: print('Возникла ошибка при получении карты: {}. Работа программы завершена.'.format(e)) pygame.quit() sys.exit(0)
def __init__(self, master, cbPing, cbSoftReset, cbFactoryReset, cbBaudrateUpdate=None): super().__init__(master) # Members # Callbacks self.cb_baudrate_update = cbBaudrateUpdate # Widgets frame = QFrame(self) frame.setFrameStyle(QFrame.StyledPanel) self.label_status = QLabel(self) self.label_status.setAlignment(Qt.AlignCenter) l_model = QLabel("Model", self) self.model_nb = QLabel(self) self.model_nb.setAlignment(Qt.AlignRight) l_firmware = QLabel("Firmware", self) self.firmware_v = QLabel(self) self.firmware_v.setAlignment(Qt.AlignRight) l_id = QLabel("ID", self) self.field_id = InputField(self, 0x00, 0xFD) l_baudrate = QLabel("Baudrate", self) self.field_baudrate = QComboBox(self) self.field_baudrate.addItems([e.name for e in OW_BAUDRATE]) self.field_baudrate.currentIndexChanged.connect(self._baudrate_changed) l_return_level = QLabel("Return level", self) self.field_return_level = QComboBox(self) self.field_return_level.addItems([e.name for e in OW_RETURN_LEVEL]) b_ping = QPushButton("Ping", self) b_ping.clicked.connect(cbPing) b_soft_reset = QPushButton("Soft reset", self) b_soft_reset.clicked.connect(cbSoftReset) b_factory_reset = QPushButton("Factory reset", self) b_factory_reset.clicked.connect(cbFactoryReset) self.ow_status = WidgetStatusDisplay(self, OW_COM_STATUS) self.device_status = WidgetStatusDisplay(self, OW_DEVICE_STATUS) # Layout grid = QGridLayout() grid.addWidget(self.label_status, 0, 0, 1, 2) grid.addWidget(l_model, 1, 0) grid.addWidget(self.model_nb, 1, 1) grid.addWidget(l_firmware, 2, 0) grid.addWidget(self.firmware_v, 2, 1) grid.addWidget(l_id, 3, 0) grid.addWidget(self.field_id, 3, 1) grid.addWidget(l_baudrate, 4, 0) grid.addWidget(self.field_baudrate, 4, 1) grid.addWidget(l_return_level, 5, 0) grid.addWidget(self.field_return_level, 5, 1) grid.addWidget(b_ping, 6, 0, 1, 2) grid.addWidget(b_soft_reset, 7, 0, 1, 2) grid.addWidget(b_factory_reset, 8, 0, 1, 2) grid.addWidget(self.ow_status, 9, 0, 1, 2) grid.addWidget(self.device_status, 10, 0, 1, 2) grid.setColumnStretch(1, 1) frame.setLayout(grid) m_grid = QGridLayout() m_grid.addWidget(frame) m_grid.setContentsMargins(0, 0, 0, 0) self.setLayout(m_grid) # Init self.set_device(1, 400000, 2)
class WidgetDevice(QWidget): def __init__(self, master, cbPing, cbSoftReset, cbFactoryReset, cbBaudrateUpdate=None): super().__init__(master) # Members # Callbacks self.cb_baudrate_update = cbBaudrateUpdate # Widgets frame = QFrame(self) frame.setFrameStyle(QFrame.StyledPanel) self.label_status = QLabel(self) self.label_status.setAlignment(Qt.AlignCenter) l_model = QLabel("Model", self) self.model_nb = QLabel(self) self.model_nb.setAlignment(Qt.AlignRight) l_firmware = QLabel("Firmware", self) self.firmware_v = QLabel(self) self.firmware_v.setAlignment(Qt.AlignRight) l_id = QLabel("ID", self) self.field_id = InputField(self, 0x00, 0xFD) l_baudrate = QLabel("Baudrate", self) self.field_baudrate = QComboBox(self) self.field_baudrate.addItems([e.name for e in OW_BAUDRATE]) self.field_baudrate.currentIndexChanged.connect(self._baudrate_changed) l_return_level = QLabel("Return level", self) self.field_return_level = QComboBox(self) self.field_return_level.addItems([e.name for e in OW_RETURN_LEVEL]) b_ping = QPushButton("Ping", self) b_ping.clicked.connect(cbPing) b_soft_reset = QPushButton("Soft reset", self) b_soft_reset.clicked.connect(cbSoftReset) b_factory_reset = QPushButton("Factory reset", self) b_factory_reset.clicked.connect(cbFactoryReset) self.ow_status = WidgetStatusDisplay(self, OW_COM_STATUS) self.device_status = WidgetStatusDisplay(self, OW_DEVICE_STATUS) # Layout grid = QGridLayout() grid.addWidget(self.label_status, 0, 0, 1, 2) grid.addWidget(l_model, 1, 0) grid.addWidget(self.model_nb, 1, 1) grid.addWidget(l_firmware, 2, 0) grid.addWidget(self.firmware_v, 2, 1) grid.addWidget(l_id, 3, 0) grid.addWidget(self.field_id, 3, 1) grid.addWidget(l_baudrate, 4, 0) grid.addWidget(self.field_baudrate, 4, 1) grid.addWidget(l_return_level, 5, 0) grid.addWidget(self.field_return_level, 5, 1) grid.addWidget(b_ping, 6, 0, 1, 2) grid.addWidget(b_soft_reset, 7, 0, 1, 2) grid.addWidget(b_factory_reset, 8, 0, 1, 2) grid.addWidget(self.ow_status, 9, 0, 1, 2) grid.addWidget(self.device_status, 10, 0, 1, 2) grid.setColumnStretch(1, 1) frame.setLayout(grid) m_grid = QGridLayout() m_grid.addWidget(frame) m_grid.setContentsMargins(0, 0, 0, 0) self.setLayout(m_grid) # Init self.set_device(1, 400000, 2) def set_device(self, aId, aBaudrate, aSRL, aStatus=0, aModelNb=None, aFirmwareV=None): try: self.label_status.setText("Device") self.field_id.set_value(aId) self.set_baudrate(aBaudrate) self.set_return_level(aSRL) self.ow_status.set_status(aStatus) self.set_model_nb(aModelNb) self.set_firmware_version(aFirmwareV) except (ValueError, IndexError): self.set_device(1, 400000, 2) def get_id(self): return self.field_id.get_value() def get_baudrate(self): return OW_BAUDRATE[self.field_baudrate.currentIndex()].hl_value def set_baudrate(self, baudrate): for i in range(self.field_baudrate.count()): if OW_BAUDRATE[i].hl_value == baudrate: self.field_baudrate.setCurrentIndex(i) return raise ValueError def get_return_level(self): return OW_RETURN_LEVEL[self.field_return_level.currentIndex()].hl_value def set_return_level(self, return_level): for i in range(self.field_return_level.count()): if OW_RETURN_LEVEL[i].hl_value == return_level: self.field_return_level.setCurrentIndex(i) return raise ValueError def set_ow_status(self, status): if status == 0: self.label_status.setText("Connected device") else: self.label_status.setText("Unreachable device") self.ow_status.set_status(status) def set_device_status(self, status): self.device_status.set_status(status) def set_model_nb(self, model_nb): if model_nb is None: self.model_nb.setText("unknown") else: self.model_nb.setText(str(model_nb)) def set_firmware_version(self, firmware_v): if firmware_v is None: self.firmware_v.setText("unknown") else: self.firmware_v.setText(str(firmware_v)) def _baudrate_changed(self, _): if self.cb_baudrate_update is not None: self.cb_baudrate_update(self.get_baudrate())