def __init__(self, availableFeeds, browser, parent=None): """ Constructor @param availableFeeds list of available RSS feeds (list of tuple of two strings) @param browser reference to the browser widget (HelpBrowser) @param parent reference to the parent widget (QWidget) """ super(FeedsDialog, self).__init__(parent) self.setupUi(self) self.iconLabel.setPixmap(UI.PixmapCache.getPixmap("rss48.png")) self.__browser = browser self.__availableFeeds = availableFeeds[:] for row in range(len(self.__availableFeeds)): feed = self.__availableFeeds[row] button = QPushButton(self) button.setText(self.tr("Add")) button.feed = feed label = QLabel(self) label.setText(feed[0]) self.feedsLayout.addWidget(label, row, 0) self.feedsLayout.addWidget(button, row, 1) button.clicked.connect(self.__addFeed) msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
def __init__(self, tableName, parent=None): super(TableEditor, self).__init__(parent) self.model = QSqlTableModel(self) self.model.setTable(tableName) self.model.setEditStrategy(QSqlTableModel.OnManualSubmit) self.model.select() self.model.setHeaderData(0, Qt.Horizontal, "ID") self.model.setHeaderData(1, Qt.Horizontal, "First name") self.model.setHeaderData(2, Qt.Horizontal, "Last name") view = QTableView() view.setModel(self.model) submitButton = QPushButton("Submit") submitButton.setDefault(True) revertButton = QPushButton("&Revert") quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox(Qt.Vertical) buttonBox.addButton(submitButton, QDialogButtonBox.ActionRole) buttonBox.addButton(revertButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) submitButton.clicked.connect(self.submit) revertButton.clicked.connect(self.model.revertAll) quitButton.clicked.connect(self.close) mainLayout = QHBoxLayout() mainLayout.addWidget(view) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Cached Table")
def __init__(self, controller): super().__init__() self.controller = controller self.setWindowTitle('Search window') self.setMinimumSize(300, 200) self.subtypes_list = QComboBox() self.subtypes_list.addItems(name_to_obj) self.subtypes_list.activated.connect(self.update_properties) self.property_list = QComboBox() self.checkbox_regex = QCheckBox('Regex search') self.entry_search = QLineEdit() button_OK = QPushButton() button_OK.setText('OK') button_OK.clicked.connect(self.search) # position in the grid layout = QGridLayout() layout.addWidget(self.subtypes_list, 0, 0, 1, 2) layout.addWidget(self.property_list, 1, 0, 1, 2) layout.addWidget(self.checkbox_regex, 2, 0, 1, 1) layout.addWidget(self.entry_search, 3, 0, 1, 1) layout.addWidget(button_OK, 4, 0, 1, 1) self.setLayout(layout) # update property with first value of the list self.update_properties()
def _setupUi(self): self.setWindowTitle(tr("Schedule Modification Scope")) self.resize(333, 133) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(tr("Do you want this change to affect all future occurrences of this schedule?")) font = QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setWordWrap(True) self.verticalLayout.addWidget(self.label) self.label_2 = QLabel(tr( "You can force global scope (in other words, changing all future occurrences) by " "holding Shift when you perform the change." )) self.label_2.setWordWrap(True) self.verticalLayout.addWidget(self.label_2) self.horizontalLayout = QHBoxLayout() self.cancelButton = QPushButton(tr("Cancel")) self.cancelButton.setShortcut("Esc") self.horizontalLayout.addWidget(self.cancelButton) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.globalScopeButton = QPushButton(tr("All future occurrences")) self.globalScopeButton.setAutoDefault(False) self.horizontalLayout.addWidget(self.globalScopeButton) self.localScopeButton = QPushButton(tr("Just this one")) self.localScopeButton.setAutoDefault(False) self.localScopeButton.setDefault(True) self.horizontalLayout.addWidget(self.localScopeButton) self.verticalLayout.addLayout(self.horizontalLayout)
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def main_process(self): th = MyThread(10) th.start() for i in range(10): print("main process") sleep(2) def initUI(self): self.pbar = QProgressBar(self) self.pbar.setGeometry(30, 40, 200, 25) self.btn = QPushButton('Start', self) self.btn.move(40, 80) self.btn.clicked.connect(self.main_process) self.timer = QBasicTimer() self.step = 0 self.setGeometry(300, 300, 280, 170) self.setWindowTitle('QProgressBar') self.show()
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.btn = QPushButton('Dialog', self) self.btn.move(20, 20) self.btn.clicked.connect(self.showDialog) self.le = QLineEdit(self) self.le.move(130, 22) self.setGeometry(300, 300, 290, 150) self.setWindowTitle('Input dialog') self.show() def showDialog(self): """ ボタンが押されるとダイアログを出す """ # input dialogを出す text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:') if ok: # QLineEditのオブジェクトにテキストをセット self.le.setText(str(text))
def _setupUi(self): self.setWindowTitle(tr("Problems!")) self.resize(413, 323) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(self) msg = tr("There were problems processing some (or all) of the files. The cause of " "these problems are described in the table below. Those files were not " "removed from your results.") self.label.setText(msg) self.label.setWordWrap(True) self.verticalLayout.addWidget(self.label) self.tableView = QTableView(self) self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.tableView.setSelectionMode(QAbstractItemView.SingleSelection) self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableView.setShowGrid(False) self.tableView.horizontalHeader().setStretchLastSection(True) self.tableView.verticalHeader().setDefaultSectionSize(18) self.tableView.verticalHeader().setHighlightSections(False) self.verticalLayout.addWidget(self.tableView) self.horizontalLayout = QHBoxLayout() self.revealButton = QPushButton(self) self.revealButton.setText(tr("Reveal Selected")) self.horizontalLayout.addWidget(self.revealButton) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.closeButton = QPushButton(self) self.closeButton.setText(tr("Close")) self.closeButton.setDefault(True) self.horizontalLayout.addWidget(self.closeButton) self.verticalLayout.addLayout(self.horizontalLayout)
def __init__(self, parent=None): QPushButton.__init__(self, parent) self.key = None self.parent = parent self.input = None self.joystick = None self.setFocusPolicy(Qt.ClickFocus)
def __init__(self, controller): super().__init__() self.controller = controller self.setWindowTitle('Maximum flow algorithms') algorithm = QLabel('Algorithm') self.mf_list = QComboBox() self.mf_list.addItems(self.algorithms) source = QLabel('Source') self.source_edit = QLineEdit() destination = QLabel('Destination') self.destination_edit = QLineEdit() # confirmation button button_compute = QPushButton() button_compute.setText('Compute') button_compute.clicked.connect(self.compute_flow) # position in the grid layout = QGridLayout() layout.addWidget(algorithm, 0, 0, 1, 1) layout.addWidget(self.mf_list, 0, 1, 1, 1) layout.addWidget(source, 1, 0, 1, 1) layout.addWidget(self.source_edit, 1, 1, 1, 1) layout.addWidget(destination, 2, 0, 1, 1) layout.addWidget(self.destination_edit, 2, 1, 1, 1) layout.addWidget(button_compute, 3, 0, 1, 2) self.setLayout(layout)
def add_button(self, x, y, text, i, page): button = QPushButton('Button', self.steps[page][5]) button.setText(text) button.setGeometry(x, y, 26, 22) button.clicked.connect(lambda: self.set_step(i+1, page, button)) return button
def __init__(self, parent, color=None): QPushButton.__init__(self, parent) self.parent = parent self.setColor(color) self.clicked.connect(self.onClick) self.setMinimumSize(QSize(25, 25)) self.setMaximumSize(QSize(25, 25))
class CueItemWidget(QWidget): def __init__(self, target, action, cue_dialog, **kwargs): super().__init__(**kwargs) self.target = target self.cue_dialog = cue_dialog self.setLayout(QHBoxLayout(self)) self.layout().setContentsMargins(2, 1, 2, 1) self.selectButton = QPushButton(self) self.selectButton.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) self.selectButton.setText(target.name) self.selectButton.setToolTip(target.name) self.selectButton.clicked.connect(self.select_target) self.layout().addWidget(self.selectButton) self.targetActionsCombo = QComboBox(self) self.targetActionsCombo.addItems([a.name for a in CueAction]) self.targetActionsCombo.setCurrentText(CueAction[action].name) self.layout().addWidget(self.targetActionsCombo) self.layout().setStretch(0, 3) self.layout().setStretch(1, 1) def get_target(self): return self.target.id, self.targetActionsCombo.currentText() def select_target(self): if self.cue_dialog.exec_() == QDialog.Accepted: self.target = self.cue_dialog.selected_cues()[0] self.selectButton.setText(self.target.name) self.selectButton.setToolTip(self.target.name)
def __init__(self, mode, obj, AS=set(), controller=None): super().__init__() title = 'Add to area' if mode == 'add' else 'Remove from area' self.setWindowTitle(title) values = tuple(map(str, AS)) # list of existing AS self.AS_list = QComboBox() self.AS_list.addItems(values) self.AS_list.activated.connect(self.update_value) # list of areas self.area_list = QComboBox() self.update_value() # confirmation button button_area_operation = QPushButton() button_area_operation.setText('OK') button_area_operation.clicked.connect(lambda: self.area_operation(mode, *obj)) # position in the grid layout = QGridLayout() layout.addWidget(self.AS_list, 0, 0, 1, 2) layout.addWidget(self.area_list, 1, 0, 1, 2) layout.addWidget(button_area_operation, 2, 0, 1, 1) layout.addWidget(cancel_button, 2, 1, 1, 1) self.setLayout(layout)
def intervalButtons(self): widget = QGroupBox('Interval') group = QButtonGroup(widget) layout = QHBoxLayout() widget.setLayout(layout) def setInterval(): self.interval = group.checkedId() interval = self.INTERVALS[self.interval][0] self.updateTitle() if interval: self.progress.show() self.progress.setMaximum(interval) value = self.timer.seconds() if value < interval: self.progress.resume() else: self.progress.stop() self.progress.setValue(min(interval, value)) else: self.progress.hide() for i, interval in enumerate(self.INTERVALS): button = QPushButton(interval[1]) button.setCheckable(True) button.clicked.connect(setInterval) group.addButton(button, i) layout.addWidget(button, 1 if i > 0 else 0) return widget
class QueryHistoryWidget(QWidget): def __init__(self, parent): super(QueryHistoryWidget, self).__init__(parent) self.selected_query = None self.list = QTreeView(self) self.model = QueryListModel(self) self.re_exec = QPushButton(self) self.select = QPushButton(self) self.grid = QGridLayout(self) self.ui() self.properties() def execute(self): # color = self.color.color.name(QtGui.QColor.HexRgb) query = Query(self.input.toPlainText()) query.execute() def properties(self): self.select.setText("Select") self.re_exec.setText("Re execute") def ui(self): self.grid.addWidget(self.list, 0, 0, 1, 10) self.grid.addWidget(self.select, 1, 0, 1, 1) self.grid.addWidget(self.re_exec, 1, 1, 1, 1)
def virtual_keyboard(self, i, pw): i = i % 3 if i == 0: chars = 'abcdefghijklmnopqrstuvwxyz ' elif i == 1: chars = 'ABCDEFGHIJKLMNOPQRTSUVWXYZ ' elif i == 2: chars = '1234567890!?.,;:/%&()[]{}+-' n = len(chars) s = [] for i in range(n): while True: k = random.randint(0, n - 1) if k not in s: s.append(k) break def add_target(t): return lambda: pw.setText(str(pw.text()) + t) vbox = QVBoxLayout() grid = QGridLayout() grid.setSpacing(2) for i in range(n): l_button = QPushButton(chars[s[i]]) l_button.setFixedWidth(25) l_button.setFixedHeight(25) l_button.clicked.connect(add_target(chars[s[i]])) grid.addWidget(l_button, i // 6, i % 6) vbox.addLayout(grid) return vbox
class Example(QWidget): def __init__(self): QWidget.__init__(self) self.initUI() def initUI(self): self.btn = QPushButton("Dialog", self) self.btn.move(20, 20) self.btn.clicked.connect(self.showDialog) self.le = QLineEdit(self) self.le.move(130, 22) self.setGeometry(300, 300, 290, 150) self.setWindowTitle("Input dialog") self.show() def showDialog(self): text, ok = QInputDialog.getText(self, "Input Dialog", "Enter your name:") if ok: self.le.setText(str(text))
def _setupUi(self): self.setWindowTitle(tr("Error Report")) self.resize(553, 349) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(self) self.label.setText(tr("Something went wrong. How about reporting the error?")) self.label.setWordWrap(True) self.verticalLayout.addWidget(self.label) self.errorTextEdit = QPlainTextEdit(self) self.errorTextEdit.setReadOnly(True) self.verticalLayout.addWidget(self.errorTextEdit) msg = tr( "Error reports should be reported as Github issues. You can copy the error traceback " "above and paste it in a new issue (bonus point if you run a search to make sure the " "issue doesn't already exist). What usually really helps is if you add a description " "of how you got the error. Thanks!" "\n\n" "Although the application should continue to run after this error, it may be in an " "unstable state, so it is recommended that you restart the application." ) self.label2 = QLabel(msg) self.label2.setWordWrap(True) self.verticalLayout.addWidget(self.label2) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.addItem(horizontalSpacer()) self.dontSendButton = QPushButton(self) self.dontSendButton.setText(tr("Close")) self.dontSendButton.setMinimumSize(QSize(110, 0)) self.horizontalLayout.addWidget(self.dontSendButton) self.sendButton = QPushButton(self) self.sendButton.setText(tr("Go to Github")) self.sendButton.setMinimumSize(QSize(110, 0)) self.sendButton.setDefault(True) self.horizontalLayout.addWidget(self.sendButton) self.verticalLayout.addLayout(self.horizontalLayout)
def password_dialog(self, pw, grid, pos): vkb_button = QPushButton(_("+")) vkb_button.setFixedWidth(20) vkb_button.clicked.connect(lambda: self.toggle_vkb(grid, pw)) grid.addWidget(vkb_button, pos, 2) self.kb_pos = 2 self.vkb = None
class window(QWidget): def __init__(self): super().__init__() self.grid = QGridLayout() self.text = QTextEdit() self.btn = QPushButton() self.btn.setText('Send') self.btn.clicked.connect(self.sendMessage) self.message = QLineEdit() self.grid.addWidget(self.text,1,1,2,2) self.grid.addWidget(self.message,3,1,1,1) self.grid.addWidget(self.btn,3,2,1,1) self.setLayout(self.grid) self.updateThread = updateThread() self.updateThread.signal.connect(self.updateMessages, Qt.QueuedConnection) self.updateThread.start() def sendMessage(self, signal): client.sendMessage(self.message.text()) def updateMessages(self, signal): self.text.append(signal)
def _setupUi(self): self.resize(259, 32) self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.prevButton = QPushButton(self) icon = QIcon() icon.addPixmap(QPixmap(":/nav_left_9"), QIcon.Normal, QIcon.Off) self.prevButton.setIcon(icon) self.horizontalLayout.addWidget(self.prevButton) self.typeButton = QPushButton("<date range>") sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.typeButton.sizePolicy().hasHeightForWidth()) self.typeButton.setSizePolicy(sizePolicy) self.typeButton.setMinimumSize(QSize(0, 0)) self.typeButton.setMaximumSize(QSize(16777215, 16777215)) self.typeButton.setIconSize(QSize(6, 6)) self.horizontalLayout.addWidget(self.typeButton) self.nextButton = QPushButton(self) icon1 = QIcon() icon1.addPixmap(QPixmap(":/nav_right_9"), QIcon.Normal, QIcon.Off) self.nextButton.setIcon(icon1) self.horizontalLayout.addWidget(self.nextButton) self.horizontalLayout.setStretch(1, 1)
def __init__(self, parent=None): super(Win, self).__init__(parent) self.player = None # args parser = argparse.ArgumentParser(description='BBC radio player') parser.add_argument('-p', '--player', default='vlc') parser.add_argument('player_args', nargs='*') args = parser.parse_args() self.player_prog = args.player self.player_args = args.player_args # UI self.setWindowTitle(WIN_TITLE) self.setMinimumSize(300, 600) self.scroll_area = QScrollArea() self.widget = QWidget() self.layout = QVBoxLayout() self.widget.setLayout(self.layout) self.scroll_area.setWidgetResizable(True) self.scroll_area.setWidget(self.widget) self.setCentralWidget(self.scroll_area) for name, url in STATIONS: button = QPushButton(name.replace('&', '&&')) button.args = { 'name': name, 'url': url, } button.clicked.connect(self.listen) self.layout.addWidget(button) # timer self.timer = QTimer() self.timer.timeout.connect(self.check_player)
def addNickScreen(self): self.chat_log.setEnabled(False) self.chat_input.setEnabled(False) self.send_button.setEnabled(False) self.addNickButton.hide() self.addUserText = QLabel("Enter a username to add a user to the group chat.", self) self.addUserText.setGeometry(200, 20, 300, 100) self.addUserText.show() self.user = QLineEdit(self) self.user.setGeometry(200, 120, 240, 20) self.user.returnPressed.connect(self.addUser) self.user.show() self.addUserButton = QPushButton('Add User', self) self.addUserButton.setGeometry(250, 150, 150, 25) self.addUserButton.clicked.connect(lambda: self.addUser(self.user)) self.addUserButton.show() self.cancel = QPushButton('Cancel', self) self.cancel.setGeometry(298, 210, 51, 23) self.cancel.clicked.connect(lambda: self.chat_log.setEnabled(True)) self.cancel.clicked.connect(lambda: self.chat_input.setEnabled(True)) self.cancel.clicked.connect(lambda: self.send_button.setEnabled(True)) self.cancel.clicked.connect(self.addUserText.hide) self.cancel.clicked.connect(self.user.hide) self.cancel.clicked.connect(self.addUserButton.hide) self.cancel.clicked.connect(self.addNickButton.show) self.cancel.clicked.connect(self.cancel.hide) self.cancel.show()
def _setupUi(self): self.resize(340, 165) self.setWindowTitle(tr("Re-assign Account")) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(self) self.label.setWordWrap(True) self.label.setText(tr( "You\'re about to delete a non-empty account. Select an account to re-assign its " "transactions to." )) self.verticalLayout.addWidget(self.label) self.accountComboBoxView = QComboBox(self) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.accountComboBoxView.sizePolicy().hasHeightForWidth()) self.accountComboBoxView.setSizePolicy(sizePolicy) self.accountComboBoxView.setMinimumSize(QSize(200, 0)) self.verticalLayout.addWidget(self.accountComboBoxView) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem) self.horizontalLayout = QHBoxLayout() spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem1) self.cancelButton = QPushButton(self) self.cancelButton.setText(tr("Cancel")) self.cancelButton.setShortcut("Esc") self.horizontalLayout.addWidget(self.cancelButton) self.continueButton = QPushButton(self) self.continueButton.setDefault(True) self.continueButton.setText(tr("Continue")) self.horizontalLayout.addWidget(self.continueButton) self.verticalLayout.addLayout(self.horizontalLayout)
def __init__(self, parent=None): super().__init__(parent) self.create_title_layout = QHBoxLayout() self.collection_title_layout = QHBoxLayout() self.local_title_layout = QHBoxLayout() self.recommend_title = QLabel(u'推荐') self.create_title = QLabel(u'创建的歌单') self.collection_title = QLabel(u'收藏的歌单') self.local_title = QLabel(u'本地歌单') self.create_fold_spread_btn = QPushButton() self.collection_fold_spread_btn = QPushButton() self.local_fold_spread_btn = QPushButton() self.new_playlist_btn = QPushButton('+') self.recommend_list_widget = SpreadWidget() self.create_list_widget = SpreadWidget() self.collection_list_widget = SpreadWidget() self.local_list_widget = SpreadWidget() self.fm_item = RecommendItem(self.recommend_list_widget, "私人FM", QPixmap(ICON_PATH + '/fm.png')) self.recommend_item = RecommendItem( self.recommend_list_widget, "每日推荐", QPixmap(ICON_PATH + '/recommend.png')) self.layout = QVBoxLayout() self.set_widgets_prop() self.set_layouts_prop() self.set_me()
def __init__(self, parent=None, button_func=None, params=None): super().__init__(parent, 'Results', params) self.button_func = button_func self.make_tables(self.params.results['algorithms'], self.params.algorithms) self.vbox.addStretch() btn_re = QPushButton('Re-analyze', self.inner) btn_re.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};') if self.params.lang == 'en': btn_re.clicked.connect(lambda: self.button_func('Analysis')) else: btn_re.clicked.connect(lambda: self.button_func('分析の実行')) self.btn_next = QPushButton('Continue without any changes', self.inner) self.btn_next.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};') if self.params.lang == 'en': self.btn_next.clicked.connect(lambda: self.button_func( 'Bias and Variance')) else: self.btn_next.clicked.connect(lambda: self.button_func( 'バイアスとバリアンス')) self.vbox.addWidget(btn_re) self.vbox.addWidget(self.btn_next)
class Record(QWidget): """docstring for Record""" def __init__(self): super(Record, self).__init__() # self.arg = arg self.seButton = QPushButton('begin') self.seButton.buttonState = 'begin' self.seButton.clicked.connect(self.beginOendTime) self.ticker = Ticker() self.ticker.start() self.lineedit = QLineEdit() buttonarea = QVBoxLayout() buttonarea.addWidget(self.seButton) buttonarea.addWidget(self.ticker) buttonarea.addWidget(self.lineedit) self.setLayout(buttonarea) def beginOendTime(self): # self.ticker.run() if self.seButton.buttonState == 'begin': # pass self.ticker.startTick() self.seButton.setText('stop') self.seButton.buttonState = 'stop' elif self.seButton.buttonState == 'stop': self.ticker.stopTick() self.seButton.setText('begin') self.seButton.buttonState = 'begin'
def initUi (self, delete_entries): delete_entries.setObjectName(_fromUtf8("delete_entries")) delete_entries.resize(472, 239) self.button_exit = QPushButton(delete_entries) self.button_exit.setGeometry(QtCore.QRect(350, 200, 110, 32)) self.button_exit.setObjectName(_fromUtf8("button_exit")) self.button_delete = QPushButton(delete_entries) self.button_delete.setGeometry(QtCore.QRect(240, 200, 110, 32)) self.button_delete.setObjectName(_fromUtf8("button_delete")) self.edit = QTextEdit(delete_entries) self.edit.setGeometry(QtCore.QRect(20, 50, 431, 141)) self.edit.setObjectName(_fromUtf8("edit")) self.label = QLabel(delete_entries) self.label.setGeometry(QtCore.QRect(60, 0, 431, 31)) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QLabel(delete_entries) self.label_2.setGeometry(QtCore.QRect(50, 20, 431, 31)) self.label_2.setObjectName(_fromUtf8("label_2")) self.retranslateUi(delete_entries) QtCore.QMetaObject.connectSlotsByName(delete_entries) #self.connect(self.button_exit, QtCore.SIGNAL("released()"), self.exit) #self.connect(self.button_delete, QtCore.SIGNAL("released()"), self.suppression) self.button_exit.clicked.connect(self.exit) self.button_delete.clicked.connect(self.suppression)
def __init__(self, parent=None, button_func=None, params=None): super().__init__(parent, 'Results2', params) self.button_func = button_func self.make_tables(self.params.results_fs['algorithms'], self.params.algorithms_fs) self.vbox.addStretch() btn_re = QPushButton('Re-analyze', self.inner) btn_re.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};') if self.params.lang == 'en': btn_re.clicked.connect( lambda: self.button_func('Feature selection')) else: btn_re.clicked.connect( lambda: self.button_func('特徴量選択')) self.btn_next = QPushButton('Continue without any changes', self.inner) self.btn_next.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};') if self.params.lang == 'en': self.btn_next.clicked.connect(lambda: self.button_func( 'Learning curve 2')) else: self.btn_next.clicked.connect(lambda: self.button_func( '学習曲線2')) self.vbox.addWidget(btn_re) self.vbox.addWidget(self.btn_next)
def _get_control_layout(self): """ Create static layout. """ widget = QWidget() vbox = QVBoxLayout() widget.setLayout(vbox) vbox.setContentsMargins(0, 0, 0, 0) self.template_combo_box = QComboBox() self.template_combo_box.currentIndexChanged.connect(self._item_selected) vbox.addWidget(self.template_combo_box) scrollable_vbox = utils.get_scrollable(self.controls_layout) vbox.addWidget(scrollable_vbox, stretch=80) buttons_layout = QHBoxLayout() vbox.addLayout(buttons_layout, stretch=20) b = QPushButton("Назад") b.setObjectName("controls") b.clicked.connect(self._close) buttons_layout.addWidget(b) widget.setGraphicsEffect(utils.get_shadow()) return widget
def __init__(self, metadatas: t_.List[t_.Tuple[ pwsdt.Acquisition, t_.Optional[AnalysisViewer.AnalysisResultsComboType]]], roiManager: ROIManager = None, parent=None, flags=QtCore.Qt.Window, title: str = "Roi Drawer 3000", initialField=AnalysisViewer.PlotFields.Thumbnail): QWidget.__init__(self, parent=parent, flags=flags) self.setWindowTitle(title) self.metadatas = metadatas layout = QGridLayout() self._mdIndex = 0 self.roiManager = roiManager if roiManager else _DefaultROIManager( self) self.anViewer = AnalysisViewer(self.metadatas[self._mdIndex][0], self.metadatas[self._mdIndex][1], title, initialField=initialField, roiManager=self.roiManager) self.anViewer.roiPlot.roiDeleted.connect( lambda acq, roi: self.roiDeleted.emit(acq, roi)) self.anViewer.roiPlot.roiModified.connect( lambda acq, roi: self.roiModified.emit(acq, roi)) self.anViewer.roiPlot.roiCreated.connect( lambda acq, roi: self.roiCreated.emit(acq, roi, False)) self.newRoiDlg = NewRoiDlg(self) self.noneButton = QPushButton("Inspect") self.lassoButton = QPushButton("Lasso") self.lassoButton.setToolTip(LassoCreator.getHelpText()) self.ellipseButton = QPushButton("Ellipse") self.ellipseButton.setToolTip(EllipseCreator.getHelpText()) self.paintButton = QPushButton("Paint") self.paintButton.setToolTip(RegionalPaintCreator.getHelpText()) self.lastButton_ = None self.buttonGroup = QButtonGroup(self) self.buttonGroup.addButton(self.noneButton) self.buttonGroup.addButton(self.lassoButton) self.buttonGroup.addButton(self.ellipseButton) self.buttonGroup.addButton(self.paintButton) self.buttonGroup.buttonReleased.connect(self.handleButtons) [i.setCheckable(True) for i in self.buttonGroup.buttons()] self.noneButton.setChecked( True ) #This doesn't seem to trigger handle buttons. we'll do that at the end of the constructor def handleAdjustButton(checkstate: bool): if self.selector is not None: self.selector.adjustable = checkstate self.adjustButton = QPushButton("Tune") self.adjustButton.setToolTip(PolygonModifier.getHelpText()) self.adjustButton.setCheckable(True) self.adjustButton.setMaximumWidth(50) self.adjustButton.toggled.connect(handleAdjustButton) def showNextCell(): idx = self._mdIndex + 1 if idx >= len(self.metadatas): idx = 0 self._updateDisplayedCell(idx) def showPreviousCell(): idx = self._mdIndex - 1 if idx < 0: idx = len(self.metadatas) - 1 self._updateDisplayedCell(idx) self.previousButton = QPushButton('←') self.nextButton = QPushButton('→') self.previousButton.released.connect(showPreviousCell) self.nextButton.released.connect(showNextCell) layout.addWidget(self.noneButton, 0, 0, 1, 1) layout.addWidget(self.lassoButton, 0, 1, 1, 1) layout.addWidget(self.ellipseButton, 0, 2, 1, 1) layout.addWidget(self.paintButton, 0, 3, 1, 1) layout.addWidget(self.adjustButton, 0, 4, 1, 1) layout.addWidget(self.previousButton, 0, 6, 1, 1) layout.addWidget(self.nextButton, 0, 7, 1, 1) layout.addWidget(self.anViewer, 1, 0, 8, 8) self.setLayout(layout) self.selector: AdjustableSelector = AdjustableSelector( self.anViewer.roiPlot.ax, self.anViewer.roiPlot.im, LassoCreator, onfinished=self.finalizeRoi, onPolyTuningCancelled=lambda: self.selector.setActive(True)) self.handleButtons(self.noneButton) # Helps initialize state self.show()
class Converter(QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initUi() self.initLayouts() self.initSignals() self.changeBtn() def initUi(self): self.setWindowTitle('Конвертер валют') self.srcLabel = QLabel('Сумма в рублях', self) self.resultLabel = QLabel('Сумма в долларах', self) self.srcAmount = QDoubleSpinBox(self) self.srcAmount.setMaximum(999999999) self.resultAmount = QDoubleSpinBox(self) self.resultAmount.setMaximum(999999999) #self.resultAmount.setReadOnly(True) self.convertBtn = QPushButton('Перевести', self) self.clearBtn = QPushButton('Сброс', self) def initSignals(self): self.convertBtn.clicked.connect(self.onClickConvertBtn) self.clearBtn.clicked.connect(self.clearAmounts) self.srcAmount.valueChanged.connect(self.changeBtn) self.resultAmount.valueChanged.connect(self.changeBtn) def initLayouts(self): w = QWidget(self) self.mainLayout = QVBoxLayout(w) self.mainLayout.addWidget(self.srcLabel) self.mainLayout.addWidget(self.srcAmount) self.mainLayout.addWidget(self.resultLabel) self.mainLayout.addWidget(self.resultAmount) self.mainLayout.addWidget(self.convertBtn) self.mainLayout.addWidget(self.clearBtn) self.setCentralWidget(w) def onClickConvertBtn(self): value = self.srcAmount.value() if self.srcAmount.value(): self.resultAmount.setValue(value / 30) else: self.srcAmount.setValue(self.resultAmount.value() * 30) def keyPressEvent(self, e): if e.key() == Qt.Key_Return: self.onClickConvertBtn() def clearAmounts(self): self.resultAmount.setValue(0) self.srcAmount.setValue(0) self.changeBtn() def changeBtn(self): v1 = self.srcAmount.value() v2 = self.resultAmount.value() if (not v1 and not v2) or (v1 and v2): self.convertBtn.setEnabled(False) else: self.convertBtn.setEnabled(True)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # See http://www.gchagnon.fr/cours/python/pyqt.html#mep import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QGridLayout, QSizePolicy app = QApplication(sys.argv) # Make widgets window = QWidget() btn1 = QPushButton("One") btn2 = QPushButton("Two") btn3 = QPushButton("Three") btn4 = QPushButton("Four") # Set the layout grid = QGridLayout() grid.addWidget(btn1, 1, 1) # QWidget, row (int), column (int), rowSpan (int), columnSpan (int), alignment grid.addWidget(btn2, 2, 2) grid.addWidget(btn3, 3, 1, 1, 2) grid.addWidget(btn4, 1, 3, 2, 1) btn4.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # http://doc.qt.io/qt-5/qsizepolicy.html ; https://stackoverflow.com/questions/40580749/why-do-some-widgets-not-stretch-to-fill-the-maximum-space-in-a-layout
def __init__(self, *args): super().__init__(BrickletIndustrialDualAnalogIn, *args) self.analog_in = self.device # the firmware version of a EEPROM Bricklet can (under common circumstances) # not change during the lifetime of an EEPROM Bricklet plugin. therefore, # it's okay to make final decisions based on it here self.has_fixed_calibration = self.firmware_version >= (2, 0, 1) self.cbe_voltage0 = CallbackEmulator(self, self.analog_in.get_voltage, 0, self.cb_voltage, self.increase_error_count, pass_arguments_to_result_callback=True) self.cbe_voltage1 = CallbackEmulator(self, self.analog_in.get_voltage, 1, self.cb_voltage, self.increase_error_count, pass_arguments_to_result_callback=True) self.calibration = None self.sample_rate_label = QLabel('Sample Rate:') self.sample_rate_combo = QComboBox() self.sample_rate_combo.addItem('976 Hz') self.sample_rate_combo.addItem('488 Hz') self.sample_rate_combo.addItem('244 Hz') self.sample_rate_combo.addItem('122 Hz') self.sample_rate_combo.addItem('61 Hz') self.sample_rate_combo.addItem('4 Hz') self.sample_rate_combo.addItem('2 Hz') self.sample_rate_combo.addItem('1 Hz') self.current_voltage = [CurveValueWrapper(), CurveValueWrapper()] # float, V self.calibration_button = QPushButton('Calibration...') self.sample_rate_combo.currentIndexChanged.connect(self.sample_rate_combo_index_changed) self.calibration_button.clicked.connect(self.calibration_button_clicked) plots = [('Channel 0', Qt.red, self.current_voltage[0], format_voltage), ('Channel 1', Qt.blue, self.current_voltage[1], format_voltage)] self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001) hlayout = QHBoxLayout() hlayout.addWidget(self.sample_rate_label) hlayout.addWidget(self.sample_rate_combo) hlayout.addStretch() hlayout.addWidget(self.calibration_button) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout)
class IndustrialDualAnalogIn(PluginBase): def __init__(self, *args): super().__init__(BrickletIndustrialDualAnalogIn, *args) self.analog_in = self.device # the firmware version of a EEPROM Bricklet can (under common circumstances) # not change during the lifetime of an EEPROM Bricklet plugin. therefore, # it's okay to make final decisions based on it here self.has_fixed_calibration = self.firmware_version >= (2, 0, 1) self.cbe_voltage0 = CallbackEmulator(self, self.analog_in.get_voltage, 0, self.cb_voltage, self.increase_error_count, pass_arguments_to_result_callback=True) self.cbe_voltage1 = CallbackEmulator(self, self.analog_in.get_voltage, 1, self.cb_voltage, self.increase_error_count, pass_arguments_to_result_callback=True) self.calibration = None self.sample_rate_label = QLabel('Sample Rate:') self.sample_rate_combo = QComboBox() self.sample_rate_combo.addItem('976 Hz') self.sample_rate_combo.addItem('488 Hz') self.sample_rate_combo.addItem('244 Hz') self.sample_rate_combo.addItem('122 Hz') self.sample_rate_combo.addItem('61 Hz') self.sample_rate_combo.addItem('4 Hz') self.sample_rate_combo.addItem('2 Hz') self.sample_rate_combo.addItem('1 Hz') self.current_voltage = [CurveValueWrapper(), CurveValueWrapper()] # float, V self.calibration_button = QPushButton('Calibration...') self.sample_rate_combo.currentIndexChanged.connect(self.sample_rate_combo_index_changed) self.calibration_button.clicked.connect(self.calibration_button_clicked) plots = [('Channel 0', Qt.red, self.current_voltage[0], format_voltage), ('Channel 1', Qt.blue, self.current_voltage[1], format_voltage)] self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001) hlayout = QHBoxLayout() hlayout.addWidget(self.sample_rate_label) hlayout.addWidget(self.sample_rate_combo) hlayout.addStretch() hlayout.addWidget(self.calibration_button) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout) def start(self): async_call(self.analog_in.get_sample_rate, None, self.get_sample_rate_async, self.increase_error_count) self.cbe_voltage0.set_period(100) self.cbe_voltage1.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_voltage0.set_period(0) self.cbe_voltage1.set_period(0) self.plot_widget.stop = True def destroy(self): if self.calibration != None: self.calibration.close() @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletIndustrialDualAnalogIn.DEVICE_IDENTIFIER def get_voltage_value0(self): return self.voltage_value[0] def get_voltage_value1(self): return self.voltage_value[1] def calibration_button_clicked(self): if self.calibration == None: self.calibration = Calibration(self) self.calibration_button.setEnabled(False) self.calibration.show() def sample_rate_combo_index_changed(self, index): async_call(self.analog_in.set_sample_rate, index, None, self.increase_error_count) def get_sample_rate_async(self, rate): self.sample_rate_combo.setCurrentIndex(rate) def cb_voltage(self, sensor, voltage): self.current_voltage[sensor].value = voltage / 1000.0
def select_storage( self, path, get_wallet_from_daemon) -> Tuple[str, Optional[WalletStorage]]: vbox = QVBoxLayout() hbox = QHBoxLayout() hbox.addWidget(QLabel(_('Wallet') + ':')) self.name_e = QLineEdit() hbox.addWidget(self.name_e) button = QPushButton(_('Choose...')) hbox.addWidget(button) vbox.addLayout(hbox) self.msg_label = QLabel('') vbox.addWidget(self.msg_label) hbox2 = QHBoxLayout() self.pw_e = QLineEdit('', self) self.pw_e.setFixedWidth(150) self.pw_e.setEchoMode(2) self.pw_label = QLabel(_('Password') + ':') hbox2.addWidget(self.pw_label) hbox2.addWidget(self.pw_e) hbox2.addStretch() vbox.addLayout(hbox2) self.set_layout(vbox, title=_('Vialectrum wallet')) self.temp_storage = WalletStorage(path, manual_upgrades=True) wallet_folder = os.path.dirname(self.temp_storage.path) def on_choose(): path, __ = QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder) if path: self.name_e.setText(path) def on_filename(filename): path = os.path.join(wallet_folder, filename) wallet_from_memory = get_wallet_from_daemon(path) try: if wallet_from_memory: self.temp_storage = wallet_from_memory.storage else: self.temp_storage = WalletStorage(path, manual_upgrades=True) self.next_button.setEnabled(True) except BaseException: self.logger.exception('') self.temp_storage = None self.next_button.setEnabled(False) user_needs_to_enter_password = False if self.temp_storage: if not self.temp_storage.file_exists(): msg =_("This file does not exist.") + '\n' \ + _("Press 'Next' to create this wallet, or choose another file.") elif not wallet_from_memory: if self.temp_storage.is_encrypted_with_user_pw(): msg = _("This file is encrypted with a password.") + '\n' \ + _('Enter your password or choose another file.') user_needs_to_enter_password = True elif self.temp_storage.is_encrypted_with_hw_device(): msg = _("This file is encrypted using a hardware device.") + '\n' \ + _("Press 'Next' to choose device to decrypt.") else: msg = _("Press 'Next' to open this wallet.") else: msg = _("This file is already open in memory.") + "\n" \ + _("Press 'Next' to create/focus window.") else: msg = _('Cannot read file') self.msg_label.setText(msg) if user_needs_to_enter_password: self.pw_label.show() self.pw_e.show() self.pw_e.setFocus() else: self.pw_label.hide() self.pw_e.hide() button.clicked.connect(on_choose) self.name_e.textChanged.connect(on_filename) n = os.path.basename(self.temp_storage.path) self.name_e.setText(n) while True: if self.loop.exec_() != 2: # 2 = next raise UserCancelled if self.temp_storage.file_exists( ) and not self.temp_storage.is_encrypted(): break if not self.temp_storage.file_exists(): break wallet_from_memory = get_wallet_from_daemon(self.temp_storage.path) if wallet_from_memory: raise WalletAlreadyOpenInMemory(wallet_from_memory) if self.temp_storage.file_exists( ) and self.temp_storage.is_encrypted(): if self.temp_storage.is_encrypted_with_user_pw(): password = self.pw_e.text() try: self.temp_storage.decrypt(password) break except InvalidPassword as e: self.show_message(title=_('Error'), msg=str(e)) continue except BaseException as e: self.logger.exception('') self.show_message(title=_('Error'), msg=str(e)) raise UserCancelled() elif self.temp_storage.is_encrypted_with_hw_device(): try: self.run('choose_hw_device', HWD_SETUP_DECRYPT_WALLET, storage=self.temp_storage) except InvalidPassword as e: self.show_message( title=_('Error'), msg=_( 'Failed to decrypt using this hardware device.' ) + '\n' + _('If you use a passphrase, make sure it is correct.' )) self.reset_stack() return self.select_storage(path, get_wallet_from_daemon) except BaseException as e: self.logger.exception('') self.show_message(title=_('Error'), msg=str(e)) raise UserCancelled() if self.temp_storage.is_past_initial_decryption(): break else: raise UserCancelled() else: raise Exception('Unexpected encryption version') return self.temp_storage.path, ( self.temp_storage if self.temp_storage.file_exists() else None) #
class InstallWizard(QDialog, MessageBoxMixin, BaseWizard): accept_signal = pyqtSignal() def __init__(self, config, app, plugins): QDialog.__init__(self, None) BaseWizard.__init__(self, config, plugins) self.setWindowTitle('Vialectrum - ' + _('Install Wizard')) self.app = app self.config = config # Set for base base class self.language_for_seed = config.get('language') self.setMinimumSize(600, 400) self.accept_signal.connect(self.accept) self.title = QLabel() self.main_widget = QWidget() self.back_button = QPushButton(_("Back"), self) self.back_button.setText( _('Back') if self.can_go_back() else _('Cancel')) self.next_button = QPushButton(_("Next"), self) self.next_button.setDefault(True) self.logo = QLabel() self.please_wait = QLabel(_("Please wait...")) self.please_wait.setAlignment(Qt.AlignCenter) self.icon_filename = None self.loop = QEventLoop() self.rejected.connect(lambda: self.loop.exit(0)) self.back_button.clicked.connect(lambda: self.loop.exit(1)) self.next_button.clicked.connect(lambda: self.loop.exit(2)) outer_vbox = QVBoxLayout(self) inner_vbox = QVBoxLayout() inner_vbox.addWidget(self.title) inner_vbox.addWidget(self.main_widget) inner_vbox.addStretch(1) inner_vbox.addWidget(self.please_wait) inner_vbox.addStretch(1) scroll_widget = QWidget() scroll_widget.setLayout(inner_vbox) scroll = QScrollArea() scroll.setWidget(scroll_widget) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setWidgetResizable(True) icon_vbox = QVBoxLayout() icon_vbox.addWidget(self.logo) icon_vbox.addStretch(1) hbox = QHBoxLayout() hbox.addLayout(icon_vbox) hbox.addSpacing(5) hbox.addWidget(scroll) hbox.setStretchFactor(scroll, 1) outer_vbox.addLayout(hbox) outer_vbox.addLayout(Buttons(self.back_button, self.next_button)) self.set_icon('vialectrum.png') self.show() self.raise_() self.refresh_gui() # Need for QT on MacOSX. Lame. def select_storage( self, path, get_wallet_from_daemon) -> Tuple[str, Optional[WalletStorage]]: vbox = QVBoxLayout() hbox = QHBoxLayout() hbox.addWidget(QLabel(_('Wallet') + ':')) self.name_e = QLineEdit() hbox.addWidget(self.name_e) button = QPushButton(_('Choose...')) hbox.addWidget(button) vbox.addLayout(hbox) self.msg_label = QLabel('') vbox.addWidget(self.msg_label) hbox2 = QHBoxLayout() self.pw_e = QLineEdit('', self) self.pw_e.setFixedWidth(150) self.pw_e.setEchoMode(2) self.pw_label = QLabel(_('Password') + ':') hbox2.addWidget(self.pw_label) hbox2.addWidget(self.pw_e) hbox2.addStretch() vbox.addLayout(hbox2) self.set_layout(vbox, title=_('Vialectrum wallet')) self.temp_storage = WalletStorage(path, manual_upgrades=True) wallet_folder = os.path.dirname(self.temp_storage.path) def on_choose(): path, __ = QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder) if path: self.name_e.setText(path) def on_filename(filename): path = os.path.join(wallet_folder, filename) wallet_from_memory = get_wallet_from_daemon(path) try: if wallet_from_memory: self.temp_storage = wallet_from_memory.storage else: self.temp_storage = WalletStorage(path, manual_upgrades=True) self.next_button.setEnabled(True) except BaseException: self.logger.exception('') self.temp_storage = None self.next_button.setEnabled(False) user_needs_to_enter_password = False if self.temp_storage: if not self.temp_storage.file_exists(): msg =_("This file does not exist.") + '\n' \ + _("Press 'Next' to create this wallet, or choose another file.") elif not wallet_from_memory: if self.temp_storage.is_encrypted_with_user_pw(): msg = _("This file is encrypted with a password.") + '\n' \ + _('Enter your password or choose another file.') user_needs_to_enter_password = True elif self.temp_storage.is_encrypted_with_hw_device(): msg = _("This file is encrypted using a hardware device.") + '\n' \ + _("Press 'Next' to choose device to decrypt.") else: msg = _("Press 'Next' to open this wallet.") else: msg = _("This file is already open in memory.") + "\n" \ + _("Press 'Next' to create/focus window.") else: msg = _('Cannot read file') self.msg_label.setText(msg) if user_needs_to_enter_password: self.pw_label.show() self.pw_e.show() self.pw_e.setFocus() else: self.pw_label.hide() self.pw_e.hide() button.clicked.connect(on_choose) self.name_e.textChanged.connect(on_filename) n = os.path.basename(self.temp_storage.path) self.name_e.setText(n) while True: if self.loop.exec_() != 2: # 2 = next raise UserCancelled if self.temp_storage.file_exists( ) and not self.temp_storage.is_encrypted(): break if not self.temp_storage.file_exists(): break wallet_from_memory = get_wallet_from_daemon(self.temp_storage.path) if wallet_from_memory: raise WalletAlreadyOpenInMemory(wallet_from_memory) if self.temp_storage.file_exists( ) and self.temp_storage.is_encrypted(): if self.temp_storage.is_encrypted_with_user_pw(): password = self.pw_e.text() try: self.temp_storage.decrypt(password) break except InvalidPassword as e: self.show_message(title=_('Error'), msg=str(e)) continue except BaseException as e: self.logger.exception('') self.show_message(title=_('Error'), msg=str(e)) raise UserCancelled() elif self.temp_storage.is_encrypted_with_hw_device(): try: self.run('choose_hw_device', HWD_SETUP_DECRYPT_WALLET, storage=self.temp_storage) except InvalidPassword as e: self.show_message( title=_('Error'), msg=_( 'Failed to decrypt using this hardware device.' ) + '\n' + _('If you use a passphrase, make sure it is correct.' )) self.reset_stack() return self.select_storage(path, get_wallet_from_daemon) except BaseException as e: self.logger.exception('') self.show_message(title=_('Error'), msg=str(e)) raise UserCancelled() if self.temp_storage.is_past_initial_decryption(): break else: raise UserCancelled() else: raise Exception('Unexpected encryption version') return self.temp_storage.path, ( self.temp_storage if self.temp_storage.file_exists() else None) # def run_upgrades(self, storage): path = storage.path if storage.requires_split(): self.hide() msg = _( "The wallet '{}' contains multiple accounts, which are no longer supported since Electrum 2.7.\n\n" "Do you want to split your wallet into multiple files?" ).format(path) if not self.question(msg): return file_list = '\n'.join(storage.split_accounts()) msg = _('Your accounts have been moved to' ) + ':\n' + file_list + '\n\n' + _( 'Do you want to delete the old file') + ':\n' + path if self.question(msg): os.remove(path) self.show_warning(_('The file was removed')) # raise now, to avoid having the old storage opened raise UserCancelled() action = storage.get_action() if action and storage.requires_upgrade(): raise WalletFileException( 'Incomplete wallet files cannot be upgraded.') if action: self.hide() msg = _("The file '{}' contains an incompletely created wallet.\n" "Do you want to complete its creation now?").format(path) if not self.question(msg): if self.question( _("Do you want to delete '{}'?").format(path)): os.remove(path) self.show_warning(_('The file was removed')) return self.show() self.data = storage.db.data # FIXME self.run(action) for k, v in self.data.items(): storage.put(k, v) storage.write() return if storage.requires_upgrade(): self.upgrade_storage(storage) def finished(self): """Called in hardware client wrapper, in order to close popups.""" return def on_error(self, exc_info): if not isinstance(exc_info[1], UserCancelled): self.logger.error("on_error", exc_info=exc_info) self.show_error(str(exc_info[1])) def set_icon(self, filename): prior_filename, self.icon_filename = self.icon_filename, filename self.logo.setPixmap( QPixmap(icon_path(filename)).scaledToWidth( 60, mode=Qt.SmoothTransformation)) return prior_filename def set_layout(self, layout, title=None, next_enabled=True): self.title.setText("<b>%s</b>" % title if title else "") self.title.setVisible(bool(title)) # Get rid of any prior layout by assigning it to a temporary widget prior_layout = self.main_widget.layout() if prior_layout: QWidget().setLayout(prior_layout) self.main_widget.setLayout(layout) self.back_button.setEnabled(True) self.next_button.setEnabled(next_enabled) if next_enabled: self.next_button.setFocus() self.main_widget.setVisible(True) self.please_wait.setVisible(False) def exec_layout(self, layout, title=None, raise_on_cancel=True, next_enabled=True): self.set_layout(layout, title, next_enabled) result = self.loop.exec_() if not result and raise_on_cancel: raise UserCancelled if result == 1: raise GoBack from None self.title.setVisible(False) self.back_button.setEnabled(False) self.next_button.setEnabled(False) self.main_widget.setVisible(False) self.please_wait.setVisible(True) self.refresh_gui() return result def refresh_gui(self): # For some reason, to refresh the GUI this needs to be called twice self.app.processEvents() self.app.processEvents() def remove_from_recently_open(self, filename): self.config.remove_from_recently_open(filename) def text_input(self, title, message, is_valid, allow_multi=False): slayout = KeysLayout(parent=self, header_layout=message, is_valid=is_valid, allow_multi=allow_multi) self.exec_layout(slayout, title, next_enabled=False) return slayout.get_text() def seed_input(self, title, message, is_seed, options): slayout = SeedLayout(title=message, is_seed=is_seed, options=options, parent=self) self.exec_layout(slayout, title, next_enabled=False) return slayout.get_seed(), slayout.is_bip39, slayout.is_ext @wizard_dialog def add_xpub_dialog(self, title, message, is_valid, run_next, allow_multi=False, show_wif_help=False): header_layout = QHBoxLayout() label = WWLabel(message) label.setMinimumWidth(400) header_layout.addWidget(label) if show_wif_help: header_layout.addWidget(InfoButton(WIF_HELP_TEXT), alignment=Qt.AlignRight) return self.text_input(title, header_layout, is_valid, allow_multi) @wizard_dialog def add_cosigner_dialog(self, run_next, index, is_valid): title = _("Add Cosigner") + " %d" % index message = ' '.join([ _('Please enter the master public key (xpub) of your cosigner.'), _('Enter their master private key (xprv) if you want to be able to sign for them.' ) ]) return self.text_input(title, message, is_valid) @wizard_dialog def restore_seed_dialog(self, run_next, test): options = [] if self.opt_ext: options.append('ext') if self.opt_bip39: options.append('bip39') title = _('Enter Seed') message = _( 'Please enter your seed phrase in order to restore your wallet.') return self.seed_input(title, message, test, options) @wizard_dialog def confirm_seed_dialog(self, run_next, test): self.app.clipboard().clear() title = _('Confirm Seed') message = ' '.join([ _('Your seed is important!'), _('If you lose your seed, your money will be permanently lost.'), _('To make sure that you have properly saved your seed, please retype it here.' ) ]) seed, is_bip39, is_ext = self.seed_input(title, message, test, None) return seed @wizard_dialog def show_seed_dialog(self, run_next, seed_text): title = _("Your wallet generation seed is:") slayout = SeedLayout(seed=seed_text, title=title, msg=True, options=['ext']) self.exec_layout(slayout) return slayout.is_ext def pw_layout(self, msg, kind, force_disable_encrypt_cb): playout = PasswordLayout( msg=msg, kind=kind, OK_button=self.next_button, force_disable_encrypt_cb=force_disable_encrypt_cb) playout.encrypt_cb.setChecked(True) self.exec_layout(playout.layout()) return playout.new_password(), playout.encrypt_cb.isChecked() @wizard_dialog def request_password(self, run_next, force_disable_encrypt_cb=False): """Request the user enter a new password and confirm it. Return the password or None for no password.""" return self.pw_layout(MSG_ENTER_PASSWORD, PW_NEW, force_disable_encrypt_cb) @wizard_dialog def request_storage_encryption(self, run_next): playout = PasswordLayoutForHW(MSG_HW_STORAGE_ENCRYPTION) playout.encrypt_cb.setChecked(True) self.exec_layout(playout.layout()) return playout.encrypt_cb.isChecked() @wizard_dialog def confirm_dialog(self, title, message, run_next): self.confirm(message, title) def confirm(self, message, title): label = WWLabel(message) vbox = QVBoxLayout() vbox.addWidget(label) self.exec_layout(vbox, title) @wizard_dialog def action_dialog(self, action, run_next): self.run(action) def terminate(self, **kwargs): self.accept_signal.emit() def waiting_dialog(self, task, msg, on_finished=None): label = WWLabel(msg) vbox = QVBoxLayout() vbox.addSpacing(100) label.setMinimumWidth(300) label.setAlignment(Qt.AlignCenter) vbox.addWidget(label) self.set_layout(vbox, next_enabled=False) self.back_button.setEnabled(False) t = threading.Thread(target=task) t.start() while True: t.join(1.0 / 60) if t.is_alive(): self.refresh_gui() else: break if on_finished: on_finished() @wizard_dialog def choice_dialog(self, title, message, choices, run_next): c_values = [x[0] for x in choices] c_titles = [x[1] for x in choices] clayout = ChoicesLayout(message, c_titles) vbox = QVBoxLayout() vbox.addLayout(clayout.layout()) self.exec_layout(vbox, title) action = c_values[clayout.selected_index()] return action def query_choice(self, msg, choices): """called by hardware wallets""" clayout = ChoicesLayout(msg, choices) vbox = QVBoxLayout() vbox.addLayout(clayout.layout()) self.exec_layout(vbox, '') return clayout.selected_index() @wizard_dialog def choice_and_line_dialog(self, title: str, message1: str, choices: List[Tuple[str, str, str]], message2: str, test_text: Callable[[str], int], run_next, default_choice_idx: int = 0) -> Tuple[str, str]: vbox = QVBoxLayout() c_values = [x[0] for x in choices] c_titles = [x[1] for x in choices] c_default_text = [x[2] for x in choices] def on_choice_click(clayout): idx = clayout.selected_index() line.setText(c_default_text[idx]) clayout = ChoicesLayout(message1, c_titles, on_choice_click, checked_index=default_choice_idx) vbox.addLayout(clayout.layout()) vbox.addSpacing(50) vbox.addWidget(WWLabel(message2)) line = QLineEdit() def on_text_change(text): self.next_button.setEnabled(test_text(text)) line.textEdited.connect(on_text_change) on_choice_click(clayout) # set default text for "line" vbox.addWidget(line) self.exec_layout(vbox, title) choice = c_values[clayout.selected_index()] return str(line.text()), choice @wizard_dialog def line_dialog(self, run_next, title, message, default, test, warning='', presets=(), warn_issue4566=False): vbox = QVBoxLayout() vbox.addWidget(WWLabel(message)) line = QLineEdit() line.setText(default) def f(text): self.next_button.setEnabled(test(text)) if warn_issue4566: text_whitespace_normalised = ' '.join(text.split()) warn_issue4566_label.setVisible( text != text_whitespace_normalised) line.textEdited.connect(f) vbox.addWidget(line) vbox.addWidget(WWLabel(warning)) warn_issue4566_label = WWLabel(MSG_PASSPHRASE_WARN_ISSUE4566) warn_issue4566_label.setVisible(False) vbox.addWidget(warn_issue4566_label) for preset in presets: button = QPushButton(preset[0]) button.clicked.connect( lambda __, text=preset[1]: line.setText(text)) button.setMinimumWidth(150) hbox = QHBoxLayout() hbox.addWidget(button, alignment=Qt.AlignCenter) vbox.addLayout(hbox) self.exec_layout(vbox, title, next_enabled=test(default)) return line.text() @wizard_dialog def show_xpub_dialog(self, xpub, run_next): msg = ' '.join([ _("Here is your master public key."), _("Please share it with your cosigners.") ]) vbox = QVBoxLayout() layout = SeedLayout(xpub, title=msg, icon=False, for_seed_words=False) vbox.addLayout(layout.layout()) self.exec_layout(vbox, _('Master Public Key')) return None def init_network(self, network): message = _("Electrum communicates with remote servers to get " "information about your transactions and addresses. The " "servers all fulfill the same purpose only differing in " "hardware. In most cases you simply want to let Electrum " "pick one at random. However if you prefer feel free to " "select a server manually.") choices = [_("Auto connect"), _("Select server manually")] title = _("How do you want to connect to a server? ") clayout = ChoicesLayout(message, choices) self.back_button.setText(_('Cancel')) self.exec_layout(clayout.layout(), title) r = clayout.selected_index() if r == 1: nlayout = NetworkChoiceLayout(network, self.config, wizard=True) if self.exec_layout(nlayout.layout()): nlayout.accept() else: network.auto_connect = True self.config.set_key('auto_connect', True, True) @wizard_dialog def multisig_dialog(self, run_next): cw = CosignWidget(2, 2) m_edit = QSlider(Qt.Horizontal, self) n_edit = QSlider(Qt.Horizontal, self) n_edit.setMinimum(2) n_edit.setMaximum(15) m_edit.setMinimum(1) m_edit.setMaximum(2) n_edit.setValue(2) m_edit.setValue(2) n_label = QLabel() m_label = QLabel() grid = QGridLayout() grid.addWidget(n_label, 0, 0) grid.addWidget(n_edit, 0, 1) grid.addWidget(m_label, 1, 0) grid.addWidget(m_edit, 1, 1) def on_m(m): m_label.setText(_('Require {0} signatures').format(m)) cw.set_m(m) def on_n(n): n_label.setText(_('From {0} cosigners').format(n)) cw.set_n(n) m_edit.setMaximum(n) n_edit.valueChanged.connect(on_n) m_edit.valueChanged.connect(on_m) on_n(2) on_m(2) vbox = QVBoxLayout() vbox.addWidget(cw) vbox.addWidget( WWLabel( _("Choose the number of signatures needed to unlock funds in your wallet:" ))) vbox.addLayout(grid) self.exec_layout(vbox, _("Multi-Signature Wallet")) m = int(m_edit.value()) n = int(n_edit.value()) return (m, n)
def create_gui(self): try: from fbs_runtime.application_context.PyQt5 import ( ApplicationContext) appctxt = ApplicationContext() app = appctxt.app except ImportError: app = QApplication(sys.argv) app.setStyle('Fusion') self.window = QMainWindow() self.quit_shortcuts = [] for seq in ("Ctrl+Q", "Ctrl+C", "Ctrl+W", "ESC"): s = QShortcut(QKeySequence(seq), self.window) s.activated.connect(app.exit) self.quit_shortcuts.append(s) is_outdated, latest_version = check_outdated( 'mint-amazon-tagger', VERSION) if is_outdated: outdate_msg = QErrorMessage(self.window) outdate_msg.showMessage( 'A new version is available. Please update for the best ' 'experience. https://github.com/jprouty/mint-amazon-tagger') v_layout = QVBoxLayout() h_layout = QHBoxLayout() v_layout.addLayout(h_layout) amazon_group = QGroupBox('Amazon Order History') amazon_group.setMinimumWidth(300) amazon_layout = QVBoxLayout() amazon_mode = QComboBox() amazon_mode.addItem('Fetch Reports') amazon_mode.addItem('Use Local Reports') amazon_mode.setFocusPolicy(Qt.StrongFocus) has_csv = any([ self.args.orders_csv, self.args.items_csv, self.args.refunds_csv]) self.amazon_mode_layout = ( self.create_amazon_import_layout() if has_csv else self.create_amazon_fetch_layout()) amazon_mode.setCurrentIndex(1 if has_csv else 0) def on_amazon_mode_changed(i): self.clear_layout(self.amazon_mode_layout) if i == 0: self.amazon_mode_layout = self.create_amazon_fetch_layout() elif i == 1: self.amazon_mode_layout = self.create_amazon_import_layout() amazon_layout.addLayout(self.amazon_mode_layout) amazon_mode.currentIndexChanged.connect( on_amazon_mode_changed) amazon_layout.addWidget(amazon_mode) amazon_layout.addLayout(self.amazon_mode_layout) amazon_group.setLayout(amazon_layout) h_layout.addWidget(amazon_group) mint_group = QGroupBox('Mint Login && Options') mint_group.setMinimumWidth(350) mint_layout = QFormLayout() mint_layout.addRow( 'Email:', self.create_line_edit('mint_email', tool_tip=NEVER_SAVE_MSG)) mint_layout.addRow( 'Password:'******'mint_password', tool_tip=NEVER_SAVE_MSG, password=True)) mint_layout.addRow( 'MFA Code:', self.create_combobox( 'mint_mfa_method', ['SMS', 'Email'], lambda x: x.lower())) mint_layout.addRow( 'Sync first?', self.create_checkbox('mint_wait_for_sync')) mint_layout.addRow( 'Merchant Filter', self.create_line_edit('mint_input_merchant_filter')) mint_layout.addRow( 'Include MMerchant', self.create_checkbox('mint_input_include_mmerchant')) mint_layout.addRow( 'Include Merchant', self.create_checkbox('mint_input_include_merchant')) mint_layout.addRow( 'Input Categories Filter', self.create_line_edit('mint_input_categories_filter')) mint_group.setLayout(mint_layout) h_layout.addWidget(mint_group) tagger_group = QGroupBox('Tagger Options') tagger_layout = QHBoxLayout() tagger_left = QFormLayout() tagger_left.addRow( 'Verbose Itemize', self.create_checkbox('verbose_itemize')) tagger_left.addRow( 'Do not Itemize', self.create_checkbox('no_itemize')) tagger_left.addRow( 'Retag Changed', self.create_checkbox('retag_changed')) tagger_right = QFormLayout() tagger_right.addRow( 'Do not tag categories', self.create_checkbox('no_tag_categories')) tagger_right.addRow( 'Do not predict categories', self.create_checkbox('do_not_predict_categories')) tagger_right.addRow( 'Max days between payment/shipment', self.create_combobox( 'max_days_between_payment_and_shipping', ['3', '4', '5', '6', '7', '8', '9', '10'], lambda x: int(x))) tagger_layout.addLayout(tagger_left) tagger_layout.addLayout(tagger_right) tagger_group.setLayout(tagger_layout) v_layout.addWidget(tagger_group) self.start_button = QPushButton('Start Tagging') self.start_button.setAutoDefault(True) self.start_button.clicked.connect(self.on_start_button_clicked) v_layout.addWidget(self.start_button) main_widget = QWidget() main_widget.setLayout(v_layout) self.window.setCentralWidget(main_widget) self.window.show() return app.exec_()
class TaggerDialog(QDialog): def __init__(self, args, **kwargs): super(TaggerDialog, self).__init__(**kwargs) self.reviewing = False self.args = args self.worker = TaggerWorker() self.thread = QThread() self.worker.moveToThread(self.thread) self.worker.on_error.connect(self.on_error) self.worker.on_review_ready.connect(self.on_review_ready) self.worker.on_stopped.connect(self.on_stopped) self.worker.on_progress.connect(self.on_progress) self.worker.on_updates_sent.connect(self.on_updates_sent) self.worker.on_mint_mfa.connect(self.on_mint_mfa) self.thread.started.connect( partial(self.worker.create_updates, args, self)) self.thread.start() self.init_ui() def init_ui(self): self.setWindowTitle('Tagger is running...') self.setModal(True) self.v_layout = QVBoxLayout() self.setLayout(self.v_layout) self.label = QLabel() self.v_layout.addWidget(self.label) self.progress = 0 self.progress_bar = QProgressBar() self.progress_bar.setRange(0, 0) self.v_layout.addWidget(self.progress_bar) self.button_bar = QHBoxLayout() self.v_layout.addLayout(self.button_bar) self.cancel_button = QPushButton('Cancel') self.button_bar.addWidget(self.cancel_button) self.cancel_button.clicked.connect(self.on_cancel) def on_error(self, msg): logger.error(msg) self.label.setText('Error: {}'.format(msg)) self.label.setStyleSheet( 'QLabel { color: red; font-weight: bold; }') self.cancel_button.setText('Close') self.cancel_button.clicked.connect(self.close) def open_amazon_order_id(self, order_id): if order_id: QDesktopServices.openUrl(QUrl( amazon.get_invoice_url(order_id))) def on_activated(self, index): # Only handle clicks on the order_id cell. if index.column() != 5: return order_id = self.updates_table_model.data(index, Qt.DisplayRole) self.open_amazon_order_id(order_id) def on_double_click(self, index): if index.column() == 5: # Ignore double clicks on the order_id cell. return order_id_cell = self.updates_table_model.createIndex(index.row(), 5) order_id = self.updates_table_model.data(order_id_cell, Qt.DisplayRole) self.open_amazon_order_id(order_id) def on_review_ready(self, results): self.reviewing = True self.progress_bar.hide() self.label.setText('Select below which updates to send to Mint.') self.updates_table_model = MintUpdatesTableModel(results.updates) self.updates_table = QTableView() self.updates_table.doubleClicked.connect(self.on_double_click) self.updates_table.clicked.connect(self.on_activated) def resize(): self.updates_table.resizeColumnsToContents() self.updates_table.resizeRowsToContents() min_width = sum( self.updates_table.columnWidth(i) for i in range(6)) self.updates_table.setMinimumSize(min_width + 20, 600) self.updates_table.setSelectionMode(QAbstractItemView.SingleSelection) self.updates_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.updates_table.setModel(self.updates_table_model) self.updates_table.setSortingEnabled(True) resize() self.updates_table_model.layoutChanged.connect(resize) self.v_layout.insertWidget(2, self.updates_table) unmatched_button = QPushButton('View Unmatched Amazon orders') self.button_bar.addWidget(unmatched_button) unmatched_button.clicked.connect( partial(self.on_open_unmatched, results.unmatched_orders)) amazon_stats_button = QPushButton('Amazon Stats') self.button_bar.addWidget(amazon_stats_button) amazon_stats_button.clicked.connect( partial(self.on_open_amazon_stats, results.items, results.orders, results.refunds)) tagger_stats_button = QPushButton('Tagger Stats') self.button_bar.addWidget(tagger_stats_button) tagger_stats_button.clicked.connect( partial(self.on_open_tagger_stats, results.stats)) self.confirm_button = QPushButton('Send to Mint') self.button_bar.addWidget(self.confirm_button) self.confirm_button.clicked.connect(self.on_send) self.setGeometry(50, 50, self.width(), self.height()) def on_updates_sent(self, num_sent): self.label.setText( 'All done! {} newly tagged Mint transactions'.format(num_sent)) self.cancel_button.setText('Close') def on_open_unmatched(self, unmatched): self.unmatched_dialog = AmazonUnmatchedTableDialog(unmatched) self.unmatched_dialog.show() def on_open_amazon_stats(self, items, orders, refunds): self.amazon_stats_dialog = AmazonStatsDialog(items, orders, refunds) self.amazon_stats_dialog.show() def on_open_tagger_stats(self, stats): self.tagger_stats_dialog = TaggerStatsDialog(stats) self.tagger_stats_dialog.show() def on_send(self): self.progress_bar.show() updates = self.updates_table_model.get_selected_updates() self.confirm_button.hide() self.updates_table.hide() self.confirm_button.deleteLater() self.updates_table.deleteLater() self.adjustSize() QMetaObject.invokeMethod( self.worker, 'send_updates', Qt.QueuedConnection, Q_ARG(list, updates), Q_ARG(object, self.args)) def on_stopped(self): self.close() def on_progress(self, msg, max, value): self.label.setText(msg) self.progress_bar.setRange(0, max) self.progress_bar.setValue(value) def on_cancel(self): if not self.reviewing: QMetaObject.invokeMethod( self.worker, 'stop', Qt.QueuedConnection) else: self.close() def on_mint_mfa(self): mfa_code, ok = QInputDialog().getText( self, 'Please enter your Mint Code.', 'Mint Code:') QMetaObject.invokeMethod( self.worker, 'mfa_code', Qt.QueuedConnection, Q_ARG(int, mfa_code))
class RoiDrawer(QWidget): """ A widget for interactively drawing ROIs. Defaults to showing as it's own window, this can be overridden with the `flags` argument. Args: metadatas: A list of pwspy AcquisitionDirectory `Acquisition` objects paired with optional analysis results objects for that acquisition. """ roiCreated = pyqtSignal( pwsdt.Acquisition, pwsdt.RoiFile, bool) # Fired when a roi is created by this widget. roiDeleted = pyqtSignal(pwsdt.Acquisition, pwsdt.RoiFile) roiModified = pyqtSignal(pwsdt.Acquisition, pwsdt.RoiFile) metadataChanged = pyqtSignal( pwsdt.Acquisition ) # The acquisition we are looking at has been switched. def __init__(self, metadatas: t_.List[t_.Tuple[ pwsdt.Acquisition, t_.Optional[AnalysisViewer.AnalysisResultsComboType]]], roiManager: ROIManager = None, parent=None, flags=QtCore.Qt.Window, title: str = "Roi Drawer 3000", initialField=AnalysisViewer.PlotFields.Thumbnail): QWidget.__init__(self, parent=parent, flags=flags) self.setWindowTitle(title) self.metadatas = metadatas layout = QGridLayout() self._mdIndex = 0 self.roiManager = roiManager if roiManager else _DefaultROIManager( self) self.anViewer = AnalysisViewer(self.metadatas[self._mdIndex][0], self.metadatas[self._mdIndex][1], title, initialField=initialField, roiManager=self.roiManager) self.anViewer.roiPlot.roiDeleted.connect( lambda acq, roi: self.roiDeleted.emit(acq, roi)) self.anViewer.roiPlot.roiModified.connect( lambda acq, roi: self.roiModified.emit(acq, roi)) self.anViewer.roiPlot.roiCreated.connect( lambda acq, roi: self.roiCreated.emit(acq, roi, False)) self.newRoiDlg = NewRoiDlg(self) self.noneButton = QPushButton("Inspect") self.lassoButton = QPushButton("Lasso") self.lassoButton.setToolTip(LassoCreator.getHelpText()) self.ellipseButton = QPushButton("Ellipse") self.ellipseButton.setToolTip(EllipseCreator.getHelpText()) self.paintButton = QPushButton("Paint") self.paintButton.setToolTip(RegionalPaintCreator.getHelpText()) self.lastButton_ = None self.buttonGroup = QButtonGroup(self) self.buttonGroup.addButton(self.noneButton) self.buttonGroup.addButton(self.lassoButton) self.buttonGroup.addButton(self.ellipseButton) self.buttonGroup.addButton(self.paintButton) self.buttonGroup.buttonReleased.connect(self.handleButtons) [i.setCheckable(True) for i in self.buttonGroup.buttons()] self.noneButton.setChecked( True ) #This doesn't seem to trigger handle buttons. we'll do that at the end of the constructor def handleAdjustButton(checkstate: bool): if self.selector is not None: self.selector.adjustable = checkstate self.adjustButton = QPushButton("Tune") self.adjustButton.setToolTip(PolygonModifier.getHelpText()) self.adjustButton.setCheckable(True) self.adjustButton.setMaximumWidth(50) self.adjustButton.toggled.connect(handleAdjustButton) def showNextCell(): idx = self._mdIndex + 1 if idx >= len(self.metadatas): idx = 0 self._updateDisplayedCell(idx) def showPreviousCell(): idx = self._mdIndex - 1 if idx < 0: idx = len(self.metadatas) - 1 self._updateDisplayedCell(idx) self.previousButton = QPushButton('←') self.nextButton = QPushButton('→') self.previousButton.released.connect(showPreviousCell) self.nextButton.released.connect(showNextCell) layout.addWidget(self.noneButton, 0, 0, 1, 1) layout.addWidget(self.lassoButton, 0, 1, 1, 1) layout.addWidget(self.ellipseButton, 0, 2, 1, 1) layout.addWidget(self.paintButton, 0, 3, 1, 1) layout.addWidget(self.adjustButton, 0, 4, 1, 1) layout.addWidget(self.previousButton, 0, 6, 1, 1) layout.addWidget(self.nextButton, 0, 7, 1, 1) layout.addWidget(self.anViewer, 1, 0, 8, 8) self.setLayout(layout) self.selector: AdjustableSelector = AdjustableSelector( self.anViewer.roiPlot.ax, self.anViewer.roiPlot.im, LassoCreator, onfinished=self.finalizeRoi, onPolyTuningCancelled=lambda: self.selector.setActive(True)) self.handleButtons(self.noneButton) # Helps initialize state self.show() def finalizeRoi(self, verts: np.ndarray): roiName = self.anViewer.roiPlot.roiFilter.currentText() if roiName == '': QMessageBox.information( self, 'Wait', 'Please type an ROI name into the box at the top of the screen.' ) self.selector.setActive(True) return shape = self.anViewer.data.shape self.newRoiDlg.show() self.newRoiDlg.exec() if self.newRoiDlg.result() == QDialog.Accepted: md = self.metadatas[self._mdIndex][0] self._saveNewRoi(roiName, self.newRoiDlg.number, np.array(verts), shape, md) self.selector.setActive(True) # Start the next roiFile. def _saveNewRoi(self, name: str, num: int, verts, datashape, acq: pwsdt.Acquisition): roi = pwsdt.Roi.fromVerts(verts, datashape) try: roiFile = self.roiManager.createRoi(acq, roi, name, num, overwrite=False) self.roiCreated.emit(acq, roiFile, False) except OSError as ose: ans = QMessageBox.question( self.anViewer, 'Overwrite?', f"Roi {name}:{num} already exists. Overwrite?") if ans == QMessageBox.Yes: roiFile = self.roiManager.getROI(acq, name, num) self.roiManager.updateRoi(roiFile, roi) self.roiCreated.emit(acq, roiFile, True) def handleButtons(self, button): if button is self.lassoButton and self.lastButton_ is not button: self.selector.setSelector(LassoCreator) self.selector.setActive(True) self.anViewer.roiPlot.enableHoverAnnotation(False) self.adjustButton.setEnabled(True) elif button is self.ellipseButton and self.lastButton_ is not button: self.selector.setSelector(EllipseCreator) self.selector.setActive(True) self.anViewer.roiPlot.enableHoverAnnotation(False) self.adjustButton.setEnabled(True) elif button is self.paintButton: def setSelector(sel): self.selector.setSelector(sel) self.selector.setActive(True) self.anViewer.roiPlot.enableHoverAnnotation(False) self.adjustButton.setEnabled(True) menu = QMenu(self) regionalAction = QAction("Regional") regionalAction.triggered.connect( lambda: setSelector(RegionalPaintCreator)) menu.addAction(regionalAction) fullAction = QAction("Full Image") fullAction.triggered.connect( lambda: setSelector(FullImPaintCreator)) menu.addAction(fullAction) watershedAction = QAction("Watershed") watershedAction.triggered.connect( lambda: setSelector(WaterShedPaintCreator)) menu.addAction(watershedAction) menu.exec(self.mapToGlobal(self.paintButton.pos())) elif button is self.noneButton and self.lastButton_ is not button: if self.selector is not None: self.selector.setActive(False) self.anViewer.roiPlot.enableHoverAnnotation(True) self.adjustButton.setEnabled(False) self.lastButton_ = button def _updateDisplayedCell(self, idx: int): currRoi = self.anViewer.roiPlot.roiFilter.currentText( ) # Since the next cell we look at will likely not have rois of the current name we want to manually force the ROI name to stay the same. md, analysis = self.metadatas[idx] self.anViewer.setMetadata(md, analysis=analysis) self.anViewer.roiPlot.roiFilter.setEditText( currRoi) # manually force the ROI name to stay the same. self.selector.reset() # Make sure to get rid of all rois self.setWindowTitle(f"Roi Drawer - {os.path.split(md.filePath)[-1]}") self.metadataChanged.emit(md) self._mdIndex = idx def setDisplayedAcquisition(self, acq: pwsdt.Acquisition): """Switch the image to display images associated with `acq`. If `acq` wasn't passed in to the constructor of this object then an IndexError will be raised. Args: acq: The acquisition to display. """ for i, (mdAcq, analysis) in enumerate(self.metadatas): if mdAcq is acq: self._updateDisplayedCell(i) return raise IndexError( f"Acquisition {acq} was not found in the list of available images." ) def closeEvent(self, a0: QtGui.QCloseEvent) -> None: self.selector.setActive( False ) # This cleans up remaining resources of the selector widgets. super().closeEvent(a0)
def __init__(self, window, plugin, keystore, device_id): title = _("{} Settings").format(plugin.device) super(CKCCSettingsDialog, self).__init__(window, title) self.setMaximumWidth(540) devmgr = plugin.device_manager() config = devmgr.config handler = keystore.handler self.thread = thread = keystore.thread def connect_and_doit(): client = devmgr.client_by_id(device_id) if not client: raise RuntimeError("Device not connected") return client body = QWidget() body_layout = QVBoxLayout(body) grid = QGridLayout() grid.setColumnStretch(2, 1) # see <http://doc.qt.io/archives/qt-4.8/richtext-html-subset.html> title = QLabel('''<center> <span style="font-size: x-large">Coldcard Wallet</span> <br><span style="font-size: medium">from Coinkite Inc.</span> <br><a href="https://coldcardwallet.com">coldcardwallet.com</a>''') title.setTextInteractionFlags(Qt.LinksAccessibleByMouse) grid.addWidget(title , 0,0, 1,2, Qt.AlignHCenter) y = 3 rows = [ ('fw_version', _("Firmware Version")), ('fw_built', _("Build Date")), ('bl_version', _("Bootloader")), ('xfp', _("Master Fingerprint")), ('serial', _("USB Serial")), ] for row_num, (member_name, label) in enumerate(rows): widget = QLabel('<tt>000000000000') widget.setTextInteractionFlags(Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard) grid.addWidget(QLabel(label), y, 0, 1,1, Qt.AlignRight) grid.addWidget(widget, y, 1, 1, 1, Qt.AlignLeft) setattr(self, member_name, widget) y += 1 body_layout.addLayout(grid) upg_btn = QPushButton('Upgrade') #upg_btn.setDefault(False) def _start_upgrade(): thread.add(connect_and_doit, on_success=self.start_upgrade) upg_btn.clicked.connect(_start_upgrade) y += 3 grid.addWidget(upg_btn, y, 0) grid.addWidget(CloseButton(self), y, 1) dialog_vbox = QVBoxLayout(self) dialog_vbox.addWidget(body) # Fetch values and show them thread.add(connect_and_doit, on_success=self.show_values)
class TaggerGui: def __init__(self, args, arg_name_to_help): self.args = args self.arg_name_to_help = arg_name_to_help def create_gui(self): try: from fbs_runtime.application_context.PyQt5 import ( ApplicationContext) appctxt = ApplicationContext() app = appctxt.app except ImportError: app = QApplication(sys.argv) app.setStyle('Fusion') self.window = QMainWindow() self.quit_shortcuts = [] for seq in ("Ctrl+Q", "Ctrl+C", "Ctrl+W", "ESC"): s = QShortcut(QKeySequence(seq), self.window) s.activated.connect(app.exit) self.quit_shortcuts.append(s) is_outdated, latest_version = check_outdated( 'mint-amazon-tagger', VERSION) if is_outdated: outdate_msg = QErrorMessage(self.window) outdate_msg.showMessage( 'A new version is available. Please update for the best ' 'experience. https://github.com/jprouty/mint-amazon-tagger') v_layout = QVBoxLayout() h_layout = QHBoxLayout() v_layout.addLayout(h_layout) amazon_group = QGroupBox('Amazon Order History') amazon_group.setMinimumWidth(300) amazon_layout = QVBoxLayout() amazon_mode = QComboBox() amazon_mode.addItem('Fetch Reports') amazon_mode.addItem('Use Local Reports') amazon_mode.setFocusPolicy(Qt.StrongFocus) has_csv = any([ self.args.orders_csv, self.args.items_csv, self.args.refunds_csv]) self.amazon_mode_layout = ( self.create_amazon_import_layout() if has_csv else self.create_amazon_fetch_layout()) amazon_mode.setCurrentIndex(1 if has_csv else 0) def on_amazon_mode_changed(i): self.clear_layout(self.amazon_mode_layout) if i == 0: self.amazon_mode_layout = self.create_amazon_fetch_layout() elif i == 1: self.amazon_mode_layout = self.create_amazon_import_layout() amazon_layout.addLayout(self.amazon_mode_layout) amazon_mode.currentIndexChanged.connect( on_amazon_mode_changed) amazon_layout.addWidget(amazon_mode) amazon_layout.addLayout(self.amazon_mode_layout) amazon_group.setLayout(amazon_layout) h_layout.addWidget(amazon_group) mint_group = QGroupBox('Mint Login && Options') mint_group.setMinimumWidth(350) mint_layout = QFormLayout() mint_layout.addRow( 'Email:', self.create_line_edit('mint_email', tool_tip=NEVER_SAVE_MSG)) mint_layout.addRow( 'Password:'******'mint_password', tool_tip=NEVER_SAVE_MSG, password=True)) mint_layout.addRow( 'MFA Code:', self.create_combobox( 'mint_mfa_method', ['SMS', 'Email'], lambda x: x.lower())) mint_layout.addRow( 'Sync first?', self.create_checkbox('mint_wait_for_sync')) mint_layout.addRow( 'Merchant Filter', self.create_line_edit('mint_input_merchant_filter')) mint_layout.addRow( 'Include MMerchant', self.create_checkbox('mint_input_include_mmerchant')) mint_layout.addRow( 'Include Merchant', self.create_checkbox('mint_input_include_merchant')) mint_layout.addRow( 'Input Categories Filter', self.create_line_edit('mint_input_categories_filter')) mint_group.setLayout(mint_layout) h_layout.addWidget(mint_group) tagger_group = QGroupBox('Tagger Options') tagger_layout = QHBoxLayout() tagger_left = QFormLayout() tagger_left.addRow( 'Verbose Itemize', self.create_checkbox('verbose_itemize')) tagger_left.addRow( 'Do not Itemize', self.create_checkbox('no_itemize')) tagger_left.addRow( 'Retag Changed', self.create_checkbox('retag_changed')) tagger_right = QFormLayout() tagger_right.addRow( 'Do not tag categories', self.create_checkbox('no_tag_categories')) tagger_right.addRow( 'Do not predict categories', self.create_checkbox('do_not_predict_categories')) tagger_right.addRow( 'Max days between payment/shipment', self.create_combobox( 'max_days_between_payment_and_shipping', ['3', '4', '5', '6', '7', '8', '9', '10'], lambda x: int(x))) tagger_layout.addLayout(tagger_left) tagger_layout.addLayout(tagger_right) tagger_group.setLayout(tagger_layout) v_layout.addWidget(tagger_group) self.start_button = QPushButton('Start Tagging') self.start_button.setAutoDefault(True) self.start_button.clicked.connect(self.on_start_button_clicked) v_layout.addWidget(self.start_button) main_widget = QWidget() main_widget.setLayout(v_layout) self.window.setCentralWidget(main_widget) self.window.show() return app.exec_() def create_amazon_fetch_layout(self): amazon_fetch_layout = QFormLayout() amazon_fetch_layout.addRow(QLabel( 'Fetches recent Amazon order history for you.')) amazon_fetch_layout.addRow( 'Email:', self.create_line_edit('amazon_email', tool_tip=NEVER_SAVE_MSG)) amazon_fetch_layout.addRow( 'Password:'******'amazon_password', tool_tip=NEVER_SAVE_MSG, password=True)) amazon_fetch_layout.addRow( 'Start date:', self.create_date_edit( 'order_history_start_date', 'Select Amazon order history start date')) amazon_fetch_layout.addRow( 'End date:', self.create_date_edit( 'order_history_end_date', 'Select Amazon order history end date')) return amazon_fetch_layout def create_amazon_import_layout(self): amazon_import_layout = QFormLayout() order_history_link = QLabel() order_history_link.setText( '''<a href="https://www.amazon.com/gp/b2b/reports"> Download your Amazon reports</a><br> and select them below:''') order_history_link.setOpenExternalLinks(True) amazon_import_layout.addRow(order_history_link) amazon_import_layout.addRow( 'Items CSV:', self.create_file_edit( 'items_csv', 'Select Amazon Items Report' )) amazon_import_layout.addRow( 'Orders CSV:', self.create_file_edit( 'orders_csv', 'Select Amazon Orders Report' )) amazon_import_layout.addRow( 'Refunds CSV:', self.create_file_edit( 'refunds_csv', 'Select Amazon Refunds Report' )) return amazon_import_layout def on_quit(self): pass def on_tagger_dialog_closed(self): self.start_button.setEnabled(True) # Reset any csv file handles, as there might have been an error and # they user may try again (could already be consumed/closed). for attr_name in ('orders_csv', 'items_csv', 'refunds_csv'): file = getattr(self.args, attr_name) if file: setattr( self.args, attr_name, open(file.name, 'r', encoding='utf-8')) def on_start_button_clicked(self): self.start_button.setEnabled(False) self.tagger = TaggerDialog( args=self.args, parent=self.window) self.tagger.show() self.tagger.finished.connect(self.on_tagger_dialog_closed) def clear_layout(self, layout): if layout: while layout.count(): child = layout.takeAt(0) if child.widget() is not None: child.widget().deleteLater() elif child.layout() is not None: self.clear_layout(child.layout()) def create_checkbox(self, name, tool_tip=None, invert=False): x_box = QCheckBox() x_box.setTristate(False) x_box.setCheckState( Qt.Checked if getattr(self.args, name) else Qt.Unchecked) if not tool_tip and name in self.arg_name_to_help: tool_tip = 'When checked, ' + self.arg_name_to_help[name] if tool_tip: x_box.setToolTip(tool_tip) def on_changed(state): setattr( self.args, name, state != Qt.Checked if invert else state == Qt.Checked) x_box.stateChanged.connect(on_changed) return x_box def advance_focus(self): self.window.focusNextChild() def create_line_edit(self, name, tool_tip=None, password=False): line_edit = QLineEdit(getattr(self.args, name)) if not tool_tip: tool_tip = self.arg_name_to_help[name] if tool_tip: line_edit.setToolTip(tool_tip) if password: line_edit.setEchoMode(QLineEdit.PasswordEchoOnEdit) def on_changed(state): setattr(self.args, name, state) def on_return(): self.advance_focus() line_edit.textChanged.connect(on_changed) line_edit.returnPressed.connect(on_return) return line_edit def create_date_edit( self, name, popup_title, max_date=datetime.date.today(), tool_tip=None): date_edit = QPushButton(str(getattr(self.args, name))) date_edit.setAutoDefault(True) if not tool_tip: tool_tip = self.arg_name_to_help[name] if tool_tip: date_edit.setToolTip(tool_tip) def on_date_edit_clicked(): dlg = QDialog(self.window) dlg.setWindowTitle(popup_title) layout = QVBoxLayout() cal = QCalendarWidget() cal.setMaximumDate(QDate(max_date)) cal.setSelectedDate(QDate(getattr(self.args, name))) cal.selectionChanged.connect(lambda: dlg.accept()) layout.addWidget(cal) okay = QPushButton('Select') okay.clicked.connect(lambda: dlg.accept()) layout.addWidget(okay) dlg.setLayout(layout) dlg.exec() setattr(self.args, name, cal.selectedDate().toPyDate()) date_edit.setText(str(getattr(self.args, name))) date_edit.clicked.connect(on_date_edit_clicked) return date_edit def create_file_edit( self, name, popup_title, filter='CSV files (*.csv)', tool_tip=None): file_button = QPushButton( 'Select a file' if not getattr(self.args, name) else os.path.split(getattr(self.args, name).name)[1]) if not tool_tip: tool_tip = self.arg_name_to_help[name] if tool_tip: file_button.setToolTip(tool_tip) def on_button(): dlg = QFileDialog() selection = dlg.getOpenFileName( self.window, popup_title, '', filter) if selection[0]: prev_file = getattr(self.args, name) if prev_file: prev_file.close() setattr( self.args, name, open(selection[0], 'r', encoding='utf-8')) file_button.setText(os.path.split(selection[0])[1]) file_button.clicked.connect(on_button) return file_button def create_combobox(self, name, items, transform, tool_tip=None): combo = QComboBox() combo.setFocusPolicy(Qt.StrongFocus) if not tool_tip: tool_tip = self.arg_name_to_help[name] if tool_tip: combo.setToolTip(tool_tip) combo.addItems(items) def on_change(option): setattr(self.args, name, transform(option)) combo.currentTextChanged.connect(on_change) return combo
def __init__(self, parent=None): super(Widget, self).__init__(parent) self.setWindowTitle("Koppel account / koper.") self.setWindowIcon(QIcon('./images/logos/logo.jpg')) self.setFont(QFont('Arial', 10)) self.Clientnummer = QLabel() kbedrEdit = QLineEdit() kbedrEdit.setFixedWidth(100) kbedrEdit.setFont(QFont("Arial", 10)) kbedrEdit.textChanged.connect(self.kbedrChanged) reg_ex = QRegExp('^[6]{1}[0-9]{8}$') input_validator = QRegExpValidator(reg_ex, kbedrEdit) kbedrEdit.setValidator(input_validator) grid = QGridLayout() grid.setSpacing(20) lbl = QLabel() pixmap = QPixmap('./images/logos/verbinding.jpg') lbl.setPixmap(pixmap) grid.addWidget(lbl, 0, 0) logo = QLabel() pixmap = QPixmap('./images/logos/logo.jpg') logo.setPixmap(pixmap) grid.addWidget(logo, 0, 1, 1, 1, Qt.AlignRight) self.setFont(QFont('Arial', 10)) grid.addWidget(QLabel('Clientnummer'), 1, 0) grid.addWidget(kbedrEdit, 1, 1) grid.addWidget( QLabel('\u00A9 2017 all rights reserved [email protected]'), 3, 0, 1, 2, Qt.AlignCenter) cancelBtn = QPushButton('Sluiten') cancelBtn.clicked.connect(lambda: windowSluit(self, m_email)) applyBtn = QPushButton('Koppel') applyBtn.clicked.connect(self.accept) grid.addWidget(applyBtn, 2, 1, 1, 1, Qt.AlignRight) applyBtn.setFont(QFont("Arial", 10)) applyBtn.setFixedWidth(100) applyBtn.setStyleSheet( "color: black; background-color: gainsboro") grid.addWidget(cancelBtn, 2, 0, 1, 1, Qt.AlignRight) cancelBtn.setFont(QFont("Arial", 10)) cancelBtn.setFixedWidth(100) cancelBtn.setStyleSheet( "color: black; background-color: gainsboro") self.setLayout(grid) self.setGeometry(500, 300, 150, 150)
def __init__(self, count_data): super(Choose, self).__init__() self.resize(250, 200) self.setWindowTitle("提示信息") # 初始化数据 self.jiaLableSort = QLabel("假") self.jiaLableCount = QLabel("数量: %d" % count_data["jia"]["count"]) self.jiaLablePrice = QLabel("总价: %.2f" % count_data["jia"]["price"]) self.siLableSort = QLabel("私") self.siLableCount = QLabel("数量: %d" % count_data["si"]["count"]) self.siLablePrice = QLabel("总价: %.2f" % count_data["si"]["price"]) self.feiLableSort = QLabel("非") self.feiLableCount = QLabel("数量: %d" % count_data["fei"]["count"]) self.feiLablePrice = QLabel("总价: %.2f" % count_data["fei"]["price"]) # self.totalPrice = QLabel(str(count_data["price"])) # 装载布局 layout = QGridLayout() layout.addWidget(self.jiaLableSort, 0, 0) layout.addWidget(self.jiaLableCount, 0, 1) layout.addWidget(self.jiaLablePrice, 0, 2) layout.addWidget(self.siLableSort, 1, 0) layout.addWidget(self.siLableCount, 1, 1) layout.addWidget(self.siLablePrice, 1, 2) layout.addWidget(self.feiLableSort, 2, 0) layout.addWidget(self.feiLableCount, 2, 1) layout.addWidget(self.feiLablePrice, 2, 2) # layout.addWidget(self.totalPrice, 3, 0, 1, 3) self.anjian_type = 0 # 案件的类型 0零盒 1小微 2一般 # 根据数量的不同,选择类型 if count_data["is_tiao"]: # 以条为单位 if count_data["jia"]["count"] > 0: self.anjian_type = 2 else: all_count = count_data["jia"]["count"] + count_data["si"]["count"] + count_data["fei"]["count"] price_count = count_data["price"] if all_count > 50 or float(price_count) > 10000: self.anjian_type = 2 else: self.anjian_type = 1 else: # 以支为单位 if count_data["jia"]["count"] > 0: self.anjian_type = 2 else: all_count = count_data["jia"]["count"] + count_data["si"]["count"] + count_data["fei"]["count"] if all_count > 800: self.anjian_type = 2 else: self.anjian_type = 0 self.confirm_btn = QPushButton("确定") self.confirm_btn.clicked.connect(self.func_confirm) if self.anjian_type == 0: # 零盒案件 self.checkbox1 = QCheckBox("当事人无异议") self.checkbox2 = QCheckBox("涉案烟未销售") layout.addWidget(self.checkbox1, 4, 0, 1, 2) layout.addWidget(self.checkbox2, 5, 0, 1, 2) layout.addWidget(self.confirm_btn, 6, 0, 1, 2) elif self.anjian_type == 1: # 小微案件 self.checkbox1 = QCheckBox("当事人无异议") layout.addWidget(self.checkbox1, 4, 0, 1, 2) layout.addWidget(self.confirm_btn, 5, 0, 1, 2) else: # 一般案件不处理 layout.addWidget(self.confirm_btn, 4, 0, 1, 2) self.setLayout(layout) style_str = "QLabel{font-size: 30px;}" + "QLineEdit{font-size: 30px;}" + \ "QPushButton{font-size: 25px; background-color: green; min-height: 50px}" + \ "QComboBox{font-size: 30px;}" + "QCheckBox{font-size: 30px;}" self.setStyleSheet(style_str)
def create_right_side(self): #will fill in the stuff on the right side - basically all the annoying fields and labels operations_box = QGridLayout(self.other_info_layout) widget_parent = self.other_info_layout label = QLabel(widget_parent) label.setText("Select File") operations_box.addWidget(label, 0, 0) button = QPushButton("Import from .bck") button.clicked.connect(self.open_file_dialog) operations_box.addWidget(button , 0, 1) #------------------------------------------- label_soundid = QLabel(widget_parent) label_soundid.setText("Sound ID:") operations_box.addWidget(label_soundid, 1, 0) self.sound_id_field = QLineEdit(widget_parent) operations_box.addWidget( self.sound_id_field, 1, 1) #------------------------------------------- label_start_time = QLabel(widget_parent) label_start_time.setText("Start Frame:") operations_box.addWidget(label_start_time, 2, 0) self.start_time_field = QLineEdit(widget_parent) operations_box.addWidget( self.start_time_field, 2, 1) label_end_time = QLabel(widget_parent) label_end_time.setText("End Frame:") operations_box.addWidget(label_end_time, 3, 0) self.end_time_field = QLineEdit(widget_parent) operations_box.addWidget( self.end_time_field, 3, 1) label_flags = QLabel(widget_parent) label_flags.setText("Loop Flags:") operations_box.addWidget(label_flags, 4, 0) self.flags_field = QLineEdit(widget_parent) operations_box.addWidget( self.flags_field, 4, 1) label_loop_count = QLabel(widget_parent) label_loop_count.setText("Loop Count:") operations_box.addWidget(label_loop_count, 5, 0) self.loop_count_field = QLineEdit(widget_parent) operations_box.addWidget( self.loop_count_field, 5, 1) #---------------------------------- label_volume = QLabel(widget_parent) label_volume.setText("Volume:") operations_box.addWidget(label_volume, 6, 0) self.volume_field = QLineEdit(widget_parent) operations_box.addWidget( self.volume_field, 6, 1) label_coarse_pitch = QLabel(widget_parent) label_coarse_pitch.setText("Coarse Pitch:") operations_box.addWidget(label_coarse_pitch, 7, 0) self.coarse_pitch_field = QLineEdit(widget_parent) operations_box.addWidget( self.coarse_pitch_field, 7, 1) label_fine_pitch = QLabel(widget_parent) label_fine_pitch.setText("Fine Pitch:") operations_box.addWidget(label_fine_pitch, 8, 0) self.fine_pitch_field = QLineEdit(widget_parent) operations_box.addWidget( self.fine_pitch_field, 8, 1) label_pan = QLabel(widget_parent) label_pan.setText("Pan:") operations_box.addWidget(label_pan, 9, 0) self.pan_field = QLineEdit(widget_parent) operations_box.addWidget( self.pan_field, 9, 1) #-------------------------------- label_unk_byte = QLabel(widget_parent) label_unk_byte.setText("Speed / Interval Value:") operations_box.addWidget(label_unk_byte, 10, 0) self.unk_byte_field = QLineEdit(widget_parent) operations_box.addWidget( self.unk_byte_field, 10, 1) return operations_box
class GPDwidget(QWidget): def __init__(self,parent=None,globals=None): self.globals = globals self.gpd = GPD() self.parent = parent super().__init__() self.setWindowTitle('GPD 3303') self.on_btn = QPushButton('off') self.initUI() self.sendScanParams() def initUI(self): layout = QHBoxLayout() l1= QVBoxLayout() l2 = QVBoxLayout() restor_btn = QPushButton('Restore') restor_btn.clicked.connect(self.restore) l2.addWidget(restor_btn) l2.addWidget(QLabel('V1, V')) self.V1line = MyBox(valid=(0, 32, 2)) self.V1line.setText('0') self.V1line.textChanged.connect(self.changeV1) l2.addWidget(self.V1line) l2.addWidget(QLabel('I1, A')) self.I1line = MyBox(valid=(0, 3.2, 2)) self.I1line.setText('0') self.I1line.textChanged.connect(self.changeI1) l2.addWidget(self.I1line) self.on_btn.clicked.connect(self.switch) l1.addWidget(self.on_btn) l1.addWidget(QLabel('V2, V')) self.V2line = MyBox(valid=(0, 32, 2)) self.V2line.setText('0') self.V2line.textChanged.connect(self.changeV2) l1.addWidget(self.V2line) l1.addWidget(QLabel('I2, A')) self.I2line = MyBox(valid=(0, 3.2, 2)) self.I2line.setText('0') self.I2line.textChanged.connect(self.changeI2) l1.addWidget(self.I2line) layout.addLayout(l1) layout.addLayout(l2) layout.addWidget(self.gpd.BasicWidget(data=self.gpd, parent=self)) self.setLayout(layout) def changeV1(self): print('V1') try: self.gpd.setV1(self.V1line.text()) except ValueError: print('V1 input is not a float') def changeV2(self): print('V2') try: self.gpd.setV2(self.V2line.text()) except ValueError: print('V2 input is not a float') def changeI1(self): print('I1') try: self.gpd.setI1(self.I1line.text()) except ValueError: print('I1 input is not a float') def changeI2(self): print('I2') try: self.gpd.setI2(self.I2line.text()) except ValueError: print('I2 input is not a float') def switch(self): if self.on_btn.text() == 'off': self.gpd.switch(1) self.on_btn.setText('on') self.on_btn.setStyleSheet("QWidget { background-color: %s }" % 'blue') else: self.gpd.switch(0) self.on_btn.setText('off') self.on_btn.setStyleSheet("QWidget { background-color: %s }" % 'None') def restore(self): self.I2line.textChanged.disconnect(self.changeI2) self.I1line.textChanged.disconnect(self.changeI1) self.V2line.textChanged.disconnect(self.changeV2) self.V1line.textChanged.disconnect(self.changeV1) I1 = self.gpd.getI1() self.I1line.setText(I1) I2 = self.gpd.getI2() self.I2line.setText(I2) V1 = self.gpd.getV1() self.V1line.setText(V1) V2 = self.gpd.getV2() self.V2line.setText(V2) self.I2line.textChanged.connect(self.changeI2) self.I1line.textChanged.connect(self.changeI1) self.V2line.textChanged.connect(self.changeV2) self.V1line.textChanged.connect(self.changeV1) def sendScanParams(self): params = ['V1','V2','I1', 'I2'] if self.globals != None: if scan_params_str not in self.globals: self.globals[scan_params_str] = {} self.globals[scan_params_str][name_in_scan_params] = params return def getUpdateMethod(self): return self.updateFromScanner def updateFromScanner(self, param_dict=None): # self.scanner = True print('Here') try: for param, val in param_dict.items(): param = param[0] print(param,val) if param == 'V1': self.V1line.setText(str(val)) self.changeV1() elif param == 'V2': self.V2line.setText(str(val)) self.changeV2() elif param == 'I1': self.I1line.setText(str(val)) self.changeI1() elif param == 'I2': self.I2line.setText(str(val)) self.changeI2() except Exception as e: print("can't change from scanner: ", e) return -1 return 0
class SignInWidget(QWidget): is_admin_signal = pyqtSignal() is_student_signal = pyqtSignal(str) def __init__(self): super(SignInWidget, self).__init__() self.resize(900, 600) self.setWindowTitle("欢迎使用银河智维AI平台") self.setUpUI() def setUpUI(self): self.Vlayout = QVBoxLayout(self) self.Hlayout1 = QHBoxLayout() self.Hlayout2 = QHBoxLayout() self.formlayout = QFormLayout() self.label1 = QLabel("用户名: ") labelFont = QFont() labelFont.setPixelSize(18) lineEditFont = QFont() lineEditFont.setPixelSize(16) self.label1.setFont(labelFont) self.lineEdit1 = QLineEdit() self.lineEdit1.setFixedHeight(32) self.lineEdit1.setFixedWidth(180) self.lineEdit1.setFont(lineEditFont) self.lineEdit1.setMaxLength(10) self.formlayout.addRow(self.label1, self.lineEdit1) self.label2 = QLabel("密 码: ") self.label2.setFont(labelFont) self.lineEdit2 = QLineEdit() self.lineEdit2.setFixedHeight(32) self.lineEdit2.setFixedWidth(180) self.lineEdit2.setMaxLength(16) # 设置验证 reg = QRegExp("PB[0~9]{8}") pValidator = QRegExpValidator(self) pValidator.setRegExp(reg) self.lineEdit1.setValidator(pValidator) reg = QRegExp("[a-zA-z0-9]+$") pValidator.setRegExp(reg) self.lineEdit2.setValidator(pValidator) passwordFont = QFont() passwordFont.setPixelSize(10) self.lineEdit2.setFont(passwordFont) self.lineEdit2.setEchoMode(QLineEdit.Password) self.formlayout.addRow(self.label2, self.lineEdit2) self.signIn = QPushButton("登 录") self.signIn.setFixedWidth(80) self.signIn.setFixedHeight(30) self.signIn.setFont(labelFont) self.formlayout.addRow("", self.signIn) self.label = QLabel("欢迎使用银河智维AI平台") fontlabel = QFont() fontlabel.setPixelSize(30) self.label.setFixedWidth(390) # self.label.setFixedHeight(80) self.label.setFont(fontlabel) self.Hlayout1.addWidget(self.label, Qt.AlignCenter) self.widget1 = QWidget() self.widget1.setLayout(self.Hlayout1) self.widget2 = QWidget() self.widget2.setFixedWidth(300) self.widget2.setFixedHeight(150) self.widget2.setLayout(self.formlayout) self.Hlayout2.addWidget(self.widget2, Qt.AlignCenter) self.widget = QWidget() self.widget.setLayout(self.Hlayout2) self.Vlayout.addWidget(self.widget1) self.Vlayout.addWidget(self.widget, Qt.AlignTop) self.signIn.clicked.connect(self.signInCheck) self.lineEdit2.returnPressed.connect(self.signInCheck) self.lineEdit1.returnPressed.connect(self.signInCheck) def signInCheck(self): studentId = self.lineEdit1.text() password = self.lineEdit2.text() if (studentId == "" or password == ""): print(QMessageBox.warning(self, "警告", "用户名和密码不可为空!", QMessageBox.Yes, QMessageBox.Yes)) return # 打开数据库连接 db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName('./db/LibraryManagement.db') db.open() query = QSqlQuery() sql = "SELECT * FROM user WHERE StudentId='%s'" % (studentId) query.exec_(sql) db.close() hl = hashlib.md5() hl.update(password.encode(encoding='utf-8')) if (not query.next()): print(QMessageBox.information(self, "提示", "该账号不存在!", QMessageBox.Yes, QMessageBox.Yes)) else: if (studentId == query.value(0) and hl.hexdigest() == query.value(2)): # 如果是管理员 if (query.value(3)==1): self.is_admin_signal.emit() else: self.is_student_signal.emit(studentId) else: print(QMessageBox.information(self, "提示", "密码错误!", QMessageBox.Yes, QMessageBox.Yes)) return
class sounds_widget(QWidget, themed_window): def __init__(self, parent, theme, sound_data): super().__init__() self.parent = parent self.sound_data = sound_data #stuff that we want to return / have access to self.selected = None self.filepath = None self.change_nothing = True self.setup_ui() self.setup_sound_data() self.sound_bar.itemSelectionChanged.connect(self.edit_right_side) self.change_nothing = False self.set_theme(theme) def setup_ui(self): #will set up the basic layout with no information self.horizontalLayout = QHBoxLayout() self.centralwidget = self.horizontalLayout #self.setCentralWidget(self.horizontalLayout) self.setLayout(self.centralwidget) #choose the animation type self.type_layout = QWidget(self) self.type_box = QVBoxLayout(self.type_layout) self.select_label = QLabel(self.type_layout) self.select_label.setText("Select Entry to Edit") self.sound_bar = sound_entry_selector(self.type_layout) self.sound_bar.clear() self.add_entry = QPushButton(self.type_layout) self.add_entry.setText("Add New Sound Entry") self.add_entry.clicked.connect(self.add_blank_entry) self.delete_entry = QPushButton(self.type_layout) self.delete_entry.setText("Remove Current Sound Entry") self.delete_entry.clicked.connect(self.delete_curr_entry) self.type_box.addWidget(self.select_label) self.type_box.addWidget(self.sound_bar) self.type_box.addWidget(self.add_entry) self.type_box.addWidget(self.delete_entry) #other needed info self.other_info_layout = QWidget(self) self.other_info_layout.setGeometry(0, 0, 250, 250) self.other_info_box = self.create_right_side() #add stuff to horizontal layout self.horizontalLayout.addWidget(self.type_layout) self.horizontalLayout.addWidget(self.other_info_layout) def setup_sound_data(self): self.change_nothing = True self.sound_bar.clear() if self.sound_data is not None: self.other_info_layout.setDisabled(False) for i in range( len(self.sound_data) ): current_sound_entry = single_sound_entry(self.sound_bar, self.sound_data[i]) current_sound_entry.setText("Sound Entry " + str(i) ) #self.sound_bar.addItem( current_sound_entry ) self.sound_bar.setCurrentItem(current_sound_entry) self.sound_bar.curr_item = current_sound_entry if len(self.sound_data) > 0: self.set_right_side() else: self.sound_id_field.setText( "" ) self.start_time_field.setText( "" ) self.end_time_field.setText( "" ) self.flags_field.setText( "" ) self.loop_count_field.setText( "" ) self.volume_field.setText( "" ) self.coarse_pitch_field.setText( "" ) self.fine_pitch_field.setText( "") self.pan_field.setText("" ) self.unk_byte_field.setText( "" ) self.other_info_layout.setDisabled(True) self.change_nothing = False def create_right_side(self): #will fill in the stuff on the right side - basically all the annoying fields and labels operations_box = QGridLayout(self.other_info_layout) widget_parent = self.other_info_layout label = QLabel(widget_parent) label.setText("Select File") operations_box.addWidget(label, 0, 0) button = QPushButton("Import from .bck") button.clicked.connect(self.open_file_dialog) operations_box.addWidget(button , 0, 1) #------------------------------------------- label_soundid = QLabel(widget_parent) label_soundid.setText("Sound ID:") operations_box.addWidget(label_soundid, 1, 0) self.sound_id_field = QLineEdit(widget_parent) operations_box.addWidget( self.sound_id_field, 1, 1) #------------------------------------------- label_start_time = QLabel(widget_parent) label_start_time.setText("Start Frame:") operations_box.addWidget(label_start_time, 2, 0) self.start_time_field = QLineEdit(widget_parent) operations_box.addWidget( self.start_time_field, 2, 1) label_end_time = QLabel(widget_parent) label_end_time.setText("End Frame:") operations_box.addWidget(label_end_time, 3, 0) self.end_time_field = QLineEdit(widget_parent) operations_box.addWidget( self.end_time_field, 3, 1) label_flags = QLabel(widget_parent) label_flags.setText("Loop Flags:") operations_box.addWidget(label_flags, 4, 0) self.flags_field = QLineEdit(widget_parent) operations_box.addWidget( self.flags_field, 4, 1) label_loop_count = QLabel(widget_parent) label_loop_count.setText("Loop Count:") operations_box.addWidget(label_loop_count, 5, 0) self.loop_count_field = QLineEdit(widget_parent) operations_box.addWidget( self.loop_count_field, 5, 1) #---------------------------------- label_volume = QLabel(widget_parent) label_volume.setText("Volume:") operations_box.addWidget(label_volume, 6, 0) self.volume_field = QLineEdit(widget_parent) operations_box.addWidget( self.volume_field, 6, 1) label_coarse_pitch = QLabel(widget_parent) label_coarse_pitch.setText("Coarse Pitch:") operations_box.addWidget(label_coarse_pitch, 7, 0) self.coarse_pitch_field = QLineEdit(widget_parent) operations_box.addWidget( self.coarse_pitch_field, 7, 1) label_fine_pitch = QLabel(widget_parent) label_fine_pitch.setText("Fine Pitch:") operations_box.addWidget(label_fine_pitch, 8, 0) self.fine_pitch_field = QLineEdit(widget_parent) operations_box.addWidget( self.fine_pitch_field, 8, 1) label_pan = QLabel(widget_parent) label_pan.setText("Pan:") operations_box.addWidget(label_pan, 9, 0) self.pan_field = QLineEdit(widget_parent) operations_box.addWidget( self.pan_field, 9, 1) #-------------------------------- label_unk_byte = QLabel(widget_parent) label_unk_byte.setText("Speed / Interval Value:") operations_box.addWidget(label_unk_byte, 10, 0) self.unk_byte_field = QLineEdit(widget_parent) operations_box.addWidget( self.unk_byte_field, 10, 1) return operations_box def edit_right_side(self): #handles when the current selected sound entry is changed if self.change_nothing == False: if self.sound_bar.count() > 0: new_sound_data_entry = self.get_on_screen() print( new_sound_data_entry ) self.sound_bar.curr_item.sound_data_entry = new_sound_data_entry self.sound_bar.curr_item = self.sound_bar.currentItem() self.set_right_side() self.change_nothing = False def get_on_screen(self): if self.change_nothing == False and self.sound_id_field.text() != "": sound_id = float(self.sound_id_field.text()) start_time = float(self.start_time_field.text()) end_time = float( self.end_time_field.text() ) coarse_pitch = float(self.coarse_pitch_field.text() ) flags = int(self.flags_field.text()) volume = int(self.volume_field.text() ) fine_pitch = int(self.fine_pitch_field.text() ) loop_count = int(self.loop_count_field.text() ) pan = int(self.pan_field.text() ) unk_byte = int(self.unk_byte_field.text() ) new_sound_entry = sound_entry(sound_id, start_time, end_time, coarse_pitch, flags, volume, fine_pitch, loop_count, pan, unk_byte) return new_sound_entry def set_right_side(self): #will set the values on the right side in all cases - will use the currentitem of the listwidget sound_data_entry = self.sound_bar.currentItem().sound_data_entry self.sound_id_field.setText( str(sound_data_entry.sound_id) ) self.start_time_field.setText( str(int(sound_data_entry.start_time)) ) self.end_time_field.setText( str(int(sound_data_entry.end_time)) ) self.flags_field.setText( str(sound_data_entry.flags) ) self.loop_count_field.setText( str(sound_data_entry.loop_count) ) self.volume_field.setText( str(sound_data_entry.volume) ) self.coarse_pitch_field.setText( str(sound_data_entry.coarse_pitch) ) self.fine_pitch_field.setText( str(sound_data_entry.fine_pitch) ) self.pan_field.setText( str(sound_data_entry.pan) ) self.unk_byte_field.setText( str(sound_data_entry.unk_byte) ) def add_blank_entry(self): self.change_nothing = True self.other_info_layout.setDisabled(False) new_entry = single_sound_entry(self.sound_bar) new_entry.setText("Sound Entry " + str(self.sound_bar.count() - 1) ) self.sound_bar.curr_item = new_entry self.sound_bar.setCurrentItem(new_entry) self.change_nothing = False self.set_right_side() def delete_curr_entry(self): self.sound_bar.takeItem(self.sound_bar.currentRow()) if self.sound_bar.count() > 0: self.sound_bar.curr_item = self.sound_bar.currentItem() self.set_right_side() else: self.other_info_layout.setDisabled(True) def get_soundids_combobox(self, widget_parent): #will fill in the combo box with the sound ids - gotta get back to xayr combo_box = QComboBox(widget_parent) return combo_box def get_info(self): if self.sound_bar.count() == 0: return None new_sound_data_entry = self.get_on_screen() self.sound_bar.curr_item.sound_data_entry = new_sound_data_entry new_sound_data = [] for i in range(0, self.sound_bar.count() ): new_sound_data.append( self.sound_bar.item(i).sound_data_entry ) return new_sound_data def open_file_dialog(self): filepath, choosentype = QFileDialog.getOpenFileName(self.other_info_layout, "Choose File Path", "", "bck files (*.bck)") if filepath: #self.filename_text.setText(filepath) self.filepath = filepath self.sound_data = sound_entry.read_sound_data(filepath) self.setup_sound_data()
def addTab(self, widget, title): """ Add a new tab to the switcher """ # Proxy up to the real addTab tab_id = super(FileTabs, self).addTab(widget, title) # A widget to put the indicator and close button in container = QWidget() box = QHBoxLayout(container) # We don't want any margins on the layout, that would expand the tab box.setContentsMargins(0, 0, 0, 0) # Ensure some space between image and button box.setSpacing(6) # Counterintuitively QImage doesn't show an image, QLabel does state_lbl = QLabel(container) box.addWidget(state_lbl) state_lbl.setPixmap(load_pixmap("document.svg")) # Watch for status change to update the dirty indicator # We watch here as it's far easier to keep track of state_lbl # It does mean we assume all tabs are EditorPane @widget.modificationChanged.connect def on_modified(): if widget.isModified(): state_lbl.setPixmap(load_pixmap("document-dirty.svg")) else: # This icon is actually empty state_lbl.setPixmap(load_pixmap("document.svg")) # Setup our own close button since we are overriding the built in one close_btn = QPushButton(container) box.addWidget(close_btn) close_btn.setToolTip(_("Close file")) close_btn.setFlat(True) # Bit of a weird size but we want to avoid giant tabs close_btn.setIconSize(QSize(10, 10)) close_btn.setIcon(load_icon("close-tab.svg")) close_btn.show() # Handle 'clicked' events @close_btn.clicked.connect def close(): # The tab_id isn't constant and may have changed, lookup the # current id of the EditorPane tab_id = self.indexOf(widget) # Close the tab self.removeTab(tab_id) container.setLayout(box) # Add the box, clearly it isn't a button but QTabBar actually takes # any QWidget not just buttons self.tabBar().setTabButton(tab_id, QTabBar.RightSide, container) # Return the index of the new page just like the reall addTab return tab_id
def setUpUI(self): self.Vlayout = QVBoxLayout(self) self.Hlayout1 = QHBoxLayout() self.Hlayout2 = QHBoxLayout() self.formlayout = QFormLayout() self.label1 = QLabel("用户名: ") labelFont = QFont() labelFont.setPixelSize(18) lineEditFont = QFont() lineEditFont.setPixelSize(16) self.label1.setFont(labelFont) self.lineEdit1 = QLineEdit() self.lineEdit1.setFixedHeight(32) self.lineEdit1.setFixedWidth(180) self.lineEdit1.setFont(lineEditFont) self.lineEdit1.setMaxLength(10) self.formlayout.addRow(self.label1, self.lineEdit1) self.label2 = QLabel("密 码: ") self.label2.setFont(labelFont) self.lineEdit2 = QLineEdit() self.lineEdit2.setFixedHeight(32) self.lineEdit2.setFixedWidth(180) self.lineEdit2.setMaxLength(16) # 设置验证 reg = QRegExp("PB[0~9]{8}") pValidator = QRegExpValidator(self) pValidator.setRegExp(reg) self.lineEdit1.setValidator(pValidator) reg = QRegExp("[a-zA-z0-9]+$") pValidator.setRegExp(reg) self.lineEdit2.setValidator(pValidator) passwordFont = QFont() passwordFont.setPixelSize(10) self.lineEdit2.setFont(passwordFont) self.lineEdit2.setEchoMode(QLineEdit.Password) self.formlayout.addRow(self.label2, self.lineEdit2) self.signIn = QPushButton("登 录") self.signIn.setFixedWidth(80) self.signIn.setFixedHeight(30) self.signIn.setFont(labelFont) self.formlayout.addRow("", self.signIn) self.label = QLabel("欢迎使用银河智维AI平台") fontlabel = QFont() fontlabel.setPixelSize(30) self.label.setFixedWidth(390) # self.label.setFixedHeight(80) self.label.setFont(fontlabel) self.Hlayout1.addWidget(self.label, Qt.AlignCenter) self.widget1 = QWidget() self.widget1.setLayout(self.Hlayout1) self.widget2 = QWidget() self.widget2.setFixedWidth(300) self.widget2.setFixedHeight(150) self.widget2.setLayout(self.formlayout) self.Hlayout2.addWidget(self.widget2, Qt.AlignCenter) self.widget = QWidget() self.widget.setLayout(self.Hlayout2) self.Vlayout.addWidget(self.widget1) self.Vlayout.addWidget(self.widget, Qt.AlignTop) self.signIn.clicked.connect(self.signInCheck) self.lineEdit2.returnPressed.connect(self.signInCheck) self.lineEdit1.returnPressed.connect(self.signInCheck)
# -*- coding: utf-8 -*- """ simple signal """ import sys from PyQt5.QtWidgets import QApplication, QDialog, QPushButton app = QApplication(sys.argv) dlg = QDialog() dlg.setWindowTitle('just close it') dlg.resize(300, 200) i = 1 def beatMe(): global i dlg.setWindowTitle("Beat me one more time! " + str(i)) i = i + 1 btn = QPushButton(dlg) btn.resize(100, 50) btn.setText('click it!') btn.move(100, 100) # 将btn的clicked信号与dlg的close槽连接 btn.clicked.connect(beatMe) dlg.show() sys.exit(app.exec())
class TimerWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) self.minutesLabel = QLabel("Minutes:") self.minutesSpinBox = QSpinBox() self.minutesSpinBox.setFixedSize(60, 23) self.minutesSpinBox.setRange(0, 10**9) self.minutesSpinBox.setSingleStep(5) self.minutesSpinBox.setFocus() self.minutesSpinBox.selectAll() self.minutesSpinBox.valueChanged.connect(self._edit_event) self.startButton = QPushButton(ButtonText.start) self.startButton.setFixedSize(50, 23) self.startButton.clicked.connect(self._start_event) self.resetButton = QPushButton(ButtonText.reset) self.resetButton.setFixedSize(50, 23) self.resetButton.clicked.connect(self._reset_event) self.displayArea = QTextEdit() self.displayArea.setTextColor(QColorConstants.DarkBlue) self.displayArea.setStyleSheet("border: none") self.displayArea.setFontFamily("Arial") self.displayArea.setFontPointSize(38) self.displayArea.setTextInteractionFlags(Qt.NoTextInteraction) self.displayArea.viewport().setCursor(Qt.ArrowCursor) self.displayArea.viewport().installEventFilter(self) self.setWidgets() self._status = TimerStatus.init self._left_seconds = 0 self.timer = QTimer() self.timer.timeout.connect(self._countdown_and_show) self.showTime() def eventFilter(self, obj, event): if obj is self.displayArea.viewport() and event.type( ) == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: self.minutesSpinBox.setFocus() self.minutesSpinBox.selectAll() return super(TimerWidget, self).eventFilter(obj, event) def _countdown_and_show(self): if self._left_seconds > 0: self._left_seconds -= 1 self.showTime() else: self.timer.stop() self.showTime() self.startButton.setText(ButtonText.start) self._status = TimerStatus.init self._left_seconds = self.minutesSpinBox.value() * 60 def _start_event(self): if (self._status == TimerStatus.init or self._status == TimerStatus.paused) and self._left_seconds > 0: self._left_seconds -= 1 self._status = TimerStatus.counting self.showTime() self.timer.start(1000) self.startButton.setText(ButtonText.pause) elif self._status == TimerStatus.counting: self.timer.stop() self._status = TimerStatus.paused self.startButton.setText(ButtonText.start) def _reset_event(self): self._status = TimerStatus.init self._left_seconds = self.minutesSpinBox.value() * 60 self.startButton.setText(ButtonText.start) self.timer.stop() self.showTime() def _edit_event(self): if self._status == TimerStatus.init: self._left_seconds = self.minutesSpinBox.value() * 60 self.showTime() def showTime(self): total_seconds = min(self._left_seconds, 359940) # Max time: 99:59:00 hours = total_seconds // 3600 total_seconds = total_seconds - (hours * 3600) minutes = total_seconds // 60 seconds = total_seconds - (minutes * 60) self.displayArea.setText("{:02}:{:02}:{:02}".format( int(hours), int(minutes), int(seconds))) self.displayArea.setAlignment(Qt.AlignHCenter) def setWidgets(self): hbox = QHBoxLayout() hbox.addWidget(self.minutesLabel) hbox.addWidget(self.minutesSpinBox) hbox.addWidget(self.startButton) hbox.addWidget(self.resetButton) hbox.setAlignment(Qt.AlignLeft) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(self.displayArea) self.setLayout(vbox)
def __init__(self, parent, receiver_slot, settings, video_dict={}): super().__init__(parent, receiver_slot, settings, video_dict) self.setWindowTitle(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video Finder')) self.size_label.hide() # empty lists for no_audio and no_video and video_audio files self.no_audio_list = [] self.no_video_list = [] self.video_audio_list = [] self.media_title = '' # 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) # extension_label self.extension_label = QLabel(self.link_frame) self.change_name_horizontalLayout.addWidget(self.extension_label) # Fetch Button self.url_submit_pushButtontton = QPushButton(self.link_frame) self.link_horizontalLayout.addWidget(self.url_submit_pushButtontton) # Status Box self.status_box_textEdit = QTextEdit(self.link_frame) self.status_box_textEdit.setMaximumHeight(150) self.link_verticalLayout.addWidget(self.status_box_textEdit) # Select format horizontal layout select_format_horizontalLayout = QHBoxLayout() # Selection Label select_format_label = QLabel(self.link_frame) select_format_horizontalLayout.addWidget(select_format_label) # Selection combobox self.media_comboBox = QComboBox(self.link_frame) self.media_comboBox.setMinimumWidth(200) select_format_horizontalLayout.addWidget(self.media_comboBox) # Duration label self.duration_label = QLabel(self.link_frame) select_format_horizontalLayout.addWidget(self.duration_label) self.format_selection_frame = QFrame(self) self.format_selection_frame.setLayout(select_format_horizontalLayout) self.link_verticalLayout.addWidget(self.format_selection_frame) # advanced_format_selection_checkBox self.advanced_format_selection_checkBox = QCheckBox(self) self.link_verticalLayout.addWidget(self.advanced_format_selection_checkBox) # advanced_format_selection_frame self.advanced_format_selection_frame = QFrame(self) self.link_verticalLayout.addWidget(self.advanced_format_selection_frame) advanced_format_selection_horizontalLayout = QHBoxLayout(self.advanced_format_selection_frame) # video_format_selection self.video_format_selection_label = QLabel(self.advanced_format_selection_frame) self.video_format_selection_comboBox = QComboBox(self.advanced_format_selection_frame) # audio_format_selection self.audio_format_selection_label = QLabel(self.advanced_format_selection_frame) self.audio_format_selection_comboBox = QComboBox(self.advanced_format_selection_frame) for widget in [self.video_format_selection_label, self.video_format_selection_comboBox, self.audio_format_selection_label, self.audio_format_selection_comboBox]: advanced_format_selection_horizontalLayout.addWidget(widget) # Set Texts self.url_submit_pushButtontton.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Fetch Media List')) select_format_label.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Select a format')) self.video_format_selection_label.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video format:')) self.audio_format_selection_label.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Audio format:')) self.advanced_format_selection_checkBox.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Advanced options')) # Add Slot Connections self.url_submit_pushButtontton.setEnabled(False) self.change_name_lineEdit.setEnabled(False) self.ok_pushButton.setEnabled(False) self.download_later_pushButton.setEnabled(False) self.format_selection_frame.setEnabled(True) self.advanced_format_selection_frame.setEnabled(False) self.advanced_format_selection_checkBox.toggled.connect(self.advancedFormatFrame) self.url_submit_pushButtontton.clicked.connect(self.submitClicked) self.media_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'video_audio')) self.video_format_selection_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'video')) self.audio_format_selection_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'audio')) self.link_lineEdit.textChanged.disconnect(super().linkLineChanged) # Should be disconnected. self.link_lineEdit.textChanged.connect(self.linkLineChangedHere) self.setMinimumSize(650, 480) self.status_box_textEdit.hide() self.format_selection_frame.hide() self.advanced_format_selection_frame.hide() self.advanced_format_selection_checkBox.hide() if 'link' in video_dict.keys() and video_dict['link']: self.link_lineEdit.setText(video_dict['link']) self.url_submit_pushButtontton.setEnabled(True) else: # check clipboard clipboard = QApplication.clipboard() text = clipboard.text() if (("tp:/" in text[2:6]) or ("tps:/" in text[2:7])): self.link_lineEdit.setText(str(text)) self.url_submit_pushButtontton.setEnabled(True)
class FTracePanel(QWidget): def __init__(self, app, flags=None, *args, **kwargs): super().__init__(flags, *args, **kwargs) self.app = app self.kernel = app.get_dwarf().get_kernel() self.ftrace = self.kernel.get_ftrace() self.trace_read_dialog = None layout = QVBoxLayout() central_layout = QVBoxLayout() self.options = QSplitter() self.filter_functions = QTextEdit() self.filter_events = QTextEdit() self.options_list = QListWidget() self.setup_options_view() central_layout.addWidget(self.options) self.buttons = QHBoxLayout() self.btn_pause = QPushButton('pause') self.btn_trace = QPushButton('start') self.btn_read = QPushButton('read') self.btn_pause.setEnabled(False) self.btn_pause.clicked.connect(self.pause_clicked) self.btn_trace.clicked.connect(self.trace_clicked) self.btn_read.clicked.connect(self.read_clicked) self.buttons.addWidget(self.btn_pause) self.buttons.addWidget(self.btn_trace) self.buttons.addWidget(self.btn_read) layout.addLayout(self.buttons) layout.addLayout(central_layout) self.setLayout(layout) def append_data(self, data): if self.trace_read_dialog is not None: self.trace_read_dialog.append(data) def disable_options_view(self): self.btn_pause.setEnabled(True) self.btn_trace.setText('stop') self.btn_read.setEnabled(False) self.options_list.setEnabled(False) self.filter_events.setEnabled(False) self.filter_functions.setEnabled(False) def enable_options_view(self): self.btn_pause.setEnabled(False) self.btn_trace.setText('start') self.btn_read.setEnabled(True) self.options_list.setEnabled(True) self.filter_events.setEnabled(True) self.filter_functions.setEnabled(True) def setup_options_view(self): self.options.setOrientation(Qt.Horizontal) self.options.setHandleWidth(1) filter_functions_layout = QVBoxLayout() filter_functions_layout.addWidget(QLabel("Filter functions")) bar = QScrollBar() bar.setFixedHeight(0) bar.setFixedWidth(0) self.filter_functions.setHorizontalScrollBar(bar) self.filter_functions.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.filter_functions.setPlainText(self.ftrace.get_current_filters()) self.filter_functions.setPlaceholderText("*SyS_open*") filter_functions_layout.addWidget(self.filter_functions) filter_events_layout = QVBoxLayout() filter_events_layout.addWidget(QLabel("Filter events")) bar = QScrollBar() bar.setFixedHeight(0) bar.setFixedWidth(0) self.filter_events.setHorizontalScrollBar(bar) self.filter_events.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.filter_events.setPlainText(self.ftrace.get_current_events()) self.filter_events.setPlaceholderText('raw_syscalls:sys_exit\nraw_syscalls:sys_enter') filter_events_layout.addWidget(self.filter_events) filter_functions_widget = QWidget() filter_functions_widget.setLayout(filter_functions_layout) filter_events_widget = QWidget() filter_events_widget.setLayout(filter_events_layout) options_list_layout = QVBoxLayout() options_list_layout.addWidget(QLabel("Options")) for option in self.ftrace.get_options(): if len(option) < 1: continue q = NotEditableListWidgetItem() q.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) if not option.startswith('no'): q.setCheckState(Qt.Checked) q.setText(option) else: q.setCheckState(Qt.Unchecked) q.setText(option[2:]) self.options_list.addItem(q) options_list_layout.addWidget(self.options_list) options_list_widget = QWidget() options_list_widget.setLayout(options_list_layout) self.options.addWidget(filter_functions_widget) self.options.addWidget(filter_events_widget) self.options.addWidget(options_list_widget) def pause_clicked(self): if self.ftrace.state == FTrace.STATE_TRACING: self.ftrace.pause() self.btn_read.setEnabled(True) self.btn_trace.setText("resume") def read_clicked(self): self.trace_read_dialog = FTraceReadDialog() self.ftrace.read_trace_async() self.trace_read_dialog.show() def trace_clicked(self): if self.ftrace.state == FTrace.STATE_TRACING: self.ftrace.stop() self.enable_options_view() elif self.ftrace.state == FTrace.STATE_NOT_TRACING: self.ftrace.set_current_events(self.filter_events.toPlainText()) self.ftrace.set_current_filters(self.filter_functions.toPlainText()) for i in range(0, self.options_list.count()): item = self.options_list.item(i) option = item.text() enabled = True if item.checkState() == Qt.Unchecked: enabled = False self.ftrace.set_option(option, enabled) self.ftrace.start() self.disable_options_view() else: self.ftrace.start() self.disable_options_view()
def edit(self): logging.debug('edit() called BinanceSched') interval_str, interval_index, offset, log_state = self.config self.binance_sched_layout = QVBoxLayout() self.confirm_button = QPushButton(QC.translate('', 'Ok')) self.interval_txt = QLabel() self.interval_txt.setText( QC.translate('', 'Choose the scheduler interval')) # https://github.com/sammchardy/python-binance/blob/master/binance/client.py self.selectInterval = QComboBox() self.selectInterval.addItem(QC.translate('', '1 Minute'), QVariant('1m')) self.selectInterval.addItem(QC.translate('', '3 Minutes'), QVariant('3m')) self.selectInterval.addItem(QC.translate('', '5 Minutes'), QVariant('5m')) self.selectInterval.addItem(QC.translate('', '15 Minutes'), QVariant('15m')) self.selectInterval.addItem(QC.translate('', '30 Minutes'), QVariant('30m')) self.selectInterval.addItem(QC.translate('', '1 Hour'), QVariant('1h')) self.selectInterval.addItem(QC.translate('', '2 Hours'), QVariant('2h')) self.selectInterval.addItem(QC.translate('', '4 Hours'), QVariant('4h')) self.selectInterval.addItem(QC.translate('', '6 Hours'), QVariant('6h')) self.selectInterval.addItem(QC.translate('', '8 Hours'), QVariant('8h')) self.selectInterval.addItem(QC.translate('', '12 Hours'), QVariant('12h')) self.selectInterval.addItem(QC.translate('', '1 Day'), QVariant('1d')) self.selectInterval.setCurrentIndex(interval_index) self.offset_txt = QLabel() self.offset_txt.setText( QC.translate( '', 'Enter time offset [s] (default: 0; range: -999s to + 999s)')) self.offset_input = QLineEdit() self.offset_input.setValidator(QIntValidator(-999, 999)) self.offset_input.setText(str(offset)) self.help_text = QWidget() self.help_text_layout = QVBoxLayout(self.help_text) self.help_text_1 = QLabel() self.help_text_1.setText( QC.translate( '', 'Synchronize with Binance and execute subsequent modules')) self.help_text_2 = QLabel() self.help_text_2.setText( QC.translate('', 'after expiration of the selected interval.')) self.help_text_layout.addWidget(self.help_text_1) self.help_text_layout.addWidget(self.help_text_2) self.log_line = QWidget() self.ask_for_logging = QLabel() self.ask_for_logging.setText(QC.translate('', 'Log output?')) self.log_checkbox = QCheckBox() self.log_line_layout = QHBoxLayout(self.log_line) self.log_line_layout.addWidget(self.ask_for_logging) self.log_line_layout.addWidget(self.log_checkbox) self.log_line_layout.addStretch(1) if log_state: self.log_checkbox.setChecked(True) self.binance_sched_edit = ElementEditor(self) self.binance_sched_edit.setWindowTitle( QC.translate('', 'Edit Binance Scheduler')) # signals and slots self.confirm_button.clicked.connect(self.binance_sched_edit.closeEvent) self.binance_sched_edit.window_closed.connect(self.edit_done) self.binance_sched_layout.addWidget(self.interval_txt) self.binance_sched_layout.addWidget(self.selectInterval) self.binance_sched_layout.addWidget(self.offset_txt) self.binance_sched_layout.addWidget(self.offset_input) self.binance_sched_layout.addWidget(self.log_line) self.binance_sched_layout.addWidget(self.help_text) self.binance_sched_layout.addStretch(1) self.binance_sched_layout.addWidget(self.confirm_button) self.binance_sched_edit.setLayout(self.binance_sched_layout) self.binance_sched_edit.show()
class VectorOpenDialog(QDialog): def __init__(self, parent, layerList): QDialog.__init__(self, parent) self.setWindowTitle('Open Vector Layer') self.layerList = layerList self.layerTypeButtonGroup = QButtonGroup() # enforces exclusivity self.layerNameRadio = QRadioButton("Layer Name") self.layerSQLRadio = QRadioButton("SQL") self.layerTypeButtonGroup.addButton(self.layerNameRadio) self.layerTypeButtonGroup.addButton(self.layerSQLRadio) self.layerNameRadio.setChecked(True) # the default self.mainLayout = QVBoxLayout() self.nameLayout = QHBoxLayout() self.nameLayout.addWidget(self.layerNameRadio) self.nameCombo = QComboBox() for layerName in layerList: self.nameCombo.addItem(layerName) self.nameLayout.addWidget(self.nameCombo) self.mainLayout.addLayout(self.nameLayout) self.sqlLayout = QHBoxLayout() self.sqlLayout.addWidget(self.layerSQLRadio) self.sqlText = QTextEdit() self.sqlText.setReadOnly(True) fm = QFontMetrics(self.sqlText.font()) self.sqlText.setFixedHeight(NUM_SQL_ROWS * fm.lineSpacing()) self.layerNameRadio.toggled.connect(self.typeToggled) self.sqlLayout.addWidget(self.sqlText) self.mainLayout.addLayout(self.sqlLayout) # ok and cancel buttons self.okButton = QPushButton(self) self.okButton.setText("OK") self.okButton.setDefault(True) self.okButton.clicked.connect(self.accept) self.cancelButton = QPushButton(self) self.cancelButton.setText("Cancel") self.cancelButton.clicked.connect(self.reject) self.buttonLayout = QHBoxLayout() self.buttonLayout.addWidget(self.okButton) self.buttonLayout.addWidget(self.cancelButton) self.mainLayout.addLayout(self.buttonLayout) self.setLayout(self.mainLayout) def typeToggled(self, checked): "signal handler for change of state" self.sqlText.setReadOnly(checked) def isNamedLayer(self): "Return if the user has selected a named layer rather than SQL" return self.layerNameRadio.isChecked() def getSelectedLayer(self): "Get the name of the selected layer" return self.nameCombo.currentText() def getSQL(self): "return the SQL text entered" return self.sqlText.toPlainText()
class SessionEditor(QDialog): def __init__(self, parent=None): super(SessionEditor, self).__init__(parent) self.setWindowModality(Qt.WindowModal) layout = QVBoxLayout() self.setLayout(layout) grid = QGridLayout() layout.addLayout(grid) self.name = QLineEdit() self.nameLabel = l = QLabel() l.setBuddy(self.name) grid.addWidget(l, 0, 0) grid.addWidget(self.name, 0, 1) self.autosave = QCheckBox() grid.addWidget(self.autosave, 1, 1) self.basedir = widgets.urlrequester.UrlRequester() self.basedirLabel = l = QLabel() l.setBuddy(self.basedir) grid.addWidget(l, 2, 0) grid.addWidget(self.basedir, 2, 1) self.inclPaths = ip = QGroupBox(self, checkable=True, checked=False) ipLayout = QVBoxLayout() ip.setLayout(ipLayout) self.replPaths = QCheckBox() ipLayout.addWidget(self.replPaths) self.replPaths.toggled.connect(self.toggleReplace) self.include = widgets.listedit.FilePathEdit() self.include.listBox.setDragDropMode(QAbstractItemView.InternalMove) ipLayout.addWidget(self.include) grid.addWidget(ip, 3, 1) self.revt = QPushButton(self) self.clear = QPushButton(self) self.revt.clicked.connect(self.revertPaths) self.clear.clicked.connect(self.clearPaths) self.include.layout().addWidget(self.revt, 5, 1) self.include.layout().addWidget(self.clear, 6, 1) layout.addWidget(widgets.Separator()) self.buttons = b = QDialogButtonBox(self) layout.addWidget(b) b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) b.accepted.connect(self.accept) b.rejected.connect(self.reject) userguide.addButton(b, "sessions") app.translateUI(self) def translateUI(self): self.nameLabel.setText(_("Name:")) self.autosave.setText(_("Always save the list of documents in this session")) self.basedirLabel.setText(_("Base directory:")) self.inclPaths.setTitle(_("Use session specific include path")) self.replPaths.setText(_("Replace global path")) self.replPaths.setToolTip(_("When checked, paths in LilyPond preferences are not included.")) self.revt.setText(_("Copy global path")) self.revt.setToolTip(_("Add and edit the path from LilyPond preferences.")) self.clear.setText(_("Clear")) self.clear.setToolTip(_("Remove all paths.")) def load(self, name): settings = sessions.sessionGroup(name) self.autosave.setChecked(settings.value("autosave", True, bool)) self.basedir.setPath(settings.value("basedir", "", str)) self.include.setValue(qsettings.get_string_list(settings, "include-path")) self.inclPaths.setChecked(settings.value("set-paths", False, bool)) self.replPaths.setChecked(settings.value("repl-paths", False, bool)) if not self.replPaths.isChecked(): self.addDisabledGenPaths() self.revt.setEnabled(False) # more settings here def fetchGenPaths(self): """Fetch paths from general preferences.""" return qsettings.get_string_list(QSettings(), "lilypond_settings/include_path") def addDisabledGenPaths(self): """Add global paths, but set as disabled.""" genPaths = self.fetchGenPaths() for p in genPaths: i = QListWidgetItem(p, self.include.listBox) i.setFlags(Qt.NoItemFlags) def toggleReplace(self): """Called when user changes setting for replace of global paths.""" if self.replPaths.isChecked(): items = self.include.items() for i in items: if not (i.flags() & Qt.ItemIsEnabled): #is not enabled self.include.listBox.takeItem(self.include.listBox.row(i)) self.revt.setEnabled(True) else: self.addDisabledGenPaths() self.revt.setEnabled(False) def revertPaths(self): """Add global paths (for edit).""" genPaths = self.fetchGenPaths() for p in genPaths: i = QListWidgetItem(p, self.include.listBox) def clearPaths(self): """Remove all active paths.""" items = self.include.items() for i in items: if i.flags() & Qt.ItemIsEnabled: self.include.listBox.takeItem(self.include.listBox.row(i)) def save(self, name): settings = sessions.sessionGroup(name) settings.setValue("autosave", self.autosave.isChecked()) settings.setValue("basedir", self.basedir.path()) settings.setValue("set-paths", self.inclPaths.isChecked()) settings.setValue("repl-paths", self.replPaths.isChecked()) path = [i.text() for i in self.include.items() if i.flags() & Qt.ItemIsEnabled] settings.setValue("include-path", path) # more settings here def defaults(self): self.autosave.setChecked(True) self.basedir.setPath('') self.inclPaths.setChecked(False) self.replPaths.setChecked(False) self.addDisabledGenPaths() self.revt.setEnabled(False) # more defaults here def edit(self, name=None): self._originalName = name if name: caption = _("Edit session: {name}").format(name=name) self.name.setText(name) self.load(name) else: caption = _("Edit new session") self.name.clear() self.name.setFocus() self.defaults() self.setWindowTitle(app.caption(caption)) if self.exec_(): # name changed? name = self.name.text() if self._originalName and name != self._originalName: sessions.renameSession(self._originalName, name) self.save(name) return name def done(self, result): if not result or self.validate(): super(SessionEditor, self).done(result) def validate(self): """Checks if the input is acceptable. If this method returns True, the dialog is accepted when OK is clicked. Otherwise a messagebox could be displayed, and the dialog will remain visible. """ name = self.name.text().strip() self.name.setText(name) if not name: self.name.setFocus() QMessageBox.warning(self, app.caption(_("Warning")), _("Please enter a session name.")) if self._originalName: self.name.setText(self._originalName) return False elif name == '-': self.name.setFocus() QMessageBox.warning(self, app.caption(_("Warning")), _("Please do not use the name '{name}'.".format(name="-"))) return False elif self._originalName != name and name in sessions.sessionNames(): self.name.setFocus() box = QMessageBox(QMessageBox.Warning, app.caption(_("Warning")), _("Another session with the name {name} already exists.\n\n" "Do you want to overwrite it?").format(name=name), QMessageBox.Discard | QMessageBox.Cancel, self) box.button(QMessageBox.Discard).setText(_("Overwrite")) result = box.exec_() if result != QMessageBox.Discard: return False return True
class VideoFinderAddLink(AddLinkWindow): running_thread = None threadPool = {} def __init__(self, parent, receiver_slot, settings, video_dict={}): super().__init__(parent, receiver_slot, settings, video_dict) self.setWindowTitle(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video Finder')) self.size_label.hide() # empty lists for no_audio and no_video and video_audio files self.no_audio_list = [] self.no_video_list = [] self.video_audio_list = [] self.media_title = '' # 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) # extension_label self.extension_label = QLabel(self.link_frame) self.change_name_horizontalLayout.addWidget(self.extension_label) # Fetch Button self.url_submit_pushButtontton = QPushButton(self.link_frame) self.link_horizontalLayout.addWidget(self.url_submit_pushButtontton) # Status Box self.status_box_textEdit = QTextEdit(self.link_frame) self.status_box_textEdit.setMaximumHeight(150) self.link_verticalLayout.addWidget(self.status_box_textEdit) # Select format horizontal layout select_format_horizontalLayout = QHBoxLayout() # Selection Label select_format_label = QLabel(self.link_frame) select_format_horizontalLayout.addWidget(select_format_label) # Selection combobox self.media_comboBox = QComboBox(self.link_frame) self.media_comboBox.setMinimumWidth(200) select_format_horizontalLayout.addWidget(self.media_comboBox) # Duration label self.duration_label = QLabel(self.link_frame) select_format_horizontalLayout.addWidget(self.duration_label) self.format_selection_frame = QFrame(self) self.format_selection_frame.setLayout(select_format_horizontalLayout) self.link_verticalLayout.addWidget(self.format_selection_frame) # advanced_format_selection_checkBox self.advanced_format_selection_checkBox = QCheckBox(self) self.link_verticalLayout.addWidget(self.advanced_format_selection_checkBox) # advanced_format_selection_frame self.advanced_format_selection_frame = QFrame(self) self.link_verticalLayout.addWidget(self.advanced_format_selection_frame) advanced_format_selection_horizontalLayout = QHBoxLayout(self.advanced_format_selection_frame) # video_format_selection self.video_format_selection_label = QLabel(self.advanced_format_selection_frame) self.video_format_selection_comboBox = QComboBox(self.advanced_format_selection_frame) # audio_format_selection self.audio_format_selection_label = QLabel(self.advanced_format_selection_frame) self.audio_format_selection_comboBox = QComboBox(self.advanced_format_selection_frame) for widget in [self.video_format_selection_label, self.video_format_selection_comboBox, self.audio_format_selection_label, self.audio_format_selection_comboBox]: advanced_format_selection_horizontalLayout.addWidget(widget) # Set Texts self.url_submit_pushButtontton.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Fetch Media List')) select_format_label.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Select a format')) self.video_format_selection_label.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video format:')) self.audio_format_selection_label.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Audio format:')) self.advanced_format_selection_checkBox.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Advanced options')) # Add Slot Connections self.url_submit_pushButtontton.setEnabled(False) self.change_name_lineEdit.setEnabled(False) self.ok_pushButton.setEnabled(False) self.download_later_pushButton.setEnabled(False) self.format_selection_frame.setEnabled(True) self.advanced_format_selection_frame.setEnabled(False) self.advanced_format_selection_checkBox.toggled.connect(self.advancedFormatFrame) self.url_submit_pushButtontton.clicked.connect(self.submitClicked) self.media_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'video_audio')) self.video_format_selection_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'video')) self.audio_format_selection_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'audio')) self.link_lineEdit.textChanged.disconnect(super().linkLineChanged) # Should be disconnected. self.link_lineEdit.textChanged.connect(self.linkLineChangedHere) self.setMinimumSize(650, 480) self.status_box_textEdit.hide() self.format_selection_frame.hide() self.advanced_format_selection_frame.hide() self.advanced_format_selection_checkBox.hide() if 'link' in video_dict.keys() and video_dict['link']: self.link_lineEdit.setText(video_dict['link']) self.url_submit_pushButtontton.setEnabled(True) else: # check clipboard clipboard = QApplication.clipboard() text = clipboard.text() if (("tp:/" in text[2:6]) or ("tps:/" in text[2:7])): self.link_lineEdit.setText(str(text)) self.url_submit_pushButtontton.setEnabled(True) def advancedFormatFrame(self, button): if self.advanced_format_selection_checkBox.isChecked(): self.advanced_format_selection_frame.setEnabled(True) self.format_selection_frame.setEnabled(False) self.mediaSelectionChanged('video', int(self.video_format_selection_comboBox.currentIndex())) else: self.advanced_format_selection_frame.setEnabled(False) self.format_selection_frame.setEnabled(True) self.mediaSelectionChanged('video_audio', int(self.media_comboBox.currentIndex())) def getReadableSize(self, size): try: return '{:1.2f} MB'.format(int(size) / 1048576) except: return str(size) def getReadableDuration(self, seconds): try: seconds = int(seconds) hours = seconds // 3600 seconds = seconds % 3600 minutes = seconds // 60 seconds = seconds % 60 return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds) except: return str(seconds) # Define native slots def urlChanged(self, value): if ' ' in value or value == '': self.url_submit_pushButtontton.setEnabled(False) self.url_submit_pushButtontton.setToolTip(QCoreApplication.translate( "ytaddlink_src_ui_tr", 'Please enter a valid video link')) else: self.url_submit_pushButtontton.setEnabled(True) self.url_submit_pushButtontton.setToolTip('') def submitClicked(self, button=None): # Clear media list self.media_comboBox.clear() self.format_selection_frame.hide() self.advanced_format_selection_checkBox.hide() self.advanced_format_selection_frame.hide() self.video_format_selection_comboBox.clear() self.audio_format_selection_comboBox.clear() self.change_name_lineEdit.clear() self.threadPool.clear() self.change_name_checkBox.setChecked(False) self.video_audio_list.clear() self.no_video_list.clear() self.no_audio_list.clear() self.url_submit_pushButtontton.setEnabled(False) self.status_box_textEdit.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Fetching Media Info...')) self.status_box_textEdit.show() self.ok_pushButton.setEnabled(False) self.download_later_pushButton.setEnabled(False) dictionary_to_send = deepcopy(self.plugin_add_link_dictionary) # More options more_options = self.collectMoreOptions() for k in more_options.keys(): dictionary_to_send[k] = more_options[k] dictionary_to_send['link'] = self.link_lineEdit.text() fetcher_thread = MediaListFetcherThread(self.fetchedResult, dictionary_to_send, self) self.parent.threadPool.append(fetcher_thread) self.parent.threadPool[len(self.parent.threadPool) - 1].start() def fileNameChanged(self, value): if value.strip() == '': self.ok_pushButton.setEnabled(False) def mediaSelectionChanged(self, combobox, index): try: if combobox == 'video_audio': if self.media_comboBox.currentText() == 'Best quality': self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_audio_list[-1]['ext']) else: self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.video_audio_list[index]['ext']) self.change_name_checkBox.setChecked(True) elif combobox == 'video': if self.video_format_selection_comboBox.currentText() != 'No video': self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_audio_list[index - 1]['ext']) self.change_name_checkBox.setChecked(True) else: if self.audio_format_selection_comboBox.currentText() != 'No audio': self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_video_list[int(self.audio_format_selection_comboBox.currentIndex()) - 1]['ext']) self.change_name_checkBox.setChecked(True) else: self.change_name_lineEdit.setChecked(False) elif combobox == 'audio': if self.audio_format_selection_comboBox.currentText() != 'No audio' and self.video_format_selection_comboBox.currentText() == 'No video': self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_video_list[index - 1]['ext']) self.change_name_checkBox.setChecked(True) elif (self.audio_format_selection_comboBox.currentText() == 'No audio' and self.video_format_selection_comboBox.currentText() != 'No video') or (self.audio_format_selection_comboBox.currentText() != 'No audio' and self.video_format_selection_comboBox.currentText() != 'No video'): self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_audio_list[int(self.video_format_selection_comboBox.currentIndex()) - 1]['ext']) self.change_name_checkBox.setChecked(True) elif self.audio_format_selection_comboBox.currentText() == 'No audio' and self.video_format_selection_comboBox.currentText() == 'No video': self.change_name_checkBox.setChecked(False) except Exception as ex: logger.sendToLog(ex, "ERROR") def fetchedResult(self, media_dict): self.url_submit_pushButtontton.setEnabled(True) if 'error' in media_dict.keys(): self.status_box_textEdit.setText('<font color="#f11">' + str(media_dict['error']) + '</font>') self.status_box_textEdit.show() else: # Show the media list # add no audio and no video options to the comboboxes self.video_format_selection_comboBox.addItem('No video') self.audio_format_selection_comboBox.addItem('No audio') self.media_title = media_dict['title'] if 'formats' not in media_dict.keys() and 'entries' in media_dict.keys(): formats = media_dict['entries'] formats = formats[0] media_dict['formats'] = formats['formats'] elif 'formats' not in media_dict.keys() and 'format' in media_dict.keys(): media_dict['formats'] = [media_dict.copy()] try: i = 0 for f in media_dict['formats']: no_audio = False no_video = False text = '' if 'acodec' in f.keys(): # only video, no audio if f['acodec'] == 'none': no_audio = True # resolution if 'height' in f.keys(): text = text + ' ' + '{}p'.format(f['height']) if 'vcodec' in f.keys(): # if f['vcodec'] == 'none' and f['acodec'] != 'none': # continue # No video, show audio bit rate if f['vcodec'] == 'none': text = text + '{}kbps'.format(f['abr']) no_video = True if 'ext' in f.keys(): text = text + ' ' + '.{}'.format(f['ext']) if 'filesize' in f.keys() and f['filesize']: # Youtube api does not supply file size for some formats, so check it. text = text + ' ' + '{}'.format(self.getReadableSize(f['filesize'])) else: # Start spider to find file size input_dict = deepcopy(self.plugin_add_link_dictionary) input_dict['link'] = f['url'] more_options = self.collectMoreOptions() for key in more_options.keys(): input_dict[key] = more_options[key] size_fetcher = FileSizeFetcherThread(input_dict, i) self.threadPool[str(i)] = {'thread': size_fetcher, 'item_id': i} self.parent.threadPool.append(size_fetcher) self.parent.threadPool[len(self.parent.threadPool) - 1].start() self.parent.threadPool[len(self.parent.threadPool) - 1].FOUND.connect(self.findFileSize) # Add current format to the related comboboxes if no_audio: self.no_audio_list.append(f) self.video_format_selection_comboBox.addItem(text) elif no_video: self.no_video_list.append(f) self.audio_format_selection_comboBox.addItem(text) else: self.video_audio_list.append(f) self.media_comboBox.addItem(text) i = i + 1 self.status_box_textEdit.hide() if 'duration' in media_dict.keys(): self.duration_label.setText('Duration ' + self.getReadableDuration(media_dict['duration'])) self.format_selection_frame.show() self.advanced_format_selection_checkBox.show() self.advanced_format_selection_frame.show() self.ok_pushButton.setEnabled(True) self.download_later_pushButton.setEnabled(True) # if we have no options for seperate audio and video, then hide advanced_format_selection... if len(self.no_audio_list) == 0 and len(self.no_video_list) == 0: self.advanced_format_selection_checkBox.hide() self.advanced_format_selection_frame.hide() # set index of comboboxes on best available quality. if len(self.no_audio_list) != 0 and len(self.no_video_list) != 0: self.media_comboBox.addItem('Best quality') self.media_comboBox.setCurrentIndex(len(self.video_audio_list)) elif len(self.video_audio_list) != 0: self.media_comboBox.setCurrentIndex(len(self.video_audio_list) - 1) if len(self.no_audio_list) != 0: self.video_format_selection_comboBox.setCurrentIndex(len(self.no_audio_list)) if len(self.no_video_list) != 0: self.audio_format_selection_comboBox.setCurrentIndex(len(self.no_video_list)) self.mediaSelectionChanged('video_audio', int(self.media_comboBox.currentIndex())) except Exception as ex: logger.sendToLog(ex, "ERROR") def findFileSize(self, result): try: item_id = self.threadPool[str(result['thread_key'])]['item_id'] if result['file_size'] and result['file_size'] != '0': text = self.media_comboBox.itemText(item_id) self.media_comboBox.setItemText(item_id, '{} - {}'.format(text, result['file_size'])) except Exception as ex: logger.sendToLog(ex, "ERROR") def linkLineChangedHere(self, lineEdit): if str(lineEdit) == '': self.url_submit_pushButtontton.setEnabled(False) else: self.url_submit_pushButtontton.setEnabled(True) # This method collects additional information like proxy ip, user, password etc. def collectMoreOptions(self): options = {'ip': None, 'port': None, 'proxy_user': None, 'proxy_passwd': None, 'download_user': None, 'download_passwd': None} if self.proxy_checkBox.isChecked(): options['ip'] = self.ip_lineEdit.text() options['port'] = self.port_spinBox.value() options['proxy_user'] = self.proxy_user_lineEdit.text() options['proxy_passwd'] = self.proxy_pass_lineEdit.text() if self.download_checkBox.isChecked(): options['download_user'] = self.download_user_lineEdit.text() options['download_passwd'] = self.download_pass_lineEdit.text() # These info (keys) are required for spider to find file size, because spider() does not check if key exists. additional_info = ['header', 'load_cookies', 'user_agent', 'referer', 'out'] for i in additional_info: if i not in self.plugin_add_link_dictionary.keys(): options[i] = None return options # user commited information by pressing ok_pushButton, so get information # from VideoFinderAddLink window and return them to the mainwindow with callback! def okButtonPressed(self, button, download_later): link_list = [] # seperate audio format and video format is selected. if self.advanced_format_selection_checkBox.isChecked(): if self.video_format_selection_comboBox.currentText() == 'No video' and self.audio_format_selection_comboBox.currentText() != 'No audio': # only audio link must be added to the link_list audio_link = self.no_video_list[self.audio_format_selection_comboBox.currentIndex() - 1]['url'] link_list.append(audio_link) elif self.video_format_selection_comboBox.currentText() != 'No video' and self.audio_format_selection_comboBox.currentText() == 'No audio': # only video link must be added to the link_list video_link = self.no_audio_list[self.video_format_selection_comboBox.currentIndex() - 1]['url'] link_list.append(video_link) elif self.video_format_selection_comboBox.currentText() != 'No video' and self.audio_format_selection_comboBox.currentText() != 'No audio': # video and audio links must be added to the link_list audio_link = self.no_video_list[self.audio_format_selection_comboBox.currentIndex() - 1]['url'] video_link = self.no_audio_list[self.video_format_selection_comboBox.currentIndex() - 1]['url'] link_list = [video_link, audio_link] elif self.video_format_selection_comboBox.currentText() == 'No video' and self.audio_format_selection_comboBox.currentText() == 'No audio': # no video and no video selected! REALY?!. user is DRUNK! close the window! :)) self.close() else: if self.media_comboBox.currentText() == 'Best quality': # the last item in no_video_list and no_audio_list are the best. audio_link = self.no_video_list[-1]['url'] video_link = self.no_audio_list[-1]['url'] link_list = [video_link, audio_link] else: audio_and_video_link = self.video_audio_list[self.media_comboBox.currentIndex()]['url'] link_list.append(audio_and_video_link) # write user's new inputs in persepolis_setting for next time :) self.persepolis_setting.setValue( 'add_link_initialization/ip', self.ip_lineEdit.text()) self.persepolis_setting.setValue( 'add_link_initialization/port', self.port_spinBox.value()) self.persepolis_setting.setValue( 'add_link_initialization/proxy_user', self.proxy_user_lineEdit.text()) self.persepolis_setting.setValue( 'add_link_initialization/download_user', self.download_user_lineEdit.text()) # get proxy information if not(self.proxy_checkBox.isChecked()): ip = None port = None proxy_user = None proxy_passwd = None else: ip = self.ip_lineEdit.text() if not(ip): ip = None port = self.port_spinBox.value() if not(port): port = None proxy_user = self.proxy_user_lineEdit.text() if not(proxy_user): proxy_user = None proxy_passwd = self.proxy_pass_lineEdit.text() if not(proxy_passwd): proxy_passwd = None # get download username and password information if not(self.download_checkBox.isChecked()): download_user = None download_passwd = None else: download_user = self.download_user_lineEdit.text() if not(download_user): download_user = None download_passwd = self.download_pass_lineEdit.text() if not(download_passwd): download_passwd = None # check that if user limits download speed. if not(self.limit_checkBox.isChecked()): limit = 0 else: if self.limit_comboBox.currentText() == "KiB/s": limit = str(self.limit_spinBox.value()) + str("K") else: limit = str(self.limit_spinBox.value()) + str("M") # get start time for download if user set that. if not(self.start_checkBox.isChecked()): start_time = None else: start_time = self.start_time_qDataTimeEdit.text() # get end time for download if user set that. if not(self.end_checkBox.isChecked()): end_time = None else: end_time = self.end_time_qDateTimeEdit.text() # set name for file(s) if self.change_name_checkBox.isChecked(): name = str(self.change_name_lineEdit.text()) if name == '': name = 'video_finder_file' else: name = 'video_finder_file' # video finder always finds extension # but if it can't find file extension # use mp4 for extension. if str(self.extension_label.text()) == '': extension = '.mp4' else: extension = str(self.extension_label.text()) # did user select seperate audio and video? if len(link_list) == 2: video_name = name + extension audio_name = name + '.' + \ str(self.no_video_list[self.audio_format_selection_comboBox.currentIndex() - 1]['ext']) name_list = [video_name, audio_name] else: name_list = [name + extension] # get number of connections connections = self.connections_spinBox.value() # get download_path download_path = self.download_folder_lineEdit.text() # referer if self.referer_lineEdit.text() != '': referer = self.referer_lineEdit.text() else: referer = None # header if self.header_lineEdit.text() != '': header = self.header_lineEdit.text() else: header = None # user_agent if self.user_agent_lineEdit.text() != '': user_agent = self.user_agent_lineEdit.text() else: user_agent = None # load_cookies if self.load_cookies_lineEdit.text() != '': load_cookies = self.load_cookies_lineEdit.text() else: load_cookies = None add_link_dictionary_list = [] if len(link_list) == 1: # save information in a dictionary(add_link_dictionary). add_link_dictionary = {'referer': referer, 'header': header, 'user_agent': user_agent, 'load_cookies': load_cookies, 'out': name_list[0], 'start_time': start_time, 'end_time': end_time, 'link': link_list[0], 'ip': ip, 'port': port, 'proxy_user': proxy_user, 'proxy_passwd': proxy_passwd, 'download_user': download_user, 'download_passwd': download_passwd, 'connections': connections, 'limit_value': limit, 'download_path': download_path} add_link_dictionary_list.append(add_link_dictionary) else: video_add_link_dictionary = {'referer': referer, 'header': header, 'user_agent': user_agent, 'load_cookies': load_cookies, 'out': name_list[0], 'start_time': start_time, 'end_time': end_time, 'link': link_list[0], 'ip': ip, 'port': port, 'proxy_user': proxy_user, 'proxy_passwd': proxy_passwd, 'download_user': download_user, 'download_passwd': download_passwd, 'connections': connections, 'limit_value': limit, 'download_path': download_path} audio_add_link_dictionary = {'referer': referer, 'header': header, 'user_agent': user_agent, 'load_cookies': load_cookies, 'out': name_list[1], 'start_time': None, 'end_time': end_time, 'link': link_list[1], 'ip': ip, 'port': port, 'proxy_user': proxy_user, 'proxy_passwd': proxy_passwd, 'download_user': download_user, 'download_passwd': download_passwd, 'connections': connections, 'limit_value': limit, 'download_path': download_path} add_link_dictionary_list = [video_add_link_dictionary, audio_add_link_dictionary] # get category of download category = str(self.add_queue_comboBox.currentText()) del self.plugin_add_link_dictionary # return information to mainwindow self.callback(add_link_dictionary_list, download_later, category) # close window self.close()
class TrajectoryBuilder(QDialog): def __init__(self, ins, outs): super(TrajectoryBuilder, self).__init__() self.window_width = 800 self.window_height = 550 self.resize(self.window_width, self.window_height) self.setWindowTitle("Build a trajectory") # init traj scroll pane self.traj_scroll = QScrollArea(self) self.traj_scroll.setGeometry(10, 10, 780, 280) self.traj_scroll.setWidgetResizable(False) self.traj_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.traj_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # grid layout to go within traj_scroll self.groupbox = QGroupBox("Trajectories") self.grid_layout = QGridLayout() self.groupbox.setLayout(self.grid_layout) self.num_rows = 0 self.groupbox.setGeometry(10, 10, 780, 40 + 30*self.num_rows) ''' self.grid_layout.addWidget(QPushButton('1'),0,0) self.grid_layout.addWidget(QPushButton('2'),0,1) self.grid_layout.addWidget(QPushButton('3'),0,2) self.grid_layout.addWidget(QPushButton('4'),1,0) self.grid_layout.addWidget(QPushButton('5'),1,1) self.grid_layout.addWidget(QPushButton('6'),1,2) self.grid_layout.addWidget(QPushButton('7'),2,0) self.grid_layout.addWidget(QPushButton('8'),2,1) self.grid_layout.addWidget(QPushButton('9'),2,2) ''' # init builder scroll pane self.build_scroll = QScrollArea(self) self.build_scroll.setGeometry(10, 300, 780, 90) self.build_scroll.setWidgetResizable(False) self.build_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.build_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # init human/micro io scroll pane self.io_scroll = QScrollArea(self) self.io_scroll.setGeometry(10, 400, 780, 90) self.io_scroll.setWidgetResizable(False) self.io_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.io_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # setup the okay and cancel buttons self.okay = QPushButton("Okay", parent=self) self.okay.setGeometry(355, 510, 40, 30) self.okay.setStyleSheet(""".QPushButton {color: white; border-radius: 4px;background: rgb(100, 100, 100);} .QPushButton:pressed {color: white; border-radius: 4px;background: rgb(150, 150, 150);}""") self.okay.clicked.connect(self.on_okay) self.cancel = QPushButton("Cancel", parent=self) self.cancel.setGeometry(405, 510, 40, 30) self.cancel.setStyleSheet(""".QPushButton {color: white; border-radius: 4px;background: rgb(100, 100, 100);} .QPushButton:pressed {color: white; border-radius: 4px;background: rgb(150, 150, 150);}""") self.cancel.clicked.connect(self.on_cancel) self.inputs = copy.copy(ins.alphabet) self.inputs["leave"] = -1 self.outputs = copy.copy(outs.alphabet) self.outputs["END"] = -1 # populate the io pane with the human inputs self.button_to_text = {} self.text_to_buttons = {} for inp in self.inputs: button = QPushButton(inp, parent=self.io_scroll) self.button_to_text[button] = inp self.text_to_buttons[inp] = button button.setStyleSheet(""".QPushButton {color: white; border-radius: 4px;background: rgb(0, 150, 150);} .QPushButton:pressed {color: white; border-radius: 4px;background: rgb(0, 100, 100);}""") button.clicked.connect(partial(self.add_hum_in, inp)) for out in self.outputs: button = QPushButton(out, parent=self.io_scroll) self.button_to_text[button] = out self.text_to_buttons[out] = button button.hide() button.setStyleSheet(""".QPushButton {color: white; border-radius: 4px;background: rgb(150, 150, 150);} .QPushButton:pressed {color: white; border-radius: 4px;background: rgb(100, 100, 100);}""") button.clicked.connect(partial(self.add_rob_out, out)) self.populate_hum_in() self.rval = None self.trajs = [] self.curr_traj = [] self.curr_hum_in = None self.curr_traj_text = "" self.curr_traj_label = QLabel(self.curr_traj_text, self.build_scroll) self.curr_traj_label.setGeometry(10,10,1000,90) self.build_scroll.setWidget(self.curr_traj_label) self.traj_label_text = "" self.trajs_label = QLabel(self.traj_label_text) self.trajs_label.setGeometry(10,10,1000,90) self.traj_scroll.setWidget(self.groupbox) self.traj2spin = {} def populate_hum_in(self): curr_x = -70 curr_y = 10 counter = 0 for inp in self.inputs: if counter%2 == 0: curr_y = 10 curr_x += 80 else: curr_y = 45 button = self.text_to_buttons[inp] button.setGeometry(curr_x, curr_y, 70, 30) button.show() counter += 1 def populate_rob_out(self): curr_x = -70 curr_y = 10 counter = 0 for out in self.outputs: if counter%2 == 0: curr_y = 10 curr_x += 80 else: curr_y = 45 button = self.text_to_buttons[out] button.setGeometry(curr_x, curr_y, 70, 30) button.show() counter += 1 def add_hum_in(self, inp): if inp == "leave": self.package_traj(prefix=True) else: self.curr_hum_in = HumanInput(inp) self.curr_traj_text += "( {} > ".format(inp) self.curr_traj_label.setText(self.curr_traj_text) for i in self.inputs: button = self.text_to_buttons[i] button.hide() self.populate_rob_out() def add_rob_out(self, out): micro = Microinteraction(out) self.curr_traj_text += "{} ) --> ".format(out) self.curr_traj_label.setText(self.curr_traj_text) for o in self.outputs: button = self.text_to_buttons[o] button.hide() tup = (self.curr_hum_in, micro) self.curr_traj.append(tup) if out == "END": self.package_traj() self.populate_hum_in() def package_traj(self, prefix=False): self.curr_traj_text = "" self.curr_traj_label.setText(self.curr_traj_text) new_traj = Trajectory(self.curr_traj,0.0,prefix,False) self.trajs.append(new_traj) self.traj_label_text += (str(new_traj) + "\n") self.trajs_label.setText(self.traj_label_text) self.curr_traj = [] sb = QSpinBox() sb.setMinimum(-1.0) sb.setMaximum(1.0) self.traj2spin[new_traj] = sb self.grid_layout.addWidget(sb,self.num_rows,0) self.grid_layout.addWidget(QLabel(str(new_traj)),self.num_rows,1) self.num_rows += 1 self.groupbox.setGeometry(10, 10, 780, 40 + 30*self.num_rows) def session(self): trajs = [] while True: command = input("what do you want to do? (build/exit)") if command == "exit": break elif command == "build": pass else: continue trajectory = self.build_trajectory() trajs.append(trajectory) return trajs def build_trajectory(self): starter_input = HumanInput("Ready") starter_micro = Microinteraction("Greeting") vect = [(starter_input, starter_micro)] is_prefix = False is_correctness = False score = 0 while True: hum_inp = input("human input? (exit to create prefix)") if hum_inp == "exit": score = float(input("score? (-1.0, 0.0, 1.0)")) is_prefix = True break rob_out = input("robot output? (END to end)") if rob_out == "END": score = float(input("score? (-1.0, 0.0, 1.0)")) break return Trajectory(vect,score,is_prefix,is_correctness) def on_okay(self): self.rval = self.trajs for traj in self.trajs: traj.reward = self.traj2spin[traj].value() self.close() def on_cancel(self): self.close()
class SessionManagerDialog(QDialog): def __init__(self, mainwindow): super(SessionManagerDialog, self).__init__(mainwindow) self.setWindowModality(Qt.WindowModal) layout = QVBoxLayout() self.setLayout(layout) self.sessions = SessionList(self) layout.addWidget(self.sessions) self.imp = QPushButton(self) self.exp = QPushButton(self) self.act = QPushButton(self) self.imp.clicked.connect(self.importSession) self.exp.clicked.connect(self.exportSession) self.act.clicked.connect(self.activateSession) self.sessions.layout().addWidget(self.imp, 5, 1) self.sessions.layout().addWidget(self.exp, 6, 1) self.sessions.layout().addWidget(self.act, 7, 1) layout.addWidget(widgets.Separator()) self.buttons = b = QDialogButtonBox(self) layout.addWidget(b) b.setStandardButtons(QDialogButtonBox.Close) b.rejected.connect(self.accept) userguide.addButton(b, "sessions") self.sessions.load() app.translateUI(self) self.sessions.changed.connect(self.enableButtons) self.sessions.listBox.itemSelectionChanged.connect(self.enableButtons) self.enableButtons() def translateUI(self): self.setWindowTitle(app.caption(_("Manage Sessions"))) self.imp.setText(_("&Import...")) self.imp.setToolTip(_("Opens a dialog to import a session from a file.")) self.exp.setText(_("E&xport...")) self.exp.setToolTip(_("Opens a dialog to export a session to a file.")) self.act.setText(_("&Activate")) self.act.setToolTip(_("Switches to the selected session.")) def enableButtons(self): """Called when the selection in the listedit changes.""" enabled = bool(self.sessions.listBox.currentItem()) self.act.setEnabled(enabled) self.exp.setEnabled(enabled) def importSession(self): """Called when the user clicks Import.""" filetypes = '{0} (*.json);;{1} (*)'.format(_("JSON Files"), _("All Files")) caption = app.caption(_("dialog title", "Import session")) mainwindow = self.parent() directory = os.path.dirname(mainwindow.currentDocument().url().toLocalFile()) or app.basedir() importfile = QFileDialog.getOpenFileName(mainwindow, caption, directory, filetypes)[0] if not importfile: return # cancelled by user try: with open(importfile, 'r') as f: self.sessions.importItem(json.load(f)) except IOError as e: msg = _("{message}\n\n{strerror} ({errno})").format( message = _("Could not read from: {url}").format(url=importfile), strerror = e.strerror, errno = e.errno) QMessageBox.critical(self, app.caption(_("Error")), msg) def exportSession(self): """Called when the user clicks Export.""" itemname, jsondict = self.sessions.exportItem() caption = app.caption(_("dialog title", "Export session")) filetypes = '{0} (*.json);;{1} (*)'.format(_("JSON Files"), _("All Files")) mainwindow = self.parent() directory = os.path.dirname(mainwindow.currentDocument().url().toLocalFile()) or app.basedir() filename = os.path.join(directory, itemname + ".json") filename = QFileDialog.getSaveFileName(mainwindow, caption, filename, filetypes)[0] if not filename: return False # cancelled try: with open(filename, 'w') as f: json.dump(jsondict, f, indent=4) except IOError as e: msg = _("{message}\n\n{strerror} ({errno})").format( message = _("Could not write to: {url}").format(url=filename), strerror = e.strerror, errno = e.errno) QMessageBox.critical(self, app.caption(_("Error")), msg) def activateSession(self): """Called when the user clicks Activate.""" item = self.sessions.listBox.currentItem() if item: name = item.text() mainwindow = self.parent() man = sessions.manager.get(mainwindow) man.saveCurrentSessionIfDesired() self.accept() man.startSession(name)