def __init__(self, parent=None): QStatusBar.__init__(self, parent) self.mLabelPos = QLabel("当前位置:(nan,nan)") self.mLabelTestName = QLabel("当前测试:凸包") self.addWidget(self.mLabelPos) self.addWidget(self.mLabelTestName)
def __init__(self, parent=None): QStatusBar.__init__(self, parent) self.mLabelPhyPos = QLabel("物理坐标:(nan,nan)") self.mLabelPaintPos = QLabel("绘制坐标:(nan,nan)") self.addWidget(self.mLabelPhyPos) self.addWidget(self.mLabelPaintPos)
def initUI(self): QToolTip.setFont(QFont('SansSerif', 10)) self.setToolTip('This is a <b>QWidget</b> widget.') #quitBtn = QPushButton('Quit', self) #quitBtn.clicked.connect(self.quitBtnEvent()) #quitBtn.clicked.connect(QCoreApplication.instance().quit) #quitBtn.setToolTip('This is a <b>QPushButton</b> widget.') #quitBtn.resize(quitBtn.sizeHint()) exitAction = QAction(QIcon('application-exit-4.png'), '&Exit', self) exitAction.setShortcut('Alt+F4') exitAction.setStatusTip('Exit Application') exitAction.triggered.connect(qApp.quit) menuBar = QMenuBar() fileMenu = menuBar.addMenu('&File') fileMenu.addAction(exitAction) fileMenu.resize(fileMenu.sizeHint()) toolBar = QToolBar(self) toolBar.addAction(exitAction) #toolBar.resize(toolBar.sizeHint()) toolBar.setFixedHeight(60) hozLine = QFrame() hozLine.setFrameStyle(QFrame.HLine) #hozLine.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Expanding) statusBar = QStatusBar(self) statusBar.showMessage('Ready') grid = QGridLayout() lbl_1 = QLabel('1,1') lbl_2 = QLabel('1,2') lbl_3 = QLabel('2,1') lbl_4 = QLabel('2,2') grid.addWidget(lbl_1, 1, 1) grid.addWidget(lbl_2, 1, 2) grid.addWidget(lbl_3, 2, 1) grid.addWidget(lbl_4, 2, 2) vbox = QVBoxLayout() vbox.addWidget(menuBar) vbox.addWidget(hozLine) vbox.addWidget(toolBar) # vbox.addWidget(hozLine) vbox.addLayout(grid) vbox.addStretch(1) vbox.addWidget(statusBar) self.setLayout(vbox) self.setGeometry(300, 300, 500, 500) self.setWindowTitle('Photos') self.setWindowIcon(QIcon('camera-photo-5.png')) self.center() self.show()
def show(self): self.clearMessage() QStatusBar.show(self) editor = main_container.MainContainer().get_actual_editor() if editor and editor.textCursor().hasSelection(): text = editor.textCursor().selectedText() self._searchWidget._line.setText(text) self._searchWidget.find_matches(editor, True) if self._widgetStatus.isVisible(): self._searchWidget._line.setFocus() self._searchWidget._line.selectAll()
def __init__(self, *args): QStatusBar.__init__(self, *args) self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Expanding) self.setSizeGripEnabled(False) self.setStyleSheet("QStatusBar {border: 0} QStatusBar::item {border: 0}") self._label = QLabel(self) self._label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self._label.setStyleSheet("color: red") self.addWidget(self._label) self._timer = QTimer() self._timer.setSingleShot(True) self._timer.timeout.connect(self.clearMessage)
class ControlPanelWindow(QDialog): def __init__(self, parent, cli_iface, iface_name): super(ControlPanelWindow, self).__init__(parent) self.setWindowTitle('SLCAN Adapter Control Panel') self.setAttribute(Qt.WA_DeleteOnClose) # This is required to stop background timers! self._cli_iface = cli_iface self._iface_name = iface_name self._state_widget = StateWidget(self, self._cli_iface) self._config_widget = ConfigWidget(self, self._cli_iface) self._cli_widget = CLIWidget(self, self._cli_iface) self._tab_widget = QTabWidget(self) self._tab_widget.addTab(self._state_widget, get_icon('dashboard'), 'Adapter State') self._tab_widget.addTab(self._config_widget, get_icon('wrench'), 'Configuration') self._tab_widget.addTab(self._cli_widget, get_icon('terminal'), 'Command Line') self._status_bar = QStatusBar(self) self._status_bar.setSizeGripEnabled(False) iface_name_label = QLabel(iface_name.split('/')[-1], self) iface_name_label.setFont(get_monospace_font()) layout = QVBoxLayout(self) layout.addWidget(iface_name_label) layout.addWidget(self._tab_widget) layout.addWidget(self._status_bar) left, top, right, bottom = layout.getContentsMargins() bottom = 0 layout.setContentsMargins(left, top, right, bottom) self.setLayout(layout) self.resize(400, 400) def closeEvent(self, close_event): if self._config_widget.have_unsaved_changes: if request_confirmation('Save changes?', 'You made changes to the adapter configuration that were not saved. ' 'Do you want to go back and save them?', parent=self): close_event.ignore() self._tab_widget.setCurrentWidget(self._config_widget) return super(ControlPanelWindow, self).closeEvent(close_event) def show_message(self, text, *fmt, duration=0): self._status_bar.showMessage(text % fmt, duration * 1000)
def __init__( self, parent, node, target_node_id, file_server_widget, node_monitor, dynamic_node_id_allocator_widget ): super(NodePropertiesWindow, self).__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) # This is required to stop background timers! self.setWindowTitle("Node Properties [%d]" % target_node_id) self.setMinimumWidth(640) self._target_node_id = target_node_id self._node = node self._file_server_widget = file_server_widget self._info_box = InfoBox(self, target_node_id, node_monitor) self._controls = Controls(self, node, target_node_id, file_server_widget, dynamic_node_id_allocator_widget) self._config_params = ConfigParams(self, node, target_node_id) self._status_bar = QStatusBar(self) self._status_bar.setSizeGripEnabled(False) layout = QVBoxLayout(self) layout.addWidget(self._info_box) layout.addWidget(self._controls) layout.addWidget(self._config_params) layout.addWidget(self._status_bar) left, top, right, bottom = layout.getContentsMargins() bottom = 0 layout.setContentsMargins(left, top, right, bottom) self.setLayout(layout)
def setup_ui(self): self.setObjectName("MainWindow") self.resize(820, 760) self.setMinimumSize(QSize(720, 560)) self.setWindowTitle("BW-StringsEdit") self.centralwidget = QWidget(self) self.centralwidget.setObjectName("centralwidget") self.setCentralWidget(self.centralwidget) self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.strings_list = QListWidget(self.centralwidget) self.horizontalLayout.addWidget(self.strings_list) self.vertLayoutWidget = QWidget(self.centralwidget) self.verticalLayout = QVBoxLayout(self.vertLayoutWidget) self.button_add_message = QPushButton(self.centralwidget) self.button_remove_message = QPushButton(self.centralwidget) self.button_set_message = QPushButton(self.centralwidget) self.button_add_message.setText("Add Message") self.button_remove_message.setText("Delete Last Message") self.button_set_message.setText("Set Message Content") self.lineedit_path = QLineEdit(self.centralwidget) self.lineedit_audioname = QLineEdit(self.centralwidget) self.lineedit_playtime = QLineEdit(self.centralwidget) self.textedit_content = QTextEdit(self.centralwidget) for widget in ( self.button_remove_message, self.button_add_message, self.button_set_message, self.lineedit_path, self.lineedit_audioname, self.lineedit_playtime, self.textedit_content): self.verticalLayout.addWidget(widget) self.horizontalLayout.addWidget(self.vertLayoutWidget) self.menubar = self.menuBar()#QMenuBar(self) #self.menubar.setGeometry(QRect(0, 0, 820, 30)) #self.menubar.setObjectName("menubar") self.file_menu = self.menubar.addMenu("File")#QMenu(self.menubar) self.file_menu.setObjectName("menuLoad") #self.menubar.addMenu(self.file_menu) self.file_load_action = QAction("Load", self) self.file_load_action.triggered.connect(self.button_load_strings) self.file_menu.addAction(self.file_load_action) self.file_save_action = QAction("Save", self) self.file_save_action.triggered.connect(self.button_save_strings) self.file_menu.addAction(self.file_save_action) self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) #self.setMenuBar(self.menubar) print("done")
def __init__(self, parent, cli_iface, iface_name): super(ControlPanelWindow, self).__init__(parent) self.setWindowTitle('SLCAN Adapter Control Panel') self.setAttribute(Qt.WA_DeleteOnClose) # This is required to stop background timers! self._cli_iface = cli_iface self._iface_name = iface_name self._state_widget = StateWidget(self, self._cli_iface) self._config_widget = ConfigWidget(self, self._cli_iface) self._cli_widget = CLIWidget(self, self._cli_iface) self._tab_widget = QTabWidget(self) self._tab_widget.addTab(self._state_widget, get_icon('dashboard'), 'Adapter State') self._tab_widget.addTab(self._config_widget, get_icon('wrench'), 'Configuration') self._tab_widget.addTab(self._cli_widget, get_icon('terminal'), 'Command Line') self._status_bar = QStatusBar(self) self._status_bar.setSizeGripEnabled(False) iface_name_label = QLabel(iface_name.split('/')[-1], self) iface_name_label.setFont(get_monospace_font()) layout = QVBoxLayout(self) layout.addWidget(iface_name_label) layout.addWidget(self._tab_widget) layout.addWidget(self._status_bar) left, top, right, bottom = layout.getContentsMargins() bottom = 0 layout.setContentsMargins(left, top, right, bottom) self.setLayout(layout) self.resize(400, 400)
def setWidget(self): if self.obj.configured==0: self.setCentralWidget(configureWidget(self)) elif self.obj.configured==1: self.setCentralWidget(setupWidget(self)) elif self.obj.configured==2: self.setStyleSheet('''#Window1{background-color: light gray;}''') self.setWindowTitle('Moodly 1.0 Beta') self.setMenuBar() self.tabWidget = tabWidget(self) self.setCentralWidget(self.tabWidget) self.tray.updateAction.setEnabled(True) self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) self.statusBar.hide() self.statusLbl1 = QLabel() self.statusLbl2 = QLabel() self.statusLbl2.setAlignment(QtCore.Qt.AlignRight) self.statusBar.addWidget(self.statusLbl1) self.statusBar.addWidget(self.statusLbl2,QtCore.Qt.AlignRight) self.updateTimer() self.notifTimer() self.i_thread = {} self.nt=0
def __init__(self): super(Main_Window, self).__init__() self.menubar = QMenuBar(self) self.statusbar = QStatusBar(self) self.centralwidget = QWidget(self) self.image_view = Image_View(self.centralwidget) self.horizontal_slider = QSlider(self.centralwidget) self.setup_ui()
def _setupUi(self): self.setWindowTitle(tr("{} Results").format(self.app.NAME)) self.resize(630, 514) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.actionsButton = QPushButton(tr("Actions")) self.detailsButton = QPushButton(tr("Details")) self.dupesOnlyCheckBox = QCheckBox(tr("Dupes Only")) self.deltaValuesCheckBox = QCheckBox(tr("Delta Values")) self.searchEdit = SearchEdit() self.searchEdit.setMaximumWidth(300) self.horizontalLayout = horizontalWrap([ self.actionsButton, self.detailsButton, self.dupesOnlyCheckBox, self.deltaValuesCheckBox, None, self.searchEdit, 8 ]) self.horizontalLayout.setSpacing(8) self.verticalLayout.addLayout(self.horizontalLayout) self.resultsView = ResultsView(self.centralwidget) self.resultsView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.resultsView.setSelectionBehavior(QAbstractItemView.SelectRows) self.resultsView.setSortingEnabled(True) self.resultsView.verticalHeader().setVisible(False) h = self.resultsView.horizontalHeader() h.setHighlightSections(False) h.setSectionsMovable(True) h.setStretchLastSection(False) h.setDefaultAlignment(Qt.AlignLeft) self.verticalLayout.addWidget(self.resultsView) self.setCentralWidget(self.centralwidget) self._setupActions() self._setupMenu() self.statusbar = QStatusBar(self) self.statusbar.setSizeGripEnabled(True) self.setStatusBar(self.statusbar) self.statusLabel = QLabel(self) self.statusbar.addPermanentWidget(self.statusLabel, 1) if self.app.prefs.resultWindowIsMaximized: self.setWindowState(self.windowState() | Qt.WindowMaximized) else: if self.app.prefs.resultWindowRect is not None: self.setGeometry(self.app.prefs.resultWindowRect) # if not on any screen move to center of default screen # moves to center of closest screen if partially off screen frame = self.frameGeometry() if QDesktopWidget().screenNumber(self) == -1: moveToScreenCenter(self) elif QDesktopWidget().availableGeometry(self).contains(frame) is False: frame.moveCenter(QDesktopWidget().availableGeometry(self).center()) self.move(frame.topLeft()) else: moveToScreenCenter(self)
def __init__(self, app): QMainWindow.__init__(self, None) self.l.debug('Initializing MainWindow ...') self.setWindowTitle('MynPad') app.setWindowIcon(QIcon(':/icons/mynpad.png')) if os.name == 'nt': # On Windows, make sure to use a unique Application User Model Id, otherwise # Windows shows the default python icon in the taskbar # see http://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7 myappid = 'afester.mynpad' import ctypes; ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) self.theApplication = app app.aboutToQuit.connect(self.saveState) # read the local configuration file iniPath = 'mynpad.ini' if not os.path.exists(iniPath): iniPath = os.path.join(expanduser("~"), iniPath) self.settings = Settings(iniPath) self.settings.load() # Set up the menu bar menuBar = QMenuBar(self) exitAction = QAction("Exit", self, triggered=self.theApplication.exit) fileMenu = menuBar.addMenu("&File") fileMenu.addAction(exitAction) aboutAction = QAction("About ...", self, triggered = self.handleAbout) helpMenu = menuBar.addMenu("&Help") helpMenu.addAction(aboutAction) self.setMenuBar(menuBar) # Setup the status bar self.statusBar = QStatusBar() self.statusBar.showMessage("Ready.") self.setStatusBar(self.statusBar) self.mainWidget = CentralWidget(self, self.settings) self.mainWidget.updateWindowTitle.connect(self.updateWindowTitle) self.setCentralWidget(self.mainWidget) # Reset main window size and position pos = self.settings.getMainWindowPos() self.move(pos.x(), pos.y()) size = self.settings.getMainWindowSize() self.resize(size) # initialize the browser tree (add the top nodes and expand the saved path) self.mainWidget.browserWidget.initialize()
class Main_Window(QMainWindow): def __init__(self): super(Main_Window, self).__init__() self.menubar = QMenuBar(self) self.statusbar = QStatusBar(self) self.centralwidget = QWidget(self) self.image_view = Image_View(self.centralwidget) self.horizontal_slider = QSlider(self.centralwidget) self.setup_ui() def setup_ui(self): # 1. self info self.setObjectName("Demo_1") self.resize(800, 600) # 2.1 sub widgets self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22)) self.menubar.setObjectName("menubar") self.setMenuBar(self.menubar) # 2.2 self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) # 2.3 self.centralwidget.setObjectName("centralwidget") self.setCentralWidget(self.centralwidget) self.image_view.setGeometry(QtCore.QRect(144, 10, 512, 512)) self.image_view.setObjectName("image_view") self.horizontal_slider.setGeometry(QtCore.QRect(144, 530, 512, 22)) self.horizontal_slider.setOrientation(QtCore.Qt.Horizontal) self.horizontal_slider.setObjectName("horizontal_slider") # 3 signals and slots self.horizontal_slider.valueChanged['int'].connect(self.image_view.repaint)
class Tab(QWidget): def __init__(self, parent, configuration): QWidget.__init__(self, parent) self._configuration = configuration layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) main_widget = QWidget(self) self._layout_main = QVBoxLayout() self._layout_main.setContentsMargins(0, 0, 0, 0) self._layout_main.setSpacing(6) main_widget.setLayout(self._layout_main) layout.addWidget(main_widget) self._status_bar = QStatusBar() layout.addWidget(self._status_bar) self.setLayout(layout) def _add_widget(self, widget): self._layout_main.addWidget(widget) def set_error_message(self, msg): self._status_bar.showMessage(msg)
def __init__(self): super().__init__() self.webView = QtWebEngineWidgets.QWebEngineView() self.sourceType = QComboBox() self.sourceType.addItems(['国测局坐标GCJ02(MX数据库/高德)','GPS坐标(wgs84/NMEA0183)']) self.inputText = QTextEdit() self.inputText.setFixedWidth(280) self.runButton = QPushButton('确定') self.runButton.setFixedWidth(100) self.clrButton = QPushButton('清除') self.clrButton.setFixedWidth(100) self.statusBar = QStatusBar() self.statusBar.showMessage(STATUS_TIP+"Ready") self.init_ui()
def __init__(self, parent, configuration): QWidget.__init__(self, parent) self._configuration = configuration layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) main_widget = QWidget(self) self._layout_main = QVBoxLayout() self._layout_main.setContentsMargins(0, 0, 0, 0) self._layout_main.setSpacing(6) main_widget.setLayout(self._layout_main) layout.addWidget(main_widget) self._status_bar = QStatusBar() layout.addWidget(self._status_bar) self.setLayout(layout)
def __init__(self, parent, node, target_node_id, param_struct, update_callback): super(ConfigParamEditWindow, self).__init__(parent) self.setWindowTitle("Edit configuration parameter") self.setModal(True) self._node = node self._target_node_id = target_node_id self._param_struct = param_struct self._update_callback = update_callback min_val = get_union_value(param_struct.min_value) if "uavcan.protocol.param.Empty" in str(min_val): min_val = None max_val = get_union_value(param_struct.max_value) if "uavcan.protocol.param.Empty" in str(max_val): max_val = None value = get_union_value(param_struct.value) self._value_widget = None value_type = uavcan.get_active_union_field(param_struct.value) if value_type == "integer_value": min_val = min_val if min_val is not None else -0x8000000000000000 max_val = max_val if max_val is not None else 0x7FFFFFFFFFFFFFFF if min_val >= -0x80000000 and max_val <= +0x7FFFFFFF: self._value_widget = QSpinBox(self) self._value_widget.setMaximum(max_val) self._value_widget.setMinimum(min_val) self._value_widget.setValue(value) if value_type == "real_value": min_val = round_float(min_val) if min_val is not None else -3.4028235e38 max_val = round_float(max_val) if max_val is not None else 3.4028235e38 value = round_float(value) if value_type == "boolean_value": self._value_widget = QCheckBox(self) self._value_widget.setChecked(bool(value)) if self._value_widget is None: self._value_widget = QLineEdit(self) self._value_widget.setText(str(value)) self._value_widget.setFont(get_monospace_font()) layout = QGridLayout(self) def add_const_field(label, *values): row = layout.rowCount() layout.addWidget(QLabel(label, self), row, 0) if len(values) == 1: layout.addWidget(FieldValueWidget(self, values[0]), row, 1) else: sub_layout = QHBoxLayout(self) for idx, v in enumerate(values): sub_layout.addWidget(FieldValueWidget(self, v)) layout.addLayout(sub_layout, row, 1) add_const_field("Name", param_struct.name) add_const_field("Type", uavcan.get_active_union_field(param_struct.value).replace("_value", "")) add_const_field("Min/Max", min_val, max_val) add_const_field("Default", render_union(param_struct.default_value)) layout.addWidget(QLabel("Value", self), layout.rowCount(), 0) layout.addWidget(self._value_widget, layout.rowCount() - 1, 1) fetch_button = make_icon_button( "refresh", "Read parameter from the node", self, text="Fetch", on_clicked=self._do_fetch ) set_default_button = make_icon_button( "fire-extinguisher", "Restore default value", self, text="Restore", on_clicked=self._restore_default ) send_button = make_icon_button( "flash", "Send parameter to the node", self, text="Send", on_clicked=self._do_send ) cancel_button = make_icon_button( "remove", "Close this window; unsent changes will be lost", self, text="Cancel", on_clicked=self.close ) controls_layout = QGridLayout(self) controls_layout.addWidget(fetch_button, 0, 0) controls_layout.addWidget(send_button, 0, 1) controls_layout.addWidget(set_default_button, 1, 0) controls_layout.addWidget(cancel_button, 1, 1) layout.addLayout(controls_layout, layout.rowCount(), 0, 1, 2) self._status_bar = QStatusBar(self) self._status_bar.setSizeGripEnabled(False) layout.addWidget(self._status_bar, layout.rowCount(), 0, 1, 2) left, top, right, bottom = layout.getContentsMargins() bottom = 0 layout.setContentsMargins(left, top, right, bottom) self.setLayout(layout)
class Dimili(QMainWindow): def baslat(self, anaPencere): anaPencere.resize(600, 400) anaPencere.setWindowTitle("Dimili-Türkçe Sözlük") anaPencere.setFixedSize(600,400) icon =QIcon() icon.addPixmap(QPixmap("Dictionary.png"),QIcon.Normal,QIcon.Off) anaPencere.setWindowIcon(icon) zemin=QWidget(anaPencere) zemin.setGeometry(QRect(0,30,600,390)) zemin.setStyleSheet("background-color:rgb(167, 196, 233);") self.araKutu = QLineEdit(anaPencere) self.araKutu.setGeometry(QRect(10, 80, 200, 20)) self.araKutu.textChanged.connect(self.benzerKelimeler) self.kelimeGir = QLabel("Kelimeler:",anaPencere) self.kelimeGir.setGeometry(QRect(10, 110, 141, 21)) self.kelimeGor = QLabel("Kelime Ara",anaPencere) self.kelimeGor.setGeometry(QRect(10, 30, 91, 16)) self.harfGrup=QButtonGroup(anaPencere) aharf=QPushButton("â",anaPencere) aharf.setGeometry(QRect(10,50,25,25)) eharf=QPushButton("é",anaPencere) eharf.setGeometry(QRect(30,50,25,25)) self.DilGrup=QButtonGroup(anaPencere) self.Dil1 = QPushButton("Zazaca-Türkçe",anaPencere) self.Dil1.setGeometry(QRect(230, 80, 91, 23)) self.Dil1.setCheckable(True) self.Dil1.setAutoExclusive(True) self.Dil1.setChecked(True) self.Dil1.setStyleSheet("background-color: rgb(102, 255, 0);") self.Dil2 = QPushButton("Türkçe-Zazaca",anaPencere) self.Dil2.setGeometry(QRect(330, 80, 91, 23)) self.Dil2.setCheckable(True) self.Dil2.setAutoExclusive(True) self.Dil2.setStyleSheet("background-color: rgb(255, 94, 105);") self.DilGrup.addButton(self.Dil1,1) self.DilGrup.addButton(self.Dil2,2) self.DilGrup.buttonClicked[int].connect(self.dilSecme) self.kelimeListesi=QListWidget(anaPencere) self.kelimeListesi.setGeometry(QRect(10, 130, 191, 231)) self.kelimeListesi.itemClicked.connect(self.kelimeAcikla) self.kelimeAnlam = QLabel("Kelimenin Anlamı:",anaPencere) self.kelimeAnlam.setGeometry(QRect(230, 110, 131, 21)) self.cumleList1 = QListWidget(anaPencere) self.cumleList1.setGeometry(QRect(230, 130, 351, 51)) self.ornekCumle1 = QLabel("Örnek Zazaca Cümle:",anaPencere) self.ornekCumle1.setGeometry(QRect(230, 200, 101, 21)) self.cumleList2 = QListWidget(anaPencere) self.cumleList2.setGeometry(QRect(230, 220, 351, 51)) self.ornekCumle2 = QLabel("Örnek Türkçe Cümle:",anaPencere) self.ornekCumle2.setGeometry(QRect(230, 290, 111, 16)) self.cumleList3 = QListWidget(anaPencere) self.cumleList3.setGeometry(QRect(230, 310, 351, 51)) self.anaMenu = QMenuBar(anaPencere) self.anaMenu.setGeometry(QRect(0, 0, 600, 21)) self.menuDosya = QMenu("Dosya",self.anaMenu) self.menuDuzenle = QMenu("Düzenle",self.anaMenu) self.menuYardim = QMenu("Yardım",self.anaMenu) anaPencere.setMenuBar(self.anaMenu) self.durum = QStatusBar(zemin) anaPencere.setStatusBar(self.durum) self.durum.setStyleSheet("background-color:white") self.durum.showMessage("Hazır") self.cikis= QAction(QIcon("Exit.ico"),"&Çıkış",anaPencere) self.cikis.setShortcut("Ctrl+X") self.cikis.triggered.connect(anaPencere.close) self.actionHakkinda = QAction("Hakkında",anaPencere) self.actionHakkinda.triggered.connect(self.hakkinda) self.actionSecenekler = QAction("Seçenekler",anaPencere) self.menuDosya.addAction(self.cikis) self.menuDuzenle.addAction(self.actionSecenekler) self.menuYardim.addAction(self.actionHakkinda) self.anaMenu.addAction(self.menuDosya.menuAction()) self.anaMenu.addAction(self.menuDuzenle.menuAction()) self.anaMenu.addAction(self.menuYardim.menuAction()) def kelimeAcikla(self): if self.DilGrup.checkedId()==1: self.cumleList1.clear() self.cumleList2.clear() self.cumleList3.clear() itemtext= [str(x.text()) for x in self.kelimeListesi.selectedItems()] for it in itemtext: itemtext=it self.im.execute("select Tur from DimTur where Zazaca=?",[itemtext]) turliste=[tur[0] for tur in self.im.fetchall()] for tura in turliste: turliste=tura self.im.execute("select Turkce from DimTur where Zazaca=?",[itemtext]) turkAnlam=[tur[0] for tur in self.im.fetchall()] for tr in turkAnlam: self.cumleList1.addItem(itemtext+"("+turliste+")"+" : "+tr) self.im.execute("select OrnekZazacaCumle from DimTur where Zazaca=?",[itemtext]) ornekZaza=[zaza[0] for zaza in self.im.fetchall()] for za in ornekZaza: ornekZaza=za self.cumleList2.addItem(ornekZaza) self.im.execute("select OrnekTurkceCumle from DimTur where Zazaca=?",[itemtext]) ornekTurk=[turk[0] for turk in self.im.fetchall()] for orn in ornekTurk: ornekTurk=orn self.cumleList3.addItem(ornekTurk) if self.DilGrup.checkedId()==2: self.cumleList1.clear() self.cumleList2.clear() self.cumleList3.clear() itemtext= [str(x.text()) for x in self.kelimeListesi.selectedItems()] for it in itemtext: itemtext=it self.im.execute("select Tur from DimTur where Turkce=?",[itemtext]) turliste=[tur[0] for tur in self.im.fetchall()] for tura in turliste: turliste=tura self.im.execute("select Zazaca from DimTur where Turkce=?",[itemtext]) zazaAnlam=[tur[0] for tur in self.im.fetchall()] for tr in zazaAnlam: self.cumleList1.addItem(itemtext+"("+turliste+")"+" : "+tr) self.im.execute("select OrnekZazacaCumle from DimTur where Turkce=?",[itemtext]) ornekTurk=[turk[0] for turk in self.im.fetchall()] for orn in ornekTurk: ornekTurk=orn self.cumleList2.addItem(ornekTurk) self.im.execute("select OrnekTurkceCumle from DimTur where Turkce=?",[itemtext]) ornekZaza=[zaza[0] for zaza in self.im.fetchall()] for za in ornekZaza: ornekZaza=za self.cumleList3.addItem(ornekZaza) def benzerKelimeler(self): if self.DilGrup.checkedId()==1: self.VT=sqlite3.connect("DimiliVT.sqlite") self.im=self.VT.cursor() self.kelimeListesi.clear() kelime=self.araKutu.text() if kelime=="" or kelime==None: self.kelimeListesi.clear() else: self.im.execute("select Zazaca from DimTur where Zazaca like ? order by Zazaca ",[kelime+'%']) zazaListe=[za[0] for za in self.im.fetchall()] for i in zazaListe: self.kelimeListesi.addItem(i) if self.DilGrup.checkedId()==2: self.VT=sqlite3.connect("DimiliVT.sqlite") self.im=self.VT.cursor() kelime=self.araKutu.text() self.kelimeListesi.clear() if kelime=="" or kelime==None: self.kelimeListesi.clear() else: self.im.execute("select Turkce from DimTur where Turkce like ? ",[kelime+'%']) turkListe=[tu[0] for tu in self.im.fetchall()] for i in turkListe: self.kelimeListesi.addItem(i) def dilSecme(self,ind): if ind==1: self.araKutu.setText("") self.kelimeListesi.clear() self.cumleList1.clear() self.cumleList2.clear() self.cumleList3.clear() self.Dil1.setStyleSheet("background:#66FF00") self.Dil2.setStyleSheet("background-color:#E41841") if ind==2: self.araKutu.setText("") self.kelimeListesi.clear() self.cumleList1.clear() self.cumleList2.clear() self.cumleList3.clear() self.Dil2.setStyleSheet("background:#66FF00") self.Dil1.setStyleSheet("background-color:#E41841") def hakkinda(self): QMessageBox.about(self, "Program Hakkında", "Bu program <b>bla bla</b> tarafından programlanmıştır. 2015")
class ProcessDialog(QDialog): def __init__(self, port, **kwargs): super().__init__() self.setWindowTitle('Preparando seu Satélite Educacional...') self.setFixedWidth(600) self.exception = None esptool.sw.progress.connect(self.update_progress) self.nam = QNetworkAccessManager() self.nrDownloads = 0 self.nrBinFile1 = QNetworkRequest() self.bin_data1 = b'' self.nrBinFile2 = QNetworkRequest() self.bin_data2 = b'' self.nrBinFile3 = QNetworkRequest() self.bin_data3 = b'' self.nrBinFile4 = QNetworkRequest() self.bin_data4 = b'' self.setLayout(VLayout(5, 5)) self.actions_layout = QFormLayout() self.actions_layout.setSpacing(5) self.layout().addLayout(self.actions_layout) self._actions = [] self._action_widgets = {} self.port = port self.file_path = kwargs.get('file_url') self.file_pathBoot = kwargs.get('file_urlBoot') self.file_pathBootloader = kwargs.get('file_urlBootloader') self.file_pathPart = kwargs.get('file_urlPart') self._actions.append('download') self.erase = kwargs.get('erase') if self.erase: self._actions.append('erase') if self.file_path: self._actions.append('write') self.create_ui() self.start_process() def create_ui(self): for action in self._actions: pb = QProgressBar() pb.setFixedHeight(35) self._action_widgets[action] = pb self.actions_layout.addRow(action.capitalize(), pb) self.btns = QDialogButtonBox(QDialogButtonBox.Abort) self.btns.rejected.connect(self.abort) self.layout().addWidget(self.btns) self.sb = QStatusBar() self.layout().addWidget(self.sb) def appendBinFile1(self): self.bin_data1 += self.bin_reply1.readAll() def appendBinFile2(self): self.bin_data2 += self.bin_reply2.readAll() def appendBinFile3(self): self.bin_data3 += self.bin_reply3.readAll() def appendBinFile4(self): self.bin_data4 += self.bin_reply4.readAll() def downloadsFinished(self): if self.nrDownloads == 4: self.run_esp() def saveBinFile1(self): if self.bin_reply1.error() == QNetworkReply.NoError: self.file_path = self.file_path.split('/')[-1] with open(self.file_path, 'wb') as f: f.write(self.bin_data1) self.nrDownloads += 1 self.downloadsFinished() else: raise NetworkError def saveBinFile2(self): if self.bin_reply2.error() == QNetworkReply.NoError: self.file_pathBoot = self.file_pathBoot.split('/')[-1] with open(self.file_pathBoot, 'wb') as f: f.write(self.bin_data2) self.nrDownloads += 1 self.downloadsFinished() else: raise NetworkError def saveBinFile3(self): if self.bin_reply3.error() == QNetworkReply.NoError: self.file_pathBootloader = self.file_pathBootloader.split('/')[-1] with open(self.file_pathBootloader, 'wb') as f: f.write(self.bin_data3) self.nrDownloads += 1 self.downloadsFinished() else: raise NetworkError def saveBinFile4(self): if self.bin_reply4.error() == QNetworkReply.NoError: self.file_pathPart = self.file_pathPart.split('/')[-1] with open(self.file_pathPart, 'wb') as f: f.write(self.bin_data4) self.nrDownloads += 1 self.downloadsFinished() else: raise NetworkError def updateBinProgress(self, recv, total): self._action_widgets['download'].setValue(recv // total * 100) def download_bin(self): self.nrBinFile1.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True) self.nrBinFile1.setUrl(QUrl(self.file_path)) self.bin_reply1 = self.nam.get(self.nrBinFile1) self.bin_reply1.readyRead.connect(self.appendBinFile1) self.bin_reply1.downloadProgress.connect(self.updateBinProgress) self.bin_reply1.finished.connect(self.saveBinFile1) self.nrBinFile2.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True) self.nrBinFile2.setUrl(QUrl(self.file_pathBoot)) self.bin_reply2 = self.nam.get(self.nrBinFile2) self.bin_reply2.readyRead.connect(self.appendBinFile2) self.bin_reply2.finished.connect(self.saveBinFile2) self.nrBinFile3.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True) self.nrBinFile3.setUrl(QUrl(self.file_pathBootloader)) self.bin_reply3 = self.nam.get(self.nrBinFile3) self.bin_reply3.readyRead.connect(self.appendBinFile3) self.bin_reply3.finished.connect(self.saveBinFile3) self.nrBinFile4.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True) self.nrBinFile4.setUrl(QUrl(self.file_pathPart)) self.bin_reply4 = self.nam.get(self.nrBinFile4) self.bin_reply4.readyRead.connect(self.appendBinFile4) self.bin_reply4.finished.connect(self.saveBinFile4) def show_connection_state(self, state): self.sb.showMessage(state, 0) def run_esp(self): params = { 'file_path': self.file_path, 'file_pathBoot': self.file_pathBoot, 'file_pathBootloader': self.file_pathBootloader, 'file_pathPart': self.file_pathPart, 'erase': self.erase } self.esp_thread = QThread() self.esp = ESPWorker(self.port, self._actions, **params) esptool.sw.connection_state.connect(self.show_connection_state) self.esp.done.connect(self.accept) self.esp.error.connect(self.error) self.esp.moveToThread(self.esp_thread) self.esp_thread.started.connect(self.esp.run) self.esp_thread.start() def start_process(self): if 'download' in self._actions: self.download_bin() self._actions = self._actions[1:] else: self.run_esp() def update_progress(self, action, value): self._action_widgets[action].setValue(value) @pyqtSlot() def stop_thread(self): self.esp_thread.wait(2000) self.esp_thread.exit() def accept(self): self.stop_thread() self.done(QDialog.Accepted) def abort(self): self.sb.showMessage('Aborting...', 0) QApplication.processEvents() self.esp.abort() self.stop_thread() self.reject() def error(self, e): self.exception = e self.abort() def closeEvent(self, e): self.stop_thread()
def __init__(self, theParent): QStatusBar.__init__(self, theParent) logger.debug("Initialising MainStatus ...") self.mainConf = nw.CONFIG self.theParent = theParent self.refTime = None self.iconGrey = QPixmap(16, 16) self.iconYellow = QPixmap(16, 16) self.iconGreen = QPixmap(16, 16) self.monoFont = QFont("Monospace", 10) self.iconGrey.fill(QColor(*self.theParent.theTheme.statNone)) self.iconYellow.fill(QColor(*self.theParent.theTheme.statUnsaved)) self.iconGreen.fill(QColor(*self.theParent.theTheme.statSaved)) self.boxStats = QLabel() self.boxStats.setToolTip("Project Word Count | Session Word Count") self.timeBox = QLabel("") self.timeBox.setToolTip("Session Time") self.timeBox.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.timeBox.setFont(self.monoFont) self.timeIcon = QLabel() self.timeIcon.setPixmap( self.theParent.theTheme.getPixmap("time", (14, 14))) self.boxCounts = QLabel() self.boxCounts.setToolTip( "Document Character | Word | Paragraph Count") self.projChanged = QLabel("") self.projChanged.setFixedHeight(14) self.projChanged.setFixedWidth(14) self.projChanged.setToolTip("Project Changes Saved") self.docChanged = QLabel("") self.docChanged.setFixedHeight(14) self.docChanged.setFixedWidth(14) self.docChanged.setToolTip("Document Changes Saved") self.langBox = QLabel("None") self.langIcon = QLabel("") self.langIcon.setPixmap( self.theParent.theTheme.getPixmap("globe", (14, 14))) # Add Them self.addPermanentWidget(self.langIcon) self.addPermanentWidget(self.langBox) self.addPermanentWidget(QLabel(" ")) self.addPermanentWidget(self.docChanged) self.addPermanentWidget(self.boxCounts) self.addPermanentWidget(QLabel(" ")) self.addPermanentWidget(self.projChanged) self.addPermanentWidget(self.boxStats) self.addPermanentWidget(QLabel(" ")) self.addPermanentWidget(self.timeIcon) self.addPermanentWidget(self.timeBox) self.setSizeGripEnabled(True) self.sessionTimer = QTimer() self.sessionTimer.setInterval(1000) self.sessionTimer.timeout.connect(self._updateTime) self.sessionTimer.start() logger.debug("MainStatus initialisation complete") self.clearStatus() return
log = win.textEdit.toPlainText() + str(datetime.toString('dd.MM.yyyy, hh:mm:ss.zzz ')) + 'There are not only words in name or familia\n' win.textEdit.setText(log) return 0 return 1 def symbol_special(result_sum_ascii): mess = logsS.logs_special(result_sum_ascii) log = win.textEdit.toPlainText() + mess win.textEdit.setText(log) return mess ############## STATUS BAR ############## datetime = QDateTime.currentDateTime() #show status bar statusbar = QStatusBar() win.statusbar.setGeometry(300, 300, 250, 150) win.statusbar.setWindowTitle('Statusbar') win.statusbar.show() win.statusbar.showMessage(datetime.toString('dd.MM.yyyy, hh:mm:ss.zzz')) #timer on status bar def time(): datetime = QDateTime.currentDateTime() win.statusbar.showMessage(datetime.toString('dd.MM.yyyy, hh:mm:ss.zzz')) timer.start() #timer out timer = QTimer() timer.setInterval(10) timer.start()
class UI(QMainWindow): """ Clase que importara los ajustes de Javi. Con la main window""" pacientSelected = pyqtSignal(Pacient, int) changeStatusBar = pyqtSignal(str, int) hideViews = pyqtSignal(bool) key_press = pyqtSignal(QtGui.QKeyEvent) on_reload = pyqtSignal(bool) inited = False def __init__(self, debug=False): super().__init__() self.setObjectName("Main_window") self.settings = None Utils.debug = debug # TODO SINGLETONS ?¿?¿?¿?¿ UI.instance = self UI.threadpool = QThreadPool() UI.DEBUG = debug # TODO SINGLETONS ?¿?¿?¿?¿ THEY ARE REALLY NEEDED? self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.connection = AuthConnection() self.login_form = GUI_Resources.get_login_register_dialog( self.connection) self.user_credentials = {"result": False} self.credentials() self.menu = Menu() self.edit_patient = self.menu.addAction( StaticActions.edit_pacient_action) self.del_patient = self.menu.addAction( StaticActions.del_pacient_action) self.add_patient = self.menu.addAction( StaticActions.add_pacient_action) self.add_patient.setEnabled(False) self.edit_patient.setEnabled(False) self.del_patient.setEnabled(False) #self.add_patient.triggered.connect(self.handle_actions) #self.edit_patient.triggered.connect(self.handle_actions) #self.del_patient.triggered.connect(self.handle_actions) if self.user_credentials["result"]: if self.user_credentials["order"] == "login": self.show() elif self.user_credentials["order"] == "register": self.connection.register_user( self.user_credentials["username"], self.user_credentials["password"]) self.show() else: sys.exit(1) else: sys.exit(0) # Recogemos el Central widget, lo añadimos y luego lo inicializamos if debug: self.user_credentials["username"] = AuthConnection.default_user self.settings = UserSettings(self.user_credentials["username"]) self.setWindowTitle(self.settings.applicationName()) self.central = CentralWidgetParkingson( self.user_credentials["username"]) self.setCentralWidget(self.central) # Creamos el objeto settings if self.settings.value(self.settings.SIZE): rect = self.settings.value(self.settings.SIZE, type=QSize) self.resize(rect.width(), rect.height()) if self.settings.value(self.settings.FULLSCREEN, False, bool): self.showMaximized() pos = self.settings.value(self.settings.POSITION, QPoint(50, 50), QPoint) self.move(pos) PruebasListModel.get_instance(self.user_credentials["username"]) self.listview_model: AbstractEntityModel = PacientsListModel.get_instance( self.user_credentials["username"]) self.central.pacients_list_view.setModel(self.listview_model) self.setCentralWidget(self.central) self.menu_bar = MenuBar() self.status_bar = QStatusBar() self.toolbar = ToolBar() self.addToolBar(self.toolbar) self.setStatusBar(self.status_bar) self.setMenuBar(self.menu_bar) self.set_up_actions() self.central.pacients_list_view.clicked.connect( self.on_listview_pacient_click) self.central.pacients_list_view.doubleClicked.connect( self.on_pacient_double_click) self.central.pacients_list_view.customContextMenuRequested.connect( self.custom_context_menu) self.central.pacients_tab.finishedSignal.connect(self.on_finished) self.central.pacients_tab.resultSignal.connect(self.on_result) self.central.cronometro_tab.finishedSignal.connect( self.on_crono_finished) self.changeStatusBar.connect(self.changeStatus) self.central.pacients_tab.set_signal_pacient_selected( self.pacientSelected) self.central.cronometro_tab.set_signal_pacient_selected( self.pacientSelected) self.central.evolution_tab.set_signal_pacient_selected( self.pacientSelected) self.central.pacients_tab.set_change_status_bar(self.changeStatusBar) self.central.cronometro_tab.set_change_status_bar(self.changeStatusBar) self.central.evolution_tab.set_change_status_bar(self.changeStatusBar) self.central.pacients_tab.set_key_pressed(self.key_press) self.central.cronometro_tab.set_key_pressed(self.key_press) self.central.evolution_tab.set_key_pressed(self.key_press) self.central.pacients_tab.set_signal_current_changed( self.central.parent_tab_widget.currentChanged) self.central.cronometro_tab.set_signal_current_changed( self.central.parent_tab_widget.currentChanged) self.central.evolution_tab.set_signal_current_changed( self.central.parent_tab_widget.currentChanged) self.central.evolution_tab.set_on_reload_signal(self.on_reload) self.central.pacients_tab.set_on_reload_signal(self.on_reload) self.central.cronometro_tab.set_on_reload_signal(self.on_reload) self.hideViews.connect(self.hide_view) self.menu_bar.view_pacientes.setCheckable(True) self.menu_bar.view_toolbar.setCheckable(True) self.menu_bar.view_crono.setCheckable(True) self.menu_bar.view_rendimiento.setCheckable(True) self.menu_bar.view_pacientes.setChecked(True) self.menu_bar.view_toolbar.setChecked(True) self.menu_bar.view_crono.setChecked(True) self.menu_bar.view_rendimiento.setChecked(True) self.menu_bar.view_pacientes.changed.connect(self.hide_view) self.menu_bar.view_toolbar.changed.connect(self.hide_view) self.menu_bar.view_crono.changed.connect(self.hide_view) self.menu_bar.view_rendimiento.changed.connect(self.hide_view) self.central.parent_tab_widget.setEnabled(False) # INIT Tab Components self.central.pacients_tab.init() self.central.cronometro_tab.init() self.central.evolution_tab.init() # El tab de pacientes sera el por defecto. pacient_index = self.central.parent_tab_widget.indexOf( self.central.pacients_tab) self.central.parent_tab_widget.setCurrentIndex(pacient_index) self.iconSizeChanged.connect(self.iconSizeChanged) threading.Thread(target=self.check_camera_worker).start() self.inited = True def custom_context_menu(self, *args) -> None: if self.sender() == self.central.pacients_list_view: index = self.central.pacients_list_view.indexAt(args[0]).row() self.paciente = self.listview_model.get(index) StaticActions.del_pacient_action.setEnabled(True) StaticActions.edit_pacient_action.setEnabled(True) Utils.popup_context_menu(self.sender(), self.menu, args[0]) def handle_actions(self): if self.sender() == self.edit_pacient and self.prueba: pass elif self.sender() == self.add_pacient: pass elif self.sender() == self.del_prueba and self.prueba: pass def credentials(self): """ Funcion que pide las credenciales. Si le dan a cancelar, sale del programa. Si son incorrectas reintenta la conexion indefinidamente""" self.login_form.show() if not self.DEBUG: self.login_form.login_validator = self.connection.valid_user self.login_form.user_checker = self.connection.user_exists result = self.login_form.exec_() if result == 1 and self.login_form.result.get("result", False): self.user_credentials = self.login_form.result else: sys.exit(0) def on_listview_pacient_click(self, *args): """Slot for clicks in the listview, listens to the builtin Signal of clicked""" row = args[0].row() if not self.central.parent_tab_widget.isEnabled(): self.central.parent_tab_widget.setEnabled(True) p = self.listview_model.get(row) self.changeStatusBar.emit(f"Selecionado: {p}", 1) self.pacientSelected.emit(p, row) self.menu_bar.edit_pacient.setEnabled(True) self.menu_bar.del_pacient.setEnabled(True) def hide_view(self, *args): if self.menu_bar.view_toolbar == self.sender(): if not self.sender().isChecked(): self.removeToolBar(self.toolbar) else: self.addToolBar(self.toolbar) self.toolbar.setVisible(True) elif self.menu_bar.view_crono == self.sender(): self.central.cronometro_tab.setVisible(self.sender().isChecked()) self.central.parent_tab_widget.currentChanged.emit( self.central.parent_tab_widget.currentIndex()) if not self.sender().isChecked(): self.central.parent_tab_widget.setTabVisible(2, False) self.central.cronometro_tab.setVisible(False) else: self.central.parent_tab_widget.setTabVisible(2, True) self.central.cronometro_tab.setVisible( self.central.cronometro_tab.is_on_focus()) pass elif self.menu_bar.view_pacientes == self.sender(): self.central.pacients_tab.setVisible(self.sender().isChecked()) self.central.parent_tab_widget.currentChanged.emit( self.central.parent_tab_widget.currentIndex()) if not self.sender().isChecked(): self.central.parent_tab_widget.setTabVisible(0, False) self.central.pacients_tab.setVisible(False) self.central.pacients_tab.cancel_button.clicked.emit() else: self.central.parent_tab_widget.setTabVisible(0, True) self.central.pacients_tab.setVisible( self.central.cronometro_tab.is_on_focus()) elif self.menu_bar.view_rendimiento == self.sender(): self.central.evolution_tab.setVisible(self.sender().isChecked()) self.central.parent_tab_widget.currentChanged.emit( self.central.parent_tab_widget.currentIndex()) if not self.sender().isChecked(): self.central.parent_tab_widget.setTabVisible(1, False) self.central.evolution_tab.setVisible(False) else: self.central.parent_tab_widget.setTabVisible(1, True) self.central.evolution_tab.setVisible( self.central.evolution_tab.is_on_focus()) @staticmethod def get_instance(): return UI.instance def on_finished(self, enable): """Finished slot""" self.central.actions_buttons[self.central.ADD_button_key].setEnabled( enable) self.central.actions_buttons[ self.central.DELETE_button_key].setEnabled(enable) self.central.actions_buttons[self.central.EDIT_button_key].setEnabled( enable) self.central.pacients_list_view.setEnabled(enable) def on_result(self, acepted: bool, row: int): if acepted: # si es true, significa que han acabado de editar if row == -1: # estan creando un usuario self.listview_model.append(self.central.pacients_tab.pacient) self.central.pacients_list_view.setCurrentIndex( self.listview_model.index(len(self.listview_model), 0)) # QModelIndex no se lo que es pero para llamarlo lo necesito else: # estan editando un usuario, el PyQt da un numero aleatorio a row cuando es None self.listview_model.update( self.central.pacients_tab.pacient, self.central.pacients_tab.last_pacient) self.central.pacients_list_view.setCurrentIndex( self.listview_model.index(row, 0)) def on_pacient_double_click(self, *args): row = args[0].row() p = self.listview_model.get(row) self.status_bar.showMessage(f"Editando: {p}") self.menu_bar.edit_pacient.triggered.emit() def changeStatus(self, string, microseconds): self.status_bar.showMessage(string, microseconds * 1000) def button_clicked(self, *args): # Llevar esto a la clase pacientsform pacient_index = self.central.parent_tab_widget.indexOf( self.central.pacients_tab) self.central.parent_tab_widget.setCurrentIndex(pacient_index) if self.sender() == self.menu_bar.add_pacient: self.central.pacients_tab.pacientSelected(Pacient(), -1) self.central.pacients_tab.set_enabled(True) self.central.parent_tab_widget.setEnabled(True) elif self.sender() == self.menu_bar.del_pacient: if len(self.listview_model ) > 0 and self.central.pacients_tab.pacient_selected(): pacient = self.listview_model.entities[ self.central.pacients_tab.index] dialog = GUI_Resources.get_confirmation_dialog_ui( f"Quieres eliminar el usuario {pacient}") if dialog.exec_() == 1: self.listview_model.delete(pacient) elif self.sender() == self.menu_bar.edit_pacient: if len(self.listview_model.entities ) > 0 and self.central.pacients_tab.pacient_selected(): self.central.pacients_tab.set_enabled(True) elif self.sender() == self.menu_bar.recargar: instances = self.listview_model.get_user_instances( self.user_credentials["username"]) for instance in instances: instance.reload() self.on_reload.emit(True) def on_crono_finished(self, prueba, row): PruebasListModel.get_instance( self.user_credentials["username"]).append(prueba) p = self.listview_model.get(row) self.status_bar.showMessage(f"Insertada nueva prueba: {p}") def resizeEvent(self, a0: QtGui.QResizeEvent) -> None: super().resizeEvent(a0) size = a0.size() old_size = a0.oldSize() if self.inited: self.settings.setValue(self.settings.SIZE, a0.size()) self.settings.setValue(self.settings.FULLSCREEN, self.isFullScreen()) Utils.print_debug(f"{size} {old_size}") def keyPressEvent(self, a0: QtGui.QKeyEvent) -> None: super().keyPressEvent(a0) self.key_press.emit(a0) @staticmethod def check_camera_worker(): if not VideoCapture( 0).read()[0]: # Compruebo si hay camara. si no la hay haz X StaticActions.tomar_foto.setEnabled(False) def moveEvent(self, a0: QtGui.QMoveEvent) -> None: super().moveEvent(a0) if self.inited: self.settings.setValue(self.settings.POSITION, self.pos()) def export_to(self): if self.sender() == self.menu_bar.exportar_JSON: type_models = AbstractEntityModel.get_type_instances( self.user_credentials["username"]) for type_model in type_models: #type_model.get_as_json() pass elif self.sender() == self.menu_bar.exportar_XML: type_models = AbstractEntityModel.get_type_instances( self.user_credentials["username"]) for type_model in type_models: #type_model.get_as_xml() pass def set_up_actions(self): self.menu_bar.ajustes.setEnabled(False) self.menu_bar.ayuda.setEnabled(False) self.menu_bar.pruebas.setEnabled(True) self.menu_bar.edit_prueba.setEnabled(False) self.menu_bar.edit_pacient.setEnabled(False) self.menu_bar.del_pacient.setEnabled(False) self.menu_bar.add_pacient.setEnabled(True) self.menu_bar.add_pacient.triggered.connect(self.button_clicked) self.menu_bar.edit_pacient.triggered.connect(self.button_clicked) self.menu_bar.del_pacient.triggered.connect(self.button_clicked) self.menu_bar.edit_prueba.triggered.connect(self.button_clicked) self.menu_bar.del_prueba.triggered.connect(self.button_clicked) self.menu_bar.recargar.triggered.connect(self.button_clicked) self.menu_bar.consultar_tablas.setEnabled(False) self.menu_bar.exportar_XML.setEnabled(False) self.menu_bar.exportar_JSON.setEnabled(False)
class Principal(QMainWindow): def __init__(self): super(Principal, self).__init__() # Define as acoes self.acao_novo = QAction('&Novo', self) self.acao_abrir = QAction('Abrir', self) self.acao_exemplos = QAction('Exemplos', self) self.acao_sair = QAction('Sair', self) self.acao_fechar_aba = QAction('Fechar aba', self) self.acao_salvar = QAction('&Salvar', self) self.acao_salvar_como = QAction('Salvar como', self) self.acao_comentar_linha = QAction('Comentar linha', self) self.acao_achar = QAction('Achar...', self) self.acao_achar_e_substituir = QAction('Achar e substituir', self) self.acao_ir_para_linha = QAction('Ir para linha', self) self.acao_placa = QAction('Placa', self) self.acao_porta = QAction('Porta', self) self.acao_lingua = QAction('Lingua', self) self.acao_instalar_biblioteca = QAction('Instalar biblioteca', self) self.acao_monitor_serial = QAction('Monitor serial', self) self.acao_verificar = QAction('Verificar', self) self.acao_verificar_e_carregar = QAction('Verificar e carregar', self) self.menu_placas = QMenu('Placa') self.menu_portas = QMenu('Porta') self.menu_exemplos = QMenu('Exemplos') self.barra_de_status = QStatusBar() self.widget_central = UI.Centro(self) self.criar_barra_menu() self.init_ui() def init_ui(self): self.setStatusBar(self.barra_de_status) self.placa_porta_label = QLabel(Preferencias.get("board") + " na " + Preferencias.get("serial.port")) self.barra_de_status.addPermanentWidget(self.placa_porta_label) self.setCentralWidget(self.widget_central) self.setGeometry(100, 50, 500, 550) self.setMinimumSize(500, 520) self.setWindowTitle('Br.ino ' + versao) self.setWindowIcon(QIcon(os.path.join('recursos', 'logo.png'))) self.show() def criar_acoes(self): """ Define as funcoes de resposta as acoes e conecta elas. Define atalhos de teclado :return: None """ self.acao_sair.setShortcut('Ctrl+Q') self.acao_sair.setStatusTip('Sair da IDE do Br.ino') self.acao_sair.triggered.connect(self.close) self.acao_sair.triggered.connect(monitor.close) self.acao_fechar_aba.setShortcut('Ctrl+W') self.acao_fechar_aba.setStatusTip('Fechar aba atual') self.acao_fechar_aba.triggered.connect(self.widget_central.remover_aba) self.acao_novo.setShortcut("Ctrl+N") self.acao_novo.triggered.connect(self.widget_central.nova_aba) self.acao_novo.setStatusTip("Criar novo arquivo") self.acao_abrir.setShortcut('Ctrl+O') self.acao_abrir.triggered.connect(self.widget_central.abrir) self.acao_abrir.setStatusTip("Abrir arquivo") self.acao_salvar.setShortcut('Ctrl+S') self.acao_salvar.triggered.connect(self.widget_central.salvar) self.acao_salvar.setStatusTip("Salvar arquivo") self.acao_salvar_como.setShortcut('Ctrl+Shift+S') self.acao_salvar_como.triggered.connect(self.widget_central.salvar_como) self.acao_salvar_como.setStatusTip("Salvar arquivo como") self.acao_comentar_linha.setShortcut('Ctrl+/') self.acao_comentar_linha.triggered.connect(self.widget_central.comentar_linha) self.acao_comentar_linha.setStatusTip("Comentar linha") self.acao_achar.setShortcut('Ctrl+F') self.acao_achar.triggered.connect(self.widget_central.achar) self.acao_achar.setStatusTip("Achar...") self.acao_achar_e_substituir.setShortcut('Ctrl+H') self.acao_achar_e_substituir.triggered.connect(self.widget_central.achar_e_substituir) self.acao_achar_e_substituir.setStatusTip("Achar e substituir...") self.acao_ir_para_linha.setShortcut('Ctrl+L') self.acao_ir_para_linha.triggered.connect(GerenciadorDeCodigo.ir_para_linha) self.acao_ir_para_linha.setStatusTip("Ir para linha...") self.acao_lingua.triggered.connect(GerenciadorDeLinguas.lingua) self.acao_lingua.setStatusTip("Opções de língua") self.acao_instalar_biblioteca.triggered.connect(self.widget_central.instalar_biblioteca) self.acao_instalar_biblioteca.setStatusTip("Instalar bilioteca") self.acao_monitor_serial.setShortcut('Ctrl+Shift+M') self.acao_monitor_serial.triggered.connect(self.abrir_serial) self.acao_monitor_serial.setStatusTip("Abrir monitor serial") self.acao_verificar.setShortcut('Ctrl+R') self.acao_verificar.triggered.connect(self.widget_central.compilar) self.acao_verificar.setStatusTip("Verificar código") self.acao_verificar_e_carregar.setShortcut('Ctrl+U') self.acao_verificar_e_carregar.triggered.connect(self.widget_central.upload) self.acao_verificar_e_carregar.setStatusTip("Verificar e carregar código") def criar_barra_menu(self): """ Cria a barra menu e adiciona as funcoes nela :return: None """ self.criar_acoes() barra_menu = self.menuBar() barra_menu.setNativeMenuBar(False) menu_arquivo = barra_menu.addMenu('Arquivo') menu_arquivo.addAction(self.acao_novo) menu_arquivo.addAction(self.acao_abrir) menu_arquivo.addMenu(self.menu_exemplos) menu_arquivo.addAction(self.acao_salvar) menu_arquivo.addAction(self.acao_salvar_como) menu_arquivo.addAction(self.acao_fechar_aba) menu_arquivo.addAction(self.acao_sair) menu_editar = barra_menu.addMenu('Editar') menu_editar.addAction(self.acao_comentar_linha) menu_editar.addAction(self.acao_achar) menu_editar.addAction(self.acao_achar_e_substituir) menu_editar.addAction(self.acao_ir_para_linha) self.menu_ferramentas = barra_menu.addMenu('Ferramentas') self.menu_ferramentas.aboutToShow.connect(self.widget_central.criar_menu_portas) self.menu_ferramentas.addMenu(self.menu_placas) self.menu_ferramentas.addMenu(self.menu_portas) self.menu_ferramentas.addAction(self.acao_lingua) self.menu_ferramentas.addAction(self.acao_monitor_serial) self.menu_ferramentas.addAction(self.acao_instalar_biblioteca) menu_rascunho = barra_menu.addMenu('Rascunho') menu_rascunho.addAction(self.acao_verificar) menu_rascunho.addAction(self.acao_verificar_e_carregar) def abrir_serial(self): """ Abre o monitor serial ou indica que a porta nao esta disponivel :return: None """ if monitor.conectar(Preferencias.get("serial.port")): monitor.show() else: QMessageBox(QMessageBox.Warning, "Erro", "A porta selecionada não está disponível", QMessageBox.NoButton, self).show() def closeEvent(self, close_event): """ Fecha o programa, mas antes verifica se os arquivos foram salvos :param close_event: :return: """ if self.widget_central.widget_abas.widget(0).caminho == 0: num_examinar = 1 else: num_examinar = 0 for num_arquivo in range(self.widget_central.widget_abas.count() - num_examinar): if not self.widget_central.remover_aba(num_examinar, True): close_event.ignore() return monitor.close() close_event.accept()
def _createStatusBar(self): status = QStatusBar() status.showMessage("I'm the Status Bar") self.setStatusBar(status)
def init(self): QWidget.__init__(self) self.item_height = 10 self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) #self.setFixedSize(400,160) #self.setFixedWidth(700) self.setStyleSheet(" padding:0px; margin-top:0px; margin-bottom:0px") #; border:2px solid rgb(0, 0, 0); self.last = [] self.pos = -1 self.move_window() self.vbox = QVBoxLayout() #self.vbox.setAlignment(Qt.AlignTop) self.box = [] self.image = [] self.label = [] for i in range(0, 5): l = QHBoxLayout() label = QLabel() label.setWordWrap(True) label.setOpenExternalLinks(True) image = QLabel() image.setFixedWidth(48) self.box.append(QWidget()) self.image.append(image) label.setAlignment(Qt.AlignLeft | Qt.AlignTop) self.label.append(label) self.box[i].setLayout(l) #self.box[i].setFixedSize(380,80) #setMinimumSize(400, 500)# l.addWidget(self.image[i]) l.addWidget(self.label[i]) toolbar = QToolBar() toolbar.setIconSize(QSize(48, 48)) self.back = QAction(icon_get("go-previous", size=32), _("Back"), self) self.back.triggered.connect(self.callback_back) toolbar.addAction(self.back) self.forward = QAction(icon_get("go-next", size=32), _("Next"), self) self.forward.triggered.connect(self.callback_forward) toolbar.addAction(self.forward) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.undo = QAction(QIcon(get_icon_path("www")), _("Online help"), self) self.undo.setStatusTip(_("On line help")) self.undo.triggered.connect(self.on_line_help) toolbar.addAction(self.undo) self.undo = QAction(icon_get("close", size=32), _("Hide"), self) self.undo.setStatusTip(_("Close")) self.undo.triggered.connect(self.callback_close) toolbar.addAction(self.undo) self.vbox.addWidget(toolbar) for i in range(0, 5): self.vbox.addWidget(self.box[i]) self.vbox.addStretch() self.status_bar = QStatusBar() self.vbox.addWidget(self.status_bar) self.setLayout(self.vbox)
class help_class(QWidget): def move_window(self): shape = QDesktopWidget().screenGeometry() w = shape.width() h = shape.height() win_w = self.frameGeometry().width() win_h = self.frameGeometry().height() x = w - win_w y = 50 self.move(x, y) def help_show(self): self.show() self.move_window() def toggle_visible(self): if self.isVisible() == True: self.setVisible(False) else: self.setVisible(True) self.move_window() def init(self): QWidget.__init__(self) self.item_height = 10 self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) #self.setFixedSize(400,160) #self.setFixedWidth(700) self.setStyleSheet(" padding:0px; margin-top:0px; margin-bottom:0px") #; border:2px solid rgb(0, 0, 0); self.last = [] self.pos = -1 self.move_window() self.vbox = QVBoxLayout() #self.vbox.setAlignment(Qt.AlignTop) self.box = [] self.image = [] self.label = [] for i in range(0, 5): l = QHBoxLayout() label = QLabel() label.setWordWrap(True) label.setOpenExternalLinks(True) image = QLabel() image.setFixedWidth(48) self.box.append(QWidget()) self.image.append(image) label.setAlignment(Qt.AlignLeft | Qt.AlignTop) self.label.append(label) self.box[i].setLayout(l) #self.box[i].setFixedSize(380,80) #setMinimumSize(400, 500)# l.addWidget(self.image[i]) l.addWidget(self.label[i]) toolbar = QToolBar() toolbar.setIconSize(QSize(48, 48)) self.back = QAction(icon_get("go-previous", size=32), _("Back"), self) self.back.triggered.connect(self.callback_back) toolbar.addAction(self.back) self.forward = QAction(icon_get("go-next", size=32), _("Next"), self) self.forward.triggered.connect(self.callback_forward) toolbar.addAction(self.forward) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.undo = QAction(QIcon(get_icon_path("www")), _("Online help"), self) self.undo.setStatusTip(_("On line help")) self.undo.triggered.connect(self.on_line_help) toolbar.addAction(self.undo) self.undo = QAction(icon_get("close", size=32), _("Hide"), self) self.undo.setStatusTip(_("Close")) self.undo.triggered.connect(self.callback_close) toolbar.addAction(self.undo) self.vbox.addWidget(toolbar) for i in range(0, 5): self.vbox.addWidget(self.box[i]) self.vbox.addStretch() self.status_bar = QStatusBar() self.vbox.addWidget(self.status_bar) self.setLayout(self.vbox) def callback_close(self, widget): self.toggle_visible() def callback_forward(self, widget): self.pos = self.pos + 1 if self.pos >= len(self.last): self.pos = len(self.last) - 1 self.update() def callback_back(self, widget): self.pos = self.pos - 1 if self.pos < 0: self.pos = 0 self.update() def on_line_help(self, widget): webbrowser.open("https://www.gpvdm.com/man/index.html") def update(self): items = int(len(self.last[self.pos]) / 2) for i in range(0, 5): self.box[i].hide() for i in range(0, items): all_text = self.last[self.pos][i * 2 + 1] nbr = all_text.count("<br>") end_text = len(all_text.split("<br>")[-1]) pixmap = QPixmap(get_icon_path(self.last[self.pos][i * 2], size=32)) self.image[i].setPixmap(pixmap) text = all_text + "<br>" self.label[i].setText(text) height = ((end_text / 80) + nbr) * 20 #self.label[i].setFixedSize(380,300) self.label[i].adjustSize() self.label[i].setOpenExternalLinks(True) self.box[i].show() #self.image[i].show() self.resize(300, items * self.item_height) self.forward.setEnabled(True) self.back.setEnabled(True) if self.pos == 0: self.back.setEnabled(False) if self.pos == len(self.last) - 1: self.forward.setEnabled(False) self.status_bar.showMessage( str(self.pos) + "/" + str(len(self.last) - 1)) def help_set_help(self, array): add = True if len(self.last) != 0: if self.last[self.pos][1] == array[1]: add = False if add == True: self.pos = self.pos + 1 self.last.append(array) self.update() self.move_window() def help_append(self, array): last_item = len(self.last) - 1 self.last[last_item] = self.last[last_item] + array self.update() #self.resize(300, 150) self.move_window()
def __init__(self, name): QWidgetSavePos.__init__(self, name) self.main_vbox = QVBoxLayout() #self.setFixedSize(900, 700) self.setWindowTitle(_("Fit window") + " https://www.gpvdm.com") self.setWindowIcon(icon_get("fit")) toolbar = QToolBar() toolbar.setIconSize(QSize(48, 48)) toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.order_widget = order_widget() self.order_widget.new_text = _("New fit") self.order_widget.delete_text = _("Delete fit") self.order_widget.clone_text = _("Clone fit") self.order_widget.rename_text = _("Rename fit") self.order_widget.new_dlg_text = _("New fit name:") self.order_widget.base_file_name = [ "fit", "fit_data", "fit_patch", "fit_math" ] self.order_widget.new_tab_name = _("fit ") self.order_widget.clone_dlg_text = _( "Clone the current fit to a new fit called:") self.order_widget.rename_dlg_text = _("Rename the fit to be called:") self.order_widget.delete_dlg_text = _("Should I remove the fit file ") self.order_widget.name_token = "#fit_name" self.order_widget.init() toolbar.addWidget(self.order_widget) self.order_widget.added.connect(self.callback_add_page) toolbar.addSeparator() self.tb_configure = QAction(icon_get("preferences-system"), wrap_text(_("Configure"), 4), self) self.tb_configure.triggered.connect(self.callback_configure) toolbar.addAction(self.tb_configure) self.import_data = QAction(icon_get("import"), _("Import data"), self) self.import_data.triggered.connect(self.callback_import) toolbar.addAction(self.import_data) toolbar.addSeparator() self.play = QAction(icon_get("media-playback-start"), wrap_text(_("Run a single fit"), 4), self) self.play.triggered.connect(self.callback_one_fit) toolbar.addAction(self.play) self.play = QAction(icon_get("forward"), wrap_text(_("Start the fitting process"), 4), self) self.play.triggered.connect(self.callback_do_fit) toolbar.addAction(self.play) self.pause = QAction(icon_get("media-playback-pause"), wrap_text(_("Stop the simulation"), 4), self) self.pause.triggered.connect(self.callback_stop) toolbar.addAction(self.pause) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.help = QAction(icon_get("help"), _("Help"), self) self.help.triggered.connect(self.callback_help) toolbar.addAction(self.help) self.main_vbox.addWidget(toolbar) self.notebook = QTabWidget() self.order_widget.notebook_pointer = self.notebook css_apply(self.notebook, "style_h.css") self.notebook.setTabBar(QHTabBar()) self.notebook.setTabPosition(QTabWidget.West) self.notebook.setMovable(True) self.load_tabs() self.main_vbox.addWidget(self.notebook) self.status_bar = QStatusBar() self.main_vbox.addWidget(self.status_bar) self.setLayout(self.main_vbox) self.fit_configure_window = None
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self._version = __version__ self.setWindowIcon(QIcon(":/logo.png")) self.setWindowTitle("Tasmota Device Manager {}".format(self._version)) self.menuBar().setNativeMenuBar(False) self.unknown = [] self.env = TasmotaEnvironment() self.device = None self.topics = [] self.mqtt_queue = [] self.fulltopic_queue = [] # ensure TDM directory exists in the user directory if not os.path.isdir("{}/TDM".format(QDir.homePath())): os.mkdir("{}/TDM".format(QDir.homePath())) self.settings = QSettings("{}/TDM/tdm.cfg".format(QDir.homePath()), QSettings.IniFormat) self.devices = QSettings("{}/TDM/devices.cfg".format(QDir.homePath()), QSettings.IniFormat) self.setMinimumSize(QSize(1000, 600)) # configure logging logging.basicConfig(filename="{}/TDM/tdm.log".format(QDir.homePath()), level=self.settings.value("loglevel", "INFO"), datefmt="%Y-%m-%d %H:%M:%S", format='%(asctime)s [%(levelname)s] %(message)s') logging.info("### TDM START ###") # load devices from the devices file, create TasmotaDevices and add the to the environment for mac in self.devices.childGroups(): self.devices.beginGroup(mac) device = TasmotaDevice(self.devices.value("topic"), self.devices.value("full_topic"), self.devices.value("device_name")) device.debug = self.devices.value("debug", False, bool) device.p['Mac'] = mac.replace("-", ":") device.env = self.env self.env.devices.append(device) # load device command history self.devices.beginGroup("history") for k in self.devices.childKeys(): device.history.append(self.devices.value(k)) self.devices.endGroup() self.devices.endGroup() self.device_model = TasmotaDevicesModel(self.env) self.setup_mqtt() self.setup_main_layout() self.add_devices_tab() self.build_mainmenu() # self.build_toolbars() self.setStatusBar(QStatusBar()) pbSubs = QPushButton("Show subscriptions") pbSubs.setFlat(True) pbSubs.clicked.connect(self.showSubs) self.statusBar().addPermanentWidget(pbSubs) self.queue_timer = QTimer() self.queue_timer.timeout.connect(self.mqtt_publish_queue) self.queue_timer.start(250) self.auto_timer = QTimer() self.auto_timer.timeout.connect(self.auto_telemetry) self.load_window_state() if self.settings.value("connect_on_startup", False, bool): self.actToggleConnect.trigger() self.tele_docks = {} self.consoles = []
def run(self): #当绘图窗口的圆图形字典为空时输出错误信息 if len(self.pw.circle_dict) == 0: msg = QMessageBox(QMessageBox.Critical, "错误", "未绘制AOE网") msg.exec() else: ok, order = topologySort(self.pw.circle_dict, self.pw.line_dict) if ok: #AOE网络合法 #执行相关算法 graph_head, graph_tail = transform(self.pw.circle_dict, self.pw.line_dict, order) aoe = AOE(graph_head, graph_tail, self.pw.circle_dict, self.pw.line_dict) self.pw.critical_activity, self.pw.critical_affair = aoe.function( ) self.routes, self.activities = aoe.critical() self.time = aoe.time self.Ve = aoe.Ve self.Vl = aoe.Vl self.e = aoe.e self.l = aoe.l self.pw.update() #更新绘图区 self.pw.isnew = True status = QStatusBar() #更新状态栏 status.showMessage('运行结果已更新') self.mw.setStatusBar(status) self.mw.action_save_result.setEnabled(True) #启用保存结果按钮 self.mw.label_time.setText(str(self.time)) #显示工程最短运行时间 #显示关键路径和关键活动 self.mw.tableWidget_critical.setRowCount(len(self.routes)) for i in range(len(self.routes)): route = self.routes[i] activity = self.activities[i] item = QTableWidgetItem() item.setText(route) self.mw.tableWidget_critical.setItem(i, 0, item) item = QTableWidgetItem() item.setText(activity) self.mw.tableWidget_critical.setItem(i, 1, item) #显示Ve,Vl self.mw.tableWidget_v.setRowCount(len(self.Ve)) row = 0 for v, ve in self.Ve.items(): vl = self.Vl[v] name = self.pw.circle_dict[v][0] item = QTableWidgetItem() item.setText(name) self.mw.tableWidget_v.setItem(row, 0, item) item = QTableWidgetItem() item.setText(str(ve)) self.mw.tableWidget_v.setItem(row, 1, item) item = QTableWidgetItem() item.setText(str(vl)) self.mw.tableWidget_v.setItem(row, 2, item) row += 1 #显示e,l self.mw.tableWidget_a.setRowCount(len(self.e)) row = 0 for a, ae in self.e.items(): al = self.l[a] name = '<' + self.pw.circle_dict[self.pw.line_dict[a][1]][ 0] + ',' + self.pw.circle_dict[self.pw.line_dict[a] [2]][0] + '>' item = QTableWidgetItem() item.setText(name) self.mw.tableWidget_a.setItem(row, 0, item) item = QTableWidgetItem() item.setText(str(ae)) self.mw.tableWidget_a.setItem(row, 1, item) item = QTableWidgetItem() item.setText(str(al)) self.mw.tableWidget_a.setItem(row, 2, item) row += 1 #显示结果dock栏 self.mw.dock_result.show() self.mw.dock_result.setMinimumSize(540, 500) self.isdock = True else: #工程不可行输出错误信息 msg = QMessageBox(QMessageBox.Critical, "错误", "该工程不可行,AOE网络必须是单源点单汇点的有向无环图") msg.addButton("确定", QMessageBox.YesRole) msg.exec()
def __init__(self, parent=None): super(Form, self).__init__(parent) self.db_interface = DB_Interface() self.db_interface.new_tracking_item.connect(self.update_tracking) fibre_saturation_Label = QLabel("Fiber Saturation Ratio (%) (from tables)") self.fibre_saturation_spinbox = QDoubleSpinBox() self.fibre_saturation_spinbox.setDecimals(1) self.fibre_saturation_spinbox.setRange(0, 100) self.fibre_saturation_spinbox.setSingleStep(0.1) self.fibre_saturation_spinbox.setValue(18) #self.fibre_saturation_spinbox.valueChanged.connect(self.control.update_EMC_fast_target) temperature_Label = QLabel("Current temperature measurement") #self.temperature_value_label = QLabel("{0}".format(self.control.temperature)) humidity_Label = QLabel("Current humidity measurement") #self.humidity_value_label = QLabel("{0}".format(self.control.humidity)) final_saturation_Label = QLabel("Target wood saturation Ratio (%)") self.final_saturation_spinbox = QDoubleSpinBox() self.final_saturation_spinbox.setDecimals(1) self.final_saturation_spinbox.setRange(0, 100) self.final_saturation_spinbox.setSingleStep(0.1) self.final_saturation_spinbox.setValue(6) #self.final_saturation_spinbox.valueChanged.connect(self.control.update_EMC_slow_target) emc_Label = QLabel("Equilibrium Moisture Content") #self.emc_value_label = QLabel("{0}".format(self.control.equilibrium_moisture_content)) self.temp_deque_len_label = QLabel() #self.temp_deque_len_label.setNum(len(self.control.temp_deque1)) self.dummy_label = QLabel() #self.dummy_label.setNum(self.control.state) mainLayout = QGridLayout() mainLayout.addWidget(fibre_saturation_Label, 0 , 0) mainLayout.addWidget(self.fibre_saturation_spinbox, 1 , 0) mainLayout.addWidget(temperature_Label, 2 , 0) #mainLayout.addWidget(self.temperature_value_label, 3 , 0) mainLayout.addWidget(humidity_Label, 4 , 0) #mainLayout.addWidget(self.humidity_value_label, 5 , 0) mainLayout.addWidget(final_saturation_Label, 0 , 1) mainLayout.addWidget(self.final_saturation_spinbox, 1 , 1) mainLayout.addWidget(emc_Label, 2 , 1) #mainLayout.addWidget(self.emc_value_label, 3 , 1) mainLayout.addWidget(self.temp_deque_len_label, 4 , 1) mainLayout.addWidget(self.dummy_label, 5 , 1) self.fire_icon = QPixmap("burn.png") self.red_icon = QPixmap("circle_red.png") self.green_icon = QPixmap("circle_green.png") self.fire_label1 = QLabel() self.fire_label2 = QLabel() self.fire_label1.setPixmap(self.fire_icon) self.fire_label2.setPixmap(self.fire_icon) self.water_icon = QPixmap("water.png") self.water_label = QLabel() self.water_label.setPixmap(self.water_icon) self.statusBar = QStatusBar() self.statusBar.addPermanentWidget(self.fire_label1) self.statusBar.addPermanentWidget(self.fire_label2) self.statusBar.addPermanentWidget(self.water_label) #self.statusBar.showMessage("{0} - {1} - {2}".format(self.control.state,self.control.states_list[self.control.state],len(self.control.temp_deque1))) centralWidget = QWidget() centralWidget.setLayout(mainLayout) self.setCentralWidget(centralWidget) self.setWindowTitle("Humidity Control V1.0") self.setStatusBar(self.statusBar)
def __init__(self, debug=False): super().__init__() self.setObjectName("Main_window") self.settings = None Utils.debug = debug # TODO SINGLETONS ?¿?¿?¿?¿ UI.instance = self UI.threadpool = QThreadPool() UI.DEBUG = debug # TODO SINGLETONS ?¿?¿?¿?¿ THEY ARE REALLY NEEDED? self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.connection = AuthConnection() self.login_form = GUI_Resources.get_login_register_dialog( self.connection) self.user_credentials = {"result": False} self.credentials() self.menu = Menu() self.edit_patient = self.menu.addAction( StaticActions.edit_pacient_action) self.del_patient = self.menu.addAction( StaticActions.del_pacient_action) self.add_patient = self.menu.addAction( StaticActions.add_pacient_action) self.add_patient.setEnabled(False) self.edit_patient.setEnabled(False) self.del_patient.setEnabled(False) #self.add_patient.triggered.connect(self.handle_actions) #self.edit_patient.triggered.connect(self.handle_actions) #self.del_patient.triggered.connect(self.handle_actions) if self.user_credentials["result"]: if self.user_credentials["order"] == "login": self.show() elif self.user_credentials["order"] == "register": self.connection.register_user( self.user_credentials["username"], self.user_credentials["password"]) self.show() else: sys.exit(1) else: sys.exit(0) # Recogemos el Central widget, lo añadimos y luego lo inicializamos if debug: self.user_credentials["username"] = AuthConnection.default_user self.settings = UserSettings(self.user_credentials["username"]) self.setWindowTitle(self.settings.applicationName()) self.central = CentralWidgetParkingson( self.user_credentials["username"]) self.setCentralWidget(self.central) # Creamos el objeto settings if self.settings.value(self.settings.SIZE): rect = self.settings.value(self.settings.SIZE, type=QSize) self.resize(rect.width(), rect.height()) if self.settings.value(self.settings.FULLSCREEN, False, bool): self.showMaximized() pos = self.settings.value(self.settings.POSITION, QPoint(50, 50), QPoint) self.move(pos) PruebasListModel.get_instance(self.user_credentials["username"]) self.listview_model: AbstractEntityModel = PacientsListModel.get_instance( self.user_credentials["username"]) self.central.pacients_list_view.setModel(self.listview_model) self.setCentralWidget(self.central) self.menu_bar = MenuBar() self.status_bar = QStatusBar() self.toolbar = ToolBar() self.addToolBar(self.toolbar) self.setStatusBar(self.status_bar) self.setMenuBar(self.menu_bar) self.set_up_actions() self.central.pacients_list_view.clicked.connect( self.on_listview_pacient_click) self.central.pacients_list_view.doubleClicked.connect( self.on_pacient_double_click) self.central.pacients_list_view.customContextMenuRequested.connect( self.custom_context_menu) self.central.pacients_tab.finishedSignal.connect(self.on_finished) self.central.pacients_tab.resultSignal.connect(self.on_result) self.central.cronometro_tab.finishedSignal.connect( self.on_crono_finished) self.changeStatusBar.connect(self.changeStatus) self.central.pacients_tab.set_signal_pacient_selected( self.pacientSelected) self.central.cronometro_tab.set_signal_pacient_selected( self.pacientSelected) self.central.evolution_tab.set_signal_pacient_selected( self.pacientSelected) self.central.pacients_tab.set_change_status_bar(self.changeStatusBar) self.central.cronometro_tab.set_change_status_bar(self.changeStatusBar) self.central.evolution_tab.set_change_status_bar(self.changeStatusBar) self.central.pacients_tab.set_key_pressed(self.key_press) self.central.cronometro_tab.set_key_pressed(self.key_press) self.central.evolution_tab.set_key_pressed(self.key_press) self.central.pacients_tab.set_signal_current_changed( self.central.parent_tab_widget.currentChanged) self.central.cronometro_tab.set_signal_current_changed( self.central.parent_tab_widget.currentChanged) self.central.evolution_tab.set_signal_current_changed( self.central.parent_tab_widget.currentChanged) self.central.evolution_tab.set_on_reload_signal(self.on_reload) self.central.pacients_tab.set_on_reload_signal(self.on_reload) self.central.cronometro_tab.set_on_reload_signal(self.on_reload) self.hideViews.connect(self.hide_view) self.menu_bar.view_pacientes.setCheckable(True) self.menu_bar.view_toolbar.setCheckable(True) self.menu_bar.view_crono.setCheckable(True) self.menu_bar.view_rendimiento.setCheckable(True) self.menu_bar.view_pacientes.setChecked(True) self.menu_bar.view_toolbar.setChecked(True) self.menu_bar.view_crono.setChecked(True) self.menu_bar.view_rendimiento.setChecked(True) self.menu_bar.view_pacientes.changed.connect(self.hide_view) self.menu_bar.view_toolbar.changed.connect(self.hide_view) self.menu_bar.view_crono.changed.connect(self.hide_view) self.menu_bar.view_rendimiento.changed.connect(self.hide_view) self.central.parent_tab_widget.setEnabled(False) # INIT Tab Components self.central.pacients_tab.init() self.central.cronometro_tab.init() self.central.evolution_tab.init() # El tab de pacientes sera el por defecto. pacient_index = self.central.parent_tab_widget.indexOf( self.central.pacients_tab) self.central.parent_tab_widget.setCurrentIndex(pacient_index) self.iconSizeChanged.connect(self.iconSizeChanged) threading.Thread(target=self.check_camera_worker).start() self.inited = True
def draw(self, qp): brush = QBrush() #刷子对象 pen = QPen() #画笔对象 lightgray = QColor() #自定义颜色 lightgray.setRgb(240, 240, 240) #绘制各个连接线 for line, value in self.line_dict.items(): if value[2] == '': #连接线终点未指定时,绘制一条虚线,终点跟随鼠标 pen.setStyle(Qt.DashLine) pen.setColor(Qt.black) qp.setPen(pen) lineF = QLineF( QPoint(self.circle_dict[value[1]][1][0], self.circle_dict[value[1]][1][1]), QPoint(self.line_dest_pos[0], self.line_dest_pos[1])) e = lineF.unitVector() new_lineF = QLineF( QPoint( self.circle_dict[value[1]][1][0] + int(e.dx() * self.d / 2), self.circle_dict[value[1]][1][1] + int(e.dy() * self.d / 2)), QPoint(self.line_dest_pos[0], self.line_dest_pos[1])) qp.drawLine(new_lineF) #连接线两端的圆形是相离状态时,绘制有向箭头 elif ((self.circle_dict[value[1]][1][0] - self.circle_dict[value[2]][1][0])**2 + (self.circle_dict[value[1]][1][1] - self.circle_dict[value[2]][1][1])**2)**0.5 > self.d: lineF = QLineF( QPoint(self.circle_dict[value[1]][1][0], self.circle_dict[value[1]][1][1]), QPoint(self.circle_dict[value[2]][1][0], self.circle_dict[value[2]][1][1])) e = lineF.unitVector() new_lineF = QLineF( QPoint( self.circle_dict[value[1]][1][0] + int(e.dx() * self.d / 2), self.circle_dict[value[1]][1][1] + int(e.dy() * self.d / 2)), QPoint( self.circle_dict[value[2]][1][0] - int(e.dx() * self.d / 2), self.circle_dict[value[2]][1][1] - int(e.dy() * self.d / 2))) #如果已生成关键路径且图形是最新的,设定连接线为红色 if line in self.critical_activity and self.isnew: pen.setColor(Qt.red) else: #否则连接线为黑色 pen.setColor(Qt.black) pen.setStyle(Qt.SolidLine) qp.setPen(pen) #绘制连接线 qp.drawLine(new_lineF) #运用向量计算箭头三个顶点 e.translate(new_lineF.dx() + e.dx(), new_lineF.dy() + e.dy()) n1 = e.normalVector() n1.setLength(self.line_width) n2 = n1.normalVector().normalVector() #如果已生成关键路径且图形是最新的,设定箭头为红色 if line in self.critical_activity and self.isnew: brush.setColor(Qt.red) else: #否则箭头为黑色 brush.setColor(Qt.black) brush.setStyle(Qt.SolidPattern) qp.setBrush(brush) #绘制箭头 qp.drawPolygon(n1.p2(), n2.p2(), new_lineF.p2()) #计算箭头上文字的长宽 metrics = qp.fontMetrics() width = metrics.width(str(value[0])) height = metrics.height() head_pos = self.circle_dict[value[1]][1] tail_pos = self.circle_dict[value[2]][1] x = (head_pos[0] + tail_pos[0]) / 2 - width / 2 y = (head_pos[1] + tail_pos[1]) / 2 + height / 2 #绘制箭头上文字的底色 brush.setColor(lightgray) brush.setStyle(Qt.SolidPattern) qp.setBrush(brush) pen.setColor(lightgray) pen.setStyle(Qt.SolidLine) qp.setPen(pen) rect = QRect() rect.setRect((head_pos[0] + tail_pos[0]) / 2 - width / 2, (head_pos[1] + tail_pos[1]) / 2 - height / 2, width, height) qp.drawRect(rect) #如果已生成关键路径且图形是最新的,设定箭头上文字为红色 if line in self.critical_activity and self.isnew: pen.setColor(Qt.red) else: #否则设定文字为黑色 pen.setColor(Qt.black) pen.setStyle(Qt.SolidLine) qp.setPen(pen) #绘制箭头上文字 qp.drawText(x, y, str(value[0])) #为了圆形的遮盖次序和选中次序统一,逆序绘制圆形 circles = list(self.circle_dict.keys()) circles.reverse() for circle in circles: value = self.circle_dict[circle] color = QColor() if self.isget and self.circle_gotton == circle: #如果圆形被选中设定颜色为青色 color.setRgb(100, 200, 200) else: #否则设定颜色为黄色 color.setRgb(255, 255, 150) brush = QBrush() brush.setColor(color) brush.setStyle(Qt.SolidPattern) qp.setBrush(brush) pen.setStyle(Qt.SolidLine) if circle in self.critical_affair and self.isnew: #如果已生成关键路径且图形是最新的,设定圆形边框为红色 pen.setColor(Qt.red) else: #否则设定颜色为黑色 pen.setColor(Qt.black) qp.setPen(pen) #绘制圆形 qp.drawEllipse(value[1][0] - self.d / 2, value[1][1] - self.d / 2, self.d, self.d) #获取圆形上文字的长宽 metrics = qp.fontMetrics() width = metrics.width(value[0]) height = metrics.height() x = value[1][0] - width / 2 y = value[1][1] + height / 2 #绘制圆形上文字 qp.drawText(x, y, value[0]) #如果结果窗口已展开但图形不是最新的 if not self.isnew and self.parent.isdock: #设置主窗口状态栏 status = QStatusBar() status.showMessage('运行结果已过期') self.parent.mw.setStatusBar(status) #禁用主窗口保存结果按钮 self.parent.mw.action_save_result.setEnabled(False) #收起主窗口 self.parent.mw.dock_result.close() self.parent.isdock = False
def __init__(self): QStatusBar.__init__(self) self.progress_bar = QProgressBar() self.addWidget(self.progress_bar)
def setupUi(self): self.setObjectName("MainWindow") self.setFixedSize(1040, 915) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) icon = QIcon() icon.addPixmap(QPixmap('./resource/weather-thunder.png'),QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) self.centralwidget = QWidget(self) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth()) self.centralwidget.setSizePolicy(sizePolicy) self.centralwidget.setObjectName("centralwidget") self.layoutWidget = QWidget(self.centralwidget) self.layoutWidget.setGeometry(QRect(32, 10, 979, 851)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_5 =QVBoxLayout(self.layoutWidget) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName("verticalLayout_5") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.datetime_label = QLabel(self.layoutWidget) self.datetime_label.setObjectName("datetime_label") self.horizontalLayout.addWidget(self.datetime_label) self.datetime = QDateEdit(self.layoutWidget) self.datetime.setDateTime(QDateTime(QDate(self.lastyear, 1, 1), QTime(0, 0, 0))) self.datetime.setObjectName("datetime") self.horizontalLayout.addWidget(self.datetime) spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem1) self.target_area_label = QLabel(self.layoutWidget) self.target_area_label.setObjectName("target_area_label") self.horizontalLayout.addWidget(self.target_area_label) self.target_area = QComboBox(self.layoutWidget) self.target_area.setObjectName("target_area") self.target_area.addItem("") self.target_area.addItem("") self.target_area.addItem("") self.target_area.addItem("") self.target_area.addItem("") self.target_area.addItem("") self.horizontalLayout.addWidget(self.target_area) spacerItem2 = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem2) self.verticalLayout_5.addLayout(self.horizontalLayout) self.tabWidget = QTabWidget(self.layoutWidget) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) self.tabWidget.setSizePolicy(sizePolicy) self.tabWidget.setObjectName("tabWidget") self.density_tab = QWidget() self.density_tab.setObjectName("density_tab") self.verticalLayout_3 =QVBoxLayout(self.density_tab) self.verticalLayout_3.setObjectName("verticalLayout_3") self.verticalLayout_2 =QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.horizontalLayout_2 = QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.density_cell_label = QLabel(self.density_tab) self.density_cell_label.setObjectName("density_cell_label") self.horizontalLayout_2.addWidget(self.density_cell_label) self.density_cell = QSpinBox(self.density_tab) self.density_cell.setProperty("value", 10) self.density_cell.setObjectName("density_cell") self.horizontalLayout_2.addWidget(self.density_cell) spacerItem3 = QSpacerItem(40, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem3) self.density_class_label = QLabel(self.density_tab) self.density_class_label.setObjectName("density_class_label") self.horizontalLayout_2.addWidget(self.density_class_label) self.density_class = QSpinBox(self.density_tab) self.density_class.setProperty("value", 10) self.density_class.setObjectName("density_class") self.horizontalLayout_2.addWidget(self.density_class) spacerItem4 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem4) self.density_mxd = QPushButton(self.density_tab) self.density_mxd.setObjectName("density_mxd") self.horizontalLayout_2.addWidget(self.density_mxd) self.verticalLayout_2.addLayout(self.horizontalLayout_2) self.density_view = QGraphicsView(self.density_tab) self.density_view.setObjectName("density_view") self.verticalLayout_2.addWidget(self.density_view) self.verticalLayout_3.addLayout(self.verticalLayout_2) self.tabWidget.addTab(self.density_tab, "") self.day_tab = QWidget() self.day_tab.setObjectName("day_tab") self.verticalLayout_4 =QVBoxLayout(self.day_tab) self.verticalLayout_4.setObjectName("verticalLayout_4") self.verticalLayout =QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout_3 =QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.day_cell_label = QLabel(self.day_tab) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.day_cell_label.sizePolicy().hasHeightForWidth()) self.day_cell_label.setSizePolicy(sizePolicy) self.day_cell_label.setObjectName("day_cell_label") self.horizontalLayout_3.addWidget(self.day_cell_label) self.day_cell = QSpinBox(self.day_tab) self.day_cell.setProperty("value", 15) self.day_cell.setObjectName("day_cell") self.horizontalLayout_3.addWidget(self.day_cell) spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem5) self.day_class_label = QLabel(self.day_tab) self.day_class_label.setObjectName("day_class_label") self.horizontalLayout_3.addWidget(self.day_class_label) self.day_class = QSpinBox(self.day_tab) self.day_class.setProperty("value", 10) self.day_class.setObjectName("day_class") self.horizontalLayout_3.addWidget(self.day_class) spacerItem6 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem6) self.day_mxd = QPushButton(self.day_tab) self.day_mxd.setObjectName("day_mxd") self.horizontalLayout_3.addWidget(self.day_mxd) self.verticalLayout.addLayout(self.horizontalLayout_3) self.day_view = QGraphicsView(self.day_tab) self.day_view.setObjectName("day_view") self.verticalLayout.addWidget(self.day_view) self.verticalLayout_4.addLayout(self.verticalLayout) self.tabWidget.addTab(self.day_tab, "") self.verticalLayout_5.addWidget(self.tabWidget) self.horizontalLayout_4 =QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.progressBar = QProgressBar(self.layoutWidget) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth()) self.progressBar.setSizePolicy(sizePolicy) self.progressBar.setProperty("value", 0) self.progressBar.setObjectName("progressBar") self.horizontalLayout_4.addWidget(self.progressBar) self.execute_button = QPushButton(self.layoutWidget) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.execute_button.sizePolicy().hasHeightForWidth()) self.execute_button.setSizePolicy(sizePolicy) self.execute_button.setObjectName("execute_button") self.horizontalLayout_4.addWidget(self.execute_button) self.verticalLayout_5.addLayout(self.horizontalLayout_4) self.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 1040, 26)) self.menubar.setObjectName("menubar") self.file_menu = QMenu(self.menubar) self.file_menu.setObjectName("file_menu") self.help_menu = QMenu(self.menubar) self.help_menu.setObjectName("help_menu") self.setMenuBar(self.menubar) self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.action_add_data = QAction(self) self.action_add_data.setObjectName("action_add_data") self.action_help = QAction(self) self.action_help.setObjectName("action_help") self.action_about = QAction(self) self.action_about.setObjectName("action_about") self.action_save_pic = QAction(self) self.action_save_pic.setObjectName("action_save_pic") self.file_menu.addAction(self.action_add_data) self.file_menu.addAction(self.action_save_pic) self.help_menu.addAction(self.action_help) self.help_menu.addAction(self.action_about) self.menubar.addAction(self.file_menu.menuAction()) self.menubar.addAction(self.help_menu.menuAction()) self.retranslateUi() self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(self) self.center() self.show() self.target_area.activated[str].connect(self.updateTargetArea) self.datetime.dateChanged.connect(self.updateDatetime) self.density_cell.valueChanged.connect(self.updateDensityCell) self.density_class.valueChanged.connect(self.updateDensityClass) self.day_cell.valueChanged.connect(self.updateDayCell) self.day_class.valueChanged.connect(self.updateDayClass) self.action_add_data.triggered.connect(self.addData) self.action_save_pic.triggered.connect(self.savePic) self.action_about.triggered.connect(self.showAbout) self.action_help.triggered.connect(self.showHelp) self.execute_button.clicked.connect(self.execute) self.density_mxd.clicked.connect(self.openMxdDensity) self.day_mxd.clicked.connect(self.openMxdDay) self.density_mxd.setDisabled(True) self.day_mxd.setDisabled(True) self.action_save_pic.setDisabled(True)
def setup_ui(self, MainWin): # Main Window MainWin.setObjectName("MainWindow") MainWin.setWindowTitle(MainWin.tr("BDBag")) MainWin.resize(680, 600) self.centralWidget = QWidget(MainWin) self.centralWidget.setObjectName("centralWidget") MainWin.setCentralWidget(self.centralWidget) self.verticalLayout = QVBoxLayout(self.centralWidget) self.verticalLayout.setContentsMargins(11, 11, 11, 11) self.verticalLayout.setSpacing(6) self.verticalLayout.setObjectName("verticalLayout") # Actions # Create/Update self.actionCreateOrUpdate = QAction(MainWin) self.actionCreateOrUpdate.setObjectName("actionCreateOrUpdate") # Revert self.actionRevert = QAction(MainWin) self.actionRevert.setObjectName("actionRevert") self.actionRevert.setText(MainWin.tr("Revert")) self.actionRevert.setToolTip( MainWin.tr("Revert a bag directory back to a normal directory.")) self.actionRevert.setShortcut(MainWin.tr("Ctrl+R")) # Validate Fast self.actionValidateFast = QAction(MainWin) self.actionValidateFast.setObjectName("actionValidateFast") self.actionValidateFast.setText(MainWin.tr("Validate: Fast")) self.actionValidateFast.setToolTip( MainWin. tr("Perform fast validation by checking the payload file counts and sizes against the Payload-0xum " "value from the bag manifest")) self.actionValidateFast.setShortcut(MainWin.tr("Ctrl+F")) # Validate Full self.actionValidateFull = QAction(MainWin) self.actionValidateFull.setObjectName("actionValidateFull") self.actionValidateFull.setText(MainWin.tr("Validate: Full")) self.actionValidateFull.setToolTip( MainWin. tr("Perform full validation by calculating checksums for all files and comparing them against " "entries in the bag manifest(s)")) self.actionValidateFull.setShortcut(MainWin.tr("Ctrl+V")) # Fetch Missing self.actionFetchMissing = QAction(MainWin) self.actionFetchMissing.setObjectName("actionFetchMissing") self.actionFetchMissing.setText(MainWin.tr("Fetch: Missing")) self.actionFetchMissing.setToolTip( MainWin. tr("Fetch only those remote files that are not already present in the bag" )) self.actionFetchMissing.setShortcut(MainWin.tr("Ctrl+M")) # Fetch All self.actionFetchAll = QAction(MainWin) self.actionFetchAll.setObjectName("actionFetchAll") self.actionFetchAll.setText(MainWin.tr("Fetch: All")) self.actionFetchAll.setToolTip( MainWin. tr("Fetch all remote files, even if they are already present in the bag" )) self.actionFetchAll.setShortcut(MainWin.tr("Ctrl+A")) # Archive ZIP self.actionArchiveZIP = QAction(MainWin) self.actionArchiveZIP.setObjectName("actionArchiveZIP") self.actionArchiveZIP.setText(MainWin.tr("Archive: ZIP")) self.actionArchiveZIP.setToolTip( MainWin.tr("Create a ZIP format archive of the bag.")) self.actionArchiveZIP.setShortcut(MainWin.tr("Ctrl+Z")) # Archive TGZ self.actionArchiveTGZ = QAction(MainWin) self.actionArchiveTGZ.setObjectName("actionArchiveTGZ") self.actionArchiveTGZ.setText(MainWin.tr("Archive: TGZ")) self.actionArchiveTGZ.setToolTip( MainWin.tr("Create a TAR/GZIP format archive of the bag.")) self.actionArchiveTGZ.setShortcut(MainWin.tr("Ctrl+T")) # Options self.actionOptions = QAction(MainWin) self.actionOptions.setObjectName("actionOptions") self.actionOptions.setText(MainWin.tr("Options")) self.actionOptions.setToolTip(MainWin.tr("Configuration options.")) self.actionOptions.setShortcut(MainWin.tr("Ctrl+O")) # Cancel self.actionCancel = QAction(MainWin) self.actionCancel.setObjectName("actionCancel") self.actionCancel.setText(MainWin.tr("Cancel")) self.actionCancel.setToolTip( MainWin.tr("Cancel the current background task.")) self.actionCancel.setShortcut(MainWin.tr("Ctrl+C")) # About self.actionAbout = QAction(MainWin) self.actionAbout.setObjectName("actionAbout") self.actionAbout.setText(MainWin.tr("About")) self.actionAbout.setToolTip(MainWin.tr("Show version information.")) self.actionAbout.setShortcut(MainWin.tr("Ctrl+B")) # Tree View self.treeView = QTreeView(self.centralWidget) self.treeView.setObjectName("treeView") self.treeView.setStyleSheet(""" QTreeView { border: 2px solid grey; border-radius: 5px; } """) self.verticalLayout.addWidget(self.treeView) # Log Widget self.logTextBrowser = log_widget.QPlainTextEditLogger( self.centralWidget) self.logTextBrowser.widget.setObjectName("logTextBrowser") self.logTextBrowser.widget.setStyleSheet(""" QPlainTextEdit { border: 2px solid grey; border-radius: 5px; background-color: lightgray; } """) self.verticalLayout.addWidget(self.logTextBrowser.widget) # Menu Bar self.menuBar = QMenuBar(MainWin) self.menuBar.setObjectName("menuBar") MainWin.setMenuBar(self.menuBar) # Bag Menu self.menuBag = QMenu(self.menuBar) self.menuBag.setObjectName("menuBag") self.menuBag.setTitle(MainWin.tr("Bag")) self.menuBar.addAction(self.menuBag.menuAction()) self.menuBag.addAction(self.actionCreateOrUpdate) self.menuBag.addAction(self.actionRevert) self.menuBag.addAction(self.actionCancel) self.menuBag.addAction(self.actionOptions) # Fetch Menu self.menuFetch = QMenu(self.menuBag) self.menuFetch.setObjectName("menuFetch") self.menuFetch.setTitle(MainWin.tr("Fetch")) self.menuFetch.addAction(self.actionFetchMissing) self.menuFetch.addAction(self.actionFetchAll) self.menuBag.addAction(self.menuFetch.menuAction()) # Validate Menu self.menuValidate = QMenu(self.menuBag) self.menuValidate.setObjectName("menuValidate") self.menuValidate.setTitle(MainWin.tr("Validate")) self.menuValidate.addAction(self.actionValidateFast) self.menuValidate.addAction(self.actionValidateFull) self.menuBag.addAction(self.menuValidate.menuAction()) # Archive Menu self.menuArchive = QMenu(self.menuBag) self.menuArchive.setObjectName("menuArchive") self.menuArchive.setTitle(MainWin.tr("Archive")) self.menuArchive.addAction(self.actionArchiveZIP) self.menuArchive.addAction(self.actionArchiveTGZ) self.menuBag.addAction(self.menuArchive.menuAction()) # Help Menu self.menuHelp = QMenu(self.menuBar) self.menuHelp.setObjectName("menuHelp") self.menuHelp.setTitle(MainWin.tr("Help")) self.menuHelp.addAction(self.actionAbout) self.menuBar.addAction(self.menuHelp.menuAction()) # Tool Bar self.mainToolBar = QToolBar(MainWin) self.mainToolBar.setObjectName("mainToolBar") self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) MainWin.addToolBar(Qt.TopToolBarArea, self.mainToolBar) # Create/Update self.mainToolBar.addAction(self.actionCreateOrUpdate) self.actionCreateOrUpdate.setIcon( self.actionCreateOrUpdate.parentWidget().style().standardIcon( getattr(QStyle, "SP_FileDialogNewFolder"))) # Revert self.mainToolBar.addAction(self.actionRevert) self.actionRevert.setIcon( self.actionRevert.parentWidget().style().standardIcon( getattr(QStyle, "SP_DialogOkButton"))) # Fetch self.mainToolBar.addAction(self.actionFetchMissing) self.actionFetchMissing.setIcon( self.actionFetchMissing.parentWidget().style().standardIcon( getattr(QStyle, "SP_ArrowDown"))) self.mainToolBar.addAction(self.actionFetchAll) self.actionFetchAll.setIcon( self.actionFetchAll.parentWidget().style().standardIcon( getattr(QStyle, "SP_ArrowDown"))) # Validate self.mainToolBar.addAction(self.actionValidateFast) self.actionValidateFast.setIcon( self.actionValidateFast.parentWidget().style().standardIcon( getattr(QStyle, "SP_DialogApplyButton"))) self.mainToolBar.addAction(self.actionValidateFull) self.actionValidateFull.setIcon( self.actionValidateFull.parentWidget().style().standardIcon( getattr(QStyle, "SP_DialogApplyButton"))) # Archive self.mainToolBar.addAction(self.actionArchiveZIP) self.actionArchiveZIP.setIcon( self.actionArchiveZIP.parentWidget().style().standardIcon( getattr(QStyle, "SP_DialogSaveButton"))) self.mainToolBar.addAction(self.actionArchiveTGZ) self.actionArchiveTGZ.setIcon( self.actionArchiveTGZ.parentWidget().style().standardIcon( getattr(QStyle, "SP_DialogSaveButton"))) # Options self.mainToolBar.addAction(self.actionOptions) self.actionOptions.setIcon( self.actionOptions.parentWidget().style().standardIcon( getattr(QStyle, "SP_FileDialogDetailedView"))) # Cancel self.mainToolBar.addAction(self.actionCancel) self.actionCancel.setIcon( self.actionCancel.parentWidget().style().standardIcon( getattr(QStyle, "SP_BrowserStop"))) # Status Bar self.statusBar = QStatusBar(MainWin) self.statusBar.setToolTip("") self.statusBar.setStatusTip("") self.statusBar.setObjectName("statusBar") MainWin.setStatusBar(self.statusBar) # Progress Bar self.progressBar = QProgressBar(self.centralWidget) self.progressBar.setValue(0) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") self.progressBar.setStyleSheet(""" QProgressBar { border: 2px solid grey; border-radius: 5px; text-align: center; } QProgressBar::chunk { background-color: darkblue; width: 10px; margin: 0.5px; } """) self.verticalLayout.addWidget(self.progressBar) # finalize UI setup self.toggleCreateOrUpdate(MainWin) QMetaObject.connectSlotsByName(MainWin)
def __init__(self, persepolis_setting): super().__init__() # MainWindow self.persepolis_setting = persepolis_setting # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", "Persepolis Download Manager")) self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) # enable drag and drop self.setAcceptDrops(True) # frame self.frame = QFrame(self.centralwidget) # download_table_horizontalLayout download_table_horizontalLayout = QHBoxLayout() tabels_splitter = QSplitter(Qt.Horizontal) # category_tree self.category_tree_qwidget = QWidget(self) category_tree_verticalLayout = QVBoxLayout() self.category_tree = CategoryTreeView(self) category_tree_verticalLayout.addWidget(self.category_tree) self.category_tree_model = QStandardItemModel() self.category_tree.setModel(self.category_tree_model) category_table_header = [QCoreApplication.translate("mainwindow_ui_tr", 'Category')] self.category_tree_model.setHorizontalHeaderLabels( category_table_header) self.category_tree.header().setStretchLastSection(True) self.category_tree.header().setDefaultAlignment(Qt.AlignCenter) # queue_panel self.queue_panel_widget = QWidget(self) queue_panel_verticalLayout_main = QVBoxLayout(self.queue_panel_widget) # queue_panel_show_button self.queue_panel_show_button = QPushButton(self) queue_panel_verticalLayout_main.addWidget(self.queue_panel_show_button) # queue_panel_widget_frame self.queue_panel_widget_frame = QFrame(self) self.queue_panel_widget_frame.setFrameShape(QFrame.StyledPanel) self.queue_panel_widget_frame.setFrameShadow(QFrame.Raised) queue_panel_verticalLayout_main.addWidget( self.queue_panel_widget_frame) queue_panel_verticalLayout = QVBoxLayout(self.queue_panel_widget_frame) queue_panel_verticalLayout_main.setContentsMargins(50, -1, 50, -1) # start_end_frame self.start_end_frame = QFrame(self) # start time start_verticalLayout = QVBoxLayout(self.start_end_frame) self.start_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) start_frame_verticalLayout = QVBoxLayout(self.start_frame) self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame) self.start_time_qDataTimeEdit.setDisplayFormat('H:mm') start_frame_verticalLayout.addWidget(self.start_time_qDataTimeEdit) start_verticalLayout.addWidget(self.start_frame) # end time self.end_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) end_frame_verticalLayout = QVBoxLayout(self.end_frame) self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame) self.end_time_qDateTimeEdit.setDisplayFormat('H:mm') end_frame_verticalLayout.addWidget(self.end_time_qDateTimeEdit) start_verticalLayout.addWidget(self.end_frame) self.reverse_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.reverse_checkBox) queue_panel_verticalLayout.addWidget(self.start_end_frame) # limit_after_frame self.limit_after_frame = QFrame(self) # limit_checkBox limit_verticalLayout = QVBoxLayout(self.limit_after_frame) self.limit_checkBox = QCheckBox(self) limit_verticalLayout.addWidget(self.limit_checkBox) # limit_frame self.limit_frame = QFrame(self) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) limit_verticalLayout.addWidget(self.limit_frame) limit_frame_verticalLayout = QVBoxLayout(self.limit_frame) # limit_spinBox limit_frame_horizontalLayout = QHBoxLayout() self.limit_spinBox = QDoubleSpinBox(self) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) limit_frame_horizontalLayout.addWidget(self.limit_spinBox) # limit_comboBox self.limit_comboBox = QComboBox(self) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") limit_frame_horizontalLayout.addWidget(self.limit_comboBox) limit_frame_verticalLayout.addLayout(limit_frame_horizontalLayout) # limit_pushButton self.limit_pushButton = QPushButton(self) limit_frame_verticalLayout.addWidget(self.limit_pushButton) # after_checkBox self.after_checkBox = QtWidgets.QCheckBox(self) limit_verticalLayout.addWidget(self.after_checkBox) # after_frame self.after_frame = QtWidgets.QFrame(self) self.after_frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.after_frame.setFrameShadow(QtWidgets.QFrame.Raised) limit_verticalLayout.addWidget(self.after_frame) after_frame_verticalLayout = QVBoxLayout(self.after_frame) # after_comboBox self.after_comboBox = QComboBox(self) self.after_comboBox.addItem("") after_frame_verticalLayout.addWidget(self.after_comboBox) # after_pushButton self.after_pushButton = QPushButton(self) after_frame_verticalLayout.addWidget(self.after_pushButton) queue_panel_verticalLayout.addWidget(self.limit_after_frame) category_tree_verticalLayout.addWidget(self.queue_panel_widget) # keep_awake_checkBox self.keep_awake_checkBox = QCheckBox(self) queue_panel_verticalLayout.addWidget(self.keep_awake_checkBox) self.category_tree_qwidget.setLayout(category_tree_verticalLayout) tabels_splitter.addWidget(self.category_tree_qwidget) # download table widget self.download_table_content_widget = QWidget(self) download_table_content_widget_verticalLayout = QVBoxLayout( self.download_table_content_widget) self.download_table = DownloadTableWidget(self) download_table_content_widget_verticalLayout.addWidget( self.download_table) tabels_splitter.addWidget(self.download_table_content_widget) self.download_table.setColumnCount(13) self.download_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.download_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.download_table.verticalHeader().hide() # hide gid and download dictioanry section self.download_table.setColumnHidden(8, True) self.download_table.setColumnHidden(9, True) download_table_header = [QCoreApplication.translate("mainwindow_ui_tr", 'File Name'), QCoreApplication.translate("mainwindow_ui_tr",'Status'), QCoreApplication.translate("mainwindow_ui_tr", 'Size'), QCoreApplication.translate("mainwindow_ui_tr", 'Downloaded'), QCoreApplication.translate("mainwindow_ui_tr", 'Percentage'), QCoreApplication.translate("mainwindow_ui_tr", 'Connections'), QCoreApplication.translate("mainwindow_ui_tr", 'Transfer rate'), QCoreApplication.translate("mainwindow_ui_tr",'Estimated time left'), 'Gid', QCoreApplication.translate("mainwindow_ui_tr",'Link'), QCoreApplication.translate("mainwindow_ui_tr", 'First try date'), QCoreApplication.translate("mainwindow_ui_tr", 'Last try date'), QCoreApplication.translate("mainwindow_ui_tr",'Category')] self.download_table.setHorizontalHeaderLabels(download_table_header) # fixing the size of download_table when window is Maximized! self.download_table.horizontalHeader().setSectionResizeMode(0) self.download_table.horizontalHeader().setStretchLastSection(True) tabels_splitter.setStretchFactor(0, 3) # category_tree width tabels_splitter.setStretchFactor(1, 10) # ratio of tables's width download_table_horizontalLayout.addWidget(tabels_splitter) self.frame.setLayout(download_table_horizontalLayout) self.verticalLayout.addWidget(self.frame) self.setCentralWidget(self.centralwidget) # menubar self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 600, 24)) self.setMenuBar(self.menubar) fileMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&File')) editMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Edit')) viewMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&View')) downloadMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Download')) queueMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Queue')) videoFinderMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", 'V&ideo Finder')) helpMenu = self.menubar.addMenu(QCoreApplication.translate("mainwindow_ui_tr", '&Help')) # viewMenu submenus sortMenu = viewMenu.addMenu(QCoreApplication.translate("mainwindow_ui_tr", 'Sort by')) # statusbar self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.statusbar.showMessage(QCoreApplication.translate("mainwindow_ui_tr", "Persepolis Download Manager")) # toolBar self.toolBar2 = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar2) self.toolBar2.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", 'Menu')) self.toolBar2.setFloatable(False) self.toolBar2.setMovable(False) self.toolBar = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.toolBar.setWindowTitle(QCoreApplication.translate("mainwindow_ui_tr", 'Toolbar')) self.toolBar.setFloatable(False) self.toolBar.setMovable(False) #toolBar and menubar and actions self.videoFinderAddLinkAction = QAction(QIcon(icons + 'video_finder'), QCoreApplication.translate("mainwindow_ui_tr", 'Find Video Links'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Download video or audio from Youtube, Vimeo, etc...'), triggered=self.showVideoFinderAddLinkWindow) QShortcut(QKeySequence('Ctrl+I'), self, self.showVideoFinderAddLinkWindow) videoFinderMenu.addAction(self.videoFinderAddLinkAction) self.stopAllAction = QAction(QIcon(icons + 'stop_all'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop all active downloads'), self, statusTip='Stop all active downloads', triggered=self.stopAllDownloads) downloadMenu.addAction(self.stopAllAction) self.sort_file_name_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'File name'), self, triggered=self.sortByName) sortMenu.addAction(self.sort_file_name_Action) self.sort_file_size_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'File size'), self, triggered=self.sortBySize) sortMenu.addAction(self.sort_file_size_Action) self.sort_first_try_date_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'First try date'), self, triggered=self.sortByFirstTry) sortMenu.addAction(self.sort_first_try_date_Action) self.sort_last_try_date_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Last try date'), self, triggered=self.sortByLastTry) sortMenu.addAction(self.sort_last_try_date_Action) self.sort_download_status_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Download status'), self, triggered=self.sortByStatus) sortMenu.addAction(self.sort_download_status_Action) self.trayAction = QAction(QCoreApplication.translate("mainwindow_ui_tr", 'Show system tray icon'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Show/Hide system tray icon"), triggered=self.showTray) self.trayAction.setCheckable(True) viewMenu.addAction(self.trayAction) self.showMenuBarAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'), triggered=self.showMenuBar) self.showMenuBarAction.setCheckable(True) viewMenu.addAction(self.showMenuBarAction) self.showSidePanelAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'), triggered=self.showSidePanel) self.showSidePanelAction.setCheckable(True) viewMenu.addAction(self.showSidePanelAction) self.minimizeAction = QAction(QIcon(icons + 'minimize'), QCoreApplication.translate("mainwindow_ui_tr", 'Minimize to system tray'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Minimize to system tray"), triggered=self.minMaxTray) QShortcut(QKeySequence('Ctrl+W'), self, self.minMaxTray) viewMenu.addAction(self.minimizeAction) self.addlinkAction = QAction(QIcon(icons + 'add'), QCoreApplication.translate("mainwindow_ui_tr", 'Add New Download Link'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Add New Download Link"), triggered=self.addLinkButtonPressed) QShortcut(QKeySequence('Ctrl+N'), self, self.addLinkButtonPressed) fileMenu.addAction(self.addlinkAction) self.addtextfileAction = QAction(QIcon(icons + 'file'), QCoreApplication.translate("mainwindow_ui_tr", 'Import links from text file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Create a Text file and put links in it.line by line!'), triggered=self.importText) fileMenu.addAction(self.addtextfileAction) self.resumeAction = QAction(QIcon(icons + 'play'), QCoreApplication.translate("mainwindow_ui_tr", 'Resume Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Resume Download"), triggered=self.resumeButtonPressed) QShortcut(QKeySequence('Ctrl+R'), self, self.resumeButtonPressed) downloadMenu.addAction(self.resumeAction) self.pauseAction = QAction(QIcon(icons + 'pause'), QCoreApplication.translate("mainwindow_ui_tr", 'Pause Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Pause Download"), triggered=self.pauseButtonPressed) QShortcut(QKeySequence('Ctrl+C'), self, self.pauseButtonPressed) downloadMenu.addAction(self.pauseAction) self.stopAction = QAction(QIcon(icons + 'stop'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Stop/Cancel Download"), triggered=self.stopButtonPressed) QShortcut(QKeySequence('Ctrl+S'), self, self.stopButtonPressed) downloadMenu.addAction(self.stopAction) self.propertiesAction = QAction(QIcon(icons + 'setting'), QCoreApplication.translate("mainwindow_ui_tr", 'Properties'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Properties"), triggered=self.propertiesButtonPressed) QShortcut(QKeySequence('Ctrl+P'), self, self.propertiesButtonPressed) downloadMenu.addAction(self.propertiesAction) self.progressAction = QAction(QIcon(icons + 'window'), QCoreApplication.translate("mainwindow_ui_tr", 'Progress'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Progress"), triggered=self.progressButtonPressed) QShortcut(QKeySequence('Ctrl+Z'), self, self.progressButtonPressed) downloadMenu.addAction(self.progressAction) self.openFileAction = QAction(QIcon( icons + 'file'), QCoreApplication.translate("mainwindow_ui_tr", 'Open file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open file'), triggered=self.openFile) fileMenu.addAction(self.openFileAction) self.openDownloadFolderAction = QAction(QIcon( icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'Open download folder'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open download folder'), triggered=self.openDownloadFolder) fileMenu.addAction(self.openDownloadFolderAction) self.openDefaultDownloadFolderAction = QAction(QIcon( icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'Open default download folder'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open default download folder'), triggered=self.openDefaultDownloadFolder) fileMenu.addAction(self.openDefaultDownloadFolderAction) self.exitAction = QAction(QIcon(icons + 'exit'), QCoreApplication.translate("mainwindow_ui_tr", 'Exit'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Exit"), triggered=self.closeEvent) QShortcut(QKeySequence('Ctrl+Q'), self, self.closeEvent) fileMenu.addAction(self.exitAction) self.clearAction = QAction(QIcon(icons + 'multi_remove'), QCoreApplication.translate("mainwindow_ui_tr", 'Clear download list'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Clear all items in download list'), triggered=self.clearDownloadList) editMenu.addAction(self.clearAction) self.removeSelectedAction = QAction(QIcon(icons + 'remove'), QCoreApplication.translate("mainwindow_ui_tr", 'Remove selected downloads from list'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Remove selected downloads form list'), triggered=self.removeSelected) editMenu.addAction(self.removeSelectedAction) self.removeSelectedAction.setEnabled(False) self.deleteSelectedAction = QAction(QIcon(icons + 'trash'), QCoreApplication.translate("mainwindow_ui_tr", 'Delete selected download files'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Delete selected download files'), triggered=self.deleteSelected) editMenu.addAction(self.deleteSelectedAction) self.deleteSelectedAction.setEnabled(False) self.createQueueAction = QAction(QIcon(icons + 'add_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Create new queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Create new download queue'), triggered=self.createQueue) queueMenu.addAction(self.createQueueAction) self.removeQueueAction = QAction(QIcon(icons + 'remove_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Remove this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Remove this queue'), triggered=self.removeQueue) queueMenu.addAction(self.removeQueueAction) self.startQueueAction = QAction(QIcon( icons + 'start_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'), triggered=self.startQueue) queueMenu.addAction(self.startQueueAction) self.stopQueueAction = QAction(QIcon( icons + 'stop_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'), triggered=self.stopQueue) queueMenu.addAction(self.stopQueueAction) self.moveUpSelectedAction = QAction(QIcon(icons + 'multi_up'), QCoreApplication.translate("mainwindow_ui_tr", 'Move up selected items'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Move currently selected items up by one row'), triggered=self.moveUpSelected) queueMenu.addAction(self.moveUpSelectedAction) self.moveDownSelectedAction = QAction(QIcon(icons + 'multi_down'), QCoreApplication.translate("mainwindow_ui_tr", 'Move down selected items'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Move currently selected items down by one row'), triggered=self.moveDownSelected) queueMenu.addAction(self.moveDownSelectedAction) self.preferencesAction = QAction(QIcon(icons + 'preferences'), QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'), triggered=self.openPreferences, menuRole=5) editMenu.addAction(self.preferencesAction) self.aboutAction = QAction(QIcon( icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'About'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'About'), triggered=self.openAbout, menuRole=4) helpMenu.addAction(self.aboutAction) self.issueAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'), triggered=self.reportIssue) helpMenu.addAction(self.issueAction) self.updateAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Check for newer version'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Check for newer release'), triggered=self.newUpdate) helpMenu.addAction(self.updateAction) self.logAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Show log file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'), triggered=self.showLog) helpMenu.addAction(self.logAction) self.helpAction = QAction(QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Help'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'), triggered=self.persepolisHelp) helpMenu.addAction(self.helpAction) self.qmenu = MenuWidget(self) self.toolBar2.addWidget(self.qmenu) # labels self.queue_panel_show_button.setText(QCoreApplication.translate("mainwindow_ui_tr", "Hide options")) self.start_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Start Time")) self.end_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "End Time")) self.reverse_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Download bottom of\n the list first")) self.limit_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Limit Speed")) self.limit_comboBox.setItemText(0, "KiB/s") self.limit_comboBox.setItemText(1, "MiB/s") self.limit_pushButton.setText(QCoreApplication.translate("mainwindow_ui_tr", "Apply")) self.after_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "After download")) self.after_comboBox.setItemText(0, QCoreApplication.translate("mainwindow_ui_tr", "Shut Down")) self.keep_awake_checkBox.setText(QCoreApplication.translate("mainwindow_ui_tr", "Keep system awake!")) self.keep_awake_checkBox.setToolTip( QCoreApplication.translate("mainwindow_ui_tr", "<html><head/><body><p>This option is preventing system from going to sleep.\ This is necessary if your power manager is suspending system automatically. </p></body></html>")) self.after_pushButton.setText(QCoreApplication.translate("mainwindow_ui_tr", "Apply"))
def __init__(self): super().__init__() self.resize(settings().value("MainWindow/size") or QSize(1280, 720)) self.setWindowTitle("untitled") if int(settings().value("MainWindow/maximized") or 0): self.showMaximized() self.setCentralWidget(QWidget()) self.setMenuBar(QMenuBar()) self.setStatusBar(QStatusBar()) self.centralWidget().setLayout(QHBoxLayout()) self.centralWidget().layout().setSpacing(0) self.centralWidget().layout().setContentsMargins(0, 0, 0, 0) self.splitter = QSplitter() self.centralWidget().layout().addWidget(self.splitter) self.projectTree = ProjectTree(self) # self.projectTree.hide() self.splitter.addWidget(self.projectTree) self.tabwidget = TabWidget(self) self.splitter.addWidget(self.tabwidget) self.splitter.setSizes((int(settings().value("Sizes/splitter0") or self.splitter.sizeHint().width() * .2), int(settings().value("Sizes/splitter1") or self.splitter.sizeHint().width() * .8))) #menüler self.fileMenu = QMenu(self.tr("File")) self.newFileActionMenu = QMenu(self.tr("New")) self.newPlainFileAction = QAction(self.tr("File"), icon=QIcon(":/img/text-plain.svg")) self.newFileActionMenu.addAction(self.newPlainFileAction) self.newPythonFileAction = QAction(self.tr("Python File"), icon=QIcon(":/img/text-python.svg")) self.newFileActionMenu.addAction(self.newPythonFileAction) self.newDirectoryAction = QAction(self.tr("Directory"), icon=QIcon(":/img/folder.svg")) self.newFileActionMenu.addAction(self.newDirectoryAction) self.newPythonPackageAction = QAction( self.tr("Python Package"), icon=QIcon(":/img/folder-python.svg")) self.newFileActionMenu.addAction(self.newPythonPackageAction) self.newFileActionMenu.addSeparator() self.newHtmlFileAction = QAction(self.tr("Html File"), icon=QIcon(":/img/text-html.svg")) self.newFileActionMenu.addAction(self.newHtmlFileAction) self.newCssFileAction = QAction(self.tr("Css File"), icon=QIcon(":/img/text-css.svg")) self.newFileActionMenu.addAction(self.newCssFileAction) self.newJsFileAction = QAction(self.tr("JavaScript File"), icon=QIcon(":/img/text-javascript.svg")) self.newFileActionMenu.addAction(self.newJsFileAction) self.newJsonFileAction = QAction(self.tr("Json File"), icon=QIcon(":/img/text-plain.svg")) self.newFileActionMenu.addAction(self.newJsonFileAction) self.newXmlFileAction = QAction(self.tr("Xml File"), icon=QIcon(":/img/text-xml.svg")) self.newFileActionMenu.addAction(self.newXmlFileAction) self.newYamlFileAction = QAction(self.tr("Yaml File"), icon=QIcon(":/img/text-plain.svg")) self.newFileActionMenu.addAction(self.newYamlFileAction) self.newSqlFileAction = QAction(self.tr("Sqlite File"), icon=QIcon(":/img/text-sql.svg")) self.newFileActionMenu.addAction(self.newSqlFileAction) self.newMdFileAction = QAction(self.tr("Markdown File"), icon=QIcon(":/img/text-plain.svg")) self.newFileActionMenu.addAction(self.newMdFileAction) self.fileMenu.addMenu(self.newFileActionMenu) self.newProjectAction = QAction(self.tr("New Project")) self.fileMenu.addAction(self.newProjectAction) self.openFileAction = QAction(self.tr("Open File...")) self.openFileAction.setShortcut("Ctrl+O") self.fileMenu.addAction(self.openFileAction) self.openProjectAction = QAction(self.tr("Open Project...")) self.openProjectAction.setShortcut("Ctrl+Alt+O") self.fileMenu.addAction(self.openProjectAction) self.openRecentFileActionMenu = QMenu(self.tr("Open Recent...")) self.fileMenu.addMenu(self.openRecentFileActionMenu) self.saveFileAction = QAction(self.tr("Save")) self.saveFileAction.setShortcut("Ctrl+S") self.fileMenu.addAction(self.saveFileAction) self.saveAsAction = QAction(self.tr("Save As...")) self.saveAsAction.setShortcut("Ctrl+Alt+S") self.fileMenu.addAction(self.saveAsAction) self.fileMenu.addSeparator() self.closeFileAction = QAction(self.tr("Close File")) self.closeFileAction.setShortcut("Ctrl+W") self.fileMenu.addAction(self.closeFileAction) self.closeAllFilesAction = QAction(self.tr("Close All File")) self.fileMenu.addAction(self.closeAllFilesAction) self.fileMenu.addSeparator() self.exitAction = QAction(self.tr("Exit")) self.exitAction.setShortcut("Ctrl+Q") self.fileMenu.addAction(self.exitAction) self.menuBar().addMenu(self.fileMenu) self.editMenu = QMenu(self.tr("Edit")) self.undoAction = QAction(self.tr("Undo")) self.undoAction.setShortcut("Ctrl+Z") self.undoAction.setShortcutVisibleInContextMenu(True) self.editMenu.addAction(self.undoAction) self.redoAction = QAction(self.tr("Redo")) self.redoAction.setShortcut("Ctrl+Y") self.redoAction.setShortcutVisibleInContextMenu(True) self.editMenu.addAction(self.redoAction) self.editMenu.addSeparator() self.copyAction = QAction(self.tr("Copy")) self.copyAction.setShortcutVisibleInContextMenu(True) self.copyAction.setShortcut("Ctrl+C") self.editMenu.addAction(self.copyAction) self.cutAction = QAction(self.tr("Cut")) self.cutAction.setShortcut("Ctrl+X") self.cutAction.setShortcutVisibleInContextMenu(True) self.editMenu.addAction(self.cutAction) self.pasteAction = QAction(self.tr("Paste")) self.pasteAction.setShortcut("Ctrl+V") self.pasteAction.setShortcutVisibleInContextMenu(True) self.editMenu.addAction(self.pasteAction) self.editMenu.addSeparator() # self.wrapActionMenu = QMenu(self.tr("Wrap")) # self.editMenu.addMenu(self.wrapActionMenu) self.menuBar().addMenu(self.editMenu) self.findMenu = QMenu(self.tr("Find")) self.findAction = QAction(self.tr("Find...")) self.findAction.setShortcut("Ctrl+F") self.findMenu.addAction(self.findAction) self.findNextAction = QAction(self.tr("Find Next")) self.findNextAction.setShortcut("F3") self.findMenu.addAction(self.findNextAction) self.findPreviousAction = QAction(self.tr("Find Previous")) self.findPreviousAction.setShortcut("Shift+F3") self.findMenu.addAction(self.findPreviousAction) self.findMenu.addSeparator() self.replaceAction = QAction(self.tr("Replace")) self.replaceAction.setShortcut("Ctrl+H") self.findMenu.addAction(self.replaceAction) self.replaceNextAction = QAction(self.tr("Replace Next")) self.replaceNextAction.setShortcut("Ctrl+Shift+H") self.findMenu.addAction(self.replaceNextAction) self.menuBar().addMenu(self.findMenu) # self.viewMenu = QMenu(self.tr("View")) # self.layoutActionMenu = QMenu(self.tr("Layout")) # self.viewMenu.addMenu(self.layoutActionMenu) # self.groupsActionMenu = QMenu(self.tr("Groups")) # self.viewMenu.addMenu(self.groupsActionMenu) # self.focusGroupActionMenu = QMenu(self.tr("Focus Group")) # self.viewMenu.addMenu(self.focusGroupActionMenu) # self.moveFileGroupActionMenu = QMenu(self.tr("Move File to Group")) # self.viewMenu.addMenu(self.moveFileGroupActionMenu) # self.viewMenu.addSeparator() # self.syntaxActionMenu = QMenu(self.tr("Syntax")) # self.viewMenu.addMenu(self.syntaxActionMenu) # self.indentationActionMenu = QMenu(self.tr("Indentation")) # self.viewMenu.addMenu(self.indentationActionMenu) # self.lineEndingsActionMenu = QMenu(self.tr("Line Endings")) # self.viewMenu.addMenu(self.lineEndingsActionMenu) # self.viewMenu.addSeparator() # self.menuBar().addMenu(self.viewMenu) self.toolsMenu = QMenu(self.tr("Tools")) self.snippetsAction = QAction(self.tr("Snippets...")) self.toolsMenu.addAction(self.snippetsAction) self.toolsMenu.addSeparator() self.runAction = QAction(self.tr("Run")) self.runAction.setShortcut("F5") self.toolsMenu.addAction(self.runAction) self.runWithAction = QAction(self.tr("Run With...")) self.runWithAction.setShortcut("F6") self.toolsMenu.addAction(self.runWithAction) self.toolsMenu.addSeparator() self.recordMacroAction = QAction(self.tr("Record Macro")) self.toolsMenu.addAction(self.recordMacroAction) self.playbackMacroAction = QAction(self.tr("Playback Macro")) self.toolsMenu.addAction(self.playbackMacroAction) self.saveMacroAction = QAction(self.tr("Save Macro...")) self.toolsMenu.addAction(self.saveMacroAction) self.macrosActionMenu = QMenu(self.tr("Macros")) self.toolsMenu.addMenu(self.macrosActionMenu) self.menuBar().addMenu(self.toolsMenu) self.helpMenu = QMenu(self.tr("Help")) self.documentationAction = QAction(self.tr("Documentation")) self.helpMenu.addAction(self.documentationAction) self.donateAction = QAction(self.tr("Donate")) self.helpMenu.addAction(self.donateAction) self.helpMenu.addSeparator() self.checkAction = QAction(self.tr("Check for Updates...")) self.helpMenu.addAction(self.checkAction) self.changelogAction = QAction(self.tr("Changelog...")) self.helpMenu.addAction(self.changelogAction) self.aboutAction = QAction(self.tr("About Untitled Editor")) self.helpMenu.addAction(self.aboutAction) self.menuBar().addMenu(self.helpMenu)
class InteractivePlotter(QMainWindow): '''main class for this tool''' def __init__(self, parent=None): super(InteractivePlotter, self).__init__(parent) self.showMaximized() self.setWindowTitle("SummaryExplorer") QApplication.processEvents() self.plot_fame = FigFrame(self) self.layout = QtWidgets.QVBoxLayout() self.layout.addWidget(self.plot_fame) self.setLayout(self.layout) self.setCentralWidget(self.plot_fame) self.showMaximized() self.raw_path = '' mainMenu = self.menuBar() fileMenu = mainMenu.addMenu('File') imageMenu = mainMenu.addMenu('Images') loadButton = QAction('Load', self) loadButton.setStatusTip('Load data') loadButton.setShortcut("Ctrl+o") loadButton.triggered.connect(self.callLoadData) fileMenu.addAction(loadButton) self.saveButton = QAction('Save', self) self.saveButton.setStatusTip('Save PSD data to xls') self.saveButton.setShortcut("Ctrl+s") self.saveButton.triggered.connect(self.plot_fame.graph_view.save_data) fileMenu.addAction(self.saveButton) self.saveButton.setEnabled(False) avwinButton = QAction('Average window', self) avwinButton.setStatusTip('Change the average window') avwinButton.setShortcut("Ctrl+w") avwinButton.triggered.connect(self.modify_av_wind) fileMenu.addAction(avwinButton) exitButton = QAction('Exit', self) exitButton.setStatusTip('Close') exitButton.triggered.connect(self.close) fileMenu.addAction(exitButton) self.rawButton = QAction('Raw Image', self) self.rawButton.setShortcut("r") self.rawButton.triggered.connect(self.find_raw_data) imageMenu.addAction(self.rawButton) self.rawButton.setEnabled(False) self.imcButton = QAction('Corrected Image', self) self.imcButton.setShortcut("c") self.imcButton.triggered.connect(self.find_imc_data) imageMenu.addAction(self.imcButton) self.imcButton.setEnabled(False) self.toggleButton = QAction('Toggle plot p', self) self.toggleButton.setShortcut("p") self.toggleButton.triggered.connect( self.plot_fame.graph_view.toggle_plot) self.toggleButton.setEnabled(False) mainMenu.addAction(self.toggleButton) self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) self.statusBar.showMessage('Hello. Load a -STATS.csv file to start', 1e12) def callLoadData(self): self.statusBar.showMessage('Loading data. PLEASE WAIT', 1e12) self.plot_fame.graph_view.load_data() self.raw_path = '' self.raw_files = '' self.saveButton.setEnabled(True) self.rawButton.setEnabled(True) self.imcButton.setEnabled(True) self.toggleButton.setEnabled(True) self.statusBar.clearMessage() self.setWindowTitle("SummaryExplorer: " + self.plot_fame.graph_view.stats_filename) def keyPressEvent(self, event): pressedkey = event.key() if (pressedkey == QtCore.Qt.Key_Up) or (pressedkey == QtCore.Qt.Key_W): self.plot_fame.graph_view.av_window += pd.Timedelta(seconds=1) self.plot_fame.graph_view.update_plot() event.accept() elif (pressedkey == QtCore.Qt.Key_Right) or (pressedkey == QtCore.Qt.Key_D): self.plot_fame.graph_view.mid_time += pd.Timedelta(seconds=1) self.plot_fame.graph_view.update_plot() event.accept() elif (pressedkey == QtCore.Qt.Key_Down) or (pressedkey == QtCore.Qt.Key_S): self.plot_fame.graph_view.av_window -= pd.Timedelta(seconds=1) self.plot_fame.graph_view.av_window = max( pd.Timedelta(seconds=1), self.plot_fame.graph_view.av_window) self.plot_fame.graph_view.update_plot() event.accept() elif (pressedkey == QtCore.Qt.Key_Left) or (pressedkey == QtCore.Qt.Key_A): self.plot_fame.graph_view.mid_time -= pd.Timedelta(seconds=1) self.plot_fame.graph_view.av_window = max( pd.Timedelta(seconds=1), self.plot_fame.graph_view.av_window) self.plot_fame.graph_view.update_plot() event.accept() else: event.ignore() def find_imc_data(self): self.extract_filename() if len(self.raw_files) == 0: return bg_window = pd.to_timedelta(5, unit='S') start_time = self.plot_fame.graph_view.mid_time - bg_window / 2 end_time = self.plot_fame.graph_view.mid_time + bg_window / 2 u = pd.to_datetime(self.plot_fame.graph_view.u) midtimeidx = np.argwhere((u >= start_time) & (u < end_time)) ws = waitsplash() self.statusBar.showMessage( 'Creating background from ' + str(len(midtimeidx)) + ' images', 1e12) imbg = np.float64(silcam_load(self.raw_files[midtimeidx[0][0]])) for i in range(len(midtimeidx) - 1): imbg += np.float64( silcam_load(self.raw_files[midtimeidx[i + 1][0]])) imbg /= len(midtimeidx) imraw = np.float64(silcam_load(self.filename)) imc = correct_im_fast(imbg, imraw) self.statusBar.showMessage('Background done.', 1e12) ws.close() self.plot_image(imc) def find_raw_data(self): self.extract_filename() if len(self.raw_files) == 0: return img = silcam_load(self.filename) self.plot_image(img) def extract_filename(self): if self.raw_path == '': self.raw_path = QFileDialog.getExistingDirectory( self, caption='Where are the raw data?', directory=self.raw_path) self.raw_files = sorted(glob(os.path.join(self.raw_path, '*.silc'))) if len(self.raw_files) == 0: self.raw_files = sorted( glob(os.path.join(self.raw_path, '*.bmp'))) if len(self.raw_files) == 0: self.statusBar.showMessage('No data here: ' + self.raw_path, 1e12) self.raw_path = '' return midtimeidx = np.argwhere( self.plot_fame.graph_view.u > self.plot_fame.graph_view.mid_time )[0] search_time = self.plot_fame.graph_view.u[midtimeidx].to_pydatetime( )[0] print('search_time', search_time) estimate_filename = os.path.join( self.raw_path, search_time.strftime('D%Y%m%dT%H%M%S.*.*')) filename = glob(estimate_filename) if len(filename) == 0: print('can' 't find this:', estimate_filename) return self.filename = filename[0] def plot_image(self, img): cv = FigureCanvas(plt.figure(figsize=(5, 3))) cv.setWindowTitle(self.filename) plt.imshow(img) plt.title(self.filename) plt.gca().axis('off') cv.show() def modify_av_wind(self): '''allow the user to modify the averaging period of interest''' window_seconds = self.plot_fame.graph_view.av_window.seconds input_value, okPressed = QInputDialog.getInt(self, "Get integer", "Average window:", window_seconds, 0, 60 * 60, 1) if okPressed: self.plot_fame.graph_view.av_window = pd.Timedelta( seconds=input_value) if not self.plot_fame.graph_view.stats_filename == '': self.plot_fame.graph_view.update_plot()
def __init__(self, parent=None): super(InteractivePlotter, self).__init__(parent) self.showMaximized() self.setWindowTitle("SummaryExplorer") QApplication.processEvents() self.plot_fame = FigFrame(self) self.layout = QtWidgets.QVBoxLayout() self.layout.addWidget(self.plot_fame) self.setLayout(self.layout) self.setCentralWidget(self.plot_fame) self.showMaximized() self.raw_path = '' mainMenu = self.menuBar() fileMenu = mainMenu.addMenu('File') imageMenu = mainMenu.addMenu('Images') loadButton = QAction('Load', self) loadButton.setStatusTip('Load data') loadButton.setShortcut("Ctrl+o") loadButton.triggered.connect(self.callLoadData) fileMenu.addAction(loadButton) self.saveButton = QAction('Save', self) self.saveButton.setStatusTip('Save PSD data to xls') self.saveButton.setShortcut("Ctrl+s") self.saveButton.triggered.connect(self.plot_fame.graph_view.save_data) fileMenu.addAction(self.saveButton) self.saveButton.setEnabled(False) avwinButton = QAction('Average window', self) avwinButton.setStatusTip('Change the average window') avwinButton.setShortcut("Ctrl+w") avwinButton.triggered.connect(self.modify_av_wind) fileMenu.addAction(avwinButton) exitButton = QAction('Exit', self) exitButton.setStatusTip('Close') exitButton.triggered.connect(self.close) fileMenu.addAction(exitButton) self.rawButton = QAction('Raw Image', self) self.rawButton.setShortcut("r") self.rawButton.triggered.connect(self.find_raw_data) imageMenu.addAction(self.rawButton) self.rawButton.setEnabled(False) self.imcButton = QAction('Corrected Image', self) self.imcButton.setShortcut("c") self.imcButton.triggered.connect(self.find_imc_data) imageMenu.addAction(self.imcButton) self.imcButton.setEnabled(False) self.toggleButton = QAction('Toggle plot p', self) self.toggleButton.setShortcut("p") self.toggleButton.triggered.connect( self.plot_fame.graph_view.toggle_plot) self.toggleButton.setEnabled(False) mainMenu.addAction(self.toggleButton) self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) self.statusBar.showMessage('Hello. Load a -STATS.csv file to start', 1e12)
def baslat(self, anaPencere): anaPencere.resize(600, 400) anaPencere.setWindowTitle("Dimili-Türkçe Sözlük") anaPencere.setFixedSize(600,400) icon =QIcon() icon.addPixmap(QPixmap("Dictionary.png"),QIcon.Normal,QIcon.Off) anaPencere.setWindowIcon(icon) zemin=QWidget(anaPencere) zemin.setGeometry(QRect(0,30,600,390)) zemin.setStyleSheet("background-color:rgb(167, 196, 233);") self.araKutu = QLineEdit(anaPencere) self.araKutu.setGeometry(QRect(10, 80, 200, 20)) self.araKutu.textChanged.connect(self.benzerKelimeler) self.kelimeGir = QLabel("Kelimeler:",anaPencere) self.kelimeGir.setGeometry(QRect(10, 110, 141, 21)) self.kelimeGor = QLabel("Kelime Ara",anaPencere) self.kelimeGor.setGeometry(QRect(10, 30, 91, 16)) self.harfGrup=QButtonGroup(anaPencere) aharf=QPushButton("â",anaPencere) aharf.setGeometry(QRect(10,50,25,25)) eharf=QPushButton("é",anaPencere) eharf.setGeometry(QRect(30,50,25,25)) self.DilGrup=QButtonGroup(anaPencere) self.Dil1 = QPushButton("Zazaca-Türkçe",anaPencere) self.Dil1.setGeometry(QRect(230, 80, 91, 23)) self.Dil1.setCheckable(True) self.Dil1.setAutoExclusive(True) self.Dil1.setChecked(True) self.Dil1.setStyleSheet("background-color: rgb(102, 255, 0);") self.Dil2 = QPushButton("Türkçe-Zazaca",anaPencere) self.Dil2.setGeometry(QRect(330, 80, 91, 23)) self.Dil2.setCheckable(True) self.Dil2.setAutoExclusive(True) self.Dil2.setStyleSheet("background-color: rgb(255, 94, 105);") self.DilGrup.addButton(self.Dil1,1) self.DilGrup.addButton(self.Dil2,2) self.DilGrup.buttonClicked[int].connect(self.dilSecme) self.kelimeListesi=QListWidget(anaPencere) self.kelimeListesi.setGeometry(QRect(10, 130, 191, 231)) self.kelimeListesi.itemClicked.connect(self.kelimeAcikla) self.kelimeAnlam = QLabel("Kelimenin Anlamı:",anaPencere) self.kelimeAnlam.setGeometry(QRect(230, 110, 131, 21)) self.cumleList1 = QListWidget(anaPencere) self.cumleList1.setGeometry(QRect(230, 130, 351, 51)) self.ornekCumle1 = QLabel("Örnek Zazaca Cümle:",anaPencere) self.ornekCumle1.setGeometry(QRect(230, 200, 101, 21)) self.cumleList2 = QListWidget(anaPencere) self.cumleList2.setGeometry(QRect(230, 220, 351, 51)) self.ornekCumle2 = QLabel("Örnek Türkçe Cümle:",anaPencere) self.ornekCumle2.setGeometry(QRect(230, 290, 111, 16)) self.cumleList3 = QListWidget(anaPencere) self.cumleList3.setGeometry(QRect(230, 310, 351, 51)) self.anaMenu = QMenuBar(anaPencere) self.anaMenu.setGeometry(QRect(0, 0, 600, 21)) self.menuDosya = QMenu("Dosya",self.anaMenu) self.menuDuzenle = QMenu("Düzenle",self.anaMenu) self.menuYardim = QMenu("Yardım",self.anaMenu) anaPencere.setMenuBar(self.anaMenu) self.durum = QStatusBar(zemin) anaPencere.setStatusBar(self.durum) self.durum.setStyleSheet("background-color:white") self.durum.showMessage("Hazır") self.cikis= QAction(QIcon("Exit.ico"),"&Çıkış",anaPencere) self.cikis.setShortcut("Ctrl+X") self.cikis.triggered.connect(anaPencere.close) self.actionHakkinda = QAction("Hakkında",anaPencere) self.actionHakkinda.triggered.connect(self.hakkinda) self.actionSecenekler = QAction("Seçenekler",anaPencere) self.menuDosya.addAction(self.cikis) self.menuDuzenle.addAction(self.actionSecenekler) self.menuYardim.addAction(self.actionHakkinda) self.anaMenu.addAction(self.menuDosya.menuAction()) self.anaMenu.addAction(self.menuDuzenle.menuAction()) self.anaMenu.addAction(self.menuYardim.menuAction())
def setupStatusbar(self): self.statusBar = QStatusBar() self.setStatusBar(self.statusBar)
class ConfigParamEditWindow(QDialog): def __init__(self, parent, node, target_node_id, param_struct, update_callback): super(ConfigParamEditWindow, self).__init__(parent) self.setWindowTitle("Edit configuration parameter") self.setModal(True) self._node = node self._target_node_id = target_node_id self._param_struct = param_struct self._update_callback = update_callback min_val = get_union_value(param_struct.min_value) if "uavcan.protocol.param.Empty" in str(min_val): min_val = None max_val = get_union_value(param_struct.max_value) if "uavcan.protocol.param.Empty" in str(max_val): max_val = None value = get_union_value(param_struct.value) self._value_widget = None value_type = uavcan.get_active_union_field(param_struct.value) if value_type == "integer_value": min_val = min_val if min_val is not None else -0x8000000000000000 max_val = max_val if max_val is not None else 0x7FFFFFFFFFFFFFFF if min_val >= -0x80000000 and max_val <= +0x7FFFFFFF: self._value_widget = QSpinBox(self) self._value_widget.setMaximum(max_val) self._value_widget.setMinimum(min_val) self._value_widget.setValue(value) if value_type == "real_value": min_val = round_float(min_val) if min_val is not None else -3.4028235e38 max_val = round_float(max_val) if max_val is not None else 3.4028235e38 value = round_float(value) if value_type == "boolean_value": self._value_widget = QCheckBox(self) self._value_widget.setChecked(bool(value)) if self._value_widget is None: self._value_widget = QLineEdit(self) self._value_widget.setText(str(value)) self._value_widget.setFont(get_monospace_font()) layout = QGridLayout(self) def add_const_field(label, *values): row = layout.rowCount() layout.addWidget(QLabel(label, self), row, 0) if len(values) == 1: layout.addWidget(FieldValueWidget(self, values[0]), row, 1) else: sub_layout = QHBoxLayout(self) for idx, v in enumerate(values): sub_layout.addWidget(FieldValueWidget(self, v)) layout.addLayout(sub_layout, row, 1) add_const_field("Name", param_struct.name) add_const_field("Type", uavcan.get_active_union_field(param_struct.value).replace("_value", "")) add_const_field("Min/Max", min_val, max_val) add_const_field("Default", render_union(param_struct.default_value)) layout.addWidget(QLabel("Value", self), layout.rowCount(), 0) layout.addWidget(self._value_widget, layout.rowCount() - 1, 1) fetch_button = make_icon_button( "refresh", "Read parameter from the node", self, text="Fetch", on_clicked=self._do_fetch ) set_default_button = make_icon_button( "fire-extinguisher", "Restore default value", self, text="Restore", on_clicked=self._restore_default ) send_button = make_icon_button( "flash", "Send parameter to the node", self, text="Send", on_clicked=self._do_send ) cancel_button = make_icon_button( "remove", "Close this window; unsent changes will be lost", self, text="Cancel", on_clicked=self.close ) controls_layout = QGridLayout(self) controls_layout.addWidget(fetch_button, 0, 0) controls_layout.addWidget(send_button, 0, 1) controls_layout.addWidget(set_default_button, 1, 0) controls_layout.addWidget(cancel_button, 1, 1) layout.addLayout(controls_layout, layout.rowCount(), 0, 1, 2) self._status_bar = QStatusBar(self) self._status_bar.setSizeGripEnabled(False) layout.addWidget(self._status_bar, layout.rowCount(), 0, 1, 2) left, top, right, bottom = layout.getContentsMargins() bottom = 0 layout.setContentsMargins(left, top, right, bottom) self.setLayout(layout) def show_message(self, text, *fmt): self._status_bar.showMessage(text % fmt) def _assign(self, value_union): value = get_union_value(value_union) if uavcan.get_active_union_field(value_union) == "real_value": value = round_float(value) if hasattr(self._value_widget, "setValue"): self._value_widget.setValue(value) self._update_callback(value) elif hasattr(self._value_widget, "setChecked"): self._value_widget.setChecked(bool(value)) self._update_callback(bool(value)) else: self._value_widget.setText(str(value)) self._update_callback(value) def _on_response(self, e): if e is None: self.show_message("Request timed out") else: logger.info("Param get/set response: %s", e.response) self._assign(e.response.value) self.show_message("Response received") def _restore_default(self): self._assign(self._param_struct.default_value) def _do_fetch(self): try: request = uavcan.protocol.param.GetSet.Request(name=self._param_struct.name) self._node.request(request, self._target_node_id, self._on_response, priority=REQUEST_PRIORITY) except Exception as ex: show_error("Node error", "Could not send param get request", ex, self) else: self.show_message("Fetch request sent") def _do_send(self): value_type = uavcan.get_active_union_field(self._param_struct.value) try: if value_type == "integer_value": if hasattr(self._value_widget, "value"): value = int(self._value_widget.value()) else: value = int(self._value_widget.text()) self._param_struct.value.integer_value = value elif value_type == "real_value": value = float(self._value_widget.text()) self._param_struct.value.real_value = value elif value_type == "boolean_value": value = bool(self._value_widget.isChecked()) self._param_struct.value.boolean_value = value elif value_type == "string_value": value = self._value_widget.text() self._param_struct.value.string_value = value else: raise RuntimeError("This is not happening!") except Exception as ex: show_error("Format error", "Could not parse value", ex, self) return try: request = uavcan.protocol.param.GetSet.Request(name=self._param_struct.name, value=self._param_struct.value) logger.info("Sending param set request: %s", request) self._node.request(request, self._target_node_id, self._on_response, priority=REQUEST_PRIORITY) except Exception as ex: show_error("Node error", "Could not send param set request", ex, self) else: self.show_message("Set request sent")
def __init__(self, pathObj, caption, icons, parent=None): """Helpview initialize with text. Arguments: pathObj -- a path object for the help file caption -- the window caption icons -- dict of view icons """ QMainWindow.__init__(self, parent) self.setAttribute(Qt.WA_QuitOnClose, False) self.setWindowFlags(Qt.Window) self.setStatusBar(QStatusBar()) self.textView = HelpViewer(self) self.setCentralWidget(self.textView) self.textView.setSearchPaths([str(pathObj.parent)]) self.textView.setSource(QUrl(pathObj.as_uri())) self.resize(520, 440) self.setWindowTitle(caption) tools = self.addToolBar(_('Tools')) self.menu = QMenu(self.textView) self.textView.highlighted[str].connect(self.showLink) backAct = QAction(_('&Back'), self) backAct.setIcon(icons['helpback']) tools.addAction(backAct) self.menu.addAction(backAct) backAct.triggered.connect(self.textView.backward) backAct.setEnabled(False) self.textView.backwardAvailable.connect(backAct.setEnabled) forwardAct = QAction(_('&Forward'), self) forwardAct.setIcon(icons['helpforward']) tools.addAction(forwardAct) self.menu.addAction(forwardAct) forwardAct.triggered.connect(self.textView.forward) forwardAct.setEnabled(False) self.textView.forwardAvailable.connect(forwardAct.setEnabled) homeAct = QAction(_('&Home'), self) homeAct.setIcon(icons['helphome']) tools.addAction(homeAct) self.menu.addAction(homeAct) homeAct.triggered.connect(self.textView.home) tools.addSeparator() tools.addSeparator() findLabel = QLabel(_(' Find: '), self) tools.addWidget(findLabel) self.findEdit = QLineEdit(self) tools.addWidget(self.findEdit) self.findEdit.textEdited.connect(self.findTextChanged) self.findEdit.returnPressed.connect(self.findNext) self.findPreviousAct = QAction(_('Find &Previous'), self) self.findPreviousAct.setIcon(icons['helpprevious']) tools.addAction(self.findPreviousAct) self.menu.addAction(self.findPreviousAct) self.findPreviousAct.triggered.connect(self.findPrevious) self.findPreviousAct.setEnabled(False) self.findNextAct = QAction(_('Find &Next'), self) self.findNextAct.setIcon(icons['helpnext']) tools.addAction(self.findNextAct) self.menu.addAction(self.findNextAct) self.findNextAct.triggered.connect(self.findNext) self.findNextAct.setEnabled(False)
def __init__(self, MainWin): # Main Window MainWin.setObjectName("UploadWindow") MainWin.setWindowTitle(MainWin.tr(self.title)) MainWin.resize(1024, 768) self.centralWidget = QWidget(MainWin) self.centralWidget.setObjectName("centralWidget") MainWin.setCentralWidget(self.centralWidget) self.verticalLayout = QVBoxLayout(self.centralWidget) self.verticalLayout.setContentsMargins(11, 11, 11, 11) self.verticalLayout.setSpacing(6) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QHBoxLayout() self.pathLabel = QLabel("Directory:") self.horizontalLayout.addWidget(self.pathLabel) self.pathTextBox = QLineEdit() self.pathTextBox.setReadOnly(True) self.horizontalLayout.addWidget(self.pathTextBox) self.browseButton = QPushButton("Browse", self.centralWidget) self.browseButton.clicked.connect(MainWin.on_actionBrowse_triggered) self.horizontalLayout.addWidget(self.browseButton) self.verticalLayout.addLayout(self.horizontalLayout) # Splitter for Upload list/Log self.splitter = QSplitter(Qt.Vertical) # Table View (Upload list) self.uploadList = TableWidget(self.centralWidget) self.uploadList.setObjectName("uploadList") self.uploadList.setStyleSheet( """ QTableWidget { border: 2px solid grey; border-radius: 5px; } """) self.uploadList.setEditTriggers(QAbstractItemView.NoEditTriggers) # use NoEditTriggers to disable editing self.uploadList.setAlternatingRowColors(True) self.uploadList.setSelectionBehavior(QAbstractItemView.SelectRows) self.uploadList.setSelectionMode(QAbstractItemView.NoSelection) self.uploadList.verticalHeader().setDefaultSectionSize(18) # tighten up the row size self.uploadList.horizontalHeader().setStretchLastSection(True) self.uploadList.setSortingEnabled(True) # allow sorting self.splitter.addWidget(self.uploadList) # Log Widget self.logTextBrowser = QPlainTextEditLogger(self.centralWidget) self.logTextBrowser.widget.setObjectName("logTextBrowser") self.logTextBrowser.widget.setStyleSheet( """ QPlainTextEdit { border: 2px solid grey; border-radius: 5px; background-color: lightgray; } """) self.splitter.addWidget(self.logTextBrowser.widget) # add splitter self.splitter.setSizes([400, 200]) self.verticalLayout.addWidget(self.splitter) # Actions # Browse self.actionBrowse = QAction(MainWin) self.actionBrowse.setObjectName("actionBrowse") self.actionBrowse.setText(MainWin.tr("Browse")) self.actionBrowse.setToolTip(MainWin.tr("Set the upload directory")) self.actionBrowse.setShortcut(MainWin.tr("Ctrl+B")) # Upload self.actionUpload = QAction(MainWin) self.actionUpload.setObjectName("actionUpload") self.actionUpload.setText(MainWin.tr("Upload")) self.actionUpload.setToolTip(MainWin.tr("Upload files")) self.actionUpload.setShortcut(MainWin.tr("Ctrl+L")) self.actionUpload.setEnabled(False) # Rescan self.actionRescan = QAction(MainWin) self.actionRescan.setObjectName("actionRescan") self.actionRescan.setText(MainWin.tr("Rescan")) self.actionRescan.setToolTip(MainWin.tr("Rescan the upload directory")) self.actionRescan.setShortcut(MainWin.tr("Ctrl+R")) self.actionRescan.setEnabled(False) # Cancel self.actionCancel = QAction(MainWin) self.actionCancel.setObjectName("actionCancel") self.actionCancel.setText(MainWin.tr("Cancel")) self.actionCancel.setToolTip(MainWin.tr("Cancel any upload(s) in-progress")) self.actionCancel.setShortcut(MainWin.tr("Ctrl+C")) # Options self.actionOptions = QAction(MainWin) self.actionOptions.setObjectName("actionOptions") self.actionOptions.setText(MainWin.tr("Options")) self.actionOptions.setToolTip(MainWin.tr("Configuration Options")) self.actionOptions.setShortcut(MainWin.tr("Ctrl+P")) # Login self.actionLogin = QAction(MainWin) self.actionLogin.setObjectName("actionLogin") self.actionLogin.setText(MainWin.tr("Login")) self.actionLogin.setToolTip(MainWin.tr("Login to the server")) self.actionLogin.setShortcut(MainWin.tr("Ctrl+G")) self.actionLogin.setEnabled(False) # Logout self.actionLogout = QAction(MainWin) self.actionLogout.setObjectName("actionLogout") self.actionLogout.setText(MainWin.tr("Logout")) self.actionLogout.setToolTip(MainWin.tr("Logout of the server")) self.actionLogout.setShortcut(MainWin.tr("Ctrl+O")) self.actionLogout.setEnabled(False) # Exit self.actionExit = QAction(MainWin) self.actionExit.setObjectName("actionExit") self.actionExit.setText(MainWin.tr("Exit")) self.actionExit.setToolTip(MainWin.tr("Exit the application")) self.actionExit.setShortcut(MainWin.tr("Ctrl+Z")) # Help self.actionHelp = QAction(MainWin) self.actionHelp.setObjectName("actionHelp") self.actionHelp.setText(MainWin.tr("Help")) self.actionHelp.setToolTip(MainWin.tr("Help")) self.actionHelp.setShortcut(MainWin.tr("Ctrl+H")) # Menu Bar """ self.menuBar = QMenuBar(MainWin) self.menuBar.setObjectName("menuBar") MainWin.setMenuBar(self.menuBar) self.menuBar.setStyleSheet( "QMenuBar{font-family: Arial;font-style: normal;font-size: 10pt;font-weight: bold;};") """ # Tool Bar self.mainToolBar = QToolBar(MainWin) self.mainToolBar.setObjectName("mainToolBar") self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.mainToolBar.setContextMenuPolicy(Qt.PreventContextMenu) MainWin.addToolBar(Qt.TopToolBarArea, self.mainToolBar) # Upload self.mainToolBar.addAction(self.actionUpload) self.actionUpload.setIcon(qApp.style().standardIcon(QStyle.SP_FileDialogToParent)) # Rescan self.mainToolBar.addAction(self.actionRescan) self.actionRescan.setIcon(qApp.style().standardIcon(QStyle.SP_BrowserReload)) # Cancel self.mainToolBar.addAction(self.actionCancel) self.actionCancel.setIcon(qApp.style().standardIcon(QStyle.SP_BrowserStop)) self.actionCancel.setEnabled(False) # Options self.mainToolBar.addAction(self.actionOptions) self.actionOptions.setIcon(qApp.style().standardIcon(QStyle.SP_FileDialogDetailedView)) # this spacer right justifies everything that comes after it spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.mainToolBar.addWidget(spacer) # Login self.mainToolBar.addAction(self.actionLogin) self.actionLogin.setIcon(qApp.style().standardIcon(QStyle.SP_DialogApplyButton)) # Logout self.mainToolBar.addAction(self.actionLogout) self.actionLogout.setIcon(qApp.style().standardIcon(QStyle.SP_DialogOkButton)) # Help #self.mainToolBar.addAction(self.actionHelp) self.actionHelp.setIcon(qApp.style().standardIcon(QStyle.SP_MessageBoxQuestion)) # Exit self.mainToolBar.addAction(self.actionExit) self.actionExit.setIcon(qApp.style().standardIcon(QStyle.SP_DialogCancelButton)) # Status Bar self.statusBar = QStatusBar(MainWin) self.statusBar.setToolTip("") self.statusBar.setStatusTip("") self.statusBar.setObjectName("statusBar") MainWin.setStatusBar(self.statusBar) # configure logging self.logTextBrowser.widget.log_update_signal.connect(MainWin.updateLog) self.logTextBrowser.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) logging.getLogger().addHandler(self.logTextBrowser) # finalize UI setup QMetaObject.connectSlotsByName(MainWin)
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(820, 760) MainWindow.setMinimumSize(QSize(720, 560)) MainWindow.setWindowTitle("BW-MapEdit") #MainWindow.setWindowTitle("Nep-Nep") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") MainWindow.setCentralWidget(self.centralwidget) self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.scrollArea = QScrollArea(self.centralwidget) self.scrollArea.setWidgetResizable(True) self.bw_map_screen = BWMapViewer(self.centralwidget) self.scrollArea.setWidget(self.bw_map_screen) self.horizontalLayout.addWidget(self.scrollArea) #self.horizontalLayout.addWidget(self.bw_map_screen) self.entity_list_widget = BWEntityListWidget(self.centralwidget) self.entity_list_widget.setMaximumSize(QSize(300, 16777215)) self.entity_list_widget.setObjectName("entity_list_widget") self.horizontalLayout.addWidget(self.entity_list_widget) spacerItem = QSpacerItem(10, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) self.horizontalLayout.addItem(spacerItem) self.vertLayoutWidget = QWidget(self.centralwidget) self.vertLayoutWidget.setMaximumSize(QSize(250, 1200)) self.verticalLayout = QVBoxLayout(self.vertLayoutWidget) self.verticalLayout.setObjectName("verticalLayout") #self.verticalLayout. self.button_clone_entity = QPushButton(self.centralwidget) self.button_clone_entity.setObjectName("button_clone_entity") self.verticalLayout.addWidget(self.button_clone_entity) self.button_remove_entity = QPushButton(self.centralwidget) self.button_remove_entity.setObjectName("button_remove_entity") self.verticalLayout.addWidget(self.button_remove_entity) self.button_move_entity = QPushButton(self.centralwidget) self.button_move_entity.setObjectName("button_move_entity") self.verticalLayout.addWidget(self.button_move_entity) self.button_show_passengers = QPushButton(self.centralwidget) self.button_show_passengers.setObjectName("button_move_entity") self.verticalLayout.addWidget(self.button_show_passengers) self.gridLayout = QGridLayout() self.gridLayout.setObjectName("gridLayout") self.button_zoom_in = QPushButton(self.centralwidget) self.button_zoom_in.setObjectName("button_zoom_in") self.gridLayout.addWidget(self.button_zoom_in, 0, 0, 0, 1) self.button_zoom_out = QPushButton(self.centralwidget) self.button_zoom_out.setObjectName("button_zoom_out") self.gridLayout.addWidget(self.button_zoom_out, 0, 1, 0, 1) self.button_edit_xml = QPushButton(self.centralwidget) self.button_edit_xml.setObjectName("button_edit_xml") self.button_edit_base_xml = QPushButton(self.centralwidget) self.button_edit_base_xml.setObjectName("button_edit_base_xml") self.verticalLayout.addLayout(self.gridLayout) self.verticalLayout.addWidget(self.button_edit_xml) self.verticalLayout.addWidget(self.button_edit_base_xml) spacerItem1 = QSpacerItem(10, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.verticalLayout.addItem(spacerItem1) self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.lineedit_angle = QLineEdit(self.centralwidget) self.lineedit_angle.setObjectName("lineedit_angle") self.lineedit_angle.setPlaceholderText("Angle") self.label_object_id = QLabel(self.centralwidget) self.label_object_id.setObjectName("label_object_id") #TextSelectableByCursor self.label_position = QLabel(self.centralwidget) self.label_position.setObjectName("label_position") self.label_model_name = QLabel(self.centralwidget) self.label_model_name.setObjectName("label_model_name") self.label_4 = QLabel(self.centralwidget) self.label_4.setObjectName("label_4") self.label_5 = QLabel(self.centralwidget) self.label_5.setObjectName("label_5") for label in (self.label_object_id, self.label_position, self.label_model_name, self.label_4, self.label_5): label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) self.verticalLayout_2.addWidget(self.lineedit_angle) self.verticalLayout_2.addWidget(self.label_object_id) self.verticalLayout_2.addWidget(self.label_position) self.verticalLayout_2.addWidget(self.label_model_name) self.verticalLayout_2.addWidget(self.label_4) self.verticalLayout_2.addWidget(self.label_5) self.verticalLayout.addLayout(self.verticalLayout_2) self.horizontalLayout.addWidget(self.vertLayoutWidget) self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QRect(0, 0, 820, 29)) self.menubar.setObjectName("menubar") self.file_menu = QMenu(self.menubar) self.file_menu.setObjectName("menuLoad") self.file_load_action = QAction("Load", self) self.file_load_action.triggered.connect(self.button_load_level) self.file_menu.addAction(self.file_load_action) self.file_save_action = QAction("Save", self) self.file_save_action.triggered.connect(self.button_save_level) self.file_menu.addAction(self.file_save_action) self.visibility_menu = MenuDontClose(self.menubar)#QMenu(self.menubar) self.visibility_menu.setObjectName("visibility") #self.visibility_menu.addAction(self.toggle_action) self.visibility_actions = [] self.terrain_menu = QMenu(self.menubar) self.terrain_menu.setObjectName("terrain") self.terrain_load_action = QAction("Load Terrain", self) self.terrain_load_action.triggered.connect(self.button_terrain_load_action) self.terrain_menu.addAction(self.terrain_load_action) self.terrain_display_actions = [] self.setup_terrain_display_toggles() #self.menuLoad_2 = QMenu(self.menubar) #self.menuLoad_2.setObjectName("menuLoad_2") MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar.addAction(self.file_menu.menuAction()) #self.menubar.addAction(self.menuLoad_2.menuAction()) self.menubar.addAction(self.visibility_menu.menuAction()) self.menubar.addAction(self.terrain_menu.menuAction()) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow)
class StringsEditorMainWindow(QMainWindow): def __init__(self): super().__init__() self.setup_ui() self.stringfile = None self.reset_in_process = False path = get_default_path() if path is None: self.default_path = "" else: self.default_path = path self.strings_list.currentItemChanged.connect(self.action_listwidget_change_item) self.button_set_message.pressed.connect(self.action_button_set_message) self.button_add_message.pressed.connect(self.action_button_add_message) self.button_remove_message.pressed.connect(self.action_button_delete_message) def reset(self): self.reset_in_process = True self.stringfile = None self.strings_list.clearSelection() self.strings_list.clear() self.textedit_content.clear() self.lineedit_path.clear() self.lineedit_playtime.clear() self.lineedit_audioname.clear() self.reset_in_process = False def action_button_add_message(self): if self.stringfile is not None: newmessage = Message(strings=[b"", b"", b"", b""], audioplaytime=0.0) self.stringfile.messages.append(newmessage) i = len(self.stringfile.messages) - 1 entry = BWEntityEntry(i, "({0}): '{1}'-'{2}'".format(i, newmessage.get_path(), newmessage.get_message())) self.strings_list.addItem(entry) self.strings_list.setCurrentRow(i) def action_button_set_message(self): print("I was pressed") current = self.strings_list.currentItem() if current is not None and self.strings_list is not None: try: msg = self.stringfile.messages[current.xml_ref] print(current) msg.set_path(self.lineedit_path.text()) msg.set_name(self.lineedit_audioname.text()) msg.playtime = float(self.lineedit_playtime.text()) msg.set_message(self.textedit_content.toPlainText()) current.setText("({0}): '{1}'-'{2}'".format(current.xml_ref, msg.get_path(), msg.get_message())) except: traceback.print_exc() def action_button_delete_message(self): if self.stringfile is not None: lastindex = len(self.stringfile.messages) - 1 lastmessage = self.stringfile.messages.pop() item = self.strings_list.takeItem(lastindex) self.strings_list.removeItemWidget(item) self.strings_list.setCurrentRow(lastindex-1) self.statusbar.showMessage("DELETED: ({0}) {1}".format(lastindex, trim_message(lastmessage.get_message()))) def action_listwidget_change_item(self, current, previous): if current is not None: print(current.xml_ref) msg = self.stringfile.messages[current.xml_ref] self.lineedit_audioname.setText(msg.get_name()) self.lineedit_path.setText(msg.get_path()) self.lineedit_playtime.setText(str(msg.playtime)) self.textedit_content.setText(msg.get_message()) def button_load_strings(self): try: print("ok", self.default_path) self.xmlPath = "" filepath, choosentype = QFileDialog.getOpenFileName( self, "Open File", self.default_path, "BW string files (*.str);;All files (*)") print("doooone") if filepath: print("resetting") self.reset() print("done") with open(filepath, "rb") as f: try: self.stringfile = BWLanguageFile(f) for i, msg in enumerate(self.stringfile.messages): entry = BWEntityEntry(i, "({0}): '{1}'-'{2}'".format(i, msg.get_path(), msg.get_message())) self.strings_list.addItem(entry) pass self.default_path = filepath except Exception as error: print("error", error) traceback.print_exc() except Exception as er: print("errrorrr", error) traceback.print_exc() print("loaded") def button_save_strings(self): if self.stringfile is not None: filepath, choosentype = QFileDialog.getSaveFileName( self, "Save File", self.default_path, "BW level files (*.str);;All files (*)") print(filepath, "saved") if filepath: with open(filepath, "wb") as f: self.stringfile.write(f) self.default_path = filepath set_default_path(filepath) else: pass # no level loaded, do nothing def setup_ui(self): self.setObjectName("MainWindow") self.resize(820, 760) self.setMinimumSize(QSize(720, 560)) self.setWindowTitle("BW-StringsEdit") self.centralwidget = QWidget(self) self.centralwidget.setObjectName("centralwidget") self.setCentralWidget(self.centralwidget) self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.strings_list = QListWidget(self.centralwidget) self.horizontalLayout.addWidget(self.strings_list) self.vertLayoutWidget = QWidget(self.centralwidget) self.verticalLayout = QVBoxLayout(self.vertLayoutWidget) self.button_add_message = QPushButton(self.centralwidget) self.button_remove_message = QPushButton(self.centralwidget) self.button_set_message = QPushButton(self.centralwidget) self.button_add_message.setText("Add Message") self.button_remove_message.setText("Delete Last Message") self.button_set_message.setText("Set Message Content") self.lineedit_path = QLineEdit(self.centralwidget) self.lineedit_audioname = QLineEdit(self.centralwidget) self.lineedit_playtime = QLineEdit(self.centralwidget) self.textedit_content = QTextEdit(self.centralwidget) for widget in ( self.button_remove_message, self.button_add_message, self.button_set_message, self.lineedit_path, self.lineedit_audioname, self.lineedit_playtime, self.textedit_content): self.verticalLayout.addWidget(widget) self.horizontalLayout.addWidget(self.vertLayoutWidget) self.menubar = self.menuBar()#QMenuBar(self) #self.menubar.setGeometry(QRect(0, 0, 820, 30)) #self.menubar.setObjectName("menubar") self.file_menu = self.menubar.addMenu("File")#QMenu(self.menubar) self.file_menu.setObjectName("menuLoad") #self.menubar.addMenu(self.file_menu) self.file_load_action = QAction("Load", self) self.file_load_action.triggered.connect(self.button_load_strings) self.file_menu.addAction(self.file_load_action) self.file_save_action = QAction("Save", self) self.file_save_action.triggered.connect(self.button_save_strings) self.file_menu.addAction(self.file_save_action) self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) #self.setMenuBar(self.menubar) print("done")
def __init__(self, scan_file): QWidget.__init__(self) self.notebook = QTabWidget() self.setWindowTitle(_("Parameter scan editor - (www.gpvdm.com)")) self.setWindowIcon(icon_get("scan")) self.main_vbox = QVBoxLayout() self.scan_tab_vbox = QVBoxLayout() self.tokens = tokens() self.myserver = server_get() self.status_bar = QStatusBar() self.param_list = get_scan_human_labels().list #self.tab_label=tab_label self.scan_io = scan_io() self.scan_io.parent_window = self #self.scan_io.set_path(self.scan_io.scan_dir) self.scan_io.load(scan_file) self.scan_io.make_dir() toolbar = QToolBar() toolbar.setIconSize(QSize(32, 32)) self.tb_add = QAction(icon_get("list-add"), _("Add parameter to scan"), self) self.tb_add.triggered.connect(self.callback_add_item) toolbar.addAction(self.tb_add) self.tb_minus = QAction(icon_get("list-remove"), _("Delete item"), self) self.tb_minus.triggered.connect(self.callback_delete_item) toolbar.addAction(self.tb_minus) self.tb_down = QAction(icon_get("go-down"), _("Move down"), self) self.tb_down.triggered.connect(self.callback_move_down) toolbar.addAction(self.tb_down) self.tb_up = QAction(icon_get("go-up"), _("Move up"), self) self.tb_up.triggered.connect(self.callback_move_up) toolbar.addAction(self.tb_up) self.tb_command = QAction(icon_get("utilities-terminal"), _("Insert python command"), self) self.tb_command.triggered.connect(self.callback_insert_command) toolbar.addAction(self.tb_command) self.scan_tab_vbox.addWidget(toolbar) self.tab = gpvdm_tab() css_apply(self.notebook, "tab_default.css") self.notebook.setMovable(True) self.tab.verticalHeader().setVisible(False) self.tab.setColumnCount(5) #if enable_betafeatures()==False: # self.tab.setColumnHidden(0, True) # self.tab.setColumnHidden(1, True) self.tab.setSelectionBehavior(QAbstractItemView.SelectRows) self.tab.setColumnWidth(2, 300) self.tab.setColumnWidth(3, 300) self.tab.setColumnWidth(4, 300) self.load() self.tab.cellChanged.connect(self.tab_changed) self.scan_tab_vbox.addWidget(self.tab) self.notebook.popMenu = QMenu(self) #self.mp_show_list=QAction(_("Select parameter to scan"), self) #self.mp_show_list.triggered.connect(self.callback_show_list) #self.popMenu.addAction(self.mp_show_list) self.notebook.popMenu.addSeparator() self.mp_delete = QAction(_("Delete item"), self) self.mp_delete.triggered.connect(self.callback_delete_item) self.notebook.popMenu.addAction(self.mp_delete) self.mp_copy = QAction(_("Copy"), self) self.mp_copy.triggered.connect(self.callback_copy_item) self.notebook.popMenu.addAction(self.mp_copy) self.mp_paste = QAction(_("Paste"), self) self.mp_paste.triggered.connect(self.callback_paste_item) self.notebook.popMenu.addAction(self.mp_paste) self.notebook.popMenu.addSeparator() self.mp_add = QAction(_("Add item"), self) self.mp_add.triggered.connect(self.callback_add_item) self.notebook.popMenu.addAction(self.mp_add) self.mp_down = QAction(_("Move down"), self) self.mp_down.triggered.connect(self.callback_move_down) self.notebook.popMenu.addAction(self.mp_down) self.mp_down = QAction(_("Move down"), self) self.mp_down.triggered.connect(self.callback_move_down) self.notebook.popMenu.addAction(self.mp_down) self.notebook.popMenu.addSeparator() self.notebook.setMinimumSize(700, 500) self.program_widget = QWidget() self.program_widget.setLayout(self.scan_tab_vbox) self.notebook.addTab(self.program_widget, "Commands") self.viewer = gpvdm_viewer(self.scan_io.scan_dir) self.viewer.show_back_arrow = True self.notebook.addTab(self.viewer, "Output") self.ribbon = scan_tab_ribbon() self.ribbon.tb_simulate.triggered.connect(self.callback_run_simulation) self.ribbon.tb_clean.triggered.connect(self.clean_scan_dir) self.ribbon.tb_plot.triggered.connect(self.callback_gen_plot_command) self.ribbon.tb_notes.triggered.connect(self.callback_notes) self.main_vbox.addWidget(self.ribbon) self.main_vbox.addWidget(self.notebook) self.main_vbox.addWidget(self.status_bar) self.setLayout(self.main_vbox) self.select_param_window = select_param(self.tab)
class ShowPoints(QWidget): def __init__(self): super().__init__() self.webView = QtWebEngineWidgets.QWebEngineView() self.sourceType = QComboBox() self.sourceType.addItems(['国测局坐标GCJ02(MX数据库/高德)','GPS坐标(wgs84/NMEA0183)']) self.inputText = QTextEdit() self.inputText.setFixedWidth(280) self.runButton = QPushButton('确定') self.runButton.setFixedWidth(100) self.clrButton = QPushButton('清除') self.clrButton.setFixedWidth(100) self.statusBar = QStatusBar() self.statusBar.showMessage(STATUS_TIP+"Ready") self.init_ui() def init_ui(self): path = os.getcwd() url = path + HTM_FILE self.webView.setUrl(QtCore.QUrl(url)) self.webView.page().loadFinished.connect(self.load_finished) # for test self.inputText.setEnabled(False) self.inputText.setAcceptRichText(False) self.inputText.setToolTip("每行一组经纬度,纬度lat在前\n" + "以空格、逗号或制表符分隔") self.runButton.clicked.connect(self.add_points) # show all points in input text window self.clrButton.clicked.connect(self.clr_points) buttonBox = QHBoxLayout() # button box buttonBox.addStretch() buttonBox.addWidget(self.runButton) buttonBox.addWidget(self.clrButton) rightBox = QVBoxLayout() # right box rightBox.addWidget(self.sourceType) rightBox.addWidget(self.inputText) rightBox.addLayout(buttonBox) rightBox.addWidget(self.statusBar) layout = QHBoxLayout() # main box layout.addWidget(self.webView) layout.addLayout(rightBox) self.setLayout(layout) self.setWindowTitle('经纬度地图显示') self.show() def load_finished(self): self.inputText.setEnabled(True) def add_marker(self): """ 添加标记,ok :return: """ a = self.webView.page() # a.runJavaScript("addMarker(114.39387,30.505299,true,1);") # a.runJavaScript("var point = new BMap.Point(114,30);var marker = new BMap.Marker(point);map.addOverlay(marker);") a.runJavaScript("testfunc(1);") # ok a.runJavaScript("addMarker(114,30.01,true,2);") def run_script(self, script): a = self.webView.page() a.runJavaScript(script) def add_points(self): self.statusBar.showMessage(STATUS_TIP+"Running...") points_text = self.inputText.toPlainText() # 获取输入 source_type = self.sourceType.currentIndex() if_mars = 'true' if (source_type == 0) else 'false' if points_text == "": # 使用示例输入 points_text = SAMPLE_DATA self.inputText.setPlainText(points_text) points = Point.points_parser(points_text) # 解析输入 lats = [p.lat for p in points] lons = [p.lon for p in points] N = len(lats) # 共N组经纬度 G = math.ceil((N - 1) / 9) # 每10个一组,首尾相接,共G组 if N == 1: G = 1 for g in range(G): # 0,1,...,G-1 index_s = 9 * g index_e = 9 * g + 10 index_e = N if (index_e > N) else index_e latsStr = "[" + ",".join(lats[index_s:index_e]) + "]" lonsStr = "[" + ",".join(lons[index_s:index_e]) + "]" script = "addSimpleMarker(%s,%s,%s);" % (latsStr, lonsStr, if_mars) self.run_script(script) time.sleep(0.1) # seconds,延时0.1秒,避免回调函数的执行顺序被打乱 self.statusBar.showMessage(STATUS_TIP+"Done") def clr_points(self): self.run_script("clearMarkers();") self.inputText.setPlainText("") self.statusBar.showMessage(STATUS_TIP+"Ready")
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(800, 600) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.toolButton = QToolButton(self.centralwidget) self.toolButton.setGeometry(QtCore.QRect(160, 170, 171, 19)) self.toolButton.setObjectName(_fromUtf8("toolButton")) self.toolButton_2 = QToolButton(self.centralwidget) self.toolButton_2.setGeometry(QtCore.QRect(450, 170, 191, 19)) self.toolButton_2.setObjectName(_fromUtf8("toolButton_2")) self.horizontalSlider = QSlider(self.centralwidget) self.horizontalSlider.setGeometry(QtCore.QRect(160, 240, 160, 22)) self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider")) self.label = QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(210, 270, 47, 13)) self.label.setObjectName(_fromUtf8("label")) self.graphicsView = QGraphicsView(self.centralwidget) self.graphicsView.setGeometry(QtCore.QRect(400, 270, 300, 180)) self.graphicsView.setVerticalScrollBarPolicy( QtCore.Qt.ScrollBarAlwaysOff) self.graphicsView.setHorizontalScrollBarPolicy( QtCore.Qt.ScrollBarAlwaysOff) self.graphicsView.setObjectName(_fromUtf8("graphicsView")) self.scence = QGraphicsScene() self.scence.addPixmap(QPixmap.scaled(QPixmap('D:\q.jpg'), 300, 180)) self.graphicsView.setScene(self.scence) self.toolButton_3 = QToolButton(self.centralwidget) self.toolButton_3.setGeometry(QtCore.QRect(450, 210, 191, 19)) self.toolButton_3.setObjectName(_fromUtf8("toolButton_3")) self.label_2 = QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(150, 333, 191, 31)) self.label_2.setAlignment(QtCore.Qt.AlignCenter) self.label_2.setObjectName(_fromUtf8("label_2")) self.label_3 = QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(440, 463, 241, 20)) self.label_3.setAlignment(QtCore.Qt.AlignCenter) self.label_3.setObjectName(_fromUtf8("label_3")) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.textEdit = QTextEdit(self.centralwidget) self.textEdit.setGeometry(QtCore.QRect(410, 480, 281, 71)) self.textEdit.setObjectName(_fromUtf8("textEdit")) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Лабораторная №3")) self.toolButton.setText(_translate("MainWindow", "Тренировка")) self.toolButton_2.setText(_translate("MainWindow", "Распознавание")) self.label.setText(_translate("MainWindow", "0.01")) self.toolButton_3.setText(_translate("MainWindow", "Изменить картинку"))
class MainWindow(QMainWindow): l = logging.getLogger('MainWindow') def __init__(self, app): QMainWindow.__init__(self, None) self.l.debug('Initializing MainWindow ...') self.setWindowTitle('MynPad') app.setWindowIcon(QIcon(':/icons/mynpad.png')) if os.name == 'nt': # On Windows, make sure to use a unique Application User Model Id, otherwise # Windows shows the default python icon in the taskbar # see http://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7 myappid = 'afester.mynpad' import ctypes; ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) self.theApplication = app app.aboutToQuit.connect(self.saveState) # read the local configuration file iniPath = 'mynpad.ini' if not os.path.exists(iniPath): iniPath = os.path.join(expanduser("~"), iniPath) self.settings = Settings(iniPath) self.settings.load() # Set up the menu bar menuBar = QMenuBar(self) exitAction = QAction("Exit", self, triggered=self.theApplication.exit) fileMenu = menuBar.addMenu("&File") fileMenu.addAction(exitAction) aboutAction = QAction("About ...", self, triggered = self.handleAbout) helpMenu = menuBar.addMenu("&Help") helpMenu.addAction(aboutAction) self.setMenuBar(menuBar) # Setup the status bar self.statusBar = QStatusBar() self.statusBar.showMessage("Ready.") self.setStatusBar(self.statusBar) self.mainWidget = CentralWidget(self, self.settings) self.mainWidget.updateWindowTitle.connect(self.updateWindowTitle) self.setCentralWidget(self.mainWidget) # Reset main window size and position pos = self.settings.getMainWindowPos() self.move(pos.x(), pos.y()) size = self.settings.getMainWindowSize() self.resize(size) # initialize the browser tree (add the top nodes and expand the saved path) self.mainWidget.browserWidget.initialize() def updateWindowTitle(self, title): self.setWindowTitle('{} - MynPad'.format(title)) def saveState(self): # Make sure that the current notepad page is saved self.mainWidget.editorWidget.save() # Note: there is no way to have eclipse shutdown the application faithfully, # see also http://stackoverflow.com/questions/677531/is-it-possible-for-eclipse-to-terminate-gently-instead-of-using-sigkill path = self.mainWidget.browserWidget.getCurrentPath() self.settings.setBrowserPath(path) self.settings.setMainWindowPos(self.pos()) self.settings.setMainWindowSize(self.size()) self.settings.save() # Close all notepads - TODO (HACK) for x in range (0, self.mainWidget.browserWidget.browserView.topLevelItemCount()): notepad = self.mainWidget.browserWidget.browserView.topLevelItem(x).getNotepad() notepad.close() def handleAbout(self): appVersion = "Development version" pythonVersion = "%s.%s.%s (%s)" % (sys.version_info[0], sys.version_info[1], sys.version_info[2], sys.version_info[3]) pyQtVersion = PYQT_VERSION_STR pyQtQtVersion = QT_VERSION_STR qtRuntimeVersion = qVersion() platformSystem = platform.system() platformRelease = platform.release() QMessageBox.about(self, "About MynPad", "Copyright \u00a9 2015 by Andreas Fester<br/>"+ "<table>"+ "<tr><th align=\"right\">Application version:</th><td>{}</td></tr>".format(appVersion) + "<tr><th align=\"right\">Python version:</th><td>{}</td></tr>".format(pythonVersion) + "<tr><th align=\"right\">PyQt version:</th><td>{} for Qt {}</td></tr>".format(pyQtVersion, pyQtQtVersion) + "<tr><th align=\"right\">Qt runtime version:</th><td>{}</td></tr>".format(qtRuntimeVersion)+ "<tr><th align=\"right\">Operating System:</th><td>{} {}</td></tr>".format(platformSystem, platformRelease)+ "<tr><th align=\"right\">sqlite version:</th><td>{}</td></tr>".format(sqlite3.version) + "<tr><th align=\"right\">sqlite runtime version:</th><td>{}</td></tr>".format(sqlite3.sqlite_version)+ "</table>")
class AppWindow(QMainWindow): def __init__(self, db_sess): super().__init__() self.setWindowTitle('Приложение пиццерии') self.db_sess = db_sess self.ordersInProgress = OrdersListWidget(self.db_sess, only_not_completed=True) self.setCentralWidget(self.ordersInProgress) self.to_orders_in_progress = QAction(self) self.to_orders_in_progress.setText('Текущие заказы') self.menuBar().addAction(self.to_orders_in_progress) self.to_orders_in_progress.triggered.connect( self.show_orders_in_progress) self.to_recent_orders = QAction(self) self.to_recent_orders.setText('Недавние заказы') self.menuBar().addAction(self.to_recent_orders) self.to_recent_orders.triggered.connect(self.show_recent_orders) self.to_categories_table = QAction(self) self.to_categories_table.setText('Категории') self.menuBar().addAction(self.to_categories_table) self.to_categories_table.triggered.connect(self.show_categories_table) self.to_dishes_table = QAction(self) self.to_dishes_table.setText('Блюда') self.menuBar().addAction(self.to_dishes_table) self.to_dishes_table.triggered.connect(self.show_dishes_table) self.to_versions_table = QAction(self) self.to_versions_table.setText('Версии блюд') self.menuBar().addAction(self.to_versions_table) self.to_versions_table.triggered.connect(self.show_versions_table) self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.setFixedSize( self.ordersInProgress.size().width(), self.ordersInProgress.size().height() + BOTTOM_PADDING) self.timer = QtCore.QTimer(self) self.timer.setInterval(UPDATE_FREQUENCY) self.timer.timeout.connect(self.update_orders_list) self.timer.start() def show_orders_in_progress(self): self.ordersInProgress = OrdersListWidget(self.db_sess, only_not_completed=True) self.setCentralWidget(self.ordersInProgress) def show_recent_orders(self): self.recentOrders = OrdersListWidget(self.db_sess, only_recent=True) self.setCentralWidget(self.recentOrders) def show_categories_table(self): self.categoriesTable = CategoriesTable(self.db_sess, self.message) self.setCentralWidget(self.categoriesTable) def show_dishes_table(self): self.dishesTable = DishesTable(self.db_sess, self.message) self.setCentralWidget(self.dishesTable) def show_versions_table(self): self.versionsTable = VersionsTable(self.db_sess, self.message) self.setCentralWidget(self.versionsTable) @QtCore.pyqtSlot() def update_orders_list(self): if isinstance(self.centralWidget(), OrdersListWidget): self.centralWidget().update_list() def message(self, text): self.statusbar.showMessage(text)
def __init__(self, persepolis_setting): super().__init__() # MainWindow self.persepolis_setting = persepolis_setting # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setWindowTitle( QCoreApplication.translate("mainwindow_ui_tr", "Persepolis Download Manager")) self.setWindowIcon( QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) # enable drag and drop self.setAcceptDrops(True) # frame self.frame = QFrame(self.centralwidget) # download_table_horizontalLayout download_table_horizontalLayout = QHBoxLayout() tabels_splitter = QSplitter(Qt.Horizontal) # category_tree self.category_tree_qwidget = QWidget(self) category_tree_verticalLayout = QVBoxLayout() self.category_tree = CategoryTreeView(self) category_tree_verticalLayout.addWidget(self.category_tree) self.category_tree_model = QStandardItemModel() self.category_tree.setModel(self.category_tree_model) category_table_header = [ QCoreApplication.translate("mainwindow_ui_tr", 'Category') ] self.category_tree_model.setHorizontalHeaderLabels( category_table_header) self.category_tree.header().setStretchLastSection(True) self.category_tree.header().setDefaultAlignment(Qt.AlignCenter) # queue_panel self.queue_panel_widget = QWidget(self) queue_panel_verticalLayout_main = QVBoxLayout(self.queue_panel_widget) # queue_panel_show_button self.queue_panel_show_button = QPushButton(self) queue_panel_verticalLayout_main.addWidget(self.queue_panel_show_button) # queue_panel_widget_frame self.queue_panel_widget_frame = QFrame(self) self.queue_panel_widget_frame.setFrameShape(QFrame.StyledPanel) self.queue_panel_widget_frame.setFrameShadow(QFrame.Raised) queue_panel_verticalLayout_main.addWidget( self.queue_panel_widget_frame) queue_panel_verticalLayout = QVBoxLayout(self.queue_panel_widget_frame) queue_panel_verticalLayout_main.setContentsMargins(50, -1, 50, -1) # start_end_frame self.start_end_frame = QFrame(self) # start time start_verticalLayout = QVBoxLayout(self.start_end_frame) self.start_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) start_frame_verticalLayout = QVBoxLayout(self.start_frame) self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame) self.start_time_qDataTimeEdit.setDisplayFormat('H:mm') start_frame_verticalLayout.addWidget(self.start_time_qDataTimeEdit) start_verticalLayout.addWidget(self.start_frame) # end time self.end_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) end_frame_verticalLayout = QVBoxLayout(self.end_frame) self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame) self.end_time_qDateTimeEdit.setDisplayFormat('H:mm') end_frame_verticalLayout.addWidget(self.end_time_qDateTimeEdit) start_verticalLayout.addWidget(self.end_frame) self.reverse_checkBox = QCheckBox(self) start_verticalLayout.addWidget(self.reverse_checkBox) queue_panel_verticalLayout.addWidget(self.start_end_frame) # limit_after_frame self.limit_after_frame = QFrame(self) # limit_checkBox limit_verticalLayout = QVBoxLayout(self.limit_after_frame) self.limit_checkBox = QCheckBox(self) limit_verticalLayout.addWidget(self.limit_checkBox) # limit_frame self.limit_frame = QFrame(self) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) limit_verticalLayout.addWidget(self.limit_frame) limit_frame_verticalLayout = QVBoxLayout(self.limit_frame) # limit_spinBox limit_frame_horizontalLayout = QHBoxLayout() self.limit_spinBox = QDoubleSpinBox(self) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) limit_frame_horizontalLayout.addWidget(self.limit_spinBox) # limit_comboBox self.limit_comboBox = QComboBox(self) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") limit_frame_horizontalLayout.addWidget(self.limit_comboBox) limit_frame_verticalLayout.addLayout(limit_frame_horizontalLayout) # limit_pushButton self.limit_pushButton = QPushButton(self) limit_frame_verticalLayout.addWidget(self.limit_pushButton) # after_checkBox self.after_checkBox = QtWidgets.QCheckBox(self) limit_verticalLayout.addWidget(self.after_checkBox) # after_frame self.after_frame = QtWidgets.QFrame(self) self.after_frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.after_frame.setFrameShadow(QtWidgets.QFrame.Raised) limit_verticalLayout.addWidget(self.after_frame) after_frame_verticalLayout = QVBoxLayout(self.after_frame) # after_comboBox self.after_comboBox = QComboBox(self) self.after_comboBox.addItem("") after_frame_verticalLayout.addWidget(self.after_comboBox) # after_pushButton self.after_pushButton = QPushButton(self) after_frame_verticalLayout.addWidget(self.after_pushButton) queue_panel_verticalLayout.addWidget(self.limit_after_frame) category_tree_verticalLayout.addWidget(self.queue_panel_widget) # keep_awake_checkBox self.keep_awake_checkBox = QCheckBox(self) queue_panel_verticalLayout.addWidget(self.keep_awake_checkBox) self.category_tree_qwidget.setLayout(category_tree_verticalLayout) tabels_splitter.addWidget(self.category_tree_qwidget) # download table widget self.download_table_content_widget = QWidget(self) download_table_content_widget_verticalLayout = QVBoxLayout( self.download_table_content_widget) self.download_table = DownloadTableWidget(self) download_table_content_widget_verticalLayout.addWidget( self.download_table) tabels_splitter.addWidget(self.download_table_content_widget) self.download_table.setColumnCount(13) self.download_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.download_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.download_table.verticalHeader().hide() # hide gid and download dictioanry section self.download_table.setColumnHidden(8, True) self.download_table.setColumnHidden(9, True) download_table_header = [ QCoreApplication.translate("mainwindow_ui_tr", 'File Name'), QCoreApplication.translate("mainwindow_ui_tr", 'Status'), QCoreApplication.translate("mainwindow_ui_tr", 'Size'), QCoreApplication.translate("mainwindow_ui_tr", 'Downloaded'), QCoreApplication.translate("mainwindow_ui_tr", 'Percentage'), QCoreApplication.translate("mainwindow_ui_tr", 'Connections'), QCoreApplication.translate("mainwindow_ui_tr", 'Transfer rate'), QCoreApplication.translate("mainwindow_ui_tr", 'Estimated time left'), 'Gid', QCoreApplication.translate("mainwindow_ui_tr", 'Link'), QCoreApplication.translate("mainwindow_ui_tr", 'First try date'), QCoreApplication.translate("mainwindow_ui_tr", 'Last try date'), QCoreApplication.translate("mainwindow_ui_tr", 'Category') ] self.download_table.setHorizontalHeaderLabels(download_table_header) # fixing the size of download_table when window is Maximized! self.download_table.horizontalHeader().setSectionResizeMode(0) self.download_table.horizontalHeader().setStretchLastSection(True) tabels_splitter.setStretchFactor(0, 3) # category_tree width tabels_splitter.setStretchFactor(1, 10) # ratio of tables's width download_table_horizontalLayout.addWidget(tabels_splitter) self.frame.setLayout(download_table_horizontalLayout) self.verticalLayout.addWidget(self.frame) self.setCentralWidget(self.centralwidget) # menubar self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 600, 24)) self.setMenuBar(self.menubar) fileMenu = self.menubar.addMenu( QCoreApplication.translate("mainwindow_ui_tr", '&File')) editMenu = self.menubar.addMenu( QCoreApplication.translate("mainwindow_ui_tr", '&Edit')) viewMenu = self.menubar.addMenu( QCoreApplication.translate("mainwindow_ui_tr", '&View')) downloadMenu = self.menubar.addMenu( QCoreApplication.translate("mainwindow_ui_tr", '&Download')) queueMenu = self.menubar.addMenu( QCoreApplication.translate("mainwindow_ui_tr", '&Queue')) videoFinderMenu = self.menubar.addMenu( QCoreApplication.translate("mainwindow_ui_tr", 'V&ideo Finder')) helpMenu = self.menubar.addMenu( QCoreApplication.translate("mainwindow_ui_tr", '&Help')) # viewMenu submenus sortMenu = viewMenu.addMenu( QCoreApplication.translate("mainwindow_ui_tr", 'Sort by')) # statusbar self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.statusbar.showMessage( QCoreApplication.translate("mainwindow_ui_tr", "Persepolis Download Manager")) # toolBar self.toolBar2 = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar2) self.toolBar2.setWindowTitle( QCoreApplication.translate("mainwindow_ui_tr", 'Menu')) self.toolBar2.setFloatable(False) self.toolBar2.setMovable(False) self.toolBar = QToolBar(self) self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.toolBar.setWindowTitle( QCoreApplication.translate("mainwindow_ui_tr", 'Toolbar')) self.toolBar.setFloatable(False) self.toolBar.setMovable(False) #toolBar and menubar and actions self.videoFinderAddLinkAction = QAction( QIcon(icons + 'video_finder'), QCoreApplication.translate("mainwindow_ui_tr", 'Find Video Links'), self, statusTip=QCoreApplication.translate( "mainwindow_ui_tr", 'Download video or audio from Youtube, Vimeo, etc...'), triggered=self.showVideoFinderAddLinkWindow) QShortcut(QKeySequence('Ctrl+I'), self, self.showVideoFinderAddLinkWindow) videoFinderMenu.addAction(self.videoFinderAddLinkAction) self.stopAllAction = QAction(QIcon(icons + 'stop_all'), QCoreApplication.translate( "mainwindow_ui_tr", 'Stop all active downloads'), self, statusTip='Stop all active downloads', triggered=self.stopAllDownloads) downloadMenu.addAction(self.stopAllAction) self.sort_file_name_Action = QAction(QCoreApplication.translate( "mainwindow_ui_tr", 'File name'), self, triggered=self.sortByName) sortMenu.addAction(self.sort_file_name_Action) self.sort_file_size_Action = QAction(QCoreApplication.translate( "mainwindow_ui_tr", 'File size'), self, triggered=self.sortBySize) sortMenu.addAction(self.sort_file_size_Action) self.sort_first_try_date_Action = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'First try date'), self, triggered=self.sortByFirstTry) sortMenu.addAction(self.sort_first_try_date_Action) self.sort_last_try_date_Action = QAction(QCoreApplication.translate( "mainwindow_ui_tr", 'Last try date'), self, triggered=self.sortByLastTry) sortMenu.addAction(self.sort_last_try_date_Action) self.sort_download_status_Action = QAction(QCoreApplication.translate( "mainwindow_ui_tr", 'Download status'), self, triggered=self.sortByStatus) sortMenu.addAction(self.sort_download_status_Action) self.trayAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show system tray icon'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Show/Hide system tray icon"), triggered=self.showTray) self.trayAction.setCheckable(True) viewMenu.addAction(self.trayAction) self.showMenuBarAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'), triggered=self.showMenuBar) self.showMenuBarAction.setCheckable(True) viewMenu.addAction(self.showMenuBarAction) self.showSidePanelAction = QAction( QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'), triggered=self.showSidePanel) self.showSidePanelAction.setCheckable(True) viewMenu.addAction(self.showSidePanelAction) self.minimizeAction = QAction( QIcon(icons + 'minimize'), QCoreApplication.translate("mainwindow_ui_tr", 'Minimize to system tray'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Minimize to system tray"), triggered=self.minMaxTray) QShortcut(QKeySequence('Ctrl+W'), self, self.minMaxTray) viewMenu.addAction(self.minimizeAction) self.addlinkAction = QAction( QIcon(icons + 'add'), QCoreApplication.translate("mainwindow_ui_tr", 'Add New Download Link'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Add New Download Link"), triggered=self.addLinkButtonPressed) QShortcut(QKeySequence('Ctrl+N'), self, self.addLinkButtonPressed) fileMenu.addAction(self.addlinkAction) self.addtextfileAction = QAction( QIcon(icons + 'file'), QCoreApplication.translate("mainwindow_ui_tr", 'Import links from text file'), self, statusTip=QCoreApplication.translate( "mainwindow_ui_tr", 'Create a Text file and put links in it.line by line!'), triggered=self.importText) fileMenu.addAction(self.addtextfileAction) self.resumeAction = QAction( QIcon(icons + 'play'), QCoreApplication.translate("mainwindow_ui_tr", 'Resume Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Resume Download"), triggered=self.resumeButtonPressed) QShortcut(QKeySequence('Ctrl+R'), self, self.resumeButtonPressed) downloadMenu.addAction(self.resumeAction) self.pauseAction = QAction( QIcon(icons + 'pause'), QCoreApplication.translate("mainwindow_ui_tr", 'Pause Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Pause Download"), triggered=self.pauseButtonPressed) QShortcut(QKeySequence('Ctrl+C'), self, self.pauseButtonPressed) downloadMenu.addAction(self.pauseAction) self.stopAction = QAction( QIcon(icons + 'stop'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop Download'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Stop/Cancel Download"), triggered=self.stopButtonPressed) QShortcut(QKeySequence('Ctrl+S'), self, self.stopButtonPressed) downloadMenu.addAction(self.stopAction) self.propertiesAction = QAction( QIcon(icons + 'setting'), QCoreApplication.translate("mainwindow_ui_tr", 'Properties'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Properties"), triggered=self.propertiesButtonPressed) QShortcut(QKeySequence('Ctrl+P'), self, self.propertiesButtonPressed) downloadMenu.addAction(self.propertiesAction) self.progressAction = QAction( QIcon(icons + 'window'), QCoreApplication.translate("mainwindow_ui_tr", 'Progress'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Progress"), triggered=self.progressButtonPressed) QShortcut(QKeySequence('Ctrl+Z'), self, self.progressButtonPressed) downloadMenu.addAction(self.progressAction) self.openFileAction = QAction( QIcon(icons + 'file'), QCoreApplication.translate("mainwindow_ui_tr", 'Open file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open file'), triggered=self.openFile) fileMenu.addAction(self.openFileAction) self.openDownloadFolderAction = QAction( QIcon(icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'Open download folder'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Open download folder'), triggered=self.openDownloadFolder) fileMenu.addAction(self.openDownloadFolderAction) self.openDefaultDownloadFolderAction = QAction( QIcon(icons + 'folder'), QCoreApplication.translate("mainwindow_ui_tr", 'Open default download folder'), self, statusTip=QCoreApplication.translate( "mainwindow_ui_tr", 'Open default download folder'), triggered=self.openDefaultDownloadFolder) fileMenu.addAction(self.openDefaultDownloadFolderAction) self.exitAction = QAction( QIcon(icons + 'exit'), QCoreApplication.translate("mainwindow_ui_tr", 'Exit'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Exit"), triggered=self.closeEvent) QShortcut(QKeySequence('Ctrl+Q'), self, self.closeEvent) fileMenu.addAction(self.exitAction) self.clearAction = QAction(QIcon(icons + 'multi_remove'), QCoreApplication.translate( "mainwindow_ui_tr", 'Clear download list'), self, statusTip=QCoreApplication.translate( "mainwindow_ui_tr", 'Clear all items in download list'), triggered=self.clearDownloadList) editMenu.addAction(self.clearAction) self.removeSelectedAction = QAction( QIcon(icons + 'remove'), QCoreApplication.translate("mainwindow_ui_tr", 'Remove selected downloads from list'), self, statusTip=QCoreApplication.translate( "mainwindow_ui_tr", 'Remove selected downloads form list'), triggered=self.removeSelected) editMenu.addAction(self.removeSelectedAction) self.removeSelectedAction.setEnabled(False) self.deleteSelectedAction = QAction( QIcon(icons + 'trash'), QCoreApplication.translate("mainwindow_ui_tr", 'Delete selected download files'), self, statusTip=QCoreApplication.translate( "mainwindow_ui_tr", 'Delete selected download files'), triggered=self.deleteSelected) editMenu.addAction(self.deleteSelectedAction) self.deleteSelectedAction.setEnabled(False) self.createQueueAction = QAction( QIcon(icons + 'add_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Create new queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Create new download queue'), triggered=self.createQueue) queueMenu.addAction(self.createQueueAction) self.removeQueueAction = QAction( QIcon(icons + 'remove_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Remove this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Remove this queue'), triggered=self.removeQueue) queueMenu.addAction(self.removeQueueAction) self.startQueueAction = QAction( QIcon(icons + 'start_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'), triggered=self.startQueue) queueMenu.addAction(self.startQueueAction) self.stopQueueAction = QAction( QIcon(icons + 'stop_queue'), QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'), triggered=self.stopQueue) queueMenu.addAction(self.stopQueueAction) self.moveUpSelectedAction = QAction( QIcon(icons + 'multi_up'), QCoreApplication.translate("mainwindow_ui_tr", 'Move up selected items'), self, statusTip=QCoreApplication.translate( "mainwindow_ui_tr", 'Move currently selected items up by one row'), triggered=self.moveUpSelected) queueMenu.addAction(self.moveUpSelectedAction) self.moveDownSelectedAction = QAction( QIcon(icons + 'multi_down'), QCoreApplication.translate("mainwindow_ui_tr", 'Move down selected items'), self, statusTip=QCoreApplication.translate( "mainwindow_ui_tr", 'Move currently selected items down by one row'), triggered=self.moveDownSelected) queueMenu.addAction(self.moveDownSelectedAction) self.preferencesAction = QAction( QIcon(icons + 'preferences'), QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'), triggered=self.openPreferences, menuRole=5) editMenu.addAction(self.preferencesAction) self.aboutAction = QAction( QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'About'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'About'), triggered=self.openAbout, menuRole=4) helpMenu.addAction(self.aboutAction) self.issueAction = QAction( QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'), triggered=self.reportIssue) helpMenu.addAction(self.issueAction) self.updateAction = QAction( QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Check for newer version'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Check for newer release'), triggered=self.newUpdate) helpMenu.addAction(self.updateAction) self.logAction = QAction( QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Show log file'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'), triggered=self.showLog) helpMenu.addAction(self.logAction) self.helpAction = QAction( QIcon(icons + 'about'), QCoreApplication.translate("mainwindow_ui_tr", 'Help'), self, statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'), triggered=self.persepolisHelp) helpMenu.addAction(self.helpAction) self.qmenu = MenuWidget(self) self.toolBar2.addWidget(self.qmenu) # labels self.queue_panel_show_button.setText( QCoreApplication.translate("mainwindow_ui_tr", "Hide options")) self.start_checkBox.setText( QCoreApplication.translate("mainwindow_ui_tr", "Start Time")) self.end_checkBox.setText( QCoreApplication.translate("mainwindow_ui_tr", "End Time")) self.reverse_checkBox.setText( QCoreApplication.translate("mainwindow_ui_tr", "Download bottom of\n the list first")) self.limit_checkBox.setText( QCoreApplication.translate("mainwindow_ui_tr", "Limit Speed")) self.limit_comboBox.setItemText(0, "KiB/s") self.limit_comboBox.setItemText(1, "MiB/s") self.limit_pushButton.setText( QCoreApplication.translate("mainwindow_ui_tr", "Apply")) self.after_checkBox.setText( QCoreApplication.translate("mainwindow_ui_tr", "After download")) self.after_comboBox.setItemText( 0, QCoreApplication.translate("mainwindow_ui_tr", "Shut Down")) self.keep_awake_checkBox.setText( QCoreApplication.translate("mainwindow_ui_tr", "Keep system awake!")) self.keep_awake_checkBox.setToolTip( QCoreApplication.translate( "mainwindow_ui_tr", "<html><head/><body><p>This option is preventing system from going to sleep.\ This is necessary if your power manager is suspending system automatically. </p></body></html>" )) self.after_pushButton.setText( QCoreApplication.translate("mainwindow_ui_tr", "Apply"))
class VideoPlayer(QWidget): def __init__(self, filename, parent=None): super(VideoPlayer, self).__init__(parent) self.fileName = filename self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) btnSize = QSize(16, 16) videoWidget = QVideoWidget() self.playButton = QPushButton() self.playButton.setEnabled(True) self.playButton.setFixedHeight(24) self.playButton.setIconSize(btnSize) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) self.statusBar = QStatusBar() self.statusBar.setFont(QFont("Noto Sans", 7)) self.statusBar.setFixedHeight(14) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) layout = QVBoxLayout() layout.addWidget(videoWidget) layout.addLayout(controlLayout) layout.addWidget(self.statusBar) self.setLayout(layout) self.mediaPlayer.setVideoOutput(videoWidget) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.error.connect(self.handleError) self.statusBar.showMessage("Ready") self.abrir() def abrir(self): if self.fileName != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(self.fileName))) self.playButton.setEnabled(True) self.statusBar.showMessage(self.fileName) def play(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() def mediaStateChanged(self, state): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playButton.setIcon(self.style().standardIcon( QStyle.SP_MediaPause)) else: self.playButton.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) def positionChanged(self, position): self.positionSlider.setValue(position) def durationChanged(self, duration): self.positionSlider.setRange(0, duration) def setPosition(self, position): self.mediaPlayer.setPosition(position) def handleError(self): self.playButton.setEnabled(False) self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())
class EditorMainWindow(QMainWindow): def __init__(self): super().__init__() self.setupUi(self) self.retranslateUi(self) self.level = None path = get_default_path() if path is None: self.default_path = "" else: self.default_path = path self.dragging = False self.last_x = None self.last_y = None self.dragged_time = None self.deleting_item = False # Hack for preventing focusing on next item after deleting the previous one self.moving = False self.resetting = False self.entity_list_widget.currentItemChanged.connect(self.action_listwidget_change_selection) self.button_zoom_in.pressed.connect(self.zoom_in) self.button_zoom_out.pressed.connect(self.zoom_out) self.button_remove_entity.pressed.connect(self.remove_position) self.button_move_entity.pressed.connect(self.move_entity) self.button_clone_entity.pressed.connect(self.action_clone_entity) self.button_show_passengers.pressed.connect(self.action_passenger_window) self.button_edit_xml.pressed.connect(self.action_open_xml_editor) self.button_edit_base_xml.pressed.connect(self.action_open_basexml_editor) self.lineedit_angle.editingFinished.connect(self.action_lineedit_changeangle) self.bw_map_screen.mouse_clicked.connect(self.get_position) self.bw_map_screen.entity_clicked.connect(self.entity_position) self.bw_map_screen.mouse_dragged.connect(self.mouse_move) self.bw_map_screen.mouse_released.connect(self.mouse_release) self.bw_map_screen.mouse_wheel.connect(self.mouse_wheel_scroll_zoom) status = self.statusbar self.bw_map_screen.setMouseTracking(True) self.passenger_window = BWPassengerWindow() self.passenger_window.passengerlist.currentItemChanged.connect(self.passengerwindow_action_choose_entity) self.xmlobject_textbox = BWEntityXMLEditor() self.xmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_object_xml) self.xmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited) self.basexmlobject_textbox = BWEntityXMLEditor(windowtype="XML Base Object") self.basexmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_base_object_xml) self.basexmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited) self.types_visible = {} self.terrain_image = None status.showMessage("Ready") self.xml_windows = {} print("We are now ready!") def reset(self): self.resetting = True self.statusbar.clearMessage() self.dragged_time = None self.moving = False self.dragging = False self.last_x = None self.last_y = None self.dragged_time = None self.moving = False self.entity_list_widget.clearSelection() self.entity_list_widget.clear() self.bw_map_screen.reset() self.clear_visibility_toggles() for window in (self.passenger_window, self.xmlobject_textbox, self.basexmlobject_textbox): window.close() window.reset() for id in self.xml_windows: self.destroy_xml_editor(id) self.resetting = False print("reset done") def destroy_xml_editor(self, id): pass @catch_exception def open_xml_editor(self, objectid, offsetx=0, offsety=0): selected = objectid if self.level is not None and selected in self.level.obj_map: delete = [] for objid, window in self.xml_windows.items(): if not window.isVisible() and objid != selected: window.destroy() delete.append(objid) for objid in delete: del self.xml_windows[objid] if selected == self.basexmlobject_textbox.entity or selected == self.xmlobject_textbox.entity: pass # No need to make a new window elif selected in self.xml_windows and self.xml_windows[selected].isVisible(): self.xml_windows[selected].activateWindow() self.xml_windows[selected].update() else: xml_window = BWEntityXMLEditor() def xmleditor_save_object_unlimited(): self.statusbar.showMessage("Saving object changes...") try: xmlnode = xml_window.get_content() #assert self.bw_map_screen.current_entity == self.basexmlobject_textbox.entity assert xml_window.entity == xmlnode.get("id") # Disallow changing the id of the base object self.level.remove_object(xmlnode.get("id")) self.level.add_object(xmlnode) self.statusbar.showMessage("Saved base object {0} as {1}".format( xml_window.entity, self.level.obj_map[xmlnode.get("id")].name)) except: self.statusbar.showMessage("Saving object failed") traceback.print_exc() xml_window.button_xml_savetext.pressed.connect(xmleditor_save_object_unlimited) xml_window.triggered.connect(self.action_open_xml_editor_unlimited) obj = self.level.obj_map[selected] xml_window.set_title(obj.name) xml_window.set_content(obj._xml_node) #xml_window.move(QPoint(xml_editor_owner.pos().x()+20, xml_editor_owner.pos().y()+20)) xml_window.move(QPoint(offsetx, offsety)) xml_window.show() xml_window.update() self.xml_windows[selected] = xml_window @catch_exception def action_open_xml_editor_unlimited(self, xml_editor_owner): selected = xml_editor_owner.textbox_xml.textCursor().selectedText() self.open_xml_editor(selected, offsetx=xml_editor_owner.pos().x()+20, offsety=xml_editor_owner.pos().y()+20) @catch_exception def action_open_basexml_editor(self): """ if not self.basexmlobject_textbox.isVisible(): self.basexmlobject_textbox.destroy() self.basexmlobject_textbox = BWEntityXMLEditor(windowtype="XML Base Object") self.basexmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_base_object_xml) self.basexmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited) self.basexmlobject_textbox.show() self.basexmlobject_textbox.activateWindow()""" if self.level is not None and self.bw_map_screen.current_entity is not None: obj = self.level.obj_map[self.bw_map_screen.current_entity] if not obj.has_attr("mBase"): pass else: baseobj = self.level.obj_map[obj.get_attr_value("mBase")] #self.basexmlobject_textbox.set_title(baseobj.id) self.open_xml_editor(baseobj.id) def xmleditor_action_save_base_object_xml(self): self.statusbar.showMessage("Saving base object changes...") try: xmlnode = self.basexmlobject_textbox.get_content() #assert self.bw_map_screen.current_entity == self.basexmlobject_textbox.entity assert self.basexmlobject_textbox.entity == xmlnode.get("id") # Disallow changing the id of the base object self.level.remove_object(xmlnode.get("id")) self.level.add_object(xmlnode) self.statusbar.showMessage("Saved base object {0} as {1}".format( self.basexmlobject_textbox.entity, self.level.obj_map[xmlnode.get("id")].name)) except: self.statusbar.showMessage("Saving base object failed") traceback.print_exc() def action_open_xml_editor(self): """ if not self.xmlobject_textbox.isVisible(): self.xmlobject_textbox.destroy() self.xmlobject_textbox = BWEntityXMLEditor() self.xmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_object_xml) self.xmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited) self.xmlobject_textbox.show() self.xmlobject_textbox.activateWindow()""" if self.level is not None and self.bw_map_screen.current_entity is not None: entityobj = self.level.obj_map[self.bw_map_screen.current_entity] self.open_xml_editor(objectid=entityobj.id) update_mapscreen(self.bw_map_screen, self.level.obj_map[entityobj.id]) self.bw_map_screen.update() """self.xmlobject_textbox.set_title(entityobj.id) self.xmlobject_textbox.set_content(entityobj._xml_node) self.xmlobject_textbox.update()""" def xmleditor_action_save_object_xml(self): self.statusbar.showMessage("Saving object changes...") try: xmlnode = self.xmlobject_textbox.get_content() #assert self.bw_map_screen.current_entity == self.xmlobject_textbox.entity assert self.xmlobject_textbox.entity == xmlnode.get("id") or xmlnode.get("id") not in self.level.obj_map if self.passenger_window.isVisible(): self.passenger_window.close() if self.xmlobject_textbox.entity != xmlnode.get("id"): #obj = self.level.obj_map[xmlnode.get("id")] self.level.remove_object(self.xmlobject_textbox.entity) print("adding", xmlnode.get("id"), xmlnode.get("id") in self.level.obj_map ) self.level.add_object(xmlnode) pos = self.get_entity_item_pos(self.xmlobject_textbox.entity) item = self.entity_list_widget.takeItem(pos) self.entity_list_widget.removeItemWidget(item) self.add_item_sorted(xmlnode.get("id")) self.bw_map_screen.rename_entity(self.xmlobject_textbox.entity, xmlnode.get("id")) assert xmlnode.get("id") in self.level.obj_map self.xmlobject_textbox.entity = xmlnode.get("id") self.xmlobject_textbox.set_title(xmlnode.get("id")) else: self.level.remove_object(xmlnode.get("id")) self.level.add_object(xmlnode) update_mapscreen(self.bw_map_screen, self.level.obj_map[xmlnode.get("id")]) self.statusbar.showMessage("Saved object {0} as {1}".format( self.xmlobject_textbox.entity, self.level.obj_map[xmlnode.get("id")].name)) self.bw_map_screen.update() except: self.statusbar.showMessage("Saving object failed") traceback.print_exc() def action_clone_entity(self): entities = [] if self.bw_map_screen.current_entity is not None: entities.append(self.bw_map_screen.current_entity) elif len(self.bw_map_screen.selected_entities) > 0: entities.extend(self.bw_map_screen.selected_entities.keys()) if len(entities) > 0: dont_clone = {} for entity in entities: obj = self.level.obj_map[entity] if obj.has_attr("mPassenger"): passengers = obj.get_attr_elements("mPassenger") for passenger in passengers: if passenger != "0": dont_clone[passenger] = True select = [] for entity in entities: if entity in dont_clone: continue obj = self.level.obj_map[entity] xml_node = deepcopy(obj._xml_node) try: cloned_id = self.level.generate_unique_id(entity) xml_node.set("id", cloned_id) self.level.add_object(xml_node) bw_x, bw_y, angle = object_get_position(self.level, cloned_id) x, y = bw_coords_to_image_coords(bw_x, bw_y) self.add_item_sorted(cloned_id) self.bw_map_screen.add_entity(x, y, cloned_id, obj.type) clonedobj = self.level.obj_map[cloned_id] select.append(cloned_id) update_mapscreen(self.bw_map_screen, clonedobj) if clonedobj.has_attr("mPassenger"): orig_x = bw_x orig_y = bw_y passengers = clonedobj.get_attr_elements("mPassenger") passengers_added = [] for i, passenger in enumerate(passengers): if passenger != "0": obj = self.level.obj_map[passenger] xml_node = deepcopy(obj._xml_node) clonedpassenger_id = self.level.generate_unique_id(passenger) xml_node.set("id", clonedpassenger_id) #print("orig passenger: {0}, new passenger: {1}, alreadyexists: {2}".format( # passenger, clonedpassenger_id, clonedpassenger_id in self.level.obj_map #)) #print(type(passenger), type(clonedpassenger_id)) self.level.add_object(xml_node) #x, y = object_get_position(self.level, newid) x = orig_x + (i+1)*8 y = orig_y + (i+1)*8 #print(orig_x, orig_y, x, y) object_set_position(self.level, clonedpassenger_id, x, y) x, y = bw_coords_to_image_coords(x, y) self.add_item_sorted(clonedpassenger_id) self.bw_map_screen.add_entity(x, y, clonedpassenger_id, obj.type) update_mapscreen(self.bw_map_screen, self.level.obj_map[clonedpassenger_id]) passengers_added.append(passenger) clonedobj.set_attr_value("mPassenger", clonedpassenger_id, i) select.append(clonedpassenger_id) #print("passengers added:", passengers_added) self.bw_map_screen.selected_entities = {} if len(select) == 1: ent = select[0] self.set_entity_text(ent) self.bw_map_screen.choose_entity(ent) else: for ent in select: self.bw_map_screen.selected_entities[ent] = True self.set_entity_text_multiple(self.bw_map_screen.selected_entities) self.bw_map_screen.update() except: traceback.print_exc() def add_item_sorted(self, entity): max_count = self.entity_list_widget.count() entityobj = self.level.obj_map[entity] index = 0 entity_item = BWEntityEntry(entity, "{0}[{1}]".format(entity, entityobj.type)) # Similar to loading a level, we add the entity in a sorted way by # creating this string and comparing it for every item in the list. entity_string = get_type(entityobj.type)+entityobj.type+entityobj.id inserted = False for i in range(max_count): curritem = self.entity_list_widget.item(i) currobj = self.level.obj_map[curritem.xml_ref] currstring = get_type(currobj.type)+currobj.type+currobj.id # The list is already sorted, so if we find an item bigger than # the one we are inserting, we know the position we have to insert the item in. # String comparison should be alpabetically. if currstring > entity_string: self.entity_list_widget.insertItem(i, entity_item) inserted = True break # If we couldn't insert the item, i.e. there are no items at all # or all items are smaller than the item we add, we just add it at the end. if not inserted: self.entity_list_widget.addItem(entity_item) def get_entity_item_pos(self, entityid): for i in range(self.entity_list_widget.count()): item = self.entity_list_widget.item(i) if item.xml_ref == entityid: return i return None def action_passenger_window(self): #if self.passenger_window.isVisible() print("window is visible: ", self.passenger_window.isVisible()) #self.passenger_window.reset() if not self.passenger_window.isVisible(): self.passenger_window.destroy() self.passenger_window = BWPassengerWindow() self.passenger_window.passengerlist.currentItemChanged.connect(self.passengerwindow_action_choose_entity) self.passenger_window.show() self.passenger_window.activateWindow() if self.bw_map_screen.current_entity is not None: self.passenger_window.reset() entityobj = self.level.obj_map[self.bw_map_screen.current_entity] self.passenger_window.set_title(entityobj.id) if entityobj.has_attr("mPassenger"): for i, passenger in enumerate(entityobj.get_attr_elements("mPassenger")): if passenger in self.level.obj_map: passengerobj = self.level.obj_map[passenger] list_item_name = "{0}[{1}]".format(passenger, passengerobj.type) elif passenger == "0": list_item_name = "{0}<none>".format(passenger) else: list_item_name = "{0}<missing>".format(passenger) self.passenger_window.add_passenger(list_item_name, passenger) self.passenger_window.update() def passengerwindow_action_choose_entity(self, current, previous): try: if current is not None and current.xml_ref in self.level.obj_map: self.set_entity_text(current.xml_ref) self.bw_map_screen.choose_entity(current.xml_ref) elif current is not None: self.statusbar.showMessage("No such entity: {0}".format(current.xml_ref), 1000*2) except: traceback.print_exc() def move_entity(self): if not self.dragging: if not self.moving: self.moving = True currtext = self.button_move_entity.text() self.button_move_entity.setText("Stop [Move Entity]") else: self.moving = False currtext = "Move Entity" self.button_move_entity.setText(currtext) def button_load_level(self): try: print("ok", self.default_path) self.xmlPath = "" filepath, choosentype = QFileDialog.getOpenFileName( self, "Open File", self.default_path, BW_LEVEL+";;"+BW_COMPRESSED_LEVEL+";;All files (*)") print("doooone") if filepath: print("resetting") self.reset() print("done") print("chosen type:",choosentype) # Some BW levels are clear XML files, some are compressed with GZIP # We decide between the two either based on user choice or end of filepath if choosentype == BW_COMPRESSED_LEVEL or filepath.endswith(".gz"): print("OPENING AS COMPRESSED") file_open = gzip.open else: file_open = open with file_open(filepath, "rb") as f: try: self.level = BattWarsLevel(f) self.default_path = filepath set_default_path(filepath) self.setup_visibility_toggles() for obj_id, obj in sorted(self.level.obj_map.items(), key=lambda x: get_type(x[1].type)+x[1].type+x[1].id): #print("doing", obj_id) if get_position_attribute(obj) is None: continue #if not obj.has_attr("Mat"): # continue x, y, angle = object_get_position(self.level, obj_id) assert type(x) != str x, y = bw_coords_to_image_coords(x, y) item = BWEntityEntry(obj_id, "{0}[{1}]".format(obj_id, obj.type)) self.entity_list_widget.addItem(item) self.bw_map_screen.add_entity(x, y, obj_id, obj.type, update=False) #if obj.type == "cMapZone": update_mapscreen(self.bw_map_screen, obj) print("ok") self.bw_map_screen.update() path_parts = path.split(filepath) self.setWindowTitle("BW-MapEdit - {0}".format(path_parts[-1])) except Exception as error: print("error", error) traceback.print_exc() except Exception as er: print("errrorrr", er) traceback.print_exc() print("loaded") def button_save_level(self): if self.level is not None: filepath, choosentype = QFileDialog.getSaveFileName( self, "Save File", self.default_path, BW_LEVEL+";;"+BW_COMPRESSED_LEVEL+";;All files (*)") print(filepath, "saved") if filepath: # Simiar to load level if choosentype == BW_COMPRESSED_LEVEL or filepath.endswith(".gz"): file_open = gzip.open else: file_open = open try: with file_open(filepath, "wb") as f: self.level._tree.write(f) except Exception as error: print("COULDN'T SAVE:", error) traceback.print_exc() self.default_path = filepath else: pass # no level loaded, do nothing def entity_position(self, event, entity): try: # Make it possible to select objects in move mode, but don't make it too easy to lose # a selection. if not (self.moving and len(self.bw_map_screen.selected_entities) > 1): print("got entity:",entity, self.bw_map_screen.entities[entity][2]) print(entity_get_model(self.level, entity)) self.set_entity_text(entity) self.bw_map_screen.choose_entity(entity) pos = self.get_entity_item_pos(entity) print("searching:",pos) try: self.entity_list_widget.select_item(pos) except: traceback.print_exc() self.bw_map_screen.selected_entities = {} self.bw_map_screen.update() except: traceback.print_exc() def remove_position(self): #self.bw_map_screen.entities.pop() try: # Remove the entity from the map, the list widget and the level data self.deleting_item = True entities = [] if self.bw_map_screen.current_entity is not None: entities.append(self.bw_map_screen.current_entity) elif len(self.bw_map_screen.selected_entities) > 0: entities.extend(self.bw_map_screen.selected_entities.keys()) self.bw_map_screen.selected_entities = {} self.set_entity_text_multiple(self.bw_map_screen.selected_entities) if len(entities) > 0: for entity in entities: pos = self.get_entity_item_pos(entity) item = self.entity_list_widget.takeItem(pos) assert item.xml_ref == entity #self.entity_list_widget.clearSelection() self.entity_list_widget.clearFocus() self.entity_list_widget.removeItemWidget(item) self.level.remove_object(entity) self.bw_map_screen.remove_entity(entity) self.bw_map_screen.update() except: traceback.print_exc() raise #@catch_exception def get_position(self, event): self.dragging = True self.last_x = event.x() self.last_y = event.y() self.dragged_time = default_timer() mouse_x = event.x()/self.bw_map_screen.zoom_factor mouse_y = event.y()/self.bw_map_screen.zoom_factor if event.buttons() == QtCore.Qt.LeftButton: if not self.moving: self.bw_map_screen.set_selectionbox_start((event.x(), event.y())) else: if self.bw_map_screen.current_entity is not None: newx, newy = image_coords_to_bw_coords(mouse_x, mouse_y) object_set_position(self.level, self.bw_map_screen.current_entity, newx, newy) self.bw_map_screen.move_entity(self.bw_map_screen.current_entity, mouse_x, mouse_y) self.set_entity_text(self.bw_map_screen.current_entity) update_mapscreen(self.bw_map_screen, self.level.obj_map[self.bw_map_screen.current_entity]) elif len(self.bw_map_screen.selected_entities) > 0: for entity in self.bw_map_screen.selected_entities: first_entity = entity break #first_entity = self.bw_map_screen.selected_entities.keys()[0] x, y, entitytype, metadata = self.bw_map_screen.entities[first_entity] startx = endx = x starty = endy = y for entity in self.bw_map_screen.selected_entities: x, y, dontneed, dontneed = self.bw_map_screen.entities[entity] if x < startx: startx = x if x > endx: endx = x if y < starty: starty = y if y > endy: endy = y middle_x = (startx+endx) / 2 middle_y = (starty+endy) / 2 delta_x = mouse_x - middle_x delta_y = mouse_y - middle_y for entity in self.bw_map_screen.selected_entities: x, y, dontneed, dontneed = self.bw_map_screen.entities[entity] newx, newy = image_coords_to_bw_coords(x+delta_x, y+delta_y) object_set_position(self.level, entity, newx, newy) self.bw_map_screen.move_entity(entity, x+delta_x, y+delta_y) #self.set_entity_text(self.bw_map_screen.current_entity) update_mapscreen(self.bw_map_screen, self.level.obj_map[entity]) self.bw_map_screen.update() @catch_exception def mouse_move(self, event): x, y = image_coords_to_bw_coords(event.x()/self.bw_map_screen.zoom_factor, event.y()/self.bw_map_screen.zoom_factor) self.statusbar.showMessage("x: {0} y: {1}".format(round(x, 5), round(y, 5))) if self.dragging and default_timer() - self.dragged_time > 0.1: if event.buttons() == QtCore.Qt.RightButton: delta_x = (event.x()-self.last_x)/8 delta_y = (event.y()-self.last_y)/8 #print("hi",event.x(), event.y()) vertbar = self.scrollArea.verticalScrollBar() horizbar = self.scrollArea.horizontalScrollBar() vertbar.setSliderPosition(vertbar.value()-delta_y) horizbar.setSliderPosition(horizbar.value()-delta_x) elif event.buttons() == QtCore.Qt.LeftButton: self.bw_map_screen.set_selectionbox_end((event.x(), event.y())) if len(self.bw_map_screen.selected_entities) > 0 or self.bw_map_screen.current_entity is None: self.bw_map_screen.choose_entity(None) self.set_entity_text_multiple(self.bw_map_screen.selected_entities) self.bw_map_screen.update() def mouse_release(self, event): self.dragging = False if self.bw_map_screen.selectionbox_end is not None: self.bw_map_screen.clear_selection_box() self.bw_map_screen.update() def set_entity_text_multiple(self, entities): self.label_object_id.setText("{0} objects selected".format(len(entities))) MAX = 15 listentities = [self.level.obj_map[x].name for x in sorted(entities.keys())][0:MAX] listentities.sort() if len(entities) > MAX: listentities.append("... and {0} more".format(len(entities) - len(listentities))) self.label_position.setText("\n".join(listentities[:5])) self.label_model_name.setText("\n".join(listentities[5:10])) self.label_4.setText("\n".join(listentities[10:]))#15])) self.label_5.setText("")#("\n".join(listentities[12:16])) def set_entity_text(self, entityid): try: obj = self.level.obj_map[entityid] if obj.has_attr("mBase"): base = self.level.obj_map[obj.get_attr_value("mBase")] self.label_object_id.setText("{0}\n[{1}]\nBase: {2}\n[{3}]".format( entityid, obj.type, base.id, base.type)) else: self.label_object_id.setText("{0}\n[{1}]".format(entityid, obj.type)) self.label_model_name.setText("Model: {0}".format(entity_get_model(self.level, entityid))) x, y, angle = object_get_position(self.level, entityid) self.label_position.setText("x: {0}\ny: {1}".format(x, y)) self.lineedit_angle.setText(str(round(angle,2))) self.label_4.setText("Army: {0}".format(entity_get_army(self.level, entityid))) if not obj.has_attr("mPassenger"): self.label_5.setText("Icon Type: \n{0}".format(entity_get_icon_type(self.level, entityid))) else: passengers = 0 for passenger in obj.get_attr_elements("mPassenger"): if passenger != "0": passengers += 1 self.label_5.setText("Icon Type: \n{0}\n\nPassengers: {1}".format( entity_get_icon_type(self.level, entityid), passengers)) except: traceback.print_exc() def action_listwidget_change_selection(self, current, previous): #QtWidgets.QListWidgetItem. if not self.resetting and current is not None: print("ok") print("hi", current.text(), current.xml_ref) self.set_entity_text(current.xml_ref) self.bw_map_screen.choose_entity(current.xml_ref) posx, posy, typename, metadata = self.bw_map_screen.entities[current.xml_ref] zf = self.bw_map_screen.zoom_factor try: if not self.deleting_item: x_margin = min(100, 50*zf) y_margin = min(100, 50*zf) self.scrollArea.ensureVisible(posx*zf, posy*zf, xMargin=x_margin, yMargin=y_margin) else: self.deleting_item = False except: traceback.print_exc() def zoom_out(self, noslider=False): horizbar = self.scrollArea.horizontalScrollBar() vertbar = self.scrollArea.verticalScrollBar() print(horizbar.maximum(), vertbar.maximum()) if horizbar.maximum() > 0: widthratio = horizbar.value()/horizbar.maximum() else: widthratio = 0 if vertbar.maximum() > 0: heightratio = vertbar.value()/vertbar.maximum() else: heightratio = 0 #oldzf = self.bw_map_screen.zoom_factor / (0.1+1) #diff = oldzf - self.bw_map_screen.zoom_factor zf = self.bw_map_screen.zoom_factor self.bw_map_screen.zoom(calc_zoom_out_factor(zf))#diff) # if not noslider: horizbar.setSliderPosition(horizbar.maximum()*widthratio) vertbar.setSliderPosition(vertbar.maximum()*heightratio) self.bw_map_screen.update() self.statusbar.showMessage("Zoom: {0}x".format(self.bw_map_screen.zoom_factor)) def zoom_in(self, noslider=False): horizbar = self.scrollArea.horizontalScrollBar() vertbar = self.scrollArea.verticalScrollBar() if horizbar.maximum() > 0: widthratio = horizbar.value()/horizbar.maximum() else: widthratio = 0 if vertbar.maximum() > 0: heightratio = vertbar.value()/vertbar.maximum() else: heightratio = 0 zf = self.bw_map_screen.zoom_factor self.bw_map_screen.zoom(calc_zoom_in_factor(zf))#zf) # print("wedidit?") if not noslider: horizbar.setSliderPosition(horizbar.maximum()*widthratio) vertbar.setSliderPosition(vertbar.maximum()*heightratio) self.bw_map_screen.update() self.statusbar.showMessage("Zoom: {0}x".format(self.bw_map_screen.zoom_factor)) @catch_exception def mouse_wheel_scroll_zoom(self, wheel_event): print("scrolling", wheel_event) print("Scroll", wheel_event.x(), wheel_event.y(), wheel_event.angleDelta().y())#, wheel_event.delta()) wheel_delta = wheel_event.angleDelta().y() zf = self.bw_map_screen.zoom_factor norm_x = wheel_event.x()/zf norm_y = wheel_event.y()/zf if wheel_delta > 0: if zf <= 10: self.zoom_in(True) zf = self.bw_map_screen.zoom_factor xmargin = self.scrollArea.viewport().width()//2 - 200 ymargin = self.scrollArea.viewport().height()//2 - 200 self.scrollArea.ensureVisible(norm_x*zf, norm_y*zf, xmargin, ymargin) self.bw_map_screen.update() else: self.zoom_in() elif wheel_delta < 0: self.zoom_out() def action_lineedit_changeangle(self): if not self.resetting and self.bw_map_screen.current_entity is not None: print("ok") current = self.bw_map_screen.current_entity currx, curry, angle = object_get_position(self.level, current) newangle = self.lineedit_angle.text().strip() print(newangle, newangle.isdecimal()) try: angle = float(newangle) object_set_position(self.level, current, currx, curry, angle=angle) currentobj = self.level.obj_map[current] update_mapscreen(self.bw_map_screen, currentobj) self.bw_map_screen.update() except: traceback.print_exc() def button_terrain_load_action(self): try: print("ok", self.default_path) filepath, choosentype = QFileDialog.getOpenFileName( self, "Open File", self.default_path, "BW terrain files (*.out *out.gz);;All files (*)") print("doooone") if filepath: if filepath.endswith(".gz"): file_open = gzip.open else: file_open = open with file_open(filepath, "rb") as f: try: terrain = BWArchiveBase(f) if self.level is not None: waterheight = get_water_height(self.level) else: waterheight = None image, light_image = parse_terrain_to_image(terrain, waterheight) self.bw_map_screen.set_terrain(image, light_image) except: traceback.print_exc() except: traceback.print_exc() def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(820, 760) MainWindow.setMinimumSize(QSize(720, 560)) MainWindow.setWindowTitle("BW-MapEdit") #MainWindow.setWindowTitle("Nep-Nep") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") MainWindow.setCentralWidget(self.centralwidget) self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.scrollArea = QScrollArea(self.centralwidget) self.scrollArea.setWidgetResizable(True) self.bw_map_screen = BWMapViewer(self.centralwidget) self.scrollArea.setWidget(self.bw_map_screen) self.horizontalLayout.addWidget(self.scrollArea) #self.horizontalLayout.addWidget(self.bw_map_screen) self.entity_list_widget = BWEntityListWidget(self.centralwidget) self.entity_list_widget.setMaximumSize(QSize(300, 16777215)) self.entity_list_widget.setObjectName("entity_list_widget") self.horizontalLayout.addWidget(self.entity_list_widget) spacerItem = QSpacerItem(10, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) self.horizontalLayout.addItem(spacerItem) self.vertLayoutWidget = QWidget(self.centralwidget) self.vertLayoutWidget.setMaximumSize(QSize(250, 1200)) self.verticalLayout = QVBoxLayout(self.vertLayoutWidget) self.verticalLayout.setObjectName("verticalLayout") #self.verticalLayout. self.button_clone_entity = QPushButton(self.centralwidget) self.button_clone_entity.setObjectName("button_clone_entity") self.verticalLayout.addWidget(self.button_clone_entity) self.button_remove_entity = QPushButton(self.centralwidget) self.button_remove_entity.setObjectName("button_remove_entity") self.verticalLayout.addWidget(self.button_remove_entity) self.button_move_entity = QPushButton(self.centralwidget) self.button_move_entity.setObjectName("button_move_entity") self.verticalLayout.addWidget(self.button_move_entity) self.button_show_passengers = QPushButton(self.centralwidget) self.button_show_passengers.setObjectName("button_move_entity") self.verticalLayout.addWidget(self.button_show_passengers) self.gridLayout = QGridLayout() self.gridLayout.setObjectName("gridLayout") self.button_zoom_in = QPushButton(self.centralwidget) self.button_zoom_in.setObjectName("button_zoom_in") self.gridLayout.addWidget(self.button_zoom_in, 0, 0, 0, 1) self.button_zoom_out = QPushButton(self.centralwidget) self.button_zoom_out.setObjectName("button_zoom_out") self.gridLayout.addWidget(self.button_zoom_out, 0, 1, 0, 1) self.button_edit_xml = QPushButton(self.centralwidget) self.button_edit_xml.setObjectName("button_edit_xml") self.button_edit_base_xml = QPushButton(self.centralwidget) self.button_edit_base_xml.setObjectName("button_edit_base_xml") self.verticalLayout.addLayout(self.gridLayout) self.verticalLayout.addWidget(self.button_edit_xml) self.verticalLayout.addWidget(self.button_edit_base_xml) spacerItem1 = QSpacerItem(10, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.verticalLayout.addItem(spacerItem1) self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.lineedit_angle = QLineEdit(self.centralwidget) self.lineedit_angle.setObjectName("lineedit_angle") self.lineedit_angle.setPlaceholderText("Angle") self.label_object_id = QLabel(self.centralwidget) self.label_object_id.setObjectName("label_object_id") #TextSelectableByCursor self.label_position = QLabel(self.centralwidget) self.label_position.setObjectName("label_position") self.label_model_name = QLabel(self.centralwidget) self.label_model_name.setObjectName("label_model_name") self.label_4 = QLabel(self.centralwidget) self.label_4.setObjectName("label_4") self.label_5 = QLabel(self.centralwidget) self.label_5.setObjectName("label_5") for label in (self.label_object_id, self.label_position, self.label_model_name, self.label_4, self.label_5): label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) self.verticalLayout_2.addWidget(self.lineedit_angle) self.verticalLayout_2.addWidget(self.label_object_id) self.verticalLayout_2.addWidget(self.label_position) self.verticalLayout_2.addWidget(self.label_model_name) self.verticalLayout_2.addWidget(self.label_4) self.verticalLayout_2.addWidget(self.label_5) self.verticalLayout.addLayout(self.verticalLayout_2) self.horizontalLayout.addWidget(self.vertLayoutWidget) self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QRect(0, 0, 820, 29)) self.menubar.setObjectName("menubar") self.file_menu = QMenu(self.menubar) self.file_menu.setObjectName("menuLoad") self.file_load_action = QAction("Load", self) self.file_load_action.triggered.connect(self.button_load_level) self.file_menu.addAction(self.file_load_action) self.file_save_action = QAction("Save", self) self.file_save_action.triggered.connect(self.button_save_level) self.file_menu.addAction(self.file_save_action) self.visibility_menu = MenuDontClose(self.menubar)#QMenu(self.menubar) self.visibility_menu.setObjectName("visibility") #self.visibility_menu.addAction(self.toggle_action) self.visibility_actions = [] self.terrain_menu = QMenu(self.menubar) self.terrain_menu.setObjectName("terrain") self.terrain_load_action = QAction("Load Terrain", self) self.terrain_load_action.triggered.connect(self.button_terrain_load_action) self.terrain_menu.addAction(self.terrain_load_action) self.terrain_display_actions = [] self.setup_terrain_display_toggles() #self.menuLoad_2 = QMenu(self.menubar) #self.menuLoad_2.setObjectName("menuLoad_2") MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar.addAction(self.file_menu.menuAction()) #self.menubar.addAction(self.menuLoad_2.menuAction()) self.menubar.addAction(self.visibility_menu.menuAction()) self.menubar.addAction(self.terrain_menu.menuAction()) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) def make_terrain_toggle(self, show_mode): def terraintoggle(toggled): print("I am", show_mode, "and I was pressed") if toggled is True: for action, toggle, mode in self.terrain_display_actions: if mode != show_mode: action.setChecked(False) self.bw_map_screen.set_show_terrain_mode(show_mode) elif toggled is False: self.bw_map_screen.set_show_terrain_mode(SHOW_TERRAIN_NO_TERRAIN) else: print("This shouldn't be possible", toggled, type(toggled)) self.bw_map_screen.update() return terraintoggle def setup_terrain_display_toggles(self): for mode, name in ((SHOW_TERRAIN_REGULAR, "Show Heightmap"), (SHOW_TERRAIN_LIGHT, "Show Lightmap")): toggle = self.make_terrain_toggle(mode) toggle_action = QAction(name, self) toggle_action.setCheckable(True) if mode == SHOW_TERRAIN_REGULAR: toggle_action.setChecked(True) else: toggle_action.setChecked(False) toggle_action.triggered.connect(toggle) self.terrain_menu.addAction(toggle_action) self.terrain_display_actions.append((toggle_action, toggle, mode)) def clear_terrain_toggles(self): try: for action, func, mode in self.terrain_display_actions: self.terrain_menu.removeAction(action) self.terrain_display_actions = [] except: traceback.print_exc() def make_toggle_function(self, objtype): def toggle(toggled): print("i was pressed") my_type = copy(objtype) self.types_visible[my_type] = toggled self.bw_map_screen.set_visibility(self.types_visible) self.bw_map_screen.update() return toggle def setup_visibility_toggles(self): for objtype in sorted(self.level.objtypes_with_positions): toggle = self.make_toggle_function(objtype) toggle_action = QAction(copy(objtype), self) toggle_action.setCheckable(True) toggle_action.setChecked(True) toggle_action.triggered.connect(toggle) self.types_visible[objtype] = True self.visibility_menu.addAction(toggle_action) self.visibility_actions.append((toggle_action, toggle)) toggle_all = QAction("Toggle All", self) toggle_all.triggered.connect(self.toggle_visiblity_all) self.visibility_menu.addAction(toggle_all) self.visibility_actions.append((toggle_all, self.toggle_visiblity_all)) def toggle_visiblity_all(self): for action, func in self.visibility_actions: if action.isCheckable(): objtype = action.text() toggle = self.types_visible[objtype] self.types_visible[objtype] = not toggle action.setChecked(not toggle) self.bw_map_screen.set_visibility(self.types_visible) self.bw_map_screen.update() def clear_visibility_toggles(self): try: for action, func in self.visibility_actions: self.visibility_menu.removeAction(action) self.visibility_actions = [] self.types_visible = {} except: traceback.print_exc() def retranslateUi(self, MainWindow): _translate = QCoreApplication.translate self.button_clone_entity.setText(_translate("MainWindow", "Clone Entity")) self.button_remove_entity.setText(_translate("MainWindow", "Delete Entity")) self.button_move_entity.setText(_translate("MainWindow", "Move Entity")) self.button_zoom_in.setText(_translate("MainWindow", "Zoom In")) self.button_zoom_out.setText(_translate("MainWindow", "Zoom Out")) self.button_show_passengers.setText(_translate("MainWindow", "Show Passengers")) self.button_edit_xml.setText("Edit Object XML") self.button_edit_base_xml.setText("Edit Base Object XML") self.label_model_name.setText(_translate("MainWindow", "TextLabel1")) self.label_object_id.setText(_translate("MainWindow", "TextLabel2")) self.label_position.setText(_translate("MainWindow", "TextLabel3")) self.label_4.setText(_translate("MainWindow", "TextLabel4")) self.label_5.setText(_translate("MainWindow", "TextLabel5")) self.file_menu.setTitle(_translate("MainWindow", "File")) self.visibility_menu.setTitle(_translate("MainWindow", "Visibility")) self.terrain_menu.setTitle("Terrain")
def __init__(self, model, allActions, parent=None): """Initialize the main window. Arguments: model -- the initial data model allActions -- a dict containing the upper level actions parent -- the parent window, usually None """ super().__init__(parent) self.allActions = allActions.copy() self.allowCloseFlag = True self.winActions = {} self.toolbars = [] self.rightTabActList = [] self.setAttribute(Qt.WA_DeleteOnClose) self.setAcceptDrops(True) self.setStatusBar(QStatusBar()) self.setCaption() self.setupActions() self.setupMenus() self.setupToolbars() self.restoreToolbarPosition() self.treeView = treeview.TreeView(model, self.allActions) self.breadcrumbSplitter = QSplitter(Qt.Vertical) self.setCentralWidget(self.breadcrumbSplitter) self.breadcrumbView = breadcrumbview.BreadcrumbView(self.treeView) self.breadcrumbSplitter.addWidget(self.breadcrumbView) self.breadcrumbView.setVisible( globalref.genOptions['InitShowBreadcrumb']) self.treeSplitter = QSplitter() self.breadcrumbSplitter.addWidget(self.treeSplitter) self.treeStack = QStackedWidget() self.treeSplitter.addWidget(self.treeStack) self.treeStack.addWidget(self.treeView) self.treeView.shortcutEntered.connect(self.execShortcut) self.treeView.selectionModel().selectionChanged.connect( self.updateRightViews) self.treeFilterView = None self.rightTabs = QTabWidget() self.treeSplitter.addWidget(self.rightTabs) self.rightTabs.setTabPosition(QTabWidget.South) self.rightTabs.tabBar().setFocusPolicy(Qt.NoFocus) self.outputSplitter = QSplitter(Qt.Vertical) self.rightTabs.addTab(self.outputSplitter, _('Data Output')) parentOutputView = outputview.OutputView(self.treeView, False) parentOutputView.highlighted[str].connect(self.statusBar().showMessage) self.outputSplitter.addWidget(parentOutputView) childOutputView = outputview.OutputView(self.treeView, True) childOutputView.highlighted[str].connect(self.statusBar().showMessage) self.outputSplitter.addWidget(childOutputView) self.editorSplitter = QSplitter(Qt.Vertical) self.rightTabs.addTab(self.editorSplitter, _('Data Edit')) parentEditView = dataeditview.DataEditView(self.treeView, self.allActions, False) parentEditView.shortcutEntered.connect(self.execShortcut) parentEditView.focusOtherView.connect(self.focusNextView) parentEditView.inLinkSelectMode.connect( self.treeView.toggleNoMouseSelectMode) self.treeView.skippedMouseSelect.connect( parentEditView.internalLinkSelected) self.editorSplitter.addWidget(parentEditView) childEditView = dataeditview.DataEditView(self.treeView, self.allActions, True) childEditView.shortcutEntered.connect(self.execShortcut) childEditView.focusOtherView.connect(self.focusNextView) childEditView.inLinkSelectMode.connect( self.treeView.toggleNoMouseSelectMode) self.treeView.skippedMouseSelect.connect( childEditView.internalLinkSelected) parentEditView.hoverFocusActive.connect(childEditView.endEditor) childEditView.hoverFocusActive.connect(parentEditView.endEditor) parentEditView.inLinkSelectMode.connect( childEditView.updateInLinkSelectMode) childEditView.inLinkSelectMode.connect( parentEditView.updateInLinkSelectMode) self.editorSplitter.addWidget(childEditView) self.titleSplitter = QSplitter(Qt.Vertical) self.rightTabs.addTab(self.titleSplitter, _('Title List')) parentTitleView = titlelistview.TitleListView(self.treeView, False) parentTitleView.shortcutEntered.connect(self.execShortcut) self.titleSplitter.addWidget(parentTitleView) childTitleView = titlelistview.TitleListView(self.treeView, True) childTitleView.shortcutEntered.connect(self.execShortcut) self.titleSplitter.addWidget(childTitleView) self.rightTabs.currentChanged.connect(self.updateRightViews) self.updateFonts()
class OpenposeGUI(QMainWindow): def __init__(self): super().__init__() loadUi("ui/main_window.ui", self) self.setWindowTitle("OpencvGUI") self.setWindowIcon(QIcon("icon/logo.png")) # 工具栏 # 所有动作定义在ui文件中 self.tool_bar = QToolBar() self.tool_bar.addAction(self.action_camera) self.tool_bar.addSeparator() self.tool_bar.addAction(self.action_save) self.tool_bar.addAction(self.action_autosave) self.tool_bar.addSeparator() self.tool_bar.addAction(self.action_setting) self.tool_bar.addAction(self.action_filetree) self.addToolBar(self.tool_bar) # 状态栏 self.status_bar = QStatusBar() self.status_fps = QLabel("FPS:00.0") self.status_bar.addPermanentWidget(self.status_fps) self.setStatusBar(self.status_bar) # 组件 self.label_frame = LabelFrame(self) # 用于显示画面 self.dock_setting = SettingDock(self) # 设置 self.dock_filetree = FiletreeDock(self) # 目录 self.dock_media = MediaDock(self) # 视频播放控制 self.timer = QTimer() self.camera = Camera() # 视频控制器 self.openpose_model = OpenposeModel() # openpose模型 self.save_widget = SaveWidget() # 保存窗口 self.gesture_model = GestureModel(r'models/gesture/[email protected]') # 设置dock self.setCentralWidget(self.label_frame) self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_setting) self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_filetree) self.addDockWidget(Qt.BottomDockWidgetArea, self.dock_media) # 工具栏动作 self.action_camera.triggered.connect(self.run_camera) self.action_filetree.triggered.connect(self.show_filetree) self.action_setting.triggered.connect(self.show_setting) self.action_save.triggered.connect(self.save) self.action_autosave.triggered.connect(self.auto_save) # 相机计时器 self.camera.timer.timeout.connect(self.update_frame) # 自动保存计时器 self.timer.timeout.connect(self.save) def update_frame(self): """更新frame画面""" start_time = time.time() self.dock_media.update_slider(self.frame_pos, self.frame_count) frame = self.frame if frame is None: return None result, keypoints = self.openpose_model(frame) result, keypoints = self.gesture_recognition(result, keypoints) message = self.generate_message(keypoints) self.label_frame.update_frame(result) fps = 1 / (time.time() - start_time) self.status_fps.setText("FPS:{:.1f}".format(fps)) self.status_bar.showMessage(message) return result, keypoints def save(self): """执行保存操作""" if not self.label_frame.pixmap(): QMessageBox.warning(self, "Note", "No data in frame", QMessageBox.Yes) return pixmap = self.label_frame.img_to_pixmap( self.openpose_model.get_rendered_image()) body, hand, face = self.openpose_model.get_keypoints() message = self.generate_message((body, hand, face)) body = copy.deepcopy(body) if self.body_on else None hand = copy.deepcopy(hand) if self.hand_on else None face = copy.deepcopy(face) if self.face_on else None keypoints = (body, hand, face) if self.timer.isActive(): self.save_widget.save(pixmap.copy(), *keypoints) else: self.save_widget.set_frame(pixmap.copy(), *keypoints, message) self.save_widget.show() def auto_save(self): """开启或关闭自动保存""" if not self.camera.is_open: self.action_autosave.setChecked(False) if self.action_autosave.isChecked(): self.timer.start(self.save_interval * 1000) else: self.timer.stop() # 功能 def show_setting(self): """隐藏或显示设置""" if self.dock_setting.isHidden(): self.dock_setting.show() else: self.dock_setting.hide() def show_filetree(self): """隐藏或显示目录树""" if self.dock_filetree.isHidden(): self.dock_filetree.show() else: self.dock_filetree.hide() def run_image(self, img_path): """图片""" image = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1) if image is None: QMessageBox.warning(self, "Note", "Read Image error", QMessageBox.Yes) return result, keypoints = self.openpose_model(image) message = self.generate_message(keypoints) self.label_frame.update_frame(result) self.status_bar.showMessage(message) self.dock_media.hide() def run_video(self, video_path): """视频""" self.camera.start(video_path) self.label_frame.resize(*self.resolution) self.update_frame() # 初始化画面 self.camera.pause() self.dock_media.reset() self.dock_media.show() def run_camera(self): """相机""" if self.action_camera.isChecked(): self.camera.start(0) self.label_frame.resize(*self.resolution) else: self.label_frame.clear() self.camera.stop() self.status_fps.setText("FPS:00.0") self.dock_media.hide() def gesture_recognition(self, result, keypoints): """实现手势识别""" if self.gesture_on: hands = keypoints[1] if hands[0].size == 1: return result, keypoints person_num = hands[0].shape[0] for i in range(person_num): # 每个人 for hand in hands: # 每只手 rect = self.gesture_model.hand_bbox(hand[i]) gesture = self.gesture_model(hand[i]) if rect: print(rect) x, y, w, h = rect cv2.rectangle(result, (x, y), (x + w, y + h), (255, 255, 255), 2) cv2.putText(result, gesture, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255)) return result, keypoints def generate_message(self, keypoints): """获取识别结果信息""" if keypoints[0].size != 1: person_num = keypoints[0].shape[0] message = "person: {}".format(person_num) for i in range(person_num): message += " | person{}(".format(i + 1) if self.body_on: pose_keypoints = keypoints[0][i, :, 2] pose_detected = pose_keypoints[ pose_keypoints > self.body_threshold] message += "pose: {:>2d}/{}".format(pose_detected.size, 25) if self.hand_on: right_hand_keypoinys = keypoints[1][0][i, :, 2] left_hand_keypoinys = keypoints[1][1][i, :, 2] right_hand_detected = right_hand_keypoinys[ right_hand_keypoinys > self.hand_threshold] left_hand_detected = left_hand_keypoinys[ left_hand_keypoinys > self.hand_threshold] message += " | right hand: {:>2d}/{}".format( right_hand_detected.size, 21) message += " | left hand: {:>2d}/{}".format( left_hand_detected.size, 21) message += ")" else: message = "person: {}".format(0) return message @property def body_on(self): return self.dock_setting.body_on @property def hand_on(self): return self.dock_setting.hand_on @property def face_on(self): return self.dock_setting.face_on @property def body_threshold(self): return self.dock_setting.body_threshold @property def hand_threshold(self): return self.dock_setting.hand_threshold @property def face_threshold(self): return self.dock_setting.face_threshold @property def gesture_on(self): return self.dock_setting.gesture_on @property def save_interval(self): return self.dock_setting.save_interval @property def frame(self): return self.camera.frame @property def frame_pos(self): return self.camera.frame_pos @property def frame_count(self): return self.camera.frame_count @property def resolution(self): return self.camera.resolution
def init_statusbar(self): self.status_bar = QStatusBar() self.setStatusBar(self.status_bar)
class ResultWindow(QMainWindow): def __init__(self, parent, app, **kwargs): super().__init__(parent, **kwargs) self.app = app self._setupUi() self.resultsModel = app.RESULT_MODEL_CLASS(self.app, self.resultsView) self.stats = StatsLabel(app.model.stats_label, self.statusLabel) self._update_column_actions_status() self.menuColumns.triggered.connect(self.columnToggled) self.resultsView.doubleClicked.connect(self.resultsDoubleClicked) self.resultsView.spacePressed.connect(self.resultsSpacePressed) self.detailsButton.clicked.connect(self.actionDetails.triggered) self.dupesOnlyCheckBox.stateChanged.connect(self.powerMarkerTriggered) self.deltaValuesCheckBox.stateChanged.connect(self.deltaTriggered) self.searchEdit.searchChanged.connect(self.searchChanged) self.app.willSavePrefs.connect(self.appWillSavePrefs) def _setupActions(self): # (name, shortcut, icon, desc, func) ACTIONS = [ ('actionDetails', 'Ctrl+I', '', tr("Details"), self.detailsTriggered), ('actionActions', '', '', tr("Actions"), self.actionsTriggered), ('actionPowerMarker', 'Ctrl+1', '', tr("Show Dupes Only"), self.powerMarkerTriggered), ('actionDelta', 'Ctrl+2', '', tr("Show Delta Values"), self.deltaTriggered), ('actionDeleteMarked', 'Ctrl+D', '', tr("Send Marked to Recycle Bin..."), self.deleteTriggered), ('actionMoveMarked', 'Ctrl+M', '', tr("Move Marked to..."), self.moveTriggered), ('actionCopyMarked', 'Ctrl+Shift+M', '', tr("Copy Marked to..."), self.copyTriggered), ('actionRemoveMarked', 'Ctrl+R', '', tr("Remove Marked from Results"), self.removeMarkedTriggered), ('actionReprioritize', '', '', tr("Re-Prioritize Results..."), self.reprioritizeTriggered), ('actionRemoveSelected', 'Ctrl+Del', '', tr("Remove Selected from Results"), self.removeSelectedTriggered), ('actionIgnoreSelected', 'Ctrl+Shift+Del', '', tr("Add Selected to Ignore List"), self.addToIgnoreListTriggered), ('actionMakeSelectedReference', 'Ctrl+Space', '', tr("Make Selected into Reference"), self.app.model.make_selected_reference), ('actionOpenSelected', 'Ctrl+O', '', tr("Open Selected with Default Application"), self.openTriggered), ('actionRevealSelected', 'Ctrl+Shift+O', '', tr("Open Containing Folder of Selected"), self.revealTriggered), ('actionRenameSelected', 'F2', '', tr("Rename Selected"), self.renameTriggered), ('actionMarkAll', 'Ctrl+A', '', tr("Mark All"), self.markAllTriggered), ('actionMarkNone', 'Ctrl+Shift+A', '', tr("Mark None"), self.markNoneTriggered), ('actionInvertMarking', 'Ctrl+Alt+A', '', tr("Invert Marking"), self.markInvertTriggered), ('actionMarkSelected', '', '', tr("Mark Selected"), self.markSelectedTriggered), ('actionExportToHTML', '', '', tr("Export To HTML"), self.app.model.export_to_xhtml), ('actionExportToCSV', '', '', tr("Export To CSV"), self.app.model.export_to_csv), ('actionSaveResults', 'Ctrl+S', '', tr("Save Results..."), self.saveResultsTriggered), ('actionInvokeCustomCommand', 'Ctrl+Alt+I', '', tr("Invoke Custom Command"), self.app.invokeCustomCommand), ] createActions(ACTIONS, self) self.actionDelta.setCheckable(True) self.actionPowerMarker.setCheckable(True) def _setupMenu(self): self.menubar = QMenuBar() self.menubar.setGeometry(QRect(0, 0, 630, 22)) self.menuFile = QMenu(self.menubar) self.menuFile.setTitle(tr("File")) self.menuMark = QMenu(self.menubar) self.menuMark.setTitle(tr("Mark")) self.menuActions = QMenu(self.menubar) self.menuActions.setTitle(tr("Actions")) self.menuColumns = QMenu(self.menubar) self.menuColumns.setTitle(tr("Columns")) self.menuView = QMenu(self.menubar) self.menuView.setTitle(tr("View")) self.menuHelp = QMenu(self.menubar) self.menuHelp.setTitle(tr("Help")) self.setMenuBar(self.menubar) self.menuActions.addAction(self.actionDeleteMarked) self.menuActions.addAction(self.actionMoveMarked) self.menuActions.addAction(self.actionCopyMarked) self.menuActions.addAction(self.actionRemoveMarked) self.menuActions.addAction(self.actionReprioritize) self.menuActions.addSeparator() self.menuActions.addAction(self.actionRemoveSelected) self.menuActions.addAction(self.actionIgnoreSelected) self.menuActions.addAction(self.actionMakeSelectedReference) self.menuActions.addSeparator() self.menuActions.addAction(self.actionOpenSelected) self.menuActions.addAction(self.actionRevealSelected) self.menuActions.addAction(self.actionInvokeCustomCommand) self.menuActions.addAction(self.actionRenameSelected) self.menuMark.addAction(self.actionMarkAll) self.menuMark.addAction(self.actionMarkNone) self.menuMark.addAction(self.actionInvertMarking) self.menuMark.addAction(self.actionMarkSelected) self.menuView.addAction(self.actionPowerMarker) self.menuView.addAction(self.actionDelta) self.menuView.addSeparator() self.menuView.addAction(self.actionDetails) self.menuView.addAction(self.app.actionIgnoreList) self.menuView.addAction(self.app.actionPreferences) self.menuHelp.addAction(self.app.actionShowHelp) self.menuHelp.addAction(self.app.actionOpenDebugLog) self.menuHelp.addAction(self.app.actionAbout) self.menuFile.addAction(self.actionSaveResults) self.menuFile.addAction(self.actionExportToHTML) self.menuFile.addAction(self.actionExportToCSV) self.menuFile.addSeparator() self.menuFile.addAction(self.app.actionQuit) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuMark.menuAction()) self.menubar.addAction(self.menuActions.menuAction()) self.menubar.addAction(self.menuColumns.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) # Columns menu menu = self.menuColumns self._column_actions = [] for index, (display, visible) in enumerate(self.app.model.result_table.columns.menu_items()): action = menu.addAction(display) action.setCheckable(True) action.setChecked(visible) action.item_index = index self._column_actions.append(action) menu.addSeparator() action = menu.addAction(tr("Reset to Defaults")) action.item_index = -1 # Action menu actionMenu = QMenu(tr("Actions"), self.menubar) actionMenu.addAction(self.actionDeleteMarked) actionMenu.addAction(self.actionMoveMarked) actionMenu.addAction(self.actionCopyMarked) actionMenu.addAction(self.actionRemoveMarked) actionMenu.addSeparator() actionMenu.addAction(self.actionRemoveSelected) actionMenu.addAction(self.actionIgnoreSelected) actionMenu.addAction(self.actionMakeSelectedReference) actionMenu.addSeparator() actionMenu.addAction(self.actionOpenSelected) actionMenu.addAction(self.actionRevealSelected) actionMenu.addAction(self.actionInvokeCustomCommand) actionMenu.addAction(self.actionRenameSelected) self.actionActions.setMenu(actionMenu) self.actionsButton.setMenu(self.actionActions.menu()) def _setupUi(self): self.setWindowTitle(tr("{} Results").format(self.app.NAME)) self.resize(630, 514) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.actionsButton = QPushButton(tr("Actions")) self.detailsButton = QPushButton(tr("Details")) self.dupesOnlyCheckBox = QCheckBox(tr("Dupes Only")) self.deltaValuesCheckBox = QCheckBox(tr("Delta Values")) self.searchEdit = SearchEdit() self.searchEdit.setMaximumWidth(300) self.horizontalLayout = horizontalWrap([self.actionsButton, self.detailsButton, self.dupesOnlyCheckBox, self.deltaValuesCheckBox, None, self.searchEdit, 8]) self.horizontalLayout.setSpacing(8) self.verticalLayout.addLayout(self.horizontalLayout) self.resultsView = ResultsView(self.centralwidget) self.resultsView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.resultsView.setSelectionBehavior(QAbstractItemView.SelectRows) self.resultsView.setSortingEnabled(True) self.resultsView.verticalHeader().setVisible(False) h = self.resultsView.horizontalHeader() h.setHighlightSections(False) h.setSectionsMovable(True) h.setStretchLastSection(False) h.setDefaultAlignment(Qt.AlignLeft) self.verticalLayout.addWidget(self.resultsView) self.setCentralWidget(self.centralwidget) self._setupActions() self._setupMenu() self.statusbar = QStatusBar(self) self.statusbar.setSizeGripEnabled(True) self.setStatusBar(self.statusbar) self.statusLabel = QLabel(self) self.statusbar.addPermanentWidget(self.statusLabel, 1) if self.app.prefs.resultWindowIsMaximized: self.setWindowState(self.windowState() | Qt.WindowMaximized) else: if self.app.prefs.resultWindowRect is not None: self.setGeometry(self.app.prefs.resultWindowRect) else: moveToScreenCenter(self) #--- Private def _update_column_actions_status(self): # Update menu checked state menu_items = self.app.model.result_table.columns.menu_items() for action, (display, visible) in zip(self._column_actions, menu_items): action.setChecked(visible) #--- Actions def actionsTriggered(self): self.actionsButton.showMenu() def addToIgnoreListTriggered(self): self.app.model.add_selected_to_ignore_list() def copyTriggered(self): self.app.model.copy_or_move_marked(True) def deleteTriggered(self): self.app.model.delete_marked() def deltaTriggered(self, state=None): # The sender can be either the action or the checkbox, but both have a isChecked() method. self.resultsModel.delta_values = self.sender().isChecked() self.actionDelta.setChecked(self.resultsModel.delta_values) self.deltaValuesCheckBox.setChecked(self.resultsModel.delta_values) def detailsTriggered(self): self.app.show_details() def markAllTriggered(self): self.app.model.mark_all() def markInvertTriggered(self): self.app.model.mark_invert() def markNoneTriggered(self): self.app.model.mark_none() def markSelectedTriggered(self): self.app.model.toggle_selected_mark_state() def moveTriggered(self): self.app.model.copy_or_move_marked(False) def openTriggered(self): self.app.model.open_selected() def powerMarkerTriggered(self, state=None): # see deltaTriggered self.resultsModel.power_marker = self.sender().isChecked() self.actionPowerMarker.setChecked(self.resultsModel.power_marker) self.dupesOnlyCheckBox.setChecked(self.resultsModel.power_marker) def preferencesTriggered(self): self.app.show_preferences() def removeMarkedTriggered(self): self.app.model.remove_marked() def removeSelectedTriggered(self): self.app.model.remove_selected() def renameTriggered(self): index = self.resultsView.selectionModel().currentIndex() # Our index is the current row, with column set to 0. Our filename column is 1 and that's # what we want. index = index.sibling(index.row(), 1) self.resultsView.edit(index) def reprioritizeTriggered(self): dlg = PrioritizeDialog(self, self.app) result = dlg.exec() if result == QDialog.Accepted: dlg.model.perform_reprioritization() def revealTriggered(self): self.app.model.reveal_selected() def saveResultsTriggered(self): title = tr("Select a file to save your results to") files = tr("dupeGuru Results (*.dupeguru)") destination, chosen_filter = QFileDialog.getSaveFileName(self, title, '', files) if destination: if not destination.endswith('.dupeguru'): destination = '{}.dupeguru'.format(destination) self.app.model.save_as(destination) self.app.recentResults.insertItem(destination) #--- Events def appWillSavePrefs(self): prefs = self.app.prefs prefs.resultWindowIsMaximized = self.isMaximized() prefs.resultWindowRect = self.geometry() def columnToggled(self, action): index = action.item_index if index == -1: self.app.model.result_table.columns.reset_to_defaults() self._update_column_actions_status() else: visible = self.app.model.result_table.columns.toggle_menu_item(index) action.setChecked(visible) def contextMenuEvent(self, event): self.actionActions.menu().exec_(event.globalPos()) def resultsDoubleClicked(self, modelIndex): self.app.model.open_selected() def resultsSpacePressed(self): self.app.model.toggle_selected_mark_state() def searchChanged(self): self.app.model.apply_filter(self.searchEdit.text())
class MyMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) self.setWindowIcon(QtGui.QIcon('./img/cartoon4.ico')) self.setupUi(self) # 状态栏 self.mak = 0 self.preSet() self.qss() # 绑定模式 self.radioButton.toggled.connect(self.buttonState) self.radioButton_2.toggled.connect(self.buttonState) # 实现测量开始、暂停、继续、停止 self.pushButton.clicked.connect(self.measure) self.pushButton_2.clicked.connect(self.pause) self.pushButton_3.clicked.connect(self.terminate_m) self.pushButton_4.clicked.connect(self.go_on) # 实现测量所需数据的保存和读取 self.pushButton_5.clicked.connect(self.save_result) self.pushButton_6.clicked.connect(self.writeconf) self.pushButton_7.clicked.connect(self.readconf) self.pushButton_8.clicked.connect(self.read_result) self.pushButton_11.clicked.connect(self.jisuan) self.actionconnect.triggered.connect(self.con_pic) self.action5.triggered.connect(QCoreApplication.instance().quit) self.actionhelp.triggered.connect(self.helppage) def read_result(self): fileName1, filetype = QFileDialog.getOpenFileName( self, "选取文件", "./save/", "All Files (*);;Text Files (*.txt)") with open(fileName1, 'r') as f: a = f.read().split() c = [] for i in a: c.append(eval(i)) self.result = c self.pyqtgraph1.clear() self.c = self.pyqtgraph1.addPlot(title='最终的结果', pen=pg.mkPen(color='b')) self.c.setLabel('left', "S21", units='dB') self.c.setLabel('bottom', "频率", units='MHz') self.c.setLogMode(x=False, y=False) self.c.plot(y=c, pen=pg.mkPen(color='r', width=2)) def save_result(self): fileName2, ok2 = QFileDialog.getSaveFileName(None, "文件保存", "./", "Text Files (*.txt)") try: shutil.copy('e:/bishe/save/3.txt', fileName2) information_dialog(self, '提示', '保存成功') except: information_dialog(self, '提示', '保存失败') def buttonState(self): radioButton = self.sender() if radioButton.isChecked(): self.state = radioButton.text() information_dialog(self, '提示', '请先进行连线测量,再进行天线测量') self.con_pic() self.pyqtgraph1.clear() self.c = self.pyqtgraph1.addPlot(title=self.state, pen=pg.mkPen(color='b')) self.c.setLabel('left', "S21", units='dB') self.c.setLabel('bottom', "频率", units='MHz') self.c.setLogMode(x=False, y=False) def jisuan(self): with open('./save/1.txt', 'r') as f: a = f.read().split() with open('./save/2.txt', 'r') as f: b = f.read().split() c = [] for i in range(len(a)): c.append(eval(b[i]) - eval(a[i])) with open('./save/3.txt', 'w') as f: for i in c: f.write(str(i) + '\n') self.pyqtgraph1.clear() self.c = self.pyqtgraph1.addPlot(title='最终结果', pen=pg.mkPen(color='b')) self.c.setLabel('left', "S21", units='dB') self.c.setLabel('bottom', "频率", units='MHz') self.c.setLogMode(x=False, y=False) self.c.plot(y=c, pen=pg.mkPen(color='r', width=2)) def set_3d(self, a): tools.setcon.pic_3d(self, a) def set_2d(self, a): tools.setcon.pic_2d(self, a) def preSet(self): self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) self.progressBar.setValue(0) self.readconf() self.path = './save' self.state = "线缆连接测量" self.save_path = 'd://save//' if not os.path.exists(self.save_path): os.mkdir(self.save_path) def con_pic(self): self.pic = field_pic.picture() self.pic.setWindowIcon(QtGui.QIcon('./img/cartoon4.ico')) self.pic.show() def helppage(self): self.help_page = helpPage.Splitter() self.help_page.setWindowIcon(QtGui.QIcon('./img/cartoon4.ico')) self.help_page.show() def measure(self): # self.thread_exa = suit_cla() # self.thread_exa.start() # self.thread_exa.mySig.connect(self.mat) # self.select_change(1) self.pyqtgraph1.clear() self.c = self.pyqtgraph1.addPlot(title=self.state, pen=pg.mkPen(color='r', width=2)) self.c.setLabel('left', "S21", units='dB') self.c.setLabel('bottom', "频率", units='MHz') self.c.setLogMode(x=False, y=False) self.statusBar.showMessage('测量中......', 10**8) self.pushButton.setEnabled(False) self.thread1 = myThread(self.state) self.thread1.start() # self.thread1.mySig.connect(lambda i:self.progressBar.setValue(i)) self.thread1.mySig.connect(self.setbar) self.thread1.mySig1.connect(self.mat) self.thread1.mySig2.connect(self.succ_dialog) self.thread1.mySig2.connect(self.finish) def finish(self): self.mak += 1 self.pushButton.setEnabled(True) self.statusBar.showMessage('测量完成', 10**8) def mat(self): if self.state == "线缆连接测量": path = './save/1.txt' s = 1 else: path = './save/2.txt' s = 2 with open(path, 'r') as f: a = f.read().split() li = [] for i in a: li.append(eval(i)) self.c.plot(y=li, pen=pg.mkPen(color='r', width=2)) def setbar(self, a): self.progressBar.setValue(a * 10) def pause(self): self.thread1.pause() self.statusBar.showMessage('暂停测量', 10**8) self.graph.show() def go_on(self): self.thread1.goon() self.statusBar.showMessage('测量中......', 10**8) def terminate_m(self): self.thread1.terminate() self.thread1.wait() self.pushButton.setEnabled(True) self.statusBar.showMessage('测量结束!', 10**8) def writeconf(self): IP = self.LineEdit.text() start = self.LineEdit_2.text() stop = self.LineEdit_3.text() ifband = self.LineEdit_4.text() averages = self.LineEdit_6.text() power = self.LineEdit_7.text() edelay = self.LineEdit_8.text() points = self.LineEdit_9.text() outputfile = self.LineEdit_10.text() self.wr = write_conf.writeThread(IP, start, stop, averages, power, edelay, ifband, points, outputfile) self.wr.start() self.statusBar.showMessage('保存配置成功!', 10**5) def readconf(self): self.rd = read_conf.MyTh('test_all') self.rd.myOut.connect(self.set_text) self.rd.start() self.statusBar.showMessage('从本地读取配置成功', 10**4) def set_text(self, a): self.LineEdit.setText(a[0]) self.LineEdit_2.setText(a[1]) self.LineEdit_3.setText(a[2]) self.LineEdit_4.setText(a[3]) self.LineEdit_6.setText(a[4]) self.LineEdit_7.setText(a[5]) self.LineEdit_8.setText(a[6]) self.LineEdit_9.setText(a[7]) self.LineEdit_10.setText(a[8]) def fail_dialog(self): warning_dialog(self, 'shibai', 'you fail') def succ_dialog(self): information_dialog(self, '成功', '测量完成') def qss(self): self.pushButton_5.setStyleSheet( '''QPushButton{background:rgb(100,149,237);border-radius:10px;}\ QPushButton:hover{background:rgb(65,105,225);border-radius:10px;}''') self.pushButton_8.setStyleSheet( '''QPushButton{background:rgb(100,149,237);border-radius:10px;}\ QPushButton:hover{background:rgb(65,105,225);border-radius:10px;}''') self.pushButton_11.setStyleSheet( '''QPushButton{background:rgb(255,192,203);border-radius:10px;}\ QPushButton:hover{background:rgb(255,182,193);border-radius:10px;}''' )