def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) self.model = QStandardItemModel() self.clear_model() self.ui.treeView.setModel(self.model) self.ui.treeView.clicked.connect(lambda: self.show_info_in_status_bar) self.ui.treeView.doubleClicked.connect(lambda: self.show_in_explorer()) self.ui.button_select_dir.clicked.connect(self.select_dir) self.ui.action_go.triggered.connect(self.fill) self.ui.action_show_in_explorer.triggered.connect( lambda: self.show_in_explorer()) self.ui.action_apply_filter.triggered.connect(self.slot_remove_dirs) self.ui.label_root_dir.setText(self.ui.line_edit_dir_path.text()) self.ui.action_apply_filter.setEnabled(False) self.read_settings()
class main_window(QMainWindow): def __init__(self, parent=None): #super(main_window, self.__init__(parent)) QWidget.__init__(self, parent) #Importing UI self.ui = Ui_MainWindow() self.ui.setupUi(self) #Setting up Initials # print("Constructor Called") self.setFixedSize(1024, 640) self.ui.pushButton.setFocusPolicy(Qt.NoFocus) self.move(QApplication.desktop().screen().rect().center() - self.rect().center()) self.setWindowTitle("NIDS") self.connect(self.ui.pushButton, SIGNAL("clicked()"), lambda: self.clicked()) # self.ui.pushButton.setChecked(True) # self.ui.pushButton_3.setChecked(True) # self.ui.pushButton_2.setChecked(False) def init(self): print("Hello") def clicked(self): print("Clicked") file_win = file_browser() self.close() file_win.exec()
def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # try connection self.settings = QSettings('elektroNIK', 'P3DA') self.con = Connection(baud=38400) self.devs = self.detectdevices() if self.devs: self.con.createconnection(self.devs[0]) msg = 'Connected to {}'.format( self.con.dev) if self.con.con else 'No serial adapter found!' self.ui.statusbar.showMessage(msg) # corrections self.gamma = self.ui.doubleSpinBox_gamma.value() r = self.ui.horizontalSlider_wb_r.value() g = self.ui.horizontalSlider_wb_g.value() b = self.ui.horizontalSlider_wb_b.value() self.wb = {'R': r, 'G': g, 'B': b} # initializing classes self.tablight = TabLight(self) self.tabilumination = TabIlumination(self) self.tabsound = TabSound(self) self.tabextbacklight = TabExtBacklight(self) self.tabsetup = TabSetup(self) # restoring self.restoresettings() self.tablight.updatepalette() # init self.ui.tabWidget.currentChanged.connect(self.updatetab) self.updatetab(self.ui.tabWidget.currentIndex())
def __init__(self): QtWidgets.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.sports = [] self.ui.add_btn.clicked.connect(self._newForm) self.ui.item1 = QtWidgets.QListWidgetItem("Events") self.ui.main_list.addItem(self.ui.item1) self.ui.item2 = QtWidgets.QListWidgetItem("Results") self.ui.main_list.addItem(self.ui.item2) self.ui.main_list.itemClicked.connect(self._mainClicked) self.manager = QtNetwork.QNetworkAccessManager() self.sport_req = QtNetwork.QNetworkRequest(QtCore.QUrl("API URL")) self.sport_reply = self.manager.get(self.sport_req) self.sport_reply.finished.connect(self._sportsReply) self.ui.sport_combo.activated.connect(self._mainReq) self.ui.subClass_list.itemClicked.connect(self._loadForm) self.sport_dic = {} self.loaded = [] self.resizeTimer = QtCore.QTimer() self.resizeTimer.setSingleShot(True) self.resizeTimer.timeout.connect(self.tryResize)
def __init__(self, parent=None): """Constructor""" super().__init__(parent) self.__ui = Ui_MainWindow() self.__ui.setupUi(self) self.__ui.tabWidget.setTabsClosable(True) self.__ui.tabWidget.setMovable(True)
class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.btnFileBrowser, QtCore.SIGNAL("clicked()"), self.selectFile) QtCore.QObject.connect(self.ui.btnDirBrowser, QtCore.SIGNAL("clicked()"), self.selectDir) QtCore.QObject.connect(self.ui.btnFilterFile, QtCore.SIGNAL("clicked()"), self.playFile) QtCore.QObject.connect(self, QtCore.SIGNAL("triggered()"), self.closeWindow) def selectFile(self): self.input_file = QtGui.QFileDialog.getOpenFileName() self.ui.txtFilename.setText(self.input_file) def selectDir(self): self.output_dir = QtGui.QFileDialog.getExistingDirectory(self, 'Select Output Directory') self.ui.txtOutputDir.setText(self.output_dir) def closeWindow(self): try: tb.stop() tb.wait() except NameError: pass def playFile(self): if os.path.isfile(self.input_file) is not True: print("Path is not a file!") return tb = top_block() tb.set_input_file(self.input_file) tb.setup_blocks() tb.start() tb.wait()
def __init__(self, data_singleton, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.data_singleton = data_singleton self.mUndoStackGroup = QUndoGroup(self) self.mUndoStackGroup.canUndoChanged.connect(self.can_undo_changed) self.mUndoStackGroup.canRedoChanged.connect(self.can_redo_changed) self.can_undo_changed(self.mUndoStackGroup.canUndo()) self.can_redo_changed(self.mUndoStackGroup.canRedo()) self.ui.actionUndo.triggered.connect(self.mUndoStackGroup.undo) self.ui.actionRedo.triggered.connect(self.mUndoStackGroup.redo) self.ui.actionSave.triggered.connect(self.save) self.ui.actionSaveAs.triggered.connect(self.save_as) self.ui.actionNew.triggered.connect(self.new_tab) self.ui.actionOpen.triggered.connect(self.open) self.ui.actionSettings.triggered.connect(self.show_settings) self.ui.actionPlugin_Manager.triggered.connect(self.show_plugin_manager) self.ui.tabWidget.currentChanged.connect(self.activate_tab) self.ui.tabWidget.currentChanged.connect(self.send_tab_changed) self.ui.tabWidget.tabCloseRequested.connect(self.close_tab) self.update_states()
def __init__(self): QDialog.__init__( self ) # Constructs a dialog with parent parent. self being ImageDailog # Set up the UI from Designer: self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.graphicsView.DontAdjustForAntialiasing #seems to help fix artifacts left by mouse track markers #make a scene: self.scene = QtGui.QGraphicsScene() #set it to show in the graphicsview window: self.ui.graphicsView.setScene(self.scene) self.items = [QtGui.QGraphicsTextItem(), QtGui.QGraphicsRectItem() ] #for squares and indexes that follow mouse self.ui.graphicsView.viewport().installEventFilter( self) #for mouse functions #Setup IO table on right self.ui.tableWidget.resizeColumnToContents(0) self.ui.tableWidget.resizeColumnToContents(1) self.ui.tableWidget.setColumnWidth(2, 50) self.ui.tableWidget.setColumnWidth(3, 40) #setup datagrid and elements: self.Tools = elementList(elementStruct) self.setupDataGrid() #set up rung variables: self.signalConnections() #default: self.currentHW = "Waltech" self.projectName = None self.currentFileDir = None
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.btnFileBrowser, QtCore.SIGNAL("clicked()"), self.selectFile) QtCore.QObject.connect(self.ui.btnDirBrowser, QtCore.SIGNAL("clicked()"), self.selectDir) QtCore.QObject.connect(self.ui.btnFilterFile, QtCore.SIGNAL("clicked()"), self.playFile) QtCore.QObject.connect(self, QtCore.SIGNAL("triggered()"), self.closeWindow)
def __init__(self): super(MainWindow, self).__init__() self.database = products.database self.ui = Ui_MainWindow() self.ui.setupUi(self) self.initSignals() self.key_buf = [] self.ui.codeBox.setFocus() self.total_price = 0
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) centralWidget = QWidget() self.setCentralWidget(centralWidget) gridLayout = QGridLayout(centralWidget) gridLayout.addWidget(self.ui.label, 0, 0, alignment=Qt.AlignCenter) gridLayout.addWidget(self.ui.pushButton, 1, 0)
def __init__(self, w): Ui_MainWindow.__init__(self) self.setupUi(w) MainWindow.file_loaded_model = joblib.load( 'modelfile.pkl') # input your model file name if MainWindow.file_loaded_model == None: print("Model load fail!") self.pushButton.clicked.connect(self.predictStart)
def __init__(self, parent=None): super().__init__(parent) self.__ui = Ui_MainWindow() self.__ui.setupUi(self) self.setWindowTitle('QDialog Test') self.__ui.msgWarning.clicked.connect(self.show_warning_msgbox) self.__ui.msgCritical.clicked.connect(self.show_critical_msgbox) self.__ui.msgQuestion.clicked.connect(self.show_question_msgbox) self.__ui.msgInformation.clicked.connect(self.show_information_msgbox) self.__ui.msgNoIcon.clicked.connect(self.show_regular_msgbox)
class MainWindow(QMainWindow): def __init__(self, parent=None): """Constructor""" super().__init__(parent) self.__ui = Ui_MainWindow() self.__ui.setupUi(self) @property def title_widget(self): """Expose the titlebar widget so it can be styled""" return self.__ui.title_widget
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui_controller = Ui_MainWindow() self.ui_controller.setupUi(self) self.connect() self.ui_controller.matplotlibWidget.connect() self.init_style_menu() self.init_indicator_menu() self.init_strategy_panel() self.ui_controller.dateStartEdit.setDateTime(datetime(1990,1,1)) self.ui_controller.dateEndEdit.setDateTime(datetime.now()) self.df = None
class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.database = products.database self.ui = Ui_MainWindow() self.ui.setupUi(self) self.initSignals() self.key_buf = [] self.ui.codeBox.setFocus() self.total_price = 0 def initSignals(self): self.ui.quitButton.clicked.connect(self.close) self.ui.codeBox.returnPressed.connect(self.search_add_prod) self.ui.newButton.clicked.connect(self.new_list) def search_add_prod(self): search_code = str(self.ui.codeBox.text()) self.ui.codeBox.setText("") print("Searching and adding code %s" % search_code) if self.database.has_key(search_code): price = self.database[search_code]["price"] human_name = self.database[search_code]["name"] if self.database[search_code].has_key("picture"): pixmap = QtGui.QPixmap() pixmap.load("products/" + self.database[search_code]["picture"]) pixmap = pixmap.scaledToWidth(self.ui.imgLabel.size().width()) self.ui.imgLabel.setPixmap(pixmap) else: human_name = search_code price = int(random.random() * 20) self.add_to_list(human_name, price) self.update_total() def add_to_list(self, product_name, price): self.ui.listProducts.addItem(product_name) self.ui.listPrices.addItem(str(price)) self.ui.listProducts.scrollToBottom() self.ui.listPrices.scrollToBottom() self.total_price += price def update_total(self): self.ui.totalBox.setText("%d" % self.total_price) def new_list(self): self.total_price = 0 self.ui.listProducts.clear() self.ui.listPrices.clear() self.update_total() self.ui.codeBox.setFocus()
def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Preparation description tag stackoverflow') # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) self.ui.action_save.triggered.connect(self.save) self.ui.action_save_all.triggered.connect(self.save_all) self.ui.ref_guide.textChanged.connect(self.ref_guide_text_changed) self.ui.description.textChanged.connect(self.description_text_changed) # TODO: при изменении тега менять и окно с его содержимым -- plain_text_edit_tag_info # TODO: заменить модель комбобокса нашим списком self.tags_dict = dict() self.modified_tags = list() # Словарь, ключом, которого id тега, а значением -- элемент списка self.tag_id_item_dict = dict() self.tag_list_model = QStandardItemModel() self.modified_tags_model = QStandardItemModel() self.ui.list_view_tag_list.setModel(self.tag_list_model) self.ui.list_view_modified_tags.setModel(self.modified_tags_model) self.ui.list_view_tag_list.clicked.connect( self.list_view_tag_list_clicked) self.ui.list_view_modified_tags.clicked.connect( self.list_view_modified_tags_clicked) self.ui.check_box_only_empty.clicked.connect( self.filter_list_tag_only_empty) # TODO: добавить кнопку для постинга изменений тега. Перед постингом нужно авторизоваться # получить текущее состояние и сравнить с новым -- может кто-то что-то добавил и # если оно было лучше, того, что я хочу добавить, получится не хорошо # TODO: кнопка сохранения всех измененных тегов self.update_states()
class MainWindow(QMainWindow): def __init__(self, parent=None): """Constructor""" super().__init__(parent) self.__ui = Ui_MainWindow() self.__ui.setupUi(self) self.__ui.tabWidget.setTabsClosable(True) self.__ui.tabWidget.setMovable(True) @property def tab_widget(self): """Expose the titlebar tab widget so it can be styled""" return self.__ui.tabWidget
def __init__(self, parent=None): #super(main_window, self.__init__(parent)) QWidget.__init__(self, parent) #Importing UI self.ui = Ui_MainWindow() self.ui.setupUi(self) #Setting up Initials # print("Constructor Called") self.setFixedSize(1024, 640) self.ui.pushButton.setFocusPolicy(Qt.NoFocus) self.move(QApplication.desktop().screen().rect().center() - self.rect().center()) self.setWindowTitle("NIDS") self.connect(self.ui.pushButton, SIGNAL("clicked()"), lambda: self.clicked())
class MyWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) centralWidget = QWidget() self.setCentralWidget(centralWidget) gridLayout = QGridLayout(centralWidget) gridLayout.addWidget(self.ui.label, 0, 0, alignment=Qt.AlignCenter) gridLayout.addWidget(self.ui.pushButton, 1, 0) def dialogbox(self): self.hide() self.myDialog = MyDialog() self.myDialog.show()
def __init__(self): QDialog.__init__(self)# Constructs a dialog with parent parent. self being ImageDailog # Set up the UI from Designer: self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.graphicsView.DontAdjustForAntialiasing #seems to help fix artifacts left by mouse track markers #make a scene: self.scene = QtGui.QGraphicsScene() #set it to show in the graphicsview window: self.ui.graphicsView.setScene(self.scene) self.items=[QtGui.QGraphicsTextItem(),QtGui.QGraphicsRectItem()]#for squares and indexes that follow mouse self.ui.graphicsView.viewport().installEventFilter(self)#for mouse functions #Setup IO table on right self.ui.tableWidget.resizeColumnToContents(0) self.ui.tableWidget.resizeColumnToContents(1) self.ui.tableWidget.setColumnWidth(2, 50) self.ui.tableWidget.setColumnWidth(3, 40) #setup datagrid and elements: self.Tools = elementList(elementStruct) self.setupDataGrid()#set up rung variables: self.signalConnections() #default: self.currentHW = "Waltech" self.ui.actionPWM.setEnabled(False) self.ui.actionADC.setEnabled(False) f=open(self.__class__.tempName, 'w') f.write("") f.close()
def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.docsModel = QSqlTableModel() # self.docsModel = QSqlRelationalTableModel() self.docsModel.setTable('DOCUMENTS') # self.docsModel.setRelation(2, QSqlRelation('THEMES', 'ID', 'NAME')) self.docsModel.setEditStrategy(QSqlTableModel.OnManualSubmit) self.docsModel.select() self.docsModel.setHeaderData(1, Qt.Horizontal, "Путь к файлу") self.docsModel.setHeaderData(2, Qt.Horizontal, "Тема") self.ui.docsView.setModel(self.docsModel) # self.ui.docsView.setItemDelegate(QSqlRelationalDelegate(self.ui.docsView)) self.ui.docsView.horizontalHeader().setStretchLastSection(True) self.updateThemes() self.ui.themes.header().setStretchLastSection(True) self.ui.themes.setHeaderHidden(True) self.ui.themes.itemSelectionChanged.connect(self.themes_selectionChanged) self.ui.themes.setCurrentItem(self.root_theme) self.ui.actionQuit.triggered.connect(self.close) self.ui.actionAdd.triggered.connect(self.add) self.ui.actionDelete.triggered.connect(self.delete) self.read_settings()
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) self.model = QStandardItemModel() self.clear_model() self.ui.treeView.setModel(self.model) self.ui.treeView.clicked.connect(self.show_info_in_status_bar) self.ui.treeView.doubleClicked.connect(self.show_in_explorer) self.ui.button_select_dir.clicked.connect(self.select_dir) self.ui.action_go.triggered.connect(self.fill) self.ui.action_show_in_explorer.triggered.connect(self.show_in_explorer) self.ui.action_apply_filter.triggered.connect(self.slot_remove_dirs) self.ui.label_root_dir.setText(self.ui.line_edit_dir_path.text()) self.ui.action_apply_filter.setEnabled(False) self.read_settings()
def setup_ui(self): self.ui = Ui_MainWindow() self.ui.setupUi(self) # auto complete self.auto_com_init() self.ui.ol_cb.setChecked(False) darkula = QPalette() # theme darkula.setColor(QPalette.Background, QColor('#300A24')) darkula.setColor(QPalette.Base, QColor('#300A24')) self.ui.textBrowser.setPalette(darkula) # status bar self.ui.statusbar.showMessage('@2016 Chestnut Studio') # signal slot self.ui.lineEdit.returnPressed.connect(self.search_bt_clicked) self.ui.search_b.clicked.connect(self.search_bt_clicked) self.ui.detail_rb.clicked.connect(self.detail_rb_clicked) self.ui.intro_rb.clicked.connect(self.intro_rb_clicked)
def __init__(self): QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.global_start_time = time.strftime('%Y%m%d_%H%M') self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("OptoWorld") self.start_mqtt() self.ui.button_lightswitch.clicked.connect(self.button_clicked) self.ui.actionedit_light_profile.triggered.connect( self.edit_light_profile) self.ui.actionshow_live_graphs.triggered.connect( self.toggle_live_graphs) self.make_graphs() if not os.path.exists(f"{HOME}/optoworld_logs"): os.mkdir(f"{HOME}/optoworld_logs")
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.de_start.setDate(QtCore.QDate().currentDate()) self.ui.de_stop.setDate(QtCore.QDate().currentDate()) self.ui.cb_whocalled.setVisible(False) self.ui.btn_report.setVisible(False) self.ui.tab_2.setEnabled(False) self.mango = MangoOffice() self.dframe = PandasDataFrame() # connections self.ui.btn_connection.clicked.connect(self.connection) self.ui.btn_download.clicked.connect(self.feel_table) self.ui.cb_whocalledtype.currentIndexChanged.connect( self.who_called_type_change) self.ui.cb_ats.currentIndexChanged.connect(self.who_called_type_change) self.ui.btn_clear.clicked.connect(self.btn_clear_click) self.ui.de_start.dateChanged.connect(self.de_start_date_change) self.ui.de_stop.dateChanged.connect(self.de_stop_date_change) self.ui.btn_report.clicked.connect(self.export_to_xls)
class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.__ui = Ui_MainWindow() self.__ui.setupUi(self) self.setWindowTitle('QDialog Test') self.__ui.msgWarning.clicked.connect(self.show_warning_msgbox) self.__ui.msgCritical.clicked.connect(self.show_critical_msgbox) self.__ui.msgQuestion.clicked.connect(self.show_question_msgbox) self.__ui.msgInformation.clicked.connect(self.show_information_msgbox) self.__ui.msgNoIcon.clicked.connect(self.show_regular_msgbox) def show_warning_msgbox(self): self.show_msg_box(QMessageBox.Warning) def show_critical_msgbox(self): self.show_msg_box(QMessageBox.Critical) def show_question_msgbox(self): self.show_msg_box(QMessageBox.Question) def show_information_msgbox(self): self.show_msg_box(QMessageBox.Information) def show_regular_msgbox(self): self.show_msg_box(QMessageBox.NoIcon) def show_msg_box(self, icon): msg = QtModernRedux.wrap( QMessageBox(self), parent=self, window_buttons_position=QtModernRedux.WINDOW_BUTTONS_RIGHT) msg.setIcon(icon) msg.setText("This is a message box") msg.setInformativeText("This is additional information") msg.setWindowTitle("MessageBox demo") msg.setDetailedText("The details are as follows:") retval = msg.exec_() print("value of pressed message box button:", retval)
def __init__(self): super(MyWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.init_logger() self.init_project_table() self.settings() self.logger.info("Program started") self.tia = TiaHandler() # self.templater = Templater() # self.templater.new_template('Test_temp') self.main_slots() # Подключаем слоты self.model = QtGui.QStandardItemModel() self.ui.project_tree.setModel(self.model) self.ui.project_tree.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.model.setHorizontalHeaderLabels(['Дерево проекта']) self.ui.project_tree.setModel(self.model) self.ui.new_folder_action.setEnabled(False) self.ui.sync_action.setEnabled(False) self.ui.import_action.setEnabled(False) self.ui.export_action.setEnabled(False)
class MyForm(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) def openFileNamesDialog(self) -> str: options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog file_path, _ = QFileDialog.getOpenFileName( self, "Select graph to load", "", "Graph Modelling Language (*.gml)", options=options) return file_path def showErrorDialog(self, errorMessage): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText(errorMessage) msg.setWindowTitle("Error") msg.exec_()
class MainWindow(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton_translate.clicked.connect(self.check) def check(self): dict_obj = dict_lib.yandex_dict(r'') text_in = str(unicode(self.ui.lineEdit_input.text()).encode('utf-8')) words = dict_obj.check_text( text_in, str(self.ui.comboBox_from.currentText()) + '-' + str(self.ui.comboBox_to.currentText())) self.ui.textEdit_main.clear() result_text = '' for word in words: result_text = result_text + word + '<br>' result_text = result_text + '<br>' self.ui.textEdit_main.insertHtml(result_text) # http://stackoverflow.com/questions/5506781/pyqt4-application-on-windows-is-crashing-on-exit def closeEvent(self, event): sys.exit(0)
class LauncherWindow(QMainWindow): def __init__(self, parent=None): super(LauncherWindow, self).__init__(parent) self.__setupUI() self.setWindowTitle("launcher") for paneclass in launcherPanes.pluginClassList: pane = paneclass(self) paneName, paneIcon = pane.paneHeader() newheader = QRadioButton(self) newheader.setText(paneName) newheader.setIcon(QIcon(paneIcon)) newheader.setIconSize(QSize(32, 32)) newheader.toggled.connect(pane.setActive) self.ui.buttonsLayout.addWidget(newheader) self.ui.horizontalLayout.addWidget(pane) pane.hide() if (self.ui.buttonsLayout.count() == 1): newheader.setChecked(True) def __setupUI(self): self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setStyleSheet('')
def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('dev_window') # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) # Выполнение кода в окне "Выполнение скрипта" self.ui.button_exec.clicked.connect(self.exec_script) try: self.code_editor = create_code_editor() self.ui.container_code_editor.setWidget(self.code_editor) except Exception as e: logger.warn(e) self.code_editor = QPlainTextEdit() self.ui.container_code_editor.setWidget(self.code_editor) self.write_code_to_editor() self.timer_save_code = QTimer() self.timer_save_code.setSingleShot(True) self.timer_save_code.setInterval(300) self.timer_save_code.timeout.connect(self.save_code_from_editor) self.code_editor.textChanged.connect(self.timer_save_code.start) OUTPUT_LOGGER_STDOUT.emit_write.connect(self.write_output) OUTPUT_LOGGER_STDERR.emit_write.connect(self.write_output)
def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('vk_chat_bot') # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) # Выполнение кода в окне "Выполнение скрипта" self.ui.button_exec.clicked.connect(lambda x=None: exec(self.ui.code.toPlainText())) # # # # Чтобы не было проблем запуска компов с прокси: QNetworkProxyFactory.setUseSystemConfiguration(True) QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) # TODO: оптимищация # QWebSettings::PrintElementBackgrounds # QWebSettings.globalSettings().setAttribute(QWebSettings.AutoLoadImages, False) self.web_view = QWebView() self.setCentralWidget(self.web_view) self.web_view.load('http://www.boibot.com/en/') self.wait_loading()
def __init__(self, app_name): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # canvas main window self.setWindowIcon(QIcon(cfg.ICONS.LOGO)) self.canvas = Canvas() self.canvas.image = QImage(cfg.ICONS.BACKGROUND) self.canvas.zoomRequest.connect(self.zoomRequest) scroll = QScrollArea() scroll.setWidget(self.canvas) scroll.setWidgetResizable(True) self.scrollBars = { Qt.Vertical: scroll.verticalScrollBar(), Qt.Horizontal: scroll.horizontalScrollBar() } self.canvas.scrollRequest.connect(self.scrollRequest) self.ui.main_video_layout.addWidget(scroll) self.zoomWidget = ZoomWidget() zoom = QWidgetAction(self) zoom.setDefaultWidget(self.zoomWidget) self.zoomWidget.setWhatsThis( u"Zoom in or out of the image. Also accessible with" " %s and %s from the canvas." % (fmtShortcut("Ctrl+[-+]"), fmtShortcut("Ctrl+Wheel"))) self.zoomWidget.setEnabled(False) self.scalers = { self.FIT_WINDOW: self.scaleFitWindow, self.FIT_WIDTH: self.scaleFitWidth, # Set to one to scale to 100% when loading files. self.MANUAL_ZOOM: lambda: 1, } self.zoomMode = self.FIT_WINDOW self.canvas.setEnabled(True) self.adjustScale(initial=True) self.paintCanvas() self.zoomWidget.valueChanged.connect(self.paintCanvas) self.resized.connect(self.adjustScale) # camera self.camera_device = CameraDevice(video_path=cfg.GLOBAL.VIDEO1) self.camera_device.newFrame.connect(self.onNewImage) self.camera_device.video_time_out.connect(self.clear) # top button functions self.ui.thread1_bn.clicked.connect(self.start_camera) self.ui.thread2_bn.clicked.connect(self.start_video1) self.ui.thread3_bn.clicked.connect(self.start_video2) self.ui.thread4_bn.clicked.connect(self.start_pic) self.ui.thread5_bn.clicked.connect(self.load_video) # left button functions self.ui.play_bn.clicked.connect(self.start_cap) self.ui.pause_bn.clicked.connect(self.stop_cap) self.ui.record_bn.clicked.connect(self.save_video) self.ui.exit_bn.clicked.connect(self.close) # right button functions self.ui.model1_bn.clicked.connect(self.apply_model1) self.ui.model2_bn.clicked.connect(self.apply_model2) self.ui.model3_bn.clicked.connect(self.apply_model3) self.ui.model4_bn.clicked.connect(self.apply_model4) self.ui.model5_bn.clicked.connect(self.apply_model5) # top button functions self.ui.thread1_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT1)) self.ui.thread1_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) self.ui.thread2_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT2)) self.ui.thread2_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) self.ui.thread3_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT3)) self.ui.thread3_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) self.ui.thread4_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT4)) self.ui.thread4_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) self.ui.thread5_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT5)) self.ui.thread5_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) # left button functions self.ui.play_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP1)) self.ui.play_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.pause_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP2)) self.ui.pause_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.record_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP3)) self.ui.record_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.empty_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP4)) self.ui.empty_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.setting_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP5)) self.ui.setting_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.exit_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP6)) self.ui.exit_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) # right button icons self.ui.model1_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP1)) self.ui.model1_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) self.ui.model2_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP2)) self.ui.model2_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) self.ui.model3_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP3)) self.ui.model3_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) self.ui.model4_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP4)) self.ui.model4_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) self.ui.model5_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP5)) self.ui.model5_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) # task special param self.image_render = GetImage() self.flag_savevideo = False self.info_header = u"Hello from PriVision!\n " self.shown_info(self.info_header) self.allframes = [] self.video_writer = None self.savevideo_counting = 0 self.savevideo_max = cfg.GLOBAL.SAVE_VIDEO_MAX_SECOND
class MainWindow(QMainWindow): FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = range(3) resized = QtCore.pyqtSignal() def __init__(self, app_name): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # canvas main window self.setWindowIcon(QIcon(cfg.ICONS.LOGO)) self.canvas = Canvas() self.canvas.image = QImage(cfg.ICONS.BACKGROUND) self.canvas.zoomRequest.connect(self.zoomRequest) scroll = QScrollArea() scroll.setWidget(self.canvas) scroll.setWidgetResizable(True) self.scrollBars = { Qt.Vertical: scroll.verticalScrollBar(), Qt.Horizontal: scroll.horizontalScrollBar() } self.canvas.scrollRequest.connect(self.scrollRequest) self.ui.main_video_layout.addWidget(scroll) self.zoomWidget = ZoomWidget() zoom = QWidgetAction(self) zoom.setDefaultWidget(self.zoomWidget) self.zoomWidget.setWhatsThis( u"Zoom in or out of the image. Also accessible with" " %s and %s from the canvas." % (fmtShortcut("Ctrl+[-+]"), fmtShortcut("Ctrl+Wheel"))) self.zoomWidget.setEnabled(False) self.scalers = { self.FIT_WINDOW: self.scaleFitWindow, self.FIT_WIDTH: self.scaleFitWidth, # Set to one to scale to 100% when loading files. self.MANUAL_ZOOM: lambda: 1, } self.zoomMode = self.FIT_WINDOW self.canvas.setEnabled(True) self.adjustScale(initial=True) self.paintCanvas() self.zoomWidget.valueChanged.connect(self.paintCanvas) self.resized.connect(self.adjustScale) # camera self.camera_device = CameraDevice(video_path=cfg.GLOBAL.VIDEO1) self.camera_device.newFrame.connect(self.onNewImage) self.camera_device.video_time_out.connect(self.clear) # top button functions self.ui.thread1_bn.clicked.connect(self.start_camera) self.ui.thread2_bn.clicked.connect(self.start_video1) self.ui.thread3_bn.clicked.connect(self.start_video2) self.ui.thread4_bn.clicked.connect(self.start_pic) self.ui.thread5_bn.clicked.connect(self.load_video) # left button functions self.ui.play_bn.clicked.connect(self.start_cap) self.ui.pause_bn.clicked.connect(self.stop_cap) self.ui.record_bn.clicked.connect(self.save_video) self.ui.exit_bn.clicked.connect(self.close) # right button functions self.ui.model1_bn.clicked.connect(self.apply_model1) self.ui.model2_bn.clicked.connect(self.apply_model2) self.ui.model3_bn.clicked.connect(self.apply_model3) self.ui.model4_bn.clicked.connect(self.apply_model4) self.ui.model5_bn.clicked.connect(self.apply_model5) # top button functions self.ui.thread1_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT1)) self.ui.thread1_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) self.ui.thread2_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT2)) self.ui.thread2_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) self.ui.thread3_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT3)) self.ui.thread3_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) self.ui.thread4_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT4)) self.ui.thread4_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) self.ui.thread5_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT5)) self.ui.thread5_bn.setIconSize( QSize(cfg.ICONS.TOP_SIZE[0], cfg.ICONS.TOP_SIZE[1])) # left button functions self.ui.play_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP1)) self.ui.play_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.pause_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP2)) self.ui.pause_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.record_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP3)) self.ui.record_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.empty_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP4)) self.ui.empty_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.setting_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP5)) self.ui.setting_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) self.ui.exit_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP6)) self.ui.exit_bn.setIconSize( QSize(cfg.ICONS.LEFT_SIZE[0], cfg.ICONS.LEFT_SIZE[1])) # right button icons self.ui.model1_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP1)) self.ui.model1_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) self.ui.model2_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP2)) self.ui.model2_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) self.ui.model3_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP3)) self.ui.model3_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) self.ui.model4_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP4)) self.ui.model4_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) self.ui.model5_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP5)) self.ui.model5_bn.setIconSize( QSize(cfg.ICONS.RIGHT_SIZE[0], cfg.ICONS.RIGHT_SIZE[1])) # task special param self.image_render = GetImage() self.flag_savevideo = False self.info_header = u"Hello from PriVision!\n " self.shown_info(self.info_header) self.allframes = [] self.video_writer = None self.savevideo_counting = 0 self.savevideo_max = cfg.GLOBAL.SAVE_VIDEO_MAX_SECOND def resizeEvent(self, event): self.resized.emit() return super(MainWindow, self).resizeEvent(event) def update_image(self): pass def zoomRequest(self, delta): units = delta / (8 * 15) scale = 10 self.addZoom(scale * units) def scrollRequest(self, delta, orientation): units = -delta / (8 * 15) bar = self.scrollBars[orientation] bar.setValue(bar.value() + bar.singleStep() * units) def setZoom(self, value): self.actions.fitWidth.setChecked(False) self.actions.fitWindow.setChecked(False) self.zoomMode = self.MANUAL_ZOOM self.zoomWidget.setValue(value) def addZoom(self, increment=10): self.setZoom(self.zoomWidget.value() + increment) def setFitWindow(self, value=True): self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM self.adjustScale() def setFitWidth(self, value=True): if value: self.actions.fitWindow.setChecked(False) self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM self.adjustScale() def adjustScale(self, initial=False): value = self.scalers[self.FIT_WINDOW if initial else self.zoomMode]() self.zoomWidget.setValue(int(100 * value)) def scaleFitWindow(self): """Figure out the size of the pixmap in order to fit the main widget.""" e = 2.0 # So that no scrollbars are generated. w1 = self.width() * 0.65 - e h1 = self.height() * 0.65 - e a1 = w1 / h1 # Calculate a new scale value based on the pixmap's aspect ratio. w2 = self.canvas.image.width() - 0.0 h2 = self.canvas.image.height() - 0.0 a2 = w2 / h2 return w1 / w2 if a2 >= a1 else h1 / h2 def scaleFitWidth(self): # The epsilon does not seem to work too well here. w = self.centralWidget().width() / 5 * 3 - 2.0 return w / self.canvas.pixmap.width() def paintCanvas(self): self.canvas.scale = 0.01 * self.zoomWidget.value() # self.canvas.scale = 0.5 self.canvas.adjustSize() self.canvas.update() def start_cap(self): # self.ui.play_bn.setIcon(QIcon("./files/icons/icon-left/play-color.png")) self.ui.pause_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP2)) self.camera_device.paused = False def stop_cap(self): self.ui.pause_bn.setIcon( QIcon(cfg.ICONS.LEFT_TOP2.replace('bright', 'color'))) self.camera_device.paused = True def save_video(self): if not self.flag_savevideo: self.flag_savevideo = True self.savevideo_counting = 0 video_name = datetime.datetime.now().strftime('%Y%m%d%H%M%S') fourcc = cv2.VideoWriter_fourcc(*'MJPG') self.video_writer = cv2.VideoWriter( '{}/{}_save.avi'.format(cfg.GLOBAL.SAVE_VIDEO_PATH, video_name), fourcc, cfg.GLOBAL.SAVE_VIDEO_FPS, tuple(cfg.GLOBAL.SAVE_VIDEO_SIZE)) self.ui.record_bn.setIcon( QIcon(cfg.ICONS.LEFT_TOP3.replace('bright', 'color'))) else: self.video_writer.release() self.savevideo_counting = 0 self.flag_savevideo = False self.video_writer = None self.ui.record_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP3)) pass def clear(self): self.allframes = [] def shown_info(self, info): self.ui.info_display.setPlainText(info) def apply_model1(self): if cfg.GLOBAL.F_MODEL1: cfg.GLOBAL.F_MODEL1 = False self.ui.model1_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP1)) else: cfg.GLOBAL.F_MODEL1 = True self.ui.model1_bn.setIcon( QIcon(cfg.ICONS.RIGHT_TOP1.replace('bright', 'color'))) def apply_model2(self): if cfg.GLOBAL.F_MODEL2: cfg.GLOBAL.F_MODEL2 = False self.ui.model2_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP2)) else: cfg.GLOBAL.F_MODEL2 = True self.ui.model2_bn.setIcon( QIcon(cfg.ICONS.RIGHT_TOP2.replace('bright', 'color'))) def apply_model3(self): if cfg.GLOBAL.F_MODEL3: cfg.GLOBAL.F_MODEL3 = False self.ui.model3_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP3)) else: cfg.GLOBAL.F_MODEL3 = True self.ui.model3_bn.setIcon( QIcon(cfg.ICONS.RIGHT_TOP3.replace('bright', 'color'))) def apply_model4(self): if cfg.GLOBAL.F_MODEL4: cfg.GLOBAL.F_MODEL4 = False self.ui.model4_bn.setIcon(QIcon(cfg.ICONS.RIGHT_TOP4)) else: cfg.GLOBAL.F_MODEL4 = True self.ui.model4_bn.setIcon( QIcon(cfg.ICONS.RIGHT_TOP4.replace('bright', 'color'))) def apply_model5(self): pass def start_camera(self): self.ui.thread1_bn.setIcon( QIcon(cfg.ICONS.TOP_LEFT1.replace('bright', 'color'))) self.ui.thread2_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT2)) self.ui.thread3_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT3)) self.ui.thread4_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT4)) self.ui.thread5_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT5)) self.camera_device = CameraDevice() self.camera_device.newFrame.connect(self.onNewImage) self.clear() def start_video1(self): self.ui.thread1_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT1)) self.ui.thread2_bn.setIcon( QIcon(cfg.ICONS.TOP_LEFT2.replace('bright', 'color'))) self.ui.thread3_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT3)) self.ui.thread4_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT4)) self.ui.thread5_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT5)) self.camera_device.set_video_path(cfg.GLOBAL.VIDEO1) self.clear() def start_video2(self): self.ui.thread1_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT1)) self.ui.thread2_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT2)) self.ui.thread3_bn.setIcon( QIcon(cfg.ICONS.TOP_LEFT3.replace('bright', 'color'))) self.ui.thread4_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT4)) self.ui.thread5_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT5)) self.camera_device.set_video_path(cfg.GLOBAL.VIDEO2) self.clear() def start_pic(self): self.ui.thread1_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT1)) self.ui.thread2_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT2)) self.ui.thread3_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT3)) self.ui.thread4_bn.setIcon( QIcon(cfg.ICONS.TOP_LEFT4.replace('bright', 'color'))) self.ui.thread5_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT5)) self.camera_device.set_video_path(cfg.GLOBAL.VIDEO3) self.clear() def load_video(self): self.ui.thread1_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT1)) self.ui.thread2_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT2)) self.ui.thread3_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT3)) self.ui.thread4_bn.setIcon(QIcon(cfg.ICONS.TOP_LEFT4)) self.ui.thread5_bn.setIcon( QIcon(cfg.ICONS.TOP_LEFT5.replace('bright', 'color'))) self.clear() @QtCore.pyqtSlot(np.ndarray) def onNewImage(self, frame): self.adjustScale() frame = np.asarray(frame[:, :]) frame = cv2.resize(frame, tuple(cfg.GLOBAL.IM_SHOW_SIZE)) self.allframes.append(frame) vis = frame.copy() # vis = cv2.resize(vis, (960, 640)) t = clock() result1, result2, result3, result4 = None, None, None, None if cfg.GLOBAL.F_MODEL1: task1_in.put(frame) if cfg.GLOBAL.F_MODEL2: task2_in.put(frame) if cfg.GLOBAL.F_MODEL3: task3_in.put(frame) if cfg.GLOBAL.F_MODEL4: task4_in.put(frame) while True: if cfg.GLOBAL.F_MODEL1: task1_empty = task1_out.empty() else: task1_empty = False if cfg.GLOBAL.F_MODEL2: task2_empty = task2_out.empty() else: task2_empty = False if cfg.GLOBAL.F_MODEL3: task3_empty = task3_out.empty() else: task3_empty = False if cfg.GLOBAL.F_MODEL4: task4_empty = task4_out.empty() else: task4_empty = False if not task1_empty and not task2_empty and not task3_empty and not task4_empty: if cfg.GLOBAL.F_MODEL1: result1 = task1_out.get() else: result1 = None if cfg.GLOBAL.F_MODEL2: result2 = task2_out.get() else: result2 = None if cfg.GLOBAL.F_MODEL3: result3 = task3_out.get() else: result3 = None if cfg.GLOBAL.F_MODEL4: result4 = task4_out.get() else: result4 = None break if result1 is not None: vis = draw_pose_kpts(vis, result1, V.COLORMAP19, V.POSE19_LINKPAIR) if result2 is not None: vis = draw_fancybbox(vis, result2) if result3 is not None: vis = draw_fancybbox(vis, result3) if result4 is not None: vis = draw_fancybbox(vis, result4) # vis = draw_fancybbox(vis, result4, attri=True) # vis = draw_face68_kpts(vis, result4) dt = clock() - t if self.flag_savevideo and self.savevideo_counting <= self.savevideo_max: save_im = cv2.resize(vis, tuple(cfg.GLOBAL.SAVE_VIDEO_SIZE)) self.video_writer.write(save_im) self.savevideo_counting += 1 elif self.savevideo_counting > self.savevideo_max: self.savevideo_counting = 0 self.flag_savevideo = False self.ui.record_bn.setIcon(QIcon(cfg.ICONS.LEFT_TOP3)) draw_str(vis, (30, 30), 'speed: %.1f fps' % (min(1.0 / dt, 30))) if len(self.allframes) % 15 == 0: cur_info = self.info_header + u'--------------------\n ' if self.flag_savevideo: cur_info += u'Saving Video~~\n--------------------\n' cur_info += u'当前为第{}帧视频\n 当前视频频率为: {:.1f}fps\n '. \ format(len(self.allframes), min(1.0 / dt, 30)) cur_info += u'--------------------\n ' self.shown_info(cur_info) vis = cv2.resize(vis, tuple(cfg.GLOBAL.IM_SHOW_SIZE)) image = QImage(vis.tostring(), vis.shape[1], vis.shape[0], QImage.Format_RGB888).rgbSwapped() self.canvas.update_image(image)
def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) self.progress_bar = QProgressBar() self.progress_bar_timer = QTimer() self.progress_bar_timer.setInterval(1000) self.progress_bar_timer.timeout.connect(lambda x=None: self.progress_bar.setValue(self.progress_bar.value() - 1)) self.progress_bar.valueChanged.connect(lambda value: self.progress_bar_timer.stop() if self.progress_bar.value() <= 0 else None) self.ui.statusbar.addWidget(self.progress_bar) # TODO: показывать историю бота: self.view.history() self.moswar_url = 'http://www.moswar.ru/' # Чтобы не было проблем запуска компов с прокси: QNetworkProxyFactory.setUseSystemConfiguration(True) QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self.ui.view.urlChanged.connect(lambda x: self.ui.url_le.setText(x.toString())) self.ui.view.linkClicked.connect(lambda x: self.ui.url_le.setText(x.toString())) self.ui.pushButtonBackWebPage.clicked.connect(self.ui.view.back) # При клике на кнопку, мы получаем значение data текущего элемента и вызываем функцию, хранящуюся там self.ui.run_pb.clicked.connect(lambda: self.ui.commands_cb.itemData(self.ui.commands_cb.currentIndex())()) self.thimblerig = Thimblerig(self) self.fight = Fight(self) self.restore_hp = RestoreHP(self) self.factory_petric = FactoryPetric(self) self.shaurburgers = Shaurburgers(self) self.patrol = Patrol(self) # Список действий бота self.name_action_dict = { 'Закоулки': self.alley, 'Площадь': self.square, 'Метро': self.metro, 'Завод': self.factory, 'Задания': self.jobs, 'Персонаж': self.player, 'Хата': self.home, 'Игра в наперстки': self.thimblerig.run, 'Напасть': self.fight.run, 'Ищем следующего противника': self.fight._next_enemy, 'Восстановление жизней': self.restore_hp.run, 'Варка нано-петриков': self.factory_petric.run, 'Убрать таймаут Тонусом': self.fight.use_tonus, 'Шаурбургерс': self.shaurburgers.go, 'Работать в Шаурбургерсе': self.shaurburgers.run, 'Патрулировать': self.patrol.run, } # Добавляем команды for command in sorted(self.name_action_dict): self.ui.commands_cb.addItem(command, self.name_action_dict[command]) # Выполнение кода в окне "Выполнение скрипта" self.ui.button_exec.clicked.connect(lambda x=None: exec(self.ui.code.toPlainText())) # Таймер используемый для вызова функции для запуска задач self._task_timer = QTimer() self._task_timer.setSingleShot(True) self._task_timer.timeout.connect(self._task_tick) self.ui.actionStartTimer.triggered.connect(self._task_tick) self.ui.actionStopTimer.triggered.connect(self._task_timer.stop) self.ui.actionStopTimer.triggered.connect(self.progress_bar_timer.stop) # Если стоит True -- происходит выполнение задачи и функция _task_tick прерывается self._used = False # Название процесса, из-за которого в данный момент _task_tick не может выполниться self._used_process = None # Минимальная сумма для игры в Наперстки self.min_money_for_thimblerig = 200000
class MainWindow(QMainWindow, QObject): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) self.progress_bar = QProgressBar() self.progress_bar_timer = QTimer() self.progress_bar_timer.setInterval(1000) self.progress_bar_timer.timeout.connect(lambda x=None: self.progress_bar.setValue(self.progress_bar.value() - 1)) self.progress_bar.valueChanged.connect(lambda value: self.progress_bar_timer.stop() if self.progress_bar.value() <= 0 else None) self.ui.statusbar.addWidget(self.progress_bar) # TODO: показывать историю бота: self.view.history() self.moswar_url = 'http://www.moswar.ru/' # Чтобы не было проблем запуска компов с прокси: QNetworkProxyFactory.setUseSystemConfiguration(True) QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self.ui.view.urlChanged.connect(lambda x: self.ui.url_le.setText(x.toString())) self.ui.view.linkClicked.connect(lambda x: self.ui.url_le.setText(x.toString())) self.ui.pushButtonBackWebPage.clicked.connect(self.ui.view.back) # При клике на кнопку, мы получаем значение data текущего элемента и вызываем функцию, хранящуюся там self.ui.run_pb.clicked.connect(lambda: self.ui.commands_cb.itemData(self.ui.commands_cb.currentIndex())()) self.thimblerig = Thimblerig(self) self.fight = Fight(self) self.restore_hp = RestoreHP(self) self.factory_petric = FactoryPetric(self) self.shaurburgers = Shaurburgers(self) self.patrol = Patrol(self) # Список действий бота self.name_action_dict = { 'Закоулки': self.alley, 'Площадь': self.square, 'Метро': self.metro, 'Завод': self.factory, 'Задания': self.jobs, 'Персонаж': self.player, 'Хата': self.home, 'Игра в наперстки': self.thimblerig.run, 'Напасть': self.fight.run, 'Ищем следующего противника': self.fight._next_enemy, 'Восстановление жизней': self.restore_hp.run, 'Варка нано-петриков': self.factory_petric.run, 'Убрать таймаут Тонусом': self.fight.use_tonus, 'Шаурбургерс': self.shaurburgers.go, 'Работать в Шаурбургерсе': self.shaurburgers.run, 'Патрулировать': self.patrol.run, } # Добавляем команды for command in sorted(self.name_action_dict): self.ui.commands_cb.addItem(command, self.name_action_dict[command]) # Выполнение кода в окне "Выполнение скрипта" self.ui.button_exec.clicked.connect(lambda x=None: exec(self.ui.code.toPlainText())) # Таймер используемый для вызова функции для запуска задач self._task_timer = QTimer() self._task_timer.setSingleShot(True) self._task_timer.timeout.connect(self._task_tick) self.ui.actionStartTimer.triggered.connect(self._task_tick) self.ui.actionStopTimer.triggered.connect(self._task_timer.stop) self.ui.actionStopTimer.triggered.connect(self.progress_bar_timer.stop) # Если стоит True -- происходит выполнение задачи и функция _task_tick прерывается self._used = False # Название процесса, из-за которого в данный момент _task_tick не может выполниться self._used_process = None # Минимальная сумма для игры в Наперстки self.min_money_for_thimblerig = 200000 def _task_tick(self): """Функция для запуска задач.""" if self._used: logger.debug('Запуск задач отменяется -- процесс занят "%s".', self._used_process) else: logger.debug('Запуск задач.') try: # Если уже играем в Наперстки или набрали нужную сумму для игры в Наперстки if 'thimble' in self.current_url() or self.money() >= self.min_money_for_thimblerig: self.thimblerig.run() elif self.shaurburgers.is_ready(): self.shaurburgers.run() elif self.patrol.is_ready(): self.patrol.run() elif self.factory_petric.is_ready(): self.factory_petric.run() elif self.fight.is_ready(): self.fight.run() except MoswarClosedError as e: logger.warn(e) # В случаи закрытия сайт, каждый час проверяем interval = 60 * 60 * 1000 except MoswarBotError as e: logger.error(e) # Возможно, в следующий раз ошибки не будет interval = 1 * 1000 except Exception as e: logger.error(e) # Возможно, в следующий раз ошибки не будет interval = 1 * 1000 import traceback traceback.print_exc() else: # TODO: настраивать interval: спрашивать у другиз модулей их таймауты (если есть) и выбирать # наименьший, он и будет interval. Если же interval не был изменен, то задавать рандомное время # Это позволит увеличить эффективность бота # Запускаем таймер выполнение задач # Следующий вызов будет случайным от 3 до 10 минут + немного случайных секунд interval = int((randint(3, 10) + random()) * 60 * 1000) self._start_task_timer(interval) def _start_task_timer(self, interval): secs = interval / 1000 logger.debug('Повторный запуск задач через %s секунд.', secs) self._task_timer.start(interval) self.progress_bar.setRange(0, secs) self.progress_bar.setValue(secs) self.progress_bar_timer.start() def _get_doc(self): return self.ui.view.page().mainFrame().documentElement() doc = property(_get_doc) def current_url(self): """Функция возвращает текущий адрес страницы.""" return self.ui.view.url().toString() def wait_loading(self): """Функция ожидания загрузки страницы. Использовать только при изменении url.""" logger.debug('Начинаю ожидание загрузки страницы.') # Ждем пока прогрузится страница loop = QEventLoop() self.ui.view.loadFinished.connect(loop.quit) loop.exec_() logger.debug('Закончено ожидание загрузки страницы.') def go(self, relative_url): """Функция для загрузки страниц. Если вызывать без параметров, то загрузит основную страницу. Если указывать relative_url, то он будет присоединен к адресу мосвара. Функция ожидание окончания загрузки страницы. Выбрасывает исключение MoswarClosedError, когда сайта закрыт (closed.html) """ url = urljoin(self.moswar_url, relative_url) logger.debug('Перехожу по адресу "%s"', url) self.ui.view.load(url) self.wait_loading() # TODO: вынести обработку переадресаций в отдельную функцию # Проверяем, что не случилось переадресации. Она возможна, например, при игре # в наперстки или попадании в милицию current_url = self.current_url() # Сравниваем url'ы между собой. Такая проверка для обхода ситуации, когда QWebView отдает url # со слешем на конце. Если сравнить их обычной проверкой (== или !=), то это будет неправильно. # http://www.moswar.ru/shaurburgers/ # # А сравниваем с: # http://www.moswar.ru/shaurburgers equal = url in current_url or current_url in url # Если адреса не равны if not equal: self.slog(url + " -> " + current_url) self.slog('Текущий заголовок: "{}"'.format(self.title())) logger.warn('Похоже, случилась переадресация: шли на %s, а попали на %s.', url, current_url) # TODO: Для http://www.moswar.ru/closed.html описывать причину -- брать из auth() # Проверка на временное отсутствие доступа к сайту if 'closed.html' in current_url: reason = self.doc.toPlainText().strip() logger.warn('Закрыто, причина:\n%s', reason) raise MoswarClosedError(reason) # TODO: руды может не хватать, поэтому предусмотреть ситуацию, когда придется платить деньгами # Обработка ситуации: Задержка за бои # url полиции police, но url'ы иногда неправильно возвращаются, поэтому надежнее смотреть # на заголовок страницы if self.title() == 'Милиция': logger.debug('Задержаны в милиции.') # Ищем кнопку для налаживания связей рудой button = self.doc.findFirst('.police-relations .button') if not button.isNull(): logger.debug('Плачу взятку рудой.') # Нажать на кнопку что-то не получается, поэтому просто шлем запрос, # который и так бы отослался при клике на кнопку self.go('police/relations') # TODO: если новый уровень выпал в момент выполнения задания, то возможна такая неприятная # ситуация: попадаем на is_ready таски, делается переход к локации такси, перенапрявляет нас # на страницу поздравления, мы это определяем, кликаем на кнопку, в этот момент is_ready # возвращает True, и мы попадаем в функцию выполнения, которая снова переходит на страницу локации # и снова нас перенапрявляет, мы это определяем, кликаем и это так может случится несколько раз # TODO: возвращать признак перенаправления и по нему таска сама решает -- отменить или нет свое # выполнение # # Проверка на новый уровень if 'quest' in current_url: level_up = self.doc.findFirst('.levelup') if not level_up.isNull(): # Показать столько побед / награблено for td in level_up.findAll('td'): logger.debug('Получен новый уровень! Результат:\n' + ' '.join(td.toPlainText().split())) # Ищем кнопку 'Вперед, к новым победам!' и кликаем на нее button = self.doc.findFirst('.levelup .button') if button.isNull(): raise MoswarButtonIsMissError('Вперед, к новым победам!') button.evaluateJavaScript('this.click()') def auth(self): """Функция загружает страницу мосвара, заполняет поля логина и пароля и нажимает на кнопку Войти. После нажатия на Войти происходит ожидание загрузки страницы. """ logger.debug('Авторизуюсь.') # Открываем страницу мосвара url = self.moswar_url logger.debug('Перехожу по адресу "%s"', url) self.ui.view.load(url) self.wait_loading() # Если закрыт доступ к сайту if 'closed.html' in self.current_url(): logger.warn('Закрыто, причина:\n%s', self.doc.toPlainText().strip()) # Попробуем снова авторизоваться через 1 час QTimer.singleShot(60 * 60 * 1000, self.auth) return login = self.doc.findFirst('#login-email') password = self.doc.findFirst('#login-password') if login.isNull() or password.isNull(): raise MoswarAuthError('Не найдены поля логина и пароля.') login.setAttribute("value", LOGIN) password.setAttribute("value", PASSWORD) submit = self.doc.findFirst("input[type=submit]") if submit.isNull(): raise MoswarButtonIsMissError('Войти') logger.debug('Захожу в игру.') submit.evaluateJavaScript("this.click()") self.wait_loading() logger.debug('Запуск таймера выполнения задач.') # Выполнение первых задач self._task_tick() def alley(self): self.go('alley') def square(self): self.go('square') def factory(self): self.go('factory') def metro(self): self.go('metro') def jobs(self): self.go('nightclub/jobs') def player(self): self.go('player') def home(self): self.go('home') def name(self): """Функция возвращает имя текущего персонажа.""" try: css_path = '#personal .name' name = self.doc.findFirst(css_path).toPlainText() name = name[:name.rindex('[')] return name.strip() except Exception as e: raise MoswarElementIsMissError(e) def money(self): """Функция возвращает количество денег персонажа.""" try: css_path = '.tugriki-block' tugriki = self.doc.findFirst(css_path) tugriki = tugriki.attribute('title') tugriki = tugriki.split(': ')[-1] return int(tugriki) except Exception as e: raise MoswarElementIsMissError(e) def current_hp(self): """Функция возвращает текущее количество жизней персонажа.""" try: css_path = '#personal #currenthp' hp = self.doc.findFirst(css_path) hp = hp.toPlainText() return int(hp) except Exception as e: raise MoswarElementIsMissError(e) def max_hp(self): """Функция возвращает текущее количество жизней персонажа.""" try: hp = self.doc.findFirst('#personal #maxhp') hp = hp.toPlainText() return int(hp) except Exception as e: raise MoswarElementIsMissError(e) def level(self): """Функция возвращает уровень персонажа.""" try: level = self.doc.findFirst('#personal b').toPlainText() level = level.split()[-1] level = level.replace('[', '').replace(']', '') return int(level) except Exception as e: raise MoswarElementIsMissError(e) def title(self): """Функция возвращает заголовок текущей страницы.""" title = self.doc.findFirst('head title') if title.isNull(): logger.warn('Не найден заголовок текущей страницы (%s).', self.current_url()) return title.toPlainText() # TODO: добавить возможность выбрать область поиска элемента для клика, а то она все время вся страница -- self.doc def click_tag(self, css_path): """Функция находит html тег по указанному пути и эмулирует клик на него. Строки в css_path нужно оборачивать в апострофы. Пример: # Кликаем на кнопку "Отнять у слабого" self.click_tag("div[class='button-big btn f1']") # Кликаем на кнопку "Искать другого" self.click_tag(".button-search a") """ logger.debug('Выполняю клик по тегу: %s', css_path) # Используем для клика jQuery code = """ tag = $("{}"); tag.click();""".format(css_path) ok = self.doc.evaluateJavaScript(code) if ok is None: logger.warn('Выполнение js скрипта неудачно. Code:\n' + code) def alert(self, text): """Функция показывает окно сообщений в браузере, используя javascript функцию alert.""" self.doc.evaluateJavaScript('alert("{}")'.format(text)) def slog(self, *args, **kwargs): """Функция для добавления текста в виджет-лог, находящегося на форме.""" # Используем стандартный print для печати в строку str_io = io.StringIO() kwargs['file'] = str_io kwargs['end'] = '' print(*args, **kwargs) text = str_io.getvalue() self.ui.simple_log.appendPlainText(text) def read_settings(self): # TODO: при сложных настройках, лучше перейти на json или yaml config = QSettings(CONFIG_FILE, QSettings.IniFormat) self.restoreState(config.value('MainWindow_State')) self.restoreGeometry(config.value('MainWindow_Geometry')) def write_settings(self): config = QSettings(CONFIG_FILE, QSettings.IniFormat) config.setValue('MainWindow_State', self.saveState()) config.setValue('MainWindow_Geometry', self.saveGeometry()) def closeEvent(self, *args, **kwargs): self.write_settings() super().closeEvent(*args, **kwargs)
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) self.model = QStandardItemModel() self.clear_model() self.ui.treeView.setModel(self.model) self.ui.treeView.clicked.connect(self.show_info_in_status_bar) self.ui.treeView.doubleClicked.connect(self.show_in_explorer) self.ui.button_select_dir.clicked.connect(self.select_dir) self.ui.action_go.triggered.connect(self.fill) self.ui.action_show_in_explorer.triggered.connect(self.show_in_explorer) self.ui.action_apply_filter.triggered.connect(self.slot_remove_dirs) self.ui.label_root_dir.setText(self.ui.line_edit_dir_path.text()) self.ui.action_apply_filter.setEnabled(False) self.read_settings() def update_states(self): pass def show_in_explorer(self, index=None): if index is None: index = self.ui.treeView.currentIndex() if index is None: return row = self.get_row_item_from_index(index) if row is None: return # TODO: Qt.UserRole + 1 path = row[0].data(Qt.UserRole + 1) cmd = 'Explorer /n,"{}"'.format(path) logger.debug('Command: %s.', cmd) os.system(cmd) def select_dir(self): dir_path = QFileDialog.getExistingDirectory(self, None, self.ui.line_edit_dir_path.text()) if dir_path: self.ui.line_edit_dir_path.setText(dir_path) def get_row_item_from_index(self, index): if index is None or not index.isValid: logger.warn('get_row_from_index: invalid index: %s.', index) return row = index.row() item = self.model.itemFromIndex(index) if item is None: return parent = item.parent() if parent is None: parent = self.model.invisibleRootItem() return [parent.child(row, i) for i in range(self.model.columnCount())] def show_info_in_status_bar(self, index): row = self.get_row_item_from_index(index) if row is None: return path, size = row # TODO: Лучше дать конкретные константные имена, чем так: Qt.UserRole + 1 / Qt.UserRole + 2 self.ui.statusbar.showMessage('{} ({} / {} bytes)'.format( path.data(Qt.UserRole + 1), size.data(Qt.UserRole + 1), size.data(Qt.UserRole + 2))) def clear_model(self): self.model.clear() header_labels = ['Name', 'Size'] self.model.setColumnCount(len(header_labels)) self.model.setHorizontalHeaderLabels(header_labels) def remove_dirs(self, root): """Удаление элементов, у которых размер не совпадает с фильтром""" for row in reversed(range(root.rowCount())): child = root.child(row, 1) filter_size = self.ui.line_edit_filter.text() if not check_filter_size_eval(filter_size, directory_sizes.get_bytes(child.data(Qt.UserRole + 1))): root.removeRow(child.row()) else: self.remove_dirs(root.child(row, 0)) def slot_remove_dirs(self): self.ui.action_apply_filter.setEnabled(False) self.remove_dirs(self.model.invisibleRootItem()) def fill(self): self.ui.action_go.setEnabled(False) self.clear_model() dir_path = self.ui.line_edit_dir_path.text() if not dir_path or not os.path.exists(dir_path): QMessageBox.information(self, 'Info', 'Choose dir path!') return filter_size = self.ui.line_edit_filter.text() if not filter_size: logger.debug('filter_size is empty. Setting default filter_size.') filter_size = "{size} >= %1GB%" logger.debug('filter_size: %s.', filter_size) t = time.clock() # Соберем список папок dir_list = [os.path.join(dir_path, entry) for entry in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, entry))] for entry in dir_list: self.dir_size_bytes(entry, self.model.invisibleRootItem(), filter_size) self.ui.action_apply_filter.setEnabled(True) if self.ui.check_box_auto_apply_filter.isChecked(): self.slot_remove_dirs() self.ui.action_apply_filter.setEnabled(False) t = time.clock() - t logger.debug('Done! Elapsed time {:.2f} sec.'.format(t)) self.ui.action_go.setEnabled(True) QMessageBox.information(self, 'Info', 'Done!\n\nElapsed time {:.2f} sec.'.format(t)) def dir_size_bytes(self, dir_path, root_item, filter_size, level=0): dir_path = QDir.toNativeSeparators(dir_path) it = QDirIterator(dir_path, '*.*', QDir.AllEntries | QDir.NoDotAndDotDot | QDir.Hidden | QDir.System) sizes = 0 path_short_name = os.path.split(dir_path) path_short_name = path_short_name[1] if path_short_name[1] else path_short_name[0] row = [QStandardItem(path_short_name), QStandardItem('-')] row[0].setData(dir_path) row[1].setText('-') row[1].setData('-') row[0].setEditable(False) row[1].setEditable(False) root_item.appendRow(row) while it.hasNext(): file_name = it.next() file = QFileInfo(file_name) if file.isDir(): size = self.dir_size_bytes(file_name, row[0], filter_size, level + 1) else: size = file.size() sizes += size qApp.processEvents() text_size = directory_sizes.pretty_file_size(sizes)[1] row[1].setText(text_size) row[1].setData(text_size) row[1].setData(str(sizes), Qt.UserRole + 2) return sizes def read_settings(self): # TODO: при сложных настройках, лучше перейти на json или yaml config = QSettings(CONFIG_FILE, QSettings.IniFormat) self.restoreState(config.value('MainWindow_State')) self.restoreGeometry(config.value('MainWindow_Geometry')) dir_path = config.value('Dir_path', None) if not dir_path: dir_path = "C:\\" self.ui.line_edit_dir_path.setText(dir_path) filter_size = config.value('Filter_size', None) if not filter_size: filter_size = "{size} >= %1GB%" self.ui.line_edit_filter.setText(filter_size) self.ui.check_box_auto_apply_filter.setChecked('true' in config.value('Auto_apply_filter', 'true').lower()) def write_settings(self): config = QSettings(CONFIG_FILE, QSettings.IniFormat) config.setValue('MainWindow_State', self.saveState()) config.setValue('MainWindow_Geometry', self.saveGeometry()) config.setValue('Dir_path', self.ui.line_edit_dir_path.text()) config.setValue('Filter_size', self.ui.line_edit_filter.text()) config.setValue('Auto_apply_filter', 'true' if self.ui.check_box_auto_apply_filter.isChecked() else 'false') def closeEvent(self, event): self.write_settings() quit()
class MainWindow(QMainWindow, QObject): def __init__(self, data_singleton, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.data_singleton = data_singleton self.mUndoStackGroup = QUndoGroup(self) self.mUndoStackGroup.canUndoChanged.connect(self.can_undo_changed) self.mUndoStackGroup.canRedoChanged.connect(self.can_redo_changed) self.can_undo_changed(self.mUndoStackGroup.canUndo()) self.can_redo_changed(self.mUndoStackGroup.canRedo()) self.ui.actionUndo.triggered.connect(self.mUndoStackGroup.undo) self.ui.actionRedo.triggered.connect(self.mUndoStackGroup.redo) self.ui.actionSave.triggered.connect(self.save) self.ui.actionSaveAs.triggered.connect(self.save_as) self.ui.actionNew.triggered.connect(self.new_tab) self.ui.actionOpen.triggered.connect(self.open) self.ui.actionSettings.triggered.connect(self.show_settings) self.ui.actionPlugin_Manager.triggered.connect(self.show_plugin_manager) self.ui.tabWidget.currentChanged.connect(self.activate_tab) self.ui.tabWidget.currentChanged.connect(self.send_tab_changed) self.ui.tabWidget.tabCloseRequested.connect(self.close_tab) self.update_states() send_cursor_pos = Signal(int, int) send_new_image_size = Signal(int, int) send_tab_changed = Signal(int) def load_plugins(self): # TODO: проверить импортирование пакетов пакетов loader = PluginsLoader(self.data_singleton) loader.enableOutput = True # TODO: список папок плагинов доставать из синглетона loader.load(['plugins']) # TODO: rem print('Plugins:') for plugin in loader.plugins(): print(' ', plugin) print() def update_states(self): if self.ui.tabWidget.count() == 0: self.setWindowTitle('Empty' + ' - ' + self.data_singleton.PROGRAM_NAME) else: canvas = self.get_current_canvas() file_name = canvas.get_file_name() title = self.data_singleton.UNTITLED if file_name is None else file_name tab_title = title if canvas.edited: title += '[*]' tab_title += '*' self.setWindowTitle(title + ' - ' + self.data_singleton.PROGRAM_NAME) index = self.ui.tabWidget.currentIndex() self.ui.tabWidget.setTabText(index, tab_title) self.setWindowModified(canvas.edited) def close_tab(self, index): canvas = self.get_canvas(index) if canvas.edited: reply = QMessageBox.warning(self, "Closing Tab...", "File has been modified\n" "Do you want to save changes?", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Yes) if reply == QMessageBox.Yes: self.save(canvas) elif reply == QMessageBox.Cancel: return self.mUndoStackGroup.removeStack(canvas.getUndoStack()) tab = self.ui.tabWidget.widget(index) self.ui.tabWidget.removeTab(index) tab.deleteLater() self.update_states() def new_tab(self): canvas = Canvas(self.data_singleton) self.mUndoStackGroup.addStack(canvas.getUndoStack()) canvas.send_cursor_pos.connect(self.send_cursor_pos) canvas.send_new_image_size.connect(self.send_new_image_size) canvas.send_change_edited.connect(self.update_states) scroll_area = QScrollArea() scroll_area.setWidget(canvas) scroll_area.setBackgroundRole(QPalette.Dark) file_name = canvas.get_file_name() title = self.data_singleton.UNTITLED if file_name is None else file_name self.ui.tabWidget.addTab(scroll_area, title) self.update_states() def activate_tab(self, index): if index == -1: return canvas = self.get_current_canvas() self.mUndoStackGroup.setActiveStack(canvas.getUndoStack()) self.send_new_image_size.emit(canvas.width(), canvas.height()) self.update_states() def save(self, canvas_=None): try: # Если canvas_ не указан, берем текущий canvas = self.get_current_canvas() if canvas_ is None else canvas_ if canvas is not None: # Если у холста есть файл, сохраняем в него, иначе вызываем "сохранить как" if canvas.file_path is None: self.save_as() else: canvas.save() except Exception as e: QMessageBox.warning(self, 'Warning', str(e)) self.update_states() def save_as(self): canvas = self.get_current_canvas() if canvas is None: return # Список строк с поддерживаемыми форматами изображений formats = [str(x) for x in QImageWriter.supportedImageFormats()] # Описываем как фильтры диалога filters = ["{} ( *.{} )".format(x.upper(), x) for x in formats] file_name = canvas.get_file_name() if file_name is None: file_name = os.path.join(QDir.homePath(), self.data_singleton.UNTITLED) default_filter = "{} ( *.{} )".format('PNG', 'png') # Получим путь к файлу file_name = QFileDialog.getSaveFileName(self, None, file_name, '\n'.join(filters), default_filter)[0] if file_name: try: canvas.save(file_name) except Exception as e: QMessageBox.warning(self, 'Warning', str(e)) self.update_states() def open(self): # Список строк с поддерживаемыми форматами изображений formats = [str(x) for x in QImageReader.supportedImageFormats()] # Описываем как фильтры диалога filters = 'Поддерживаемые форматы (' filters += ' '.join(["*.{}".format(x.lower()) for x in formats]) filters += ')' # Получим путь к файлу file_name = QFileDialog.getOpenFileName(self, None, None, filters)[0] if file_name: try: canvas = self.get_current_canvas() if canvas is not None: canvas.load(file_name) self.update_states() except Exception as e: QMessageBox.warning(self, 'Внимание', str(e)) def show_settings(self): settings = Settings(self.data_singleton) settings.exec_() def show_plugin_manager(self): plugin_manager = PluginManager(self.data_singleton) plugin_manager.exec_() def can_undo_changed(self, enabled): self.ui.actionUndo.setEnabled(enabled) def get_canvas(self, index): if index < 0 or index >= self.ui.tabWidget.count(): return None tab = self.ui.tabWidget.widget(index) return tab.widget() def get_current_canvas(self): index = self.ui.tabWidget.currentIndex() if index != -1: return self.get_canvas(index) def can_redo_changed(self, enabled): self.ui.actionRedo.setEnabled(enabled) def read_settings(self): try: import json with open(self.data_singleton.settings_path, 'r') as f: data = json.load(f) self.restoreGeometry(QByteArray.fromHex(data['MainWindow']['geometry'])) self.restoreState(QByteArray.fromHex(data['MainWindow']['state'])) # TODO: синглетон должен сам грузить свои настройки, еще до загрузки mainwindow # self.data_singleton.from_serialize(data['Settings']) except Exception as e: print(e) def write_settings(self): # TODO: для ini есть модуль ConfigParser try: import json with open(self.data_singleton.settings_path, 'w') as f: data = { 'MainWindow': { 'state': str(self.saveState().toHex()), 'geometry': str(self.saveGeometry().toHex()), }, # TODO: вызывать у синглетона функцию 'Settings': self.data_singleton.to_serialize(), } json.dump(data, f, sort_keys=True, indent=4, ensure_ascii=False) except Exception as e: print(e) def closeEvent(self, *args, **kwargs): self.write_settings() # Закрывать вкладки будем с правого края for i in reversed(range(self.ui.tabWidget.count())): self.close_tab(i) # TODO: спрашивать о том уверенности пользователя нужно с учетом флажка # reply = QtGui.QMessageBox.question(self, 'Message', # "Are you sure to quit?", QtGui.QMessageBox.Yes | # QtGui.QMessageBox.No, QtGui.QMessageBox.No) # # if reply == QtGui.QMessageBox.Yes: # event.accept() # else: # event.ignore() super().closeEvent(*args, **kwargs)
class MainWindow(QMainWindow): ui = None mainWindow = None client = WudaoClient() painter = GuiDraw() draw_conf = True is_zh = False word = '' def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.history_manager = UserHistory() self.setup_ui() def setup_ui(self): self.ui = Ui_MainWindow() self.ui.setupUi(self) # auto complete self.auto_com_init() self.ui.ol_cb.setChecked(False) darkula = QPalette() # theme darkula.setColor(QPalette.Background, QColor('#300A24')) darkula.setColor(QPalette.Base, QColor('#300A24')) self.ui.textBrowser.setPalette(darkula) # status bar self.ui.statusbar.showMessage('@2016 Chestnut Studio') # signal slot self.ui.lineEdit.returnPressed.connect(self.search_bt_clicked) self.ui.search_b.clicked.connect(self.search_bt_clicked) self.ui.detail_rb.clicked.connect(self.detail_rb_clicked) self.ui.intro_rb.clicked.connect(self.intro_rb_clicked) def detail_rb_clicked(self): self.draw_conf = True self.search_bt_clicked() def intro_rb_clicked(self): self.draw_conf = False self.search_bt_clicked() # auto complete def auto_com_init(self): sl = ['a', 'air', 'airplane'] com = QCompleter(sl) com.setCaseSensitivity(Qt.CaseInsensitive) self.ui.lineEdit.setCompleter(com) def search_bt_clicked(self): self.word = self.ui.lineEdit.text().strip() if self.word: # if chinese if is_alphabet(self.word[0]): self.is_zh = False else: self.is_zh = True # query on server server_context = self.client.get_word_info(self.word).strip() if server_context != 'None': wi = json.loads(server_context) self.painter.html = '' if self.is_zh: self.painter.draw_zh_text(wi, self.draw_conf) else: self.history_manager.add_item(self.word) self.painter.draw_text(wi, self.draw_conf) self.ui.textBrowser.setHtml(self.painter.html) else: # Online search html = '' if self.ui.ol_cb.isChecked(): self.painter.html = '' try: self.ui.textBrowser.setHtml(self.painter.P_W_PATTERN % 'Searching OL...') from src.WudaoOnline import get_text, get_zh_text from urllib.error import URLError if self.is_zh: word_info = get_zh_text(self.word) else: word_info = get_text(self.word) if not word_info['paraphrase']: html += self.painter.P_W_PATTERN % ('No such word: %s found online' % self.word) if not self.is_zh: self.history_manager.add_word_info(word_info) self.painter.draw_text(word_info, self.draw_conf) else: self.painter.draw_zh_text(word_info, self.draw_conf) self.ui.textBrowser.setHtml(self.painter.html) return except ImportError: html += self.painter.P_W_PATTERN % 'You need install bs4 first.' html += self.painter.P_W_PATTERN % 'Use \'pip3 install bs4\' or get bs4 online.' except URLError: html += self.painter.P_W_PATTERN % 'No Internet : Please check your connection first' else: # search in online cache first word_info = self.history_manager.get_word_info(self.word) if word_info: self.history_manager.add_item(self.word) self.painter.draw_text(word_info, self.draw_conf) self.ui.textBrowser.setHtml(self.painter.html) return else: html += self.painter.P_W_PATTERN % ('Error: no such word :' + self.word) html += self.painter.P_W_PATTERN % 'You can check Online Box to search it online.' self.ui.textBrowser.setHtml(html)
class mainWindowUI(QMainWindow): #mainwindow inheriting from QMainWindow here. projectName = None currentFileDir = None tempName = "variables.var" def __init__(self): QDialog.__init__(self)# Constructs a dialog with parent parent. self being ImageDailog # Set up the UI from Designer: self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.graphicsView.DontAdjustForAntialiasing #seems to help fix artifacts left by mouse track markers #make a scene: self.scene = QtGui.QGraphicsScene() #set it to show in the graphicsview window: self.ui.graphicsView.setScene(self.scene) self.items=[QtGui.QGraphicsTextItem(),QtGui.QGraphicsRectItem()]#for squares and indexes that follow mouse self.ui.graphicsView.viewport().installEventFilter(self)#for mouse functions #Setup IO table on right self.ui.tableWidget.resizeColumnToContents(0) self.ui.tableWidget.resizeColumnToContents(1) self.ui.tableWidget.setColumnWidth(2, 50) self.ui.tableWidget.setColumnWidth(3, 40) #setup datagrid and elements: self.Tools = elementList(elementStruct) self.setupDataGrid()#set up rung variables: self.signalConnections() #default: self.currentHW = "Waltech" self.ui.actionPWM.setEnabled(False) self.ui.actionADC.setEnabled(False) f=open(self.__class__.tempName, 'w') f.write("") f.close() def signalConnections(self): #connect signals: self.ui.actionUndo.triggered.connect(self.unDo) self.ui.actionRedo.triggered.connect(self.reDo) self.ui.actionSave_As.triggered.connect(self.saveFileAs) self.ui.actionSave.triggered.connect(self.saveFile) self.ui.actionOpen.triggered.connect(self.openFile) self.ui.actionNew.triggered.connect(self.newFile) self.ui.actionWhatsThis.triggered.connect(self.whatsThis) self.ui.actionCheck_HW_2.triggered.connect(self.checkHW) self.ui.actionUSBHelp.triggered.connect(self.USBHelp) self.ui.actionArduinoMega_IO.triggered.connect(self.ArduinoMegaIOHelp) self.ui.actionArduinoUno_IO.triggered.connect(self.ArduinoUnoIOHelp) self.ui.actionArduinoNano_IO.triggered.connect(self.ArduinoNanoIOHelp) self.ui.actionAbout.triggered.connect(self.AboutHelp) self.ui.infoButton.clicked.connect(self.parseGrid) self.ui.burnButton.clicked.connect(self.burn) #FOR DEBUG BUTTON #self.ui.pushButton.clicked.connect(self.showInfo) #self.ui.pushButton_3.clicked.connect(self.printLadder) ##003## #action group for tool buttons: self.connect(self.ui.actionContNO, QtCore.SIGNAL("triggered()"),lambda who="contNO": self.anyButton(who)) self.connect(self.ui.actionContNC, QtCore.SIGNAL("triggered()"),lambda who="contNC": self.anyButton(who)) self.connect(self.ui.actionCoil, QtCore.SIGNAL("triggered()"),lambda who="Coil": self.anyButton(who)) #self.connect(self.ui.actionCoilNot, QtCore.SIGNAL("triggered()"),lambda who="CoilNot": self.anyButton(who)) self.connect(self.ui.actionaddRung, QtCore.SIGNAL("triggered()"),lambda who="addRung": self.anyButton(who)) self.connect(self.ui.actionWiden, QtCore.SIGNAL("triggered()"),lambda who="Widen": self.anyButton(who)) #self.connect(self.ui.actionORbranch, QtCore.SIGNAL("triggered()"),lambda who="blankOR": self.anyButton(who)) self.connect(self.ui.actionDEL, QtCore.SIGNAL("triggered()"),lambda who="Del": self.anyButton(who)) self.connect(self.ui.actionORwire, QtCore.SIGNAL("triggered()"),lambda who="ORwire": self.anyButton(who)) self.connect(self.ui.actionNarrow, QtCore.SIGNAL("triggered()"),lambda who="Narrow": self.anyButton(who)) #self.connect(self.ui.actionRising, QtCore.SIGNAL("triggered()"),lambda who="Rising": self.anyButton(who)) self.connect(self.ui.actionFalling, QtCore.SIGNAL("triggered()"),lambda who="Fall": self.anyButton(who)) self.connect(self.ui.actionTimer, QtCore.SIGNAL("triggered()"),lambda who="Timer": self.anyButton(who)) self.connect(self.ui.actionCounter, QtCore.SIGNAL("triggered()"),lambda who="Counter": self.anyButton(who)) self.connect(self.ui.actionEquals, QtCore.SIGNAL("triggered()"),lambda who="Equals": self.anyButton(who)) self.connect(self.ui.actionPlus, QtCore.SIGNAL("triggered()"),lambda who="Plus": self.anyButton(who)) self.connect(self.ui.actionMinus, QtCore.SIGNAL("triggered()"),lambda who="Minus": self.anyButton(who)) self.connect(self.ui.actionMove, QtCore.SIGNAL("triggered()"),lambda who="Move": self.anyButton(who)) self.connect(self.ui.actionMult, QtCore.SIGNAL("triggered()"),lambda who="Mult": self.anyButton(who)) self.connect(self.ui.actionGreater, QtCore.SIGNAL("triggered()"),lambda who="Greater": self.anyButton(who)) self.connect(self.ui.actionLessthan, QtCore.SIGNAL("triggered()"),lambda who="Lessthan": self.anyButton(who)) self.connect(self.ui.actionGreaterOrEq, QtCore.SIGNAL("triggered()"),lambda who="GreaterOrEq": self.anyButton(who)) self.connect(self.ui.actionLessOrEq, QtCore.SIGNAL("triggered()"),lambda who="LessOrEq": self.anyButton(who)) self.connect(self.ui.actionPWM, QtCore.SIGNAL("triggered()"),lambda who="PWM": self.anyButton(who)) self.connect(self.ui.actionADC, QtCore.SIGNAL("triggered()"),lambda who="ADC": self.anyButton(who)) self.connect(self.ui.actionDivide, QtCore.SIGNAL("triggered()"),lambda who="Divide": self.anyButton(who)) ##002## #make a actiongroup so tools are exclusive (only one clicked) toolActionGroup = QActionGroup(self.ui.toolBar)#toolbar is named in _ui.py toolActionGroup.addAction(self.ui.actionContNO) toolActionGroup.addAction(self.ui.actionContNC) toolActionGroup.addAction(self.ui.actionCoil) #toolActionGroup.addAction(self.ui.actionCoilNot) toolActionGroup.addAction(self.ui.actionaddRung) toolActionGroup.addAction(self.ui.actionWiden) #toolActionGroup.addAction(self.ui.actionORbranch) toolActionGroup.addAction(self.ui.actionDEL) toolActionGroup.addAction(self.ui.actionORwire) toolActionGroup.addAction(self.ui.actionNarrow) #toolActionGroup.addAction(self.ui.actionRising) toolActionGroup.addAction(self.ui.actionFalling) toolActionGroup.addAction(self.ui.actionTimer) toolActionGroup.addAction(self.ui.actionCounter) toolActionGroup.addAction(self.ui.actionEquals) toolActionGroup.addAction(self.ui.actionPlus) toolActionGroup.addAction(self.ui.actionMinus) toolActionGroup.addAction(self.ui.actionMove) toolActionGroup.addAction(self.ui.actionMult) toolActionGroup.addAction(self.ui.actionGreater) toolActionGroup.addAction(self.ui.actionLessthan) toolActionGroup.addAction(self.ui.actionGreaterOrEq) toolActionGroup.addAction(self.ui.actionLessOrEq) toolActionGroup.addAction(self.ui.actionPWM) toolActionGroup.addAction(self.ui.actionADC) toolActionGroup.addAction(self.ui.actionDivide) toolActionGroup.setExclusive(True) self.connect(self.ui.actionWaltech, QtCore.SIGNAL("triggered()"),lambda HW="Waltech": self.chooseHW(HW)) self.connect(self.ui.actionOpenPLC, QtCore.SIGNAL("triggered()"),lambda HW="OpenPLC": self.chooseHW(HW)) self.connect(self.ui.actionArduinoUno, QtCore.SIGNAL("triggered()"),lambda HW="ArduinoUno": self.chooseHW(HW)) self.connect(self.ui.actionArduinoNano, QtCore.SIGNAL("triggered()"),lambda HW="ArduinoNano": self.chooseHW(HW)) self.connect(self.ui.actionArduinoMega, QtCore.SIGNAL("triggered()"),lambda HW="ArduinoMega": self.chooseHW(HW) ) hwActionGroup = QActionGroup(self.ui.menuDiagnostics) hwActionGroup.addAction(self.ui.actionWaltech) hwActionGroup.addAction(self.ui.actionOpenPLC) hwActionGroup.addAction(self.ui.actionArduinoUno) hwActionGroup.addAction(self.ui.actionArduinoNano) hwActionGroup.addAction(self.ui.actionArduinoMega) def checkmarkHW(self): pass #print "hardware clicked" ##########hardware choosing def chooseHW(self,HW): oldHW = self.currentHW self.currentHW = HW if self.checkForHiIO(HW)==True: #make popup refusing to change self.dialog = popupDialogs.ardIODialog() self.dialog.exec_()# For Modal dialogs self.currentHW = oldHW #change back HW = oldHW if str(HW)=="Waltech": self.ui.actionPWM.setEnabled(False) self.ui.actionADC.setEnabled(False) self.ui.actionWaltech.setChecked(True) if str(HW)=="OpenPLC": self.ui.actionPWM.setEnabled(True) self.ui.actionADC.setEnabled(True) self.ui.actionOpenPLC.setChecked(True) if str(HW)=="ArduinoUno": self.ui.actionPWM.setEnabled(True) self.ui.actionADC.setEnabled(True) self.ui.actionArduinoUno.setChecked(True) if str(HW)=="ArduinoNano": self.ui.actionPWM.setEnabled(True) self.ui.actionADC.setEnabled(True) self.ui.actionArduinoNano.setChecked(True) if str(HW)=="ArduinoMega": self.ui.actionPWM.setEnabled(True) self.ui.actionADC.setEnabled(True) self.ui.actionArduinoMega.setChecked(True) print "Hardware:", HW def checkForHiIO(self,oldHW): #go through grid and look for I higher than 12 for Waltech, 5 for ArduinoUno , 6 for ArduinoNano if self.currentHW == "Waltech" and ( self.checkInputNums() > 12 or self.checkOutputNums() >12 or self.checkADCPWMNs() != [0,0]): print ">>too high number io or have PWM or ADC" return True if self.currentHW == "ArduinoUno" and ( self.checkInputNums() > 5 or self.checkOutputNums() >7 or self.checkADCPWMNs()[0] > 4 or self.checkADCPWMNs()[1] > 2): print ">>too high number io or PWM or ADC" return True if self.currentHW == "ArduinoNano" and ( self.checkInputNums() > 6 or self.checkOutputNums() >8 or self.checkADCPWMNs()[0] > 4 or self.checkADCPWMNs()[1] > 2): print ">>too high number io or PWM or ADC" return True return False def checkADCPWMNs(self): #count up PWMs and ADCs #PWMADC[0] is number pf PWMs #PWMADC[1] is number pf ADCs height = len(self.grid) width = len(self.grid[0]) PWMADC = [0,0] for i in range(height): for j in range(width): if self.grid[i][j].MTorElement != None: print"mtorelement", self.grid[i][j].MTorElement if self.grid[i][j].MTorElement[:3] == 'PWM': PWMADC[0] = PWMADC[0] +1 if self.grid[i][j].MTorElement[:3] == 'ADC': PWMADC[1] = PWMADC[1] +1 print "PWM,ADC ",PWMADC return PWMADC def checkInputNums(self): height = len(self.grid) width = len(self.grid[0]) MaxIONum = 0 for i in range(height): for j in range(width): if self.grid[i][j].ioAssign != None and self.grid[i][j].ioAssign[:3] == 'in_': #print "input: ", self.grid[i][j].ioAssign[3:] if int(self.grid[i][j].ioAssign[3:]) > MaxIONum: MaxIONum = int(self.grid[i][j].ioAssign[3:]) return MaxIONum def checkOutputNums(self): height = len(self.grid) width = len(self.grid[0]) MaxIONum = 0 for i in range(height): for j in range(width): if self.grid[i][j].ioAssign != None and self.grid[i][j].ioAssign[:4] == 'out_': #print "input: ", self.grid[i][j].ioAssign[3:] if int(self.grid[i][j].ioAssign[4:]) > MaxIONum: MaxIONum = int(self.grid[i][j].ioAssign[4:]) return MaxIONum ##########hardware choosing^^^^^ def USBHelp(self): self.dialog = popupDialogs.USBHelpDialog() self.dialog.exec_()# For Modal dialogs def ArduinoUnoIOHelp(self): self.dialog = popupDialogs.ArduinoUnoIOHelpDialog() self.dialog.exec_()# For Modal dialogs def ArduinoNanoIOHelp(self): self.dialog = popupDialogs.ArduinoNanoIOHelpDialog() self.dialog.exec_()# For Modal dialogs def ArduinoMegaIOHelp(self): self.dialog = popupDialogs.ArduinoMegaIOHelpDialog() self.dialog.exec_()# For Modal dialogs def AboutHelp(self): self.dialog = popupDialogs.AboutHelpDialog() self.dialog.exec_()# For Modal dialogs def checkHW(self): plat = sys.platform.lower() # try to detect the OS so that a device can be selected... print "checked platform" if plat[:5] == 'linux': opSys = "NIX" elif plat == 'win32': opSys = "WIN" elif plat == "darwin": opSys = "MAC" else: opSys = "WIN" tester(opSys,self.currentHW).test1(self.ui.textBrowser) def printLadder(self): #printer = QPrinter(QPrinter.HighResolution) printer = QPrinter() dialog = QtGui.QPrintDialog(printer, self) if dialog.exec_() != QDialog.Accepted: return #printer.setResolution(600) #resolution = printer.resolution() #pageRect = printer.pageRect() painter = QPainter(printer) self.scene.render(painter) #self.ui.tableWidget.render(painter) del painter def makeImage(self): #def printLadder(self): image = QtGui.QImage(400,400,QtGui.QImage.Format_ARGB32)#for png #image = QtGui.QImage(256,256,QtGui.QImage.Format_RGB32) painter = QtGui.QPainter(image) painter.setRenderHint(QtGui.QPainter.Antialiasing) self.scene.render(painter) painter.end() print "saving image" if image.save('hexes/newImage.png', 'PNG'): print('saved') else: print("didn't save") #image.save("out.png") del painter def setupDataGrid(self): #x,y, element there, rung there, & there, element name, variable name, i/o connection. self.grid = [[]] # grid: list of rows ex: grid [2][6] gives cell 6 in row(rung) 2 self.reDoGrid = [[[]]]# list of grids for redo self.unDoGrid = [[[]]]# list of grids for undo self.currentTool = 0 #to track the tool being used width=10 for i in range(width):#fill the first row self.grid[0].append(cellStruct(i*60, 60, "MT","Rung", None, None, None, None, False, False, False, False, False, False,None,None,None,None,None)) for i in range(1,6):# add 5 more rungs to start ManageGrid(self.grid, self.scene,self.Tools,self.items).insertRung(i) def reFillList(self,uiList): #clear list while uiList.rowCount() > 0 : uiList.removeRow(0) #rows = uiList.rowCount() #for i in range(rows): # #delete this row # uiList.removeRow(0) #refill list print "refilling list" height = len(self.grid) width = len(self.grid[0]) for i in range(height): for j in range(width): if self.grid[i][j].MTorElement != "MT" and self.grid[i][j].MTorElement !="blankOR": uiList.setSortingEnabled(False)#stop sorting while adding row uiList.setRowCount(uiList.rowCount()+1) numRows= uiList.rowCount() try: uiList.setItem(numRows-1,0,QtGui.QTableWidgetItem(self.grid[i][j].variableName)) except: pass try: uiList.setItem(numRows-1,1,QtGui.QTableWidgetItem(self.grid[i][j].ioAssign)) except: pass try: uiList.setItem(numRows-1,2,QtGui.QTableWidgetItem(self.grid[i][j].MTorElement)) except: pass try: uiList.setItem(numRows-1,3,QtGui.QTableWidgetItem(str(i)+","+str(j))) except: pass uiList.setSortingEnabled(True) #track which tool is being used. maybe use names here? def anyButton(self,who): self.currentTool = who #print who def parseGrid(self): #self.showInfo() font=self.ui.textBrowser.currentFont() font.setWeight(QFont.Bold) self.ui.textBrowser.setCurrentFont(font) self.ui.textBrowser.setText("compiling with avr-gcc") QApplication.processEvents()#this makes the UI update before going on. font.setWeight(QFont.Normal) self.ui.textBrowser.setCurrentFont(font) QApplication.processEvents()#this makes the UI update before going on. outLine = ladderToOutLine(self.grid).makeOutLine() OutLineToC(self.grid,self.currentHW).makeC(outLine,self.ui.textBrowser, "C") #hexMaker(self).self.saveCfileAndCompile(C_txt,displayOutputPlace) def burn(self): #self.showInfo() font=self.ui.textBrowser.currentFont() font.setWeight(QFont.Bold) self.ui.textBrowser.setCurrentFont(font) self.ui.textBrowser.setText("compiling with avr-gcc") QApplication.processEvents()#this makes the UI update before going on. font.setWeight(QFont.Normal) self.ui.textBrowser.setCurrentFont(font) QApplication.processEvents()#this makes the UI update before going on. outLine = ladderToOutLine(self.grid).makeOutLine() OutLineToC(self.grid,self.currentHW).makeC(outLine,self.ui.textBrowser, "B") def showInfo(self): """ ManageGrid(self.grid, self.scene,self.Tools,self.items).reportCellInfo() ManageGrid(self.grid, self.scene,self.Tools,self.items).findStartsAndEnds() ManageGrid(self.grid, self.scene,self.Tools,self.items).reportCellStartsEnds() """ def unDo(self): if len(self.unDoGrid)>1: self.reDoGrid.append(copy.deepcopy(self.grid))#save this grid for re-do self.grid = copy.deepcopy(self.unDoGrid[-1])#make current grid last one in undo self.unDoGrid.pop()#delete last one in undo ManageGrid(self.grid, self.scene,self.Tools,self.items).totalRedraw() print("undone") else: print("no more undoes") def reDo(self): if len(self.reDoGrid)>0: self.unDoGrid.append(copy.deepcopy(self.grid))#save this grid for re-do if len(self.unDoGrid) >20:#limit to 20 undos self.unDoGrid.pop(0)#pop 0 self.grid = copy.deepcopy(self.reDoGrid[-1]) self.reDoGrid.pop() ManageGrid(self.grid, self.scene,self.Tools,self.items).totalRedraw() print("redone") else: print("no more redoes") def newFile(self): #verify popup self.clearList(self.ui.tableWidget) self.setupDataGrid()#set up rung variables: def saveGlobal(self): f=open(self.__class__.tempName, 'w') f.write(self.__class__.currentFileDir + "\n" + self.__class__.projectName) f.close() def saveFile(self): if self.__class__.projectName == None: format = "wlm" initialPath = os.getcwd() + "/untitled." + format; filename = QtGui.QFileDialog.getSaveFileName(self, 'Save As',initialPath) if filename == "": return self.__class__.currentFileDir=ntpath.dirname(str(filename)) self.__class__.projectName = filename self.saveGlobal() else: filename = self.__class__.projectName print "filename", filename f = open(filename, 'w') gridToSave = copy.deepcopy(self.grid) gridToSave.insert(0,self.currentHW)#put current hardware in list at 0 pickle.dump(gridToSave, f) f.close() def saveFileAs(self): format = "wlm" if self.__class__.currentFileDir == None: initialPath = os.getcwd() + "/untitled." + format; else: initialPath = self.__class__.currentFileDir + "untitled." + format; filename = QtGui.QFileDialog.getSaveFileName(self, 'Save As',initialPath) self.__class__.currentFileDir = ntpath.dirname(str(filename)) self.__class__.projectName = filename self.saveGlobal() print "filename", filename if filename == "": return f = open(str(filename), 'w') gridToSave = copy.deepcopy(self.grid) gridToSave.insert(0,self.currentHW)#put current hardware in list at 0 pickle.dump(gridToSave, f) f.close() def openFile(self): filedialog = QtGui.QFileDialog() #filedialog.setNameFilter('*.jpg') filename = filedialog.getOpenFileName(self, 'Open File', os.path.expanduser("~"),"*.wlm") if filename == "": return f = open(str(filename), 'r') justName = ntpath.basename(str(filename)) self.__class__.currentFileDir = ntpath.dirname(str(filename)) self.__class__.projectName = filename self.saveGlobal() print "self.currentFileDir:", self.__class__.currentFileDir print "self.projectName:", self.__class__.projectName self.grid = pickle.load(f) f.close() self.currentHW = self.grid.pop(0)#get current hardware from file print self.currentHW self.chooseHW(self.currentHW) #check width and height, make bounding box ManageGrid(self.grid, self.scene,self.Tools,self.items).changeRectangle() try: ManageGrid(self.grid, self.scene,self.Tools,self.items).totalRedraw() except: self.dialog = popupDialogs.wrongVersionDialog() self.dialog.exec_()# For Modal dialogs self.setupDataGrid() else: self.reFillList(self.ui.tableWidget) def whatsThis(self): QtGui.QWhatsThis.enterWhatsThisMode() def eventFilter(self, source, event): if event.type() == QtCore.QEvent.MouseMove: self.eraseMarker() cellNum = self.findCell(event) self.showMarker(cellNum) elif event.type() == QtCore.QEvent.Leave or event.type() == QtCore.QEvent.Wheel: self.eraseMarker() elif event.type() == QtCore.QEvent.MouseButtonPress: self.eraseMarker() cellNum = self.findCell(event) if cellNum != [None,None,None,None]: if event.button() == QtCore.Qt.LeftButton: print "left" self.leftClick(cellNum) elif event.button() == QtCore.Qt.RightButton: print "right" self.rightClick(cellNum) #if cellNum == [None,None,None,None]: else: pass # do other stuff return QtGui.QMainWindow.eventFilter(self, source, event) #self.ui.graphicsView.viewport().installEventFilter(self) def findCell(self,event): #Pos = event.globalPos() #doesn't stay when window moves #Pos = event.pos()# offset -60,-50 #Pos = self.ui.graphicsView.mapToScene(event.globalPos()) #doesn't stay when window moves Pos = self.ui.graphicsView.mapToScene(event.pos()) #things that don't work: #Pos = event.screenPos() #Pos = self.ui.graphicsView.mapToScene(event.screenPos()) #Qmousevent has no attribute screenPos #Pos = event.scenePos() #Pos = self.ui.graphicsView.mapToScene(event.scenePos()) #Qmousevent has no attribute scenePos #x=Pos.x()-172 x=Pos.x() -30 y=Pos.y() +60 self.ui.label_2.setNum(x)# set x,y display values self.ui.label_4.setNum(y) if 1 == 1:#disabled if #pos = self.ui.graphicsView.mapToScene(event.pos()) #pos = event.pos() #x = pos.x()-30 #y = pos.y()+60 cellNum = [None,None,None,None] for i in range(len(self.grid)): #cellNum[0]=i #backwards: row,col for j in range(len(self.grid[i])): if (self.grid[i][j].midPointX-30< x < self.grid[i][j].midPointX+30) and (self.grid[i][j].midPointY-30< y< self.grid[i][j].midPointY+30): cellNum = [i,j,None,None] if y<self.grid[cellNum[0]][cellNum[1]].midPointY: #insert above cellNum[2] = "up" else:#insert below cellNum[2] = "dn" if x<self.grid[cellNum[0]][cellNum[1]].midPointX: #insert left or right cellNum[3] = "rt" else: cellNum[3] = "lt" return cellNum def eraseMarker(self): itemlist = self.scene.items() #this is a list of ALL items in the scene for k in range(len(itemlist)): #compare to items placed last mousemove if itemlist[k] == self.items[0]: self.scene.removeItem(self.items[0]) if itemlist[k] == self.items[1]: self.scene.removeItem(self.items[1]) #puts a box around cell or marks or wire, or rung insert spot. called by mouse move in event filter def showMarker(self, cellNum): i=cellNum[0] j=cellNum[1] #see if the item was deleted elsewhere, like by scene.clear() #self.eraseMarker() if cellNum != [None,None,None,None]: #Optional: Don't show mouse pointer on graphiscview #self.ui.graphicsView.viewport().setCursor(QtCore.Qt.BlankCursor ) #show cell numbers: if self.currentTool != "addRung": self.items[0] = QtGui.QGraphicsTextItem("%d, %d" %(i,j)) self.items[0].setPos(self.grid[i][j].midPointX+35,self.grid[i][j].midPointY-35) self.scene.addItem(self.items[0]) #go through elementList and see which tool is being used if self.currentTool == "addRung": if cellNum[2] =="up" and cellNum[0] == 0: x=self.grid[i][j].midPointX y=self.grid[i][j].midPointY-90 else: x=self.grid[i][j].midPointX y=self.grid[i][j].midPointY-30 #y=self.grid[i][j].midPointY-90 w=200 h=1 self.items[1] = QtGui.QGraphicsRectItem(x-100,y,w,h) self.items[1].setPen(QtGui.QColor("blue")) self.scene.addItem(self.items[1]) self.items[0] = QtGui.QGraphicsTextItem("< >") self.items[0].setPos(self.grid[i][j].midPointX-111,y-15) self.items[0].setFont(QtGui.QFont("Arial",16)) self.items[0].setDefaultTextColor(QtGui.QColor("blue")) self.scene.addItem(self.items[0]) elif self.currentTool == "Widen": x=self.grid[i][j].midPointX y=self.grid[i][j].midPointY-90 w=1 h=62 self.items[1] = QtGui.QGraphicsRectItem(x,y,w,h) self.items[1].setPen(QtGui.QColor("blue")) self.scene.addItem(self.items[1]) elif self.currentTool == "ORwire": if cellNum[2] =="up": y=self.grid[i][j].midPointY-120 if cellNum[2] =="dn": y=self.grid[i][j].midPointY-60 x=self.grid[i][j].midPointX #y=self.grid[i][j].midPointY-60 w=1 h=60 self.items[1] = QtGui.QGraphicsRectItem(x,y,w,h) self.items[1].setPen(QtGui.QColor("blue")) self.scene.addItem(self.items[1]) elif self.currentTool == "blankOR": #"blankOR" 5 pixmap = QtGui.QPixmap(_fromUtf8(":/icons/icons/OR_big.png")) self.items[1] = QtGui.QGraphicsPixmapItem(pixmap) x=self.grid[i][j].midPointX y=self.grid[i][j].midPointY-60 self.items[1].setPos(x,y) self.scene.addItem(self.items[1]) else: #show box around cell: x=self.grid[i][j].midPointX y=self.grid[i][j].midPointY-90 w=58 h=58 self.items[1] = QtGui.QGraphicsRectItem(x,y,w,h) self.items[1].setPen(QtGui.QColor("blue")) self.scene.addItem(self.items[1]) def rightClick(self, cellNum): if cellNum != [None,None,None,None]: tool = self.grid[cellNum[0]][cellNum[1]].MTorElement clickSuccssful = False #update undo/redo stack here del self.reDoGrid[:]#first clear re-do satck self.unDoGrid.append(copy.deepcopy(self.grid))#save a copy(list) of this grid for undo if len(self.unDoGrid) >30:#limit to 30 undos self.unDoGrid.pop(0)#pop 0 #run popup: tempCellData = self.runPopup(tool,cellNum) if tempCellData != False:# Yes, new data entered, so update list at right: orphan = False if self.grid[cellNum[0]][cellNum[1]].variableName != tempCellData.variableName:#check if leaving orphan names orphan = ManageGrid(self.grid, self.scene, self.Tools,self.items).checkOrphanName(cellNum) if orphan == False: #update cell: ##014## """ #check that name is OK if not re.match(r'^[a-zA-Z0-9_]+$', tempCellData.variableName): print "bad name" self.grid[cellNum[0]][cellNum[1]].variableName = "rename_this" else: self.grid[cellNum[0]][cellNum[1]].variableName = tempCellData.variableName print "varname:", tempCellData.variableName """ self.grid[cellNum[0]][cellNum[1]].variableName = tempCellData.variableName print "varname:", tempCellData.variableName self.grid[cellNum[0]][cellNum[1]].comment = tempCellData.comment print "comment:", tempCellData.comment self.grid[cellNum[0]][cellNum[1]].ioAssign = tempCellData.ioAssign print "ioassign:", tempCellData.ioAssign self.grid[cellNum[0]][cellNum[1]].setPoint = tempCellData.setPoint print "setpoint:", tempCellData.setPoint self.grid[cellNum[0]][cellNum[1]].source_A = tempCellData.source_A print "source_A:", tempCellData.source_A self.grid[cellNum[0]][cellNum[1]].source_B = tempCellData.source_B print "source_B:", tempCellData.source_B self.grid[cellNum[0]][cellNum[1]].const_A = tempCellData.const_A print "const_A:", tempCellData.const_A self.grid[cellNum[0]][cellNum[1]].const_B = tempCellData.const_B print "const_B:", tempCellData.const_B self.grid[cellNum[0]][cellNum[1]].functType = tempCellData.functType #not used print "functType:", tempCellData.functType #not used clickSuccssful = True #>>>>>cleanup and redraw: if clickSuccssful == False: print("nothing done") self.unDoGrid.pop()#delete last one in undo ManageGrid(self.grid, self.scene, self.Tools,self.items).totalRedraw() self.reFillList(self.ui.tableWidget) def leftClick(self, cellNum): #this def is a specific one, automatically connected to mousePressEvent in UI if cellNum != [None,None,None,None]:#mouse click was located in cells #variable bridge from findng position (todo: change this): if cellNum[2] == "up":UpDwn = 0 if cellNum[2] == "dn":UpDwn = 1 if cellNum[3] == "rt":RtLft = 1 if cellNum[3] == "lt":RtLft = 0 clickSuccssful = False #will be set to true if an action is taken, allows undo to be rolled back of not #update undo/redo stack here del self.reDoGrid[:]#first clear re-do satck self.unDoGrid.append(copy.deepcopy(self.grid))#save a copy(list) of this grid for undo if len(self.unDoGrid) >30:#limit to 30 undos self.unDoGrid.pop(0)#pop 0 #go through elementList and see which tool is being used numTools = len(self.Tools.toolList) toolToPlace = ("0",0)#name and index of tool in toolList for i in range(0,numTools): if self.Tools.toolList[i].toolName == self.currentTool: toolToPlace = (self.Tools.toolList[i].toolName,i) print("tool #: %d" %(toolToPlace[1])) #>>>>>↓↓↓ELEMENT PLACEMENT↓↓↓<<<<<<<<< #>>>>place Element on rung: if self.Tools.toolList[toolToPlace[1]].toolType == "Element"\ and self.grid[cellNum[0]][cellNum[1]].rungOrOR != "OR": #tool to place is an elememt, (not widen or add rung) #>>>>place non-coil Element on rung: if self.Tools.toolList[toolToPlace[1]].position == "any": if self.grid[cellNum[0]][cellNum[1]].MTorElement == "MT"\ and cellNum[1] != len(self.grid[cellNum[0]])-1: #not at the far right # cause popup dialog tempCellInfo = self.runPopup(toolToPlace[0],cellNum) if tempCellInfo != False: #update list at right #self.addToList(self.ui.tableWidget,tempCellInfo,(cellNum[0],cellNum[1])) #place element on grid ManageGrid(self.grid, self.scene, self.Tools,self.items)\ .placeElememt(cellNum,tempCellInfo,toolToPlace) clickSuccssful = True #>>element that should shift to right if "right" (coil, timerreset..) elif self.Tools.toolList[toolToPlace[1]].position == "right": cellNum[1] = len(self.grid[0])-1 #right most spot if self.grid[cellNum[0]][cellNum[1]].MTorElement == "MT": # cause popup dialog tempCellInfo = self.runPopup(toolToPlace[0],cellNum) if tempCellInfo != False: #update list at right #self.addToList(self.ui.tableWidget,tempCellInfo,(cellNum[0],cellNum[1])) #place element on grid ManageGrid(self.grid, self.scene, self.Tools,self.items)\ .placeElememt(cellNum,tempCellInfo,toolToPlace) clickSuccssful = True #>>>>place Element on OR: if self.Tools.toolList[toolToPlace[1]].toolType == "Element"\ and self.grid[cellNum[0]][cellNum[1]].MTorElement == "blankOR": if self.Tools.toolList[toolToPlace[1]].position == "any": # cause popup dialog tempCellInfo = self.runPopup(toolToPlace[0],cellNum) if tempCellInfo != False: ManageGrid(self.grid, self.scene, self.Tools,self.items)\ .placeElememt(cellNum,tempCellInfo,toolToPlace) clickSuccssful = True #>>element only allowed on rt (coil, timerreset..) elif self.Tools.toolList[toolToPlace[1]].position == "right": cellNum[1] = len(self.grid[0])-1 #right most spot print ("elemnt to right") if self.grid[cellNum[0]][cellNum[1]].MTorElement == "blankOR": tempCellInfo = self.runPopup(toolToPlace[0],cellNum)# cause popup dialog if tempCellInfo != False: ManageGrid(self.grid, self.scene, self.Tools,self.items)\ .placeElememt(cellNum,tempCellInfo,toolToPlace) clickSuccssful = True #>>>>↑↑↑ELEMENT PLACEMENT↑↑↑<<<<< #>>>>>addRung: if self.Tools.toolList[toolToPlace[1]].toolName == "addRung": Ypos = cellNum[0] + UpDwn print "upDwn", UpDwn ManageGrid(self.grid, self.scene, self.Tools,self.items).insertRung(Ypos) clickSuccssful = True #>>>>>Widen: elif self.Tools.toolList[toolToPlace[1]].toolName == "Widen": #cellNum[1] = cellNum[1] + RtLft ManageGrid(self.grid, self.scene, self.Tools,self.items).Widen(cellNum) clickSuccssful = True #>>>>>addOR: elif self.Tools.toolList[toolToPlace[1]].toolName == "blankOR": cellNum[0] = cellNum[0] + UpDwn #cellNum[1] = cellNum[1] - RtLft #adjust for right or left clickage of cell if cellNum[1]< 0:# don't add off left cellNum[1] = 0 if cellNum[0] <1: cellNum[0]= 1#don't add an OR above ManageGrid(self.grid, self.scene, self.Tools,self.items).insertBlankOR(cellNum) clickSuccssful = True print("blank OR added") #>>>>>addORwire: elif self.Tools.toolList[toolToPlace[1]].toolName == "ORwire": cellNum[0] = cellNum[0] + UpDwn #cellNum[1] = cellNum[1] - RtLft #adjust for right or left clickage of cell if cellNum[1]< 0:# don't add off left cellNum[1] = 0 if cellNum[0] <1: cellNum[0]= 1#don't add an OR above ManageGrid(self.grid, self.scene, self.Tools,self.items).addWire(cellNum) clickSuccssful = True print("wire placed") #>>>>>Delete: elif self.Tools.toolList[toolToPlace[1]].toolName == "Del": #loc = (cellNum[0],cellNum[1]) if ManageGrid(self.grid, self.scene, self.Tools,self.items).checkOrphanName(cellNum)==False: #delete element on OR branch: if self.grid[cellNum[0]][cellNum[1]].rungOrOR == "OR"\ and self.grid[cellNum[0]][cellNum[1]].MTorElement != "MT"\ and self.grid[cellNum[0]][cellNum[1]].MTorElement != "blankOR": ManageGrid(self.grid, self.scene, self.Tools,self.items).Delete(cellNum) #delete of element on Rung or delete the rung: elif self.grid[cellNum[0]][cellNum[1]].rungOrOR == "Rung": ManageGrid(self.grid, self.scene, self.Tools,self.items).Delete(cellNum) clickSuccssful = True #>>>>>Shrink elif self.Tools.toolList[toolToPlace[1]].toolName == "Narrow": #self.ui.graphicsView.prepareGeometryChange() ManageGrid(self.grid, self.scene, self.Tools,self.items).Shrink(cellNum)#then do function to narrow if can #>>>>>cleanup and redraw: if clickSuccssful == False: print("nothing done") self.unDoGrid.pop()#delete last one in undo ManageGrid(self.grid, self.scene, self.Tools,self.items).totalRedraw() self.showInfo() self.reFillList(self.ui.tableWidget) #will run popup and return tempCellData with all info from popup #send tool being used, cellNum #doesn't do anything with the grid. def runPopup(self, tool, cellNum): popUpOKed = False #becomes true if dialog is OK'ed tempCellInfo = cellStruct(None,None,None,None,None,None,None,None, False, False, False, False, False, False,None,None,None,None,None) ##004## if tool == "Coil" or tool =="CoilNot":#do dialog for this tool: self.dialog = popupDialogs.CoilDialog(self.grid, cellNum,self.currentHW) popUpOKed = self.dialog.exec_()# For Modal dialogs elif tool == "contNO" or tool =="contNC":#do dialog for this tool: self.dialog = popupDialogs.ContDialog(self.grid, cellNum,self.currentHW) popUpOKed = self.dialog.exec_()# For Modal dialogs elif tool == "Rising" or tool =="Fall":#do dialog for this tool: self.dialog = popupDialogs.EdgeDialog(self.grid, cellNum,self.currentHW) popUpOKed = self.dialog.exec_()# For Modal dialogs elif tool == "Timer" :#do dialog for this tool: self.dialog = popupDialogs.TimerDialog(self.grid, cellNum,self.currentHW) popUpOKed = self.dialog.exec_()# For Modal dialogs elif tool == "Counter" :#do dialog for this tool: self.dialog = popupDialogs.CounterDialog(self.grid, cellNum,self.currentHW) popUpOKed = self.dialog.exec_()# For Modal dialogs elif tool == "Plus"or tool =="Minus"or tool =="Divide"or tool =="Mult" or tool == "Move" :#do dialog for this tool: self.dialog = popupDialogs.MathDialog(self.grid, cellNum,self.currentHW,tool) popUpOKed = self.dialog.exec_()# For Modal dialogs elif tool == "Equals" or tool =="Greater"or tool =="Lessthan"or tool =="GreaterOrEq"or tool =="LessOrEq":#do dialog for this tool: self.dialog = popupDialogs.CompairDialog(self.grid, cellNum,self.currentHW,tool) popUpOKed = self.dialog.exec_()# For Modal dialogs #elif tool == "Move" :#do dialog for this tool: # self.dialog = popupDialogs.MoveDialog(self.grid, cellNum,self.currentHW) # popUpOKed = self.dialog.exec_()# For Modal dialogs elif tool == "PWM" :#do dialog for this tool: self.dialog = popupDialogs.PWMDialog(self.grid, cellNum,self.currentHW) popUpOKed = self.dialog.exec_()# For Modal dialogs elif tool == "ADC" :#do dialog for this tool: self.dialog = popupDialogs.ADCDialog(self.grid, cellNum,self.currentHW) popUpOKed = self.dialog.exec_()# For Modal dialogs #Equals Greater Lessthan GreaterOrEq LessOrEq Plus Minus Divide Mult Move PWM ADC if popUpOKed == True: ##008## # get all info from popup: try: tempCellInfo.ioAssign = self.dialog.ui.comboBox.currentText()#I/O assign except: pass try: tempCellInfo.variableName = self.dialog.ui.comboBox_2.currentText()#variable Name except: pass else: #check that name is OK if not re.match(r'^[a-zA-Z0-9_]+$', tempCellInfo.variableName): print "bad name" tempCellInfo.variableName = "please_rename" try: tempCellInfo.comment = self.dialog.ui.lineEdit.text()#comment except: pass try: tempCellInfo.setPoint = self.dialog.ui.doubleSpinBox.value() #setpoint decimal except: pass try: tempCellInfo.setPoint = self.dialog.ui.spinBox.value() #setpoint integer except: pass #try: tempCellInfo.ioAssign = self.dialog.ui.comboBox.currentText() #except: pass #for comparison operators: try: tempCellInfo.source_A = self.dialog.ui.comboBox_A.currentText() except: pass try: tempCellInfo.source_B = self.dialog.ui.comboBox_B.currentText() except: pass try: tempCellInfo.const_A = self.dialog.ui.spinBox_A.value() except: pass try: tempCellInfo.const_B = self.dialog.ui.spinBox_B.value() except: pass tempCellInfo.MTorElement = tool return tempCellInfo else: return False
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui_controller = Ui_MainWindow() self.ui_controller.setupUi(self) self.connect() self.ui_controller.matplotlibWidget.connect() self.init_style_menu() self.init_indicator_menu() self.init_strategy_panel() self.ui_controller.dateStartEdit.setDateTime(datetime(1990,1,1)) self.ui_controller.dateEndEdit.setDateTime(datetime.now()) self.df = None def init_style_menu(self): self.ui_controller.styleMenu = QtGui.QMenu(self) self.ui_controller.lineChartAction = QtGui.QAction("Line", self) self.ui_controller.areaChartAction = QtGui.QAction("Area", self) self.ui_controller.barChartAction = QtGui.QAction("Bar", self) self.ui_controller.candleChartAction = QtGui.QAction("Candle", self) self.ui_controller.styleMenu.addAction(self.ui_controller.lineChartAction) self.ui_controller.styleMenu.addAction(self.ui_controller.areaChartAction) self.ui_controller.styleMenu.addAction(self.ui_controller.barChartAction) self.ui_controller.styleMenu.addAction(self.ui_controller.candleChartAction) self.ui_controller.styleToolButton.setMenu(self.ui_controller.styleMenu) def init_indicator_menu(self): self.ui_controller.indicatorMenu = QtGui.QMenu(self) self.ui_controller.indicator_SMAAction = QtGui.QAction("Simple Moving Average (SMA)", self) self.ui_controller.indicator_EMAAction = QtGui.QAction("Exponential Moving Average (EMA)", self) self.ui_controller.indicator_MACDAction = QtGui.QAction("MACD", self) self.ui_controller.indicator_RSIAction = QtGui.QAction("Relative Strength Index (RSI)", self) self.ui_controller.indicatorMenu.addAction(self.ui_controller.indicator_SMAAction) self.ui_controller.indicatorMenu.addAction(self.ui_controller.indicator_EMAAction) self.ui_controller.indicatorMenu.addAction(self.ui_controller.indicator_MACDAction) self.ui_controller.indicatorMenu.addAction(self.ui_controller.indicator_RSIAction) self.ui_controller.indicatorToolButton.setMenu(self.ui_controller.indicatorMenu) def init_strategy_panel(self): strategy_files = sorted(glob.glob('%s/*.py' % strategy_path)) for file in strategy_files: base = os.path.splitext(os.path.basename(file))[0] item = QtGui.QListWidgetItem(base, self.ui_controller.strategyListWidget) item.setData(QtCore.Qt.UserRole, QtCore.QVariant(file)) self.ui_controller.strategyListWidget.addItem(item) self.ui_controller.strategyListWidget.customContextMenuRequested.connect(self.showMenu) def connect(self): for toolButton in self.ui_controller.buttonGroup.buttons(): toolButton.clicked.connect(partial(self.on_toolButtonClicked, toolButton)) self.ui_controller.actionRunStrategy.triggered.connect(self.on_runStrategy) self.ui_controller.actionEditStrategy.triggered.connect(self.on_editStrategy) self.ui_controller.symbolLineEdit.returnPressed.connect(self.load_symbol) self.ui_controller.symbolLineEdit.textChanged.connect(self.on_symbolEditChanged) def on_loadQuoteClicked(self): logger.info('load quote') fileName = QtGui.QFileDialog.getOpenFileName( self, self.tr("Open Quote Data"), data_path, self.tr("Quote Files (*.csv)")) logger.info("Filename %s" % fileName) if os.path.isfile(fileName): df = pd.read_csv(unicode(fileName)) df.columns = [col.lower() for col in df.columns] if 'datetime' in df.columns: df = df.sort(['datetime']) df['datetime'] = df.apply( lambda row: mdates.date2num(parser.parse(row['datetime'])), axis=1) elif 'date' in df.columns: df = df.sort(['date']) df['datetime'] = df.apply( lambda row: mdates.date2num(parser.parse(row['date'])), axis=1) if 'datetime' in df.columns and not df['datetime'].empty: self.ui_controller.matplotlibWidget.set_data(df) self.ui_controller.matplotlibWidget.draw_data() self.df = df def on_toolButtonClicked(self, button): name = str(button.objectName()) button_values = { 'oneDayToolButton': WindowSize.ONEDAY, 'fiveDayToolButton': WindowSize.FIVEDAY, 'oneMonthToolButton': WindowSize.ONEMONTH, 'threeMonthToolButton': WindowSize.THREEMONTH, 'sixMonthToolButton': WindowSize.SIXMONTH, 'oneYearToolButton': WindowSize.ONEYEAR, 'twoYearToolButton': WindowSize.TWOYEAR, 'fiveYearToolButton': WindowSize.FIVEYEAR, 'maxToolButton': WindowSize.MAX, } size = button_values[name] self.ui_controller.matplotlibWidget.setxlim(size) def showMenu(self, position): indexes = self.ui_controller.strategyListWidget.selectedIndexes() if len(indexes) > 0: menu = QtGui.QMenu() menu.addAction(self.ui_controller.actionRunStrategy) menu.addAction(self.ui_controller.actionEditStrategy) menu.exec_(self.ui_controller.strategyListWidget.viewport().mapToGlobal(position)) def on_runStrategy(self, check): indexes = self.ui_controller.strategyListWidget.selectedIndexes() if len(indexes) > 0: logger.info('Run strategy') index = indexes[0].row() item = self.ui_controller.strategyListWidget.item(index) strategy_file = str(item.data(QtCore.Qt.UserRole).toPyObject()) strategy = imp.load_source('strategy', strategy_file) if hasattr(strategy, 'initialize') and hasattr(strategy, 'run'): runner = StrategyRunner(initialize=strategy.initialize, run=strategy.run) runner.run(self.df) else: logger.error("%s is not a valid strategy" % strategy_file) def on_editStrategy(self, check): indexes = self.ui_controller.strategyListWidget.selectedIndexes() if len(indexes) > 0: logger.info('Edit strategy') index = indexes[0].row() item = self.ui_controller.strategyListWidget.item(index) strategy_file = item.data(QtCore.Qt.UserRole).toPyObject() sysopen(strategy_file) def on_symbolEditChanged(self, text): if text: self.ui_controller.symbolLineEdit.setText(str(text).upper()) def load_symbol(self): start = parser.parse(str(self.ui_controller.dateStartEdit.text())) end = parser.parse(str(self.ui_controller.dateEndEdit.text())) symbol = str(self.ui_controller.symbolLineEdit.text()) if not symbol: return data = _load_raw_yahoo_data(stocks=[symbol], indexes={}, start=start, end=end) self.df = data[symbol] self.df.columns = [col.lower() for col in self.df.columns] self.df['datetime'] = self.df.index self.df['datetime'] = self.df.apply( lambda row: mdates.date2num(row['datetime']), axis=1) if 'adj close' in self.df.columns: self.df['close'] = self.df['adj close'] self.ui_controller.matplotlibWidget.set_data(self.df) self.ui_controller.matplotlibWidget.draw_data() self.ui_controller.symbolLineEdit.setText('')
""" Main module for PyReddit """ from mainwindow_ui import Ui_MainWindow from PyQt4 import QtGui if __name__ == "__main__": import sys APP = QtGui.QApplication(sys.argv) MAIN_WIN = QtGui.QMainWindow() UI = Ui_MainWindow() UI.setupUi(MAIN_WIN) MAIN_WIN.show() sys.exit(APP.exec_())
class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.docsModel = QSqlTableModel() # self.docsModel = QSqlRelationalTableModel() self.docsModel.setTable('DOCUMENTS') # self.docsModel.setRelation(2, QSqlRelation('THEMES', 'ID', 'NAME')) self.docsModel.setEditStrategy(QSqlTableModel.OnManualSubmit) self.docsModel.select() self.docsModel.setHeaderData(1, Qt.Horizontal, "Путь к файлу") self.docsModel.setHeaderData(2, Qt.Horizontal, "Тема") self.ui.docsView.setModel(self.docsModel) # self.ui.docsView.setItemDelegate(QSqlRelationalDelegate(self.ui.docsView)) self.ui.docsView.horizontalHeader().setStretchLastSection(True) self.updateThemes() self.ui.themes.header().setStretchLastSection(True) self.ui.themes.setHeaderHidden(True) self.ui.themes.itemSelectionChanged.connect(self.themes_selectionChanged) self.ui.themes.setCurrentItem(self.root_theme) self.ui.actionQuit.triggered.connect(self.close) self.ui.actionAdd.triggered.connect(self.add) self.ui.actionDelete.triggered.connect(self.delete) self.read_settings() def themes_selectionChanged(self): item = self.ui.themes.currentItem() if item: if item is self.root_theme: self.docsModel.setFilter(None) else: # pid = item.data(0, Qt.UserRole)[0] # self.docsModel.setFilter('ID_THEME = {}'.format(pid)) name = item.data(0, Qt.UserRole)[1] self.docsModel.setFilter('THEME = "{}"'.format(name)) def updateThemes(self): self.ui.themes.clear() self.root_theme = QTreeWidgetItem(['Все темы']) self.ui.themes.addTopLevelItem(self.root_theme) query = QSqlQuery() query.exec_('SELECT ID, NAME FROM THEMES') while query.next(): pid = query.value(0) name = query.value(1) child = QTreeWidgetItem([name]) child.setData(0, Qt.UserRole, [pid, name]) self.root_theme.addChild(child) self.ui.themes.expandAll() def add(self): d = DocDialog() d.exec_() # TODO: обновлять когда диалог закрывается на Ок self.docsModel.select() def delete(self): pass def read_settings(self): ini = QSettings('settings.ini') self.restoreGeometry(ini.value('MainWindow_Geometry')) self.restoreState(ini.value('MainWindow_State')) self.ui.splitter.restoreState(ini.value('Splitter_State')) def write_settings(self): ini = QSettings('settings.ini') ini.setValue('MainWindow_State', self.saveState()) ini.setValue('MainWindow_Geometry', self.saveGeometry()) ini.setValue('Splitter_State', self.ui.splitter.saveState()) def closeEvent(self, *args, **kwargs): self.write_settings() super().closeEvent(*args, **kwargs)
class MainWindow(QMainWindow, QObject): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('vk_chat_bot') # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) # Выполнение кода в окне "Выполнение скрипта" self.ui.button_exec.clicked.connect(lambda x=None: exec(self.ui.code.toPlainText())) # # # # Чтобы не было проблем запуска компов с прокси: QNetworkProxyFactory.setUseSystemConfiguration(True) QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) # TODO: оптимищация # QWebSettings::PrintElementBackgrounds # QWebSettings.globalSettings().setAttribute(QWebSettings.AutoLoadImages, False) self.web_view = QWebView() self.setCentralWidget(self.web_view) self.web_view.load('http://www.boibot.com/en/') self.wait_loading() # TODO: Установка вопроса, отправка его # self.slog( # self.doc.evaluateJavaScript(""" # //cleverbot.stimuluselement.value = "Расскажи анекдот!" # alert(cleverbot.stimuluselement.value) # alert(cleverbot.input) # alert(cleverbot.reply) # //cleverbot.sendAI() # """) # ) def _get_doc(self): return self.web_view.page().mainFrame().documentElement() doc = property(_get_doc) def wait_loading(self): """Функция ожидания загрузки страницы. Использовать только при изменении url.""" logger.debug('Начинаю ожидание загрузки страницы.') # Ждем пока прогрузится страница loop = QEventLoop() self.web_view.loadFinished.connect(loop.quit) loop.exec_() logger.debug('Закончено ожидание загрузки страницы.') # TODO: добавить возможность выбрать область поиска элемента для клика, а то она все время вся страница -- self.doc def click_tag(self, css_path): """Функция находит html тег по указанному пути и эмулирует клик на него. Строки в css_path нужно оборачивать в апострофы. Пример: # Кликаем на кнопку "Отнять у слабого" self.click_tag("div[class='button-big btn f1']") # Кликаем на кнопку "Искать другого" self.click_tag(".button-search a") """ logger.debug('Выполняю клик по тегу: %s', css_path) # Используем для клика jQuery code = """ tag = $("{}"); tag.click();""".format(css_path) ok = self.doc.evaluateJavaScript(code) if ok is None: logger.warn('Выполнение js скрипта неудачно. Code:\n' + code) def slog(self, text): """Функция для добавления текста в виджет-лог, находящегося на форме.""" self.ui.simple_log.appendPlainText('{}'.format(text)) def read_settings(self): # TODO: при сложных настройках, лучше перейти на json или yaml config = QSettings(CONFIG_FILE, QSettings.IniFormat) self.restoreState(config.value('MainWindow_State')) self.restoreGeometry(config.value('MainWindow_Geometry')) def write_settings(self): config = QSettings(CONFIG_FILE, QSettings.IniFormat) config.setValue('MainWindow_State', self.saveState()) config.setValue('MainWindow_Geometry', self.saveGeometry()) def closeEvent(self, *args, **kwargs): self.write_settings() super().closeEvent(*args, **kwargs)
class MainWindow(QMainWindow, QObject): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('dev_window') # Все действия к прикрепляемым окнам поместим в меню for dock in self.findChildren(QDockWidget): self.ui.menuDockWindow.addAction(dock.toggleViewAction()) # Все действия к toolbar'ам окнам поместим в меню for tool in self.findChildren(QToolBar): self.ui.menuTools.addAction(tool.toggleViewAction()) # Выполнение кода в окне "Выполнение скрипта" self.ui.button_exec.clicked.connect(self.exec_script) try: self.code_editor = create_code_editor() self.ui.container_code_editor.setWidget(self.code_editor) except Exception as e: logger.warn(e) self.code_editor = QPlainTextEdit() self.ui.container_code_editor.setWidget(self.code_editor) self.write_code_to_editor() self.timer_save_code = QTimer() self.timer_save_code.setSingleShot(True) self.timer_save_code.setInterval(300) self.timer_save_code.timeout.connect(self.save_code_from_editor) self.code_editor.textChanged.connect(self.timer_save_code.start) OUTPUT_LOGGER_STDOUT.emit_write.connect(self.write_output) OUTPUT_LOGGER_STDERR.emit_write.connect(self.write_output) def save_code_from_editor(self): logger.debug('Save code from editor to file: %s. Start.', CODE_EDITOR_BACKUP) with open(CODE_EDITOR_BACKUP, mode='w', encoding='utf-8') as f: f.write(self.code_editor.toPlainText()) logger.debug('Finish save code from editor.') def write_code_to_editor(self): logger.debug('Write code to editor in file: %s. Start.', CODE_EDITOR_BACKUP) try: with open(CODE_EDITOR_BACKUP, encoding='utf-8') as f: content = f.read() try: self.code_editor.setPlainText(content, None, None) except: self.code_editor.setPlainText(content) except Exception as e: logger.warn(e) logger.debug('Finish write code to editor.') def exec_script(self): try: has_selected = self.code_editor.textCursor().hasSelection() if has_selected: # http://doc.qt.io/qt-4.8/qtextcursor.html#selectedText # Note: If the selection obtained from an editor spans a line break, the text will contain a # Unicode U+2029 paragraph separator character instead of a newline \n character. Use QString::replace() # to replace these characters with newlines. code = self.code_editor.textCursor().selectedText() code = code.replace('\u2028', '\n').replace('\u2029', '\n') else: code = self.code_editor.toPlainText() exec(code.strip()) except Exception as e: import traceback # Выводим ошибку в консоль traceback.print_exc() # Сохраняем в переменную tb = traceback.format_exc() last_error_message = str(e) last_detail_error_message = str(tb) message = last_error_message + '\n\n' + last_detail_error_message mb = QErrorMessage() mb.setWindowTitle('Error') # Сообщение ошибки содержит отступы, символы-переходы на следующую строку, # которые поломаются при вставке через QErrorMessage.showMessage, и нет возможности # выбрать тип текста, то делаем такой хак. mb.findChild(QTextEdit).setPlainText(message) mb.exec_() def write_output(self, text, severity): """Функция для добавления сообщения с указанием серьезности (Debug, Error).""" # save text_cursor = self.ui.output.textCursor() orig_fmt = text_cursor.charFormat() fmt = QTextCharFormat() # modify if severity == OutputLogger.Severity.ERROR: fmt.setFontWeight(QFont.DemiBold) fmt.setForeground(Qt.red) # append text_cursor.movePosition(QTextCursor.End) text_cursor.setCharFormat(fmt) text_cursor.insertText(text) # restore text_cursor.setCharFormat(orig_fmt) def clear_slog(self): self.ui.simple_log.clear() def slog(self, *args, **kwargs): """Функция для добавления текста в виджет-лог, находящегося на форме.""" try: # Используем стандартный print для печати в строку str_io = io.StringIO() kwargs['file'] = str_io kwargs['end'] = '' print(*args, **kwargs) text = str_io.getvalue() self.ui.simple_log.appendPlainText(text) except Exception as e: self.ui.simple_log.appendPlainText(str(e)) def read_settings(self): # TODO: при сложных настройках, лучше перейти на json или yaml config = QSettings(CONFIG_FILE, QSettings.IniFormat) self.restoreState(config.value('MainWindow_State')) self.restoreGeometry(config.value('MainWindow_Geometry')) def write_settings(self): config = QSettings(CONFIG_FILE, QSettings.IniFormat) config.setValue('MainWindow_State', self.saveState()) config.setValue('MainWindow_Geometry', self.saveGeometry()) def closeEvent(self, event): self.write_settings() quit()