def _init_widgets(self): # current function function_label = QLabel() self._function_label = function_label # options button option_btn = QPushButton() option_btn.setText('Options') option_btn.setMenu(self._options_menu.qmenu()) # Save image button saveimage_btn = QPushButton() saveimage_btn.setText('Save image to...') saveimage_btn.clicked.connect(self._on_saveimage_btn_clicked) layout = QHBoxLayout() layout.setContentsMargins(2, 2, 2, 2) layout.addWidget(function_label) layout.addStretch(0) layout.addWidget(saveimage_btn) layout.addWidget(option_btn) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout)
def __init__(self, parent=None): global client super(CharacterSelect, self).__init__(parent) self.setWindowTitle("Select A Character") # Character Portrait # Character Sprite # Name # Current zone # Money self.charbuttons = {} for char in client.characters: button = QPushButton() button.setText(char) button.setIcon(QIcon.fromTheme('applications-games')) func = functools.partial(self.select_character, char=char) button.clicked.connect(func) self.charbuttons[char] = button layout = QVBoxLayout() for w in self.charbuttons.values(): layout.addWidget(w) self.setLayout(layout) self.character_chosen.connect(qtclient.choose_char)
def _init_widgets(self): # label label = QLabel() label.setText('%#x' % self.path.addr) # the select button path_button = QPushButton() path_button.setText('Select') path_button.released.connect(self._on_path_button_released) # the disasm button disasm_button = QPushButton() disasm_button.setText('Disasm') disasm_button.released.connect(self._on_disasm_button_released) sublayout = QHBoxLayout() sublayout.addWidget(path_button) sublayout.addWidget(disasm_button) layout = QVBoxLayout() layout.addWidget(label) layout.addLayout(sublayout) self.setLayout(layout)
class PingerView(QWidget): def __init__(self, parent=None): super(PingerView, self).__init__(parent) self.state = 0 layout = QVBoxLayout() self.btn_start_stop = QPushButton("Start Pinging") self.lbl_output = QLabel() self.btn_start_stop.clicked.connect(self.controlThread) layout.addWidget(self.btn_start_stop) layout.addWidget(self.lbl_output) self.setLayout(layout) def createPingerThread(self): req_data = RequestData(100, 1000, 1000, 3) self.receive_pipe, send_pipe = Pipe(duplex=False) self.pinger_process = Pinger(["www.google.com"], req_data, send_pipe) def controlThread(self): if self.state == 0: self.createPingerThread() self.state = 1 self.btn_start_stop.setText("Stop Pinging") self.pinger_process.start() data = self.receive_pipe.recv() self.lbl_output.setText(str(data)) self.pinger_process.terminate() self.pinger_process.wait() self.state = 0 self.btn_start_stop.setText("Start Pinging")
def create_button(self, parent, label=""): """ Returns an adapted button. """ control = QPushButton(check_parent(parent)) control.setText(label) control.setAutoDefault(False) return control_adapter_for(control)
def doneCreating(): name = nameToCreate.text() created = QPushButton() created.setText("{0} @ {1}".format(name, hex(id(created)))) createdLayout.addWidget(created) doneButton.hide() nameToCreate.hide() createButton.show()
def _init_pathgroups_tab(self, tab): # pathgroups list pathgroups_label = QLabel(self) pathgroups_label.setText('PathGroup') pathgroups_list = QComboBox(self) self._pathgroups_list = pathgroups_list pg_layout = QHBoxLayout() pg_layout.addWidget(pathgroups_label) pg_layout.addWidget(pathgroups_list) # path group information viewer = QPathGroupViewer(None) self._pathgroup_viewer = viewer # # Buttons # # step button step_button = QPushButton() step_button.setText('Step Path Group') step_button.released.connect(self._on_step_clicked) # step until branch step_until_branch_button = QPushButton('Step Path Group until branch') step_until_branch_button.released.connect( self._on_step_until_branch_clicked) # explore button explore_button = QPushButton('Explore') explore_button.released.connect(self._on_explore_clicked) # buttons layout buttons_layout = QVBoxLayout() layout = QHBoxLayout() layout.addWidget(explore_button) buttons_layout.addLayout(layout) layout = QHBoxLayout() layout.addWidget(step_button) layout.addWidget(step_until_branch_button) buttons_layout.addLayout(layout) pathgroups_layout = QVBoxLayout() pathgroups_layout.addLayout(pg_layout) pathgroups_layout.addWidget(viewer) pathgroups_layout.addLayout(buttons_layout) frame = QFrame() frame.setLayout(pathgroups_layout) tab.addTab(frame, 'General')
def __init__(self): super(MainWindow, self).__init__() btn = QPushButton(self) QObject.connect(btn, SIGNAL('clicked()'), self.startRunToAnthill) btn.setText('Start') self.setGeometry(200, 200, 500, 300) self.setWindowTitle('Mr Ant') self.show()
def __init__(self, parent, clients): super(ClientStartDialog, self).__init__(parent) grid_layout = QGridLayout(self) xpos = 0 ypos = 0 for client in clients: if client.status == ClientStati.NOT_RUNNING: start_button = QPushButton(self) start_button.setText(client.hostname.decode("utf-8")) start_button.clicked.connect(self.start_button_clicked) grid_layout.addWidget(start_button, ypos, xpos, 1, 1) xpos += 1 self.clients = clients
class ToggleWidget(QWidget): toggled = Signal() service_changed = Signal() def __init__(self, *args, **kwargs): super(ToggleWidget, self).__init__(*args, **kwargs) self.line_edit = QLineEdit(self) self.button = QPushButton("Toggle", self) self.label = QLabel() self.layout = QVBoxLayout() self.layout.addWidget(self.line_edit) self.layout.addStretch() self.layout.addWidget(self.button) self.layout.addWidget(self.label) self.layout.addStretch() self.button.clicked.connect(self.on_click) self.line_edit.editingFinished.connect(self.on_edit) self.setLayout(self.layout) self.s = False def set_label(self, k): self.button.setText(k) def update_me(self): self.label.setText( "Current state: {}".format("ON" if self.s else "OFF")) def service(self): return str(self.line_edit.text()) def set_service(self, s): self.line_edit.setText(s) def set_state(self, s): self.s = s self.update_me() @Slot() def on_edit(self): self.service_changed.emit() @Slot() def on_click(self): self.s = not self.s self.update_me() self.toggled.emit()
class DBusWidget(dbus.service.Object): def __init__(self, name, session): # export this object to dbus dbus.service.Object.__init__(self, name, session) # create a simple widget self.widget = QPushButton() self.widget.resize(200, 50) # To export a Qt signal as a DBus-signal, you need to connect it to a method in this class. # The method MUST have the signal annotation, so python-dbus will export it as a dbus-signal QObject.connect(self.widget, SIGNAL("clicked()"), self.clicked) QObject.connect(QApplication.instance(), SIGNAL("lastWindowClosed()"), self.lastWindowClosed) # You can export methods to dbus like you do in python-dbus. @dbus.service.method("com.example.SampleWidget", in_signature='', out_signature='') def show(self): self.widget.show() # Another method... now with a parameter @dbus.service.method("com.example.SampleWidget", in_signature='s', out_signature='') def setText(self, value): self.widget.setText(value) # Another one... @dbus.service.method("com.example.SampleWidget", in_signature='', out_signature='') def exit(self): qApp().quit() # A signal that will be exported to dbus @dbus.service.signal("com.example.SampleWidget", signature='') def clicked(self): pass # Another signal that will be exported to dbus @dbus.service.signal("com.example.SampleWidget", signature='') def lastWindowClosed(self): pass
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) #self.setWindowIcon(self.style().standardIcon(QStyle.SP_DirIcon)) #QtGui.QIcon(QtGui.QMessageBox.Critical)) self.txt = QLabel() self.txt.setText("This will remove ALL Suffix from selection objects. .\nDo you want to continue?\n\n\'suffix\'") self.le = QLineEdit() self.le.setObjectName("suffix_filter") self.le.setText(".step") self.pb = QPushButton() self.pb.setObjectName("OK") self.pb.setText("OK") self.pbC = QPushButton() self.pbC.setObjectName("Cancel") self.pbC.setText("Cancel") layout = QFormLayout() layout.addWidget(self.txt) layout.addWidget(self.le) layout.addWidget(self.pb) layout.addWidget(self.pbC) self.setLayout(layout) self.connect(self.pb, SIGNAL("clicked()"),self.OK_click) self.connect(self.pbC, SIGNAL("clicked()"),self.Cancel_click) self.setWindowTitle("Warning ...") def OK_click(self): # shost is a QString object filtered = self.le.text() print (filtered) self.close() def Cancel_click(self): # shost is a QString object filtered = '.stp' print (filtered) self.close()
def _init_widgets(self): # current function function_label = QLabel() self._function_label = function_label # options button option_btn = QPushButton() option_btn.setText('Options') option_btn.setMenu(self._options_menu.qmenu()) layout = QHBoxLayout() layout.setContentsMargins(2, 2, 2, 2) layout.addWidget(function_label) layout.addStretch(0) layout.addWidget(option_btn) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout)
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.orientations = itertools.cycle([maliit.Angle0, maliit.Angle90, maliit.Angle180, maliit.Angle270]) currentOrientation = maliit.InputMethod.instance().orientationAngle() while self.orientations.next() != currentOrientation: pass self.rotateKeyboardButton = QPushButton() self.textEdit = QTextEdit() self.rotateKeyboardButton.clicked.connect(self.onRotateKeyboardClicked) self.setWindowTitle("Maliit test application") vbox = QVBoxLayout() self.rotateKeyboardButton.setText("Rotate keyboard") vbox.addWidget(self.rotateKeyboardButton) # Steals the focus when clicked hideVkb = QPushButton("Hide virtual keyboard") vbox.addWidget(hideVkb) vbox.addWidget(self.textEdit) self.rotateKeyboardButton.setFocusProxy(self.textEdit) closeApp = QPushButton("Close application") vbox.addWidget(closeApp) closeApp.clicked.connect(self.close) self.setCentralWidget(QWidget()) self.centralWidget().setLayout(vbox) def onRotateKeyboardClicked(self): maliit.InputMethod.instance().setOrientationAngle(self.orientations.next())
class FolderSelector(QWidget): def __init__(self, var_name, default_folder, project_root_dir = "", help_instance=None, handler=None): QWidget.__init__(self) self.project_root_dir = project_root_dir self.my_layout = QHBoxLayout() self.setLayout(self.my_layout) self.var_name = var_name self.current_value = default_folder self.full_path = project_root_dir + default_folder self.project_root_dir = project_root_dir self.handler=handler self.my_but = QPushButton(os.path.basename(remove_trailing_slash(default_folder))) self.my_but.setFont(regular_small_font) self.my_but.setStyleSheet("text-align: left") self.my_but.clicked.connect(self.set_folder) self.my_layout.addWidget(self.my_but) my_label = QLabel(var_name) my_label.setFont(regular_small_font) self.my_layout.addWidget(my_label) def set_folder(self): directions = "Select a folder for " + self.var_name new_value = QFileDialog.getExistingDirectory(self, directions, dir=os.path.dirname(self.full_path), options=QFileDialog.ShowDirsOnly) new_value = re.sub(self.project_root_dir, "", new_value) self.set_myvalue(new_value) if self.handler is not None: self.handler() def get_myvalue(self): return self.current_value def set_myvalue(self, new_value): if new_value != "": self.current_value = new_value self.full_path = add_slash(self.project_root_dir + new_value) self.my_but.setText(os.path.basename(remove_trailing_slash(self.current_value))) value = property(get_myvalue, set_myvalue)
def _init_widgets(self): # name label name_label = QLabel(self) name_label.setText('New name') name_box = LabelNameBox(self._on_name_changed, self) if self._label_addr in self._disasm_view.disasm.kb.labels: name_box.setText(self._disasm_view.disasm.kb.labels[self._label_addr]) name_box.selectAll() self._name_box = name_box label_layout = QHBoxLayout() label_layout.addWidget(name_label) label_layout.addWidget(name_box) self.main_layout.addLayout(label_layout) # status label status_label = QLabel(self) self.main_layout.addWidget(status_label) self._status_label = status_label # buttons ok_button = QPushButton(self) ok_button.setText('OK') ok_button.setEnabled(False) ok_button.clicked.connect(self._on_ok_clicked) self._ok_button = ok_button cancel_button = QPushButton(self) cancel_button.setText('Cancel') cancel_button.clicked.connect(self._on_cancel_clicked) buttons_layout = QHBoxLayout() buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) self.main_layout.addLayout(buttons_layout)
def _init_widgets(self): # address label address_label = QLabel(self) address_label.setText('Address') address = QAddressInput(self._on_address_changed, parent=self) self._address_box = address address_layout = QHBoxLayout() address_layout.addWidget(address_label) address_layout.addWidget(address) self.main_layout.addLayout(address_layout) # status label status_label = QLabel(self) self.main_layout.addWidget(status_label) self._status_label = status_label # buttons ok_button = QPushButton(self) ok_button.setText('OK') ok_button.setEnabled(False) ok_button.clicked.connect(self._on_ok_clicked) self._ok_button = ok_button cancel_button = QPushButton(self) cancel_button.setText('Cancel') cancel_button.clicked.connect(self._on_cancel_clicked) buttons_layout = QHBoxLayout() buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) self.main_layout.addLayout(buttons_layout)
class FileSelector(QWidget): def __init__(self, var_name, default_file, project_root_dir = None, help_instance=None): QWidget.__init__(self) self.project_root_dir = project_root_dir self.my_layout = QHBoxLayout() self.setLayout(self.my_layout) self.var_name = var_name self.current_value = default_file self.full_path = project_root_dir + default_file self.my_layout.setContentsMargins(1, 1, 1, 1) self.my_layout.setSpacing(3) self.my_but = QPushButton(os.path.basename(remove_trailing_slash(default_file))) self.my_but.setFont(regular_small_font) self.my_but.setStyleSheet("text-align: left") self.my_but.clicked.connect(self.set_file) self.my_layout.addWidget(self.my_but) my_label = QLabel(var_name) my_label.setFont(regular_small_font) self.my_layout.addWidget(my_label) def set_file(self): directions = "Select a file for " + self.var_name new_value = QFileDialog.getOpenFileName(self, directions, dir=os.path.dirname(self.full_path))[0] new_value = re.sub(self.project_root_dir, "", new_value) self.set_myvalue(new_value) def get_myvalue(self): return self.current_value def set_myvalue(self, new_value): if new_value != "": self.current_value = new_value self.my_but.setText(os.path.basename(remove_trailing_slash(self.current_value))) value = property(get_myvalue, set_myvalue)
def _init_widgets(self): # filename filename_caption = QLabel(self) filename_caption.setText('File name:') filename = QLabel(self) filename.setText(self.filename) filename_layout = QHBoxLayout() filename_layout.addWidget(filename_caption) filename_layout.addWidget(filename) self.main_layout.addLayout(filename_layout) # central tab tab = QTabWidget() self._init_central_tab(tab) self.main_layout.addWidget(tab) # buttons ok_button = QPushButton(self) ok_button.setText('OK') ok_button.clicked.connect(self._on_ok_clicked) cancel_button = QPushButton(self) cancel_button.setText('Cancel') cancel_button.clicked.connect(self._on_cancel_clicked) buttons_layout = QHBoxLayout() buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) self.main_layout.addLayout(buttons_layout)
def __init__(self, process_manager): super(MainWindow, self).__init__(None) self.resize(731, 475) central_widget = QWidget(self) grid_layout = QGridLayout(central_widget) self.clients_label = QLabel(self) self.clients_label.setText("Connected clients: ") grid_layout.addWidget(self.clients_label, 0, 0, 1, 1) start_clients_button = QPushButton(self) start_clients_button.setText("Start Clients") start_clients_button.clicked.connect(self.start_clients_clicked) grid_layout.addWidget(start_clients_button, 0, 1, 1, 1) self.my_widgets = {} for id, process in enumerate(process_manager.get_process_descriptions()): xpos = 0 ypos = id+1 name_label = QLabel(self) name_label.setText(process.id) grid_layout.addWidget(name_label, ypos, xpos, 1, 1) xpos += 1 host_label = QLabel(self) host_label.setText(process.target_host) grid_layout.addWidget(host_label, ypos, xpos, 1, 1) xpos += 1 status_label = QLabel(self) status_label.setText(ProcessStati.INIT.name) grid_layout.addWidget(status_label, ypos, xpos, 1, 1) xpos += 1 start_button = QPushButton(self) start_button.setText("Start "+process.id) start_button.clicked.connect(self.button_clicked) grid_layout.addWidget(start_button, ypos, xpos, 1, 1) xpos += 1 log_button = QPushButton(self) log_button.setText("Update-log "+process.id) log_button.clicked.connect(self.log_button_clicked) grid_layout.addWidget(log_button, ypos, xpos, 1, 1) xpos += 1 self.my_widgets[process.id] = [name_label, status_label, start_button, log_button] self.setCentralWidget(central_widget) self.clients = process_manager.get_client_stati() self.start_clients_dialog = ClientStartDialog(self, self.clients) self.process_manager = process_manager self.status_dialogs = {} timer = QTimer(self) self.connect(timer, SIGNAL("timeout()"), self.update_stati) timer.start(1000)
class managebkm(QDialog): def __init__(self, parent=None): super(managebkm, self).__init__(parent) appicom = QIcon(":/icons/njnlogo.png") self.setWindowIcon(appicom) self.setWindowTitle("Nigandu | Manage Book Marks") self.setFixedSize(463, 242) self.verticalLayoutWidget = QWidget(self) self.verticalLayoutWidget.setGeometry(QRect(350, 30, 101, 201)) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.sortbtn = QPushButton(self.verticalLayoutWidget) self.sortbtn.setText("&Sort") self.verticalLayout.addWidget(self.sortbtn) self.deletebtn = QPushButton(self.verticalLayoutWidget) self.deletebtn.setText("&Delete") self.verticalLayout.addWidget(self.deletebtn) self.deleteallbtn = QPushButton(self.verticalLayoutWidget) self.deleteallbtn.setText("Delete &All") self.verticalLayout.addWidget(self.deleteallbtn) self.closebtn = QPushButton(self.verticalLayoutWidget) self.closebtn.setText("&Close") self.verticalLayout.addWidget(self.closebtn) self.listWidget = QListWidget(self) self.listWidget.setGeometry(QRect(10, 30, 331, 201)) self.label = QLabel(self) self.label.setGeometry(QRect(20, 10, 91, 25)) font = QFont() font.setPointSize(10) self.label.setFont(font) self.label.setBuddy(self.listWidget) self.label.setText("Book Mark List:")
class UiMain(QMainWindow): """ The main gui interface, invokes all windows and ties everything together """ def __init__(self): """ automatically called __init__ function """ super(UiMain, self).__init__() # initialize all the variables that are going to be defined in the # future self.update_dialog = None self.update_dialog_lbl = None self.app_select_box = None self.selector_lbl = None self.current_playing_lbl = None self.current_playing = None self.misc_messages = None self.start_btn = None self.output_dir_lbl = None self.select_output_dir_btn = None self.output_cur_dir_lbl = None self.active_items_list = None self.inactive_items_list = None self.switch_active_item_button_off = None self.switch_active_item_button_on = None self.switch_output_split_btn = None self.switch_output_split_lbl = None # initialize the system tray # self.system_tray = QSystemTrayIcon(self) # self.system_tray.setIcon(QIcon(resource_path('icon.png'))) # self.system_tray.show() # self.system_tray.setToolTip('SMG') # self.system_tray.activated.connect(self.on_systray_activated) # initialize the main window self.setObjectName('self') self.setWindowTitle('SMG - By Azeirah') self.resize(400, 250) # Gives the self an icon self.setWindowIcon(QIcon(resource_path('icon.png'))) # create the tabs # the tab widget itself self.tabbed_windows = QTabWidget(self) self.tabbed_windows.resize(400, 300) # tab 1, contains the music player selection self.music_players = QFrame() # tab 2, contains options self.options = QFrame() self.tabbed_windows.addTab(self.music_players, 'Music players') self.tabbed_windows.addTab(self.options, 'Options') # initializes the two tabs, with all the code down below self.tab_music_players() self.tab_options() # shows the main window self.show() # self.update() CheckUpdateThread = Thread(target=self.update) CheckUpdateThread.setName('CheckUpdateThread') CheckUpdateThread.run() def closeEvent(self, event): """ an automatically called function when the program is about to close. """ # Stops all Threads. These would continue to run in the background # Even if the window was closed. Main.running = False # close the ZuneNowPlaying.exe process if Constants.SUBP: Constants.SUBP.kill() def changeEvent(self, event): # if event.type() == QEvent.WindowStateChange: # if self.isMinimized(): # event.ignore() # self.hide() # self.system_tray.showMessage('Running', 'Running in the # background.') # return super(UiMain, self).changeEvent(event) def on_systray_activated(self, reason): if reason == QSystemTrayIcon.DoubleClick: self.show() @staticmethod def toggle_split(event): # 0 = Qt.Unchecked The item is unchecked. # 1 = Qt.PartiallyChecked The item is partially checked. Items in # hierarchical models may be partially checked if some, but not all, # of # their children are checked. # 2 = Qt.Checked The item is checked. if event == 0: Constants.OPTIONS['splitText'] = False elif event == 2: Constants.OPTIONS['splitText'] = True def update(self): """ Checks a webpage for current version, compares this to built-in current versions, and shows update dialog if necessary """ try: ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\ .read() except IOError: # if for some reason it couldn't retrieve the version, set it to # automatically ignore the update: False ver = False if not float(VERSION) >= float(ver): self.popup = QDialog(self) self.popup.setModal(True) self.popup.setGeometry(200, 100, 500, 100) self.popup.show() self.popup_text = QLabel(self.popup) self.popup_text.setGeometry(5, 5, 500, 30) self.popup_text.setOpenExternalLinks(True) self.popup_text.show() self.popup_text.setText( """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>""" ) # reply = QMessageBox.question(Constants.UI, 'Message', # "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) # if reply == QMessageBox.Yes: # import atexit # import subprocess # def runUpdater(): # import time # time.sleep(3) # subprocess.Popen(resource_path('update.exe')) # atexit.register(runUpdater) # sys.exit() # Constants.update_dialog = QWidget() # Constants.update_dialog.resize(350, 100) # Constants.update_dialog.setWindowIcon(QIcon(resource_path\ # ('icon.png'))) # Constants.update_dialog.setWindowTitle('Updater') # Constants.update_dialog_lbl = QLabel(Constants.update_dialog) # Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12) # Constants.update_dialog.show() # updateThread = Thread(target = update.update) # updateThread.setName('updateThread') # updateThread.start() def tab_music_players(self): """ Everything inside the Music players tab gets created here.""" # self.music_players # Creates the box with all the music players inside of it self.app_select_box = QComboBox(self.music_players) self.app_select_box.setGeometry(135, 10, 150, 25) # Whenever you change the application, it runs the selectnewapp func self.app_select_box.activated[str].connect(self.select_new_app) # Creates the label for the selection combobox self.selector_lbl = QLabel(self.music_players) self.selector_lbl.setGeometry(10, 10, 150, 25) self.selector_lbl.setText('Select your music player: ') # Creates the label for the current playing song (and the current # playing song label) self.current_playing_lbl = QLabel(self.music_players) self.current_playing_lbl.setGeometry(10, 45, 150, 25) self.current_playing_lbl.setText('Current playing song: ') self.current_playing = QLabel(self.music_players) self.current_playing.setGeometry(117, 45, 250, 25) self.current_playing.setText(Misc.noSongPlaying) # Creates a label which displays any additional messages self.misc_messages = QLabel(self.music_players) self.misc_messages.setGeometry(10, 80, 390, 24) self.misc_messages.setText(Misc.misc_message()) self.misc_messages.setOpenExternalLinks(True) # adds all the music players into the combobox self.app_select_box.addItem(None) for item in Constants.ACTIVEITEMS: if item == '__name__' or item == 'active': continue self.app_select_box.addItem(item) # creates the start button self.start_btn = QPushButton(self.music_players) self.start_btn.setGeometry(75, 120, 250, 35) self.start_btn.setText('Start') # links the start button to the self.start function QObject.connect( self.start_btn, SIGNAL("clicked()"), lambda: Thread(target=self.start, name='startbutton').start()) def tab_options(self): """ Everything inside the Options tab gets created here. """ # self.options # This section is for selecting output dir # Creates the output dir label self.output_dir_lbl = QLabel(self.options) self.output_dir_lbl.setGeometry(10, 10, 125, 15) self.output_dir_lbl.setText('Change Output Directory: ') # Creates the output dir button self.select_output_dir_btn = QPushButton(self.options) self.select_output_dir_btn.setGeometry(137, 8, 30, 20) self.select_output_dir_btn.setText('...') # Creates the output dir currentdir Lineedit self.output_cur_dir_lbl = QLineEdit(self.options) self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25) self.output_cur_dir_lbl.setReadOnly(True) self.output_cur_dir_lbl.setText( Constants.CONFIG.get('directories', 'current_song')) # when the '...' button is clicked, show a dialog (fire func # disp_dialog) QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"), self.disp_dialog) # This section is for selecting what players you use # The box with all the active players self.active_items_list = QListWidget(self.options) self.active_items_list.setGeometry(10, 40, 150, 100) # The box with all the inactive players self.inactive_items_list = QListWidget(self.options) self.inactive_items_list.setGeometry(230, 40, 150, 100) # Populate the two boxes with active and inactive items for item in Constants.ACTIVEITEMS: if item == '__name__' or item == 'active': continue self.active_items_list.addItem(item) for item in Constants.INACTIVEITEMS: if item == '__name__' or item == 'active': continue self.inactive_items_list.addItem(item) # The buttons responsible for switching # off button self.switch_active_item_button_off = QPushButton(self.options) self.switch_active_item_button_off.setText('->'.decode('utf-8')) # Makes the -> readable and clear self.switch_active_item_button_off.setFont(QFont('SansSerif', 17)) self.switch_active_item_button_off.setGeometry(175, 55, 40, 30) # on button self.switch_active_item_button_on = QPushButton(self.options) self.switch_active_item_button_on.setText('<-'.decode('utf-8')) # makes <- readable and clear self.switch_active_item_button_on.setFont(QFont('SansSerif', 17)) self.switch_active_item_button_on.setGeometry(175, 90, 40, 30) QObject.connect(self.switch_active_item_button_on, SIGNAL("clicked()"), self.switch_item_on) QObject.connect(self.switch_active_item_button_off, SIGNAL("clicked()"), self.switch_item_off) # A button to toggle the split output in half option. It's a temporary # fix for the Foobar double output problem. self.switch_output_split_btn = QCheckBox(self.options) self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked) self.switch_output_split_btn.setGeometry(10, 140, 40, 30) self.switch_output_split_btn.stateChanged.connect(self.toggle_split) # The label for the split toggle self.switch_output_split_lbl = QLabel(self.options) self.switch_output_split_lbl.setText( "Split the output text in half (don't use this if you don't need it)" ) self.switch_output_split_lbl.setGeometry(30, 140, 300, 30) def switch_item_on(self): """ Switches items (musicapps) on """ try: # If an item from the active box is selected # Remove it and place it inside the inactive box item_taken = self.inactive_items_list.takeItem( self.inactive_items_list.currentRow()) self.active_items_list.addItem(item_taken) active_items = {} inactive_items = {} for i in range(self.active_items_list.count()): active_items[self.active_items_list.item(i).text()] =\ ITEMS[self.active_items_list.item(i).text() .encode('utf-8')] for i in range(self.inactive_items_list.count()): inactive_items[self.inactive_items_list.item(i).text()] =\ ITEMS[self.inactive_items_list.item(i).text() .encode('utf-8')] Constants.ACTIVE_ITEMS = active_items Constants.INACTIVE_ITEMS = inactive_items # clear the selection combobox self.app_select_box.clear() # Repopulate the combobox self.app_select_box.addItem(None) for item in active_items: self.app_select_box.addItem(item) Constants.CONFIG.set('active', item_taken.text(), ITEMS[item_taken.text()]) Constants.CONFIG.remove_option('inactive', item_taken.text()) # Updates the config file to be up to date with activeItems Constants.CONFIG.update() except: raise def switch_item_off(self): """ Switches items (musicapps) off """ try: # If an item from the inactive box is selected. # Remove it and place it inside the active box item_taken = self.active_items_list.takeItem( self.active_items_list.currentRow()) self.inactive_items_list.addItem(item_taken) # update activeItems active_items = {} inactive_items = {} for i in range(self.active_items_list.count()): active_items[self.active_items_list.item(i).text()] =\ ITEMS[self.active_items_list.item(i).text() .encode('utf-8')] for i in range(self.inactive_items_list.count()): inactive_items[self.inactive_items_list.item(i).text()] =\ ITEMS[self.inactive_items_list.item(i).text() .encode('utf-8')] Constants.ACTIVE_ITEMS = active_items Constants.INACTIVE_ITEMS = inactive_items # clear the selection combobox self.app_select_box.clear() # Repopulate the combobox self.app_select_box.addItem(None) for item in active_items: self.app_select_box.addItem(item) # Updates the active items Constants property Constants.CONFIG.set('inactive', item_taken.text(), ITEMS[item_taken.text()]) Constants.CONFIG.remove_option('active', item_taken.text()) # Updates the config file to be up to date with activeItems Constants.CONFIG.update() except: raise def disp_dialog(self): """ displays the dialog which select a directory for output. """ fname = QFileDialog.getExistingDirectory() Constants.CONFIG.set('directories', 'current_song', fname) self.output_cur_dir_lbl.setText( Constants.CONFIG.get('directories', 'current_song')) def select_new_app(self, text): """ Sets the new application to check for """ try: Main.selectedProgram = ITEMS[text] except KeyError: # catches the empty option, it's obviously not in the dict pass # custom message for zune if Main.selectedProgram == 'zune': self.misc_messages.setText(Misc.ZuneNotification) # custom message for webplayers which require the groovemarklet elif text.find('*'): self.misc_messages.setText(Misc.GetGroovemarklet) def start(self): """ When the start button is pressed, start the main program loop """ if Main.selectedProgram: if not Main.running: self.start_btn.setText('Stop') Main.running = True try: pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) except pythoncom.com_error: # already initialized. pass thread = Thread(target=Main.enumWindows, name='enumWindows') thread.run() else: self.start_btn.setText('Start') Main.running = False self.set_playing(Misc.noSongPlaying) Wr.write('') def set_playing(self, title=''): """ Sets the text of the label of what song is playing """ # print 'setting title: ', title self.current_playing.setText(title)
class window(QMainWindow): """Main window.""" def __init__(self, parent=None): """Initialize the parent class of this instance.""" super(window, self).__init__(parent) app.aboutToQuit.connect(self.myExitHandler) self.style_sheet = self.styleSheet('style') # app.setStyle(QStyleFactory.create('Macintosh')) #app.setStyleSheet(self.style_sheet) self.layout().setSpacing(0) self.layout().setContentsMargins(0,0,0,0) app.setOrganizationName("Eivind Arvesen") app.setOrganizationDomain("https://github.com/eivind88/raskolnikov") app.setApplicationName("Raskolnikov") app.setApplicationVersion("0.0.1") settings = QSettings() self.data_location = QDesktopServices.DataLocation self.temp_location = QDesktopServices.TempLocation self.cache_location = QDesktopServices.CacheLocation self.startpage = "https://duckduckgo.com/" self.new_tab_behavior = "insert" global bookmarks global saved_tabs print "Currently saved_tabs:\n", saved_tabs global menubar menubar = QMenuBar() # Initialize a statusbar for the window self.statusbar = self.statusBar() self.statusbar.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) self.statusbar.setStyleSheet(self.style_sheet) self.statusbar.setMinimumHeight(15) self.pbar = QProgressBar() self.pbar.setMaximumWidth(100) self.statusbar.addPermanentWidget(self.pbar) self.statusbar.hide() self.setMinimumSize(504, 235) # self.setWindowModified(True) # app.alert(self, 0) self.setWindowTitle("Raskolnikov") # toolbar = self.addToolBar('Toolbar') # toolbar.addAction(exitAction) # self.setUnifiedTitleAndToolBarOnMac(True) self.setWindowIcon(QIcon("")) # Create input widgets self.bbutton = QPushButton(u"<") self.fbutton = QPushButton(u">") self.hbutton = QPushButton(u"⌂") self.edit = QLineEdit("") self.edit.setFont(QFont("Helvetica Neue", 12, QFont.Normal)) self.edit.setPlaceholderText("Enter URL") # self.edit.setMinimumSize(400, 24) self.rbutton = QPushButton(u"↻") self.dbutton = QPushButton(u"☆") self.tbutton = QPushButton(u"⁐") # ↆ ⇧ √ ⌘ ⏎ ⏏ ⚠ ✓ ✕ ✖ ✗ ✘ ::: ❤ ☮ ☢ ☠ ✔ ☑ ♥ ✉ ☣ ☤ ✘ ☒ ♡ ツ ☼ ☁ ❅ ✎ self.nbutton = QPushButton(u"+") self.nbutton.setObjectName("NewTab") self.nbutton.setMinimumSize(35, 30) self.nbutton.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) self.edit.setTextMargins(2, 1, 2, 0) # create a horizontal layout for the input input_layout = QHBoxLayout() input_layout.setSpacing(4) input_layout.setContentsMargins(0, 0, 0, 0) # add the input widgets to the input layout input_layout.addWidget(self.bbutton) input_layout.addWidget(self.fbutton) input_layout.addWidget(self.hbutton) input_layout.addWidget(self.edit) input_layout.addWidget(self.rbutton) input_layout.addWidget(self.dbutton) input_layout.addWidget(self.tbutton) # create a widget to hold the input layout self.input_widget = QFrame() self.input_widget.setObjectName("InputWidget") self.input_widget.setStyleSheet(self.style_sheet) # set the layout of the widget self.input_widget.setLayout(input_layout) self.input_widget.setVisible(True) # CREATE BOOKMARK-LINE HERE self.bookmarks_layout = QHBoxLayout() self.bookmarks_layout.setSpacing(0) self.bookmarks_layout.setContentsMargins(0, 0, 0, 0) for i in bookmarks: link = QToolButton() link.setDefaultAction(QAction(unicode(i), link)) link.setObjectName(unicode(i)) link.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) link.clicked.connect(self.handleBookmarks) self.bookmarks_layout.addWidget(link) self.bookmarks_widget = QFrame() self.bookmarks_widget.setObjectName("BookmarkWidget") self.bookmarks_widget.setStyleSheet(self.style_sheet) self.bookmarks_widget.setLayout(self.bookmarks_layout) if not bookmarks: self.bookmarks_widget.hide() # Task list self.tasklist = QStandardItemModel() #parentItem = self.tasklist.invisibleRootItem() #self.tasklist.header().hide() self.tasklist.setHorizontalHeaderItem(0, QStandardItem('Tasks')) parentItem = QStandardItem("Parent") self.tasklist.appendRow(parentItem) for i in range(4): item = QStandardItem("Item %d" % i) parentItem.appendRow(item) #parentItem = item #self.list.activated[str].connect(self.handleBookmarks) #self.list.view().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) # create tabs self.tabs = QTabWidget() self.tabs.setDocumentMode(True) self.tabs.setTabsClosable(True) self.tabs.setMovable(True) self.tabs.tabBar().hide() self.tabs.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) self.tabs.setCornerWidget(self.nbutton) self.tabs.cornerWidget().setObjectName("CornerWidget") self.tabs.cornerWidget().setMinimumSize(10, 24) self.tabs.cornerWidget().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) if saved_tabs: for tab in saved_tabs['tabs']: tasklist = QTreeView() tasklist.hide() tasklist.setObjectName('taskList') tasklist.setMinimumWidth(100) tasklist.setMaximumWidth(250) new_tab = QWebView() new_tab.setObjectName('webView') inspector = QWebInspector(self) inspector.setObjectName('webInspector') inspector.hide() page_layout = QVBoxLayout() page_layout.setSpacing(0) page_layout.setContentsMargins(0, 0, 0, 0) page_layout.addWidget(new_tab) page_layout.addWidget(inspector) page_widget = QFrame() page_widget.setObjectName('pageWidget') page_widget.setLayout(page_layout) complete_tab_layout = QHBoxLayout() complete_tab_layout.setSpacing(0) complete_tab_layout.setContentsMargins(0, 0, 0, 0) complete_tab_layout.addWidget(tasklist) complete_tab_layout.addWidget(page_widget) complete_tab_widget = QFrame() complete_tab_widget.setLayout(complete_tab_layout) #for page in tab['history']: # new_tab.load(QUrl(page['url'])) #print tab['current_history'] #for item in new_tab.history().items(): # print item #new_tab.history().goToItem(new_tab.history().itemAt(tab['current_history'])) new_tab.load(QUrl(tab['history'][tab['current_history']]['url'])) tab['current_history'] self.tabs.setUpdatesEnabled(False) if self.new_tab_behavior == "insert": self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget, unicode(new_tab.title())) elif self.new_tab_behavior == "append": self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title())) self.tabs.setUpdatesEnabled(True) new_tab.titleChanged.connect(self.change_tab) new_tab.urlChanged.connect(self.change_tab) new_tab.loadStarted.connect(self.load_start) new_tab.loadFinished.connect(self.load_finish) new_tab.loadProgress.connect(self.pbar.setValue) new_tab.page().linkHovered.connect(self.linkHover) inspector.setPage(new_tab.page()) for index, tab in enumerate(saved_tabs['tabs']): self.tabs.setTabText(index, tab['history'][tab['current_history']]['title']) self.tabs.setCurrentIndex(saved_tabs['current_tab']) else: self.new_tab() tabs_layout = QVBoxLayout() tabs_layout.setSpacing(0) tabs_layout.setContentsMargins(0, 0, 0, 0) tabs_layout.addWidget(self.tabs) self.tabs_widget = QFrame() self.tabs_widget.setObjectName("TabLine") self.tabs_widget.setStyleSheet(self.style_sheet) self.tabs_widget.setLayout(tabs_layout) self.tabs_widget.setVisible(True) # Webkit settings gsettings = self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).settings().globalSettings() # Basic settings gsettings.setAttribute(QWebSettings.AutoLoadImages, True) gsettings.setAttribute(QWebSettings.JavascriptEnabled, True) gsettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, False) gsettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, False) gsettings.setAttribute(QWebSettings.PluginsEnabled, False) # Flash isn't stable at present gsettings.setAttribute(QWebSettings.JavaEnabled, False) # Java applet's aren't supported by PySide gsettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) # Performace settings gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) # Other settings gsettings.setAttribute(QWebSettings.PrivateBrowsingEnabled, False) # Create a vertical layout and add widgets vlayout = QVBoxLayout() vlayout.setSpacing(0) vlayout.setContentsMargins(0, 0, 0, 0) # toolbar.addWidget(self.input_widget) vlayout.addWidget(self.input_widget) vlayout.addWidget(self.bookmarks_widget) vlayout.addWidget(self.tabs_widget) # create a widget to hold the vertical layout wrapper_widget = QWidget() wrapper_widget.setLayout(vlayout) self.setCentralWidget(wrapper_widget) self.bbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).back) self.fbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).forward) self.hbutton.clicked.connect(self.goHome) self.edit.returnPressed.connect(self.set_url) # Add button signal to "go" slot self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload) self.dbutton.clicked.connect(self.bookmark) self.tbutton.clicked.connect(self.toggleTaskBar) self.nbutton.clicked.connect(self.new_tab) self.tabs.tabCloseRequested.connect(self.tabs.removeTab) self.tabs.currentChanged.connect(self.change_tab) widgets = (input_layout.itemAt(i).widget() for i in range( input_layout.count())) for widget in widgets: if isinstance(widget, QPushButton): widget.setFixedSize(33, 21) widget.setFont(QFont("Helvetica Neue", 12, QFont.Normal)) widget.pressed.connect(self.press_button) widget.released.connect(self.release_button) # make a ctrl+q quit sequence = QKeySequence(Qt.CTRL + Qt.Key_Q) QShortcut(sequence, self, SLOT("close()")) # make an accelerator to toggle fullscreen sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F) QShortcut(sequence, self, self.toggle_fullscreen) # make an accelerator to toggle input visibility sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_L) QShortcut(sequence, self, self.toggle_input) # make an accelerator to focus adress-bar sequence = QKeySequence(Qt.CTRL + Qt.Key_L) QShortcut(sequence, self, self.focus_adress) # make an accelerator to reload page sequence = QKeySequence(Qt.CTRL + Qt.Key_R) QShortcut(sequence, self, self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload) # make an accelerator to create new tab sequence = QKeySequence(Qt.CTRL + Qt.Key_T) QShortcut(sequence, self, self.new_tab) # make an accelerator to close tab sequence = QKeySequence(Qt.CTRL + Qt.Key_W) QShortcut(sequence, self, self.close_tab) # make an accelerator to navigate tabs sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Left) QShortcut(sequence, self, self.previous_tab) sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Right) QShortcut(sequence, self, self.next_tab) # make an accelerator to toggle inspector sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_U) QShortcut(sequence, self, self.handleShowInspector) # make an accelerator to toggle bookmark sequence = QKeySequence(Qt.CTRL + Qt.Key_D) QShortcut(sequence, self, self.bookmark) # make an accelerator to toggle task/project-list sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_L) QShortcut(sequence, self, self.toggleTaskBar) # finally set the attribute need to rotate # try: # self.setAttribute(Qt.WA_Maemo5AutoOrientation, True) # except: # print "not maemo" self.statusbar.show() def press_button(self): """On button press. Connected.""" self.sender().setStyleSheet('background-color: rgba(228, 228, 228)') def release_button(self): """On button release. Connected.""" self.sender().setStyleSheet('background-color: rgba(252, 252, 252)') def goHome(self): """Go to startpage.""" self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setUrl(QUrl(self.startpage)) def handleShowInspector(self): """Toggle web inspector.""" self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).setShown(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).isHidden()) def toggleTaskBar(self): """Toggle task bar.""" if self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).isHidden(): self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).setModel(self.tasklist) self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).setShown(self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).isHidden()) #self.tasklist.setShown(self.tasklist.isHidden()) def focus_adress(self): """Focus adress bar.""" self.edit.selectAll() self.edit.setFocus() def toggle_input(self): """Toggle input visibility.""" if self.input_widget.isVisible(): visible = False else: visible = True self.input_widget.setVisible(visible) def toggle_fullscreen(self): """Toggle fullscreen.""" if self.isFullScreen(): self.showNormal() else: self.showFullScreen() self.change_tab() def linkHover(self, l): """Show link adress in status bar on mouse hover.""" self.statusbar.showMessage(l) def new_tab(self): """Open new tab.""" tasklist = QTreeView() tasklist.hide() tasklist.setObjectName('taskList') tasklist.setMinimumWidth(100) tasklist.setMaximumWidth(250) new_tab = QWebView() new_tab.setObjectName('webView') inspector = QWebInspector(self) inspector.setObjectName('webInspector') inspector.hide() page_layout = QVBoxLayout() page_layout.setSpacing(0) page_layout.setContentsMargins(0, 0, 0, 0) page_layout.addWidget(new_tab) page_layout.addWidget(inspector) page_widget = QFrame() page_widget.setObjectName('pageWidget') page_widget.setLayout(page_layout) complete_tab_layout = QHBoxLayout() complete_tab_layout.setSpacing(0) complete_tab_layout.setContentsMargins(0, 0, 0, 0) complete_tab_layout.addWidget(tasklist) complete_tab_layout.addWidget(page_widget) complete_tab_widget = QFrame() complete_tab_widget.setLayout(complete_tab_layout) new_tab.load(QUrl(self.startpage)) self.tabs.setUpdatesEnabled(False) if self.new_tab_behavior == "insert": self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget, unicode(new_tab.title())) elif self.new_tab_behavior == "append": self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title())) self.tabs.setCurrentWidget(complete_tab_widget) self.tabs.setTabText(self.tabs.currentIndex(), unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title())) self.tabs.setUpdatesEnabled(True) # tab.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) # tab.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) new_tab.titleChanged.connect(self.change_tab) new_tab.urlChanged.connect(self.change_tab) new_tab.loadStarted.connect(self.load_start) new_tab.loadFinished.connect(self.load_finish) new_tab.loadProgress.connect(self.pbar.setValue) new_tab.page().linkHovered.connect(self.linkHover) inspector.setPage(new_tab.page()) def change_tab(self): """Change active tab.""" if self.tabs.count() <= 1: self.tabs.tabBar().hide() else: self.tabs.tabBar().show() try: self.edit.setText(str(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())) self.tabs.setTabText(self.tabs.currentIndex(), unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title())) self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setFocus() except Exception: self.tabs.tabBar().hide() self.new_tab() #print (self.tabs.widget(self.tabs.currentIndex()).size().width()-10), self.tabs.count() self.tabs_widget.setStyleSheet(self.style_sheet + "QTabBar::tab { width:" + str( (self.tabs.widget( self.tabs.currentIndex() ).size().width()-26-self.tabs.count()*2)/self.tabs.count() ) + "px; }") def previous_tab(self): """Previous tab.""" try: if self.tabs.currentIndex() > 0: self.tabs.setCurrentIndex(self.tabs.currentIndex()-1) else: self.tabs.setCurrentIndex(self.tabs.count()-1) self.change_tab() except Exception: pass def next_tab(self): """Next tab.""" try: if self.tabs.currentIndex() < self.tabs.count()-1: self.tabs.setCurrentIndex(self.tabs.currentIndex()+1) else: self.tabs.setCurrentIndex(0) self.change_tab() except Exception: #, e pass def close_tab(self): """Close tab.""" self.tabs.removeTab(self.tabs.currentIndex()) def close(self): """Close app.""" Qapplication.quit() def set_url(self): """Set url.""" url = self.edit.text() # does the url start with http://? if "." not in url: url = "http://www.google.com/search?q="+url elif not url.startswith("http://"): url = "http://" + url qurl = QUrl(url) self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).load(qurl) self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setFocus() def load_start(self): """Update view values, called upon started page load.""" self.rbutton.setText(u"╳") self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).stop) self.pbar.show() def load_finish(self): """Update view values, called upon finished page load.""" if (self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().canGoBack()): self.bbutton.setEnabled(True) else: self.bbutton.setEnabled(False) if (self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().canGoForward()): self.fbutton.setEnabled(True) else: self.fbutton.setEnabled(False) self.rbutton.setText(u"↻") self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload) self.pbar.hide() global bookmarks if unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()) in bookmarks: self.dbutton.setText(u"★") else: self.dbutton.setText(u"☆") if not self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).isHidden(): self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).hide() self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).show() def bookmark(self): """Toggle bookmark.""" global bookmarks if not self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded() in bookmarks: bookmarks.append(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()) pickle.dump(bookmarks, open(bookFile, "wb")) link = QToolButton() link.setDefaultAction(QAction(unicode(unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())), link)) link.setObjectName(unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())) link.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) link.clicked.connect(self.handleBookmarks) self.bookmarks_layout.addWidget(link) if self.bookmarks_widget.isHidden(): self.bookmarks_widget.show() self.dbutton.setText(u"★") else: bookmarks.remove(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()) pickle.dump(bookmarks, open(bookFile, "wb")) link = self.bookmarks_widget.findChild(QToolButton, unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())) self.bookmarks_layout.removeWidget(link) link.deleteLater() link = None if not bookmarks: self.bookmarks_widget.hide() self.dbutton.setText(u"☆") def handleBookmarks(self): self.gotoLink(self.sender().objectName()) #self.gotoLink(unicode()) def gotoLink(self, url): self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).load(QUrl(url)) def styleSheet(self, style_sheet): """Load stylesheet.""" try: with open(os.path.join (basedir, 'assets', 'style.qss'), 'r') as file: return file.read() except Exception: # print e return '' def resizeEvent(self, evt=None): """Called on window resize.""" self.change_tab() def myExitHandler(self): """Exiting.""" pass global tabFile # {current_tab: 1, tabs:[0: {current_history:3, history:[{title, url}]]} pb = {'current_tab': self.tabs.currentIndex()} pb['tabs'] = list() for tab in range(self.tabs.count()): pb['tabs'].append(dict(current_history=self.tabs.widget( tab).findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().currentItemIndex(), history=list(dict( title=item.title(), url=item.url() ) for item in self.tabs.widget(tab).findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().items()))) # print pb pickle.dump(pb, open(tabFile, "wb"))
mainWindow = QMainWindow() mainWindow.setUnifiedTitleAndToolBarOnMac(True) toolbar = mainWindow.addToolBar("Main") toolbar.setMovable(False) dirPath = os.path.dirname(__file__) basePath = os.path.join(dirPath, "../../resources/images/") icon = QIcon(basePath + "UserTransformButton.png") toolButtonLeft1 = CreateFlatButton(QAction(icon, "Left", mainWindow)) toolButtonLeft2 = CreateFlatButton(QAction(icon, "2nd left", mainWindow)) toolButtonRight = CreateFlatButton(QAction(icon, "Right", mainWindow)) toolButtonCenter = QPushButton() toolButtonCenter.setIcon(QIcon(basePath + "LandmarkTransformButton.png")) toolButtonCenter.setText("Center") toolButtonCenter.setMinimumWidth(200) barWidget = ToolbarWidget() barWidget.addLeftItem(toolButtonLeft1) barWidget.addLeftItem(toolButtonLeft2) barWidget.addCenterItem(toolButtonCenter) barWidget.addRightItem(toolButtonRight) toolbar.addWidget(barWidget) layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter) layout.addWidget(QLabel("Test toolbar widget"))
class HighwayAnalyzeWidget(QWidget): def __init__(self): super(HighwayAnalyzeWidget,self).__init__() self.averageSimulationTime = 325.0 mainLayout = QVBoxLayout() mainLayout.setAlignment(Qt.AlignTop|Qt.AlignHCenter) mainLayout.setSpacing(0) self.setLayout(mainLayout) topWidget = QWidget() self.topLayout = QHBoxLayout() self.topLayout.setSpacing(0) topWidget.setLayout(self.topLayout) topLeftWidget = QWidget() self.topLeftLayout = QVBoxLayout() topLeftWidget.setLayout(self.topLeftLayout) self.setupTopGroup() self.setupFilterGroup() self.topLayout.addWidget(topLeftWidget) self.layout().addWidget(topWidget) # Button and log buttonAndLogWidget = QWidget() buttonAndLogWidget.setLayout(QVBoxLayout()) # Analyze the results BUTTON self.analyzeResultsButton = QPushButton('Analyze the results') self.analyzeResultsButton.clicked.connect(self.analyzeResults) self.analyzeResultsButton.setEnabled(False) buttonAndLogWidget.layout().addWidget(self.analyzeResultsButton) # LOG self.logText = QTextBrowser() self.logText.setFont(QFont('Century Gothic', 7)) self.logText.setWordWrapMode(QTextOption.NoWrap) buttonAndLogWidget.layout().addWidget(self.logText) self.topLayout.addWidget(buttonAndLogWidget) self.results = [] self.logFile = os.path.join(self.resultsPath(), 'analyze_'+os.uname()[1]+'.log') # Image self.picLabel = QLabel() self.picLabel.setAlignment(Qt.AlignHCenter) #self.picLabel.resize(800,600) self.picLabel.setMinimumSize(800,600) self.layout().addWidget(self.picLabel) def setupTopGroup(self): topGroup = QGroupBox("Simulation Results") self.resultsPathLineEdit = SimpleOption('resultsPath','Results Path','/home/thomas/Dropbox/Keio/research/results/') topGroupLayout = QVBoxLayout() topGroupLayout.setSpacing(0) topGroupLayout.setAlignment(Qt.AlignTop) topGroupLayout.addWidget(self.resultsPathLineEdit) self.loadResultsLabel = QLabel() self.loadResultsLabel.setAlignment(Qt.AlignHCenter) topGroupLayout.addWidget(self.loadResultsLabel) self.loadResultsButton = QPushButton("Load the results") self.loadResultsButton.clicked.connect(self.loadResults) topGroupLayout.addWidget(self.loadResultsButton) topGroup.setLayout(topGroupLayout) self.topLeftLayout.addWidget(topGroup) def resultsPath(self): return self.resultsPathLineEdit.getValue() def setupFilterGroup(self): filterGroup = QGroupBox('Filter the results') filterGroupLayout = QVBoxLayout() filterGroupLayout.setSpacing(0) filterGroupLayout.setAlignment(Qt.AlignTop) # Distribution Model self.filterDistribution = SimpleComboboxOption('dis','Speed Distribution Model',3, True, 'Uniform','Exponential','Normal','Log Normal') filterGroupLayout.addWidget(self.filterDistribution) self.filterDistribution.setVisible(False) # Number of results per point self.filterNb = SimpleSpinOption('simuNbMin', 'Minimum results for a given setting', 10, integer=True, checkable=True) self.filterNb.checkBox.setChecked(True) filterGroupLayout.addWidget(self.filterNb) # Filter the date dateWidget = QWidget() dateWidget.setLayout(QHBoxLayout()) self.filterDate = QCheckBox('After') self.filterDate.setChecked(QSettings().value('filterDate','0')=='1') dateWidget.layout().addWidget(self.filterDate) self.filterDateYear = QComboBox() for m in xrange(2010,2012): self.filterDateYear.addItem(str(m)) self.filterDateYear.setCurrentIndex(int(QSettings().value('dateYear', 1))) dateWidget.layout().addWidget(self.filterDateYear) dateWidget.layout().addWidget(QLabel('Year')) self.filterDateMonth = QComboBox() for m in xrange(1,13): self.filterDateMonth.addItem(str(m)) self.filterDateMonth.setCurrentIndex(int(QSettings().value('dateMonth', 4))) dateWidget.layout().addWidget(self.filterDateMonth) dateWidget.layout().addWidget(QLabel('Month')) self.filterDateDay = QComboBox() for d in xrange(1,32): self.filterDateDay.addItem(str(d)) self.filterDateDay.setCurrentIndex(int(QSettings().value('dateDay', 0))) dateWidget.layout().addWidget(self.filterDateDay) dateWidget.layout().addWidget(QLabel('Day')) filterGroupLayout.addWidget(dateWidget) filterGroup.setLayout(filterGroupLayout) self.topLeftLayout.addWidget(filterGroup) # Filter the scenario self.filterScenar = SimpleComboboxOption('scenar','Scenario',1, True, 'vanet-highway-test-thomas','vanet-highway-scenario2') filterGroupLayout.addWidget(self.filterScenar) # Filter gap self.filterGap = SimpleSpinOption('avgdistanalyze','Average Distance (m)',100, checkable=True) filterGroupLayout.addWidget(self.filterGap) def loadResults(self): self.loadResultsButton.setText('Loading the results...') self.loadResultsButton.setEnabled(False) self.results = [] self.resultsThread = LoadResults(resultsPath=self.resultsPath()) self.resultsThread.done.connect(self.loadResultsDone) self.resultsThread.error.connect(self.loadResultsError) self.resultsThread.start() @Slot(str) def loadResultsError(self, errorMsg): QMessageBox.critical(self, 'Error!', errorMsg) self.analyzeResultsButton.setEnabled(False) @Slot(dict) def loadResultsDone(self, results): self.results = results resultsNb = len(self.results) msg= 'Found %d Simulation Results\n(%d invalid files, %d simulations failed)' % (resultsNb, self.resultsThread.fileUnloadable, self.resultsThread.simulationFailed) self.loadResultsLabel.setText(msg) #self.calculateAverageSimulationTime() self.loadResultsButton.setText('Reload the results') self.loadResultsButton.setEnabled(True) self.analyzeResultsButton.setEnabled(True) if resultsNb>0: self.analyzeResults() def calculateAverageSimulationTime(self): totalTime = 0 nb = 0 for r in self.results: if 'simulationTime' in r: #print 'simu time: %s' % r['simulationTime'] totalTime += int(r['simulationTime']) nb += 1 #print 'from %s: [%3.3f,%3.3f]' % (r['filename'], r['settings']['prate'],r['results']['timeToReachDest']) if nb<=0: errorMsg= 'No simulation found with simulationTime' QMessageBox.critical(self, 'Error!', errorMsg) self.averageSimulationTime = 290.0 else: self.averageSimulationTime= totalTime/nb self.loadResultsLabel.setText(self.loadResultsLabel.text()+'\nAverage simulation time: %3.0f'%self.averageSimulationTime) def fil(self, r): return self.checkDis(r) and self.checkDate(r) and self.checkGap(r) and self.checkScenario(r) def checkDis(self,r): return (not self.filterDistribution.checkBox.isChecked()) or r['settings']['dis']==self.filterDistribution.getValue() def checkDate(self, r): return (not self.filterDate.isChecked()) or (r['date'] >= datetime(int(self.filterDateYear.currentText()), int(self.filterDateMonth.currentText()), int(self.filterDateDay.currentText()))) def checkScenario(self, r): return (not self.filterScenar.checkBox.isChecked()) or r['scenario']==self.filterScenar.getName() def checkGap(self, r): return (not self.filterGap.checkBox.isChecked()) or float(r['settings']['avgdist'])==float(self.filterGap.getValue()) def analyzeResults(self): self.saveSettings() if len(self.results)<=0: QMessageBox.critical(self, 'Error!', 'No results loaded :s') return self.log("=== ANALYZING RESULTS ===") self.logText.clear() p=0 meanValues = {} uniqueName = dateToFilename() gnuPlotDataFile =os.path.join(self.resultsPath(),'graphs/' + uniqueName+'.dat') with open(gnuPlotDataFile,'w') as data: while p<=100: nb = 0 totalTimeToReachDest = 0 totalSimulationTime = 0 for result in filter(lambda x: x['settings']['prate']==p and self.fil(x), self.results): totalSimulationTime += float(result['simulationTime']) totalTimeToReachDest += float(result['results']['timeToReachDest']) nb += 1 if self.filterNb.checkBox.isChecked(): minNb = self.filterNb.getValue() else: minNb = 0 if nb>minNb: meanSimulationTime = float(1.0*totalSimulationTime/nb) meanTimeToReachDest = float(1.0*totalTimeToReachDest/nb) meanValues[p] = {'prate':p, 'simuLationTime':meanSimulationTime, 'simulationsNb':nb, 'timeToReachDest':meanTimeToReachDest} self.log(meanValues[p]) toPlot = '%s %s' % (p, meanValues[p]['timeToReachDest']) #print toPlot data.write(toPlot+'\n') p += 1 data.close() if len(meanValues)>0: outputPic = 'graphs/' + uniqueName s = subprocess.Popen(['./toPlot.sh', outputPic, gnuPlotDataFile], cwd=self.resultsPath()) s.wait() outputPicPath = os.path.join(self.resultsPath(),outputPic+'.svg') pic = QImage(outputPicPath) #pic = pic.scaled(QSize(640,480)) self.picLabel.setPixmap(QPixmap(pic)) #os.system(os.path.join(self.resultsPath(),'toPlot.sh')) else: QMessageBox.critical(self, 'Error!', 'No simulation satisfies the criteria...') def log(self, txt): toLog = str(txt) toLogFile = '%s | %s' % (datetime.now(), txt) with open(self.logFile, 'a') as logFile: logFile.write(toLogFile+'\n') self.logText.append(toLog) def saveSettings(self): QSettings().setValue('simuNbMin', self.filterNb.getValue()) QSettings().setValue('avgdistanalyze', self.filterGap.getValue()) QSettings().setValue('scenar', self.filterScenar.getValue()) QSettings().setValue('dis', self.filterDistribution.getValue()) QSettings().setValue('dateDay', self.filterDateDay.currentIndex()) QSettings().setValue('dateMonth', self.filterDateMonth.currentIndex()) QSettings().setValue('dateYear', self.filterDateYear.currentIndex()) if self.filterDate.isChecked(): QSettings().setValue('filterDate', '1') else: QSettings().setValue('filterDate', '0')
def __init__(self, parent=None): """ Default class constructor. :param `parent`: Pointer to a parent widget instance. :type `parent`: `QWidget`_ """ super(AboutDialog, self).__init__(parent) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) if parent: self.gImgDir = parent.gImgDir self.gIconDir = parent.gIconDir elif __name__ == '__main__': self.gImgDir = gAppDir + os.sep + 'images' self.gIconDir = gAppDir + os.sep + 'icons' + os.sep + 'default' # The tiled theme background texture. self.bgLogo = QPixmap(self.gImgDir + os.sep + 'texture-spirals.png') self.bgBrush = QBrush(self.bgLogo) self.setWhatsThis( self.tr("""\ The background is a tiled image of an actual design that was stitched out during the pre-alpha stage. It was created by Nina Paley and Theodore Gray using Mathematica in conjunction with our software. They have graciously allowed us to use it for the project in whichever way we wish. We thought it looked so good, that it has become the new theme for Embroidermodder 2. To check out some of the more interesting embroidery projects they are working on, visit http://blog.ninapaley.com/""")) self.imgLbl = EmbroidermodderLogo(self) aboutLbl = QTextBrowser(self) aboutLbl.setReadOnly(True) aboutLbl.setOpenExternalLinks(True) aboutLbl.setText('<b>%s</b>' % '<br>'.join(ABOUT.split('\n'))) aboutLbl.setWhatsThis( self. tr('This is the AWESOME people that brought Embroidermodder 2 to life.' )) # We want very slight opacity of the white background # so the seamless texture shows slightly through. opacityStyleSheet = """\ QTextEdit:read-only { color: rgb(50, 50, 50); font-size: 12px; font-weight: bold; background-color: rgba(255, 255, 255, 240); border: 1px solid rgba(0, 0, 0, 255); } """ aboutLbl.setStyleSheet(opacityStyleSheet) op = QGraphicsOpacityEffect(aboutLbl) op.setOpacity(0.95) aboutLbl.setGraphicsEffect(op) self.notebook = QTabWidget(self) self.notebook.setMinimumWidth(500) self.notebook.addTab(aboutLbl, self.tr('About')) self.notebook.setTabIcon(0, QIcon(self.gIconDir + os.sep + 'app.png')) self.notebook.setTabIcon( 1, QIcon(self.gImgDir + os.sep + 'kickstarter-logo-k-color.png')) notebookStyleSheet = """\ QTabWidget::pane { /* The tab widget frame */ border-top: 1px solid #000000; position: absolute; top: -0.5em; } QTabWidget::tab-bar { alignment: center; } /* Style the tab using the tab sub-control. Note that it reads QTabBar _not_ QTabWidget */ QTabBar::tab { margin-top: 2px; /* make non-selected tabs look smaller */ font-size: 14px; font-weight: bold; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #E1E1E1, stop: 0.4 #DDDDDD, stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3); border: 1px solid #000000; /* border-bottom-color: #C2C7CB; */ /* same as the pane color */ border-top-left-radius: 4px; border-top-right-radius: 4px; min-width: 40ex; min-height: 5ex; padding: 3px; } QTabBar::tab:selected { margin-top: 0px; font-size: 16px; font-weight: bold; background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2, stop: 0 #0C6AB0, stop: 0.15 #55C4E6, stop: 0.15 #55C4E6, stop: 0.5 #FFFFFF, stop: 0.5 #FFFFFF, stop: 0.85 #55C4E6, stop: 0.85 #55C4E6, stop: 1.0 #0C6AB0); border: 1px solid #000000; } QTabBar::tab:!selected:hover { margin-top: 2px; /* make non-selected tabs look smaller */ font-size: 14px; font-weight: bold; background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2, stop: 0 #888888, stop: 0.15 #BBBBBB, stop: 0.15 #BBBBBB, stop: 0.5 #FFFFFF, stop: 0.5 #FFFFFF, stop: 0.85 #BBBBBB, stop: 0.85 #BBBBBB, stop: 1.0 #888888); border: 1px solid #000000; } QTabBar::tab:selected { border-color: #000000; border-bottom-color: #000000; /* same as pane color */ } """ self.notebook.setStyleSheet(notebookStyleSheet) self.notebook.currentChanged.connect(self.CurrentTabChanged) buttonbox = QDialogButtonBox(Qt.Horizontal, self) button = QPushButton(self) button.setText(self.tr("Oh, Yeah!")) button.setWhatsThis( self.tr('This is the Oh, Yeah! button!') + '\n' + self.tr('Oh, Yeah!')) buttonbox.addButton(button, QDialogButtonBox.AcceptRole) buttonbox.setCenterButtons(True) buttonbox.accepted.connect(self.accept) hbLayout1 = QHBoxLayout() hbLayout2 = QHBoxLayout() vbLayout = QVBoxLayout() hbLayout1.addStretch() hbLayout1.addWidget(self.imgLbl) hbLayout1.addStretch() hbLayout2.addStretch() hbLayout2.addWidget(self.notebook) hbLayout2.addStretch() vbLayout.addLayout(hbLayout1) vbLayout.addLayout(hbLayout2) vbLayout.addWidget(buttonbox) self.setLayout(vbLayout) self.setWindowTitle(self.tr('About Embroidermodder Version 2.0')) QApplication.restoreOverrideCursor( ) # TODO/???/PORT# don't mess with the window resize cursors.
class SyncView(View): """`View` derived class. Defines the sync widget""" sync = Signal((str, )) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(SyncView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(580, 340) self.status.setMessage('Ready') def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() pathLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(10) fieldsLayout.addStretch(50) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addWidget(self.localdirLabel) pathLayout.addWidget(self.localdirEdit) pathLayout.addWidget(self.browseButton) fieldsLayout.addLayout(pathLayout) buttonLayout.addStretch(50) buttonLayout.addWidget(self.syncButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(10) fieldsLayout.addWidget(self.statusLabel) fieldsLayout.addWidget(self.status) fieldsLayout.addStretch(80) mainLayout.addLayout(fieldsLayout, 60) mainLayout.addStretch(10) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 450 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.localdirLabel = QLabel(self) self.localdirEdit = QLineEdit(self) self.localdirLabel.setText('Choose a folder') self.localdirLabel.setFont(labelsFont) self.localdirEdit.setFixedWidth(fieldsWidth) self.localdirEdit.setReadOnly(False) self.localdirEdit.setFont(editsFont) self.browseButton = QPushButton(self) self.browseButton.setText('Browse') self.browseButton.setFont(labelsFont) self.syncButton = QPushButton(self) self.syncButton.setText('Sync') self.syncButton.setFont(labelsFont) self.browseButton.clicked.connect(self.onBrowseClicked) self.syncButton.clicked.connect(self.onSyncClicked) settings = get_settings() self.localdirEdit.setText(settings.value(SettingsKeys['localdir'], '')) self.statusLabel = QLabel(self) self.statusLabel.setText('Status') self.statusLabel.setFont(View.labelsFont()) self.status = StatusArea(self) @Slot() def onBrowseClicked(self): """Slot. Called when the user clicks on the `browseButton` button""" # Presents the user with a native directory selector window localdir = QFileDialog.getExistingDirectory() localdir = QDir.fromNativeSeparators(localdir) if len(localdir) > 0: # If `localdir`'s value is good, store it using a `QSettings` object # and triggers a sync request. # Careful with '\' separators on Windows. localdir = QDir.toNativeSeparators(localdir) get_settings().setValue(SettingsKeys['localdir'], localdir) self.localdirEdit.setText(localdir) @Slot() def onSyncClicked(self): """Slot. Called when the user clicks on the `syncButton` button""" localdir = self.localdirEdit.text() if len(localdir) > 0: self.syncButton.setEnabled(False) self.sync.emit(localdir)
class RenderPropWidget(QWidget): """ RenderPropWidget is a widget that is displayed under the render widgets. It contains a tabwidget in which information of the data can be displayed and in which visualization parameters can be shown. One of the tabs is a RenderParameterWidget object. """ def __init__(self, renderController, parent=None): super(RenderPropWidget, self).__init__(parent=parent) # Three tabs: Visualization, data info and slices self.visParamTabWidget = RenderParameterWidget(renderController) self.dataInfoTabWidget = RenderInfoWidget() self.slicesTabWidget = RenderSlicerParamWidget(renderController) # Create the load dataset widget self.loadDataWidget = QWidget() self.loadDataButton = QPushButton() self.loadDataButton.setText("Load a dataset") layout = QVBoxLayout() layout.setAlignment(Qt.AlignTop) layout.addWidget(self.loadDataButton) self.loadDataWidget.setLayout(layout) # Create the tab widget self.tabWidget = QTabWidget() self.tabWidget.addTab(self.visParamTabWidget, "Visualization") self.tabWidget.addTab(self.dataInfoTabWidget, "Data info") self.tabWidget.addTab(self.slicesTabWidget, "Slices") layout = QVBoxLayout() layout.addWidget(self.loadDataWidget) self.setLayout(layout) def setFileChangedSignal(self, signal): """ :param signal: Signal that is connected to some file-loading slots. :type signal: SIGNAL """ self.signal = signal self.signal.connect(self.setFile) self.signal.connect(self.dataInfoTabWidget.setFile) def setLoadDataSlot(self, slot): """ The button is connected to the given slot. The slot action should load a dataset from disk. :type slot: Slot """ self.loadDataButton.clicked.connect(slot) @Slot(basestring) def setFile(self, fileName): """ When a file is loaded, the 'load data' button is removed from the widget and the actual tabs with parameters are put on screen. """ layout = self.layout() if fileName is None: if layout.indexOf(self.tabWidget) != -1: # Remove the parameter widgets layout.removeWidget(self.tabWidget) self.tabWidget.setParent(None) # Show the load data button layout.addWidget(self.loadDataWidget) self.setLayout(layout) else: if layout.indexOf(self.loadDataWidget) != -1: # Remove the load data button layout.removeWidget(self.loadDataWidget) self.loadDataWidget.setParent(None) # Add the parameter widgets layout.addWidget(self.tabWidget) self.setLayout(layout)
class AVRProgrammerDialog(QtFixes.QDialog): def __init__(self): super(AVRProgrammerDialog, self).__init__(CWMainGUI.getInstance()) # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint) self.avr = AVRProgrammer() self.setWindowTitle("ChipWhisperer-Lite AVR Programmer") layout = QVBoxLayout() layoutFW = QHBoxLayout() self.flashLocation = QtFixes.QLineEdit() flashFileButton = QPushButton("Find") flashFileButton.clicked.connect(self.findFlash) layoutFW.addWidget(QLabel("FLASH File")) layoutFW.addWidget(self.flashLocation) layoutFW.addWidget(flashFileButton) layout.addLayout(layoutFW) self.flashLocation.setText(QSettings().value("avr-flash-location")) # Add buttons readSigBut = QPushButton("Check Signature") readSigBut.clicked.connect(self.readSignature) verifyFlashBut = QPushButton("Verify FLASH") verifyFlashBut.clicked.connect(self.verifyFlash) verifyFlashBut.setEnabled(False) progFlashBut = QPushButton("Erase/Program/Verify FLASH") progFlashBut.clicked.connect(self.writeFlash) layoutBut = QHBoxLayout() layoutBut.addWidget(readSigBut) layoutBut.addWidget(verifyFlashBut) layoutBut.addWidget(progFlashBut) layout.addLayout(layoutBut) layoutFuse = QHBoxLayout() readFuseBut = QPushButton("Read Fuses") readFuseBut.clicked.connect(self.readFuses) writeFuseBut = QPushButton("Write Fuses") writeFuseBut.clicked.connect(self.writeFuses) self.lowfuseLine = QtFixes.QLineEdit("?") self.lowfuseLine.setMaxLength(2) self.lowfuseLine.setFixedWidth(25) self.highfuseLine = QtFixes.QLineEdit("?") self.highfuseLine.setMaxLength(2) self.highfuseLine.setFixedWidth(25) self.extfuseLine = QtFixes.QLineEdit("?") self.extfuseLine.setMaxLength(2) self.extfuseLine.setFixedWidth(25) # Don't allow use to change these fuses self.highfuseLine.setReadOnly(True) self.extfuseLine.setReadOnly(True) layoutFuse.addWidget(readFuseBut) layoutFuse.addWidget(QLabel("LOW:")) layoutFuse.addWidget(self.lowfuseLine) layoutFuse.addWidget(QLabel("HIGH:")) layoutFuse.addWidget(self.highfuseLine) layoutFuse.addWidget(QLabel("EXT:")) layoutFuse.addWidget(self.extfuseLine) layoutFuse.addWidget(writeFuseBut) layout.addLayout(layoutFuse) layoutExtra = QHBoxLayout() self.clockMode = QPushButton("Enable Slow Clock Mode") self.clockMode.setCheckable(True) self.clockMode.clicked.connect(self.toggleSlowClock) layoutExtra.addWidget(self.clockMode) layoutExtra.addStretch() layout.addLayout(layoutExtra) # Add status stuff self.statusLine = QPlainTextEdit() self.statusLine.setReadOnly(True) # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10) self.statusLine.append = self.statusLine.appendPlainText layout.addWidget(self.statusLine) self.avr._logging = self.statusLine.append # Set dialog layout self.setLayout(layout) def toggleSlowClock(self): if self.clockMode.isChecked(): self.avr.avr.enableSlowClock(True) self.clockMode.setText("Disable Slow Clock Mode") else: self.avr.avr.enableSlowClock(False) self.clockMode.setText("Enable Slow Clock Mode") def reject(self): #Ensure we disable slow-clock mode if self.clockMode.isChecked(): self.clockMode.setChecked(False) self.toggleSlowClock() #Release AVR self.avr.close() QDialog.reject(self) def findFlash(self): fname, _ = QFileDialog.getOpenFileName(self, 'Find FLASH File', QSettings().value("avr-flash-location"), '*.hex') if fname: self.flashLocation.setText(fname) QSettings().setValue("avr-flash-location", fname) def readSignature(self, close=True): self.avr.find() if close: self.avr.close() def readFuses(self): try: self.readSignature(close=False) self.statusLine.append("Reading fuses") lfuse = self.avr.avr.readFuse("low") hfuse = self.avr.avr.readFuse("high") efuse = self.avr.avr.readFuse("extended") self.statusLine.append("OK: %02x %02x %02x" % (lfuse, hfuse, efuse)) self.lowfuseLine.setText("%02x" % lfuse) self.highfuseLine.setText("%02x" % hfuse) self.extfuseLine.setText("%02x" % efuse) except IOError: self.statusLine.append("Reading fuses failed") self.lowfuseLine.setText("?") self.highfuseLine.setText("?") self.extfuseLine.setText("?") self.avr.close() def writeFuses(self): lfuse = int(self.lowfuseLine.text(), 16) # hfuse = int(self.highfuseLine.text(), 16) # efuse = int(self.extfuseLine.text(), 16) self.statusLine.append("Writing fuse: not only 'low' fuse is written, as hfuse/efuse can disable device\n") try: self.readSignature(close=False) self.avr.avr.writeFuse("low", lfuse) # self.avr.avr.writeFuse("high", hfuse) # self.avr.avr.writeFuse("extended", efuse) # print("%x %x %x" % (lfuse, hfuse, efuse)) self.avr.close() except: self.avr.close() raise def verifyFlash(self): self.statusLine.append("Verify not implemented") def writeFlash(self, erase=True, verify=True): status = "FAILED" fname = self.flashLocation.text() self.statusLine.append("***Starting FLASH program process at %s***" % datetime.now().strftime('%H:%M:%S')) if (os.path.isfile(fname)): self.statusLine.append("File %s last changed on %s" % (fname, time.ctime(os.path.getmtime(fname)))) QCoreApplication.processEvents() try: self.statusLine.append("Entering Programming Mode") QCoreApplication.processEvents() self.readSignature(close=False) if erase: self.statusLine.append("Erasing Chip") QCoreApplication.processEvents() self.avr.erase() self.avr.close() self.readSignature(close=False) QCoreApplication.processEvents() self.avr.program(self.flashLocation.text(), memtype="flash", verify=verify) QCoreApplication.processEvents() self.statusLine.append("Exiting programming mode") self.avr.close() QCoreApplication.processEvents() status = "SUCCEEDED" except IOError as e: self.statusLine.append("FAILED: %s" % str(e)) try: self.avr.close() except IOError: pass else: self.statusLine.append("%s does not appear to be a file, check path" % fname) self.statusLine.append("***FLASH Program %s at %s***" % (status, datetime.now().strftime('%H:%M:%S'))) def setUSBInterface(self, iface): self.avr.setUSBInterface(iface)
class UiMain(QMainWindow): """ The main gui interface, invokes all windows and ties everything together """ def __init__(self): """ automatically called __init__ function """ super(UiMain, self).__init__() # initialize all the variables that are going to be defined in the # future self.update_dialog = None self.update_dialog_lbl = None self.app_select_box = None self.selector_lbl = None self.current_playing_lbl = None self.current_playing = None self.misc_messages = None self.start_btn = None self.output_dir_lbl = None self.select_output_dir_btn = None self.output_cur_dir_lbl = None self.active_items_list = None self.inactive_items_list = None self.switch_active_item_button_off = None self.switch_active_item_button_on = None self.switch_output_split_btn = None self.switch_output_split_lbl = None # initialize the system tray # self.system_tray = QSystemTrayIcon(self) # self.system_tray.setIcon(QIcon(resource_path('icon.png'))) # self.system_tray.show() # self.system_tray.setToolTip('SMG') # self.system_tray.activated.connect(self.on_systray_activated) # initialize the main window self.setObjectName('self') self.setWindowTitle('SMG - By Azeirah') self.resize(400, 250) # Gives the self an icon self.setWindowIcon(QIcon(resource_path('icon.png'))) # create the tabs # the tab widget itself self.tabbed_windows = QTabWidget(self) self.tabbed_windows.resize(400, 300) # tab 1, contains the music player selection self.music_players = QFrame() # tab 2, contains options self.options = QFrame() self.tabbed_windows.addTab(self.music_players, 'Music players') self.tabbed_windows.addTab(self.options, 'Options') # initializes the two tabs, with all the code down below self.tab_music_players() self.tab_options() # shows the main window self.show() def closeEvent(self, event): """ an automatically called function when the program is about to close. """ # Stops all Threads. These would continue to run in the background # Even if the window was closed. Main.running = False # close the ZuneNowPlaying.exe process if Constants.SUBP: Constants.SUBP.kill() def changeEvent(self, event): # if event.type() == QEvent.WindowStateChange: # if self.isMinimized(): # event.ignore() # self.hide() # self.system_tray.showMessage('Running', 'Running in the # background.') # return super(UiMain, self).changeEvent(event) def on_systray_activated(self, reason): if reason == QSystemTrayIcon.DoubleClick: self.show() @staticmethod def toggle_split(event): # 0 = Qt.Unchecked The item is unchecked. # 1 = Qt.PartiallyChecked The item is partially checked. Items in # hierarchical models may be partially checked if some, but not all, # of # their children are checked. # 2 = Qt.Checked The item is checked. if event == 0: Constants.OPTIONS['splitText'] = False elif event == 2: Constants.OPTIONS['splitText'] = True def update(self): """ Checks a webpage for current version, compares this to built-in current versions, and shows update dialog if necessary """ try: ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\ .read() except IOError: # if for some reason it couldn't retrieve the version, set it to # automatically ignore the update: False ver = False if not float(VERSION) >= float(ver): self.popup = QDialog(self) self.popup.setModal(True) self.popup.setGeometry(200, 100, 500, 100) self.popup.show() self.popup_text = QLabel(self.popup) self.popup_text.setGeometry(5, 5, 500, 30) self.popup_text.setOpenExternalLinks(True) self.popup_text.show() self.popup_text.setText( """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>""") # reply = QMessageBox.question(Constants.UI, 'Message', # "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) # if reply == QMessageBox.Yes: # import atexit # import subprocess # def runUpdater(): # import time # time.sleep(3) # subprocess.Popen(resource_path('update.exe')) # atexit.register(runUpdater) # sys.exit() # Constants.update_dialog = QWidget() # Constants.update_dialog.resize(350, 100) # Constants.update_dialog.setWindowIcon(QIcon(resource_path\ # ('icon.png'))) # Constants.update_dialog.setWindowTitle('Updater') # Constants.update_dialog_lbl = QLabel(Constants.update_dialog) # Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12) # Constants.update_dialog.show() # updateThread = Thread(target = update.update) # updateThread.setName('updateThread') # updateThread.start() def tab_music_players(self): """ Everything inside the Music players tab gets created here.""" # self.music_players # Creates the box with all the music players inside of it self.app_select_box = QComboBox(self.music_players) self.app_select_box.setGeometry(135, 10, 150, 25) # Whenever you change the application, it runs the selectnewapp func self.app_select_box.activated[str].connect(self.select_new_app) # Creates the label for the selection combobox self.selector_lbl = QLabel(self.music_players) self.selector_lbl.setGeometry(10, 10, 150, 25) self.selector_lbl.setText('Select your music player: ') # Creates the label for the current playing song (and the current # playing song label) self.current_playing_lbl = QLabel(self.music_players) self.current_playing_lbl.setGeometry(10, 45, 150, 25) self.current_playing_lbl.setText('Current playing song: ') self.current_playing = QLabel(self.music_players) self.current_playing.setGeometry(117, 45, 250, 25) self.current_playing.setText(Misc.noSongPlaying) # Creates a label which displays any additional messages self.misc_messages = QLabel(self.music_players) self.misc_messages.setGeometry(10, 80, 390, 24) self.misc_messages.setText(Misc.misc_message()) self.misc_messages.setOpenExternalLinks(True) # adds all the music players into the combobox self.app_select_box.addItem(None) for item in Constants.ACTIVEITEMS: if item == '__name__' or item == 'active': continue self.app_select_box.addItem(item) # creates the start button self.start_btn = QPushButton(self.music_players) self.start_btn.setGeometry(75, 120, 250, 35) self.start_btn.setText('Start') # links the start button to the self.start function QObject.connect(self.start_btn, SIGNAL("clicked()"), lambda: Thread(target=self.start, name='startbutton').start()) def tab_options(self): """ Everything inside the Options tab gets created here. """ # self.options # This section is for selecting output dir # Creates the output dir label self.output_dir_lbl = QLabel(self.options) self.output_dir_lbl.setGeometry(10, 10, 125, 15) self.output_dir_lbl.setText('Change Output Directory: ') # Creates the output dir button self.select_output_dir_btn = QPushButton(self.options) self.select_output_dir_btn.setGeometry(137, 8, 30, 20) self.select_output_dir_btn.setText('...') # Creates the output dir currentdir Lineedit self.output_cur_dir_lbl = QLineEdit(self.options) self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25) self.output_cur_dir_lbl.setReadOnly(True) self.output_cur_dir_lbl.setText(Constants.CONFIG. get('directories', 'current_song')) # when the '...' button is clicked, show a dialog (fire func # disp_dialog) QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"), self.disp_dialog) # This section is for selecting what players you use # The box with all the active players self.active_items_list = QListWidget(self.options) self.active_items_list.setGeometry(10, 40, 150, 100) # The box with all the inactive players self.inactive_items_list = QListWidget(self.options) self.inactive_items_list.setGeometry(230, 40, 150, 100) # Populate the two boxes with active and inactive items for item in Constants.ACTIVEITEMS: if item == '__name__' or item == 'active': continue self.active_items_list.addItem(item) for item in Constants.INACTIVEITEMS: if item == '__name__' or item == 'active': continue self.inactive_items_list.addItem(item) # The buttons responsible for switching # off button self.switch_active_item_button_off = QPushButton(self.options) self.switch_active_item_button_off.setText('->'.decode('utf-8')) # Makes the -> readable and clear self.switch_active_item_button_off.setFont(QFont('SansSerif', 17)) self.switch_active_item_button_off.setGeometry(175, 55, 40, 30) # on button self.switch_active_item_button_on = QPushButton(self.options) self.switch_active_item_button_on.setText('<-'.decode('utf-8')) # makes <- readable and clear self.switch_active_item_button_on.setFont(QFont('SansSerif', 17)) self.switch_active_item_button_on.setGeometry(175, 90, 40, 30) QObject.connect(self.switch_active_item_button_on, SIGNAL ("clicked()"), self.switch_item_on) QObject.connect(self.switch_active_item_button_off, SIGNAL ("clicked()"), self.switch_item_off) # A button to toggle the split output in half option. It's a temporary # fix for the Foobar double output problem. self.switch_output_split_btn = QCheckBox(self.options) self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked) self.switch_output_split_btn.setGeometry(10, 140, 40, 30) self.switch_output_split_btn.stateChanged.connect(self.toggle_split) # The label for the split toggle self.switch_output_split_lbl = QLabel(self.options) self.switch_output_split_lbl.setText( "Split the output text in half (don't use this if you don't need it)") self.switch_output_split_lbl.setGeometry(30, 140, 300, 30) def switch_item_on(self): """ Switches items (musicapps) on """ try: # If an item from the active box is selected # Remove it and place it inside the inactive box item_taken = self.inactive_items_list.takeItem( self.inactive_items_list.currentRow()) self.active_items_list.addItem(item_taken) active_items = {} inactive_items = {} for i in range(self.active_items_list.count()): active_items[self.active_items_list.item(i).text()] =\ ITEMS[self.active_items_list.item(i).text() .encode('utf-8')] for i in range(self.inactive_items_list.count()): inactive_items[self.inactive_items_list.item(i).text()] =\ ITEMS[self.inactive_items_list.item(i).text() .encode('utf-8')] Constants.ACTIVE_ITEMS = active_items Constants.INACTIVE_ITEMS = inactive_items # clear the selection combobox self.app_select_box.clear() # Repopulate the combobox self.app_select_box.addItem(None) for item in active_items: self.app_select_box.addItem(item) Constants.CONFIG.set('active', item_taken.text(), ITEMS[item_taken.text()]) Constants.CONFIG.remove_option('inactive', item_taken.text()) # Updates the config file to be up to date with activeItems Constants.CONFIG.update() except: raise def switch_item_off(self): """ Switches items (musicapps) off """ try: # If an item from the inactive box is selected. # Remove it and place it inside the active box item_taken = self.active_items_list.takeItem( self.active_items_list.currentRow()) self.inactive_items_list.addItem(item_taken) # update activeItems active_items = {} inactive_items = {} for i in range(self.active_items_list.count()): active_items[self.active_items_list.item(i).text()] =\ ITEMS[self.active_items_list.item(i).text() .encode('utf-8')] for i in range(self.inactive_items_list.count()): inactive_items[self.inactive_items_list.item(i).text()] =\ ITEMS[self.inactive_items_list.item(i).text() .encode('utf-8')] Constants.ACTIVE_ITEMS = active_items Constants.INACTIVE_ITEMS = inactive_items # clear the selection combobox self.app_select_box.clear() # Repopulate the combobox self.app_select_box.addItem(None) for item in active_items: self.app_select_box.addItem(item) # Updates the active items Constants property Constants.CONFIG.set('inactive', item_taken.text(), ITEMS[item_taken.text()]) Constants.CONFIG.remove_option('active', item_taken.text()) # Updates the config file to be up to date with activeItems Constants.CONFIG.update() except: raise def disp_dialog(self): """ displays the dialog which select a directory for output. """ fname = QFileDialog.getExistingDirectory() Constants.CONFIG.set('directories', 'current_song', fname) self.output_cur_dir_lbl.setText(Constants.CONFIG. get('directories', 'current_song')) def select_new_app(self, text): """ Sets the new application to check for """ try: Main.selectedProgram = ITEMS[text] except KeyError: # catches the empty option, it's obviously not in the dict pass # custom message for zune if Main.selectedProgram == 'zune': self.misc_messages.setText(Misc.ZuneNotification) # custom message for webplayers which require the groovemarklet elif text.find('*'): self.misc_messages.setText(Misc.GetGroovemarklet) def start(self): """ When the start button is pressed, start the main program loop """ if Main.selectedProgram: if not Main.running: self.start_btn.setText('Stop') Main.running = True try: pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) except pythoncom.com_error: # already initialized. pass thread = Thread( target=Main.enumWindows, name='enumWindows') thread.run() else: self.start_btn.setText('Start') Main.running = False self.set_playing(Misc.noSongPlaying) Wr.write('') def set_playing(self, title=''): """ Sets the text of the label of what song is playing """ # print 'setting title: ', title self.current_playing.setText(title)
class MainWindow(object): ''' Contains the implementation for building and displaying the application's main window. ''' def __init__(self, model, alg): ''' Constructs the GUI and initializes internal parameters. ''' self._window = QMainWindow() self._window.setWindowTitle("Reverse A*") self._worldWidget = WorldWidget(model, alg) self._model = model self._alg = alg self._spdSetting = 0 self._timer = QTimer() #Every time the timer times out, invoke the _onStep method. self._timer.timeout.connect(self._onStep) self._buildGUI() self._window.show() def _buildGUI(self): ''' Construct the GUI widgets and layouts. ''' centerWidget = QWidget() self._window.setCentralWidget(centerWidget) worldLayout = QHBoxLayout() worldLayout.addWidget(self._worldWidget) grpBx = QGroupBox("2D World") grpBx.setLayout(worldLayout) grpBx.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) ctrlPan = self._buildControlPanel() layout = QHBoxLayout() layout.addWidget(ctrlPan) layout.addWidget(grpBx) layout.setAlignment(ctrlPan, Qt.AlignLeft | Qt.AlignTop) centerWidget.setLayout(layout) def _buildControlPanel(self): ''' Create all buttons, labels, etc for the application control elements ''' layout = QVBoxLayout() layout.addWidget(self._buildSetupPanel()) layout.addWidget(self._buildSpeedPanel()) layout.addWidget(self._buildResultsPanel()) layout.addWidget(self._buildRenderingOptions()) layout.setAlignment(Qt.AlignLeft | Qt.AlignTop) ctrlWidget = QWidget(self._window) ctrlWidget.setLayout(layout) ctrlWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) return ctrlWidget def _buildSetupPanel(self): ''' Creates the sub-panel containing control widgets for re-initializing the world on demand. ''' self._percentLbl = QLabel("%") self._setupBtn = QPushButton("Setup", self._window) self._setupBtn.clicked.connect(self._onSetup) self._percentObstacleSldr = QSlider(Qt.Horizontal, self._window) self._percentObstacleSldr.setTickPosition(QSlider.TickPosition.TicksBelow) self._percentObstacleSldr.setTickInterval(10) self._percentObstacleSldr.setMinimum(0) self._percentObstacleSldr.setMaximum(100) self._percentObstacleSldr.valueChanged.connect(self._onPercentSlideChange) self._percentObstacleSldr.setValue(33) layout = QGridLayout() layout.addWidget(self._setupBtn, 0, 0, 1, 2) layout.addWidget(QLabel("Percent Occupied:"), 1, 0) layout.addWidget(self._percentLbl, 1, 1) layout.addWidget(self._percentObstacleSldr, 2, 0, 1, 2) grpBx = QGroupBox("Setup Controls") grpBx.setLayout(layout) grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) return grpBx def _buildSpeedPanel(self): ''' Creates the sub-panel containing control widgets for controlling the speed of execution of the algorithm. ''' self._runBtn = QPushButton("Run", self._window) self._stepBtn = QPushButton("Step Once", self._window) self._runBtn.clicked.connect(self._onRun) self._stepBtn.clicked.connect(self._onStep) slowRadio = QRadioButton('Slow', self._window) medRadio = QRadioButton('Medium', self._window) fastRadio = QRadioButton('Fast', self._window) notVisRadio = QRadioButton('Not visible', self._window) slowRadio.setChecked(True) self._speedGroup = QButtonGroup(self._window) self._speedGroup.addButton(slowRadio, 0) self._speedGroup.addButton(medRadio, 1) self._speedGroup.addButton(fastRadio, 2) self._speedGroup.addButton(notVisRadio, 3) self._speedGroup.buttonClicked.connect(self._onSpeedChange) layout = QVBoxLayout() layout.addWidget(self._runBtn) layout.addWidget(self._stepBtn) layout.addWidget(slowRadio) layout.addWidget(medRadio) layout.addWidget(fastRadio) layout.addWidget(notVisRadio) grpBx = QGroupBox("Run Controls") grpBx.setLayout(layout) grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) return grpBx def _buildResultsPanel(self): ''' Creates the sub-panel containing displays widgets for informing the user on the results of running the algorithm. ''' self._doneLbl = QLabel("No", self._window) self._solvableLbl = QLabel("Yes", self._window) #_doneLbl is highlighted green upon successful algorithm completion pal = self._doneLbl.palette() pal.setColor(QPalette.Window, Qt.green) self._doneLbl.setPalette(pal) #_solvableLbl is highlighted red if the world model isn't solvable pal = self._solvableLbl.palette() pal.setColor(QPalette.Window, Qt.red) self._solvableLbl.setPalette(pal) layout = QGridLayout() layout.addWidget(QLabel("Path Found:"), 0, 0) layout.addWidget(self._doneLbl, 0, 1) layout.addWidget(QLabel("Is Solvable:"), 1, 0) layout.addWidget(self._solvableLbl, 1, 1) grpBx = QGroupBox("Results") grpBx.setLayout(layout) grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) return grpBx def _buildRenderingOptions(self): ''' Creates the sub-panel containing control widgets for setting options in how the world is rendered on the GUI. ''' self._openChk = QCheckBox("Active Cells") self._visitedChk = QCheckBox("Visited Cells") self._pathChk = QCheckBox("Draw Path") self._costChk = QCheckBox("Draw Estimated Costs") pal = self._openChk.palette() pal.setColor(QPalette.WindowText, Qt.green) self._openChk.setPalette(pal) pal = self._visitedChk.palette() pal.setColor(QPalette.WindowText, Qt.cyan) self._visitedChk.setPalette(pal) pal = self._pathChk.palette() pal.setColor(QPalette.WindowText, Qt.red) self._pathChk.setPalette(pal) self._visitedChk.setChecked(True) self._pathChk.setChecked(True) self._costChk.setChecked(True) self._openChk.stateChanged.connect(self._renderingOptionChanged) self._visitedChk.stateChanged.connect(self._renderingOptionChanged) self._pathChk.stateChanged.connect(self._renderingOptionChanged) self._costChk.stateChanged.connect(self._renderingOptionChanged) layout = QVBoxLayout() layout.addWidget(self._openChk) layout.addWidget(self._visitedChk) layout.addWidget(self._pathChk) layout.addWidget(self._costChk) grpBx = QGroupBox("Rendering Options") grpBx.setLayout(layout) grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) return grpBx @Slot() def _renderingOptionChanged(self, value): ''' When any rendering option is changed this method is invoked. It polls the GUI for the selected setting values and passes them to the 2D world widget. ''' self._worldWidget.setDrawActiveCells(self._openChk.isChecked()) self._worldWidget.setDrawVisitedCells(self._visitedChk.isChecked()) self._worldWidget.setDrawPath(self._pathChk.isChecked()) self._worldWidget.setDrawCosts(self._costChk.isChecked()) self._worldWidget.repaint() @Slot() def _onPercentSlideChange(self, value): ''' Invoked every time the percent slider is changed. Displays the percent value on the GUI. ''' #Add extra padding to the front of the string to help prevent #gui layout resizing if value < 10: self._percentLbl.setText(" " + str(value) + "%") elif value < 100: self._percentLbl.setText(" " + str(value) + "%") else: self._percentLbl.setText(str(value) + "%") @Slot() def _onSpeedChange(self, value): ''' Invoked every time one of the speed setting radio buttons are selected. Resets the algorithm iterating callback timer if it's currently running. ''' self._spdSetting = self._speedGroup.checkedId() if self._timer.isActive(): self._resetTimer() @Slot() def _onSetup(self): ''' Invoked when the setup button is pushed. Re-initializes the world model and the algorithm. ''' self._timer.stop() self._runBtn.setText('Run') self._model.reset(self._percentObstacleSldr.value() / 100.0) self._alg.reset() self._doneLbl.setText("No") self._solvableLbl.setText("Yes") self._doneLbl.setAutoFillBackground(False) self._solvableLbl.setAutoFillBackground(False) self._worldWidget.repaint() @Slot() def _onRun(self): ''' Invoked when the run button is pushed. Toggles the algorithm iterating timer on and off. ''' if self._timer.isActive(): self._timer.stop() self._runBtn.setText("Run") else: self._resetTimer() self._runBtn.setText("Stop") @Slot() def _onStep(self): ''' Invoked on every 'step once' call and on every timer timeout. Iterates one step of the algorithm and then checks for termination conditions such as the algorithm being done or solvable. ''' self._alg.step() self._worldWidget.repaint() if self._alg.isDone() or not self._alg.isSolvable(): self._timer.stop() self._runBtn.setText('Run') self._checkTerminalConditions() def _checkTerminalConditions(self): ''' Sets the 'results' labels based on the algorithm results. ''' if self._alg.isDone(): self._doneLbl.setText("Yes") self._doneLbl.setAutoFillBackground(True) if not self._alg.isSolvable(): self._solvableLbl.setAutoFillBackground(True) self._solvableLbl.setText("No") def _resetTimer(self): ''' When the algorithm run speed is modified by the user this resets the algorithm timer. ''' if self._spdSetting == 3: while not self._alg.isDone() and self._alg.isSolvable(): self._alg.step() self._worldWidget.repaint() self._timer.stop() self._runBtn.setText("Run") self._checkTerminalConditions() else: timeOut = 1 if self._spdSetting == 0: timeOut = 500 elif self._spdSetting == 1: timeOut = 250 elif self._spdSetting == 2: timeOut = 1 self._timer.start(timeOut)
class CookieCutterWidget(QWidget): "CookieCutter UI" FILE_FILTER = u'Inselect cookie cutter (*{0})'.format( CookieCutter.EXTENSION ) def __init__(self, parent=None): super(CookieCutterWidget, self).__init__(parent) # Configure the UI self._create_actions() self.button = QPushButton("Cookie cutter") self.button.setMaximumWidth(250) self.button.setStyleSheet("text-align: left") self.popup = QMenu() self.inject_actions(self.popup) self.button.setMenu(self.popup) layout = QHBoxLayout() layout.addWidget(self.button) self.setLayout(layout) def _create_actions(self): self.save_to_new_action = QAction( "Save boxes to new cookie cutter...", self ) self.choose_action = QAction( "Choose...", self, triggered=self.choose ) self.clear_action = QAction( "Do not use a cookie cutter", self, triggered=self.clear ) self.apply_current_action = QAction("Apply", self) def inject_actions(self, menu): "Adds cookie cutter actions to menu" menu.addAction(self.choose_action) menu.addAction(self.apply_current_action) menu.addSeparator() menu.addAction(self.clear_action) menu.addSeparator() menu.addAction(self.save_to_new_action) @report_to_user def clear(self): "Clears the choice of cookie cutter" cookie_cutter_choice().clear() @report_to_user def choose(self): "Shows a 'choose cookie cutter' file dialog" debug_print('CookieCutterWidget.choose_cookie_cutter') path, selectedFilter = QFileDialog.getOpenFileName( self, "Choose cookie cutter", unicode(cookie_cutter_choice().last_directory()), self.FILE_FILTER ) if path: # Save the user's choice cookie_cutter_choice().load(path) def sync_actions(self, has_document, has_rows): "Sync state of actions" debug_print('CookieCutterWidget.sync_ui') current = cookie_cutter_choice().current has_current = cookie_cutter_choice().current is not None name = current.name if current else 'Cookie cutter' # Truncate text to fit button metrics = QFontMetrics(self.button.font()) elided = metrics.elidedText( name, Qt.ElideRight, self.button.width() - 25 ) self.button.setText(elided) self.save_to_new_action.setEnabled(has_rows) self.clear_action.setEnabled(has_current) self.apply_current_action.setEnabled(has_document and has_current)
def create_browser_pane(self, title): # Create the pane widget pane = QWidget() layout = QVBoxLayout() pane.setLayout(layout) # Create a label for the title title_bar = QLabel("") # title_bar.setFixedHeight(32) title_bar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) title_bar.show() layout.addWidget(title_bar) # Create the "address" box address_bar = QLineEdit() layout.addWidget(address_bar) # todo: we could add some tool buttons here.. toolbar_layout = QHBoxLayout() toolbar = QWidget() toolbar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) toolbar.setLayout(toolbar_layout) tool_stop = QPushButton() tool_stop.setText('Stop') toolbar_layout.addWidget(tool_stop) tool_back = QPushButton() tool_back.setText('Back') toolbar_layout.addWidget(tool_back) tool_forward = QPushButton() tool_forward.setText('Forward') toolbar_layout.addWidget(tool_forward) tool_reload = QPushButton() tool_reload.setText('Reload') toolbar_layout.addWidget(tool_reload) layout.addWidget(toolbar) # Create the web view web_view = QWebView() web_view.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) layout.addWidget(web_view) # Create a status bar status_bar = QLabel("") status_bar.setFixedHeight(32) status_bar.show() status_bar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) layout.addWidget(status_bar) # Attach signal handlers address_bar.editingFinished.connect(functools.partial( self._addrbar_changed, address_bar, web_view)) web_view.loadStarted.connect( lambda: status_bar.setText('Loading...')) web_view.loadProgress.connect( lambda p: status_bar.setText('Loading ({0}%)...'.format(p))) web_view.loadFinished.connect( lambda p: status_bar.setText('Ready.'.format(p))) web_view.statusBarMessage.connect(status_bar.setText) web_view.titleChanged.connect(title_bar.setText) web_view.urlChanged.connect(functools.partial( self._url_changed, web_view)) web_view.urlChanged.connect( lambda url: address_bar.setText(url.toString())) # Connect tool buttons tool_stop.clicked.connect(web_view.stop) tool_back.clicked.connect(web_view.back) tool_forward.clicked.connect(web_view.forward) tool_reload.clicked.connect(web_view.reload) return { 'main': pane, 'layout': layout, 'title': title_bar, 'address': address_bar, 'web_view': web_view, 'status': status_bar, }
class Widget(QDialog): def __init__(self, parent= None): super(Widget, self).__init__(parent, QtCore.Qt.WindowStaysOnTopHint) #QtGui.QMainWindow.__init__(self, None, QtCore.Qt.WindowStaysOnTopHint) #icon = style.standardIcon( # QtGui.QStyle.SP_MessageBoxCritical, None, widget) #self.setWindowIcon(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxCritical)) #self.setIcon(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxCritical)) #self.setIcon(self.style().standardIcon(QStyle.SP_DirIcon)) #QtGui.QIcon(QtGui.QMessageBox.Critical)) #icon = QtGui.QIcon() #icon.addPixmap(QtGui.QPixmap("icons/157-stats-bars.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) #Widget.setWindowIcon(icon) self.txt = QLabel() self.txt.setText("This will remove ALL Suffix from selection objects. \nDo you want to continue?\n\n\'suffix\'") self.le = QLineEdit() self.le.setObjectName("suffix_filter") self.le.setText(".step") self.pb = QPushButton() self.pb.setObjectName("OK") self.pb.setText("OK") self.pbC = QPushButton() self.pbC.setObjectName("Cancel") self.pbC.setText("Cancel") layout = QVBoxLayout() layout.addWidget(self.txt) layout.addWidget(self.le) layout.addWidget(self.pb) layout.addWidget(self.pbC) self.setWindowTitle("Warning ...") #self.setWindowIcon(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxCritical)) # btn_folder = QPushButton("Folder") # btn_folder.setIcon(self.style().standardIcon(QStyle.SP_DirIcon)) # # btn_one = QPushButton("Play") # btn_one.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) # # btn_two = QPushButton("Stop") # btn_two.setIcon(self.style().standardIcon(QStyle.SP_MediaStop)) # # btn_three = QPushButton("Pause") # btn_three.setIcon(self.style().standardIcon(QStyle.SP_MediaPause)) #layout = QHBoxLayout() #layout.addWidget(btn_folder) #layout.addWidget(btn_one) #layout.addWidget(btn_two) #layout.addWidget(btn_three) self.setLayout(layout) #self.setLayout(layout) self.connect(self.pb, SIGNAL("clicked()"),self.OK_click) self.connect(self.pbC, SIGNAL("clicked()"),self.Cancel_click) def OK_click(self): # shost is a QString object filtered = self.le.text() print (filtered) self.close() def Cancel_click(self): # shost is a QString object filtered = '.stp' print (filtered) self.close()
class ui(QWidget): def __init__(self): QWidget.__init__(self) self.setupUI() self.id = 1 self.lines = [] self.editable = True self.des_sort = True self.faker = Factory.create() self.btn_add.clicked.connect(self.add_line) self.btn_del.clicked.connect(self.del_line) self.btn_modify.clicked.connect(self.modify_line) self.btn_select_line.clicked.connect(self.select_line) self.btn_select_single.clicked.connect(self.deny_muti_line) self.btn_sort.clicked.connect(self.sortItem) self.btn_set_header.clicked.connect(self.setheader) self.btn_set_middle.clicked.connect(self.middle) self.table.cellChanged.connect(self.cellchange) self.btn_noframe.clicked.connect(self.noframe) # # Sess = sessionmaker(bind = engine) def setupUI(self): self.setWindowTitle(windowTital) self.resize(640, 480) self.table = QTableWidget(self) self.btn_add = QPushButton(u'增加') self.btn_del = QPushButton(u'删除') self.btn_modify = QPushButton(u'可以编辑') self.btn_select_line = QPushButton(u'选择整行') self.btn_select_single = QPushButton(u'禁止选多行') self.btn_sort = QPushButton(u'以分数排序') self.btn_set_header = QPushButton(u'标头设置') self.btn_set_middle = QPushButton(u'文字居中加颜色') self.btn_noframe = QPushButton(u'取消边框颜色交替') self.spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) self.vbox = QVBoxLayout() self.vbox.addWidget(self.btn_add) self.vbox.addWidget(self.btn_del) self.vbox.addWidget(self.btn_modify) self.vbox.addWidget(self.btn_select_line) self.vbox.addWidget(self.btn_select_single) self.vbox.addWidget(self.btn_sort) self.vbox.addWidget(self.btn_set_header) self.vbox.addWidget(self.btn_set_middle) self.vbox.addWidget(self.btn_noframe) self.vbox.addSpacerItem( self.spacerItem) #可以用addItem也可以用addSpacerItem方法添加,没看出哪里不一样 self.txt = QLabel() self.txt.setMinimumHeight(50) self.vbox2 = QVBoxLayout() self.vbox2.addWidget(self.table) self.vbox2.addWidget(self.txt) self.hbox = QHBoxLayout() self.hbox.addLayout(self.vbox2) self.hbox.addLayout(self.vbox) self.setLayout(self.hbox) self.table.setColumnCount(4) ##设置列数 self.headers = [u'id', u'选择', u'姓名', u'成绩', u'住址'] self.table.setHorizontalHeaderLabels(self.headers) self.show() def add_line(self): self.table.cellChanged.disconnect() row = self.table.rowCount() self.table.setRowCount(row + 1) id = str(self.id) ck = QCheckBox() h = QHBoxLayout() h.setAlignment(Qt.AlignCenter) h.addWidget(ck) w = QWidget() w.setLayout(h) name = self.faker.name() score = str(random.randint(50, 99)) add = self.faker.address() self.table.setItem(row, 0, QTableWidgetItem(id)) self.table.setCellWidget(row, 1, w) self.table.setItem(row, 2, QTableWidgetItem(name)) self.table.setItem(row, 3, QTableWidgetItem(score)) self.table.setItem(row, 4, QTableWidgetItem(add)) self.id += 1 self.lines.append([id, ck, name, score, add]) self.settext(u'自动生成随机一行数据!,checkbox设置为居中显示') self.table.cellChanged.connect(self.cellchange) def del_line(self): removeline = [] for line in self.lines: if line[1].isChecked(): row = self.table.rowCount() for x in range(row, 0, -1): if line[0] == self.table.item(x - 1, 0).text(): self.table.removeRow(x - 1) removeline.append(line) for line in removeline: self.lines.remove(line) self.settext(u'删除在左边checkbox中选中的行,使用了一个笨办法取得行号\n,不知道有没有其他可以直接取得行号的方法!') def modify_line(self): if self.editable == True: self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.btn_modify.setText(u'禁止编辑') self.editable = False else: self.table.setEditTriggers(QAbstractItemView.AllEditTriggers) self.btn_modify.setText(u'可以编辑') self.editable = True self.settext(u'设置,是否可以编辑整个表格') def select_line(self): if self.table.selectionBehavior() == 0: self.table.setSelectionBehavior(1) self.btn_select_line.setStyleSheet('background-color:lightblue') else: self.table.setSelectionBehavior(0) self.btn_select_line.setStyleSheet('') self.settext(u'默认时,点击单元格,只可选择一个格,此处设置为可选择整行') def deny_muti_line(self): if self.table.selectionMode() in [2, 3]: self.table.setSelectionMode(QAbstractItemView.SingleSelection) self.btn_select_single.setStyleSheet('background-color:lightblue') else: self.table.setSelectionMode(QAbstractItemView.ExtendedSelection) self.btn_select_single.setStyleSheet('') self.settext(u'点击时会轮换以多行或单行选择,默认是可以同时选择多行') def sortItem(self): if self.des_sort == True: self.table.sortItems(3, Qt.DescendingOrder) self.des_sort = False self.btn_sort.setStyleSheet('background-color:lightblue') self.table.setSortingEnabled(True) # 设置表头可以自动排序 else: self.table.sortItems(3, Qt.AscendingOrder) self.des_sort = True self.btn_sort.setStyleSheet('background-color:lightblue') self.table.setSortingEnabled(False) self.settext(u'点击时会轮换以升序降序排列,但排序时,会使自动列宽失效!') def setheader(self): font = QFont(u'微软雅黑', 12) font.setBold(True) self.table.horizontalHeader().setFont(font) # 设置表头字体 self.table.setColumnWidth(0, 50) self.table.setColumnWidth(1, 50) self.table.setColumnWidth(3, 100) self.table.horizontalHeader().setSectionResizeMode( 2, QHeaderView.Stretch) self.table.horizontalHeader().setStyleSheet( 'QHeaderView::section{background:gray}') self.table.horizontalHeader().setFixedHeight(50) self.table.setColumnHidden(0, True) self.btn_set_header.setStyleSheet('background-color:lightblue') self.settext( u'设置标头字体及字号,隐藏ID列,设置标头除姓名外全部为固定宽度\n,设置姓名列自动扩展宽度,设置标头行高,设置标头背景色') def middle(self): self.btn_set_middle.setStyleSheet('background-color:lightblue') self.table.setStyleSheet('color:green;') row = self.table.rowCount() for x in range(row): for y in range(4): if y != 1: item = self.table.item(x, y) item.setTextAlignment(Qt.AlignCenter) else: pass self.btn_set_middle.setStyleSheet('background-color:lightblue') self.settext(u'将文字居中显示,设置文字颜色') def cellchange(self, row, col): item = self.table.item(row, col) txt = item.text() self.settext(u'第%s行,第%s列 , 数据改变为:%s' % (row, col, txt)) def noframe(self): self.table.setAlternatingRowColors(True) self.table.setFrameStyle(QFrame.NoFrame) self.table.setStyleSheet('color:green;' 'gridline-color:white;' 'border:0px solid gray') self.settext(u'取消表的框线,\n 取消表格内框') def settext(self, txt): font = QFont(u'微软雅黑', 10) self.txt.setFont(font) self.txt.setText(txt)
class MainWindow(QWidget, object): # noinspection PyUnresolvedReferences def __init__(self): super(MainWindow, self).__init__() self.clip_filename = None self.audio_filename = None layout = QBoxLayout(QBoxLayout.TopToBottom) clip_row = QBoxLayout(QBoxLayout.LeftToRight) self.clip_button = QPushButton() self.clip_button.clicked.connect(self.open_clip) self.clip_button.setText(self.tr("Open clip")) clip_row.addWidget(self.clip_button) self.clip_view = QLabel() clip_row.addWidget(self.clip_view) clip_frame = QFrame() clip_frame.setLayout(clip_row) layout.addWidget(clip_frame) audio_row = QBoxLayout(QBoxLayout.LeftToRight) self.audio_button = QPushButton() self.audio_button.clicked.connect(self.open_audio) self.audio_button.setText(self.tr("Open audio")) audio_row.addWidget(self.audio_button) self.audio_view = QLabel() audio_row.addWidget(self.audio_view) audio_frame = QFrame() audio_frame.setLayout(audio_row) layout.addWidget(audio_frame) save_row = QBoxLayout(QBoxLayout.LeftToRight) self.save_button = QPushButton() self.save_button.clicked.connect(self.save) self.save_button.setText(self.tr("Save synced clip")) save_row.addWidget(self.save_button) save_frame = QFrame() save_frame.setLayout(save_row) layout.addWidget(save_frame) self.update_save_button() layout.addStretch() self.setLayout(layout) self.show() def open_clip(self): self.clip_filename = QFileDialog.getOpenFileName( self, self.tr("Open Clip"), os.getcwd(), self. tr("Video Files [.mp4, .ogv, .mkv, .avi, .mov] (*.mp4 *.ogv *.mkv *.avi *.mov);;" + "Audio Files [.flac, .ogg, .wav, .mp3] (*.flac *.ogg *.wav *.mp3)" ))[0] self.clip_view.setText(self.clip_filename) self.update_save_button() def open_audio(self): self.audio_filename = QFileDialog.getOpenFileName( self, self.tr("Open Audio"), os.getcwd(), self. tr("Audio Files [.flac, .ogg, .wav, .mp3] (*.flac *.ogg *.wav *.mp3)" ))[0] self.audio_view.setText(self.audio_filename) self.update_save_button() def update_save_button(self): self.save_button.setEnabled( bool(self.clip_filename and self.audio_filename)) def save(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setDefaultSuffix("avi") dialog.setDirectory(os.getcwd()) dialog.setNameFilter(self.tr("Video Files [.avi] (*.avi)")) if dialog.exec_(): output_file_name = dialog.selectedFiles()[0] correlate(self.clip_filename, self.audio_filename, output_file_name)
class SyncView(View): """`View` derived class. Defines the sync widget""" sync = Signal((str,)) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(SyncView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(580, 340) self.status.setMessage('Ready') def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() pathLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(10) fieldsLayout.addStretch(50) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addWidget(self.localdirLabel) pathLayout.addWidget(self.localdirEdit) pathLayout.addWidget(self.browseButton) fieldsLayout.addLayout(pathLayout) buttonLayout.addStretch(50) buttonLayout.addWidget(self.syncButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(10) fieldsLayout.addWidget(self.statusLabel) fieldsLayout.addWidget(self.status) fieldsLayout.addStretch(80) mainLayout.addLayout(fieldsLayout, 60) mainLayout.addStretch(10) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 450 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.localdirLabel = QLabel(self) self.localdirEdit = QLineEdit(self) self.localdirLabel.setText('Choose a folder') self.localdirLabel.setFont(labelsFont) self.localdirEdit.setFixedWidth(fieldsWidth) self.localdirEdit.setReadOnly(False) self.localdirEdit.setFont(editsFont) self.browseButton = QPushButton(self) self.browseButton.setText('Browse') self.browseButton.setFont(labelsFont) self.syncButton = QPushButton(self) self.syncButton.setText('Sync') self.syncButton.setFont(labelsFont) self.browseButton.clicked.connect(self.onBrowseClicked) self.syncButton.clicked.connect(self.onSyncClicked) settings = get_settings() self.localdirEdit.setText(settings.value(SettingsKeys['localdir'], '')) self.statusLabel = QLabel(self) self.statusLabel.setText('Status') self.statusLabel.setFont(View.labelsFont()) self.status = StatusArea(self) @Slot() def onBrowseClicked(self): """Slot. Called when the user clicks on the `browseButton` button""" # Presents the user with a native directory selector window localdir = QFileDialog.getExistingDirectory() localdir = QDir.fromNativeSeparators(localdir) if len(localdir) > 0: # If `localdir`'s value is good, store it using a `QSettings` object # and triggers a sync request. # Careful with '\' separators on Windows. localdir = QDir.toNativeSeparators(localdir) get_settings().setValue(SettingsKeys['localdir'], localdir) self.localdirEdit.setText(localdir) @Slot() def onSyncClicked(self): """Slot. Called when the user clicks on the `syncButton` button""" localdir = self.localdirEdit.text() if len(localdir) > 0: self.syncButton.setEnabled(False) self.sync.emit(localdir)
class UI(gobject.GObject): __gsignals__ = { 'command' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)) } def __init__(self,args,continuous): self.continuous = continuous gobject.GObject.__init__(self) #start by making our app self.app = QApplication(args) #make a window self.window = QMainWindow() #give the window a name self.window.setWindowTitle("BlatherQt") self.window.setMaximumSize(400,200) center = QWidget() self.window.setCentralWidget(center) layout = QVBoxLayout() center.setLayout(layout) #make a listen/stop button self.lsbutton = QPushButton("Listen") layout.addWidget(self.lsbutton) #make a continuous button self.ccheckbox = QCheckBox("Continuous Listen") layout.addWidget(self.ccheckbox) #connect the buttons self.lsbutton.clicked.connect(self.lsbutton_clicked) self.ccheckbox.clicked.connect(self.ccheckbox_clicked) #add a label to the UI to display the last command self.label = QLabel() layout.addWidget(self.label) #add the actions for quiting quit_action = QAction(self.window) quit_action.setShortcut('Ctrl+Q') quit_action.triggered.connect(self.accel_quit) self.window.addAction(quit_action) def accel_quit(self): #emit the quit self.emit("command", "quit") #function for managing the continuou listening check box being clicked. When it is clicked it #emits an event for blather to let blather know that the state of things has changed. This is #caught by blather's process_command function. def ccheckbox_clicked(self): checked = self.ccheckbox.isChecked() if checked: #disable lsbutton self.lsbutton.setEnabled(False) self.lsbutton_stopped() self.emit('command', "continuous_listen") self.set_icon_active() else: self.lsbutton.setEnabled(True) self.emit('command', "continuous_stop") self.set_icon_inactive() #functions related to the listen button. lsbutton_stopped is a quasi place holder for if I #want to expand the end of listening to do other things as well. def lsbutton_stopped(self): self.lsbutton.setText("Listen") def lsbutton_clicked(self): val = self.lsbutton.text() if val == "Listen": self.emit("command", "listen") self.lsbutton.setText("Stop") #clear the label self.label.setText("") self.set_icon_active() else: self.lsbutton_stopped() self.emit("command", "stop") self.set_icon_inactive() #called by blather right before the main loop is started. Mainloop is handled by gst. def run(self): self.set_icon_inactive() self.window.show() if self.continuous: self.set_icon_active() self.ccheckbox.setCheckState(Qt.Checked) self.ccheckbox_clicked() self.app.exec_() self.emit("command", "quit") #This function is called when it hears a pause in the audio. #This is called after the command has been sent of to the commander. def finished(self, text): #if the continuous isn't pressed if not self.ccheckbox.isChecked(): self.lsbutton_stopped() self.label.setText(text) #functions dealing with the icon def set_icon(self, icon): self.window.setWindowIcon(QIcon(icon)) def set_icon_active_asset(self, i): self.icon_active = i def set_icon_inactive_asset(self, i): self.icon_inactive = i def set_icon_active(self): self.window.setWindowIcon(QIcon(self.icon_active)) def set_icon_inactive(self): self.window.setWindowIcon(QIcon(self.icon_inactive))
class LoginView(View): """`View` derived class. Defines the log in widget""" login = Signal((str, str, str, bool,)) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(LoginView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(250, 340) def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() ftpInfoLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(20) fieldsLayout.addStretch(80) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addStretch(20) ftpInfoLayout.addWidget(self.hostLabel, 50, Qt.AlignLeft) ftpInfoLayout.addStretch(20) ftpInfoLayout.addWidget(self.sslLabel, 20, Qt.AlignRight) ftpInfoLayout.addWidget(self.sslCheck, 10, Qt.AlignRight) fieldsLayout.addLayout(ftpInfoLayout) fieldsLayout.addWidget(self.hostEdit) fieldsLayout.addWidget(self.usernameLabel) fieldsLayout.addWidget(self.usernameEdit) fieldsLayout.addWidget(self.passwdLabel) fieldsLayout.addWidget(self.passwdEdit) fieldsLayout.addStretch(30) buttonLayout.addStretch(50) buttonLayout.addWidget(self.loginButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(20) mainLayout.addLayout(fieldsLayout, 30) mainLayout.addStretch(20) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 200 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.hostLabel = QLabel(self) self.hostEdit = QLineEdit(self) self.sslLabel = QLabel(self) self.sslCheck = QCheckBox(self) self.hostLabel.setText('FTP Location') self.hostLabel.setFont(labelsFont) self.hostEdit.setFixedWidth(fieldsWidth) self.hostEdit.setFont(editsFont) self.sslLabel.setText('SSL') self.sslLabel.setFont(labelsFont) self.usernameLabel = QLabel(self) self.usernameEdit = QLineEdit(self) self.usernameLabel.setText('Username') self.usernameLabel.setFont(labelsFont) self.usernameEdit.setFixedWidth(fieldsWidth) self.usernameEdit.setFont(editsFont) self.passwdLabel = QLabel(self) self.passwdEdit = QLineEdit(self) self.passwdLabel.setText('Password') self.passwdLabel.setFont(labelsFont) self.passwdEdit.setFixedWidth(fieldsWidth) self.passwdEdit.setEchoMode(QLineEdit.Password) self.passwdEdit.setFont(editsFont) self.passwdEdit.returnPressed.connect(self.onLoginClicked) self.loginButton = QPushButton(self) self.loginButton.setText('Login') self.loginButton.setFont(labelsFont) self.loginButton.setFixedWidth(fieldsWidth / 2) self.loginButton.clicked.connect(self.onLoginClicked) # Sets previously stored values into the fields, if any settings = get_settings() self.hostEdit.setText(settings.value(SettingsKeys['host'], '')) self.usernameEdit.setText(settings.value(SettingsKeys['username'], '')) self.passwdEdit.setText(crypt.decrypt(settings.value(SettingsKeys['passwd'], ''))) # Unicode to boolean conversion ssl = settings.value(SettingsKeys['ssl'], u'true') ssl = True if ssl == u'true' else False self.sslCheck.setChecked(ssl) @Slot() def onLoginClicked(self): """ Slot. Called on the user clicks on the `loginButton` button """ # Takes out the user input from the fields host = self.hostEdit.text() username = self.usernameEdit.text() passwd = self.passwdEdit.text() ssl = self.sslCheck.isChecked() print 'Logging in: %s, %s, %s' % (host, username, '*' * len(passwd)) if len(host) > 0: # If the fields are valid, store them using a `QSettings` object # and triggers a log in request settings = get_settings() settings.setValue(SettingsKeys['host'], host) settings.setValue(SettingsKeys['username'], username) settings.setValue(SettingsKeys['passwd'], crypt.encrypt(passwd)) settings.setValue(SettingsKeys['ssl'], ssl) self.setEnabled(False) self.login.emit(host.strip(), username, passwd, ssl) @Slot() def onFailedLogIn(self): """ Slot. Called when the log in request fails """ # Enables the fields again for user input self.setEnabled(True)
class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(598, 450) self.icon = QIcon(":/icons/uglytheme/48x48/polibeepsync.png") Form.setWindowIcon(self.icon) Form.setLocale(QLocale(QLocale.English, QLocale.UnitedStates)) self.verticalLayout = QVBoxLayout(Form) self.verticalLayout.setObjectName("verticalLayout") self.tabWidget = QTabWidget(Form) self.tabWidget.setObjectName("tabWidget") # Tab General Settings self.tab = QWidget() self.tab.setObjectName("tab") self.horizontalLayout = QHBoxLayout(self.tab) self.horizontalLayout.setObjectName("horizontalLayout") self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.gridLayout = QGridLayout() self.gridLayout.setObjectName("gridLayout") self.label_2 = QLabel(self.tab) self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1) self.label = QLabel(self.tab) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 1, 0, 1, 1) self.password = QLineEdit(self.tab) self.password.setMaximumSize(QSize(139, 16777215)) self.password.setEchoMode(QLineEdit.Password) self.password.setObjectName("password") self.gridLayout.addWidget(self.password, 3, 1, 1, 1) self.userCode = QLineEdit(self.tab) self.userCode.setMaximumSize(QSize(139, 16777215)) self.userCode.setText("") self.userCode.setObjectName("userCode") self.gridLayout.addWidget(self.userCode, 1, 1, 1, 1) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 1, 2, 1, 1) self.verticalLayout_2.addLayout(self.gridLayout) self.trylogin = QPushButton(self.tab) self.trylogin.setMaximumSize(QSize(154, 16777215)) self.trylogin.setObjectName("trylogin") self.verticalLayout_2.addWidget(self.trylogin) self.login_attempt = QLabel(self.tab) self.login_attempt.setText("Logging in, please wait.") self.login_attempt.setStyleSheet("color: rgba(0, 0, 0, 0);") self.login_attempt.setObjectName("login_attempt") self.verticalLayout_2.addWidget(self.login_attempt) spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem1) self.horizontalLayout_3 = QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.label_4 = QLabel(self.tab) self.label_4.setObjectName("label_4") self.horizontalLayout_3.addWidget(self.label_4) self.rootfolder = QLineEdit(self.tab) self.rootfolder.setMinimumSize(QSize(335, 0)) self.rootfolder.setMaximumSize(QSize(335, 16777215)) self.rootfolder.setInputMask("") self.rootfolder.setReadOnly(True) self.rootfolder.setObjectName("rootfolder") self.horizontalLayout_3.addWidget(self.rootfolder) self.changeRootFolder = QPushButton(self.tab) self.changeRootFolder.setObjectName("changeRootFolder") self.horizontalLayout_3.addWidget(self.changeRootFolder) spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem2) self.verticalLayout_2.addLayout(self.horizontalLayout_3) self.horizontalLayout_5 = QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.label_5 = QLabel(self.tab) self.label_5.setObjectName("label_5") self.horizontalLayout_5.addWidget(self.label_5) self.timerMinutes = QSpinBox(self.tab) self.timerMinutes.setObjectName("timerMinutes") self.horizontalLayout_5.addWidget(self.timerMinutes) self.label_6 = QLabel(self.tab) self.label_6.setObjectName("label_6") self.horizontalLayout_5.addWidget(self.label_6) self.syncNow = QPushButton(self.tab) self.syncNow.setObjectName("syncNow") self.horizontalLayout_5.addWidget(self.syncNow) spacerItem3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_5.addItem(spacerItem3) self.verticalLayout_2.addLayout(self.horizontalLayout_5) self.addSyncNewCourses = QCheckBox(self.tab) self.addSyncNewCourses.setObjectName("addSyncNewCourses") self.verticalLayout_2.addWidget(self.addSyncNewCourses) self.horizontalLayout.addLayout(self.verticalLayout_2) self.tabWidget.addTab(self.tab, "") # Tab Courses self.tab_2 = QWidget() self.tab_2.setObjectName("tab_2") self.horizontalLayout_2 = QHBoxLayout(self.tab_2) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.verticalLayout_3 = QVBoxLayout() self.verticalLayout_3.setObjectName("verticalLayout_3") self.horizontalLayout_6 = QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.refreshCourses = QPushButton(self.tab_2) self.refreshCourses.setObjectName("refreshCourses") self.horizontalLayout_6.addWidget(self.refreshCourses) spacerItem4 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_6.addItem(spacerItem4) self.verticalLayout_3.addLayout(self.horizontalLayout_6) self.coursesView = CoursesListView(self.tab_2) self.coursesView.setObjectName("coursesView") self.verticalLayout_3.addWidget(self.coursesView) self.horizontalLayout_2.addLayout(self.verticalLayout_3) self.tabWidget.addTab(self.tab_2, "") # Tab Status self.tab_3 = QWidget() self.tab_3.setObjectName("tab_3") self.horizontalLayout_7 = QHBoxLayout(self.tab_3) self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.verticalLayout_4 = QVBoxLayout() self.verticalLayout_4.setObjectName("verticalLayout_4") self.horizontalLayout_8 = QHBoxLayout() self.horizontalLayout_8.setObjectName("horizontalLayout_8") self.about = QPushButton(self.tab_3) self.about.setObjectName("about") self.horizontalLayout_8.addWidget(self.about) spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_8.addItem(spacerItem5) self.verticalLayout_4.addLayout(self.horizontalLayout_8) self.status = QTextEdit(self.tab_3) self.status.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse) self.status.setObjectName("status") self.verticalLayout_4.addWidget(self.status) self.horizontalLayout_7.addLayout(self.verticalLayout_4) self.tabWidget.addTab(self.tab_3, "") self.tab_4 = QWidget() self.tab_4.setObjectName("tab_4") self.verticalLayout.addWidget(self.tabWidget) self.okButton = QDialogButtonBox(Form) self.okButton.setStandardButtons(QDialogButtonBox.Ok) self.okButton.setObjectName("okButton") self.okButton.clicked.connect(self.hide) self.verticalLayout.addWidget(self.okButton) self.statusLabel = QLabel(Form) self.statusLabel.setObjectName("statusLabel") self.verticalLayout.addWidget(self.statusLabel) self.retranslateUi(Form) self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle("poliBeePsync") if pysideVersion == '1.2.2': self.label_2.setText( QApplication.translate("Form", "Password", None, QApplication.UnicodeUTF8)) self.label.setText( QApplication.translate("Form", "User code", None, QApplication.UnicodeUTF8)) self.trylogin.setText( QApplication.translate("Form", "Try login credentials", None, QApplication.UnicodeUTF8)) self.login_attempt.setText( QApplication.translate("Form", "Login successful", None, QApplication.UnicodeUTF8)) self.label_4.setText( QApplication.translate("Form", "Root folder", None, QApplication.UnicodeUTF8)) self.changeRootFolder.setText( QApplication.translate("Form", "Change", None, QApplication.UnicodeUTF8)) self.label_5.setText( QApplication.translate("Form", "Sync every", None, QApplication.UnicodeUTF8)) self.label_6.setText( QApplication.translate("Form", "minutes", None, QApplication.UnicodeUTF8)) self.syncNow.setText( QApplication.translate("Form", "Sync now", None, QApplication.UnicodeUTF8)) self.addSyncNewCourses.setText( QApplication.translate( "Form", "Automatically add and sync new available courses", None, QApplication.UnicodeUTF8)) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab), QApplication.translate("Form", "General settings", None, QApplication.UnicodeUTF8)) self.refreshCourses.setText( QApplication.translate("Form", "Refresh list", None, QApplication.UnicodeUTF8)) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab_2), QApplication.translate("Form", "Courses", None, QApplication.UnicodeUTF8)) self.about.setText( QApplication.translate("Form", "About", None, QApplication.UnicodeUTF8)) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab_3), QApplication.translate("Form", "Status", None, QApplication.UnicodeUTF8)) else: self.label_2.setText( QApplication.translate("Form", "Password", None)) self.label.setText( QApplication.translate("Form", "User code", None)) self.trylogin.setText( QApplication.translate("Form", "Try login credentials", None)) self.login_attempt.setText( QApplication.translate("Form", "Login successful", None)) self.label_4.setText( QApplication.translate("Form", "Root folder", None)) self.changeRootFolder.setText( QApplication.translate("Form", "Change", None)) self.label_5.setText( QApplication.translate("Form", "Sync every", None)) self.label_6.setText( QApplication.translate("Form", "minutes", None)) self.syncNow.setText( QApplication.translate("Form", "Sync now", None)) self.addSyncNewCourses.setText( QApplication.translate( "Form", "Automatically add and sync new available courses", None)) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab), QApplication.translate("Form", "General settings", None)) self.refreshCourses.setText( QApplication.translate("Form", "Refresh list", None)) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab_2), QApplication.translate("Form", "Courses", None)) self.about.setText(QApplication.translate("Form", "About", None)) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab_3), QApplication.translate("Form", "Status", None))
def _init_widgets(self): layout = QGridLayout() row = 0 # name name_label = QLabel(self) name_label.setText("Name") txt_name = QLineEdit(self) txt_name.setText(NameGenerator.random_name()) self._name_edit = txt_name layout.addWidget(name_label, row, 0) layout.addWidget(txt_name, row, 1) row += 1 # base state state_label = QLabel(self) state_label.setText('Base state') base_state_combo = QStateComboBox(self._workspace.instance.states, self) self._base_state_combo = base_state_combo layout.addWidget(state_label, row, 0) layout.addWidget(base_state_combo, row, 1) row += 1 # mode mode_label = QLabel(self) mode_label.setText("Mode") mode_combo = QComboBox(self) mode_combo.addItem("Symbolic", "symbolic") mode_combo.addItem("Static", "static") mode_combo.addItem("Fast-path", "fastpath") self._mode_combo = mode_combo layout.addWidget(mode_label, row, 0) layout.addWidget(mode_combo, row, 1) row += 1 # custom code code_label = QLabel(self) code_label.setText('Initialization code') self._editor = pyqode.core.api.CodeEdit() self._editor.modes.append( pyqode.core.modes.PygmentsSyntaxHighlighter( self._editor.document())) self._editor.modes.append(pyqode.core.modes.CaretLineHighlighterMode()) self._editor.insertPlainText(self.INITIAL_INIT_CODE) layout.addWidget(code_label, row, 0) layout.addWidget(self._editor, row, 1) row += 1 # buttons ok_button = QPushButton(self) ok_button.setText('OK') ok_button.clicked.connect(self._on_ok_clicked) self._ok_button = ok_button cancel_button = QPushButton(self) cancel_button.setText('Cancel') cancel_button.clicked.connect(self._on_cancel_clicked) buttons_layout = QHBoxLayout() buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) self.main_layout.addLayout(layout) self.main_layout.addLayout(buttons_layout)
def __init__(self, parent=None): """Default class constructor.""" super(AboutDialog, self).__init__(parent) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) if parent: self.gImgDir = parent.gImgDir self.gIconDir = parent.gIconDir elif __name__ == '__main__': self.gImgDir = gAppDir + os.sep + 'images' self.gIconDir = gAppDir + os.sep + 'icons' + os.sep + 'default' # The tiled theme background texture. self.bgLogo = QPixmap(self.gImgDir + os.sep + 'texture-spirals.png') self.bgBrush = QBrush(self.bgLogo) self.setWhatsThis(self.tr("""\ The background is a tiled image of an actual design that was stitched out during the pre-alpha stage. It was created by Nina Paley and Theodore Gray using Mathematica in conjunction with our software. They have graciously allowed us to use it for the project in whichever way we wish. We thought it looked so good, that it has become the new theme for Embroidermodder 2. To check out some of the more interesting embroidery projects they are working on, visit http://blog.ninapaley.com/""")) self.imgLbl = EmbroidermodderLogo(self) aboutLbl = QTextBrowser(self) aboutLbl.setReadOnly(True) aboutLbl.setOpenExternalLinks(True) aboutLbl.setText('<b>%s</b>' % '<br>'.join(__doc__.split('\n'))) aboutLbl.setWhatsThis(self.tr('This is the AWESOME people that brought Embroidermodder 2 to life.')) # We want very slight opacity of the white background # so the seamless texture shows slightly through. opacityStyleSheet = """\ QTextEdit:read-only { color: rgb(50, 50, 50); font-size: 12px; font-weight: bold; background-color: rgba(255, 255, 255, 240); border: 1px solid rgba(0, 0, 0, 255); } """ aboutLbl.setStyleSheet(opacityStyleSheet) op = QGraphicsOpacityEffect(aboutLbl) op.setOpacity(0.95) aboutLbl.setGraphicsEffect(op) self.notebook = QTabWidget(self) self.notebook.setMinimumWidth(500) self.notebook.addTab(aboutLbl, self.tr('About')) self.notebook.setTabIcon(0, QIcon(self.gIconDir + os.sep + 'app.png')) self.notebook.setTabIcon(1, QIcon(self.gImgDir + os.sep + 'kickstarter-logo-k-color.png')) notebookStyleSheet = """\ QTabWidget::pane { /* The tab widget frame */ border-top: 1px solid #000000; position: absolute; top: -0.5em; } QTabWidget::tab-bar { alignment: center; } /* Style the tab using the tab sub-control. Note that it reads QTabBar _not_ QTabWidget */ QTabBar::tab { margin-top: 2px; /* make non-selected tabs look smaller */ font-size: 14px; font-weight: bold; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #E1E1E1, stop: 0.4 #DDDDDD, stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3); border: 1px solid #000000; /* border-bottom-color: #C2C7CB; */ /* same as the pane color */ border-top-left-radius: 4px; border-top-right-radius: 4px; min-width: 40ex; min-height: 5ex; padding: 3px; } QTabBar::tab:selected { margin-top: 0px; font-size: 16px; font-weight: bold; background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2, stop: 0 #0C6AB0, stop: 0.15 #55C4E6, stop: 0.15 #55C4E6, stop: 0.5 #FFFFFF, stop: 0.5 #FFFFFF, stop: 0.85 #55C4E6, stop: 0.85 #55C4E6, stop: 1.0 #0C6AB0); border: 1px solid #000000; } QTabBar::tab:!selected:hover { margin-top: 2px; /* make non-selected tabs look smaller */ font-size: 14px; font-weight: bold; background: qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2, stop: 0 #888888, stop: 0.15 #BBBBBB, stop: 0.15 #BBBBBB, stop: 0.5 #FFFFFF, stop: 0.5 #FFFFFF, stop: 0.85 #BBBBBB, stop: 0.85 #BBBBBB, stop: 1.0 #888888); border: 1px solid #000000; } QTabBar::tab:selected { border-color: #000000; border-bottom-color: #000000; /* same as pane color */ } """ self.notebook.setStyleSheet(notebookStyleSheet) self.notebook.currentChanged.connect(self.CurrentTabChanged) buttonbox = QDialogButtonBox(Qt.Horizontal, self) button = QPushButton(self) button.setText(self.tr("Oh, Yeah!")) button.setWhatsThis(self.tr('This is the Oh, Yeah! button!') + '\n' + self.tr('Oh, Yeah!')) buttonbox.addButton(button, QDialogButtonBox.AcceptRole) buttonbox.setCenterButtons(True) buttonbox.accepted.connect(self.accept) hbLayout1 = QHBoxLayout() hbLayout2 = QHBoxLayout() vbLayout = QVBoxLayout() hbLayout1.addStretch() hbLayout1.addWidget(self.imgLbl) hbLayout1.addStretch() hbLayout2.addStretch() hbLayout2.addWidget(self.notebook) hbLayout2.addStretch() vbLayout.addLayout(hbLayout1) vbLayout.addLayout(hbLayout2) vbLayout.addWidget(buttonbox) self.setLayout(vbLayout) self.setWindowTitle(self.tr('About Embroidermodder Version 2.0')) QApplication.restoreOverrideCursor() # TODO/???/PORT# don't mess with the window resize cursors.
def _init_widgets(self): layout = QGridLayout() row = 0 # name name_label = QLabel(self) name_label.setText("Name") name_box = QLineEdit(self) name_box.setText(NameGenerator.random_name()) self._name_box = name_box layout.addWidget(name_label, row, 0) layout.addWidget(name_box, row, 1) row += 1 # address label address_label = QLabel(self) address_label.setText('Address') address = QAddressInput(None, parent=self, default="%#x" % self._addr) self._address_box = address layout.addWidget(address_label, row, 0) layout.addWidget(address, row, 1) row += 1 # initial state state_label = QLabel(self) state_label.setText('Initial state') init_state_combo = QStateComboBox(self._workspace.instance.states, self) self._init_state_combo = init_state_combo layout.addWidget(state_label, row, 0) layout.addWidget(init_state_combo, row, 1) row += 1 # buttons ok_button = QPushButton(self) ok_button.setText('OK') ok_button.clicked.connect(self._on_ok_clicked) self._ok_button = ok_button cancel_button = QPushButton(self) cancel_button.setText('Cancel') cancel_button.clicked.connect(self._on_cancel_clicked) buttons_layout = QHBoxLayout() buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) self.main_layout.addLayout(layout) self.main_layout.addLayout(buttons_layout)
class AVRProgrammerDialog(QtFixes.QDialog): def __init__(self): super(AVRProgrammerDialog, self).__init__(CWMainGUI.getInstance()) # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint) self.avr = AVRProgrammer() self.setWindowTitle("ChipWhisperer-Lite AVR Programmer") layout = QVBoxLayout() layoutFW = QHBoxLayout() self.flashLocation = QtFixes.QLineEdit() flashFileButton = QPushButton("Find") flashFileButton.clicked.connect(self.findFlash) layoutFW.addWidget(QLabel("FLASH File")) layoutFW.addWidget(self.flashLocation) layoutFW.addWidget(flashFileButton) layout.addLayout(layoutFW) self.flashLocation.setText(QSettings().value("avr-flash-location")) # Add buttons readSigBut = QPushButton("Check Signature") readSigBut.clicked.connect(self.readSignature) verifyFlashBut = QPushButton("Verify FLASH") verifyFlashBut.clicked.connect(self.verifyFlash) verifyFlashBut.setEnabled(False) progFlashBut = QPushButton("Erase/Program/Verify FLASH") progFlashBut.clicked.connect(self.writeFlash) layoutBut = QHBoxLayout() layoutBut.addWidget(readSigBut) layoutBut.addWidget(verifyFlashBut) layoutBut.addWidget(progFlashBut) layout.addLayout(layoutBut) layoutFuse = QHBoxLayout() readFuseBut = QPushButton("Read Fuses") readFuseBut.clicked.connect(self.readFuses) writeFuseBut = QPushButton("Write Fuses") writeFuseBut.clicked.connect(self.writeFuses) self.lowfuseLine = QtFixes.QLineEdit("?") self.lowfuseLine.setMaxLength(2) self.lowfuseLine.setFixedWidth(25) self.highfuseLine = QtFixes.QLineEdit("?") self.highfuseLine.setMaxLength(2) self.highfuseLine.setFixedWidth(25) self.extfuseLine = QtFixes.QLineEdit("?") self.extfuseLine.setMaxLength(2) self.extfuseLine.setFixedWidth(25) # Don't allow use to change these fuses self.highfuseLine.setReadOnly(True) self.extfuseLine.setReadOnly(True) layoutFuse.addWidget(readFuseBut) layoutFuse.addWidget(QLabel("LOW:")) layoutFuse.addWidget(self.lowfuseLine) layoutFuse.addWidget(QLabel("HIGH:")) layoutFuse.addWidget(self.highfuseLine) layoutFuse.addWidget(QLabel("EXT:")) layoutFuse.addWidget(self.extfuseLine) layoutFuse.addWidget(writeFuseBut) layout.addLayout(layoutFuse) layoutExtra = QHBoxLayout() self.clockMode = QPushButton("Enable Slow Clock Mode") self.clockMode.setCheckable(True) self.clockMode.clicked.connect(self.toggleSlowClock) layoutExtra.addWidget(self.clockMode) layoutExtra.addStretch() layout.addLayout(layoutExtra) # Add status stuff self.statusLine = QPlainTextEdit() self.statusLine.setReadOnly(True) # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10) layout.addWidget(self.statusLine) self.avr.newTextLog.connect(self.append) # Set dialog layout self.setLayout(layout) def append(self, text): self.statusLine.appendPlainText(text) def toggleSlowClock(self): if self.clockMode.isChecked(): self.avr.enableSlowClock(True) self.clockMode.setText("Disable Slow Clock Mode") else: self.avr.enableSlowClock(False) self.clockMode.setText("Enable Slow Clock Mode") def reject(self): #Ensure we disable slow-clock mode if self.clockMode.isChecked(): self.clockMode.setChecked(False) self.toggleSlowClock() #Release AVR self.avr.close() QDialog.reject(self) def findFlash(self): fname, _ = QFileDialog.getOpenFileName( self, 'Find FLASH File', QSettings().value("avr-flash-location"), '*.hex') if fname: self.flashLocation.setText(fname) QSettings().setValue("avr-flash-location", fname) def readSignature(self, close=True): self.avr.find() if close: self.avr.close() def readFuses(self): try: self.readSignature(close=False) self.statusLine.appendPlainText("Reading fuses") lfuse = self.avr.readFuse("low") hfuse = self.avr.readFuse("high") efuse = self.avr.readFuse("extended") self.statusLine.appendPlainText("OK: %02x %02x %02x" % (lfuse, hfuse, efuse)) self.lowfuseLine.setText("%02x" % lfuse) self.highfuseLine.setText("%02x" % hfuse) self.extfuseLine.setText("%02x" % efuse) except IOError: self.statusLine.appendPlainText("Reading fuses failed") self.lowfuseLine.setText("?") self.highfuseLine.setText("?") self.extfuseLine.setText("?") self.avr.close() def writeFuses(self): lfuse = int(self.lowfuseLine.text(), 16) # hfuse = int(self.highfuseLine.text(), 16) # efuse = int(self.extfuseLine.text(), 16) self.statusLine.appendPlainText( "Writing fuse: not only 'low' fuse is written, as hfuse/efuse can disable device\n" ) try: self.readSignature(close=False) self.avr.writeFuse("low", lfuse) # self.avr.writeFuse("high", hfuse) # self.avr.writeFuse("extended", efuse) # print("%x %x %x" % (lfuse, hfuse, efuse)) self.avr.close() except: self.avr.close() raise def verifyFlash(self): self.statusLine.appendPlainText("Verify not implemented") def writeFlash(self, erase=True, verify=True): self.avr.autoProgram(self.flashLocation.text(), erase, verify, self.statusLine.appendPlainText, QCoreApplication.processEvents) def setUSBInterface(self, iface): self.avr.setUSBInterface(iface)
class MainWindow(QMainWindow): # Sets up the main window def resize_window(self): # Function for resizing the window self.resize(self.minimumSizeHint()) def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # Set window Icon self.setWindowTitle(__appname__) iconImage = QImage(iconByteArray) iconPixmap = QPixmap(iconImage) self.setWindowIcon(QIcon(iconPixmap)) # Set up private key format widgets privateKeyFormatLayout = QHBoxLayout() privateKeyFormatLabel = QLabel('Select Key Format: ') self.privateKeyTypeCombobox = QComboBox() self.privateKeyTypeCombobox.addItems(privateKeyFormats) self.privateKeyLengthLabel = QLabel('0') privateKeyFormatLayout.addWidget(privateKeyFormatLabel) privateKeyFormatLayout.addWidget(self.privateKeyTypeCombobox) privateKeyFormatLayout.addWidget(self.privateKeyLengthLabel) # Set up private key text widgets privateKeyLayout = QVBoxLayout() privateKeyButtonsLayout = QHBoxLayout() generatePrivateKeyButton = QPushButton('Generate Key') generatePrivateKeyButton.clicked.connect(self.get_private_key) self.copyPrivateKeyButton = QPushButton('Copy Key') self.copyPrivateKeyButton.setDisabled(True) self.copyPrivateKeyButton.clicked.connect(self.copy_private_key) privateKeyButtonsLayout.addWidget(generatePrivateKeyButton) privateKeyButtonsLayout.addWidget(self.copyPrivateKeyButton) self.privateKeyEdit = GrowingTextEdit() self.privateKeyEdit.setFont(QFont('Courier')) self.privateKeyEdit.textChanged.connect( self.private_key_or_code_changed) privateKeyLayout.addLayout(privateKeyButtonsLayout) privateKeyLayout.addWidget(self.privateKeyEdit) # Set up cypher code widgets codeLayout = QHBoxLayout() codeLabel = QLabel('Select Cypher Code: ') self.codeSelect = QSpinBox() self.codeSelect.setValue(10) self.codeSelect.setMinimum(2) self.codeSelect.setDisabled(True) self.codeSelect.valueChanged.connect(self.private_key_or_code_changed) codeLayout.addWidget(codeLabel) codeLayout.addWidget(self.codeSelect) # Set up cypher text widgets cypherLayout = QVBoxLayout() cypherButtonsLayout = QHBoxLayout() cardButtonsLayout = QHBoxLayout() self.generateCypherButton = QPushButton('Generate Cypher') self.generateCypherButton.clicked.connect(self.get_cypher) self.generateCypherButton.setDisabled(True) self.copyCypherButton = QPushButton('Copy Cypher') self.copyCypherButton.setDisabled(True) self.copyCypherButton.clicked.connect(self.copy_cypher) cypherButtonsLayout.addWidget(self.generateCypherButton) cypherButtonsLayout.addWidget(self.copyCypherButton) self.cypherEdit = GrowingTextEdit() self.cypherEdit.setFont(QFont('Courier')) self.cypherEdit.setReadOnly(True) self.cypherEdit.setVisible(False) self.cypherEdit.textChanged.connect(self.resize_window) self.cypherPreviewLabel = QLabel('-CYPHER PREVIEW-') self.cypherPreviewLabel.setAlignment(Qt.AlignCenter) self.cypherPreviewLabel.setVisible(False) self.cypherPreview = GrowingTextEdit() self.cypherPreview.setFont(QFont('Courier')) self.cypherPreview.setAlignment(Qt.AlignHCenter) self.cypherPreview.setWordWrapMode(QTextOption.NoWrap) self.cypherPreview.setReadOnly(True) self.cypherPreview.setVisible(False) self.cypherCardsPrintButton = QPushButton('Print Cypher Cards') self.cypherCardsPrintButton.setVisible(False) self.cypherCardsPrintButton.clicked.connect(partial(self.cards, True)) self.cypherCardsCopyButton = QPushButton('Copy Cypher Cards') self.cypherCardsCopyButton.setVisible(False) self.cypherCardsCopyButton.clicked.connect(partial(self.cards, False)) cardButtonsLayout.addWidget(self.cypherCardsPrintButton) cardButtonsLayout.addWidget(self.cypherCardsCopyButton) cypherLayout.addLayout(cypherButtonsLayout) cypherLayout.addWidget(self.cypherEdit) cypherLayout.addWidget(self.cypherPreviewLabel) cypherLayout.addWidget(self.cypherPreview) cypherLayout.addLayout(cardButtonsLayout) # Set up donation widgets donationsLayout = QVBoxLayout() separater = QFrame() separater.setFrameShape(QFrame.HLine) self.donationButton = QPushButton('Donate') self.donationButton.setVisible(False) self.donationButton.clicked.connect(self.donate) self.copyEthAddressButton = QPushButton('ETH: Copy Address') self.copyEthAddressButton.clicked.connect( self.copy_eth_donation_address) self.copyEthAddressButton.setVisible(False) self.copyBtcAddressButton = QPushButton('BTC: Copy Address') self.copyBtcAddressButton.clicked.connect( self.copy_btc_donation_address) self.copyBtcAddressButton.setVisible(False) donationsLayout.addWidget(separater) donationsLayout.addWidget(self.donationButton) donationsLayout.addWidget(self.copyEthAddressButton) donationsLayout.addWidget(self.copyBtcAddressButton) # Add all widgets and sub-layouts to the master layout self.master_layout = QVBoxLayout() self.master_layout.addLayout(privateKeyFormatLayout) self.master_layout.addLayout(privateKeyLayout) self.master_layout.addLayout(codeLayout) self.master_layout.addLayout(cypherLayout) self.master_layout.addLayout(donationsLayout) self.master_widget = QWidget() self.master_widget.setLayout(self.master_layout) self.setCentralWidget(self.master_widget) # Start and connect the window resizing thread self.worker = Worker() self.worker.updateWindowSize.connect(self.resize_window) def copy_private_key( self): # Copies the private key text to the system clipboard clip.setText(self.privateKeyEdit.toPlainText()) self.copyPrivateKeyButton.setText('Key Copied') app.processEvents() sleep(2) self.copyPrivateKeyButton.setText('Copy Key') def copy_cypher(self): # Copies the cypher text to the system clipboard clip.setText(self.cypherEdit.toPlainText()) self.copyCypherButton.setText('Cypher Copied') app.processEvents() sleep(2) self.copyCypherButton.setText('Copy Cypher') def copy_eth_donation_address( self): # Copies the ETH donation address to the system clipboard clip.setText(ethDonationAddress) self.copyEthAddressButton.setText('ETH: Address Copied\nThanks!') app.processEvents() sleep(2) self.copyEthAddressButton.setText('ETH: Copy Address') def copy_btc_donation_address( self): # Copies the BTC donation address to the system clipboard clip.setText(btcDonationAddress) self.copyBtcAddressButton.setText('BTC: Address Copied\nThanks!') app.processEvents() sleep(2) self.copyBtcAddressButton.setText('BTC: Copy Address') def get_private_key( self ): # Generates a key of the desired format using two instances of the SystemRandom function privateKey = generate_private_key.start( self.privateKeyTypeCombobox.currentText()) self.privateKeyEdit.setText(privateKey) self.private_key_or_code_changed() self.copyPrivateKeyButton.setDisabled(False) def private_key_or_code_changed( self ): # Changes visibility and ability of some widgets based on user input self.privateKeyLengthLabel.setText( str(len(self.privateKeyEdit.toPlainText()))) self.copyCypherButton.setDisabled(True) self.cypherEdit.setText('') self.cypherPreview.setText('') self.cypherEdit.setVisible(False) self.cypherPreviewLabel.setVisible(False) self.cypherPreview.setVisible(False) if len(self.privateKeyEdit.toPlainText()) <= 2: self.copyPrivateKeyButton.setDisabled(True) self.generateCypherButton.setDisabled(True) self.codeSelect.setDisabled(True) else: self.codeSelect.setMaximum( len(self.privateKeyEdit.toPlainText()) - 1) self.copyPrivateKeyButton.setDisabled(False) self.generateCypherButton.setDisabled(False) self.codeSelect.setDisabled(False) self.cypherCardsPrintButton.setDisabled(True) self.cypherCardsPrintButton.setVisible(False) self.cypherCardsCopyButton.setDisabled(True) self.cypherCardsCopyButton.setVisible(False) self.worker.start() def get_cypher( self ): # Converts the raw key into a cypher based on the codeSelect value if not 1 >= len(self.privateKeyEdit.toPlainText()) >= int( self.privateKeyLengthLabel.text()): self.generateCypherButton.setDisabled(False) cypherRows, cypherSeed = create_cypher.start( self.privateKeyEdit.toPlainText(), self.codeSelect.value()) self.copyCypherButton.setDisabled(False) self.cypherEdit.setVisible(True) self.cypherEdit.setText(cypherSeed) self.cypherPreviewLabel.setVisible(True) self.cypherPreview.setVisible(True) previewText = '' for i in cypherRows: previewText += i + '\n' self.cypherPreview.setText(previewText) self.worker.start() self.cypherCardsPrintButton.setDisabled(False) self.cypherCardsPrintButton.setVisible(True) self.cypherCardsCopyButton.setDisabled(False) self.cypherCardsCopyButton.setVisible(True) self.donationButton.setVisible(True) else: self.generateCypherButton.setDisabled(True) def cards(self, print): # Creates and prints the output.txt file cardList = split_cypher_into_pairs.start(self.cypherEdit.toPlainText()) printString = format_cards.start(cardList) if print: self.cypherCardsPrintButton.setText('Printing') app.processEvents() cards_output.start(printString) self.cypherCardsPrintButton.setText('Print Cypher Cards') else: clip.setText(printString) self.cypherCardsCopyButton.setText('Cards Copied') app.processEvents() sleep(2) self.cypherCardsCopyButton.setText('Copy Cypher Cards') def donate(self): # Adjusts the visibility of the donation buttons if self.donationButton.text() == 'Donate': self.copyEthAddressButton.setVisible(True) self.copyBtcAddressButton.setVisible(True) self.donationButton.setText('Hide') elif self.donationButton.text() == 'Hide': self.copyEthAddressButton.setVisible(False) self.copyBtcAddressButton.setVisible(False) self.donationButton.setText('Donate') self.worker.start() def cleanup(self): # Clears the clipboard of any copied text clip.setText('')
class LandmarkLocationWidget(QWidget): # Signals activated = Signal(int, bool) deleted = Signal(int) def __init__(self): super(LandmarkLocationWidget, self).__init__() self._active = False self._font = QFont() self._font.setPointSize(10) self.indexLabel = QLabel() self.indexLabel.setMaximumWidth(10) self.indexLabel.setMinimumWidth(10) self.doneButton = QPushButton("Done") self.doneButton.setMaximumWidth(50) self.doneButton.setFont(self._font) self.doneButton.clicked.connect(self.doneButtonClicked) self.deleteButton = QPushButton("X") self.deleteButton.setMaximumWidth(15) self.deleteButton.setMinimumWidth(15) self.deleteButton.setMaximumHeight(15) self.deleteButton.setMinimumHeight(15) self.deleteButton.setFont(self._font) self.deleteButton.setVisible(False) self.deleteButton.clicked.connect(self.deleteButtonClicked) self.fixedButton = SpecialButton() self.fixedButton.setFont(self._font) self.movingButton = SpecialButton() self.movingButton.setFont(self._font) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setVerticalSpacing(0) layout.addWidget(self.deleteButton, 0, 0) layout.addWidget(self.indexLabel, 0, 1) layout.addWidget(self.fixedButton, 0, 2) layout.addWidget(self.movingButton, 0, 3) layout.addWidget(self.doneButton, 0, 4) self.setLayout(layout) self._updateState() def setIndex(self, index): self.index = index self.indexLabel.setText(str(index+1)) @property def active(self): return self._active @active.setter def active(self, value): self._active = value self._updateState() def setLandmarkSet(self, points): self.setFixedLandmark(points[0]) self.setMovingLandmark(points[1]) def setFixedLandmark(self, landmark): if not landmark: return labelX = "%2.0f" % landmark[0] labelY = "%2.0f" % landmark[1] labelZ = "%2.0f" % landmark[2] self.fixedButton.setText(labelX + ", " + labelY + ", " + labelZ) def setMovingLandmark(self, landmark): if not landmark: return labelX = "%2.0f" % landmark[0] labelY = "%2.0f" % landmark[1] labelZ = "%2.0f" % landmark[2] self.movingButton.setText(labelX + ", " + labelY + ", " + labelZ) @Slot() def doneButtonClicked(self): self._active = not self._active self.activated.emit(self.index, self._active) self._updateState() @Slot() def deleteButtonClicked(self): self.deleted.emit(self.index) def _updateState(self): text = "Done" if self._active else "Edit" self.doneButton.setText(text) self.deleteButton.setVisible(self._active) self.indexLabel.setVisible(not self._active) self.fixedButton.setEnabled(self._active) self.movingButton.setEnabled(self._active)
def __init__(self, parent): super(TipOfTheDayDialog, self).__init__(parent) """ Default class constructor. :param `parent`: Pointer to a parent widget instance. :type `parent`: `QWidget`_ """ ## qDebug("TipOfTheDayDialog constructor") self.mainWin = parent self.setAttribute(Qt.WA_DeleteOnClose) self.setWizardStyle(QWizard.ModernStyle) self.setMinimumSize(550, 400) ## self.setOption(QWizard.HaveHelpButton, True) page = QWizardPage(self) self.imgBanner = ImageWidget(self.mainWin.gImgDir, self.mainWin.gIconDir, self) # Read in the tips.txt file. # fileOpen = open(self.mainWin.gAppDir + os.sep + 'tips.txt') # tips = fileOpen.read() # fileOpen.close() # self.tipsList = [tip for tip in tips.split('\n') if tip] # remove the blank lines also. self.tipsList = [tip for tip in TIPS_TXT.split('\n') if tip] # remove the blank lines also. # Make sure we don't cause an IndexError. # DEV-We might be adding tips to the txt at runtime. The easy way to add and check tips. if int(self.mainWin.settings_general_current_tip) >= len(self.tipsList): self.mainWin.settings_general_current_tip = 0 self.labelTipOfTheDay = QLabel(self) self.labelTipOfTheDay.setText(self.tipsList[int(self.mainWin.settings_general_current_tip)]) self.labelTipOfTheDay.setWordWrap(True) # Forget about a standardish QCheckBox, real powerusers keep the lights on! self.lightswitch = LightSwitchWidget(self.mainWin.gImgDir, self.mainWin, self) self.showOnStartupLabel = QLabel(self) self.showOnStartupLabel.setText(self.tr('Show tips on startup')) layout = QVBoxLayout(self) hblayout = QHBoxLayout() hblayout2 = QHBoxLayout() hblayout.addStretch(1) hblayout.addWidget(self.imgBanner) hblayout.addStretch(1) layout.addLayout(hblayout) layout.addStrut(1) layout.addSpacerItem(QSpacerItem(0, 5)) layout.addWidget(self.labelTipOfTheDay) layout.addStretch(1) hblayout2.addWidget(self.lightswitch) hblayout2.addWidget(self.showOnStartupLabel) hblayout2.addStretch(1) self.showOnStartupLabel.setAlignment(Qt.AlignBottom) layout.addLayout(hblayout2) page.setLayout(layout) self.addPage(page) self.setWindowTitle(self.tr('Tip of the Day')) buttonPrevious = QPushButton(self) buttonPrevious.setText(self.tr('&Previous')) buttonPrevious.setIcon(QIcon(self.mainWin.gIconDir + os.sep + 'undo.png')) buttonPrevious.setIconSize(QSize(24, 24)) buttonNext = QPushButton(self) buttonNext.setText(self.tr('&Next')) buttonNext.setIcon(QIcon(self.mainWin.gIconDir + os.sep + 'redo.png')) buttonNext.setIconSize(QSize(24, 24)) buttonClose = QPushButton(self) buttonClose.setText(self.tr('&Close')) buttonClose.setIcon(QIcon(self.mainWin.gIconDir + os.sep + 'windowclose.png')) buttonClose.setIconSize(QSize(24, 24)) self.setButton(QWizard.CustomButton1, buttonPrevious) self.setButton(QWizard.CustomButton2, buttonNext) self.setButton(QWizard.CustomButton3, buttonClose) self.setOption(QWizard.HaveCustomButton1, True) self.setOption(QWizard.HaveCustomButton2, True) self.setOption(QWizard.HaveCustomButton3, True) self.customButtonClicked.connect(self.buttonTipOfTheDayClicked) listTipOfTheDayButtons = [QWizard.Stretch, QWizard.CustomButton1, QWizard.CustomButton2, QWizard.CustomButton3] self.setButtonLayout(listTipOfTheDayButtons) self.DoSetWhatsThis()
class NotificationTab(): """ui class for new notification tab""" global logger def __init__(self): ##### logger.info('Inside PurchaseSchedule') self.notificationTab_tab_4 = QWidget() self.notificationTab_tab_4.setObjectName("notificationTab_tab_4") self.gridLayout_19 = QGridLayout(self.notificationTab_tab_4) self.gridLayout_19.setObjectName("gridLayout_19") ## self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.title_label = QLabel(self.notificationTab_tab_4) self.title_label.setObjectName("title_label") self.horizontalLayout.addWidget(self.title_label) self.gridLayout_19.addLayout(self.horizontalLayout, 0, 0, 1, 1) ## self.horizontalLayout_6 = QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.id_label = QLabel(self.notificationTab_tab_4) self.id_label.setObjectName("id_label") self.horizontalLayout_6.addWidget(self.id_label) self.id_line = QLineEdit(self.notificationTab_tab_4) self.id_line.setObjectName("id_line") self.horizontalLayout_6.addWidget(self.id_line) self.notification_schedule_fromdate_label = QLabel( self.notificationTab_tab_4) self.notification_schedule_fromdate_label.setObjectName( "notification_schedule_fromdate_label") self.horizontalLayout_6.addWidget( self.notification_schedule_fromdate_label) self.notification_schedule_fromdate_dateedit = QDateEdit( self.notificationTab_tab_4) self.notification_schedule_fromdate_dateedit.setMaximumDate( QDate.currentDate()) self.notification_schedule_fromdate_dateedit.setDate( QDate.currentDate()) self.notification_schedule_fromdate_dateedit.setCalendarPopup(True) self.notification_schedule_fromdate_dateedit.setObjectName( "notification_schedule_fromdate_dateedit") self.horizontalLayout_6.addWidget( self.notification_schedule_fromdate_dateedit) self.notification_schedule_todate_label = QLabel( self.notificationTab_tab_4) self.notification_schedule_todate_label.setObjectName( "notification_schedule_todate_label") self.horizontalLayout_6.addWidget( self.notification_schedule_todate_label) self.notification_schedule_todate_dateedit = QDateEdit( self.notificationTab_tab_4) self.notification_schedule_todate_dateedit.setMaximumDate( QDate.currentDate()) self.notification_schedule_todate_dateedit.setDate(QDate.currentDate()) self.notification_schedule_todate_dateedit.setCalendarPopup(True) self.notification_schedule_todate_dateedit.setObjectName( "notification_schedule_todate_dateedit") self.horizontalLayout_6.addWidget( self.notification_schedule_todate_dateedit) self.type_label = QLabel(self.notificationTab_tab_4) self.type_label.setObjectName("type_label") self.horizontalLayout_6.addWidget(self.type_label) self.notification_states = QComboBox(self.notificationTab_tab_4) self.notification_states.setObjectName("notification_states") self.horizontalLayout_6.addWidget(self.notification_states) self.batch_label = QLabel(self.notificationTab_tab_4) self.batch_label.setObjectName("batch_label") self.horizontalLayout_6.addWidget(self.batch_label) self.notification_results = QComboBox(self.notificationTab_tab_4) self.notification_results.setObjectName("notification_results") self.horizontalLayout_6.addWidget(self.notification_results) self.gridLayout_19.addLayout(self.horizontalLayout_6, 1, 0, 1, 1) self.gridLayout_8 = QGridLayout() self.gridLayout_8.setObjectName("gridLayout_8") self.notification_schedule_table = QTableWidget( self.notificationTab_tab_4) self.notification_schedule_table.setObjectName( "notification_schedule_table") self.notification_schedule_table.setColumnCount(5) self.notification_schedule_table.setRowCount(0) self.notification_schedule_table.setWordWrap(True) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(0, item) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(1, item) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(2, item) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(3, item) item = QTableWidgetItem() self.notification_schedule_table.setHorizontalHeaderItem(4, item) self.notification_schedule_table.horizontalHeader( ).setCascadingSectionResizes(True) self.notification_schedule_table.horizontalHeader( ).setStretchLastSection(True) self.notification_schedule_table.verticalHeader().setVisible(False) self.notification_schedule_table.verticalHeader( ).setCascadingSectionResizes(True) self.notification_schedule_table.verticalHeader( ).setStretchLastSection(False) self.gridLayout_8.addWidget(self.notification_schedule_table, 0, 0, 1, 5) self.notification_search_button = QPushButton( self.notificationTab_tab_4) self.notification_search_button.setObjectName( "notification_search_button") self.gridLayout_8.addWidget(self.notification_search_button, 1, 0, 1, 1) spacerItem10 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_8.addItem(spacerItem10, 1, 2, 1, 1) self.notification_reset_button = QPushButton( self.notificationTab_tab_4) self.notification_reset_button.setObjectName( "notification_reset_button") self.gridLayout_8.addWidget(self.notification_reset_button, 1, 3, 1, 1) self.notification_load_more_button = QPushButton( self.notificationTab_tab_4) self.notification_load_more_button.setObjectName( "notification_load_more_button") self.gridLayout_8.addWidget(self.notification_load_more_button, 1, 4, 1, 1) self.gridLayout_19.addLayout(self.gridLayout_8, 2, 0, 1, 1) ###retranslate self.title_label.setText( QApplication.translate( "MainWindow", "<html><head/><body><p align=\"center\">" "<span style=\" font-weight:600;font-size:20px\">" "<u>All Notifications</u></span></p></body></html>", None, QApplication.UnicodeUTF8)) self.id_label.setText( QApplication.translate("MainWindow", "Message Id", None, QApplication.UnicodeUTF8)) self.notification_schedule_fromdate_label.setText( QApplication.translate("MainWindow", "From Date", None, QApplication.UnicodeUTF8)) self.notification_schedule_fromdate_dateedit.setDisplayFormat( QApplication.translate("MainWindow", "dd/MM/yyyy", None, QApplication.UnicodeUTF8)) self.notification_schedule_todate_label.setText( QApplication.translate("MainWindow", "To Date", None, QApplication.UnicodeUTF8)) self.notification_schedule_todate_dateedit.setDisplayFormat( QApplication.translate("MainWindow", "dd/MM/yyyy", None, QApplication.UnicodeUTF8)) self.type_label.setText( QApplication.translate("MainWindow", "Type", None, QApplication.UnicodeUTF8)) self.batch_label.setText( QApplication.translate("MainWindow", "Number of Notifications", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(0).setText( QApplication.translate("MainWindow", "Message Id", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(1).setText( QApplication.translate("MainWindow", "Date", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(2).setText( QApplication.translate("MainWindow", "From", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(3).setText( QApplication.translate("MainWindow", "Message", None, QApplication.UnicodeUTF8)) self.notification_schedule_table.horizontalHeaderItem(4).setText( QApplication.translate("MainWindow", "State", None, QApplication.UnicodeUTF8)) self.notification_search_button.setText( QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.notification_reset_button.setText( QApplication.translate("MainWindow", "Reset All", None, QApplication.UnicodeUTF8)) self.notification_load_more_button.setText( QApplication.translate("MainWindow", "Load More", None, QApplication.UnicodeUTF8)) ##signals and slotts && other stuffs self.scheduletable_count = 0 self.addtable_count = 0 # self.mainwindow = Ui_MainWindow # just for the ease of finding the attributes in pycharm self.notification_schedule_table.setEditTriggers( QAbstractItemView.NoEditTriggers) self.batch_number = None self.notification_results.addItems([str(i) for i in range(1, 50, 5)]) self.notification_states.addItems(['All', 'New', 'To Do', 'Done']) self.message = Messaging() self.notification_load_more_button.clicked.connect(self.load_more) self.notification_search_button.clicked.connect(self.search_messages) self.notification_reset_button.clicked.connect(self.reset_all) self.notificationTab_tab_4.setFocusPolicy(Qt.StrongFocus) self.notificationTab_tab_4.focusInEvent = self.load_rows # self.assign_shortcuts() # def assign_shortcuts(self): # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_search']), # self.notificationTab_tab_4, self.search_messages) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_additem']), # self.notificationTab_tab_4, self.add_new_blank_rows) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_print']), # self.notificationTab_tab_4, self.commit_and_print) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_today']), # self.notificationTab_tab_4, lambda: self.load_messages('today')) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_tommorow']), # self.notificationTab_tab_4, lambda: self.load_messages('tomorrow')) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_thismonth']), # self.notificationTab_tab_4, lambda: self.load_messages('month')) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_thisweek']), # self.notificationTab_tab_4, lambda: self.load_messages('week')) # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_clear']), # self.notificationTab_tab_4, self.clear_table) def add_messages(self, *args): """ Populates the Schedules when we load the tab """ table = self.notification_schedule_table if args: if args[0] != 'new': table.clearContents() table.setRowCount(0) table.setRowCount(len(args)) for i, j in enumerate(args): item = QTableWidgetItem(j['msg_id']) table.setItem(i, 0, item) item = QTableWidgetItem(j['date']) table.setItem(i, 1, item) item = QTableWidgetItem( 'Name:{}\nDesignation:{}\nAddress:{}'.format( j['name'], j['designation'], j['address'])) table.setItem(i, 2, item) item = QTableWidgetItem( 'Message Type:{}\nMessage:{}'.format( j['msg_type'].title(), j['msg_body'])) table.setItem(i, 3, item) states = QComboBox() self.populate_states(states, j['msg_state'].title()) states.currentIndexChanged.connect( lambda index, row=i: self.changed_state(row, index)) table.setCellWidget(i, 4, states) elif args[0] == 'new': initial = table.rowCount() row = table.rowCount() + len(args[1]) table.setRowCount(row) forward_range = range(initial, row) for i, j in zip(forward_range, args[1]): item = QTableWidgetItem(j['msg_id']) table.setItem(i, 0, item) item = QTableWidgetItem(j['date']) table.setItem(i, 1, item) item = QTableWidgetItem( 'Name:{}\nDesignation:{}\nAddress:{}'.format( j['name'], j['designation'], j['address'])) table.setItem(i, 2, item) item = QTableWidgetItem( 'Message Type:{}\nMessage:{}'.format( j['msg_type'].title(), j['msg_body'])) table.setItem(i, 3, item) states = QComboBox() self.populate_states(states, j['msg_state'].title()) states.currentIndexChanged.connect( lambda index, row=i: self.changed_state(row, index)) table.setCellWidget(i, 4, states) table.setColumnWidth(0, (table.width() * 0.5) / 5) table.setColumnWidth(1, (table.width() * 0.5) / 5) table.setColumnWidth(2, table.width() / 5) table.setColumnWidth(3, (table.width() * 2) / 5) self.notification_schedule_table.resizeRowsToContents() def populate_states(self, combo, state): """ fills the supplier list for each item line :param combo: the combo box of suppliers :return:none """ combo.setStyleSheet("QAbstractItemView{" "background: #4B77BE;" "}") combo.addItems(['New', 'To Do', 'Done']) index = combo.findText(state) combo.setCurrentIndex(index) def changed_state(self, row, index): """ fill the item combo box :param combo: the combobox object :return: none """ table = self.notification_schedule_table data = {} data['message_id'] = table.item(row, 0).text() data['msg_state'] = table.cellWidget(row, 4).currentText() msg = QMessageBox.information( QMessageBox(), 'Alert!!', 'Do you want to change the status of the Message??', QMessageBox.Yes | QMessageBox.No) if msg == QMessageBox.Yes: report = self.message.update_message(data) if report: _ = QMessageBox.information(QMessageBox(), 'Success!!', 'The Message was updated', QMessageBox.Yes | QMessageBox.No) else: _ = QMessageBox.critical(QMessageBox(), 'Error!!', 'The Message was not updated', QMessageBox.Yes | QMessageBox.No) def search_messages(self): """ Searches for messages when search button is pressed """ logger.info('Notifications searching messages initiated') from_date = self.notification_schedule_fromdate_dateedit.text() to_date = self.notification_schedule_todate_dateedit.text() limit = self.notification_results.currentText() msg_id = self.id_line.text() msg_state = self.notification_states.currentText() dataobj = self.message.load_message(limit=limit, from_date=from_date, to_date=to_date, msg_id=msg_id, msg_state=msg_state) if dataobj: self.add_messages(*dataobj) else: self.notification_schedule_table.clearContents() self.notification_schedule_table.setRowCount(0) def load_more(self): """ Searches for messages when search button is pressed """ logger.info('Notifications searching messages initiated') from_date = self.notification_schedule_fromdate_dateedit.text() to_date = self.notification_schedule_todate_dateedit.text() limit = self.notification_results.currentText() msg_id = self.id_line.text() msg_state = self.notification_states.currentText() offset = self.notification_schedule_table.rowCount() dataobj = self.message.load_message(limit=limit, from_date=from_date, to_date=to_date, msg_id=msg_id, msg_state=msg_state, offset=offset) if dataobj: self.add_messages('new', dataobj) else: self.notification_schedule_table.clearContents() self.notification_schedule_table.setRowCount(0) def load_single_message(self, msg_id): # api """method to load a single message""" self.reset_all() dataobj = self.message.load_message(msg_id=msg_id) if dataobj: self.add_messages('new', dataobj) self.id_line.setText(str(msg_id)) else: self.notification_schedule_table.clearContents() self.notification_schedule_table.setRowCount(0) def load_rows(self, event): """ :return:loads the rows """ self.add_messages() def reset_all(self): """ :return: resets the the data in the search text """ try: self.id_line.clear() self.notification_schedule_table.clearContents() self.notification_schedule_table.setRowCount(0) except Exception as _: if settings.level == 10: logger.exception('raised exception') return False
class ToolBox(QVBoxLayout): sig = QtCore.Signal(object) listThread = None groupBoxThreadInfo = None threadvbox = None mode = None def __init__(self, mode, parentQWidget = None): QVBoxLayout.__init__(self) self.sig.connect(self.addThreadList) self.mode = mode self.sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding) self.groupBoxSearch = QGroupBox() self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };") vboxSearch = QVBoxLayout() self.searchTitle = QLabel("Search Messages") vboxSearch.addWidget(self.searchTitle) self.searchHLayout = QHBoxLayout() self.editTextSearch = QTextEdit('') self.editTextSearch.setFixedSize(200,30) self.buttonSearch = QPushButton('Search') self.buttonSearch.setFixedSize(100,30) self.buttonSearch.clicked.connect(self.searchMsg) vboxSearch.addWidget(self.editTextSearch) self.searchHLayout.addWidget(self.buttonSearch) self.searchCursor = QLabel() self.searchHLayout.addWidget(self.searchCursor) vboxSearch.addLayout(self.searchHLayout) self.browseHLayout = QHBoxLayout() self.buttonLookUp = QPushButton('\u21e7') #Arrow up self.buttonLookUp.setFixedWidth(100) self.buttonLookUp.clicked.connect(self.moveToPrev) self.buttonLookDown = QPushButton('\u21e9') #Arrow down self.buttonLookDown.setFixedWidth(100) self.buttonLookDown.clicked.connect(self.moveToNext) self.browseHLayout.addWidget(self.buttonLookUp) self.browseHLayout.addWidget(self.buttonLookDown) vboxSearch.addLayout(self.browseHLayout) self.groupBoxSearch.setLayout(vboxSearch) self.addWidget(self.groupBoxSearch) self.groupBoxSearch.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)) self.buttonHiddenLifelines = QPushButton('Show hidden life-lines') self.buttonHiddenLifelines.setFixedWidth(200) self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines) self.addWidget(self.buttonHiddenLifelines) self.buttonHiddenMessages = QPushButton('Show hidden Messages') self.buttonHiddenMessages.setFixedWidth(200) self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages) self.addWidget(self.buttonHiddenMessages) if const.mode_interactive == mode: self.buttonCapture = QPushButton('Capture') self.buttonCapture.setFixedWidth(200) self.buttonCapture.clicked.connect(self.notifyCapture) self.addWidget(self.buttonCapture) self.msgRcv = [] self.msgInfo = QLabel("Message Info.") self.groupBoxMessageInfo = QGroupBox() self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;") vbox = QVBoxLayout() vbox.addWidget(self.msgInfo) self.tableTime = QtGui.QTableWidget(3,2) self.tableTime.setHorizontalHeaderLabels(['-','time']) self.tableTime.setColumnWidth(0,80) self.tableTime.setColumnWidth(1,150) vwidth = self.tableTime.verticalHeader().length() hwidth = self.tableTime.horizontalHeader().height() fwidth = self.tableTime.frameWidth() * 2 self.tableTime.setFixedHeight(vwidth + hwidth + fwidth) self.tableTime.horizontalHeader().setStretchLastSection(True) self.tableTime.setItem(0,0,QTableWidgetItem('begin')) self.tableTime.setItem(0,1,QTableWidgetItem(' - ')) self.tableTime.setItem(1,0,QTableWidgetItem('end')) self.tableTime.setItem(1,1,QTableWidgetItem(' - ')) self.tableTime.setItem(2,0,QTableWidgetItem('duration')) self.tableTime.setItem(2,1,QTableWidgetItem(' - ')) vbox.addWidget(self.tableTime) self.titleArg = QLabel('Argument List') vbox.addWidget(self.titleArg) max_arg_num = 10 self.tableArgs = QtGui.QTableWidget(max_arg_num,2) self.tableArgs.setHorizontalHeaderLabels(['type','value']) for idx in range(0,max_arg_num): self.tableArgs.setItem(idx,0,QTableWidgetItem()) self.tableArgs.setItem(idx,1,QTableWidgetItem()) self.tableArgs.horizontalHeader().setStretchLastSection(True) vbox.addWidget(self.tableArgs) self.titleArg = QLabel('Return Value List') vbox.addWidget(self.titleArg) max_ret_num = 4 self.tableRet = QtGui.QTableWidget(max_ret_num,2) self.tableRet.setHorizontalHeaderLabels(['type','value']) for idx in range(0,max_ret_num): self.tableRet.setItem(idx,0,QTableWidgetItem()) self.tableRet.setItem(idx,1,QTableWidgetItem()) self.tableRet.horizontalHeader().setStretchLastSection(True) vwidth = self.tableRet.verticalHeader().length() hwidth = self.tableRet.horizontalHeader().height() fwidth = self.tableRet.frameWidth() * 2 self.tableRet.setFixedHeight(vwidth + hwidth + fwidth) vbox.addWidget(self.tableRet) self.buttonSrcView = QPushButton('view code') self.buttonSrcView.setFixedWidth(200) self.buttonSrcView.clicked.connect(self.openSourceViewer) self.buttonHide = QPushButton('Hide') self.buttonHide.setFixedWidth(200) self.buttonHide.clicked.connect(self.notifyHide) self.buttonHideAllMsg = QPushButton('Hide All') self.buttonHideAllMsg.setFixedWidth(200) self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected) self.groupBoxMessageInfo.setLayout(vbox) self.checkHideCircular = QCheckBox('Hide Circular Messages') self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked) self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage) self.addWidget(self.checkHideCircular) self.addWidget(self.groupBoxMessageInfo) self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy) def reset(self): for idx in reversed(range(0,self.listThread.count())): self.listThread.takeItem(idx) def setMsgInfoMessage(self,msg): self.strMessage = msg def changeHideCircularMessage(self,state): if state == QtCore.Qt.Unchecked: self.diagramView.hideCircularChanged(False) elif state == QtCore.Qt.Checked: self.diagramView.hideCircularChanged(True) def setMsgInfoModule(self,module): self.strModule = module def updateSearchStatus(self,curr,number): self.searchCursor.setText("%d/%d" % (curr,number)) def connectSourceViewer(self,viewer): self.srcViewer = viewer def openSourceViewer(self): self.srcViewer.openViewer(self.strModule,self.strMessage) def setMessageInfoTime(self,begin,end,duration): self.tableTime.item(0,1).setText(begin) self.tableTime.item(1,1).setText(end) self.tableTime.item(2,1).setText(duration + ' msec') def setMessageInfoArg(self,listParam,listArg): if listArg: for idx, text in enumerate(listArg): self.tableArgs.item(idx,1).setText(text) for idx, text in enumerate(listParam): self.tableArgs.item(idx,0).setText(text) else: for idx in range(0,self.tableArgs.rowCount()): self.tableArgs.item(idx,1).setText('') self.tableArgs.item(idx,0).setText('') def setMessageInfoRet(self,listRet): if listRet: for idx, text in enumerate(listRet): self.tableRet.item(idx,1).setText(text) else: for idx in range(0,self.tableRet.rowCount()): self.tableRet.item(idx,1).setText('') self.tableRet.item(idx,0).setText('') def notifyInteractiveStateChanged(self,state): if const.mode_interactive != self.mode: return if const.STATE_INTERACTIVE_CAPTURING == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Stop Capture') if const.STATE_INTERACTIVE_PROCESSING == state: self.buttonCapture.setEnabled(False) if const.STATE_INTERACTIVE_IDLE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') if const.STATE_INTERACTIVE_RESET == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') elif const.STATE_INTERACTIVE_ACTIVE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') def setMessageInfo(self,info): self.msgInfo.setText(info) def setAvailable(self,threads): self.sig.emit(threads) def toggleThreadDisplay(self,item): print(self.listThread.currentRow()) #if item.isSelected(): # print(item.text() + " is selected") #else: # print(item.text() + " is not selected") self.diagramView.showThread(self.listThread.currentRow(),item.isSelected()) def hideAllMsgNamedAsSelected(self): self.diagramView.hideAllMessageSelected() def addThreadList(self,threads): if not self.groupBoxThreadInfo: self.groupBoxThreadInfo = QGroupBox() self.threadInfo = QLabel("Thread Info.") self.groupBoxThreadInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;") if not self.threadvbox: self.threadvbox = QVBoxLayout() if not self.listThread: self.listThread = QListWidget() self.listThread.setFixedWidth(200) self.listThread.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay) self.threadvbox.addWidget(self.threadInfo) self.threadvbox.addWidget(self.listThread) self.groupBoxThreadInfo.setLayout(self.threadvbox) self.addWidget(self.groupBoxThreadInfo) self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy) for id in threads: item = QtGui.QListWidgetItem(id) self.listThread.addItem(item) def connectController(self,controller): self.controller = controller self.connect(controller,QtCore.SIGNAL('setAvailable()'),self.setAvailable) def connectDiagramView(self,view): self.diagramView = view def disconnectMsgRcv(self,receiver): print("Implement this method !!! disconnectMsgRcv") def connectMsgRcv(self,receiver): self.msgRcv.append(receiver) def notifyHide(self): for rcv in self.msgRcv: rcv.activateHide(True) def showHiddenLifelines(self): response, selected_items = HiddenDialog.HiddenDialog.getSelectedItems(self.diagramView.getHiddenLifeLines()) if response: self.diagramView.showLifelines(selected_items) def showHiddenMessages(self): response, selected_items = HiddenMessageDialog.HiddenMessageDialog.getSelectedItems(self.diagramView.getHiddenMessages(),self.diagramView.getHiddenLifeLines()) if response: if selected_items[3] in self.diagramView.getHiddenLifeLines(): confirmation = ShowLifeLineDialog.ShowLifeLineDialog.confirmToShowLifeLine(selected_items[3]) if confirmation: self.diagramView.showLifelines([selected_items[3]]) self.diagramView.showMessages(selected_items) else: self.diagramView.showMessages(selected_items) def notifyCapture(self): for rcv in self.msgRcv: rcv.activateCapture(True) def moveToPrev(self): for rcv in self.msgRcv: rcv.moveToPrev() def moveToNext(self): for rcv in self.msgRcv: rcv.moveToNext() def searchMsg(self): str = self.editTextSearch.toPlainText() for rcv in self.msgRcv: rcv.searchMessage(str)
class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(560, 560) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) Form.setMinimumSize(QtCore.QSize(0, 0)) self.gridLayout_2 = QGridLayout(Form) self.gridLayout_2.setObjectName("gridLayout_2") self.editorGroupBox = QGroupBox(Form) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth( self.editorGroupBox.sizePolicy().hasHeightForWidth()) self.editorGroupBox.setSizePolicy(sizePolicy) self.editorGroupBox.setMinimumSize(QtCore.QSize(0, 0)) self.editorGroupBox.setObjectName("editorGroupBox") self.gridLayout_3 = QGridLayout(self.editorGroupBox) self.gridLayout_3.setObjectName("gridLayout_3") self.gridLayout = QGridLayout() self.gridLayout.setObjectName("gridLayout") self.variable_verticalLayout_1 = QVBoxLayout() self.variable_verticalLayout_1.setObjectName( "variable_verticalLayout_1") self.listBox = QListWidget(self.editorGroupBox) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth( self.listBox.sizePolicy().hasHeightForWidth()) self.listBox.setSizePolicy(sizePolicy) self.listBox.setDragEnabled(True) self.listBox.setDragDropOverwriteMode(False) self.listBox.setDragDropMode(QAbstractItemView.InternalMove) self.listBox.setDefaultDropAction(QtCore.Qt.MoveAction) self.listBox.setAlternatingRowColors(True) self.listBox.setSelectionMode(QAbstractItemView.SingleSelection) self.listBox.setMovement(QListView.Snap) self.listBox.setResizeMode(QListView.Fixed) self.listBox.setSelectionRectVisible(False) self.listBox.setObjectName("listBox") self.variable_verticalLayout_1.addWidget(self.listBox) self.gridLayout.addLayout(self.variable_verticalLayout_1, 0, 0, 1, 1) self.variable_verticalLayout_2 = QVBoxLayout() self.variable_verticalLayout_2.setObjectName( "variable_verticalLayout_2") self.addButton = QPushButton(self.editorGroupBox) self.addButton.setObjectName("addButton") self.variable_verticalLayout_2.addWidget(self.addButton) self.editButton = QPushButton(self.editorGroupBox) self.editButton.setObjectName("editButton") self.variable_verticalLayout_2.addWidget(self.editButton) self.removeButton = QPushButton(self.editorGroupBox) self.removeButton.setObjectName("removeButton") self.variable_verticalLayout_2.addWidget(self.removeButton) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.variable_verticalLayout_2.addItem(spacerItem) self.upButton = QPushButton(self.editorGroupBox) self.upButton.setObjectName("upButton") self.variable_verticalLayout_2.addWidget(self.upButton) self.downButton = QPushButton(self.editorGroupBox) self.downButton.setObjectName("downButton") self.variable_verticalLayout_2.addWidget(self.downButton) spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.variable_verticalLayout_2.addItem(spacerItem1) self.variable_verticalLayout_2.setStretch(3, 1) self.variable_verticalLayout_2.setStretch(6, 1) self.gridLayout.addLayout(self.variable_verticalLayout_2, 0, 1, 1, 1) self.gridLayout.setColumnStretch(0, 1) self.gridLayout_3.addLayout(self.gridLayout, 0, 0, 1, 1) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setContentsMargins(15, 15, 15, 15) self.horizontalLayout.setObjectName("horizontalLayout") spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem2) self.ok_pushButton = QPushButton(self.editorGroupBox) self.ok_pushButton.setObjectName("ok_pushButton") self.horizontalLayout.addWidget(self.ok_pushButton) self.cancel_pushButton = QPushButton(self.editorGroupBox) self.cancel_pushButton.setObjectName("cancel_pushButton") self.horizontalLayout.addWidget(self.cancel_pushButton) self.horizontalLayout.setStretch(0, 1) self.gridLayout_3.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.gridLayout_2.addWidget(self.editorGroupBox, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle( QApplication.translate("Form", "Form", None, QApplication.UnicodeUTF8)) self.editorGroupBox.setTitle( QApplication.translate("Form", "Maya Module Path Editor", None, QApplication.UnicodeUTF8)) self.addButton.setText( QApplication.translate("Form", "<<", None, QApplication.UnicodeUTF8)) self.editButton.setText( QApplication.translate("Form", "Edit", None, QApplication.UnicodeUTF8)) self.removeButton.setText( QApplication.translate("Form", ">>", None, QApplication.UnicodeUTF8)) self.upButton.setText( QApplication.translate("Form", "Move Up", None, QApplication.UnicodeUTF8)) self.downButton.setText( QApplication.translate("Form", "Move Down", None, QApplication.UnicodeUTF8)) self.ok_pushButton.setText( QApplication.translate("Form", "Save", None, QApplication.UnicodeUTF8)) self.cancel_pushButton.setText( QApplication.translate("Form", "Close", None, QApplication.UnicodeUTF8))
class LoginView(View): """`View` derived class. Defines the log in widget""" login = Signal(( str, str, str, bool, )) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(LoginView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(250, 340) def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() ftpInfoLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(20) fieldsLayout.addStretch(80) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addStretch(20) ftpInfoLayout.addWidget(self.hostLabel, 50, Qt.AlignLeft) ftpInfoLayout.addStretch(20) ftpInfoLayout.addWidget(self.sslLabel, 20, Qt.AlignRight) ftpInfoLayout.addWidget(self.sslCheck, 10, Qt.AlignRight) fieldsLayout.addLayout(ftpInfoLayout) fieldsLayout.addWidget(self.hostEdit) fieldsLayout.addWidget(self.usernameLabel) fieldsLayout.addWidget(self.usernameEdit) fieldsLayout.addWidget(self.passwdLabel) fieldsLayout.addWidget(self.passwdEdit) fieldsLayout.addStretch(30) buttonLayout.addStretch(50) buttonLayout.addWidget(self.loginButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(20) mainLayout.addLayout(fieldsLayout, 30) mainLayout.addStretch(20) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 200 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.hostLabel = QLabel(self) self.hostEdit = QLineEdit(self) self.sslLabel = QLabel(self) self.sslCheck = QCheckBox(self) self.hostLabel.setText('FTP Location') self.hostLabel.setFont(labelsFont) self.hostEdit.setFixedWidth(fieldsWidth) self.hostEdit.setFont(editsFont) self.sslLabel.setText('SSL') self.sslLabel.setFont(labelsFont) self.usernameLabel = QLabel(self) self.usernameEdit = QLineEdit(self) self.usernameLabel.setText('Username') self.usernameLabel.setFont(labelsFont) self.usernameEdit.setFixedWidth(fieldsWidth) self.usernameEdit.setFont(editsFont) self.passwdLabel = QLabel(self) self.passwdEdit = QLineEdit(self) self.passwdLabel.setText('Password') self.passwdLabel.setFont(labelsFont) self.passwdEdit.setFixedWidth(fieldsWidth) self.passwdEdit.setEchoMode(QLineEdit.Password) self.passwdEdit.setFont(editsFont) self.passwdEdit.returnPressed.connect(self.onLoginClicked) self.loginButton = QPushButton(self) self.loginButton.setText('Login') self.loginButton.setFont(labelsFont) self.loginButton.setFixedWidth(fieldsWidth / 2) self.loginButton.clicked.connect(self.onLoginClicked) # Sets previously stored values into the fields, if any settings = get_settings() self.hostEdit.setText(settings.value(SettingsKeys['host'], '')) self.usernameEdit.setText(settings.value(SettingsKeys['username'], '')) self.passwdEdit.setText( crypt.decrypt(settings.value(SettingsKeys['passwd'], ''))) # Unicode to boolean conversion ssl = settings.value(SettingsKeys['ssl'], u'true') ssl = True if ssl == u'true' else False self.sslCheck.setChecked(ssl) @Slot() def onLoginClicked(self): """ Slot. Called on the user clicks on the `loginButton` button """ # Takes out the user input from the fields host = self.hostEdit.text() username = self.usernameEdit.text() passwd = self.passwdEdit.text() ssl = self.sslCheck.isChecked() print 'Logging in: %s, %s, %s' % (host, username, '*' * len(passwd)) if len(host) > 0: # If the fields are valid, store them using a `QSettings` object # and triggers a log in request settings = get_settings() settings.setValue(SettingsKeys['host'], host) settings.setValue(SettingsKeys['username'], username) settings.setValue(SettingsKeys['passwd'], crypt.encrypt(passwd)) settings.setValue(SettingsKeys['ssl'], ssl) self.setEnabled(False) self.login.emit(host.strip(), username, passwd, ssl) @Slot() def onFailedLogIn(self): """ Slot. Called when the log in request fails """ # Enables the fields again for user input self.setEnabled(True)
class optdlg(QDialog): def __init__(self, parent=None): super(optdlg, self).__init__(parent) self.setFixedSize(484, 399) appicom = QIcon(":/icons/njnlogo.png") self.setWindowIcon(appicom) self.setWindowTitle("Nigandu English to Tamil Dictionary | OPTIONS") self.buttonBox = QDialogButtonBox(self) self.buttonBox.setEnabled(True) self.buttonBox.setGeometry(QRect(350, 20, 121, 200)) self.buttonBox.setOrientation(Qt.Vertical) self.buttonBox.setStandardButtons(QDialogButtonBox.Apply|QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.buttonBox.setCenterButtons(True) self.restorebtn = QPushButton(self) self.restorebtn.setGeometry(QRect(354, 360, 121, 23)) self.restorebtn.setText("&RestoreDefults") self.fontbox = QGroupBox(self) self.fontbox.setGeometry(QRect(10, 10, 331, 141)) self.spinBox = QSpinBox(self.fontbox) self.spinBox.setGeometry(QRect(100, 20, 81, 21)) self.spinBox.setMinimum(10) self.spinBox.setMaximum(24) self.label = QLabel(self.fontbox) self.label.setGeometry(QRect(20, 20, 71, 21)) self.label.setText("Font Size:") self.fontbox.setTitle("Font") self.samplefontbox = QGroupBox(self) self.samplefontbox.setGeometry(QRect(20, 50, 291, 91)) self.samplefontbox.setTitle("Sample Text") self.sampletxt = QLabel(self.samplefontbox) self.sampletxt.setGeometry(QRect(20, 20, 251, 61)) self.sampletxt.setText("AaBbCcDdEeFfGgHhIiJjKkLlYyZz") self.clipbox = QGroupBox(self) self.clipbox.setGeometry(QRect(10, 160, 331, 61)) self.clipbox.setTitle("ClipBoard Options") self.checkclip = QCheckBox(self.clipbox) self.checkclip.setGeometry(QRect(20, 20, 301, 31)) self.checkclip.setText("Allow copy from clipboard on start-up") self.histbox = QGroupBox(self) self.histbox.setGeometry(QRect(10, 230, 331, 91)) self.histbox.setTitle("History") self.checkshowhistdock = QCheckBox(self.histbox) self.checkshowhistdock.setGeometry(QRect(20, 60, 301, 17)) self.checkshowhistdock.setText("Show History Dock on the right side") self.checkdelhist = QCheckBox(self.histbox) self.checkdelhist.setGeometry(QRect(20, 30, 301, 17)) self.checkdelhist.setText("Clear all the past history records") self.bkmbox = QGroupBox(self) self.bkmbox.setGeometry(QRect(10, 330, 331, 61)) self.bkmbox.setTitle("Book Marks") self.checkshowbkmdock = QCheckBox(self.bkmbox) self.checkshowbkmdock.setGeometry(QRect(20, 30, 301, 17)) self.checkshowbkmdock.setText("Show Book Marks Dock on the right side.") self.spinBox.valueChanged[int].connect(self.setsampletxt) self.restorebtn.clicked.connect(self.setdeafults) self.buttonBox.rejected.connect(self.close) def setdeafults(self): self.spinBox.setValue(13) self.checkshowhistdock.setChecked(True) self.checkshowbkmdock.setChecked(True) self.checkclip.setChecked(True) self.checkdelhist.setChecked(False) def setsampletxt(self, i): font = QFont() font.setPixelSize(i) self.sampletxt.setFont(font)
class MainWindow(QMainWindow): """docstring for MainWindow""" def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.serviceProvider = 0 self.popupMenu = None self.mapControlButtons = [] self.mapControlTypes = [] self.markerObjects = [] self.setWindowTitle(self.tr('Map Viewer Demo')) self.routingManager = None self.mapManager = None self.mapWidget = None self.markerIcon = None self.slider = None manager = QNetworkConfigurationManager() canStartIAP = manager.capabilities() & QNetworkConfigurationManager.CanStartAndStopInterfaces configuration = manager.defaultConfiguration() if not configuration.isValid or (not canStartIAP and configuration.starte() != QNetworkConfiguration.Active): QMessageBox.information(self, self.tr('Map Viewer Demo'), self.tr('Available Access Points not found.')) return self.session = QNetworkSession(configuration, self) self.session.opened.connect(self.networkSessionOpened) self.session.error.connect(self.error) self.session.open() self.session.waitForOpened() self.setProvider('nokia') self.setupUi() def networkSessionOpened(self): pass def sliderValueChanged(self, value): self.mapWidget.setZoomLevel(value) def mapZoomLevelChanged(self, level): self.slider.setSliderPosition(int(level)) def mapTypeChanged(self, newType): index = self.mapControlTypes.index(newType) if index != -1: self.mapControButtons[index].setChecked(True) def mapTypeToggled(self, checked): if checked: button = self.sender() index = self.mapControlButtons.index(button) if index != -1: print index, self.mapControlTypes[index] self.mapWidget.setMapType(self.mapControlTypes[index]) def updateCoords(self, coords): if not coords.isValid(): return self.latitudeEdit.setText('%f' % coords.latitude()) self.longitudeEdit.setText('%f' % coords.longitude()) def setCoordsClicked(self): lat = float(self.latitudeEdit.text()) lon = float(self.longitudeEdit.text()) self.mapWidget.setCenter(QGeoCoordinate(lat, lon)) def setProvider(self, providerId): self.serviceProvider = QGeoServiceProvider(providerId) if self.serviceProvider.error() != QGeoServiceProvider.NoError: QMessageBox.information(self, self.tr('MapViewer Example'), self.tr('Unable to dinf the %s geoservices plugin.' % providerId)) qApp.quit() return self.mapManager = self.serviceProvider.mappingManager() self.routingManager = self.serviceProvider.routingManager() def error(self, error): if error == QNetworkSession.UnknownSessionError: msgBox = QMessageBox(self.parent()) msgBox.setText('This application requires network access to function.') msgBox.setInformativeText('Press Cancel to quit the application.') msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel) msgBox.setIcon(QMessageBox.Information) msgBox.setDefaultButton(QMessageBox.Retry) ret = msgBox.exec_() if ret == QMessageBox.Retry: QTimer.singleShot(0, self.session.open) elif ret == QMessageBox.Cancel: self.close() elif error == QNetworkSession.SessionAbortedError: msgBox = QMessageBox(self.parent()) msgBox.setText('Out of range of network') msgBox.setInformativeText('Move back into range and press Retry, or press Cancel to quit the application') msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel) msgBox.setIcon(QMessageBox.Information) msgBox.setDefaultButton(QMessageBox.Retry) ret = msgBox.exec_() if ret == QMessageBox.Retry: QTimer.singleShot(0, self.session.open) elif ret == QMessageBox.Cancel: self.close() def setupUi(self): scene = QGraphicsScene(self) self.view = QGraphicsView(scene, self) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVisible(True) self.view.setInteractive(True) self.createPixmapIcon() self.mapWidget = MapWidget(self.mapManager) scene.addItem(self.mapWidget) self.mapWidget.setCenter(QGeoCoordinate(-8.1, -34.95)) self.mapWidget.setZoomLevel(5) #... self.slider = QSlider(Qt.Vertical, self) self.slider.setTickInterval(1) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.setMaximum(self.mapManager.maximumZoomLevel()) self.slider.setMinimum(self.mapManager.minimumZoomLevel()) self.slider.valueChanged[int].connect(self.sliderValueChanged) self.mapWidget.zoomLevelChanged[float].connect(self.mapZoomLevelChanged) mapControlLayout = QVBoxLayout() self.mapWidget.mapTypeChanged.connect(self.mapTypeChanged) for mapType in self.mapWidget.supportedMapTypes(): radio = QRadioButton(self) if mapType == QGraphicsGeoMap.StreetMap: radio.setText('Street') elif mapType == QGraphicsGeoMap.SatelliteMapDay: radio.setText('Sattelite') elif mapType == QGraphicsGeoMap.SatelliteMapNight: radio.setText('Sattelite - Night') elif mapType == QGraphicsGeoMap.TerrainMap: radio.setText('Terrain') if mapType == self.mapWidget.mapType(): radio.setChecked(True) radio.toggled[bool].connect(self.mapTypeToggled) self.mapControlButtons.append(radio) self.mapControlTypes.append(mapType) mapControlLayout.addWidget(radio) self.latitudeEdit = QLineEdit() self.longitudeEdit = QLineEdit() formLayout = QFormLayout() formLayout.addRow('Latitude', self.latitudeEdit) formLayout.addRow('Longitude', self.longitudeEdit) self.captureCoordsButton = QToolButton() self.captureCoordsButton.setText('Capture coordinates') self.captureCoordsButton.setCheckable(True) self.captureCoordsButton.toggled[bool].connect( self.mapWidget.setMouseClickCoordQuery) self.mapWidget.coordQueryResult.connect(self.updateCoords) self.setCoordsButton = QPushButton() self.setCoordsButton.setText('Set coordinates') self.setCoordsButton.clicked.connect(self.setCoordsClicked) buttonLayout = QHBoxLayout() buttonLayout.addWidget(self.captureCoordsButton) buttonLayout.addWidget(self.setCoordsButton) coordControlLayout = QVBoxLayout() coordControlLayout.addLayout(formLayout) coordControlLayout.addLayout(buttonLayout) widget = QWidget(self) layout = QGridLayout() layout.setRowStretch(0, 1) layout.setRowStretch(1, 0) topLayout = QGridLayout() bottomLayout = QGridLayout() topLayout.setColumnStretch(0, 0) topLayout.setColumnStretch(1, 1) bottomLayout.setColumnStretch(0, 0) bottomLayout.setColumnStretch(1, 1) topLayout.addWidget(self.slider, 0, 0) topLayout.addWidget(self.view, 0, 1) bottomLayout.addLayout(mapControlLayout, 0, 0) bottomLayout.addLayout(coordControlLayout, 0, 1) layout.addLayout(topLayout, 0, 0) layout.addLayout(bottomLayout, 1, 0) self.layout = layout widget.setLayout(layout) self.setCentralWidget(widget) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect(self.customContextMenuRequest) def createPixmapIcon(self): self.markerIcon = QPixmap(MARKER_WIDTH, MARKER_HEIGHT) self.markerIcon.fill(Qt.transparent) painter = QPainter(self.markerIcon) p1 = QPoint(MARKER_WIDTH / 2, MARKER_HEIGHT - 1) p2 = QPoint(MARKER_WIDTH / 2, MARKER_HEIGHT - 1 - MARKER_PIN_LEN) pen = QPen(Qt.black) pen.setWidth(2) pen.setCosmetic(True) painter.setPen(pen) painter.drawLine(p1, p2) ellipse = QRect(0, 0, MARKER_WIDTH - 1, MARKER_HEIGHT - 1) pen.setWidth(1) painter.setPen(pen) color = QColor(Qt.green) color.setAlpha(127) brush = QBrush(color) painter.setBrush(brush) painter.drawEllipse(ellipse) def resizeEvent(self, event): self.view.setSceneRect(QRectF(QPointF(0.0, 0.0), self.view.size())) self.mapWidget.resize(self.view.size()) def showEvent(self, event): self.view.setSceneRect(QRectF(QPointF(0.0, 0.0), self.view.size())) self.mapWidget.resize(self.view.size()) def createMenus(self): self.popupMenu = QMenu(self) # Markers subMenuItem = QMenu(self.tr('Marker'), self) self.popupMenu.addMenu(subMenuItem) menuItem = QAction(self.tr('Set marker'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawPixmap) menuItem = QAction(self.tr('Remove marker'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.removePixmaps) menuItem = QAction(self.tr('Select objects'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.selectObjects) # Draw subMenuItem = QMenu(self.tr('Draw'), self) self.popupMenu.addMenu(subMenuItem) menuItem = QAction(self.tr('Rectangle'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawRect) menuItem = QAction(self.tr('Polyline'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawPolyline) menuItem = QAction(self.tr('Polygon'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawPolygon) menuItem = QAction(self.tr('Circle'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawCircle) menuItem = QAction(self.tr('Text'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.drawText) # Routing subMenuItem = QMenu(self.tr('Route'), self) self.popupMenu.addMenu(subMenuItem) menuItem = QAction(self.tr('Calculate route'), self) subMenuItem.addAction(menuItem) menuItem.triggered[bool].connect(self.calculateRoute) def selectObjects(self): for obj in self.mapWidget.mapObjects(): obj.setSelected(False) if len(self.markerObjects) < 2: return bottomRight = self.markerObjects.pop() topLeft = self.markerObjects.pop() self.mapWidget.removeMapObject(topLeft) self.mapWidget.removeMapObject(bottomRight) selectedObjects = self.mapWidget.mapObjectsInScreenRect( QRectF(self.mapWidget.coordinateToScreenPosition(topLeft.coordinate()), self.mapWidget.coordinateToScreenPosition(bottomRight.coordinate())) ) for obj in selectedObjects: obj.setSelected(True) def drawRect(self): if len(self.markerObjects) < 2: return p1, p2 = self.markerObjects[:2] pen = QPen(Qt.white) pen.setWidth(2) pen.setCosmetic(True) fill = QColor(Qt.black) fill.setAlpha(65) rectangle = QGeoMapRectangleObject(p1.coordinate(), p2.coordinate()) rectangle.setPen(pen) rectangle.setBrush(QBrush(fill)) self.mapWidget.addMapObject(rectangle) def drawPolyline(self): path = [mark.coordinate() for mark in self.markerObjects] pen = QPen(Qt.white) pen.setWidth(2) pen.setCosmetic(True) polyline = QGeoMapPolylineObject() polyline.setPen(pen) polyline.setPath(path) self.mapWidget.addMapObject(polyline) def drawPolygon(self): path = [mark.coordinate() for mark in self.markerObjects] pen = QPen(Qt.white) pen.setWidth(2) pen.setCosmetic(True) polygon = QGeoMapPolygonObject() polygon.setPen(pen) fill = QColor(Qt.black) fill.setAlpha(65) polygon.setBrush(QBrush(fill)) polygon.setPath(path) self.mapWidget.addMapObject(polygon) def drawCircle(self): if not len(self.markerObjects): return p1 = self.markerObjects[0] center = p1.coordinate() radius = 3000 # Meters if len(self.markerObjects) >= 2: radius = center.distanceTo(self.markerObjects[1].coordinate()) pen = QPen(Qt.white) pen.setWidth(2) pen.setCosmetic(True) circle = QGeoMapCircleObject(center, radius) circle.setPen(pen) fill = QColor(Qt.black) fill.setAlpha(65) circle.setBrush(QBrush(fill)) self.mapWidget.addMapObject(circle) def drawText(self): if not len(self.markerObjects): return start = self.markerObjects[0].coordinate() text = QGeoMapTextObject(start, 'Text') fill = QColor(Qt.black) text.setBrush(fill) self.mapWidget.addMapObject(text) def calculateRoute(self): if len(self.markerObjects) < 2: return waypoints = [x.coordinate() for x in self.markerObjects[:2]] request = QGeoRouteRequest(waypoints) self.routeReply = self.routingManager.calculateRoute(request) self.routeReply.finished.connect(self.routeFinished) def routeFinished(self): if not self.routeReply.routes(): return route = QGeoMapRouteObject(self.routeReply.routes()[0]) routeColor = QColor(Qt.blue) routeColor.setAlpha(127) pen = QPen(routeColor) pen.setWidth(7) pen.setCosmetic(True) pen.setCapStyle(Qt.RoundCap) route.setPen(pen) self.mapWidget.addMapObject(route) def drawPixmap(self): marker = QGeoMapPixmapObject(self.mapWidget.screenPositionToCoordinate(self.lastClicked), QPoint(-(MARKER_WIDTH / 2), -MARKER_HEIGHT), self.markerIcon) self.mapWidget.addMapObject(marker) self.markerObjects.append(marker) def removePixmaps(self): for i in range(len(self.markerObjects)): marker = self.markerObjects.pop() self.mapWidget.removeMapObject(marker) marker.deleteLater() def customContextMenuRequest(self, point): self.lastClicked = point if self.focusWidget() == self.view: if not self.popupMenu: self.createMenus() self.popupMenu.popup(self.view.mapToGlobal(self.lastClicked))
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(583, 96) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.gridLayout = QGridLayout() self.gridLayout.setObjectName("gridLayout") self.UI_label = QLabel(self.centralwidget) self.UI_label.setObjectName("UI_label") self.gridLayout.addWidget(self.UI_label, 0, 0, 1, 1) self.seleccionarUI_pushButton = QPushButton(self.centralwidget) self.seleccionarUI_pushButton.setObjectName("seleccionarUI_pushButton") self.gridLayout.addWidget(self.seleccionarUI_pushButton, 0, 2, 1, 1) self.Py_label = QLabel(self.centralwidget) self.Py_label.setObjectName("Py_label") self.gridLayout.addWidget(self.Py_label, 1, 0, 1, 1) self.rutaSalida_pushButton = QPushButton(self.centralwidget) self.rutaSalida_pushButton.setObjectName("rutaSalida_pushButton") self.gridLayout.addWidget(self.rutaSalida_pushButton, 1, 2, 1, 1) self.rutaEntrada_lineEdit = QLineEdit(self.centralwidget) self.rutaEntrada_lineEdit.setEnabled(False) self.rutaEntrada_lineEdit.setObjectName("rutaEntrada_lineEdit") self.gridLayout.addWidget(self.rutaEntrada_lineEdit, 0, 1, 1, 1) self.rutaSalida_lineEdit = QLineEdit(self.centralwidget) self.rutaSalida_lineEdit.setObjectName("rutaSalida_lineEdit") self.gridLayout.addWidget(self.rutaSalida_lineEdit, 1, 1, 1, 1) self.verticalLayout.addLayout(self.gridLayout) self.horizontalWidget = QWidget(self.centralwidget) self.horizontalWidget.setObjectName("horizontalWidget") self.horizontalLayout = QHBoxLayout(self.horizontalWidget) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setObjectName("horizontalLayout") spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.convertir_pushButton = QPushButton(self.horizontalWidget) self.convertir_pushButton.setObjectName("convertir_pushButton") self.horizontalLayout.addWidget(self.convertir_pushButton) self.verticalLayout.addWidget(self.horizontalWidget) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle( QApplication.translate( "MainWindow", "Convertidor UI a Py", None, QApplication.UnicodeUTF8 ) ) self.UI_label.setText( QApplication.translate( "MainWindow", "Seleccionar UI:", None, QApplication.UnicodeUTF8 ) ) self.seleccionarUI_pushButton.setText( QApplication.translate( "MainWindow", "Abrir...", None, QApplication.UnicodeUTF8 ) ) self.Py_label.setText( QApplication.translate( "MainWindow", "Archivo Py:", None, QApplication.UnicodeUTF8 ) ) self.rutaSalida_pushButton.setText( QApplication.translate( "MainWindow", "...", None, QApplication.UnicodeUTF8 ) ) self.convertir_pushButton.setText( QApplication.translate( "MainWindow", "Convertir", None, QApplication.UnicodeUTF8 ) ) #Codigo agregado para ensamblar el GUI con el programa actual self.seleccionarUI_pushButton.clicked.connect(self.seleccionarUI) self.rutaSalida_pushButton.clicked.connect(self.seleccionarPY) self.convertir_pushButton.clicked.connect(convertir) #Funciones anexadas para la funcionalidad de los botones def seleccionarUI(self): dialogo = QFileDialog(None) dialogo.setFileMode(QFileDialog.ExistingFile) dialogo.setNameFilter('Interfaz(*.ui)') if dialogo.exec_(): global Ruta_archivoUI Ruta_archivoUI = dialogo.selectedFiles()[0] self.rutaEntrada_lineEdit.setText(Ruta_archivoUI) def seleccionarPY(self): dialogo = QFileDialog(None) dialogo.setFileMode(QFileDialog.AnyFile) dialogo.setNameFilter('Archivo Python(*.py)') dialogo.setAcceptMode(QFileDialog.AcceptSave) dialogo.setDefaultSuffix('py') if dialogo.exec_(): global Ruta_archivoPY Ruta_archivoPY = dialogo.selectedFiles()[0] self.rutaSalida_lineEdit.setText(Ruta_archivoPY)