def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), "action.ui") result = loader.load(filePath, w) self.assert_(isinstance(result.actionFoo, QtGui.QAction))
def __init__(self): loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'bug_426.ui') self.widget = loader.load(filePath) self.group = QtGui.QActionGroup(self.widget) self.widget.show() QtCore.QTimer.singleShot(0, self.widget.close)
def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.child_object, QtGui.QFrame))
def __init__(self): QtGui.QWidget.__init__(self) loader = QUiLoader() widget = loader.load(adjust_filename('bug_552.ui', __file__), self) self.children = [] for child in widget.findChildren(QtCore.QObject, None): self.children.append(child) self.t = widget.tabWidget self.t.removeTab(0)
def testPythonCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() loader.registerCustomWidget(MyWidget) filePath = os.path.join(os.path.dirname(__file__), "pycustomwidget.ui") result = loader.load(filePath, w) self.assert_(isinstance(result.custom, MyWidget)) self.assert_(result.custom.isPython())
def testBug909(self): fileName = QFile(adjust_filename('bug_909.ui', __file__)) loader = QUiLoader() main_win = loader.load(fileName) self.assertEqual(sys.getrefcount(main_win), 2) fileName.close() tw = QTabWidget(main_win) main_win.setCentralWidget(tw) main_win.show()
def testLoadFileUnicodeFilePath(self): filePath = str(os.path.join(os.path.dirname(__file__), 'test.ui')) loader = QUiLoader() parent = QWidget() w = loader.load(filePath, parent) self.assertNotEqual(w, None) self.assertEqual(len(parent.children()), 1) child = w.findChild(QWidget, "child_object") self.assertNotEqual(child, None) self.assertEqual(w.findChild(QWidget, "grandson_object"), child.findChild(QWidget, "grandson_object"))
def setupUi(self, Form): path = f"{os.path.dirname(__file__)}/new_gui.ui" ui_file = QFile(path) ui_file.open(QFile.ReadOnly) loader = QUiLoader() self._window = loader.load(ui_file) # Need to fix this courses list view self._window.coursesView = CoursesListView(self._window.courses_tab) self._window.courses_layout.addWidget(self._window.coursesView) self._window.coursesView.setObjectName("coursesView") self._window.coursesView2.deleteLater() self.icon = QIcon(":/icons/uglytheme/polibeepsync.svg") self.retranslateUi(self._window) self._window.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(self._window)
class AppContext(ApplicationContext): def run(self): self.COLUMN_ADDRESS = 0 self.COLUMN_DATA1 = 1 self.COLUMN_DATA2 = 2 self.COLUMN_DATA3 = 3 self.COLUMN_DATA4 = 4 self.app.setStyle('Fusion') ui_file = self.get_resource("mainwindow.ui") self.file = QFile(ui_file) self.file.open(QFile.ReadOnly) self.loader = QUiLoader() self.window = self.loader.load(self.file) self.window.updateView.clicked.connect(self.onUpdateView) self.window.clearView.clicked.connect(self.onClearView) self.address_list = ['0x0800C000', '0x0800C004', '0x0800C008', '0x0800C00C', '0x0800C010', '0x0800C014'] self.data_list = ['0xAAAAAAAA', '0xBBBBBBBB', '0xCCCCCCCC', '0xDDDDDDDD', '0xEEEEEEEE', '0xFFFFFFFF'] self.model = TestModel() self.window.tableView.setModel(self.model) # Add a row for the default data.. self.model.insertRows(0) row = 0 first_index = self.model.createIndex(row, self.COLUMN_ADDRESS) self.model.setData(first_index, self.address_list[0], Qt.EditRole) first_index = self.model.createIndex(row, self.COLUMN_DATA1) self.model.setData(first_index, self.data_list[0], Qt.EditRole) first_index = self.model.createIndex(row, self.COLUMN_DATA2) self.model.setData(first_index, self.data_list[1], Qt.EditRole) first_index = self.model.createIndex(row, self.COLUMN_DATA3) self.model.setData(first_index, self.data_list[2], Qt.EditRole) first_index = self.model.createIndex(row, self.COLUMN_DATA4) self.model.setData(first_index, self.data_list[3], Qt.EditRole) self.window.tableView.show() # Show the application to the user self.window.show() return self.app.exec_() @Slot() def onClearView(self): print(f'onClearView') current_rows = self.model.rowCount() self.model.removeRows(0, current_rows) @Slot() def onUpdateView(self): print(f'Updating view...') print(f'We have {self.model.rowCount()} rows') # Insert rows for new data address_len = len(self.address_list) rows_nedded = address_len // 4 print(f'We have {address_len} addresses, each row should display every fifth address on the list, so we need to add {rows_nedded} rows') current_rows = self.model.rowCount() rows_to_add = rows_nedded print(f'Inserting {rows_to_add} new rows for the new data') self.model.insertRows(0, rows_to_add) # self.model.insertRows(0, 2) print(f'We now have {self.model.rowCount()} rows') print(f'Inserting new data into the model...') for addr_idx in range(len(self.address_list)): addr_to_add = addr_idx % 4 if addr_to_add == 0: print(f'offset {addr_idx // 4}') row = addr_idx // 4 print(f'Adding {self.address_list[addr_idx]} to the row {row}') idx = self.model.createIndex(row, self.COLUMN_ADDRESS) tmp = self.model.setData(idx, self.address_list[addr_idx], Qt.EditRole) print(f'Result of setData: {tmp}') print(f'Adding data to the model') for row in range(2): for column in range(1, 5): idx = self.model.createIndex(row, column) print(f'Adding {self.data_list[column]} to index row {row}; column {column}') tmp = self.model.setData(idx, self.data_list[column - 1], Qt.EditRole) print(f'Result of setData: {tmp}') print('Done')
class QtFrontend(ViewSBFrontend): """ Qt Frontend that consumes packets for display. """ UI_NAME = 'qt' UI_DESCRIPTION = 'unstable GUI in Qt' # So, Qt's tree widgets require that column 0 have the expand arrow, but you _can_ change # where column 0 is displayed. # We want the summary column to have the expand arrow, so we'll swap it # with the timestamp column in __init__(). COLUMN_TIMESTAMP = 5 COLUMN_DEVICE = 1 COLUMN_ENDPOINT = 2 COLUMN_DIRECTION = 3 COLUMN_LENGTH = 4 COLUMN_SUMMARY = 0 COLUMN_STATUS = 6 COLUMN_DATA = 7 @staticmethod def reason_to_be_disabled(): try: import PySide2 except ImportError: return "PySide2 (Qt library) not available." return None def _create_item_for_packet(self, viewsb_packet): """ Creates a QTreeWidgetItem for a given ViewSBPacket. Args: viewsb_packet -- The ViewSBPacket to create the QTreeWidgetItem from. Returns a QTreeWidgetItem. """ stringify_list = lambda l : [str(x) if x is not None else '' for x in l] def get_packet_string_array(viewsb_packet): """ Tiny helper to return and stringify the common fields used for the columns of tree items. """ direction = viewsb_packet.direction.name if viewsb_packet.direction is not None else '' length = len(viewsb_packet.data) if viewsb_packet.data is not None else '' return stringify_list([ viewsb_packet.summarize(), viewsb_packet.device_address, viewsb_packet.endpoint_number, direction, length, viewsb_packet.timestamp, viewsb_packet.summarize_status(), viewsb_packet.summarize_data() ]) + [viewsb_packet] item = QTreeWidgetItem(get_packet_string_array(viewsb_packet)) # Give the item a reference to the original packet object. item.setData(0, QtCore.Qt.UserRole, viewsb_packet) return item def _recursively_walk_packet(self, viewsb_packet): """ Recursively walks packet subordinates, batching QTreeWidgetItem.addChildren as much as possible. Args: viewsb_packet -- The top-level packet (as far as the caller's context is concerned). """ packet_item = self._create_item_for_packet(viewsb_packet) packet_children_list = [] for sub_packet in viewsb_packet.subordinate_packets: # Create the item for this packet, and recursively fill its children. packet_children_list.append(self._recursively_walk_packet(sub_packet)) packet_item.addChildren(packet_children_list) return packet_item def __init__(self): """ Sets up the Qt UI. """ QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) self.app = QApplication([]) self.ui_file = QtCore.QFile(os.path.dirname(os.path.realpath(__file__)) + '/qt.ui') self.loader = QUiLoader() self.loader.registerCustomWidget(ViewSBQTreeWidget) self.loader.registerCustomWidget(ViewSBHexView) self.window = self.loader.load(self.ui_file) # type: QMainWindow # Swap columns 0 and 5 to put the expand arrow on the summary column. self.window.usb_tree_widget.header().swapSections(0, 5) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_TIMESTAMP, 120) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_DEVICE, 32) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_ENDPOINT, 24) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_DIRECTION, 42) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_LENGTH, 60) self.window.usb_tree_widget.setColumnWidth(self.COLUMN_SUMMARY, 500) self.window.update_timer = QtCore.QTimer() self.window.update_timer.timeout.connect(self._update) self.window.usb_tree_widget.currentItemChanged.connect(self._tree_current_item_changed) self.window.usb_tree_widget = self.window.usb_tree_widget self.window.usb_tree_widget.sortByColumn(0) self.window.showMaximized() def _update(self): """ Called by the QTimer `update_timer`; collects packets the queue and adds them to the tree view. We use this instead of calling `handle_communications` and defining `handle_incoming_packet`, because adding items one at a time as we receive them is slower than batching them. Note: Since this is called via a QTimer signal, this method runs in the UI thread. """ packet_list = [] try: # Get as many packets as we can as quick as we can. while True: packet = self.data_queue.get_nowait() packet_list.append(packet) # But the instant it's empty, don't wait for any more; just send them to be processed. except multiprocessing.queues.Empty: pass finally: self.add_packets(packet_list) def _tree_current_item_changed(self, current_item, _previous_item): """ Handler for the QTreeWidget.currentItemChanged() signal that populates the side panels with detail fields and a hex representation of the current packet. """ # Clear the details widget. self.window.usb_details_tree_widget.clear() current_packet = current_item.data(0, QtCore.Qt.UserRole) # A list of 2-tuples: first element is a table title, and the second is usually a string:string dict. detail_fields = current_packet.get_detail_fields() if detail_fields: self.update_detail_fields(detail_fields) self.window.usb_hex_view.populate(current_packet.get_raw_data()) def update_detail_fields(self, detail_fields): """ Populates the detail view with the relevant fields for the selected packet. """ # Each table will have a root item in the details view. root_items = [] for table in detail_fields: title = table[0] root = QTreeWidgetItem([title]) children = [] fields = table[1] # The usual case: a str:str dict. if isinstance(fields, dict): for key, value in fields.items(): children.append(QTreeWidgetItem([str(key), str(value)])) # Sometimes it'll just be a 1-column list. elif isinstance(fields, list): for item in fields: children.append(QTreeWidgetItem([str(item)])) # Sometimes it'll just be a string, or a `bytes` instance. else: children.append(QTreeWidgetItem([str(fields)])) root.addChildren(children) # Add an empty "item" between each table. root_items.extend([root, QTreeWidgetItem([])]) self.window.usb_details_tree_widget.addTopLevelItems(root_items) self.window.usb_details_tree_widget.expandAll() self.window.usb_details_tree_widget.resizeColumnToContents(0) self.window.usb_details_tree_widget.resizeColumnToContents(1) def add_packets(self, viewsb_packets): """ Adds a list of top-level ViewSB packets to the tree. We're in the UI thread; every bit of overhead counts, so let's batch as much as possible. """ top_level_items_list = [] for viewsb_packet in viewsb_packets: # Create the item for this packet, and recursively fill its children. top_level_items_list.append(self._recursively_walk_packet(viewsb_packet)) self.window.usb_tree_widget.addTopLevelItems(top_level_items_list) def run(self): """ Overrides ViewSBFrontend.run(). """ # TODO: is there a better value than 100 ms? Should it be configurable by the Analyzer? self.window.update_timer.start(100) self.app.exec_() self.stop() def stop(self): self.app.closeAllWindows() self.termination_event.set()
def __init__(self, parent=None): super(Dialog, self).__init__(parent) def setup(self): for s in ['fusion', 'macintosh', 'windows', 'windowsvista']: self.comboBox.addItem(s) self.comboBox.currentIndexChanged.connect(self.setStyle) for r in range(0, 4): self.tableWidget.insertRow(0) self.tableWidget.insertColumn(0) def setStyle(self): app.setStyle(self.comboBox.currentText()) if __name__ == '__main__': app = QApplication([]) loader = QUiLoader() loader.registerCustomWidget(Dialog) base_dir = os.path.dirname(os.path.realpath(__file__)) ui_file = QFile('widgets.ui') ui_file = QFile(os.path.join(base_dir, 'widgets.ui')) #dialog = loader.load(os.path.join(base_dir, 'widgets.ui')) dialog = loader.load(ui_file) dialog.setup() dialog.show() app.exec_()
def __init__(self, ui_file, application, parent=None): super(Form, self).__init__(parent) self.application = application # ================================ # Load Window # ================================ ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() self.window = loader.load(ui_file) ui_file.close() # =================================== # Instantiate some window properties # =================================== # Collection self.collection_path = None self.collection_working_path = getcwd() self.cobj = None self.document = None self.matches = None self.shelf_path = None self.shelf_working_path = getcwd() self.query_list = [] # visual list for the GUI self.queries = [] # shelve object list self.formatted_queries = [] self.selected_query = None # Single Document self.file_path = None self.working_path = getcwd() # Mutual self.results = None self.num_sentences = 5 self.num_keywords = 10 # ================================ # Locate and bind window children # ================================ # menuBar -> menuTools action_load = self.window.findChild(QAction, 'actionLoadQL') action_load.triggered.connect(self.browse_and_load) action_refresh = self.window.findChild(QAction, 'actionRefresh') action_refresh.triggered.connect(self.refresh) # centralWidget -> tabWidget self.tab_widget = self.window.findChild(QTabWidget, 'tabWidget') # ----------------------------- # tabWidget -> Collection Panel # ----------------------------- # centralWidget -> collection self.line_collection_path = self.window.findChild( QPlainTextEdit, 'collectionPathInput') self.line_collection_path.textChanged.connect( self.check_collection_path) butt_browse_collection_path = self.window.findChild( QPushButton, 'collectionBrowseButton') butt_browse_collection_path.clicked.connect( self.browse_collection_path) # centralWidget -> Process Collection self.butt_process_collection_processing = self.window.findChild( QPushButton, 'processButton') self.butt_process_collection_processing.clicked.connect( self.process_configuration) self.prog_bar = self.window.findChild(QProgressBar, 'progressBar') self.prog_label = self.window.findChild(QLabel, 'progressLabel') # centralWidget -> queryFiles self.line_query_path = self.window.findChild(QPlainTextEdit, 'queryPathInput') self.line_query_path.textChanged.connect(self.check_query_path) butt_browse_query_path = self.window.findChild(QPushButton, 'queryBrowseButton') butt_browse_query_path.clicked.connect(self.browse_shelf_path) self.butt_load_query_path = self.window.findChild( QPushButton, 'queryLoadButton') self.butt_load_query_path.clicked.connect(self.load_shelf_file) butt_open_query_builder = self.window.findChild( QPushButton, 'openQueryBuilderButton') butt_open_query_builder.clicked.connect(open_query_builder) # centralWidget -> querySelection self.combo_query = self.window.findChild(QComboBox, 'queriesCombo') self.combo_query.currentIndexChanged.connect(self.set_query_combo) self.clear_query = self.window.findChild(QPushButton, 'clearQueryButton') self.clear_query.clicked.connect(self.clear_query_box) # centralWidget -> Query Options self.spin_sentence_buffer = self.window.findChild( QSpinBox, 'spinSentenceBuffer') # centralWidget -> Summary Options self.radio_full = self.window.findChild(QRadioButton, 'radioFull') self.radio_reduced = self.window.findChild(QRadioButton, 'radioReduced') self.radio_reduced.setChecked(True) # reduced by default self.spin_num_sentences_collection = self.window.findChild( QSpinBox, 'spinSentencesCollection') self.spin_num_sentences_collection.valueChanged.connect( self.set_sentences_collection) self.spin_num_words_collection = self.window.findChild( QSpinBox, 'spinWordsCollection') self.spin_num_words_collection.valueChanged.connect( self.set_words_collection) # centralWidget -> Apply Query self.butt_apply_query = self.window.findChild(QPushButton, 'applyQueryButton') self.butt_apply_query.clicked.connect(self.apply_query) # ----------------------------------- # tabWidget -> Single Document Panel # ----------------------------------- # centralWidget -> file self.line_file_path = self.window.findChild(QPlainTextEdit, 'filePathInput') self.line_file_path.textChanged.connect(self.enable_summary_button) butt_browse_file_path = self.window.findChild(QPushButton, 'fileBrowseButton') butt_browse_file_path.clicked.connect(self.browse_file_path) # centralWidget -> Customization self.spin_num_sentences = self.window.findChild( QSpinBox, 'spinSentences') self.spin_num_sentences.valueChanged.connect(self.set_sentences) self.spin_num_words = self.window.findChild(QSpinBox, 'spinWords') self.spin_num_words.valueChanged.connect(self.set_words) # centralWidget -> Apply Query self.butt_summarize = self.window.findChild(QPushButton, 'summarizeButton') self.butt_summarize.clicked.connect(self.apply_summary) # ----------------------------- # tabWidget -> Results Panel # ----------------------------- # centralWidget -> view results self.results_text = self.window.findChild(QPlainTextEdit, 'outputText') self.results_text.textChanged.connect(self.enable_save_results_button) self.butt_save_results = self.window.findChild(QPushButton, 'saveOutputButton') self.butt_save_results.clicked.connect(self.write_results) # ----------------------------- # tabWidget -> Results Panel # ----------------------------- # centralWidget -> view matches self.matches_text = self.window.findChild(QPlainTextEdit, 'outputMatches') # ======== # Show # ======== self.window.show()
app = QtGui.qApp msg_box = QMessageBox() msg_box.setWindowTitle(x) msg_box.setText(y) msg_box.show() close = msg_box.exec() if __name__ == "__main__": app = QApplication(sys.argv) ui_file = QFile("login.ui") ui_file.open(QFile.ReadOnly) loader = QUiLoader() window = loader.load(ui_file) if existe_db() == False: criar_db() def valida_usuario1(): us = window.le_login.text() pw = window.le_senha.text() if valida_usuario(us, pw) == True: menu() else: aviso("Login", "Login ou senha incorreto, tente novamente.") window.le_login.clear() window.le_senha.clear() window.btn_acessar.clicked.connect(valida_usuario1)
class pesquisa_editar(): pesquisa_editar = None def __init__(self): global pesquisa_editar self.jan = QtGui.qApp self.arquivo = QFile("editarcliente.ui") self.arquivo.open(QFile.ReadOnly) self.carrega = QUiLoader() pesquisa_editar = self.carrega.load(self.arquivo) pesquisa_editar.janela1.raise_() pesquisa_editar.setFixedSize(287, 91) def k(): cp = pesquisa_editar.le_cpf.text() if len(cp) == 14: try: db = conecta_db(meu_db[0]) cursor = db.cursor() sql = "SELECT * FROM clientes WHERE cpf = %s" val = (cp, ) cursor.execute(sql, val) usuarios = cursor.fetchone() if usuarios != None: pesquisa_editar.janela2.raise_() pesquisa_editar.setFixedSize(661, 581) l = [] for x in usuarios: l.append(x) c = ["Auxiliar", "Diácono", "Presbítero", "Pastor"] for dado in c: if dado == l[6]: c.remove(dado) c.insert(0, dado) pesquisa_editar.combo_cargo_editar.addItem(c[0]) pesquisa_editar.combo_cargo_editar.addItem(c[1]) pesquisa_editar.combo_cargo_editar.addItem(c[2]) pesquisa_editar.combo_cargo_editar.addItem(c[3]) t = l[7] if t[0] == 0: d1 = f"{t[1]}" else: d1 = f"{t[0]+t[1]}" if t[3] == 0: d2 = f"{t[4]}" else: d2 = f"{t[3]+t[4]}" d3 = f"{t[6]}{t[7]}{t[8]}{t[9]}" print(d3, d2, d1) k = l[8] if k[0] == 0: f1 = f"{k[1]}" else: f1 = f"{k[0]+k[1]}" if k[3] == 0: f2 = f"{k[4]}" else: f2 = f"{k[3]+k[4]}" f3 = f"{k[6]}{k[7]}{k[8]}{k[9]}" print(f3, f2, f1) pesquisa_editar.le_nome.setText(l[1]) pesquisa_editar.le_endereco.setText(l[2]) pesquisa_editar.le_rg.setText(l[3]) pesquisa_editar.le_cpf_2.setText(l[4]) pesquisa_editar.le_contato.setText(l[5]) pesquisa_editar.le_d_bat.setDate( QtCore.QDate(int(d3), int(d2), int(d1))) pesquisa_editar.le_d_con.setDate( QtCore.QDate(int(f3), int(f2), int(f1))) def val_editar(l): if cpf_db(cpf) == True: if verificar_cpf(cpf) == True: print("posicao padrão", l[0]) nome = pesquisa_editar.le_nome.text() endereco = pesquisa_editar.le_endereco.text( ) rg = pesquisa_editar.le_rg.text() cpf_2 = pesquisa_editar.le_cpf_2.text() contato = pesquisa_editar.le_contato.text() cargo = str( c_membro.combo_cargo.currentText()) d_bat = pesquisa_editar.le_d_bat.text() d_con = pesquisa_editar.le_d_con.text() c = [(l[0]), str(nome), str(endereco), str(rg), str(cpf_2), str(contato), str(cargo), str(d_bat), str(d_con)] variavel = [ "id", "nome", "endereco", "RG", "CPF", "Contato", "Cargo", "d_bat", "d_con" ] for x in range(8): print("posicao de x::", x) if l[x] != c[x]: db = conecta_db(meu_db[0]) cursor = db.cursor() print( f"variavel modificadas são: {variavel[x]}" ) sql = f"UPDATE clientes SET {variavel[x]} = %s WHERE clientes.id = " + str( l[0]) val = (c[x], ) cursor.execute(sql, val) db.commit() aviso( "MEMBRO EDITAR", "Membro editado com sucesso!!") else: aviso("Editar Membro", "CPF Inválido, digite um cpf real") else: aviso( "Editar Membro", "CPF já cadastrado no banco, escolha outro" ) pesquisa_editar.btn_editar.clicked.connect( lambda: val_editar(l)) else: aviso("CPF", "CPF não cadastrado!!") except BaseException as e: print("AVISO", " ERRO AO editar O MEMBRO" + str(e)) finally: cursor.close() db.close() pesquisa_editar.btn_ok.clicked.connect(k) self.arquivo.close() pesquisa_editar.show()
def __init__(self, ui_file, parent=None): super(Form, self).__init__(parent) ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() loader.registerCustomWidget(InterfaceWindow) self.window = loader.load(ui_file) ui_file.close() self.window.set_reload_ref(self.reload_viewer) # system flags self.current_data_dir = "." # new task window self.in_task = False # indicating its currently performing a Task self.newTaskWin = NewTask(ui_file='newtaskwindow.ui') # Menu actions ================================================== # Load ADS action self.window.findChild(QAction, 'loadAOAction').\ triggered.connect(self.load_adc) # Load from video self.window.findChild(QAction, 'actionFrom_Video').\ triggered.connect(self.get_active_from_video) self.window.findChild(QAction, 'actionFrom_Video').\ setEnabled(False) # load save target mod action self.window.findChild(QAction, 'actionTarget_Modifications').\ triggered.connect(self.save_mods) # show change history self.window.findChild(QAction, 'actionView_history').\ triggered.connect(self.show_mods) # save active data to .. self.window.findChild(QAction, 'actionActive_data_to').\ triggered.connect(self.save_active_to) # Tools ----------- # data spliter self.window.findChild(QAction, 'actionData_spliter').\ triggered.connect(self.run_spliter) # renamer self.window.findChild(QAction, 'actionRename').\ triggered.connect(self.run_rename) # check labels self.window.findChild(QAction, 'actionCheck_Labels').\ triggered.connect(self.check_labels_integrity) # set defult class self.window.findChild(QAction, 'actionset_defult_class').\ triggered.connect(self.set_defult_class) # For task ------------------------------------------------------ self.window.findChild(QAction, 'actionNewTask').\ triggered.connect(self.new_task) self.window.findChild(QAction, 'actionOpenTask').\ triggered.connect(self.open_task) # Data list ===================================================== self.dataList = \ self.window.findChild(QListWidget, 'dataList') self.dataList.setViewMode(QListView.IconMode) self.dataList.setIconSize(PySide2.QtCore.QSize(128, 72)) self.dataList.itemSelectionChanged.connect(self.load_viewer) self.dataList.itemDoubleClicked.connect(self.double_click_data) # Data Viewer =================================================== self.viewerScene = ImgScene(self) self.viewerView = self.window.findChild(QGraphicsView, 'dataViewer') self.viewerView.setScene(self.viewerScene) self.viewerView.setCursor(QCursor(PySide2.QtCore.Qt.CrossCursor)) # Targets list ================================================== self.targetList = \ self.window.findChild(QListWidget, 'targetList') self.targetList.itemClicked.connect(self.hightlight_target) # self.current_dataScene = DataScene(self.viewerScene, \ # self.viewerView, self.targetList) # self.targetList.itemDoubleClicked.connect(\ # self.current_dataScene.edit_target_class) # editing buttons =============================================== self.rmTargetButton = \ self.window.findChild(QPushButton, 'rmTargetButton') self.undoButton = \ self.window.findChild(QPushButton, 'undoButton') self.editButton = \ self.window.findChild(QPushButton, 'editButton') self.deleteButton = \ self.window.findChild(QPushButton, 'deleteButton') self.editButton_connected = False # make sure only connect once self.rmTargetButton.setEnabled(False) self.undoButton.setEnabled(False) self.rmTargetButton.clicked.connect(\ lambda state=0, x=-1:\ self.remove_target(x)) self.targetList_modified = False self.undoButton.clicked.connect(self.undo_mod) self.deleteButton.clicked.connect(self.remove_img) # shortcuts ==================================================== QShortcut(QKeySequence("Ctrl+R"), self.window).activated.\ connect(lambda state=0, x=-1: self.remove_target(x)) self.window.show()
def main(): """main function """ # Adds Ctrl+C support to kill app signal.signal(signal.SIGINT, signal.SIG_DFL) QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) app.setOrganizationName("djieffx") app.setApplicationName("vspleeter") loader = QUiLoader() mw = loader.load( os.path.join(os.path.dirname(__file__), "vspleeter_mainWindow.ui")) mw.setWindowIcon(QIcon(":/icons/vspleeter_icon.png")) def getBinaries(): """Create a generator that yield the proper command name if the checkbox is checked. :return: generator with command name :rtype: generator """ if mw.cpuCheckBox.checkState(): yield 'spleeter' if mw.gpuCheckBox.checkState(): yield 'spleeter-gpu' def getStemsAmount(): """Create a generator that yield the stems amount if the checkbox is checked. :return: generator with stem count :rtype: generator """ if mw.stems2CheckBox.checkState(): yield '2' if mw.stems4CheckBox.checkState(): yield '4' if mw.stems5CheckBox.checkState(): yield '5' def createOutputDir(cmdSpecs): """Create the output directory from defined output specifications :param cmdSpecs: context based variables to execute spleeter command :type cmdSpecs: dict :return: the output directory :rtype: str """ outputDir = OUTPUT_PATH_SUFFIX.format(**cmdSpecs) if not os.path.exists(outputDir): os.makedirs(outputDir, mode=0o777) print('Created the {0} directory'.format(outputDir)) return outputDir def generateCommandsPerElements(binaryGenerator, inputFilePath, stemsCPUGenerator, stemsGPUGenerator, rootOutputDir): """Generate all the commands necessary, per what is selected in the UI, looping on the process type :param binaryGenerator: generator with all the binary selections :param str inputFilePath: The file to be spleeted :param stemsCPUGenerator: generator with the CPU processes flag :param stemsGPUGenerator: generator with the GPU processes flag :param str rootOutputDir: The output directory :return: generator with all command line to spleet the file """ for binaryName in binaryGenerator: cmdSpecs = { 'rootOutputDir': rootOutputDir, 'basename': os.path.basename(os.path.splitext(inputFilePath)[0]), 'binaryType': 'CPU', 'binaryName': binaryName, 'inputFilePath': inputFilePath, 'stemsGenerator': stemsCPUGenerator } if 'gpu' in binaryName: cmdSpecs['binaryType'] = 'GPU' cmdSpecs['stemsGenerator'] = stemsGPUGenerator yield from generateCmdPerStem(cmdSpecs) else: yield from generateCmdPerStem(cmdSpecs) def generateCmdPerStem(cmdSpecs): """Generate the command from the stem count :param dict cmdSpecs: a dictionary containing all necessary data to generate the command :return: a command to execute :rtype: list """ stemsGenerator = cmdSpecs['stemsGenerator'] for stemNum in stemsGenerator: cmdSpecs['stemNum'] = stemNum outputDir = createOutputDir(cmdSpecs) if os.name == 'nt': cmd = [ "python", "-m", "{}".format(cmdSpecs['binaryName']), "separate", "-i", "{}".format(cmdSpecs['inputFilePath']), "-p", "spleeter:{}stems".format(cmdSpecs['stemNum']), "-o", "{}".format(outputDir) ] else: cmd = [ "{}".format(cmdSpecs['binaryName']), "separate", "-i", "{}".format(cmdSpecs['inputFilePath']), "-p", "spleeter:{}stems".format(cmdSpecs['stemNum']), "-o", "{}".format(outputDir) ] yield cmd def browseForInputFile(_): """Opens a file browser, and set the input file :param _: unused """ inputFile = QFileDialog.getOpenFileName()[0] mw.inputFileLineEdit.setText(inputFile) checkToEnableProcess() def browseForOutputDir(_): """Opens a file browser, and set the input file :param _: unused """ outputDir = QFileDialog.getExistingDirectory() mw.outputDirLineEdit.setText(outputDir) checkToEnableProcess() def checkToEnableProcess(): """If all the necessary params are set, enable the process button""" mw.processPushButton.setEnabled(False) inputFileCheck = bool(mw.inputFileLineEdit.text()) procCheck = any([ mw.cpuCheckBox.checkState(), mw.gpuCheckBox.checkState(), ]) stemsCheck = any([ mw.stems2CheckBox.checkState(), mw.stems4CheckBox.checkState(), mw.stems5CheckBox.checkState(), ]) outputFileCheck = bool(mw.outputDirLineEdit.text()) if all([ inputFileCheck, procCheck, stemsCheck, outputFileCheck, ]): mw.processPushButton.setEnabled(True) def processBatchElements(_): """Process all the data from the UI, and execute all the commands generated :param _: unused input """ binaryGenerator = getBinaries() inputFilePath = mw.inputFileLineEdit.text() stemsCPUGenerator = getStemsAmount() stemsCPUGenerator, stemsGPUGenerator = itertools.tee(stemsCPUGenerator) rootOutputDir = mw.outputDirLineEdit.text() generatedCmds = generateCommandsPerElements(binaryGenerator, inputFilePath, stemsCPUGenerator, stemsGPUGenerator, rootOutputDir) generatedCmds, generatedCmdsForLength = itertools.tee(generatedCmds) amountOfCommands = 0 for _ in generatedCmdsForLength: amountOfCommands += 1 mw.progressBar.setRange(0, amountOfCommands) mw.progressBar.setValue(0) mw.resultTextEdit.setText('') mw.resultTextEdit.append('Source File: %s' % inputFilePath) for cmd in generatedCmds: currentJobCount = mw.progressBar.value() subprocess.run(cmd) mw.progressBar.setValue(currentJobCount + 1) mw.resultTextEdit.append('Output %s:' % cmd[5].split(':')[1]) outputFiles = glob.glob(os.path.join(cmd[7], '*', '*')) for outputFile in outputFiles: mw.resultTextEdit.append(outputFile) mw.resultTextEdit.append('') checkToEnableProcess() mw.inputFilePushButton.clicked.connect(browseForInputFile) mw.outputDirPushButton.clicked.connect(browseForOutputDir) mw.cpuCheckBox.stateChanged.connect(checkToEnableProcess) mw.gpuCheckBox.stateChanged.connect(checkToEnableProcess) mw.stems2CheckBox.stateChanged.connect(checkToEnableProcess) mw.stems4CheckBox.stateChanged.connect(checkToEnableProcess) mw.stems5CheckBox.stateChanged.connect(checkToEnableProcess) mw.processPushButton.clicked.connect(processBatchElements) mw.actionexit.triggered.connect(app.quit) mw.show() sys.exit(app.exec_())
class MainWindow(QObject): """ Appliaction GUI """ current_port_signal = Signal(str) current_table = Signal(str) def __init__(self, ui_fil, parent=None): super(MainWindow, self).__init__(parent) self.ui_file = QFile(ui_fil) self.ui_file.open(QFile.ReadOnly) self.loader = QUiLoader() self.loader.setLanguageChangeEnabled(True) self.window = self.loader.load(self.ui_file) self.window.setGeometry(50, 50, 860, 640) self.window.setWindowIcon(QIcon('icons/icons8-wi-fi-64.png')) self.ui_file.close() self.trans = QTranslator() self.trans.load('lang/pl_PL.qm') self.conn_baudrates = [ "9600", "115200", "300", "1200", "2400", "4800", "14400", "19200", "31250", "38400", "57600" ] self.conn_boards = ["ESP32", "ESP8266"] self.widget_tab = self.window.findChild(QTabWidget, 'tabWidget') self.widget_tab.setIconSize(QSize(36, 36)) self.widget_tab.setTabIcon(0, QIcon('icons/icons8-automatic-64.png')) self.widget_tab.setTabIcon(1, QIcon('icons/icons8-bar-chart-50.png')) self.widget_tab.setTabIcon(2, QIcon('icons/icons8-menu-64.png')) self.widget_tab.setTabIcon(3, QIcon('icons/icons8-timeline-64.png')) self.widget_tab.setTabIcon(4, QIcon('icons/icons8-bluetooth-50.png')) self.widget_tab.setTabIcon(5, QIcon('icons/icons8-console-64.png')) self.lang_combo_box = self.window.findChild(QComboBox, 'lang_combo_box') self.lang_combo_box.addItem("English") self.lang_combo_box.addItem("Polski") self.lang_combo_box.currentTextChanged.connect(self.change_language) self.serial_port_box = self.window.findChild(QComboBox, 'serial_port_box') self.baud_rate_box = self.window.findChild(QComboBox, 'baud_rate_box') self.select_board_box = self.window.findChild(QComboBox, 'select_board_box') self.scan_time_edit = self.window.findChild(QTimeEdit, 'scan_time_edit') self.wifi_scan_box = self.window.findChild(QCheckBox, 'wifi_scan_box') self.blue_scan_box = self.window.findChild(QCheckBox, 'blue_scan_box') self.save_data_check = self.window.findChild(QCheckBox, 'save_data_check') self.connection_status_edit = self.window.findChild( QLineEdit, 'connection_status_edit') self.start_button = self.window.findChild(QPushButton, 'start_button') self.stop_button = self.window.findChild(QPushButton, 'stop_button') self.stop_button.setEnabled(False) self.vertical_wifi_layout = self.window.findChild( QVBoxLayout, 'verticalLayout_5') self.wifi_list_view = self.window.findChild(QListWidget, 'wifi_list_view') self.wifi_list_view.setIconSize(QSize(64, 64)) self.vertical_timeline_layout = self.window.findChild( QVBoxLayout, 'verticalLayout_7') self.blue_list_view = self.window.findChild(QListWidget, 'blue_list_view') self.blue_list_view.setIconSize(QSize(64, 64)) self.console_logging_check = self.window.findChild( QCheckBox, 'console_logging_check') self.console_autoscroll_check = self.window.findChild( QCheckBox, 'console_autoscroll_check') self.console_text_edit = self.window.findChild(QTextEdit, 'console_text_edit') self.select_board_box.activated[str].connect(self.change_board) #Settings tab for i in self.conn_baudrates: self.baud_rate_box.addItem(i) for i in self.conn_boards: self.select_board_box.addItem(i) self.connection_status_edit.setText('Not connected') self.connection_status_edit.setStyleSheet( "background: red; color: white; font-size: 14px; border-width: 1px; \ border-style: solid; border-radius: 2px; border-color: red;") thread1 = ReadSerialPortsThread.ReadSerialPortsThread(self) thread1.add_serial_port.connect( lambda p: self.serial_port_box.addItem(p)) thread1.remove_serial_port.connect( lambda p: self.serial_port_box.removeItem( self.serial_port_box.findText(p))) thread1.start() thread2 = MakeSerialConnection.MakeSerialConnection(self) thread4 = WriteToDatabase.WriteToDatabase(self) self.serial_port_box.currentTextChanged.connect(thread2.get_curr_port) self.baud_rate_box.activated[str].connect(thread2.get_curr_baud) self.select_board_box.activated[str].connect(thread2.get_curr_board) self.scan_time_edit.timeChanged.connect(thread2.get_curr_time) self.start_button.clicked.connect(thread2.start) self.stop_button.clicked.connect(thread2.stop_serial_communication) self.wifi_scan_box.clicked.connect(thread2.get_wifi_check) self.blue_scan_box.clicked.connect(thread2.get_blue_check) self.save_data_check.clicked.connect(thread2.enable_saving_to_db) self.save_data_check.clicked.connect(thread4.enable_saving_data_func) self.lang_combo_box.currentTextChanged.connect( lambda s: thread2.get_current_lang(s)) thread2.baud_box_state.connect( lambda b: self.baud_rate_box.setEnabled(b)) thread2.port_box_state.connect( lambda b: self.serial_port_box.setEnabled(b)) thread2.board_box_state.connect( lambda b: self.select_board_box.setEnabled(b)) thread2.time_edit_state.connect( lambda b: self.scan_time_edit.setEnabled(b)) thread2.wifi_check_state.connect( lambda b: self.wifi_scan_box.setEnabled(b)) thread2.blue_check_state.connect( lambda b: self.blue_scan_box.setEnabled(b)) thread2.serial_port_placeholder.connect( lambda t: self.serial_port_box.addItem(t)) thread2.serial_port_clear.connect(self.serial_port_box.clear) thread2.send_text_signal.connect( lambda t: self.console_text_edit.append(t)) thread2.start_btn_state.connect( lambda b: self.start_button.setEnabled(b)) thread2.stop_btn_state.connect( lambda b: self.stop_button.setEnabled(b)) thread2.conn_stat_text.connect( lambda t: self.connection_status_edit.setText(t)) thread2.conn_stat_style.connect( lambda s: self.connection_status_edit.setStyleSheet(s)) #Wi-Fi Chart tab self.chart = QtCharts.QChart() self.axis_x = QtCharts.QValueAxis() self.axis_y = QtCharts.QValueAxis() self.line_series = QtCharts.QLineSeries() self.line_series.append(QPoint(0, 0)) self.chart.setAxisX(self.axis_x, self.line_series) self.axis_x.setRange(2400, 2483) self.axis_x.setTickCount(10) self.axis_x.setMinorTickCount(4) self.axis_x.applyNiceNumbers() self.axis_x.setTitleText("Frequency [MHz]") self.chart.setAxisY(self.axis_y, self.line_series) self.axis_y.setRange(-100, -30) self.axis_y.applyNiceNumbers() self.axis_y.setTickCount(9) self.axis_y.setMinorTickCount(4) self.axis_y.setTitleText("RSSI [dBm]") self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignRight) self.chart.setBackgroundRoundness(0) self.chart_view = QtCharts.QChartView(self.chart) self.chart_view.setRenderHint(QPainter.Antialiasing) self.vertical_wifi_layout.addWidget(self.chart_view) #WiFi List tab thread2.clear_wifi_list.connect(self.wifi_list_view.clear) thread2.append_wifi_list_item.connect( lambda i: self.wifi_list_view.addItem(i)) thread2.append_wifi_timeline_data.connect( lambda d: self.append_data(d)) thread2.save_wifi_timeline_data.connect( lambda t: thread4.update_db_file(t)) thread2.clear_wifi_series.connect(self.chart.removeAllSeries) thread2.add_wifi_series.connect(lambda s: self.chart.addSeries(s)) thread2.set_axis_x_series.connect( lambda s: self.chart.setAxisX(self.axis_x, s)) thread2.set_axis_y_series.connect( lambda s: self.chart.setAxisY(self.axis_y, s)) thread2.wifi_data_to_func.connect( lambda d: thread2.append_wifi_data(d)) thread2.wifi_data_to_func.connect( lambda d: thread2.append_data_to_wifi_graph(d)) thread2.wifi_data_to_func.connect( lambda d: thread2.append_data_to_wifi_timeline(d)) thread2.blue_data_to_func.connect( lambda d: thread2.append_blue_data(d)) #Wi-Fi Timeline tab self.wifi_channels_occupancy_array = [] self.wifi_channels_timestamps = [] self.deleted_empty_vals = False self.freeze_graph_bool_val = False self.last_item = 0 self.graph_item_color = QColor(255, 195, 0) self.bars = QtDataVisualization.Q3DBars() self.column_axis = QtDataVisualization.QCategory3DAxis() self.column_axis.setTitle('Channels') self.column_axis.setTitleVisible(True) self.column_axis.setLabels([ 'Channel 1', 'Channel 2', 'Channel 3', 'Channel 4', 'Channel 5', 'Channel 6', 'Channel 7', 'Channel 8', 'Channel 9', 'Channel 10', 'Channel 11', 'Channel 12', 'Channel 13' ]) self.column_axis.setLabelAutoRotation(45) self.column_axis.setAutoAdjustRange(True) self.row_axis = QtDataVisualization.QCategory3DAxis() self.row_axis.setTitle('Timeline') self.row_axis.setTitleVisible(True) self.value_axis = QtDataVisualization.QValue3DAxis() self.value_axis.setTitle('RSSI [dBm]') self.value_axis.setTitleVisible(True) self.value_axis.setRange(-100, -10) self.bars.setRowAxis(self.row_axis) self.bars.setColumnAxis(self.column_axis) self.bars.setValueAxis(self.value_axis) self.bars.setBarSpacingRelative(False) self.bars.setFloorLevel(-100) self.series = QtDataVisualization.QBar3DSeries() self.array_data = [[]] self.series.dataProxy().addRows( self.data_to_bar_data_array(self.array_data)) self.series.setBaseColor(self.graph_item_color) self.bars.setPrimarySeries(self.series) self.container = QWidget.createWindowContainer(self.bars) if not self.bars.hasContext(): print("Couldn't initialize the OpenGL context") sys.exit(-1) camera = self.bars.scene().activeCamera() camera.setXRotation(-45.0) camera.setYRotation(22.5) geometry = QGuiApplication.primaryScreen().geometry() size = geometry.height() * 3 / 4 self.container.setMinimumSize(size, size) self.container.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.container.setFocusPolicy(Qt.StrongFocus) self.append_data([ -100, -80, -100, -80, -100, -80, -100, -80, -100, -80, -100, -80, -100 ]) self.nav_layout_h = QHBoxLayout() self.freeze_check = QCheckBox() self.freeze_check.setText("Freeze") self.freeze_check.clicked.connect(self.enable_scrolling_data) self.freeze_check.stateChanged.connect(self.freeze_graph) self.prev_button = QPushButton() self.prev_button.setText("Previous") self.prev_button.setEnabled(False) self.prev_button.clicked.connect(self.previous_data) self.next_button = QPushButton() self.next_button.setText("Next") self.next_button.setEnabled(False) self.next_button.clicked.connect(self.next_data) self.nav_layout_h.addWidget(self.freeze_check) self.nav_layout_h.addWidget(self.prev_button) self.nav_layout_h.addWidget(self.next_button) self.load_data_check = QCheckBox() self.load_data_check.setText("Load archival data") self.load_data_check.clicked.connect(self.enable_load_data) self.load_data_combo = QComboBox() self.load_data_combo.addItem("No data found") self.load_data_combo.setEnabled(False) self.load_data_btn = QPushButton() self.load_data_btn.setText("Load") self.load_data_btn.setEnabled(False) self.nav_layout_h2 = QHBoxLayout() self.nav_layout_h2.addWidget(self.load_data_check) self.nav_layout_h2.addWidget(self.load_data_combo) self.nav_layout_h2.addWidget(self.load_data_btn) thread4.start() thread4.remove_defualt_item.connect( lambda: self.load_data_combo.clear()) thread4.append_available_day.connect( lambda s: self.load_data_combo.addItem(s)) thread4.send_data_from_database.connect( lambda t: self.append_data_from_database(t)) self.load_data_combo.currentTextChanged.connect( lambda t: thread4.get_curr_table(t)) self.load_data_btn.clicked.connect(thread4.load_data_button) self.vertical_timeline_layout.addWidget(self.container) self.vertical_timeline_layout.addLayout(self.nav_layout_h) self.vertical_timeline_layout.addLayout(self.nav_layout_h2) #Bluetooth tab thread2.clear_blue_list.connect(self.blue_list_view.clear) thread2.append_blue_list_item.connect( lambda i: self.blue_list_view.addItem(i)) #Console tab self.console_autoscroll_check.stateChanged.connect( self.enable_auto_scroll) thread3 = WriteToFile.WriteToFile(self) self.console_logging_check.stateChanged.connect(thread3.enable_logging) thread2.send_text_signal.connect(lambda t: thread3.write_to_file(t)) self.window.show() def change_board(self): """ Disable Bluetooth scan option if ESP8266 board is selected """ print(self.select_board_box.currentText()) if self.select_board_box.currentText() == "ESP8266": self.blue_scan_box.setEnabled(False) elif self.select_board_box.currentText() == "ESP32": self.blue_scan_box.setEnabled(True) def enable_auto_scroll(self): """ Enable scrolling in text console """ if self.console_autoscroll_check.checkState() == Qt.Checked: self.console_text_edit.moveCursor(QTextCursor.End) else: self.console_text_edit.moveCursor(QTextCursor.Start) def freeze_graph(self, state): """ Stop showing live data in 3d Wi-Fi graph """ if state == 2: self.freeze_graph_bool_val = True else: self.freeze_graph_bool_val = False def data_to_bar_data_row(self, data): """ DOCSTRING """ return list(QtDataVisualization.QBarDataItem(d) for d in data) def data_to_bar_data_array(self, data): """ DOCSTRING """ return list(self.data_to_bar_data_row(row) for row in data) def append_data(self, data): """ DOCSTRING """ self.wifi_channels_occupancy_array.append(data) self.wifi_channels_timestamps.append(str(datetime.datetime.now())) self.update_graph() def update_graph(self): """ DOCSTRING """ if len(self.wifi_channels_occupancy_array) < 10: missing_vals = 10 - len(self.wifi_channels_occupancy_array) for z in range(missing_vals): self.wifi_channels_occupancy_array.append([ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]) self.wifi_channels_timestamps.append("") self.print_freshes_ten() elif len(self.wifi_channels_occupancy_array ) > 20 and self.deleted_empty_vals is False: for y in range( self.wifi_channels_occupancy_array.count([ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ])): self.wifi_channels_occupancy_array.remove([ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]) self.wifi_channels_timestamps.remove("") self.deleted_empty_vals = True self.print_freshes_ten() else: self.print_freshes_ten() def previous_data(self): """ DOCSTRING """ if self.last_item < 9 and len(self.wifi_channels_occupancy_array) < 9: QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning', "To few information to rewind!", QMessageBox.Ok) elif self.last_item < 9: print('out of range') QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning', "No more data to rewind!", QMessageBox.Ok) else: temp_array = [] temp_timestamp_array = [] if self.last_item - 9 < 0: print('out of range') QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning', "No more data to rewind!", QMessageBox.Ok) else: for x in range(self.last_item - 10, self.last_item - 1): temp_array.append(self.wifi_channels_occupancy_array[x]) temp_timestamp_array.append( self.wifi_channels_timestamps[x]) self.last_item = self.last_item - 9 self.row_axis.setLabels(temp_timestamp_array) self.series.dataProxy().resetArray() self.series.dataProxy().addRows( self.data_to_bar_data_array(temp_array)) def next_data(self): """ DOCSTRING """ if self.last_item < 9 and len(self.wifi_channels_occupancy_array) < 9: QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning', "To few information to rewind!", QMessageBox.Ok) elif self.last_item > len(self.wifi_channels_occupancy_array): print('out of range') QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning', "No more data to rewind!", QMessageBox.Ok) else: temp_array = [] temp_timestamp_array = [] if self.last_item + 9 > len(self.wifi_channels_occupancy_array): print('out of range') QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning', "No more data to rewind!", QMessageBox.Ok) else: for x in range(self.last_item + 1, self.last_item + 10): temp_array.append(self.wifi_channels_occupancy_array[x]) temp_timestamp_array.append( self.wifi_channels_timestamps[x]) self.last_item = self.last_item + 9 self.row_axis.setLabels(temp_timestamp_array) self.series.dataProxy().resetArray() self.series.dataProxy().addRows( self.data_to_bar_data_array(temp_array)) def print_freshes_ten(self): """ DOCSTRING """ if self.freeze_graph_bool_val is False: i = 0 temp_array = [] temp_timestamp_array = [] self.last_item = 0 for x in range(len(self.wifi_channels_occupancy_array) - 1): if i < 10: temp_array.append(self.wifi_channels_occupancy_array[ len(self.wifi_channels_occupancy_array) - x - 1]) temp_timestamp_array.append(self.wifi_channels_timestamps[ len(self.wifi_channels_timestamps) - x - 1]) i += 1 elif i == 10: self.last_item = len( self.wifi_channels_occupancy_array) - 10 i += 1 self.row_axis.setLabels(temp_timestamp_array) self.series.dataProxy().resetArray() self.series.dataProxy().addRows( self.data_to_bar_data_array(temp_array)) def enable_scrolling_data(self, state): """ DOCSTRING """ if state is True: self.prev_button.setEnabled(True) self.next_button.setEnabled(True) else: self.prev_button.setEnabled(False) self.next_button.setEnabled(False) def enable_load_data(self, state): """ DOCSTRING """ if state is True: self.load_data_combo.setEnabled(True) if (self.load_data_combo.findText("No data found") == -1 or self.load_data_combo.findText("Nie znaleziono danych")): self.load_data_btn.setEnabled(True) else: self.load_data_combo.setEnabled(False) self.load_data_btn.setEnabled(False) self.wifi_channels_occupancy_array = [] self.wifi_channels_timestamps = [] self.print_freshes_ten() def change_language(self, lang): """ DOCSTRING """ if lang == "Polski": QCoreApplication.installTranslator(self.trans) self.axis_x.setTitleText("Częstotliwość [MHz]") self.freeze_check.setText("Zamróź") self.load_data_check.setText("Otwórz dane archiwalne") self.load_data_combo.removeItem( self.load_data_combo.findText("No data found")) self.load_data_combo.addItem("Nie znaleziono danych") self.load_data_btn.setText("Otwórz") self.next_button.setText("Następny") self.prev_button.setText("Poprzedni") self.column_axis.setTitle('Kanały') self.column_axis.setLabels([ 'Kanał 1', 'Kanał 2', 'Kanał 3', 'Kanał 4', 'Kanał 5', 'Kanał 6', 'Kanał 7', 'Kanał 8', 'Kanał 9', 'Kanał 10', 'Kanał 11', 'Kanał 12', 'Kanał 13' ]) self.row_axis.setTitle('Oś czasu') self.bars.setColumnAxis(self.column_axis) self.bars.setRowAxis(self.row_axis) else: QCoreApplication.removeTranslator(self.trans) self.axis_x.setTitleText("Frequency [MHz]") self.freeze_check.setText("Freeze") self.load_data_check.setText("Load archival data") self.load_data_combo.removeItem( self.load_data_combo.findText("Nie znaleziono danych")) self.load_data_combo.addItem("No data found") self.load_data_btn.setText("Load") self.next_button.setText("Next") self.prev_button.setText("Previous") self.column_axis.setTitle('Channels') self.column_axis.setLabels([ 'Channel 1', 'Channel 2', 'Channel 3', 'Channel 4', 'Channel 5', 'Channel 6', 'Channel 7', 'Channel 8', 'Channel 9', 'Channel 10', 'Channel 11', 'Channel 12', 'Channel 13' ]) self.row_axis.setTitle('Timeline') self.bars.setColumnAxis(self.column_axis) self.bars.setRowAxis(self.row_axis) def append_data_from_database(self, data): """ DOCSTRING !!! """ self.wifi_channels_occupancy_array = [] self.wifi_channels_timestamps = [] self.print_freshes_ten() for row in data: itm_nmbr = 0 self.temp_db_array = [] for item in row: if itm_nmbr == 1: self.wifi_channels_timestamps.append( "" + str(self.load_data_combo.currentText()) + " " + item + "") elif itm_nmbr > 1: self.temp_db_array.append(item) itm_nmbr += 1 self.wifi_channels_occupancy_array.append(self.temp_db_array) self.print_freshes_ten()
def __init__(self, ui_file, parent=None): self.DEFAULT_PICTURE = "actions/pictures/default.png" self.CUSTOM_COMMAND_ROW = 'Custom command...' self.UP = 1 self.DOWN = -1 self.is_saved = True self.is_recording = False self.is_rewriting_mode = False # add -> false, rewrite -> true self.csv_linked_path = '' self.opened_box_id = -1 self.keys_map = dict() if 'key_settings.xml' in (os.listdir(os.getcwd() + '\\settings')): self.keys_map = SettingsParser.parse_to_sequence( os.getcwd() + '\\settings\\key_settings.xml') self.custom_commands = dict() self.command_box = QComboBox() self.complex_keys = list() super(ActionWindow, self).__init__(parent) ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() self.window = loader.load(ui_file) ui_file.close() # tab self.tab_action: QTableWidget = self.window.findChild( QTableWidget, "tab_action") self.tab_action.horizontalHeader().setStretchLastSection(True) self.btn_add = self.window.findChild(QPushButton, "btn_add") self.btn_down = self.window.findChild(QPushButton, "btn_down") self.btn_up = self.window.findChild(QPushButton, "btn_up") self.btn_remove = self.window.findChild(QPushButton, "btn_remove") self.btn_merge: QPushButton = self.window.findChild( QPushButton, "btn_merge") self.btn_record: QPushButton = self.window.findChild( QPushButton, "btn_record") # img self.act_picture = self.window.findChild(QLabel, "img_action") self.le_name = self.window.findChild(QLineEdit, "le_name") self.rbtn_add: QRadioButton = self.window.findChild( QRadioButton, "rbtn_add") self.rbtn_rewrite: QRadioButton = self.window.findChild( QRadioButton, "rbtn_rewrite") self.menu_file = self.window.findChild(QMenu, 'menuFile').actions() self.menu_new = self.menu_file[0] self.menu_load = self.menu_file[1] self.menu_save = self.menu_file[2] self.menu_save_as = self.menu_file[3] self.menu_import_pic = self.menu_file[5] self.menu_settings: QAction = self.window.findChild( QMenu, 'menuSettings').actions()[0] self.sc_record: QtWidgets.QShortcut = QtWidgets.QShortcut( QKeySequence('Ctrl+R'), self.btn_record) self.btn_add.clicked.connect(self.add_row) self.btn_remove.clicked.connect(self.remove_row) self.btn_up.clicked.connect(self.up_row) self.btn_down.clicked.connect(self.down_row) self.btn_merge.clicked.connect(self.merge_row) self.btn_record.clicked.connect(self.toggle_recording) self.command_box.textActivated.connect( lambda command: self.close_box_in_cell(command)) self.rbtn_add.clicked.connect(self.check_add_mode) self.rbtn_rewrite.clicked.connect(self.check_rewrite_mode) #self.tab_action.itemChanged.connect(self.unsaved) self.tab_action.itemChanged.connect(self.unsaved) self.tab_action.cellClicked.connect( lambda row, column: self.init_box_signal(row, column)) self.menu_new.triggered.connect(self.new_pic_action) self.menu_import_pic.triggered.connect(self.import_picture) self.menu_save.triggered.connect(self.save_short) self.menu_save_as.triggered.connect(self.save_full) self.menu_settings.triggered.connect(self.show_loading_settings_dialog) self.menu_load.triggered.connect(self.load_action) self.rbtn_add.setChecked(True) self.window.installEventFilter(self) self.act_picture.setPixmap(QtGui.QPixmap(self.DEFAULT_PICTURE)) self.tab_action.setRowCount(0) self.window.setWindowTitle('{} Admin'.format( GlobalParams.application_name)) self.window.show()
class StockWindow: def __init__(self, excel_manager): self.excel_manager = excel_manager self.ui_file = QFile("product_select.ui") self.ui_file.open(QFile.ReadOnly) self.loader = QUiLoader() self.main_window = self.loader.load(self.ui_file) self.ui_file.close() self.main_window.show() # 콤보박스 객체 저장 self.combobox_manufacturer = None self.combobox_product = None self.combobox_weight = None self.combobox_color = None self.combobox_size = None # 콤보박스 선택된 item Text self.combobox_manufacturer_text = None self.combobox_product_text = None self.combobox_weight_text = None self.combobox_color_text = None self.combobox_size_text = None # 제조사 콤보박스 객체 찾기 cb = self.main_window.findChild(QtWidgets.QComboBox, "comboBox") self.combobox_manufacturer = cb # 제조사 콤보박스에 시그널 별로 슬랏 연결 cb.activated.connect(self.activated_manufacturer) # 제품 콤보박스 객체 찾기 cb2 = self.main_window.findChild(QtWidgets.QComboBox, "comboBox_2") self.combobox_product = cb2 # 제품 콤보박스에 시그널 슬랏 연결 cb2.activated.connect(self.activated_product) # 무게 콤보박스 객체 찾기 cb3 = self.main_window.findChild(QtWidgets.QComboBox, "comboBox_3") self.combobox_weight = cb3 # 제품 콤보박스에 시그널 슬랏 연결 cb3.activated.connect(self.activated_weight) # 컬러 콤보박스 객체 찾기 cb4 = self.main_window.findChild(QtWidgets.QComboBox, "comboBox_4") self.combobox_color = cb4 # 제품 콤보박스에 시그널 슬랏 연결 cb3.activated.connect(self.activated_color) self.combobox_add_manufacturer() def combobox_add_manufacturer(self): cb = self.combobox_manufacturer # 엑셀 메니저에서 제조사 리스트 가져오기 mf_list = self.excel_manager.get_manufacturer() # 제조사 리스트 콤보박스에 아이템 추가 cb.addItems(mf_list) def activated_manufacturer(self): print("activated") # 현재 선택된 아이템 저장 text = self.combobox_manufacturer.currentText() self.combobox_manufacturer_text = text print(text) # 선택된 제조사를 보고 그 제조사 제품을 추가 self.combobox_add_product() def combobox_add_product(self): # 제조사에 해당하는 제품 리스트 가져오기 name = self.combobox_manufacturer_text p_list = self.excel_manager.get_products(name) print(p_list) # 제품 콤보박스에 제품리스트 추가 cb2 = self.combobox_product cb2.addItems(p_list) def activated_product(self): print("activated") # 현재 선택된 아이템 저장 text = self.combobox_product.currentText() self.combobox_product_text = text print(text) # 선택된 제조사를 보고 그 제조사 제품을 추가 self.combobox_add_weight() def combobox_add_weight(self): name = self.combobox_product_text w_list = self.excel_manager.get_weight(name) print(w_list) cb3 = self.combobox_weight cb3.addItems(w_list) def activated_weight(self): print("activated") # 현재 선택된 아이템 저장 text = self.combobox_weight.currentText() self.combobox_weight_text = text print(text) # 선택된 제조사를 보고 그 제조사 제품을 추가 self.combobox_add_color() def combobox_add_color(self): name = self.combobox_weight_text c_list = self.excel_manager.get_color(name) print(c_list) cb4 = self.combobox_color cb4.addItems(c_list) def activated_color(self): print("activated") # 현재 선택된 아이템 저장 text = self.combobox_color.currentText() self.combobox_color_text = text print(text) # 선택된 제조사를 보고 그 제조사 제품을 추가 # self.combobox_add_size() def highlighted(self): print("highlighted") def idxchanged(self): print("idx changed")
class ShowInvoice(QWidget): def __init__(self, action, parent=None): super(ShowInvoice, self).__init__(parent) self.path = os.path.join('faces', 'invoicing.ui') self.ui_file = QFile(self.path) self.ui_file.open(QFile.ReadOnly) self.loader = QUiLoader() self.dialog = self.loader.load(self.ui_file, self) self.ui_file.close() self.action = action # определим элементы управления self.label = self.dialog.findChild(QLabel, 'label') self.table_bill = self.dialog.findChild(QTableWidget, 'table_bill') self.btn_add = self.dialog.findChild(QPushButton, 'btn_add') self.btn_changed = self.dialog.findChild(QPushButton, 'btn_changed') self.btn_delete = self.dialog.findChild(QPushButton, 'btn_delete') # назначим подсказки для элементов self.btn_changed.setToolTip('Выбрать счёт для создание акта') # задаём специальные размеров колонок self.table_bill.setColumnWidth(0, 80) # дата self.table_bill.setColumnWidth(1, 80) # сумма self.table_bill.setColumnWidth(2, 160) # контрагент # колонка "комментарий" использует остаток пространства # смена названия кнопок self.btn_changed.setText('Выбрать') # убираем лишние кнопки self.btn_add.hide() self.btn_delete.hide() self.period = [] self.id_invoices = [] # ID данных загружаемых из таблицы Invoice self.filling_table() # метод формирование надписи def change_period(self): query_list = conn.query(Invoice).filter(Invoice.date_invoice).all() data_list = [] for elem in query_list: data_list.append(elem.date_invoice.strftime("%d.%m.%Y")) data_list.sort(key=lambda d: datetime.strptime(d, '%d.%m.%Y')) if data_list: first = data_list[0] last = data_list[-1] self.label.setText(f'C {first} по {last}') # метод добавление данных в новую строку def set_data_in_new_row(self, data: list): rows = self.table_bill.rowCount() self.table_bill.setRowCount(int(rows + 1)) columns = self.table_bill.columnCount() for i in range(0, columns): item = QtWidgets.QTableWidgetItem(str(data[i])) self.table_bill.setItem(rows, i, item) # метод заполнения таблицы def filling_table(self): self.table_bill.setRowCount(int(0)) # удаляем строки items = conn.query(Invoice).all() self.id_invoices = [] for item in items: # пересохраняем объект таблицы в строчку row = [] self.id_invoices.append(item.id) row.append(item.date_invoice.strftime("%d.%m.%Y")) row.append(item.summ_invoice) name_company = conn.query(Counterparties).filter( Counterparties.id == item.id_company).first().name_c row.append(name_company) row.append(item.comment_invoice) # вставляем строчку в таблицу self.set_data_in_new_row(row) self.change_period() # метод возвращвет ID выбранного счёта def selected_invoice(self): selected_row = self.table_bill.currentItem() index_row = self.table_bill.row(selected_row) result = self.id_invoices[index_row] return result
def __init__(self): super(MainWindow, self).__init__() self.system_id = DataBase.select('system_id') self.device_version = DataBase.select('app_version') self.device_mode = DataBase.select('device_mode') loader = QUiLoader() self.ui = loader.load('main.ui', None) sp_retain = QSizePolicy() sp_retain.setRetainSizeWhenHidden(True) self.ui.btn_left.setSizePolicy(sp_retain) self.ui.btn_right.setSizePolicy(sp_retain) self.ui.lbl_device_info.setSizePolicy(sp_retain) self.ui.btn_setting.setSizePolicy(sp_retain) self.btnOwnerLogin = CustomButton() self.btnOwnerLogin.setGif("animations/Rolling-white.gif") self.ui.vLayoutSignInOwner.addWidget(self.btnOwnerLogin) self.ui.vLayoutSignInOwner.setAlignment(Qt.AlignHCenter) self.btnUserLoginID = CustomButton() self.btnUserLoginID.setGif("animations/Rolling-white.gif") self.lbl = QLabel(None) self.lbl.setStyleSheet(BTN_PASS_RECOVERY_STYLE) self.ui.vLayoutSignInUser.addWidget(self.btnUserLoginID) self.ui.vLayoutSignInUser.addWidget(self.lbl) self.ui.vLayoutSignInUser.setAlignment(Qt.AlignHCenter) self.btnUserLoginMobile = CustomButton() self.btnUserLoginMobile.setGif("animations/Rolling-white.gif") self.lbl = QLabel(None) self.lbl.setStyleSheet(BTN_PASS_RECOVERY_STYLE) # Threads self.auto_delivery_items_thread = AutoDeliveryItemsThread() self.rfid_thread = RFIDThread() self.rfid_thread.success_signal.connect(self.successTransferToRFIDCard) self.rfid_thread.fail_signal.connect(self.transferToRFIDCard) # signals self.ui.btn_refresh_loading.clicked.connect(self.refresh) self.ui.btn_main_menu_1.clicked.connect(self.checkDeviceMode) self.ui.btn_start.hide() #self.ui.btn_main_menu_3.clicked.connect(self.stackFastCharging) self.ui.btn_main_menu_4.clicked.connect(self.stackWalletServices) self.ui.btn_print_receipt_yes.clicked.connect(self.printReceipt) self.ui.btn_print_receipt_no.clicked.connect(self.stackStart) self.ui.btn_other_services_after_delivery.clicked.connect( self.stackWalletServices) self.ui.btn_no_exit_app_setting.clicked.connect(self.stackSetting) self.ui.btn_yes_exit_app_setting.clicked.connect(self.exitProgram) self.ui.btn_setting_start.clicked.connect(self.stackStart) self.ui.btn_setting_1.clicked.connect(self.stackDeviceMode) self.ui.btn_setting_5.clicked.connect(self.stackConveyorPort) self.ui.btn_setting_2.clicked.connect(self.stackPressMotor) # self.ui.btn_setting_10.clicked.connect(self.stackSeparationMotor) self.ui.btn_setting_3.clicked.connect(self.stackSensor1Ports) self.ui.btn_setting_9.clicked.connect(self.stackSensor2Ports) self.ui.btn_setting_6.clicked.connect(self.stackExitApp) self.ui.btn_wallet_services_1.clicked.connect( self.stackChargingResidentialUnit) self.ui.btn_wallet_services_2.clicked.connect(self.stackRFID) self.ui.btn_wallet_services_3.clicked.connect(self.stackCharity) self.ui.btn_wallet_services_4.clicked.connect( self.stackEnvirnmentalProtection) self.ui.btn_wallet_services_5.clicked.connect(self.stackWallet) self.ui.btn_plus_charity.clicked.connect(self.plusCharity) self.ui.btn_minus_charity.clicked.connect(self.minusCharity) self.ui.btn_plus_envirnmental_protection.clicked.connect( self.plusEnvirnment) self.ui.btn_minus_envirnmental_protection.clicked.connect( self.minusEnvirnment) self.ui.btn_plus_rfid.clicked.connect(self.plusRFID) self.ui.btn_minus_rfid.clicked.connect(self.minusRFID) self.ui.btn_confirm_transfer_to_RFIDcard.clicked.connect( self.transferToRFIDCard) self.ui.btn_charity_1.clicked.connect( lambda: self.ui.lbl_selected_charity.setText(self.ui.lbl_charity_1. text())) self.ui.btn_charity_2.clicked.connect( lambda: self.ui.lbl_selected_charity.setText(self.ui.lbl_charity_2. text())) self.ui.btn_charity_3.clicked.connect( lambda: self.ui.lbl_selected_charity.setText(self.ui.lbl_charity_3. text())) self.ui.btn_charity_4.clicked.connect( lambda: self.ui.lbl_selected_charity.setText(self.ui.lbl_charity_4. text())) self.ui.btn_envirnmental_protection_1.clicked.connect( lambda: self.ui.lbl_selected_envirnmental_protection.setText( self.ui.lbl_envirnmental_protection_1.text())) self.ui.btn_envirnmental_protection_2.clicked.connect( lambda: self.ui.lbl_selected_envirnmental_protection.setText( self.ui.lbl_envirnmental_protection_2.text())) self.ui.btn_envirnmental_protection_3.clicked.connect( lambda: self.ui.lbl_selected_envirnmental_protection.setText( self.ui.lbl_envirnmental_protection_3.text())) self.ui.btn_envirnmental_protection_4.clicked.connect( lambda: self.ui.lbl_selected_envirnmental_protection.setText( self.ui.lbl_envirnmental_protection_4.text())) self.ui.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) self.ui.showMaximized() self.back_delivery_item_flag = False self.flag_system_startup_now = True self.delivery_state = 'none' # self.categories = Server.getCategories() self.image_classifier = ImageClassifier() self.predict_item_threshold = float( DataBase.select('predict_item_threshold')) self.initHardwares() self.readFile() self.stackSetting() self.playSound('audio2') self.refresh()
def __init__(self, parent=None): super(CmdLib, self).__init__(parent) # open ui file directly ui_file = QFile('mainwindow.ui') ui_file.open(QFile.ReadOnly) loader = QUiLoader() self.window = loader.load(ui_file) ui_file.close() # app name and version self.appname = "CmdLib" self.version = "0.1" # set fixed window size #self.window.setFixedSize(self.window.size()) # set title and center window self.window.setWindowTitle(self.appname) self.center_window() # print available styles print(QStyleFactory.keys()) ##### SIGNALS # run command self.window.button_run_term.clicked.connect(self.run_cmd_term) # load cmd #self.window.cmd_list.clicked.connect(self.load_cmd) self.window.cmd_list.itemSelectionChanged.connect(self.load_cmd) #self.window.cmd_list.currentRowChanged.connect(self.load_cmd) # add cmd to list self.window.button_to_list.clicked.connect(self.save_cmd) # delete cmd self.window.button_delete_cmd.clicked.connect(self.delete_cmd) # multi cmd mode self.window.multicmd_mode.clicked.connect(self.multicmd_mode) # is script mode self.window.check_script.clicked.connect(self.is_script) # search self.window.search_box.currentTextChanged.connect(self.search_cmds) # workdir self.window.set_workdir.clicked.connect(self.set_workdir) self.window.open_workdir.clicked.connect(self.open_workdir) self.window.workdir_line.editingFinished.connect(self.check_workdir) # show help from helpbox self.window.show_helpbox.clicked.connect(self.show_help) # new cmd self.window.new_button.clicked.connect(self.new_cmd) # copy cmd self.window.copy_button.clicked.connect(self.copy2clipboard) # add file name self.window.addfile_button.clicked.connect(self.on_insert_file_name) # open file self.window.openfile_button.clicked.connect(self.on_open_file_button) # if cmd selection is changed self.window.cmd_field.selectionChanged.connect( self.set_open_file_button) # check name self.window.name_field.textChanged.connect(self.check_name) # check command self.window.cmd_field.textChanged.connect(self.check_command) # DROP signal!! self.window.cmd_list.model().rowsMoved.connect(self.reorder_cmds) # menu/actions self.window.actionBackupLib.triggered.connect(self.backup) self.window.actionExportLib.triggered.connect(self.exportlib) self.window.actionImportLib.triggered.connect(self.importlib) self.window.actionInsert_File_Name.triggered.connect( self.on_insert_file_name) self.window.actionInsert_File_Path.triggered.connect( self.on_insert_file_path) self.window.actionExport2Script.triggered.connect(self.export2script) self.window.actionGet_File_Name.triggered.connect( self.on_copy_file_name) self.window.actionGet_File_Path.triggered.connect( self.on_copy_file_path) self.window.actionOpen_Scripts_Folder.triggered.connect( self.open_scriptsdir) self.window.actionOpen_File.triggered.connect(self.open_file) self.window.actionOpen_Script.triggered.connect(self.open_script) self.window.actionAbout.triggered.connect(self.on_about) # extra shortcuts # delete cmd from cmdlist QShortcut(QKeySequence(Qt.Key_Delete), self.window.cmd_list, self.delete_cmd) # save cmd QShortcut(QKeySequence("Ctrl+S"), self.window, self.on_save_cmd) # new cmd QShortcut(QKeySequence("Ctrl+N"), self.window, self.new_cmd) # new cmd QShortcut(QKeySequence("Ctrl+H"), self.window, self.show_help) # run in term QShortcut(QKeySequence("Ctrl+Return"), self.window, self.run_cmd_term) # focus on search QShortcut(QKeySequence("Ctrl+F"), self.window, self.focus_search) # focus on lib QShortcut(QKeySequence("Ctrl+L"), self.window, self.focus_lib) QShortcut(QKeySequence(Qt.Key_Tab), self.window, self.focus_lib) # trigger when quitting app.aboutToQuit.connect(self.on_quit) # update cmd list self.update_cmd_list() # select first cmd self.window.cmd_list.setCurrentRow(0) # load init command self.load_cmd() # set search box to All self.window.search_box.setCurrentIndex(0) #set focus on search box self.focus_search() # if provided, set first argument to workdir self.set_workdir_with_arg() # make start backup self.df.to_csv("./backups/cmds.csv", index=False) # show main window self.window.show()
def __init__(self, ui_file, parent=None): super(MainWindow, self).__init__(parent) ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) self.compartment_list = list() # Empty compartment_list initialized self.variable_list = list() # Empty variable list initialized self.simulation = None # Simulation is generated after compilation self.substitutions = dict() # Substitutions come from exec code loader = QUiLoader() loader.registerCustomWidget( QTableWidgetDragRows ) # Register custom QTableWidgetDragRows for Drag and Right-Click functions self.window = loader.load(ui_file) ui_file.close() plt.rc('text', usetex=True ) # set matplotlib options so that it uses LaTeX formatting plt.rc('font', family='serif') # Find buttons and link them to the respective functions, signals and options action_save_digraph = self.window.findChild(QAction, 'actionSaveDigraph') action_save_digraph.triggered.connect(self.save_digraph_event) action_save_plot = self.window.findChild(QAction, 'actionSavePlot') action_save_plot.triggered.connect(self.save_plot_event) add_compartment_button = self.window.findChild(QPushButton, 'AddCompartmentButton') add_compartment_button.clicked.connect( self.open_add_compartment_dialog) add_variable_button = self.window.findChild(QPushButton, 'AddVariableButton') add_variable_button.clicked.connect(self.open_add_variable_dialog) compile_button = self.window.findChild(QPushButton, 'CompileButton') compile_button.clicked.connect(self.compile) run_simulation_button = self.window.findChild(QPushButton, 'SimulateButton') run_simulation_button.clicked.connect(self.open_run_simulation) show_r0_button = self.window.findChild(QPushButton, 'R0Button') show_r0_button.clicked.connect(self.show_r0) self.compartment_table = self.window.findChild(QTableWidgetDragRows, 'CompartmentTable') self.compartment_table.setEditableInfectionState(True) self.compartment_table.delItem.connect(self.remove_item) self.compartment_table.editIS.connect(self.toggle_is) self.compartment_table.dropSignal.connect(self.drop_event) self.variable_table = self.window.findChild(QTableWidgetDragRows, 'VariableTable') self.variable_table.setDragEnabled( False) # Set this table to be undraggable self.variable_table.delItem.connect(self.remove_item) self.vital_dynamics_checkbox = self.window.findChild( QCheckBox, 'VitalDynamicsCheckBox') self.vital_dynamics_checkbox.stateChanged.connect( self.vital_dynamics_toggle) self.diagram_view = self.window.findChild( QGraphicsView, 'DiagramView') # Diagram for NetworkX Graph self.logging_view = self.window.findChild( QGraphicsView, 'LoggingView') # Console for Logging progress self.timeLE = self.window.findChild(QLineEdit, 'TimeLE') self.timeLE.setValidator(QIntValidator( )) # Validator to ensure only integers are placed in Time LineEdit self.window.setWindowIcon(QIcon(os.path.join( 'ui_files', 'icon.png'))) # Set the window icon self.window.show()
import sys from PySide2 import QtWidgets from PySide2.QtUiTools import QUiLoader loader = QUiLoader() def mainwindow_setup(w): w.setWindowTitle("MainWindow Title") app = QtWidgets.QApplication(sys.argv) window = loader.load("mainwindow.ui", None) mainwindow_setup(window) window.show() app.exec_()
conf = open("arduino.txt", "r+") arduino = conf.read() conf.close() conf = open("metapath.txt", "r+") metapath = conf.read() conf.close() #start GUI app = QApplication(sys.argv) # load UI files created with QT ui_file = QFile("main.ui") ui_2file = QFile("settings.ui") ui_file.open(QFile.ReadOnly) loader = QUiLoader() window = loader.load(ui_file) ui_file.close() window.show() window.setWindowTitle("Sherd Capture") loader2 = QUiLoader() setwin = loader2.load(ui_2file) ui_2file.close() #GUI functions that get called on buttons pressed. window.actionSettings.triggered.connect(settingsKlick) window.actionExit.triggered.connect(exit) window.capture.clicked.connect(startCapture) window.pushButton_2.clicked.connect(show_browser) window.pushButton.clicked.connect(breakLoop) window.pushButton_4.clicked.connect(projectApply) setwin.setApply.clicked.connect(settingsApply)
class c_membro(): c_membro = None def __init__(self): global c_membro self.jan = QtGui.qApp self.arquivo = QFile("cadastro_de_membro.ui") self.arquivo.open(QFile.ReadOnly) self.carrega = QUiLoader() c_membro = self.carrega.load(self.arquivo) def cadastra_membro(): nome = c_membro.le_nome.text() endereco = c_membro.le_endereco.text() d_bat = c_membro.le_d_bat.text() d_con = c_membro.le_d_con.text() contato = c_membro.le_contato.text() rg = c_membro.le_rg.text() cpf = c_membro.le_cpf.text() cargo = str(c_membro.combo_cargo.currentText()) if nome != "" and endereco != "" and len(d_bat) == 10 and len( d_con) == 10 and len(contato) == 16 and len( rg) == 13 and len(cpf) == 14: if cpf_db(cpf) == True: if verificar_cpf(cpf) == True: try: db = conecta_db(meu_db[0]) cursor = db.cursor() sql = "INSERT INTO clientes(nome, endereco, rg, cpf, contato, cargo, d_bat, d_con) VALUES(%s, %s, %s, %s, %s, %s, %s, %s)" val = (str(nome), str(endereco), str(rg), str(cpf), str(contato), str(cargo), str(d_bat), str(d_con)) cursor.execute(sql, val) db.commit() aviso("Cadastro de Membro", "Cadastro efetuado com sucesso...") c_membro.le_nome.clear() c_membro.le_endereco.clear() c_membro.le_d_bat.setDate(QtCore.QDate(2000, 1, 1)) c_membro.le_d_con.setDate(QtCore.QDate(2000, 1, 1)) c_membro.le_contato.clear() c_membro.le_rg.clear() c_membro.le_cpf.clear() except BaseException as erro: print("Erro no cadastrado do cliente.", str(erro)) finally: cursor.close() db.close() else: aviso("Cadastro de Membro", "CPF Inválido, digite um cpf real") else: aviso("Cadastro de Membro", "CPF já cadastrado no banco") else: aviso("Cadastro de Membro", "Por favor prencha todos os parâmetros") c_membro.btn_salvar.clicked.connect(lambda: cadastra_membro()) #r self.arquivo.close() c_membro.show()
global verdmontot1 global usercompar1 verdmontot1=int(0) indforwid1=str(None) montotpre1=0 usercompar1 = None #userlog1=str('Master') #passw1=str('master6969') QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) loginfile = QFile("iniciosesion.ui") loginfile.open(QFile.ReadOnly) loader = QUiLoader() loginwindow = loader.load(loginfile) USqline1 = loginwindow.findChild(QLineEdit, 'Usuarioline1') PSqline1 = loginwindow.findChild(QLineEdit, 'passw1') alerforlog1=loginwindow.findChild(QLabel, 'aviso1') btn_brow_1 = loginwindow.findChild(QPushButton, 'inisesbut1') loginwindow.show() ##### Ventana de Ventas venfile1 = QFile("ventaventana.ui") venfile1.open(QFile.ReadOnly) loader2 = QUiLoader() venwindow2 = loader2.load(venfile1) nomqline2 = venwindow2.findChild(QLineEdit, 'busnom1') codqline2 = venwindow2.findChild(QLineEdit, 'buscod1') codadd2 = venwindow2.findChild(QLineEdit, 'addcodven1') canadd2 = venwindow2.findChild(QLineEdit, 'cantprodven1') btn_nom_1 = venwindow2.findChild(QPushButton, 'busnombut1')
class pesquisa_excluir(): pesquisa_excluir = None def __init__(self): global pesquisa_excluir self.jan = QtGui.qApp self.arquivo = QFile("excluircliente.ui") self.arquivo.open(QFile.ReadOnly) self.carrega = QUiLoader() pesquisa_excluir = self.carrega.load(self.arquivo) pesquisa_excluir.janela1.raise_() pesquisa_excluir.setFixedSize(287, 91) def x(): cp = pesquisa_excluir.le_cpf.text() if len(cp) == 14: try: db = conecta_db(meu_db[0]) cursor = db.cursor() sql = "SELECT * FROM clientes WHERE cpf = %s" val = (cp, ) cursor.execute(sql, val) usuarios = cursor.fetchone() if usuarios != None: pesquisa_excluir.janela2.raise_() pesquisa_excluir.setFixedSize(661, 581) l = [] for x in usuarios: l.append(x) pesquisa_excluir.le_nome.setText(l[1]) pesquisa_excluir.le_endereco.setText(l[2]) pesquisa_excluir.le_rg.setText(l[3]) pesquisa_excluir.le_cpf_2.setText(l[4]) pesquisa_excluir.le_contato.setText(l[5]) pesquisa_excluir.le_cargo.setText(l[6]) pesquisa_excluir.le_d_bat.setText(l[7]) pesquisa_excluir.le_d_con.setText(l[8]) def y(): try: db = conecta_db(meu_db[0]) cursor = db.cursor() cpf = pesquisa_excluir.le_cpf.text() print(cpf) sql = "SELECT * FROM clientes WHERE cpf = %s" val = (cpf, ) cursor.execute(sql, val) resultado = cursor.fetchall() if (len(resultado) > 0): for r in resultado: sql = "DELETE FROM clientes WHERE clientes.id = " + str( r[0]) cursor.execute(sql) db.commit() aviso( "CPF", "O MEMBRO " + cpf + " FOI EXCLUÍDO") pesquisa_excluir.close() except BaseException as e: print("AVISO", " ERRO AO EXCLUIR O MEMBRO" + str(e)) finally: cursor.close() db.close() pesquisa_excluir.btn_excluir.clicked.connect( lambda: y()) cursor.close() db.close() else: aviso("CPF", "CPF não cadastrado!!") except BaseException as erro: print("Erro ao pesquisa Cliente: " + str(erro)) else: aviso("CPF", "Digitos do cpf faltando") pesquisa_excluir.btn_ok.clicked.connect(x) self.arquivo.close() pesquisa_excluir.show()
class ShowBankDocs(QWidget): def __init__(self, parent=None): super(ShowBankDocs, self).__init__(parent) self.path = os.path.join('faces', 'show_bank_docs.ui') self.ui_file = QFile(self.path) self.ui_file.open(QFile.ReadOnly) self.loader = QUiLoader() self.dialog = self.loader.load(self.ui_file, self) self.ui_file.close() # определим элементы управления self.label = self.dialog.findChild(QLabel, 'label') self.date_start = self.dialog.findChild(QDateEdit, 'date_start') self.date_end = self.dialog.findChild(QDateEdit, 'date_end') self.cmbox_company = self.dialog.findChild(QComboBox, 'cmbox_company') self.cmbox_action = self.dialog.findChild(QComboBox, 'cmbox_action') self.btn_create = self.dialog.findChild(QPushButton, 'btn_create') # назначим подсказки для элементов self.btn_create.setToolTip('Сформировать отчёт') # добавляем значения по умолчанию: текущую дату self.date_start.setDate(QDate.currentDate()) self.date_end.setDate(QDate.currentDate()) # список контроагентов result = conn.query(Counterparties).all() if result: for elem in result: self.cmbox_company.addItem(str(elem.name_c)) # назначим действия для объектов self.btn_create.clicked.connect(self.create_report) self.setMaximumHeight(225) self.setMaximumWidth(473) def create_report(self): # собираем условия с формы # name_company = self.cmbox_company.currentText() # id_company = conn.query(Counterparties).filter(Counterparties.name_c == name_company).first().id # data_start = self.date_start.text() # data_end = self.date_end.text() # action = self.cmbox_action.currentText() # приход / расход # формируем запрос в базу bank_query = conn.query(BankDocsRev).filter(BankDocsRev.date_docs >= self.date_start.date().toPython()).filter(BankDocsRev.date_docs <= self.date_end.date().toPython()).filter(BankDocsRev.action_docs == self.cmbox_action.currentText()).all() for item in bank_query: print(f'Контрагент: {item.p_counterparties.name_c}, сумма: {item.summ_docs:.2f}, статус документа: {item.action_docs}') # определяем пути к файлам path_empty = os.path.join('templates', 'report_bank.ods') path_full = os.path.join('temp', 'report_bank.ods') t = Template(path_empty, path_full) items = list() total_summ = 0 # перебираем значения из запроса for bank in bank_query: item = Item() item.date = bank.date_docs.strftime('%d.%m.%Y') # item.summ = str(round(bank.summ_docs, 2)).replace('.', ',') item.summ = round(bank.summ_docs, 2) item.counterp = bank.p_counterparties.name_c item.coment = bank.comment_docs items.append(item) total_summ += bank.summ_docs # формируем даты start_date = Item() start_date.date = datetime.strftime(self.date_start.date().toPython(), '%d.%m.%Y') end_date = Item() end_date.date = datetime.strftime(self.date_end.date().toPython(), '%d.%m.%Y') total = Item() # total.summ = str(round(total_summ, 2)).replace('.', ',') total.summ = round(total_summ, 2) # группируем данные для передачи в отчёт date = dict(items = items, start_date = start_date, end_date = end_date, total = total) # передаём данные в отчёт t.render(date) # открываем созданный отчёт if sys.platform == "win32": os.startfile(path_full) else: opener ="open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, path_full])
class LoginWindow(object): def __init__(self, main_window): self.main_window = main_window login_file = QFile('ui/login_dialog.ui') login_file.open(QFile.ReadOnly) self.loader = QUiLoader() self.dialog = self.loader.load(login_file) login_file.close() self.connect_slots() self.read_config() def show(self): self.dialog.show() def hide(self): self.dialog.hide() def connect_slots(self): for item in widgets: widget = getattr(self.dialog, item['name']) fn = getattr(self, item['fn']) QObject.connect(widget, SIGNAL(item['signal']), fn) def address_checkbox_changed(self, state): if not state: self.dialog.remember_username_checkbox.setChecked(False) self.dialog.remember_password_checkbox.setChecked(False) self.dialog.remember_username_checkbox.setEnabled(state) def username_checkbox_changed(self, state): if not state: self.dialog.remember_password_checkbox.setChecked(False) self.dialog.remember_password_checkbox.setEnabled(state) def read_config(self): saved_config = config.load_config() if 'filename' in saved_config['UserInfo']: filename = saved_config['UserInfo']['filename'] self.dialog.file_path_lineedit.setText(filename) if 'host' in saved_config['UserInfo']: host = saved_config['UserInfo']['host'] self.dialog.address_lineedit.setText(host) self.dialog.remember_address_checkbox.setChecked(True) if 'username' in saved_config['UserInfo']: username = saved_config['UserInfo']['username'] self.dialog.username_lineedit.setText(username) self.dialog.remember_username_checkbox.setChecked(True) if 'password' in saved_config['UserInfo']: password = saved_config['UserInfo']['password'] self.dialog.password_lineedit.setText(password) self.dialog.remember_password_checkbox.setChecked(True) def update_config(self, filename, host, username=None, password=None): new_config = {} new_config['filename'] = filename new_config['host'] = host if username: new_config['username'] = username if password: new_config['password'] = password config.write_config(new_config) def open_file_dialog(self): dialog = QFileDialog(self.dialog) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setDirectory(os.environ['HOME']) name_filter = 'Excel 2007-2019 (*.xlsx);;All files (*)' dialog.setNameFilter(name_filter) if dialog.exec_(): filename = dialog.selectedFiles()[0] self.dialog.file_path_lineedit.setText(filename) def login(self): filename = self.dialog.file_path_lineedit.text() host = self.dialog.address_lineedit.text() if not bool(host_re.match(host)): self.main_window.show_error('Invalid host %s.' % host) return username = self.dialog.username_lineedit.text() if not username: self.main_window.show_error('Blank username.') return password = self.dialog.password_lineedit.text() if not password: self.main_window.show_error('Blank password.') return if self.dialog.remember_password_checkbox.isChecked(): self.update_config(filename, host, username, password) elif self.dialog.remember_username_checkbox.isChecked(): self.update_config(filename, host, username) elif self.dialog.remember_address_checkbox.isChecked(): self.update_config(filename, host) self.main_window.set_config(config.load_config()) self.main_window.set_excel_file(filename) self.main_window.db_login(host, username, password)
def _pyside_load_ui(fyle, parent=None): from PySide.QtUiTools import QUiLoader loader = QUiLoader() return loader.load(fyle, parent)
def __init__(self, parent=None): try: super().__init__(parent) loader = QUiLoader() file = QFile(os.path.abspath("forms/MainWindow.ui")) file.open(QFile.ReadOnly) ui = loader.load(file, self) file.close() self.setLayout(ui.layout()) # Components self.clipboard = QGuiApplication.clipboard() self.desktop = QDesktopWidget() self.trans_label = self.findChild(QLabel, "transLabel") self.transparent_slider = self.findChild(QSlider, "transparentSlider") self.interface_frame = self.findChild(QFrame, "interfaceFrame") self.hide_button = self.findChild(QPushButton, "hideButton") self.enable_box = self.findChild(QCheckBox, "enableBox") self.on_top_box = self.findChild(QCheckBox, "onTopBox") self.clear_button = self.findChild(QPushButton, "clearButton") self.system_tray = SystemTray(self) self.currentScreen = 0 self.currentPosition = 0 self.is_on_top = True self.is_enable = True self.is_show_panel = True self.is_not_fixed = True self.is_grab = False self.is_follow_cursor = False # Instances self.config = config_parser.Configuration() self.trans_request = web_api.YouDaoRequest(self.config) self.translate_thread = threads.TranslatorThread( self.config, self.trans_request, self.get_clip_text, self) # initialize self._initialize() # self.trans_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True); # register QObject.connect(self.enable_box, SIGNAL("stateChanged(int)"), self, SLOT("_set_enabled(int)")) QObject.connect(self.on_top_box, SIGNAL("stateChanged(int)"), self, SLOT("_set_on_top(int)")) QObject.connect(self.translate_thread, SIGNAL("finished()"), self, SLOT("_translate()")) QObject.connect(self.transparent_slider, SIGNAL("valueChanged(int)"), self, SLOT("_set_transparent(int)")) QObject.connect(self.clipboard, SIGNAL("dataChanged()"), self, SLOT("translate()")) QObject.connect(self.desktop, SIGNAL("resized(int)"), self, SLOT("_set_geometry()")) QObject.connect(self.hide_button, SIGNAL("clicked()"), self, SLOT("hide_interface()")) except TranslatorException as e: err_box = QMessageBox(self.parent()) err_box.setText(str(e)) err_box.exec_() sys.exit(-1)
with open("guids.json", "r") as g: guid_dict = json.loads(g.read()) try: # find the install path for the steam version steam_reg = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam") steam_path = winreg.QueryValueEx(steam_reg, "SteamPath")[0] steam_path += "/steamapps/common/Deep Rock Galactic/FSD/Saved/SaveGames" except: steam_path = "." # load the UI and do a basic check loader = QUiLoader() loader.registerCustomWidget(TextEditFocusChecking) widget = loader.load(ui_file, None) ui_file.close() if not widget: print(loader.errorString()) sys.exit(-1) # connect file opening function to menu item widget.actionOpen_Save_File.triggered.connect(open_file) # set column names for overclock treeview widget.overclock_tree.setHeaderLabels(["Overclock", "Status", "GUID"]) # populate the promotion drop downs promo_boxes = [ widget.driller_promo_box, widget.gunner_promo_box, widget.engineer_promo_box,
class QtFrontend(ViewSBFrontend): """ Qt Frontend that consumes packets for display. """ UI_NAME = 'qt' UI_DESCRIPTION = 'proof-of-concept, unstable GUI in Qt' @staticmethod def reason_to_be_disabled(): # If we weren't able to import pyside2, disable the library. if 'QWidget' not in globals(): return "pyside2 (qt library) not available" return None def __init__(self): """ Sets up the Qt UI. """ QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) self.app = QApplication([]) self.ui_file = QtCore.QFile('viewsb/frontends/qt.ui') self.loader = QUiLoader() self.window: QtWidgets.QMainWindow = self.loader.load(self.ui_file) # The default column size of 100 is too small for the summary column. self.window.usb_tree_widget.setColumnWidth(1, 400) self.window.update_timer = QtCore.QTimer() self.window.update_timer.timeout.connect(self.update) self.window.usb_tree_widget.currentItemChanged.connect( self.tree_current_item_changed) self.window.usb_tree_widget: QtWidgets.QTreeWidget = self.window.usb_tree_widget self.window.usb_tree_widget.sortByColumn(0) self.window.showMaximized() def update(self): """ Called by the QTimer `update_timer`, collects packets waiting the queue and adds them to the tree view. Note: Since this is called via a QTimer signal, this method runs in the UI thread. """ packet_list = [] try: # Get as many packets as we can as quick as we can. while (True): packet = self.data_queue.get_nowait() packet_list.append(packet) # But the instant it's empty, don't wait for any more; just send them to be processed. except multiprocessing.queues.Empty: pass finally: # In case the queue was empty in the first place and didn't have anything ready. if len(packet_list) > 0: self.add_packets(packet_list) def add_packets(self, viewsb_packets: []): """ Adds a list of top-level ViewSB packets to the tree. We're in the UI thread; every bit of overhead counts, so let's batch as much as possible. """ for viewsb_packet in viewsb_packets: top_level_item = QtWidgets.QTreeWidgetItem( get_packet_string_array(viewsb_packet)) top_level_item.setData(0, QtCore.Qt.UserRole, viewsb_packet) list_of_children = [] recursive_packet_walk(viewsb_packet, list_of_children) top_level_item.addChildren(list_of_children) self.window.usb_tree_widget.addTopLevelItem(top_level_item) def tree_current_item_changed(self, current_item, previous_item): """ Use the side panel to show a detailed view of the current item. """ # Clear the details widget. self.window.usb_details_tree_widget.clear() self.window.usb_details_tree_widget.setColumnCount(2) current_packet: ViewSBPacket = current_item.data(0, QtCore.Qt.UserRole) # A list of 2-tuples: first element is a table title, and the second is usually a string: string dict detail_fields = current_packet.get_detail_fields() # Each table will have a root item in the details view. root_items = [] for table in detail_fields: title: str = table[0] root = QtWidgets.QTreeWidgetItem([title]) children = [] fields = table[1] # The usual case: a str: str dict. if type(fields) == type({}): for key, value in fields.items(): children.append( QtWidgets.QTreeWidgetItem(stringify_list([key, value]))) # Sometimes a descriptor will just be a 1-column list. elif type(fields) == type([]): for item in fields: children.append(QtWidgets.QTreeWidgetItem([str(item)])) # Sometimes it'll just be a string, or, if it's an unknown descriptor, a `bytes` instance. else: children.append(QtWidgets.QTreeWidgetItem([str(fields)])) root.addChildren(children) # Add an empty "item" between each table root_items += [root, QtWidgets.QTreeWidgetItem([])] self.window.usb_details_tree_widget.addTopLevelItems(root_items) self.window.usb_details_tree_widget.expandAll() self.window.usb_details_tree_widget.resizeColumnToContents(0) self.window.usb_details_tree_widget.resizeColumnToContents(1) def run(self): """ Overrides `ViewSBFrontend.run()` """ # TODO: is there a better value than 100 ms? Should it be configurable by the Analyzer? self.window.update_timer.start(100) self.app.exec_() self.stop() def stop(self): self.app.closeAllWindows() self.termination_event.set()
class EditIncomingActs(QWidget): def __init__(self, action, parent=None): super(EditIncomingActs, self).__init__(parent) self.path = os.path.join('faces', 'edit_invoicing.ui') self.ui_file = QFile(self.path) self.ui_file.open(QFile.ReadOnly) self.loader = QUiLoader() self.dialog = self.loader.load(self.ui_file, self) self.ui_file.close() self.action = action # определим элементы управления self.date_edit = self.dialog.findChild(QDateEdit, 'date_edit') self.table_service = self.dialog.findChild(QTableWidget, 'table_service') self.comment_edit = self.dialog.findChild(QLineEdit, 'comment_edit') self.table_total = self.dialog.findChild(QTableWidget, 'table_total') self.cmbox_company = self.dialog.findChild(QComboBox, 'cmbox_company') self.btn_save = self.dialog.findChild(QPushButton, 'btn_save') self.btn_add = self.dialog.findChild(QPushButton, 'btn_add') self.btn_changed = self.dialog.findChild(QPushButton, 'btn_changed') self.btn_delete = self.dialog.findChild(QPushButton, 'btn_delete') # назначим подсказки для элементов self.btn_save.setToolTip('Сохранить акт') self.btn_add.setToolTip('Добавить услугу, товар') self.btn_changed.setToolTip('Изменить услугу, товар') self.btn_delete.setToolTip('Удалить услугу, товар') # задаём специальные размеров колонок основной таблицы self.table_service.setColumnWidth(0, 329) # наименование услуг self.table_service.setColumnWidth(1, 100) # количество self.table_service.setColumnWidth(2, 100) # цена self.table_service.setColumnWidth(3, 100) # сумма # задаём специальные размеров колонок итоговой таблицы self.table_total.setColumnWidth(0, 549) # наименование услуг self.table_total.setColumnWidth(1, 80) # количество # замена имени колонки в форме self.table_total.horizontalHeaderItem(0).setText('Итого по актам') # добавляем значения по умолчанию: текущую дату self.date_edit.setDate(QDate.currentDate()) # список контроагентов result = conn.query(Counterparties).all() if result: for elem in result: self.cmbox_company.addItem(str(elem.name_c)) # назначим подсказки для элементов self.btn_add.setToolTip('Добавить') self.btn_delete.setToolTip('Удалить') # назначим действия для объектов self.btn_save.clicked.connect(self.save_service) self.btn_add.clicked.connect(self.insert_service) self.btn_changed.clicked.connect(self.edit_service) self.btn_delete.clicked.connect(self.dell_service) # метод добавление данных в новую строку def set_data_in_new_row(self, data: list): rows = self.table_service.rowCount() self.table_service.setRowCount(int(rows + 1)) columns = self.table_service.columnCount() for i in range(0, columns): item = QtWidgets.QTableWidgetItem(str(data[i])) self.table_service.setItem(rows, i, item) # метод добавление данных в текущую строку def set_data_in_current_row(self, data: list): selected_row = self.table_service.currentItem() id_row = self.table_service.row(selected_row) columns = self.table_service.columnCount() for i in range(0, columns): item = QtWidgets.QTableWidgetItem(str(data[i])) self.table_service.setItem(id_row, i, item) # Возвращает список значений строки таблицы def get_value_row(self, current_row): value_cells = [] if self.table_service.isItemSelected(current_row): index_row = self.table_service.row(current_row) columns = self.table_service.columnCount() for column in range(0, columns): value_cells.append( self.table_service.item(index_row, column).text()) return value_cells # метод суммирования стоимости услуг def total_summ(self): # собираем значения последних ячеек по строкам value_cells = [] columns = self.table_service.columnCount() rows = self.table_service.rowCount() for row in range(0, rows): value = self.table_service.item(row, columns - 1).text() value_cells.append(float(value)) summ = sum(value_cells) # вставляем сумму self.table_total.horizontalHeaderItem(1).setText(str(summ)) # метод заполнения таблицы def filling_table(self, row): self.table_service.setRowCount(int(0)) # удаляем строки self.set_data_in_new_row(row) # метод отображения окна def work_with_service(self, selector): self.win = ServiceForInvoice(selector) self.id_selected_row = '' # ID выделенной строки if selector == 'add': self.win.setWindowTitle('Добавить услугу') self.start_win() else: # получаем выделенную строку selected_row = self.table_service.currentItem() if selector == 'dell': id_row = self.table_service.row(selected_row) self.table_service.removeRow(id_row) elif selector == 'edit': # получаем значения ячеек выделенной строки value_cells = self.get_value_row(selected_row) # вставляем исходные значения: название услуги for i in range(self.win.cmbox_service.count()): if self.win.cmbox_service.itemText(i) == value_cells[0]: self.win.cmbox_service.setCurrentIndex(i) self.win.amount_service.setText(value_cells[1]) # количество self.win.price_service.setText(value_cells[2]) # стоимость self.start_win() self.total_summ() # запуск окна def start_win(self): self.win.setWindowModality(Qt.ApplicationModal) self.win.setWindowFlags(Qt.Window) self.win.btn_action.clicked.connect(self.add_upt_dell) self.win.btn_exit.clicked.connect(self.win.close) self.win.show() # метод модального окна "Дорбавления услуг" def add_upt_dell(self): if self.win.action == 'add' or self.win.action == 'edit': # получаем данные из дочернего окна: new_service = [ self.win.cmbox_service.currentText(), self.win.amount_service.text(), self.win.price_service.text(), self.win.summ_service.text() ] # вставляем данные а таблицу if self.win.action == 'edit': # вставляем данные в туже строку self.set_data_in_current_row(new_service) else: self.set_data_in_new_row(new_service) self.win.close() self.total_summ() # сохранение услуг def save_service(self): if not self.action == 'edit': self.action = 'save' # метод добавления услуг def insert_service(self): self.work_with_service('add') # метод редактирования услуг def edit_service(self): if self.table_service.isItemSelected(self.table_service.currentItem()): self.work_with_service('edit') # метод удаления виделеной строки def dell_service(self): if self.table_service.isItemSelected(self.table_service.currentItem()): self.work_with_service('dell')
# directly_loading_QML import sys from PySide2.QtUiTools import QUiLoader from PySide2.QtWidgets import QApplication from PySide2.QtCore import QFile if __name__ == '__main__': app = QApplication(sys.argv) ui_file=QFile('./mainwindow.ui') ui_file.open(QFile.ReadOnly) loader = QUiLoader() window = loader.load(ui_file) ui_file.close() window.show() sys.exit(app.exec_())
def __init__(self, ui_file, parent=None): #call parent QObject constructor super(MainWindow, self).__init__(parent) #load the UI file into Python ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() self.window = loader.load(ui_file) #always remember to close files ui_file.close() #add event listener to the 7 button zeroButton = self.window.findChild(QPushButton, 'zeroButton') zeroButton.clicked.connect(self.zero_button_clicked) oneButton = self.window.findChild(QPushButton, 'oneButton') oneButton.clicked.connect(self.one_button_clicked) twoButton = self.window.findChild(QPushButton, 'twoButton') twoButton.clicked.connect(self.two_button_clicked) threeButton = self.window.findChild(QPushButton, 'threeButton') threeButton.clicked.connect(self.three_button_clicked) fourButton = self.window.findChild(QPushButton, 'fourButton') fourButton.clicked.connect(self.four_button_clicked) fiveButton = self.window.findChild(QPushButton, 'fiveButton') fiveButton.clicked.connect(self.five_button_clicked) sixButton = self.window.findChild(QPushButton, 'sixButton') sixButton.clicked.connect(self.six_button_clicked) sevenButton = self.window.findChild(QPushButton, 'sevenButton') sevenButton.clicked.connect(self.seven_button_clicked) eightButton = self.window.findChild(QPushButton, 'eightButton') eightButton.clicked.connect(self.eight_button_clicked) nineButton = self.window.findChild(QPushButton, 'nineButton') nineButton.clicked.connect(self.nine_button_clicked) addButton = self.window.findChild(QPushButton, 'addButton') addButton.clicked.connect(self.add_button_clicked) equalsButton = self.window.findChild(QPushButton, 'equalsButton') equalsButton.clicked.connect(self.equals_button_clicked) subtractButton = self.window.findChild(QPushButton, 'subtractButton') subtractButton.clicked.connect(self.subtract_button_clicked) multiplyButton = self.window.findChild(QPushButton, 'multiplyButton') multiplyButton.clicked.connect(self.multiply_button_clicked) divideButton = self.window.findChild(QPushButton, 'divideButton') divideButton.clicked.connect(self.divide_button_clicked) #show window to user self.window.show()
def _open_ui_file(self, my_ui,parent=None): ui_file = QtCore.QFile(my_ui) ui_file.open(QtCore.QFile.ReadOnly) loader = QUiLoader() return loader.load(ui_file,parent=parent)
def __init__(self): QObject.__init__(self) self.module_path = os.path.dirname(__file__) self.mouse_pressed = False self.draw_ellipse = False self.write_text = False self.mouse_pressed_x = 0 self.mouse_pressed_y = 0 self.tables = [] self.ellipses = [] self.texts = [] self.text_event_filter = TextEventFilter(self) # loading widgets from designer file loader = QUiLoader() loader.registerCustomWidget(QtCharts.QChartView) self.window = loader.load(self.module_path + "/ui/application_window.ui") self.tab_widget = self.window.findChild(QTabWidget, "tab_widget") chart_frame = self.window.findChild(QFrame, "chart_frame") chart_cfg_frame = self.window.findChild(QFrame, "chart_cfg_frame") self.chart_view = self.window.findChild(QtCharts.QChartView, "chart_view") button_add_tab = self.window.findChild(QPushButton, "button_add_tab") button_reset_zoom = self.window.findChild(QPushButton, "button_reset_zoom") button_save_image = self.window.findChild(QPushButton, "button_save_image") self.label_mouse_coords = self.window.findChild( QLabel, "label_mouse_coords") self.radio_zoom = self.window.findChild(QRadioButton, "radio_zoom") self.radio_ellipse = self.window.findChild(QRadioButton, "radio_ellipse") self.radio_text = self.window.findChild(QRadioButton, "radio_text") # Creating QChart self.chart = QtCharts.QChart() self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations) self.chart.setTheme(QtCharts.QChart.ChartThemeLight) self.chart.setAcceptHoverEvents(True) self.axis_x = QtCharts.QValueAxis() self.axis_x.setTitleText("PC1") self.axis_x.setRange(-10, 10) self.axis_x.setLabelFormat("%.1f") self.axis_y = QtCharts.QValueAxis() self.axis_y.setTitleText("PC2") self.axis_y.setRange(-10, 10) self.axis_y.setLabelFormat("%.1f") self.chart.addAxis(self.axis_x, Qt.AlignBottom) self.chart.addAxis(self.axis_y, Qt.AlignLeft) self.chart_view.setChart(self.chart) self.chart_view.setRenderHint(QPainter.Antialiasing) self.chart_view.setRubberBand(QtCharts.QChartView.RectangleRubberBand) # 1 tab by default self.add_tab() # custom stylesheet style_file = QFile(self.module_path + "/ui/custom.css") style_file.open(QFile.ReadOnly) self.window.setStyleSheet(style_file.readAll().data().decode("utf-8")) style_file.close() # effects self.tab_widget.setGraphicsEffect(self.card_shadow()) chart_frame.setGraphicsEffect(self.card_shadow()) chart_cfg_frame.setGraphicsEffect(self.card_shadow()) button_add_tab.setGraphicsEffect(self.button_shadow()) button_reset_zoom.setGraphicsEffect(self.button_shadow()) button_save_image.setGraphicsEffect(self.button_shadow()) # signal connection self.tab_widget.tabCloseRequested.connect(self.remove_tab) button_add_tab.clicked.connect(self.add_tab) button_reset_zoom.clicked.connect(self.reset_zoom) button_save_image.clicked.connect(self.save_image) self.radio_zoom.toggled.connect(self.on_mouse_function_changed) self.radio_ellipse.toggled.connect(self.on_mouse_function_changed) self.radio_text.toggled.connect(self.on_mouse_function_changed) # event filter self.chart.installEventFilter(self) # show window self.window.show()