def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.setup_ui() self.ui.screen.set_disconnect_callback(self.on_disconnected) self.setup_signal() self.cap_screen = None self.queue = multiprocessing.Queue() self.starting_dialog = None self.timer = None self.check_code = -1 self.recording = False self.record_frames = [] self.record_timer = QtCore.QTimer() self.record_timer.timeout.connect(self.on_record_timeout) self.mini_cap_head = None self.ipc = None # 是否连接过本地手机 self.cap_used = False self.is_first_start = True self.customer_running = False self.device_name = "" self.angle = 0 self.virtual_width = config.DEFAULT_WIDTH self.rotation_watcher = None self.share_proc = None self.share_val = multiprocessing.Value("i", 0) self.frame_timer = None self.frame_queue = deque() self.donate_scene = QtWidgets.QGraphicsScene(self) self.donate_view = QtWidgets.QGraphicsView(self.donate_scene) self.donate_view.setWindowTitle(_("Donate")) self.donate_scene.addItem(QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(":/app/icons/app/donate.jpg")))
class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # setup menu actions self.ui.actionExit.triggered.connect(QtCore.QCoreApplication.instance().quit) self.ui.actionAbout.triggered.connect(self.about) self.ui.actionAboutQt.triggered.connect(self.aboutQt) # initialize tabs self._systemWindowWidget = SystemWindow() self._processMonitorWidget = ProcessMonitor() self._memoryMonitorWidget = MemoryMonitor() self._cpuMonitorWidget = CpuMonitor() self._networkMonitorWidget = NetworkMonitor() self._logBrowserWidget = LogBrowser() self.ui.tabWidget.addTab(self._systemWindowWidget, "System") self.ui.tabWidget.addTab(self._processMonitorWidget, "Processes") self.ui.tabWidget.addTab(self._memoryMonitorWidget, "Memory") self.ui.tabWidget.addTab(self._cpuMonitorWidget, "CPU(s)") self.ui.tabWidget.addTab(self._networkMonitorWidget, "Network") self.ui.tabWidget.addTab(self._logBrowserWidget, "Log browser") def about(self): QtGui.QMessageBox.about(self, "About System Monitor", "A sample Qt/PySide application, which uses self-updating models") def aboutQt(self): QtGui.QMessageBox.aboutQt(self)
def __init__(self, configDb): # self.obeyResize = False self.servers = [] self.configDb = configDb QMainWindow.__init__(self) mainWindow = Ui_MainWindow() mainWindow.setupUi(self) databaseInfoTable = mainWindow.databaseInfoTable mainWindow.databaseTree.currentItemChanged.connect( self.updateDatabaseTreeSelection) # 左侧数据库Tree展开处理 mainWindow.databaseTree.itemExpanded.connect( self.databaseTreeItemExpanded) databaseInfoTable.horizontalHeader().sectionResized.connect( self.databaseTreeColumnResized) # mainWindow.txtStatus.setTextColor(QColor('darkBlue')) mainWindow.twMachineTabs.removeTab( mainWindow.twMachineTabs.indexOf(mainWindow.databaseTab)) mainWindow.twMachineTabs.removeTab( mainWindow.twMachineTabs.indexOf(mainWindow.tableTab)) mainWindow.tableInfoTable.mainApplicationWindow = self # self.logHighlighter = MysqlSyntaxHighlighter(mainWindow.txtStatus.document()) self.mainWindow = mainWindow # self.restoreSizePreferences() self.show() self.tableTab = TableTab(self) self.databaseTab = DatabaseTab(self) self.closeEvent = self.onClose
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.logger = logging.getLogger() self.strl = [] self.connectSlots() self.show()
def __init__(self, parent=None, sockfd=None): super(MyMainWindow, self).__init__(parent) self.sockfd = sockfd self.net_status = '' # 创建用户对象 self.user = User() self.user_l = User() self.user_r = User() Ui_MainWindow.__init__(parent, self.user) # 用户对象传入窗口 self.setupUi(self) self.load_config() # 加载配置
def __init__(self, configDb): self.obeyResize = False self.servers = [] self.configDb = configDb QMainWindow.__init__(self) mainWindow = Ui_MainWindow() mainWindow.setupUi(self) databaseInfoTable = mainWindow.databaseInfoTable mainWindow.actionRefresh.activated.connect(self.actionRefresh) mainWindow.databaseTree.currentItemChanged.connect( self.updateDatabaseTreeSelection) databaseInfoTable.horizontalHeader().sectionResized.connect( self.databaseTreeColumnResized) mainWindow.databaseTree.itemExpanded.connect( self.databaseTreeItemExpanded) mainWindow.txtStatus.setTextColor(QColor('darkBlue')) mainWindow.twMachineTabs.removePage(mainWindow.databaseTab) mainWindow.twMachineTabs.removePage(mainWindow.tableTab) mainWindow.tableInfoTable.mainApplicationWindow = self # mainWindow.txtStatus.append("# Single Comment") # mainWindow.txtStatus.append("/* Multi\nLine Comment") # mainWindow.txtStatus.append("*/") # mainWindow.txtStatus.append("SHOW CREATE TABLE FOR `apiclarify`.`facepalm`;") # mainWindow.txtStatus.append("/* multi-line\n commentz */ SHOW CREATE TABLE FOR `apiclarify`.`facepalm`;") # mainWindow.txtStatus.append("/* comment */ SHOW CREATE TABLE FOR `apiclarify`.`facepalm`; /* commentz */") # mainWindow.txtStatus.append("/* comment SHOW CREATE TABLE FOR `apiclarify`.`facepalm`; commentz */") # mainWindow.txtStatus.append("/* comment \nSHOW CREATE TABLE FOR `apiclarify`.`facepalm`; commentz */") # mainWindow.txtStatus.append("SELECT * FROM test_command;") # mainWindow.txtStatus.append("SHOW TABLE STATUS; # Inline comment") # mainWindow.txtStatus.append("/* comment */ SHOW DATABASES; /* commentz */") # mainWindow.txtStatus.append("SHOW DATABASEN; /* start multiline") # mainWindow.txtStatus.append("commenting */") # mainWindow.txtStatus.append('SELECT * FROM facepalm; /* i can haz comment? */') self.logHighlighter = MysqlSyntaxHighlighter( mainWindow.txtStatus.document()) self.mainWindow = mainWindow self.restoreSizePreferences() self.show() self.tableTab = TableTab(self) self.databaseTab = DatabaseTab(self) self.closeEvent = self.onClose databaseInfoTable.setContextMenuPolicy(Qt.CustomContextMenu) databaseInfoTable.customContextMenuRequested.connect( self.databaseContextMenu)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowIcon(QtGui.QIcon("res/dollar-icon.png")) self.connectAll() self._manager = ModelManager(self) def connectAll(self): self.ui.addButton.pressed.connect(self.addButtonPressed) self.ui.deleteButton.pressed.connect(self.deleteButtonPressed) self.ui.calcButton.pressed.connect(self.calcButtonPressed) self.ui.file_open.triggered.connect(self.open) self.ui.file_save.triggered.connect(self.save) def addButtonPressed(self): cur, flag = QtWidgets.QInputDialog.getText(self, "Ввод названия", "Введите название валюты:") if not flag: return self._manager.addCurrency(cur.strip()) def deleteButtonPressed(self): index = self.ui.listView.currentIndex() if not index.isValid(): QtWidgets.QMessageBox.warning(self, "Не выбрана валюта", "Вы не выбрали валюту для удаления.") else: self._manager.deleteCurrencyNum(index.row()) def calcButtonPressed(self): spec = self._manager.speculation() if spec is not None and spec.exists: self.ui.pathEdit.setText(" -> ".join(spec.path + spec.path[0:1])) self.ui.ratioEdit.setText("{:.5f}".format(spec.ratio)) else: self.ui.pathEdit.clear() self.ui.ratioEdit.clear() QtWidgets.QMessageBox.information(self, "Решения нет", "В данных условиях спекуляция невозможна.") def open(self): filename = QtWidgets.QFileDialog.getOpenFileName(self, u'Открыть', filter = u"Таблица валют (*.ctb);;Все файлы (*.*)")[0] if filename: self._manager.loadModel(filename) def save(self): filename = QtWidgets.QFileDialog.getSaveFileName(self, u'Сохранить', filter = u"Таблица валют (*.ctb);;Все файлы (*.*)")[0] if filename: self._manager.saveModel(filename)
def __init__(self, configDb): self.obeyResize = False self.servers = [] self.configDb = configDb QMainWindow.__init__(self) mainWindow = Ui_MainWindow() mainWindow.setupUi(self) databaseInfoTable = mainWindow.databaseInfoTable mainWindow.actionRefresh.activated.connect(self.actionRefresh) mainWindow.databaseTree.currentItemChanged.connect(self.updateDatabaseTreeSelection) databaseInfoTable.horizontalHeader().sectionResized.connect(self.databaseTreeColumnResized) mainWindow.databaseTree.itemExpanded.connect(self.databaseTreeItemExpanded) mainWindow.txtStatus.setTextColor(QColor('darkBlue')) mainWindow.twMachineTabs.removePage(mainWindow.databaseTab) mainWindow.twMachineTabs.removePage(mainWindow.tableTab) mainWindow.tableInfoTable.mainApplicationWindow = self # mainWindow.txtStatus.append("# Single Comment") # mainWindow.txtStatus.append("/* Multi\nLine Comment") # mainWindow.txtStatus.append("*/") # mainWindow.txtStatus.append("SHOW CREATE TABLE FOR `apiclarify`.`facepalm`;") # mainWindow.txtStatus.append("/* multi-line\n commentz */ SHOW CREATE TABLE FOR `apiclarify`.`facepalm`;") # mainWindow.txtStatus.append("/* comment */ SHOW CREATE TABLE FOR `apiclarify`.`facepalm`; /* commentz */") # mainWindow.txtStatus.append("/* comment SHOW CREATE TABLE FOR `apiclarify`.`facepalm`; commentz */") # mainWindow.txtStatus.append("/* comment \nSHOW CREATE TABLE FOR `apiclarify`.`facepalm`; commentz */") # mainWindow.txtStatus.append("SELECT * FROM test_command;") # mainWindow.txtStatus.append("SHOW TABLE STATUS; # Inline comment") # mainWindow.txtStatus.append("/* comment */ SHOW DATABASES; /* commentz */") # mainWindow.txtStatus.append("SHOW DATABASEN; /* start multiline") # mainWindow.txtStatus.append("commenting */") # mainWindow.txtStatus.append('SELECT * FROM facepalm; /* i can haz comment? */') self.logHighlighter = MysqlSyntaxHighlighter(mainWindow.txtStatus.document()) self.mainWindow = mainWindow self.restoreSizePreferences() self.show() self.tableTab = TableTab(self) self.databaseTab = DatabaseTab(self) self.closeEvent = self.onClose databaseInfoTable.setContextMenuPolicy(Qt.CustomContextMenu) databaseInfoTable.customContextMenuRequested.connect(self.databaseContextMenu)
def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.data_root = "dtpdata" self.year = "" self.month = "" self.reg_code = "" self.ui.tableWidget.setHorizontalHeaderLabels([ "Дата", "ДТП Район", "Вид ДТП", "Погибло", "Ранено", "Кол-во ТС", "Кол-во уч." ]) # Установить текущий год self.ui.spinBox_year.setValue(datetime.now().year) # Установить список месяцев months = [""] months.extend([str(x) for x in range(1, 13)]) self.ui.comboBox_month.insertItems(0, months) if os.path.isfile(regions_json_filename): self.ui.comboBox_regcode.insertItems(0, self.get_combobox_regions()) else: msg = "Необходимо обновить справочник кодов регионов." self.statusBar().showMessage(msg) self.ui.pushButton.setDisabled(True) self.ui.action_Start.setDisabled(True) # a figure instance to plot on self.figure = plt.figure() # self.figure = matplotlib.pyplot.figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent # self.toolbar = NavigationToolbar(self.canvas, self) # Just some button connected to `plot` method # self.button.clicked.connect(self.plot) self.ui.verticalLayout_graph.addWidget(self.canvas)
def __init__(self): super(MainWindow, self).__init__() # Set up the user interface from Designer. self.ui = Ui_MainWindow() self.ui.setupUi(self) self.loadDataDialog = QFileDialog() self.loadDataDialog.setFileMode(QFileDialog.DirectoryOnly) self.loadDataDialog.setOption(QFileDialog.ShowDirsOnly, True) self.loadDataDialog.setAcceptMode(QFileDialog.AcceptOpen) self.loadDataDialog.fileSelected.connect(self.directorySelected) self.ui.loadDataButton.clicked.connect(self.loadDataDialog.show) self.ui.calculateButton.clicked.connect(self.calculateClicked) self.ui.actionAbout.triggered.connect(self.actionAboutTriggered)
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # setup menu actions self.ui.actionExit.triggered.connect(QtCore.QCoreApplication.instance().quit) self.ui.actionAbout.triggered.connect(self.about) self.ui.actionAboutQt.triggered.connect(self.aboutQt) # initialize tabs self._systemWindowWidget = SystemWindow() self._processMonitorWidget = ProcessMonitor() self._memoryMonitorWidget = MemoryMonitor() self._cpuMonitorWidget = CpuMonitor() self._networkMonitorWidget = NetworkMonitor() self._logBrowserWidget = LogBrowser() self.ui.tabWidget.addTab(self._systemWindowWidget, "System") self.ui.tabWidget.addTab(self._processMonitorWidget, "Processes") self.ui.tabWidget.addTab(self._memoryMonitorWidget, "Memory") self.ui.tabWidget.addTab(self._cpuMonitorWidget, "CPU(s)") self.ui.tabWidget.addTab(self._networkMonitorWidget, "Network") self.ui.tabWidget.addTab(self._logBrowserWidget, "Log browser")
def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowIcon(QtGui.QIcon("res/dollar-icon.png")) self.connectAll() self._manager = ModelManager(self)
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # slot button self.ui.buttonCompte.clicked.connect(self.on_click_button_compte) QObject.connect(self.ui.actionClose, SIGNAL("triggered()"), self, SLOT('on_click_menu_button_close()')) QObject.connect(self.ui.actionOuvrir, SIGNAL("triggered()"), self, SLOT('on_click_menu_button_open()')) # widget self.comptepage = ComptePage() self.ui.stack.addWidget(self.comptepage) #default page self.ui.stack.setCurrentWidget(self.comptepage)
class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.worker = None self.DataVisualizer = DataVisualizer(self) self.addDockWidget(Qt.TopDockWidgetArea, self.DataVisualizer) self.boardControl = BoardControl(self) self.addDockWidget(Qt.BottomDockWidgetArea, self.boardControl) self.cmdline = CommandLineWidget(self) self.addDockWidget(Qt.BottomDockWidgetArea, self.cmdline) self.tabifyDockWidget(self.boardControl, self.cmdline) s = QSettings() if s.value("mainwindow/geometry") is not None: self.restoreGeometry(s.value("mainwindow/geometry")) self.restoreState(s.value("mainwindow/state")) # run loadState when the event loop starts QTimer.singleShot(0, self.loadState) def setWorker(self, worker): self.worker = worker self.boardControl.setWorker(worker) @pyqtSlot() def loadState(self): s = QSettings() if s.value("mainwindow/state") is not None: self.restoreState(s.value("mainwindow/state")) def closeEvent(self, event): s = QSettings() s.setValue("mainwindow/geometry", self.saveGeometry()) s.setValue("mainwindow/state", self.saveState()) super().closeEvent(event)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # slot button self.ui.buttonCompte.clicked.connect(self.on_click_button_compte) QObject.connect(self.ui.actionClose, SIGNAL("triggered()"), self, SLOT('on_click_menu_button_close()')) QObject.connect(self.ui.actionOuvrir, SIGNAL("triggered()"), self, SLOT('on_click_menu_button_open()')) # widget self.comptepage = ComptePage() self.ui.stack.addWidget(self.comptepage) #default page self.ui.stack.setCurrentWidget(self.comptepage) @Slot() def on_click_button_compte(self): self.ui.stack.setCurrentWidget(self.comptepage) @Slot() def on_click_menu_button_close(self): self.close() @Slot() def on_click_menu_button_open(self): """Open database file""" w = QFileDialog(self, directory=str(Path.home().absolute()), caption="Selectionnez la base de donné", filter="Base de donnée SQLite (*.sqlite)") w.open()
def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.storage = Storage() self._setStorage(self.storage) self.ui.addGoodButton.pressed.connect(self.addGood) self.ui.delGoodButton.pressed.connect(self.delGood) self.ui.addResButton.pressed.connect(self.addRes) self.ui.delResButton.pressed.connect(self.delRes) self.ui.findSolutionButton.pressed.connect(self.findSolution) self.ui.file_open.triggered.connect(self.openFile) self.ui.file_save.triggered.connect(self.saveFile) for edit in (self.ui.popsizeEdit, self.ui.choosesizeEdit, self.ui.mutsizeEdit, self.ui.breakEdit): edit.setValidator(QtGui.QIntValidator(0, 100000, self)) int(self.ui.popsizeEdit.text()) chosen = int(self.ui.choosesizeEdit.text()) mutsize = int(self.ui.mutsizeEdit.text()) brk = int(self.ui.breakEdit.text())
def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.prediction_models = [] for num, file in zip((10, 100, 1000), (S10_FILE, S100_FILE, S1000_FILE)): model, scaler, labeler = pickle.load(open(file, "rb")) self.prediction_models.append({"num": num, "model": model, "scaler": scaler, "labeler": labeler}) self.ui.action_start.triggered.connect(self.startCapture) self.ui.action_stop.triggered.connect(self.stopCapture) self.ui.tableView.doubleClicked.connect(self.viewDoubleClicked) self.thread = None self.model = TrafficModel(self.prediction_models, self) self.ui.tableView.setModel(self.model) self.ui.tableView.resizeColumnsToContents() ## Иконки: self.setWindowIcon(QtGui.QIcon("res/sherlock.png")) self.ui.action_start.setIcon(QtGui.QIcon("res/start.png")) self.ui.action_stop.setIcon(QtGui.QIcon("res/pause.png"))
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.setup_ui() self.ui.screen.set_disconnect_callback(self.on_disconnected) self.setup_signal() self.cap_screen = None self.queue = multiprocessing.Queue() self.starting_dialog = None self.timer = None self.check_code = -1 self.recording = False self.record_frames = [] self.record_timer = QtCore.QTimer() self.record_timer.timeout.connect(self.on_record_timeout) self.mini_cap_head = None self.ipc = None # 是否连接过本地手机 self.cap_used = False self.is_first_start = True self.customer_running = False self.device_name = "" self.angle = 0 self.virtual_width = config.DEFAULT_WIDTH self.rotation_watcher = None self.share_proc = None self.share_val = multiprocessing.Value("i", 0) self.frame_timer = None self.frame_queue = deque() self.donate_scene = QtWidgets.QGraphicsScene(self) self.donate_view = QtWidgets.QGraphicsView(self.donate_scene) self.donate_view.setWindowTitle(_("Donate")) self.donate_scene.addItem(QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(":/app/icons/app/donate.jpg"))) def on_image_quality_action_triggered(self, checked, width, height): """选择画质""" logger.debug("select image quality %dx%d" % (width, height)) if width == self.virtual_width: return self.on_rotation_changed(self.angle, width) self.virtual_width = width def on_device_action_triggered(self, checked, serial_no): """选择一个设备""" adb_helper.choose_device(serial_no) self.setWindowTitle("pyphone(%s)" % serial_no) self.ui.actionStart.setEnabled(True) real_width, real_height = adb_helper.device_real_size() assert real_height > 0, "Ops! real_height less than 0!" rate = real_height / real_width if real_width not in config.IMAGE_QUALITIES: config.IMAGE_QUALITIES.append(real_width) logger.debug("Image qualities: %s" % config.IMAGE_QUALITIES) self.ui.menuImageQuality.clear() for width in config.IMAGE_QUALITIES: height = int(rate * width) widget = QtWidgets.QRadioButton("%dx%d" % (width, height), self) if width == config.DEFAULT_WIDTH: widget.setChecked(True) action = QtWidgets.QWidgetAction(self) action.setDefaultWidget(widget) widget.clicked.connect(lambda checked_, width_=width, height_=height: self.on_image_quality_action_triggered(checked_, width_, height_)) self.ui.menuImageQuality.addAction(action) def setup_ui(self): self.ui.setupUi(self) serial_no_list = adb_helper.device_serial_no_list() logger.debug("devices: %s" % serial_no_list) # 只有一个设备时,默认选中 if len(serial_no_list) == 1: self.on_device_action_triggered(True, serial_no_list[0]) for sn in serial_no_list: action = QtWidgets.QAction(sn, self) action.triggered.connect(lambda checked_, sn_=sn, action_=action: self.on_device_action_triggered(checked_, sn_)) self.ui.menuDevices.addAction(action) def setup_signal(self): self.ui.actionStart.triggered.connect(self.on_action_start) self.ui.actionVertical.triggered.connect(lambda triggered, angle=0: self.on_rotation_changed(angle)) self.ui.actionHorizontal.triggered.connect(lambda triggered, angle=90: self.on_rotation_changed(angle)) self.ui.actionStop.triggered.connect(self.on_action_stop) self.ui.actionMenu.triggered.connect(KeyEvent.menu) self.ui.actionHome.triggered.connect(KeyEvent.home) self.ui.actionBack.triggered.connect(KeyEvent.back) self.ui.actionLock_Unlocak.triggered.connect(KeyEvent.lock_unlock) self.ui.actionSend_text.triggered.connect(self.on_action_send_text) self.ui.actionRecorder.triggered.connect(self.on_action_recorder) self.ui.actionShare.triggered.connect(self.on_action_share) self.ui.actionRemote_screen.triggered.connect(self.on_action_remote_screen) self.ui.actionAbout.triggered.connect(self.on_action_about) self.ui.actionDonate.triggered.connect(self.on_action_donate) self.ui.actionQuit.triggered.connect(self.close) def update_ui_on_started(self, enable=True): self.ui.actionStart.setEnabled(not enable) self.ui.actionStop.setEnabled(enable) self.ui.actionShare.setEnabled(enable) self.ui.menuEdit.setEnabled(enable) self.ui.menuDevices.setEnabled(not enable) def update_ui_on_stopped(self): self.update_ui_on_started(enable=False) def show_starting_dialog(self, title=_("First start"), text=_("Init env, please wait(about 6 seconds)..."), cap_start=False): logger.debug("show starting dialog") if self.timer: return max_value = 30 self.timer = QtCore.QTimer() self.starting_dialog = QtWidgets.QProgressDialog(self) self.starting_dialog.setWindowModality(QtCore.Qt.ApplicationModal) self.starting_dialog.setWindowTitle(title) self.starting_dialog.setLabelText(text) self.starting_dialog.setMaximum(max_value) self.starting_dialog.setCancelButton(None) def on_start_up_timer(): value = self.starting_dialog.value() self.starting_dialog.setValue(value + 1) pid = adb_helper.current_device().get_pid(config.MINICAP) if pid: logger.debug("minicap pid is %s" % pid) if not cap_start: self.dismiss_starting_dialog() return self.dismiss_starting_dialog() self.on_action_start(ready=True) mini_touch_pid = adb_helper.current_device().get_pid(config.MINITOUCH) logger.debug("minitouch pid is %s" % mini_touch_pid) elif value >= max_value - 1: self.dismiss_starting_dialog() QtWidgets.QMessageBox.critical( self, _(config.TITLE_ERROR), _("Fatal error occurred, please restart")) self.close() self.timer.timeout.connect(on_start_up_timer) self.timer.start(100) self.starting_dialog.show() def dismiss_starting_dialog(self): logger.debug("dismiss starting dialog") self.starting_dialog.close() if self.timer: self.timer.stop() self.timer = None def on_action_stop(self): if self.cap_screen is None: return self.cap_screen.stop() self.on_action_disable_share() self.cap_screen = None self.rotation_watcher.stop() self.update_ui_on_stopped() def on_screenshots_result(self, filename, show_toast=True): if show_toast: Toast.show_(self, _("Saved: %s") % filename) def on_action_start(self, ready=False): if not ready: self.rotation_watcher = RotationWatcher(self.on_rotation_changed, self.queue, adb_helper.current_device()) self.rotation_watcher.start() adb_helper.start_mini_touch() self.show_starting_dialog(cap_start=True) return self.cap_screen = CapScreen(self.on_start_result, self.on_mini_cap_head, self.on_frame, self.on_mini_touch_connect_result, self.on_screenshots_result, self.ui.screen, config.MINICAP_HOST, config.MINICAP_PORT) self.cap_screen.start_() self.cap_used = True self.ui.actionStart.setEnabled(False) self.ui.actionScreenshots.triggered.connect(self.cap_screen.screenshots) def on_start_result(self, ret): if ret == 0: self.update_ui_on_started() else: self.dismiss_starting_dialog() QtWidgets.QMessageBox.critical( self, _(config.TITLE_ERROR), _("Connect failed, please retry after reset your USB line")) self.close() def on_mini_touch_connect_result(self, ret): if not ret: QtWidgets.QMessageBox.warning( self, _(config.TITLE_WARNING), _("Fail to connect minitouch\nThe screen is OK, but you couldn't control")) def on_mini_cap_head(self, head): if not head: return self.mini_cap_head = head w, h = adb_helper.device_real_size() self.ui.screen.set_real_size(w, h) self.setFixedSize(self.sizeHint()) def on_frame(self, frame): self.ui.screen.refresh(frame) if self.ipc: # 注意:只有在producer模式下 if self.ipc.is_producer(): self.frame_queue.append(frame) if self.recording: if frame: self.record_frames.append(frame) def closeEvent(self, event): if self.cap_screen: self.cap_screen.stop() adb_helper.p_kill(config.MINICAP) adb_helper.p_kill(config.MINITOUCH) if self.rotation_watcher: self.rotation_watcher.stop() if self.ipc: self.ipc.stop() if self.share_proc: self.on_disconnect_remote_screen() event.accept() def on_rotation_changed(self, angle, virtual_width=config.DEFAULT_WIDTH): logger.debug("on_rotation_changed. angle={}".format(angle)) self.angle = angle if self.cap_screen: self.cap_screen.stop() adb_helper.restart_mini_cap(angle=angle, virtual_width=virtual_width) self.ui.screen.set_orientation(angle) self.show_starting_dialog(title=_("Rotating"), text=_("Adapting screen rotation, wait about 3 seconds"), cap_start=True) def on_disconnected(self): self.on_action_stop() self.setWindowTitle(version.app_name) QtWidgets.QMessageBox.critical( self, _("Disconnected"), _("USB line pulled out or you closed USB-DEBUG mode")) def on_rpc_event(self, sig_id, data): if sig_id == IpcSignal.SIG_TOUCH: if self.cap_screen: # now data is a operation dict self.cap_screen.handle_rpc_event(data) elif sig_id == IpcSignal.SIG_FRAME: # now data is a jpg buffer self.on_frame(data) def on_action_send_text(self): """向设备发送文本""" if not self.cap_screen: return text, ret = QtWidgets.QInputDialog.getText(self, _("Send text"), _("Please input the content")) if not ret: return self.cap_screen.touch.send_text(text) def on_disconnect_remote_screen(self): self.share_val.value = 1 self.share_proc = None logger.debug("kill share process") self.ui.actionRemote_screen.setText(_("Connect remote screen...")) def on_action_remote_screen(self): if self.share_proc: return self.on_disconnect_remote_screen() share_id, ret = QtWidgets.QInputDialog.getInt( self, _("Remote share"), _("Please input your share id"), value=Ipc.MIN_SHARE_ID) if not ret: return frame_queue, tmp = Ipc.make_queue(share_id) self.share_val.value = 0 self.share_proc = multiprocessing.Process(target=remote_screen.start, args=(self.share_val, frame_queue, )) self.share_proc.start() Toast.show_(self, _("Remote screen started, waiting frame ...")) logger.debug("remote screen started, pid: %d" % self.share_proc.pid) self.ui.actionRemote_screen.setText(_("Disconnect remote screen...")) def update_frame_in_timer(self): size = len(self.frame_queue) if size < 1: return elif size > 4: self.frame_queue.popleft() if self.ipc: self.ipc.push_frame(self.frame_queue.popleft()) def on_action_share(self): if self.ipc is None: self.on_action_enable_share() else: self.on_action_disable_share() def on_action_enable_share(self): if not self.cap_screen: return self.ipc = Ipc(self.on_rpc_event) ret, share_id = self.ipc.producer_init(config.REDIS_HOST, config.REDIS_PORT, config.REDIS_DB) if not ret: QtWidgets.QMessageBox.critical( self, _(config.TITLE_ERROR), _("Fail to connect redis server\n%s:%d" % (config.REDIS_HOST, config.REDIS_PORT))) self.ipc = None return # 若定时器未初始化过,则先初始化并绑定信号槽 if self.frame_timer is None: self.frame_timer = QtCore.QTimer() self.frame_timer.timeout.connect(self.update_frame_in_timer) self.frame_queue.clear() self.frame_timer.start(10) self.set_tip_message(_("Sharing with ID: %d") % share_id) self.ipc.start() self.ui.actionShare.setText(_("Disable share")) def on_action_disable_share(self): if self.ipc is None: logger.error("self.ipc is None") return self.frame_timer.stop() self.ipc.stop() self.ipc = None self.set_tip_message("") self.ui.actionShare.setText(_("Enable share")) def on_action_about(self): QtWidgets.QMessageBox.information(self, _("About"), version.about) def on_action_donate(self): self.donate_view.move(self.x() + self.width(), self.y()) self.donate_view.show() def on_record_timeout(self): self.on_record() def on_action_recorder(self): if self.recording: self.on_action_stop_recorder() else: self.on_action_start_recorder() def on_action_start_recorder(self): if len(self.record_frames) > 0: QtWidgets.QMessageBox.critical( self, _(config.TITLE_INFO), _("Please try after current video been saved")) return self.record_timer.start(config.MAX_RECORD_MIN * 60 * 1000) self.recording = True self.set_tip_message(_("Recording (time limit %d min)...") % config.MAX_RECORD_MIN) mp4file = os.path.join(config.VIDEO_DIR, time.strftime("%y-%m-%d/%H-%M-%S.mp4")) _dir = os.path.dirname(mp4file) if not os.path.exists(_dir): try: os.makedirs(_dir) except OSError as err: logger.error("fail to create video path: %s" % err) mp4file = "tmp.mp4" orientation = self.ui.screen.get_orientation() if orientation == self.ui.screen.VERTICAL: logger.debug("VERTICAL recorder") width, height = self.mini_cap_head.virtual_width, self.mini_cap_head.virtual_height else: logger.debug("HORIZONTAL recorder") width, height = self.mini_cap_head.virtual_height, self.mini_cap_head.virtual_width recorder.init(mp4file, 40, width, height) self.record_frames = [] self.ui.actionRecorder.setText(_("Stop video recorder ...")) def on_action_stop_recorder(self): self.recording = False if self.record_timer.isActive(): self.record_timer.stop() if len(self.record_frames) < 1: QtWidgets.QMessageBox.critical(self, _(config.TITLE_ERROR), _("No any frame, your screen didn't change!")) self.set_tip_message("") self.ui.actionRecorder.setText(_("Start video recorder ...")) return self.set_tip_message(_("Saving video ...")) self.ui.actionRecorder.setEnabled(self.recording) def save_task(frames): recorder.write_frames(frames) mp4file = recorder.finish() self.set_tip_message("%s" % mp4file.replace("\\", "/")) self.record_frames = [] self.ui.actionRecorder.setEnabled(not self.recording) self.ui.actionRecorder.setText(_("Start video recorder ...")) task = threading.Thread(target=save_task, args=(self.record_frames,)) task.start() def set_tip_message(self, text): if text == "": text = "%s(%s)" % (version.app_name, self.device_name) self.setWindowTitle(text)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() # Set up the user interface from Designer. self.ui = Ui_MainWindow() self.ui.setupUi(self) self.loadDataDialog = QFileDialog() self.loadDataDialog.setFileMode(QFileDialog.DirectoryOnly) self.loadDataDialog.setOption(QFileDialog.ShowDirsOnly, True) self.loadDataDialog.setAcceptMode(QFileDialog.AcceptOpen) self.loadDataDialog.fileSelected.connect(self.directorySelected) self.ui.loadDataButton.clicked.connect(self.loadDataDialog.show) self.ui.calculateButton.clicked.connect(self.calculateClicked) self.ui.actionAbout.triggered.connect(self.actionAboutTriggered) @pyqtSlot(str) def directorySelected(self, dataDirectory): print("Selected data directory: {0}".format(dataDirectory)) self.loadData(dataDirectory) def loadData(self, dataDirectory): print("Loading model with data from: {0}".format(dataDirectory)) self.ui.loadDataButton.setEnabled(False) self.ui.statusLabel.setText("Loading model, please wait...") try: self.model = Model(dataDirectory) except Exception as ex: print("Model load error: {0}".format(ex)) self.ui.statusLabel.setText( "Error occured during loading the model. Please, try again.") self.ui.statusLabel.setStyleSheet("color: red") self.ui.loadDataButton.setEnabled(True) return self.triggerModelLoaded() print("Model loaded successfully") def triggerModelLoaded(self): self.ui.statusLabel.setStyleSheet("color: orange") self.ui.statusLabel.setText( "Model loaded sucessfully. Now you can start calculations.") self.ui.loadDataButton.setEnabled(True) self.ui.calculateButton.setEnabled(True) @pyqtSlot() def calculateClicked(self): print("Running model") if self.ui.useSweepRadioButton.isChecked(): algorithmType = Model.AlgorithmType.Sweep elif self.ui.useClarkeWrightRadioButton.isChecked(): algorithmType = Model.AlgorithmType.ClarkeWright else: assert False, "Either Sweep or ClarkeWright should be checked" self.ui.loadDataButton.setEnabled(False) self.ui.calculateButton.setEnabled(False) self.ui.useSweepRadioButton.setEnabled(False) self.ui.useClarkeWrightRadioButton.setEnabled(False) self.ui.statusLabel.setText("Running model, please wait...") try: carsUsage, _ = self.model.run(algorithmType) except Exception as ex: print("Model run error: {0}".format(ex)) self.ui.statusLabel.setText( "Error occured during running the model. Please, try again.") self.ui.statusLabel.setStyleSheet("color: red") self.ui.loadDataButton.setEnabled(True) self.ui.useSweepRadioButton.setEnabled(True) self.ui.useClarkeWrightRadioButton.setEnabled(True) raise self.ui.statusLabel.setText("Model calculated successfully!") self.ui.statusLabel.setStyleSheet("color: green") self.openResultsDialog(carsUsage) def openResultsDialog(self, modelResults): print("Opening results dialog") self.ui.inputDataDialog = InputDataDialog(self.model.data, self) self.ui.resultsDialog = ResultsDialog(self.model.data, modelResults, self) self.ui.resultsDialog.finished.connect(self.resultsDialogFinished) self.ui.inputDataDialog.show() self.ui.resultsDialog.show() print("Results dialog opened") @pyqtSlot() def resultsDialogFinished(self): self.triggerModelLoaded() self.ui.useSweepRadioButton.setEnabled(True) self.ui.useClarkeWrightRadioButton.setEnabled(True) @pyqtSlot() def actionAboutTriggered(self): self.aboutDialog = AboutDialog(self) self.aboutDialog.show()
class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.prediction_models = [] for num, file in zip((10, 100, 1000), (S10_FILE, S100_FILE, S1000_FILE)): model, scaler, labeler = pickle.load(open(file, "rb")) self.prediction_models.append({"num": num, "model": model, "scaler": scaler, "labeler": labeler}) self.ui.action_start.triggered.connect(self.startCapture) self.ui.action_stop.triggered.connect(self.stopCapture) self.ui.tableView.doubleClicked.connect(self.viewDoubleClicked) self.thread = None self.model = TrafficModel(self.prediction_models, self) self.ui.tableView.setModel(self.model) self.ui.tableView.resizeColumnsToContents() ## Иконки: self.setWindowIcon(QtGui.QIcon("res/sherlock.png")) self.ui.action_start.setIcon(QtGui.QIcon("res/start.png")) self.ui.action_stop.setIcon(QtGui.QIcon("res/pause.png")) def startCapture(self): all_devs = sorted(pcapy.findalldevs()) dev, ok = QtGui.QInputDialog.getItem(self, u"Выбор устройства", u"Выберите устройство:", all_devs, 0, False) if not ok: return self.model = TrafficModel(self.prediction_models, self) self.ui.tableView.setModel(self.model) self.ui.tableView.resizeColumnsToContents() self.ui.action_start.setEnabled(False) self.ui.action_stop.setEnabled(True) self.thread = CapThread(str(dev)) self.thread.framesReceived.connect(self.addFrames) self.thread.start() def stopCapture(self): self.ui.action_start.setEnabled(True) self.ui.action_stop.setEnabled(False) self.thread.terminate() self.thread = None def addFrames(self, raws): flows = {} for raw in raws: eth = dpkt.ethernet.Ethernet(raw) if eth.type != dpkt.ethernet.ETH_TYPE_IP: continue ip = eth.data if ip.p == dpkt.ip.IP_PROTO_TCP: proto = "TCP" elif ip.p == dpkt.ip.IP_PROTO_UDP: proto = "UDP" else: continue seg = ip.data flow_key = (frozenset([(ip.src, seg.sport), (ip.dst, seg.dport)]), proto) if flow_key not in flows: flows[flow_key] = [] flows[flow_key].append(eth) self.model.addFlows(flows) self.ui.tableView.resizeColumnsToContents() def viewDoubleClicked(self, index): flow = self.model.getFlow(index) outfile = dpkt.pcap.Writer(open("/tmp/dump.pcap", "wb")) for i, eth in enumerate(flow["dump"]): outfile.writepkt(eth, i) outfile.close() subprocess.call("echo 'wireshark /tmp/dump.pcap' | runuser sergio &", shell=True)
class MainWindow(QtWidgets.QMainWindow): '''To modify the ui: 1. open & modify & save the ui file with qt-creator 2. puic5 file_name.ui -o output_name.py 3. import the output class ''' def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.logger = logging.getLogger() self.strl = [] self.connectSlots() self.show() def connectSlots(self): self.ui.RadioMono.clicked.connect(self.onMonoSelected) self.ui.RadioStereo.clicked.connect(self.onStereoSelected) self.ui.RadioNormal.clicked.connect(self.onNormalSelected) self.ui.RadioAigue.clicked.connect(self.onAigueSelected) self.ui.RadioGrave.clicked.connect(self.onGraveSelected) self.ui.RadioFoule.clicked.connect(self.onFouleSelected) def setHosts(self, hosts): self.logger.debug(hosts) self.hosts = hosts.copy() def connectToStreams(self): self.logger.debug("It starts to connect to the streams") try: for i in range(len(self.hosts)): self.logger.debug(self.hosts[i]) self.strl.append( Stream(True, self.hosts[i][0], self.hosts[i][1])) self.strl[-1].connect() self.strl[-1].start() except Exception as e: self.logger.error(e) def updateStream(self, n): for i in range(len(self.strl)): self.strl[i].setCanal(n) #user's event @pyqtSlot() def onMonoSelected(self): self.logger.debug("The output is now Mono") self.updateStream(1) pass @pyqtSlot() def onStereoSelected(self): self.logger.debug("The output is now Stereo") self.updateStream(2) pass @pyqtSlot() def onNormalSelected(self): self.logger.debug("The filter is now: normal") #self.updateStream(2) pass @pyqtSlot() def onAigueSelected(self): self.logger.debug("The filter is now: aigue") #self.updateStream(3) pass @pyqtSlot() def onGraveSelected(self): self.logger.debug("The filter is now: grave") #self.updateStream(1) pass @pyqtSlot() def onFouleSelected(self): self.logger.debug("The filter is now: foule") pass
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.storage = Storage() self._setStorage(self.storage) self.ui.addGoodButton.pressed.connect(self.addGood) self.ui.delGoodButton.pressed.connect(self.delGood) self.ui.addResButton.pressed.connect(self.addRes) self.ui.delResButton.pressed.connect(self.delRes) self.ui.findSolutionButton.pressed.connect(self.findSolution) self.ui.file_open.triggered.connect(self.openFile) self.ui.file_save.triggered.connect(self.saveFile) for edit in (self.ui.popsizeEdit, self.ui.choosesizeEdit, self.ui.mutsizeEdit, self.ui.breakEdit): edit.setValidator(QtGui.QIntValidator(0, 100000, self)) int(self.ui.popsizeEdit.text()) chosen = int(self.ui.choosesizeEdit.text()) mutsize = int(self.ui.mutsizeEdit.text()) brk = int(self.ui.breakEdit.text()) def addGood(self): good, flag = QtWidgets.QInputDialog.getText(self, "Ввод названия", "Введите название товара:") if not flag: return good = good.strip() if not good: return QtWidgets.QMessageBox.warning(self, "Ошибка", "Название товара не может быть пустым.") try: self.storage.addGood(good) except ValueError: QtWidgets.QMessageBox.warning(self, "Ошибка", "Товар с таким названием уже существует.") def delGood(self): index = self.ui.goodsView.currentIndex() if not index.isValid(): QtWidgets.QMessageBox.warning(self, "Ошибка", "Вы не выбрали товар для удаления.") else: self.storage.delGood(index.row()) def addRes(self): resname, flag = QtWidgets.QInputDialog.getText(self, "Ввод названия", "Введите название ресурса:") if not flag: return resname = resname.strip() if not resname: return QtWidgets.QMessageBox.warning(self, "Ошибка", "Название товара не может быть пустым.") try: self.storage.addRes(resname) except ValueError: QtWidgets.QMessageBox.warning(self, "Ошибка", "Товар с таким названием уже существует.") def delRes(self): index = self.ui.resView.currentIndex() if not index.isValid(): QtWidgets.QMessageBox.warning(self, "Ошибка", "Вы не выбрали ресурс для удаления.") else: self.storage.delRes(index.row()) def findSolution(self): if self.storage.resCount() == 0 or self.storage.goodsCount() == 0: return QtWidgets.QMessageBox.warning(self, "Ошибка", "Вы должны задать хотя бы один товар и хотя бы один ресурс.") goods, res = self.storage.goods(), self.storage.resources() if any(all(cost == 0 for cost in good["cost"]) for good in goods): return QtWidgets.QMessageBox.warning(self, "Ошибка", "У каждого товара должна быть ненулевая ресурсная стоимость.") popsize = int(self.ui.popsizeEdit.text()) chosen = int(self.ui.choosesizeEdit.text()) mutsize = int(self.ui.mutsizeEdit.text()) brk = int(self.ui.breakEdit.text()) if 0 in (popsize, chosen, brk): return QtWidgets.QMessageBox.warning(self, "Ошибка", "Число популяции, количество отбираемых решений и число холостых итераций должны быть ненулевыми.") if popsize < chosen: return QtWidgets.QMessageBox.warning(self, "Ошибка", "Число отбираемых решений не может быть больше численности популяции!") solution = GeneticAlgorithm(goods, res, popsize, chosen, mutsize, brk).solve() self._updateGoodsSolutionTable(solution) self._updateResSolutionTable(solution) def _updateGoodsSolutionTable(self, sln): tbl = self.ui.goodResultTable tbl.setRowCount(len(sln["items"])+1) s = 0 c = 0 for i, item in enumerate(sln["items"]): name = QtWidgets.QTableWidgetItem(item["name"]) count = QtWidgets.QTableWidgetItem(str(item["count"])) price = item["count"]*self.storage.goodPrice(i) s += price c += item["count"] price_item = QtWidgets.QTableWidgetItem(str(price)) tbl.setItem(i, 0, name) tbl.setItem(i, 1, count) tbl.setItem(i, 2, price_item) lastrow = [ QtWidgets.QTableWidgetItem("Итого:"), QtWidgets.QTableWidgetItem(str(c)), QtWidgets.QTableWidgetItem(str(s)) ] font = QtGui.QFont() font.setBold(True) for i, tab_item in enumerate(lastrow): tab_item.setFont(font) tbl.setItem(len(sln["items"]), i, tab_item) def _updateResSolutionTable(self, sln): tbl = self.ui.resResultTable_2 resources = self.storage.resources() res_info = [{"name": res["name"], "needed": 0, "left": res["qnt"]} for res in resources] for gdind, item in enumerate(sln["items"]): count = item["count"] for resind in range(self.storage.resCount()): cost = count * self.storage.goodCost(gdind, resind) res_info[resind]["needed"] += cost res_info[resind]["left"] -= cost tbl.setRowCount(self.storage.resCount()) for i, res in enumerate(res_info): tbl.setItem(i, 0, QtWidgets.QTableWidgetItem(res["name"])) tbl.setItem(i, 1, QtWidgets.QTableWidgetItem(str(res["needed"]))) tbl.setItem(i, 2, QtWidgets.QTableWidgetItem(str(res["left"]))) def openFile(self): filename = QtWidgets.QFileDialog.getOpenFileName(self, u'Открыть', filter = u"Таблица товаров (*.gtb);;Все файлы (*.*)")[0] if filename: try: self.storage = Storage.fromDump(filename) except pickle.UnpicklingError: QtWidgets.QMessageBox.warning(self, "Ошибка", "Файл повреждён или имеет неверный формат.") except PermissionError: QtWidgets.QMessageBox.warning(self, "Ошибка", "Не удалось прочесть файл: отказано в доступе.") except: QtWidgets.QMessageBox.warning(self, "Ошибка", "Ошибка чтения файла.") else: self._setStorage(self.storage) def saveFile(self): filename = QtWidgets.QFileDialog.getSaveFileName(self, u'Сохранить', filter = u"Таблица товаров (*.gtb);;Все файлы (*.*)")[0] if filename: try: self.storage.dump(filename) except PermissionError: QtWidgets.QMessageBox.warning(self, "Ошибка", "Не удалось записать файл: отказано в доступе.") except: QtWidgets.QMessageBox.warning(self, "Ошибка", "Ошибка записи файла.") def _setStorage(self, storage): self.resmodel = ResModel(storage, self) self.goodsmodel = GoodsModel(storage, self) self.ui.resView.setModel(self.resmodel) self.ui.goodsView.setModel(self.goodsmodel)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, dbase, parent = None): super(MainWindow, self).__init__(parent) self.dbase = dbase self.ui = Ui_MainWindow() self.ui.setupUi(self) self.configUI() def reportDay(self): dlg = GetDate(self) dlg.exec_() if not dlg.date: return filename, ok = QtWidgets.QFileDialog.getSaveFileName(self, u'Сохранить', filter = u"Документ PDF (*.pdf)") if ok: report_day_sales(dlg.date, filename, self.dbase) def reportMonth(self): filename, ok = QtWidgets.QFileDialog.getSaveFileName(self, u'Сохранить', filter = u"Документ PDF (*.pdf)") if ok: report_month_sales(filename, self.dbase) def configUI(self): # Устанавливаем иконки к действиям: self.setWindowIcon(get_icon("appicon")) self.ui.view_clients.setIcon(get_icon("customer")) self.ui.view_employees.setIcon(get_icon("employee")) self.ui.view_shops.setIcon(get_icon("shop")) self.ui.view_details.setIcon(get_icon("detail")) self.ui.view_cars.setIcon(get_icon("car")) self.ui.view_warehouse.setIcon(get_icon("warehouse")) self.ui.view_cardetails.setIcon(get_icon("cardetails")) self.ui.view_orders.setIcon(get_icon("order")) self.ui.report_day.triggered.connect(self.reportDay) self.ui.report_month.triggered.connect(self.reportMonth) # Настраиваем переключение форм: actions = [self.ui.view_clients, self.ui.view_orders, self.ui.view_employees, self.ui.view_shops, self.ui.view_warehouse, self.ui.view_details, self.ui.view_cars, self.ui.view_cardetails] for act in actions: act.triggered.connect((lambda a: lambda: self.actionTriggered(a))(act)) # Форма "Клиенты": self._clientForm = GenericFormController("customer", self.dbase, {"widget": self.ui.clientListView, "role": "view", "format": "{lastname} {firstname:.1}. {middlename:.1}."}, {"widget": self.ui.clientAddButton, "role": "insert"}, {"widget": self.ui.clientDeleteButton, "role": "delete"}, {"widget": self.ui.clientSaveButton, "role": "commit"}, {"widget": self.ui.clientCancelButton, "role": "rollback"}, {"widget": self.ui.clientFirstnameLabel, "role": "display", "column": "firstname"}, {"widget": self.ui.clientLastnameLabel, "role": "display", "column": "lastname"}, {"widget": self.ui.clientMiddlenameLabel, "role": "display", "column": "middlename"}, {"widget": self.ui.clientBirthdateLabel, "role": "display", "column": "birthdate"}, {"widget": self.ui.clientRegdateLabel, "role": "display", "column": "regdate"}, {"widget": self.ui.clientEmailLabel, "role": "display", "column": "email"}, {"widget": self.ui.clientPhoneLabel, "role": "display", "column": "phone"}, {"widget": self.ui.clientPassportLabel, "role": "display", "column": "passport"}, {"widget": self.ui.clientFirstnameEdit, "role": "edit", "column": "firstname"}, {"widget": self.ui.clientLastnameEdit, "role": "edit", "column": "lastname"}, {"widget": self.ui.clientMiddlenameEdit, "role": "edit", "column": "middlename"}, {"widget": self.ui.clientBirthdateEdit, "role": "edit", "column": "birthdate"}, {"widget": self.ui.clientRegdateEdit, "role": "edit", "column": "regdate"}, {"widget": self.ui.clientEmailEdit, "role": "edit", "column": "email"}, {"widget": self.ui.clientPhoneEdit, "role": "edit", "column": "phone"}, {"widget": self.ui.clientPassportEdit, "role": "edit", "column": "passport"} ) self.setupForm(self._clientForm, self.ui.clientEditButton, self.ui.clientStack, self.ui.clientReadPage, self.ui.clientWritePage) # Форма "Магазины": self._shopForm = GenericFormController("shop", self.dbase, {"widget": self.ui.shopListView, "role": "view", "format": "{name}"}, {"widget": self.ui.shopAddButton, "role": "insert"}, {"widget": self.ui.shopDeleteButton, "role": "delete"}, {"widget": self.ui.shopSaveButton, "role": "commit"}, {"widget": self.ui.shopCancelButton, "role": "rollback"}, {"widget": self.ui.shopAddressLabel, "role": "display", "column": "address"}, {"widget": self.ui.shopDescriptionLabel, "role": "display", "column": "description"}, {"widget": self.ui.shopNameLabel, "role": "display", "column": "name"}, {"widget": self.ui.shopPhoneLabel, "role": "display", "column": "phone"}, {"widget": self.ui.shopDescriptionEdit, "role": "edit", "column": "description"}, {"widget": self.ui.shopNameEdit, "role": "edit", "column": "name"}, {"widget": self.ui.shopPhoneEdit, "role": "edit", "column": "phone"}, {"widget": self.ui.shopAddressEdit, "role": "edit", "column": "address"}, ) self.setupForm(self._shopForm, self.ui.shopEditButton, self.ui.shopStack, self.ui.shopReadPage, self.ui.shopWritePage) # Форма "Машины": self._carForm = PhotoFormController("car", self.dbase, {"widget": self.ui.carListView, "role": "view", "format": "{name}"}, {"widget": self.ui.carAddButton, "role": "insert"}, {"widget": self.ui.carDeleteButton, "role": "delete"}, {"widget": self.ui.carSaveButton, "role": "commit"}, {"widget": self.ui.carCancelButton, "role": "rollback"}, {"widget": self.ui.carDescriptionLabel, "role": "display", "column": "description"}, {"widget": self.ui.carNameLabel, "role": "display", "column": "name"}, {"widget": self.ui.carProddateLabel, "role": "display", "column": "proddate"}, {"widget": self.ui.carDescriptionEdit, "role": "edit", "column": "description"}, {"widget": self.ui.carNameEdit, "role": "edit", "column": "name"}, {"widget": self.ui.carProddateEdit, "role": "edit", "column": "proddate"}, {"widget": self.ui.carPhotoLabel, "role": "photo", "column": "photo"}, {"widget": self.ui.carPhotoLabel_2, "role": "photo", "column": "photo"}, {"widget": self.ui.carBrowsePhotoButton, "role": "browse_photo", "column": "photo"}, {"widget": self.ui.carDeletePhotoButton, "role": "delete_photo", "column": "photo"} ) self.setupForm(self._carForm, self.ui.carEditButton, self.ui.carStack, self.ui.carReadPage, self.ui.carWritePage) # Форма "Детали": self._detailForm = PhotoFormController("detail", self.dbase, {"widget": self.ui.detailListView, "role": "view", "format": "{article}: {name}"}, {"widget": self.ui.detailAddButton, "role": "insert"}, {"widget": self.ui.detailDeleteButton, "role": "delete"}, {"widget": self.ui.detailSaveButton, "role": "commit"}, {"widget": self.ui.detailCancelButton, "role": "rollback"}, {"widget": self.ui.detailDescriptionLabel, "role": "display", "column": "description"}, {"widget": self.ui.detailNameLabel, "role": "display", "column": "name"}, {"widget": self.ui.detailArticleLabel, "role": "display", "column": "article"}, {"widget": self.ui.detailCategoryLabel, "role": "display", "column": "category"}, {"widget": self.ui.detailPriceLabel, "role": "display", "column": "price"}, {"widget": self.ui.detailWarrantyLabel, "role": "display", "column": "warranty"}, {"widget": self.ui.detailDescriptionEdit, "role": "edit", "column": "description"}, {"widget": self.ui.detailNameEdit, "role": "edit", "column": "name"}, {"widget": self.ui.detailArticleEdit, "role": "edit", "column": "article"}, {"widget": self.ui.detailCategoryEdit, "role": "edit", "column": "category"}, {"widget": self.ui.detailPriceEdit, "role": "edit", "column": "price"}, {"widget": self.ui.detailWarrantyEdit, "role": "edit", "column": "warranty"}, {"widget": self.ui.detailPhotoLabel, "role": "photo", "column": "photo"}, {"widget": self.ui.detailPhotoLabel_2, "role": "photo", "column": "photo"}, {"widget": self.ui.detailBrowsePhotoButton, "role": "browse_photo", "column": "photo"}, {"widget": self.ui.detailDeletePhotoButton, "role": "delete_photo", "column": "photo"} ) self.setupForm(self._detailForm, self.ui.detailEditButton, self.ui.detailStack, self.ui.detailReadPage, self.ui.detailWritePage) # Форма "Работники": self._empForm = ForeignFormController("employee", self.dbase, {"widget": self.ui.empListView, "role": "view", "format": "{lastname} {firstname:.1}. {middlename:.1}."}, {"widget": self.ui.empAddButton, "role": "insert"}, {"widget": self.ui.empDeleteButton, "role": "delete"}, {"widget": self.ui.empSaveButton, "role": "commit"}, {"widget": self.ui.empCancelButton, "role": "rollback"}, {"widget": self.ui.empLastnameLabel, "role": "display", "column": "lastname"}, {"widget": self.ui.empFirstnameLabel, "role": "display", "column": "firstname"}, {"widget": self.ui.empMiddlenameLabel, "role": "display", "column": "middlename"}, {"widget": self.ui.empBirthdateLabel, "role": "display", "column": "birthdate"}, {"widget": self.ui.empDepartmentLabel, "role": "display", "column": "department"}, {"widget": self.ui.empEmpdateLabel, "role": "display", "column": "empdate"}, {"widget": self.ui.empPassportLabel, "role": "display", "column": "passport"}, {"widget": self.ui.empPositionLabel, "role": "display", "column": "position"}, {"widget": self.ui.empSalaryLabel, "role": "display", "column": "salary"}, {"widget": self.ui.empLastnameEdit, "role": "edit", "column": "lastname"}, {"widget": self.ui.empFirstnameEdit, "role": "edit", "column": "firstname"}, {"widget": self.ui.empMiddlenameEdit, "role": "edit", "column": "middlename"}, {"widget": self.ui.empBirthdateEdit, "role": "edit", "column": "birthdate"}, {"widget": self.ui.empDepartmentEdit, "role": "edit", "column": "department"}, {"widget": self.ui.empEmpdateEdit, "role": "edit", "column": "empdate"}, {"widget": self.ui.empPassportEdit, "role": "edit", "column": "passport"}, {"widget": self.ui.empPositionEdit, "role": "edit", "column": "position"}, {"widget": self.ui.empSalaryEdit, "role": "edit", "column": "salary"}, {"widget": self.ui.empShopEdit, "role": "edit", "column": "shop_id"}, {"widget": self.ui.empShopProxyLabel, "role": "proxy_display", "source": self.ui.empShopEdit, "table": "shop", "column": "id", "format": "{name}"}, {"widget": self.ui.empShopProxyCombo, "role": "proxy_edit", "source": self.ui.empShopEdit, "table": "shop", "column": "id", "format": "{name}"}, ) self.setupForm(self._empForm, self.ui.empEditButton, self.ui.empStack, self.ui.empReadPage, self.ui.empWritePage) # Форма "Склад": self._warehouseForm = WarehouseController(self.ui.warehouseShopView, self.ui.warehouseDetailView, self.ui.warehouseAddButton, self.ui.warehouseEditButton, self.ui.warehouseDeleteButton, self.dbase) # Форма "Запчасти машин": self._carDetailForm = CarDetailController(self.ui.carListView_2, self.ui.carDetailListView, self.ui.carDetailAddButton, self.ui.carDetailDeleteButton, self.dbase) # Форма "Заказы": orderForm = ForeignFormController("orders", self.dbase, {"widget": self.ui.orderListView, "role": "view", "format": "#{id}"}, {"widget": self.ui.orderAddButton, "role": "insert"}, {"widget": self.ui.orderDeleteButton, "role": "delete"}, {"widget": self.ui.orderSaveButton, "role": "commit"}, {"widget": self.ui.orderCancelButton, "role": "rollback"}, {"widget": self.ui.orderDateLabel, "role": "display", "column": "regdate"}, {"widget": self.ui.orderPriceLabel, "role": "display", "column": "price"}, {"widget": self.ui.orderPriceLabel_2, "role": "display", "column": "price"}, {"widget": self.ui.orderPriceSpin, "role": "edit", "column": "price"}, {"widget": self.ui.orderClientSpin, "role": "edit", "column": "customer_id"}, {"widget": self.ui.orderShopSpin, "role": "edit", "column": "shop_id"}, {"widget": self.ui.orderEmpSpin, "role": "edit", "column": "employee_id"}, {"widget": self.ui.orderDateEdit, "role": "edit", "column": "regdate"}, {"widget": self.ui.orderClientLabel, "role": "proxy_display", "source": self.ui.orderClientSpin, "table": "customer", "column": "id", "format": "{lastname} {firstname:.1}. {middlename:.1}."}, {"widget": self.ui.orderEmpLabel, "role": "proxy_display", "source": self.ui.orderEmpSpin, "table": "employee", "column": "id", "format": "{lastname} {firstname:.1}. {middlename:.1}."}, {"widget": self.ui.orderShopLabel, "role": "proxy_display", "source": self.ui.orderShopSpin, "table": "shop", "column": "id", "format": "{name}"}, {"widget": self.ui.orderClientCombo, "role": "proxy_edit", "source": self.ui.orderClientSpin, "table": "customer", "column": "id", "format": "{lastname} {firstname:.1}. {middlename:.1}."}, {"widget": self.ui.orderEmpCombo, "role": "proxy_edit", "source": self.ui.orderEmpSpin, "table": "employee", "column": "id", "format": "{lastname} {firstname:.1}. {middlename:.1}."}, {"widget": self.ui.orderShopCombo, "role": "proxy_edit", "source": self.ui.orderShopSpin, "table": "shop", "column": "id", "format": "{name}"}, ) self.setupForm(orderForm, self.ui.orderEditButton, self.ui.orderStack, self.ui.orderReadPage, self.ui.orderWritePage) self._orderForm = OrderController(orderForm, self.ui.orderDetailView, self.ui.orderDetailAddButton, self.ui.orderDetailEditButton, self.ui.orderDetailDeleteButton, self.dbase, self) def setupForm(self, form, editbutton, stack, readpage, writepage): if not form.only_select: form.currentRecordChanged.connect( lambda cur: editbutton.setEnabled(bool(cur))) form.currentRecordChanged.connect( lambda cur: stack.setCurrentWidget(readpage)) form.recordDeleted.connect( lambda: editbutton.setEnabled(False)) form.recordInserted.connect( lambda: stack.setCurrentWidget(writepage)) form.recordCommitted.connect( lambda: stack.setCurrentWidget(readpage)) form.recordRollbacked.connect( lambda: stack.setCurrentWidget(readpage)) editbutton.clicked.connect( lambda: stack.setCurrentWidget(writepage)) if form.recordsCount() > 0 and not form.only_select: editbutton.setEnabled(True) else: editbutton.setEnabled(False) def actionTriggered(self, cur_action): mapping = { self.ui.view_clients: (self.ui.page_clients, self._clientForm), self.ui.view_orders: (self.ui.page_orders, self._orderForm), self.ui.view_employees: (self.ui.page_employees, self._empForm), self.ui.view_shops: (self.ui.page_shops, self._shopForm), self.ui.view_warehouse: (self.ui.page_warehouse, self._warehouseForm), self.ui.view_details: (self.ui.page_details, self._detailForm), self.ui.view_cars: (self.ui.page_cars, self._carForm), self.ui.view_cardetails: (self.ui.page_cardetails, self._carDetailForm) } for action in mapping.keys(): action.setChecked(action == cur_action) page, form = mapping[cur_action] self.ui.stackedWidget.setCurrentWidget(page) if form: form.update()
class MainWindow(QtWidgets.QMainWindow): """Основной класс программы""" def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.data_root = "dtpdata" self.year = "" self.month = "" self.reg_code = "" self.ui.tableWidget.setHorizontalHeaderLabels([ "Дата", "ДТП Район", "Вид ДТП", "Погибло", "Ранено", "Кол-во ТС", "Кол-во уч." ]) # Установить текущий год self.ui.spinBox_year.setValue(datetime.now().year) # Установить список месяцев months = [""] months.extend([str(x) for x in range(1, 13)]) self.ui.comboBox_month.insertItems(0, months) if os.path.isfile(regions_json_filename): self.ui.comboBox_regcode.insertItems(0, self.get_combobox_regions()) else: msg = "Необходимо обновить справочник кодов регионов." self.statusBar().showMessage(msg) self.ui.pushButton.setDisabled(True) self.ui.action_Start.setDisabled(True) # a figure instance to plot on self.figure = plt.figure() # self.figure = matplotlib.pyplot.figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent # self.toolbar = NavigationToolbar(self.canvas, self) # Just some button connected to `plot` method # self.button.clicked.connect(self.plot) self.ui.verticalLayout_graph.addWidget(self.canvas) # self.ui.pushButton.clicked.connect(self.start_calculation) def get_column_data(self, column): data = [] for i in range(self.ui.tableWidget.rowCount()): # print(self.ui.tableWidget.item(i, column).text()) data.append(self.ui.tableWidget.item(i, column).text()) return data def get_dtp_number_by_days(self): dates = self.get_column_data(0) c = collections.Counter() for date in dates: c[date] += 1 mc = sorted(c.most_common(len(set(c)))) date, data = zip(*mc) return date, data @staticmethod def get_month(date): _, month, _ = date.split(".") return month def get_dtp_number_by_months(self): dates = self.get_column_data(0) c = collections.Counter() for date in dates: c[self.get_month(date)] += 1 mc = sorted(c.most_common(len(set(c)))) date, data = zip(*mc) return date, data def get_combobox_regions(self): regions = self.read_regions_from_json() regions_dict = {} for region in regions: regions_dict[int(region['id'])] = region['name'] regions_list = [] for k, v in sorted(regions_dict.items()): regions_list.append(f"{k} - {v}") return regions_list def read_form_data(self): """Считывание данных с формы""" # self.data_root = "dtpdata" # Год try: self.year = str(self.ui.spinBox_year.value()) except ValueError: msg = "Год введён не корректно." self.statusBar().showMessage(msg) # Месяц try: self.month = str(self.ui.comboBox_month.currentText()) except ValueError: msg = "Месяц введён не корректно." self.statusBar().showMessage(msg) # Регион try: self.reg_code = (re.match( "([0-9]+) - (.*)", self.ui.comboBox_regcode.currentText())).group(1).strip() except ValueError: msg = "Регион введён не корректно." self.statusBar().showMessage(msg) def clear_results(self): self.ui.label_dtp_count.setText("0") self.ui.label_dead.setText("0") self.ui.label_inj.setText("0") self.ui.label_proc.setText("0.00%") self.ui.tableWidget.setRowCount(0) # for row in reversed(range(self.ui.tableWidget.rowCount())): # self.ui.tableWidget.removeRow(row) def start_calculation(self): """Основная функция программы""" self.clear_results() # Очистить данные предыдущих вычислений self.read_form_data() # Считать данные с формы if not os.path.exists(self.data_root): os.makedirs(self.data_root) if not os.path.exists(gibdd.log_filename): gibdd.create_log() # получаем месяц (если параметр опущен - все прошедшие месяцы года) if self.month: months = [int(self.month)] else: if self.year == str(datetime.now().year): months = list(range(1, datetime.now().month, 1)) else: months = list(range(1, 13, 1)) # загружаем данные из справочника ОКАТО-кодов регионов и муниципалитетов regions = self.read_regions_from_json() msg = "Идёт обработка данных..." self.ui.statusbar.showMessage(msg) gibdd.get_dtp_info(self.data_root, self.year, months, regions, region_id=self.reg_code) # Тест: читаем сохраненные данные ДТП for region in regions: if self.reg_code != "0" and region["id"] == self.reg_code: region_name = region["name"] break path = os.path.join( self.data_root, self.year, f"{self.reg_code} {region_name} {months[0]}-{months[-1]}.{self.year}.json" ) dtp_data = gibdd.read_dtp_data(path) self.ui.label_dtp_count.setText(dtp_data["dtp_count"]) self.ui.label_dead.setText(dtp_data["pog"]) self.ui.label_inj.setText(dtp_data["ran"]) self.ui.label_proc.setText(dtp_data["proc"]) self.ui.tableWidget.setSortingEnabled(False) for dtp in dtp_data["dtp_data"].values(): row_position = self.ui.tableWidget.rowCount() self.ui.tableWidget.insertRow(row_position) # insert new row self.ui.tableWidget.setItem( row_position, 0, QtWidgets.QTableWidgetItem(dtp["date"])) self.ui.tableWidget.setItem( row_position, 1, QtWidgets.QTableWidgetItem(dtp["District"])) self.ui.tableWidget.setItem( row_position, 2, QtWidgets.QTableWidgetItem(str(dtp["DTP_V"]))) self.ui.tableWidget.setItem( row_position, 3, QtWidgets.QTableWidgetItem(str(dtp["POG"]))) self.ui.tableWidget.setItem( row_position, 4, QtWidgets.QTableWidgetItem(str(dtp["RAN"]))) self.ui.tableWidget.setItem( row_position, 5, QtWidgets.QTableWidgetItem(str(dtp["K_TS"]))) self.ui.tableWidget.setItem( row_position, 6, QtWidgets.QTableWidgetItem(str(dtp["K_UCH"]))) self.ui.tableWidget.setSortingEnabled(True) self.ui.tableWidget.sortByColumn(0, QtCore.Qt.AscendingOrder) self.ui.tableWidget.resizeColumnsToContents() self.ui.groupBox_2.setTitle(f"Статистика по региону: {region_name}") if self.month: date, data = self.get_dtp_number_by_days() title = "Статистика ДТП по дням" xlabel = "Дни" ylabel = "Количество ДТП" date = [x.split(".")[2].lstrip("0") for x in date] else: date, data = self.get_dtp_number_by_months() title = "Статистика ДТП по месяцам" xlabel = "Месяцы" ylabel = "Количество ДТП" label = [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ] date = label[:len(date)] self.plot(date, data, title, xlabel, ylabel) msg = "Обработка данных закончена." self.ui.statusbar.showMessage(msg) def plot(self, date, data, title="", xlabel="", ylabel=""): """plot data""" self.figure.clear() # create an axis ax = self.figure.add_subplot(111) # plot data ax.plot(data, 'or-') ax.set_xticks(range(len(data))) ax.set_xticklabels(date) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) # refresh canvas self.canvas.draw() @staticmethod def read_regions_from_json(): """Загрузка данных из справочника ОКАТО-кодов регионов и муниципалитетов""" with codecs.open(regions_json_filename, "r", "utf-8") as f: regions = json.loads(json.loads(json.dumps(f.read()))) return regions @QtCore.pyqtSlot() def update_codes(self): log_text = "Обновление справочника кодов регионов..." self.ui.statusbar.showMessage(log_text) gibdd.write_log(log_text) gibdd.save_code_dictionary(regions_json_filename) self.ui.comboBox_regcode.insertItems(0, self.get_combobox_regions()) self.ui.pushButton.setDisabled(False) self.ui.action_Start.setDisabled(False) log_text = "Обновление справочника завершено" self.ui.statusbar.showMessage(log_text) gibdd.write_log(log_text) @QtCore.pyqtSlot() def show_about_window(self): """Отображение окна сведений о программе""" self.aboutwindow = about_window.AboutWindow() self.aboutwindow.show() @QtCore.pyqtSlot() def show_aboutqt_window(self): """Отображение окна сведений о библиотеке Qt""" return QtWidgets.QMessageBox.aboutQt(self)
def __init__(self, dbase, parent = None): super(MainWindow, self).__init__(parent) self.dbase = dbase self.ui = Ui_MainWindow() self.ui.setupUi(self) self.configUI()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self)