def showImageTab(self): items = ['Use Imageinfo', 'VistaSP0x64', 'VistaSP0x86', 'VistaSP1x64', 'VistaSP2x64', \ 'VistaSP2x86', 'Win2003SP0x86', 'Win2003SP1x64', 'Win2003SP1x86', 'Win2003SP2x64', \ 'Win2003SP2x86', 'Win2008R2SP0x64', 'Win2008R2SP1x64', 'Win2008SP1x64', 'Win2008SP1x86', \ 'Win2008SP2x64', 'Win7SP0x64', 'Win7SP0x86', 'Win7SP1x64', 'Win7SP1x86', 'WinXPSP1x64', \ 'WinXPSP2x64', 'WinXPSP2x86', 'WinXPSP3x86'] fileNameLabel = QLabel("Image: ") profileLabel = QLabel("Profile: ") fileName = QLabel(self.filename) self.profileSelector = QComboBox() self.profileSelector.addItems(items) # index = items.index(self.profile) self.profileSelector.setCurrentIndex(index) horizontalLayout = QHBoxLayout() grid = QGridLayout() grid.addWidget(fileNameLabel, 1, 0) grid.addWidget(fileName, 1, 1) grid.addWidget(profileLabel, 2, 0) grid.addWidget(self.profileSelector, 2, 1) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) grid.addItem(spacerItem) horizontalLayout.addItem(grid) horizontalLayout.addStretch() self.connect(self.profileSelector, SIGNAL("currentIndexChanged(QString)"), self.storeProfile) self.addTabFnc("Image", horizontalLayout) self.dirty = True
class DMessage(VDialog): def __init__(self, parent): VDialog.__init__(self, parent) self.resize(450, 150) self.gLayout = QGridLayout(self) self.mesaj = QLabel(self) self.gLayout.addWidget(self.mesaj, 0, 0, 1, 3) self.pDaha = QPushButton(self) self.gLayout.addWidget(self.pDaha, 1, 1, 1, 1) self.pUzulme = QPushButton(self) self.gLayout.addWidget(self.pUzulme, 1, 2, 1, 1) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gLayout.addItem(spacerItem, 1, 0, 1, 1) self.pDaha.clicked.connect(self.daha) self.pUzulme.clicked.connect(self.close) self.setWindowTitle(u"Hay Aksi!") self.mesaj.setText(u"Hay Aksi! Elimden kaçırdım bir tane...") self.pDaha.setText(u"Daha dikkatli ol!") self.pUzulme.setText(u"Üzülme be abi") def daha(self): QMessageBox.information(self, u"Emredersiniz!", u"Emredersiniz Paşam!", u"Uzatma!") self.close()
class DMessage(VDialog): def __init__(self, parent): VDialog.__init__(self, parent) self.resize(450, 150) self.gLayout = QGridLayout(self) self.mesaj = QLabel(self) self.gLayout.addWidget(self.mesaj, 0, 0, 1, 3) self.pYapma = QPushButton(self) self.gLayout.addWidget(self.pYapma, 1, 2, 1, 1) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gLayout.addItem(spacerItem, 1, 0, 1, 1) self.pSifirlama = QPushButton(self) self.pSifirlama.setEnabled(False) self.gLayout.addWidget(self.pSifirlama, 1, 1, 1, 1) self.pYapma.clicked.connect(self.yapma) self.setWindowTitle(u"Eyvah!") self.mesaj.setText(u"Virux, sistemin tamamını virüs olarak algıladı. Sistem sıfırlanıyor.") self.pYapma.setText(u"Yapma be abi!") self.pSifirlama.setText(u"Sıfırlama!") def yapma(self): QMessageBox.information(self, u":)", u"Yaptım bile!", u"Öyle olsun :(") self.close()
class DMessage(VDialog): def __init__(self, parent): VDialog.__init__(self, parent) self.resize(450, 150) self.gLayout = QGridLayout(self) self.mesaj = QLabel(self) self.gLayout.addWidget(self.mesaj, 0, 0, 1, 3) self.pYapma = QPushButton(self) self.gLayout.addWidget(self.pYapma, 1, 2, 1, 1) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gLayout.addItem(spacerItem, 1, 0, 1, 1) self.pSifirlama = QPushButton(self) self.pSifirlama.setEnabled(False) self.gLayout.addWidget(self.pSifirlama, 1, 1, 1, 1) self.pYapma.clicked.connect(self.yapma) self.setWindowTitle(u"Eyvah!") self.mesaj.setText( u"Virux, sistemin tamamını virüs olarak algıladı. Sistem sıfırlanıyor." ) self.pYapma.setText(u"Yapma be abi!") self.pSifirlama.setText(u"Sıfırlama!") def yapma(self): QMessageBox.information(self, u":)", u"Yaptım bile!", u"Öyle olsun :(") self.close()
def add_global_shortcut_page(self,dialog): self.kb_settings_page = QWidget() layout = QGridLayout() self.kb_settings_page.setLayout(layout) self.louder_action_editor = KKeySequenceWidget() self.louder_action_editor.setKeySequence( self.louder_action.globalShortcut().primary()) self.louder_action_editor.keySequenceChanged.connect(dialog.settingsModified) layout.addWidget(QLabel(i18n("Veromix volume up")), 0,0) layout.addWidget(self.louder_action_editor, 0,1) self.lower_action_editor = KKeySequenceWidget() self.lower_action_editor.setKeySequence( self.lower_action.globalShortcut().primary()) self.lower_action_editor.keySequenceChanged.connect(dialog.settingsModified) layout.addWidget(QLabel(i18n("Veromix volume down")), 1, 0) layout.addWidget(self.lower_action_editor, 1, 1) self.mute_action_editor = KKeySequenceWidget() self.mute_action_editor.setKeySequence( self.mute_action.globalShortcut().primary()) self.mute_action_editor.keySequenceChanged.connect(dialog.settingsModified) layout.addWidget(QLabel(i18n("Veromix toggle mute")), 2, 0) layout.addWidget(self.mute_action_editor, 2, 1) layout.addItem(QSpacerItem(0,0, QSizePolicy.Minimum,QSizePolicy.Expanding), 3,0) dialog.addPage(self.kb_settings_page, i18n("Volume Keyboard Shortcuts"), "preferences-desktop-keyboard")
class SynchronizedEditors(QWidget): def __init__(self): super(SynchronizedEditors, self).__init__() self._layout = QGridLayout() @property def layout(self): return self._layout @layout.setter def layout(self, layout): self._layout = layout self.initUI() def initUI(self): self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.setFocusPolicy(Qt.StrongFocus) self.setLayout(self._layout) self.show() def addEditorWidget(self, imageEditorWidget, position=(0, 0)): self.checkPosition(position) self._layout.addWidget(imageEditorWidget, position[0], position[1]) def checkPosition(self, position): widget = self._layout.itemAtPosition(position[0], position[1]) if widget: freePos = self.getFreePosition() self._layout.removeItem(widget) self._layout.addItem(widget, freePos[0], freePos[1]) def getFreePosition(self): i = 0 j = 0 while self._layout.itemAtPosition(i, j): while i > j: if self._layout.itemAtPosition(i, j): break j = j + 1 i = i + 1 return (i, j) def link(self, iEWidget1, iEWidget2): iEWidget2._imageEditor.posModel = iEWidget1._imageEditor.posModel self._saveShape = iEWidget1._imageEditor.posModel.shape def unlink(self, iEWidget1, iEWidget2): shape = iEWidget1._imageEditor.posModel.shape iEWidget1._imageEditor.posModel = PositionModelImage() iEWidget2._imageEditor.posModel = PositionModelImage() iEWidget1._imageEditor.posModel.shape = shape iEWidget2._imageEditor.posModel.shape = shape
def init_ui(self): """Init the UI""" klog.debug('init_ui') self.setWindowTitle('Cinfkiosk') #self.setWindowIcon(QIcon('web.png')) layout = QGridLayout(self) # Add graphs # FIXME Maybe flowlayout, gridlayout or anchorlayout max_column = 0 max_row = 0 for xmldef in self.xml.findall('table') + self.xml.findall('figure'): id_ = xmldef.attrib['id'] if xmldef.tag == "figure": # Make the figure if id_ in self.figures: raise ValueError('The graph id must be unique. "{} already known"'\ .format(id_)) klog.debug("Add figure: %s", id_) element = Cinfpyqtgraph(self, xmldef, include_old_data=self.include_old_data) self.figures[id_] = element else: element = CinfQTable(parent=self, table_def=xmldef) self.tables[id_] = element # Add it to the grid layout # grid is [row, column, rowspan, columnspan] or [row, column] grid = typed(xmldef.find('grid')) # Pad 1's for the row and column span if necessary grid = grid + [1] * (4 - len(grid)) klog.debug("Add to grid %s", grid) max_column = max(max_column, grid[1] + grid[3] - 1) max_row = max(max_row, grid[0] + grid[2] - 1) layout.addWidget(element, *grid) for table in self.tables.values(): table.finalize_table() klog.debug("Add spacer to %s, %s", max_row + 1, max_column + 1) layout.addItem(QSpacerItem(1, 1), max_row + 1, max_column + 1) layout.setColumnStretch(max_column + 1, 1) layout.setRowStretch(max_row + 1, 1) self.setLayout(layout) klog.debug('show') self.showMaximized() self.show()
def __init__(self, publisher, plugin, parentWidget=None): DialogBase.__init__(self, parentWidget) self.setupUi(self) self.setObjectName("ProgressDialog") self.viewButton_.setEnabled(False) self._publisher = publisher self._plugin = plugin self._parent = parentWidget self._cancelled = False self._timeline = QTimeLine(1000 * 60, self) self._timeline.setFrameRange(0, 2 * 60) self._timeline.setLoopCount(0) self.progressBar_.setRange(0, 60) self.connect(self._timeline, QtCore.SIGNAL("frameChanged(int)"), self.updateProgressBar) self.outputGroupBox_ = QGroupBox("Script output", None) self.outputTextEdit_ = QTextEdit() self.outputTextEdit_.setTextInteractionFlags( Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse) self.outputTextEdit_.setReadOnly(True) self.outputTextEdit_.setTabChangesFocus(True) self.outputTextEdit_.setAcceptRichText(False) groupBoxLayout = QVBoxLayout() groupBoxLayout.setObjectName("groupBoxLayout") groupBoxLayout.setMargin(0) groupBoxLayout.addWidget(self.outputTextEdit_) self.outputGroupBox_.setLayout(groupBoxLayout) gridLayout = QGridLayout() gridLayout.setSizeConstraint(gridLayout.SetFixedSize) gridLayout.addWidget(self.progressLabel_, 0, 0, 1, 4) gridLayout.addWidget(self.progressBar_, 1, 0, 1, 4) gridLayout.addWidget(self.detailsCheckBox_, 2, 0) hSpacer = QSpacerItem(250, 10, QSizePolicy.Expanding) gridLayout.addItem(hSpacer, 2, 1) gridLayout.addWidget(self.viewButton_, 2, 2) gridLayout.addWidget(self.cancelButton_, 2, 3) gridLayout.addWidget(self.outputGroupBox_, 3, 0, 1, 4) self.setLayout(gridLayout) self.outputGroupBox_.setVisible(False)
def buildChooseLanguage(self, layout, row, col): language = QGroupBox(self) language.setTitle(tr('Language for emails')) language_layout = QGridLayout(language) language_info = QLabel(tr('Language for emails sent by EdenWall to the Administrator')) language_info.setWordWrap(True) language_choose = QComboBox() for name in ContactConf.CODE_TO_NAME.itervalues(): language_choose.addItem(name) language_layout.addWidget(language_info, 0, 0, 1, 0) language_layout.addWidget(language_choose, 1, 0) language_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) , 1, 1) self.connect(language_choose, SIGNAL('activated(QString)'), self.setLanguage) layout.addWidget(language, row, col) self.mainwindow.writeAccessNeeded(language_info, language_choose) return language_choose
def buildAdminMail(self, layout, row, col): admin_mail = QGroupBox(self) admin_mail.setTitle(tr("Administrator email address")) admin_mail_layout = QGridLayout(admin_mail) admin_mail_info = QLabel(tr("Administrator email address (EdenWall will send the system alerts to this address)")) admin_mail_info.setWordWrap(True) admin_mail_edit = MailEdit() admin_mail_edit.setMinimumWidth(admin_mail_edit.fontMetrics().averageCharWidth() * 15) admin_mail_edit.setMaximumWidth(admin_mail_edit.fontMetrics().averageCharWidth() * 45) admin_mail_layout.addWidget(admin_mail_info, 0, 0) admin_mail_layout.addWidget(admin_mail_edit, 1, 0) admin_mail_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) , 2, 0) self.connect(admin_mail_edit, SIGNAL('textEdited(QString)'), self.setAdminMail) layout.addWidget(admin_mail, row, col) self.mainwindow.writeAccessNeeded(admin_mail_info, admin_mail_edit) return admin_mail_edit
class CombinedValueRangeWidget(QWidget): def __init__(self, parent = None): super(CombinedValueRangeWidget, self).__init__(parent) self.roiWidgets = [] self.roiLayout = QGridLayout(self) self.setLayout(self.roiLayout) hbox = QHBoxLayout() hbox.addWidget(QLabel("min"),0,Qt.Alignment(Qt.AlignLeft)) hbox.addWidget(QLabel("max"),0,Qt.Alignment(Qt.AlignLeft)) self.roiLayout.addLayout(hbox, 0,1) self.roiLayout.addWidget(QLabel("Export Full Range"), 0, 2) self.roiLayout.addItem(QSpacerItem(0,0,QSizePolicy.Expanding, QSizePolicy.Minimum),0,3) self.roiCheckBoxes = [] self.setFocusPolicy(Qt.TabFocus) self.lastInChain = super(CombinedValueRangeWidget, self).nextInFocusChain() def addRanges(self, keys, extents): for key, extent in zip(keys, extents): w = ValueRangeWidget(self) w.setFocusPolicy(Qt.TabFocus) w.setDType(numpy.uint32) w.setValues(0,extent) w.setLimits(0,extent) #w.setLabels("min:","max:") self.roiWidgets.append(w) row = self.roiLayout.rowCount() align = Qt.Alignment(Qt.AlignLeft) check = QCheckBox() self.roiCheckBoxes.append(check) check.setChecked(True) check.setFocusPolicy(Qt.ClickFocus) w.changedSignal.connect(partial(check.setChecked,False)) if extent == 1: w.setEnabled(False) check.toggled.connect(partial(check.setChecked, True)) #w.setBackgroundColor("gray", [0,1]) self.roiLayout.addWidget(QLabel(key + ": "),row, 0, align) self.roiLayout.addWidget(self.roiWidgets[-1],row, 1, align) self.roiLayout.addWidget(check,row, 2, align) def focusInEvent(self, QFocusEvent): if len(self.roiWidgets) > 0: self.roiWidgets[0].setFocus()
def __init__(self, publisher, plugin, parentWidget=None): DialogBase.__init__(self, parentWidget) self.setupUi(self) self.setObjectName("ProgressDialog") self.viewButton_.setEnabled(False) self._publisher = publisher self._plugin = plugin self._parent = parentWidget self._cancelled = False self._timeline = QTimeLine(1000*60, self) self._timeline.setFrameRange(0, 2*60) self._timeline.setLoopCount(0) self.progressBar_.setRange(0, 60) self.connect(self._timeline, QtCore.SIGNAL("frameChanged(int)"), self.updateProgressBar) self.outputGroupBox_ = QGroupBox("Script output", None) self.outputTextEdit_ = QTextEdit() self.outputTextEdit_.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse) self.outputTextEdit_.setReadOnly(True) self.outputTextEdit_.setTabChangesFocus(True) self.outputTextEdit_.setAcceptRichText(False) groupBoxLayout = QVBoxLayout() groupBoxLayout.setObjectName("groupBoxLayout") groupBoxLayout.setMargin(0) groupBoxLayout.addWidget(self.outputTextEdit_) self.outputGroupBox_.setLayout(groupBoxLayout) gridLayout = QGridLayout() gridLayout.setSizeConstraint(gridLayout.SetFixedSize) gridLayout.addWidget(self.progressLabel_, 0, 0, 1, 4) gridLayout.addWidget(self.progressBar_, 1, 0, 1, 4) gridLayout.addWidget(self.detailsCheckBox_, 2, 0) hSpacer = QSpacerItem(250, 10, QSizePolicy.Expanding) gridLayout.addItem(hSpacer, 2, 1) gridLayout.addWidget(self.viewButton_, 2, 2) gridLayout.addWidget(self.cancelButton_, 2, 3) gridLayout.addWidget(self.outputGroupBox_, 3, 0, 1, 4) self.setLayout(gridLayout) self.outputGroupBox_.setVisible(False)
def buildTestMail(self, layout, row, col): test = QGroupBox(self) test.setTitle(tr('Test for emails')) test_layout = QGridLayout(test) test_info = QLabel(tr( "To check the configuration, you can send a test " "email to your contact email address. Be sure to configure the " "smarthost in the Mail page if needed." )) test_info.setWordWrap(True) test_button = Button(text=tr('Send test email'), flat=False) test_layout.addWidget(test_info, 0, 0, 1, 0) test_layout.addWidget(test_button, 1, 0) test_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) , 1, 1) self.connect(test_button, SIGNAL('clicked()'), self.sendTestMail) layout.addWidget(test, row, col) self.mainwindow.writeAccessNeeded(test_info, test_button) return test_button
def buildTestMail(self, layout, row, col): test = QGroupBox(self) test.setTitle(tr('Test for emails')) test_layout = QGridLayout(test) test_info = QLabel(tr('To check the configuration, you can send a test ' 'email to the email address of your contact. Be sure to configure the ' 'smarthost in the Email page if you need one.')) test_info.setWordWrap(True) test_button = Button(text=tr('Send test email'), flat=False) test_layout.addWidget(test_info, 0, 0, 1, 2) test_layout.addWidget(test_button, 1, 0) test_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred), 1, 1) self.connect(test_button, SIGNAL('clicked()'), self.sendTestMail) layout.addWidget(test, row, col) return test_button
class DMessage(VDialog): def __init__(self, parent): VDialog.__init__(self, parent) self.resize(450, 150) self.gLayout = QGridLayout(self) self.pBulunan = QPushButton(self) self.pBulunan.setEnabled(False) self.pBulunan.clicked.connect(self.bulunan) self.gLayout.addWidget(self.pBulunan, 3, 2, 1, 1) self.mesaj = QLabel(self) self.gLayout.addWidget(self.mesaj, 0, 0, 1, 3) self.pBar = QProgressBar(self) self.pBar.setProperty("value", 0) self.gLayout.addWidget(self.pBar, 1, 0, 1, 3) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gLayout.addItem(spacerItem, 3, 0, 1, 1) spacerItem1 = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gLayout.addItem(spacerItem1, 2, 0, 1, 3) self.setWindowTitle(u"Sistemi taramaya karar verdim...") self.pBulunan.setText(u"Bulunan Virüsleri Sil") self.mesaj.setText(u"") self.mesaj.setMaximumWidth(430) self.progress = Thread(self) self.progress.start() self.connect(self.progress, SIGNAL("setValue"), self.pBar.setValue) self.mesaj.setText(u"Dosya bilgileri alınıyor...") def bulunan(self): QMessageBox.information(self, u"Sildim gitti!", u"Sayamayacağım kadar virüs silindi!", u"Bileğine Kuvvet!") self.close() @staticmethod def getOption(): return Option()
def buildSenderMail(self, layout, row, col): sender_mail = QGroupBox(self) sender_mail.setTitle(tr("Sender email address for system messages")) sender_mail_layout = QGridLayout(sender_mail) sender_mail_info = QLabel( tr("Email address that will be used as the sender address in the emails sent to the administrator by EdenWall.") ) sender_mail_info.setWordWrap(True) sender_mail_edit = MailEdit() sender_mail_edit.setMinimumWidth(sender_mail_edit.fontMetrics().averageCharWidth() * 15) sender_mail_edit.setMaximumWidth(sender_mail_edit.fontMetrics().averageCharWidth() * 45) sender_mail_layout.addWidget(sender_mail_info, 0, 0) sender_mail_layout.addWidget(sender_mail_edit, 1, 0) sender_mail_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) , 2, 0) self.connect(sender_mail_edit, SIGNAL('textEdited(QString)'), self.setSenderMail) layout.addWidget(sender_mail, row, col) self.mainwindow.writeAccessNeeded(sender_mail_info, sender_mail_edit) return sender_mail_edit
def add_audio_settings(self, dialog): self.audio_settings_page = QWidget() layout = QGridLayout() self.audio_settings_page.setLayout(layout) self.max_volume_spinbox = QSpinBox() self.max_volume_spinbox.setRange(1,255) self.max_volume_spinbox.setSingleStep(1) self.max_volume_spinbox.setValue(self.get_max_volume_value()) self.max_volume_spinbox.valueChanged.connect(dialog.settingsModified) layout.addWidget(QLabel(i18n("Max volume value")), 0,0) layout.addWidget(self.max_volume_spinbox, 0,1) self.automute_checkbox = QCheckBox() self.automute_checkbox.setChecked(self.get_auto_mute()) self.automute_checkbox.stateChanged.connect(dialog.settingsModified) layout.addWidget(QLabel(i18n("Mute if volume reaches zero")), 1,0) layout.addWidget(self.automute_checkbox, 1,1) layout.addItem(QSpacerItem(0,20, QSizePolicy.Minimum,QSizePolicy.Fixed), 2,0) layout.addWidget(QLabel("<b>"+i18n("Sound Card Profiles")+"</b>"), 3,0) index=4 self.card_settings = {} for card in self.widget.card_infos.values(): combo = QComboBox() #self.automute_checkbox.setChecked(self.get_auto_mute()) #print card.properties layout.addWidget(QLabel(card.properties[dbus.String("device.description")]), index,0) layout.addWidget(combo, index,1) index = index + 1 self.card_settings[combo] = card profiles = card.get_profiles() active = card.get_active_profile_name() active_index = 0 for profile in profiles: combo.addItem(profile.description) if active == profile.name: active_index = profiles.index(profile) combo.setCurrentIndex(active_index) layout.addItem(QSpacerItem(0,0, QSizePolicy.Minimum,QSizePolicy.Expanding), index,0) dialog.addPage(self.audio_settings_page, i18n("Pulseaudio"), "audio-card")
def add_ladspa_settings(self, dialog): self.ladspa_settings_page = QWidget() layout = QGridLayout() self.ladspa_settings_page.setLayout(layout) text = i18n("LADSPA is a standard for handling audio filters and effects. Every linux software archive offers a large number of effects - search for LADSPA to get more.\ Not every effect is supported by Pulseaudio and others simple don't make sense (or create only noise).<br/><br/>\ The following list shows all available effects on your system: Only checked effects will appear in the context-menu.") if not LADSPAEffects().ladspa_sdk_available(): text = text + i18n("<br/><br/><b>Warning:</b> Cannot find the executables 'listplugins' and 'analyseplugin' which are required for dynamically detecting installed effects.<br/>\ In OpenSUSE, Fedora and Arch Linux the package is named 'ladspa', in Debian/Ubuntu 'ladspa-sdk'.<br/><br/>") ladspa_intro = QLabel(text) ladspa_intro.setWordWrap(True) layout.addWidget(ladspa_intro, 0,0) self.ladspa_enabled_checkbox = QCheckBox() self.ladspa_enabled_checkbox.setText(i18n("Enable LADSPA effects.")) self.ladspa_enabled_checkbox.setChecked(self.is_ladspa_enabled()) self.ladspa_enabled_checkbox.stateChanged.connect(dialog.settingsModified) layout.addWidget(self.ladspa_enabled_checkbox, 1,0) self.effects_list_widget = QListWidget() layout.addWidget(self.effects_list_widget,2,0) self.effects_list_widget.itemClicked.connect(dialog.settingsModified) blacklisted = LADSPAEffects().blacklist() effects = LADSPAEffects().all_effects() for effect in effects: item = QListWidgetItem(effect["preset_name"]) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) if effect["preset_name"] in blacklisted: item.setCheckState(Qt.Unchecked) else: item.setCheckState(Qt.Checked) self.effects_list_widget.addItem(item) layout.addItem(QSpacerItem(0,0, QSizePolicy.Minimum,QSizePolicy.Expanding), 3,0) dialog.addPage(self.ladspa_settings_page, i18n("Effects / Equalizer"), "preferences-desktop-sound")
class DMessage(VDialog): def __init__(self, parent): VDialog.__init__(self, parent) self.resize(450, 150) self.gLayout = QGridLayout(self) self.mesaj = QLabel(self) self.gLayout.addWidget(self.mesaj, 0, 0, 1, 3) self.pGeliyor = QPushButton(self) self.pGeliyor.setMinimumSize(100, 0) self.gLayout.addWidget(self.pGeliyor, 1, 1, 1, 1) self.pHelal = QPushButton(self) self.pHelal.setMinimumSize(100, 0) self.gLayout.addWidget(self.pHelal, 1, 2, 1, 1) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gLayout.addItem(spacerItem, 1, 0, 1, 1) self.pGeliyor.clicked.connect(self.geliyor) self.pHelal.clicked.connect(self.helal) self.setWindowTitle(u"Yardım Et!") self.mesaj.setText( u"Ölümcül bir virüs buldum ama o kadar güçlü ki baş edemiyorum.<br>Ya yardımıma bir iki antivirüs programı daha gönder ya da hakkını helal et!..." ) self.pGeliyor.setText(u"Geliyor abi!") self.pHelal.setText(u"Helal olsun!") def geliyor(self): QMessageBox.information(self, u"Yettim Gayri!", u"Yardıma geldik abi!", u"Afferin!") self.close() def helal(self): QMessageBox.information(self, u"Üzülme!", u"Her şeyin bir çaresi vardır!", u"Çare bul!") QMessageBox.information(self, u"Çare bulundu!", u"Her şeyin bir çaresi vardır demiştim!", u"Allah razı olsun!") self.close()
def add_to_grid(*items): """Add items to a QGrid layout easily. Keyword arguments: *items -- list with lists of items to be added. items in the same list will be added to the same line of grid. """ layout = QGridLayout() # for now it adds only 1 item per cell. for x, _list in enumerate(items): for y, item in enumerate(_list): if isinstance(item, QWidget): layout.addWidget(item, x, y) elif isinstance(item, QLayout): layout.addLayout(item, x, y) elif isinstance(item, QSpacerItem): layout.addItem(item, x, y) elif item is None: pass else: raise TypeError("Argument of wrong type!") return layout
def setup_dynamically(self): font = QFont() font.setBold(False) lineEdit_list = [] Layout = QGridLayout() row = 0 col = 0 values = self.sheet.row_values(3, 1) for x in range(1, len(values)): if values[x-1] == "!": break else: cell = self.sheet.cell_value(1, x) tool_tip = self.sheet.cell_value(2, x) Layout2 = QVBoxLayout() label = QLabel(str(cell)) label.setFont(font) lineedit = QLineEdit() lineedit.setFont(font) lineedit.setToolTip(str(tool_tip)) lineedit.setEnabled(0) Layout2.addWidget(label) Layout2.addWidget(lineedit) vert_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Maximum) Layout2.addItem(vert_spacer) Layout.addLayout(Layout2, row, col) lineEdit_list.append(lineedit) if x > 0: if x % 5 == 0: row += 1 col = 0 vert_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Maximum) Layout.addItem(vert_spacer) else: col += 1 self.groupBox2.setLayout(Layout) return lineEdit_list
class DHakkinda(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(500, 350) self.setMaximumSize(500, 350) self.gLayout =QGridLayout(self) self.logo = QLabel(self) self.logo.setPixmap(QPixmap(":/logo/data/logo.png")) self.gLayout.addWidget(self.logo, 0, 0, 2, 1) self.appName = QLabel(self) font = QFont() font.setPointSize(32) font.setWeight(50) self.appName.setFont(font) self.gLayout.addWidget(self.appName, 0, 1, 1, 2) self.appVersion = QLabel(self) font = QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.appVersion.setFont(font) self.appVersion.setAlignment(Qt.AlignHCenter|Qt.AlignTop) self.gLayout.addWidget(self.appVersion, 1, 1, 1, 2) self.gBox = QGroupBox(self) font = QFont() font.setPointSize(12) font.setWeight(75) font.setBold(True) self.gBox.setFont(font) self.gLayout2 = QGridLayout(self.gBox) self.scrollArea = QScrollArea(self.gBox) self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setWidgetResizable(True) self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setGeometry(0, 0, 476, 199) self.gLayout3 = QGridLayout(self.scrollAreaWidgetContents) self.appHakkinda = QLabel(self.scrollAreaWidgetContents) font = QFont() font.setPointSize(9) font.setWeight(50) font.setBold(False) self.appHakkinda.setFont(font) self.appHakkinda.setWordWrap(True) self.gLayout3.addWidget(self.appHakkinda, 0, 0, 1, 1) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.gLayout2.addWidget(self.scrollArea, 0, 0, 1, 1) self.gLayout.addWidget(self.gBox, 2, 0, 2, 4) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gLayout.addItem(spacerItem, 0, 3, 1, 1) spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gLayout.addItem(spacerItem1, 2, 1, 1, 2) self.setWindowTitle(u"Virux Hakkında") self.appName.setText(u"Virux") self.appVersion.setText(u"Sürüm %s"%QApplication.applicationVersion()) self.gBox.setTitle(u"Hakkında") self.appHakkinda.setText(u""" <p>Virux, platform bağımsız bir antivirüs yazılımıdır :P</p> <p>Yazılımıın bir arayüzü yoktur. Sadece sistem çubuğunda bir tepsi oluşur. Bu tepsi animasyon şeklindedir.</p> <p>Rasgele zamanlarda mevcut olan dialoglardan bir tanesi ekranda gözükecektir. Sadece eğlence amacıyla yapılmıştır...</p> <p><b>Geliştirici:</b> Metehan Özbek - <a href='mailto:[email protected]'>[email protected]</a></p> <p><b>Görsel Çalışma:</b> Yasin Özcan - <a href='mailto:[email protected]'>[email protected]</a></p> <p><b>Katkı Yapanlar:</b> Yaşar Arabacı - <a href='mailto:[email protected]'>[email protected]</a></p> <p><b>Lisans:</b> GPL v3</p> <p></p>""")
def __init__(self, parent): super(ProjectExecution, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(self.tr("Main File:")), 0, 0) self.path = QLineEdit() ui_tools.LineEditButton( self.path, self.path.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.path.setText(self._parent._item.mainFile) self.path.setReadOnly(True) self.btnBrowse = QPushButton( QIcon(self.style().standardPixmap(self.style().SP_FileIcon)), '') grid.addWidget(self.path, 0, 1) grid.addWidget(self.btnBrowse, 0, 2) self.txtPythonPath = QLineEdit() self.txtPythonPath.setText(self._parent._item.pythonPath) self.btnPythonPath = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Python Path:")), 1, 0) grid.addWidget(self.txtPythonPath, 1, 1) grid.addWidget(self.btnPythonPath, 1, 2) self.txtPreExec = QLineEdit() ui_tools.LineEditButton( self.txtPreExec, self.txtPreExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPreExec.setReadOnly(True) self.txtPreExec.setText(self._parent._item.preExecScript) self.btnPreExec = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Pre-exec Script:")), 2, 0) grid.addWidget(self.txtPreExec, 2, 1) grid.addWidget(self.btnPreExec, 2, 2) self.txtPostExec = QLineEdit() ui_tools.LineEditButton( self.txtPostExec, self.txtPostExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPostExec.setReadOnly(True) self.txtPostExec.setText(self._parent._item.postExecScript) self.btnPostExec = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Post-exec Script:")), 3, 0) grid.addWidget(self.txtPostExec, 3, 1) grid.addWidget(self.btnPostExec, 3, 2) grid.addItem( QSpacerItem(5, 10, QSizePolicy.Expanding, QSizePolicy.Expanding), 4, 0) # Properties grid.addWidget(QLabel(self.tr("Properties:")), 5, 0) self.txtParams = QLineEdit() self.txtParams.setToolTip( self.tr("Separate the params with commas (ie: help, verbose)")) self.txtParams.setText(self._parent._item.programParams) grid.addWidget(QLabel(self.tr("Params (comma separated):")), 6, 0) grid.addWidget(self.txtParams, 6, 1) #Widgets for virtualenv properties self.txtVenvPath = QLineEdit() ui_tools.LineEditButton( self.txtVenvPath, self.txtVenvPath.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtVenvPath.setText(self._parent._item.venv) self.txtVenvPath.setReadOnly(True) self.btnVenvPath = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Virtualenv Folder:")), 7, 0) grid.addWidget(self.txtVenvPath, 7, 1) grid.addWidget(self.btnVenvPath, 7, 2) self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_file) self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path) self.connect(self.btnVenvPath, SIGNAL("clicked()"), self._load_python_venv) self.connect(self.btnPreExec, SIGNAL("clicked()"), self.select_pre_exec_script) self.connect(self.btnPostExec, SIGNAL("clicked()"), self.select_post_exec_script)
class CombinedValueRangeWidget(QWidget): def __init__(self, parent = None): super(CombinedValueRangeWidget, self).__init__(parent) self.roiWidgets = [] self.roiLayout = QGridLayout(self) self.setLayout(self.roiLayout) hbox = QHBoxLayout() hbox.addWidget(QLabel("min"),0,Qt.Alignment(Qt.AlignLeft)) hbox.addWidget(QLabel("max"),0,Qt.Alignment(Qt.AlignLeft)) self.roiLayout.addLayout(hbox, 0,1) self.roiLayout.addWidget(QLabel("Export Full Range"), 0, 2) self.roiLayout.addItem(QSpacerItem(0,0,QSizePolicy.Expanding, QSizePolicy.Minimum),0,3) self.roiCheckBoxes = [] self.setFocusPolicy(Qt.TabFocus) self.lastInChain = super(CombinedValueRangeWidget, self).nextInFocusChain() def addRanges(self, keys, extents): for key, extent in zip(keys, extents): w = ValueRangeWidget(self) w.setFocusPolicy(Qt.TabFocus) w.setDType(numpy.uint32) w.setValues(0,extent) w.setLimits(0,extent) #w.setLabels("min:","max:") self.roiWidgets.append(w) row = self.roiLayout.rowCount() align = Qt.Alignment(Qt.AlignLeft) check = QCheckBox() self.roiCheckBoxes.append(check) check.setChecked(True) check.setFocusPolicy(Qt.ClickFocus) if extent == 1: w.setEnabled(False) self.roiLayout.addWidget(QLabel(key + ": "),row, 0, align) self.roiLayout.addWidget(self.roiWidgets[-1],row, 1, align) self.roiLayout.addWidget(check,row, 2, align) def onChanged(i): val1,val2 = self.roiWidgets[i].getValues() lim1,lim2 = self.roiWidgets[i].getLimits() #limits are stored as ranges if val1==lim1 and val2==lim2: self.roiCheckBoxes[i].setChecked(True) else: self.roiCheckBoxes[i].setChecked(False) def onCheck(i, state): if state == 0: return self.roiWidgets[i].setValues(0,extents[i]) self.roiCheckBoxes[i].setChecked(True) for i, check in enumerate(self.roiCheckBoxes): check.stateChanged.connect(partial(onCheck, i)) self.roiWidgets[i].changedSignal.connect(partial(onChanged, i)) def focusInEvent(self, QFocusEvent): if len(self.roiWidgets) > 0: self.roiWidgets[0].setFocus()
class DogrulaDialog(QDialog): def __init__(self, ui): QDialog.__init__(self, ui) self.ui = ui self.resize(450, 170) self.setMinimumSize(QSize(450, 170)) self.setMaximumSize(QSize(500, 200)) self.setWindowTitle(self.trUtf8("Doğrula")) self.gridLayout = QGridLayout(self) self.neredenButton = QPushButton(self) self.neredenButton.setText(self.trUtf8("Nereden")) self.neredenButton.clicked.connect(self.nereden) self.gridLayout.addWidget(self.neredenButton, 0, 4, 1, 1) self.dogrulaButton = QPushButton(self) self.dogrulaButton.setText(self.trUtf8("Doğrula")) self.dogrulaButton.clicked.connect(self.dogrula) self.gridLayout.addWidget(self.dogrulaButton, 3, 4, 1, 1) self.neredenEdit = QLineEdit(self) self.neredenEdit.setReadOnly(True) self.gridLayout.addWidget(self.neredenEdit, 0, 0, 1, 4) self.hashEdit = QLineEdit(self) self.hashEdit.setReadOnly(True) self.gridLayout.addWidget(self.hashEdit, 3, 2, 1, 1) spacerItem = QSpacerItem(20, 15, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gridLayout.addItem(spacerItem, 1, 1, 1, 1) self.comboBox = QComboBox(self) self.comboBox.setMinimumSize(QSize(100, 0)) self.comboBox.addItem("MD5") self.comboBox.addItem("SHA1") self.gridLayout.addWidget(self.comboBox, 3, 1, 1, 1) self.karaWidget = KaraWidget(self, "=") self.karaWidget.hide() def nereden(self): dosya = QFileDialog.getOpenFileName(self, "", settings().value("Genel/Yol").toString()) if dosya == "": pass elif QFile.exists(dosya): from os.path import abspath, dirname settings().setValue("Genel/Yol", abspath(dirname(str(dosya)))) self.neredenEdit.setText(dosya) else: QMessageBox.warning(self, self.trUtf8("Hata!"), self.trUtf8("Böyle bir dosya mevcut değil!")) def dogrula(self): if self.neredenEdit.text() == "": QMessageBox.warning(self, self.trUtf8("Hata!"), self.trUtf8("Dosya seçmediniz!")) else: self.karaWidget.show() self.karaWidget.start() def keyPressEvent(self, event): pass def resizeEvent(self, event): self.karaWidget.setGeometry(0,0, event.size().width(), event.size().height())
class DBManager(QMainWindow): def __init__(self, iface, parent=None): QMainWindow.__init__(self, parent) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi() self.iface = iface # restore the window state settings = QSettings() self.restoreGeometry(settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray)) self.restoreState(settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray)) self.connect(self.tabs, SIGNAL("currentChanged(int)"), self.tabChanged) self.connect(self.tree, SIGNAL("selectedItemChanged"), self.itemChanged) self.itemChanged(None) def closeEvent(self, e): self.unregisterAllActions() # save the window state settings = QSettings() settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState()) settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry()) QMainWindow.closeEvent(self, e) def refreshItem(self, item=None): QApplication.setOverrideCursor(Qt.WaitCursor) try: if item is None: item = self.tree.currentItem() self.tree.refreshItem(item) # refresh item children in the db tree except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() def itemChanged(self, item): QApplication.setOverrideCursor(Qt.WaitCursor) try: self.reloadButtons() self.refreshTabs() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() def reloadButtons(self): db = self.tree.currentDatabase() if not hasattr(self, '_lastDb'): self._lastDb = db elif db == self._lastDb: return # remove old actions if self._lastDb is not None: self.unregisterAllActions() # add actions of the selected database self._lastDb = db if self._lastDb is not None: self._lastDb.registerAllActions(self) def tabChanged(self, index): QApplication.setOverrideCursor(Qt.WaitCursor) try: self.refreshTabs() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() def refreshTabs(self): index = self.tabs.currentIndex() item = self.tree.currentItem() table = self.tree.currentTable() # enable/disable tabs self.tabs.setTabEnabled(self.tabs.indexOf(self.table), table is not None) self.tabs.setTabEnabled(self.tabs.indexOf(self.preview), table is not None and table.type in [table.VectorType, table.RasterType] and table.geomColumn is not None) # show the info tab if the current tab is disabled if not self.tabs.isTabEnabled(index): self.tabs.setCurrentWidget(self.info) current_tab = self.tabs.currentWidget() if current_tab == self.info: self.info.showInfo(item) elif current_tab == self.table: self.table.loadData(item) elif current_tab == self.preview: self.preview.loadPreview(item) def refreshActionSlot(self): self.info.setDirty() self.table.setDirty() self.preview.setDirty() self.refreshItem() def importActionSlot(self): db = self.tree.currentDatabase() if db is None: self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."), QgsMessageBar.INFO, self.iface.messageTimeout()) return outUri = db.uri() schema = self.tree.currentSchema() if schema: outUri.setDataSource(schema.name, "", "", "") from .dlg_import_vector import DlgImportVector dlg = DlgImportVector(None, db, outUri, self) dlg.exec_() def exportActionSlot(self): table = self.tree.currentTable() if table is None: self.infoBar.pushMessage(self.tr("Select the table you want export to file."), QgsMessageBar.INFO, self.iface.messageTimeout()) return inLayer = table.toMapLayer() from .dlg_export_vector import DlgExportVector dlg = DlgExportVector(inLayer, table.database(), self) dlg.exec_() inLayer.deleteLater() def runSqlWindow(self): db = self.tree.currentDatabase() if db is None: self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."), QgsMessageBar.INFO, self.iface.messageTimeout()) # force displaying of the message, it appears on the first tab (i.e. Info) self.tabs.setCurrentIndex(0) return from dlg_sql_window import DlgSqlWindow query = DlgSqlWindow(self.iface, db, self) dbname = db.connection().connectionName() tabname = self.tr("Query") + u" (%s)" % dbname index = self.tabs.addTab(query, tabname) self.tabs.setTabIcon(index, db.connection().icon()) self.tabs.setCurrentIndex(index) query.nameChanged.connect(functools.partial(self.update_query_tab_name, index, dbname)) def update_query_tab_name(self, index, dbname, queryname): if not queryname: queryname = self.tr("Query") tabname = u"%s (%s)" % (queryname, dbname) self.tabs.setTabText(index, tabname) def showSystemTables(self): self.tree.showSystemTables(self.actionShowSystemTables.isChecked()) def registerAction(self, action, menuName, callback=None): """ register an action to the manager's main menu """ if not hasattr(self, '_registeredDbActions'): self._registeredDbActions = {} if callback is not None: invoke_callback = lambda x: self.invokeCallback(callback) if menuName is None or menuName == "": self.addAction(action) if menuName not in self._registeredDbActions: self._registeredDbActions[menuName] = list() self._registeredDbActions[menuName].append(action) if callback is not None: QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback) return True # search for the menu actionMenu = None helpMenuAction = None for a in self.menuBar.actions(): if not a.menu() or a.menu().title() != menuName: continue if a.menu() != self.menuHelp: helpMenuAction = a actionMenu = a break # not found, add a new menu before the help menu if actionMenu is None: menu = QMenu(menuName, self) if helpMenuAction is not None: actionMenu = self.menuBar.insertMenu(helpMenuAction, menu) else: actionMenu = self.menuBar.addMenu(menu) menu = actionMenu.menu() menuActions = menu.actions() # get the placeholder's position to insert before it pos = 0 for pos in range(len(menuActions)): if menuActions[pos].isSeparator() and menuActions[pos].objectName().endswith("_placeholder"): menuActions[pos].setVisible(True) break if pos < len(menuActions): before = menuActions[pos] menu.insertAction(before, action) else: menu.addAction(action) actionMenu.setVisible(True) # show the menu if menuName not in self._registeredDbActions: self._registeredDbActions[menuName] = list() self._registeredDbActions[menuName].append(action) if callback is not None: QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback) return True def invokeCallback(self, callback, *params): """ Call a method passing the selected item in the database tree, the sender (usually a QAction), the plugin mainWindow and optionally additional parameters. This method takes care to override and restore the cursor, but also catches exceptions and displays the error dialog. """ QApplication.setOverrideCursor(Qt.WaitCursor) try: callback(self.tree.currentItem(), self.sender(), self, *params) except BaseError as e: # catch database errors and display the error dialog DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() def unregisterAction(self, action, menuName): if not hasattr(self, '_registeredDbActions'): return if menuName is None or menuName == "": self.removeAction(action) if menuName in self._registeredDbActions: if self._registeredDbActions[menuName].count(action) > 0: self._registeredDbActions[menuName].remove(action) action.deleteLater() return True for a in self.menuBar.actions(): if not a.menu() or a.menu().title() != menuName: continue menu = a.menu() menuActions = menu.actions() menu.removeAction(action) if menu.isEmpty(): # hide the menu a.setVisible(False) if menuName in self._registeredDbActions: if self._registeredDbActions[menuName].count(action) > 0: self._registeredDbActions[menuName].remove(action) # hide the placeholder if there're no other registered actions if len(self._registeredDbActions[menuName]) <= 0: for i in range(len(menuActions)): if menuActions[i].isSeparator() and menuActions[i].objectName().endswith("_placeholder"): menuActions[i].setVisible(False) break action.deleteLater() return True return False def unregisterAllActions(self): if not hasattr(self, '_registeredDbActions'): return for menuName in self._registeredDbActions: for action in list(self._registeredDbActions[menuName]): self.unregisterAction(action, menuName) del self._registeredDbActions def close_tab(self, index): widget = self.tabs.widget(index) if widget not in [self.info, self.table, self.preview]: self.tabs.removeTab(index) widget.deleteLater() def setupUi(self): self.setWindowTitle(self.tr("DB Manager")) self.setWindowIcon(QIcon(":/db_manager/icon")) self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint())) # create central tab widget and add the first 3 tabs: info, table and preview self.tabs = QTabWidget() self.info = InfoViewer(self) self.tabs.addTab(self.info, self.tr("Info")) self.table = TableViewer(self) self.tabs.addTab(self.table, self.tr("Table")) self.preview = LayerPreview(self) self.tabs.addTab(self.preview, self.tr("Preview")) self.setCentralWidget(self.tabs) # display close button for all tabs but the first 3 ones, i.e. # HACK: just hide the close button where not needed (GS) self.tabs.setTabsClosable(True) self.tabs.tabCloseRequested.connect(self.close_tab) tabbar = self.tabs.tabBar() for i in range(3): btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(i, QTabBar.RightSide) else tabbar.tabButton(i, QTabBar.LeftSide) btn.resize(0, 0) btn.hide() # Creates layout for message bar self.layout = QGridLayout(self.info) self.layout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layout.addItem(spacerItem, 1, 0, 1, 1) # init messageBar instance self.infoBar = QgsMessageBar(self.info) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.infoBar.setSizePolicy(sizePolicy) self.layout.addWidget(self.infoBar, 0, 0, 1, 1) # create database tree self.dock = QDockWidget("Tree", self) self.dock.setObjectName("DB_Manager_DBView") self.dock.setFeatures(QDockWidget.DockWidgetMovable) self.tree = DBTree(self) self.dock.setWidget(self.tree) self.addDockWidget(Qt.LeftDockWidgetArea, self.dock) # create status bar self.statusBar = QStatusBar(self) self.setStatusBar(self.statusBar) # create menus self.menuBar = QMenuBar(self) self.menuDb = QMenu(self.tr("&Database"), self) self.menuBar.addMenu(self.menuDb) self.menuSchema = QMenu(self.tr("&Schema"), self) actionMenuSchema = self.menuBar.addMenu(self.menuSchema) self.menuTable = QMenu(self.tr("&Table"), self) actionMenuTable = self.menuBar.addMenu(self.menuTable) self.menuHelp = None # QMenu(self.tr("&Help"), self) # actionMenuHelp = self.menuBar.addMenu(self.menuHelp) self.setMenuBar(self.menuBar) # create toolbar self.toolBar = QToolBar("Default", self) self.toolBar.setObjectName("DB_Manager_ToolBar") self.addToolBar(self.toolBar) # create menus' actions # menu DATABASE sep = self.menuDb.addSeparator() sep.setObjectName("DB_Manager_DbMenu_placeholder") sep.setVisible(False) self.actionRefresh = self.menuDb.addAction(QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"), self.refreshActionSlot, QKeySequence("F5")) self.actionSqlWindow = self.menuDb.addAction(QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"), self.runSqlWindow, QKeySequence("F2")) self.menuDb.addSeparator() self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q")) # menu SCHEMA sep = self.menuSchema.addSeparator() sep.setObjectName("DB_Manager_SchemaMenu_placeholder") sep.setVisible(False) actionMenuSchema.setVisible(False) # menu TABLE sep = self.menuTable.addSeparator() sep.setObjectName("DB_Manager_TableMenu_placeholder") sep.setVisible(False) self.actionImport = self.menuTable.addAction(QIcon(":/db_manager/actions/import"), self.tr("&Import layer/file"), self.importActionSlot) self.actionExport = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&Export to file"), self.exportActionSlot) self.menuTable.addSeparator() #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables) #self.actionShowSystemTables.setCheckable(True) #self.actionShowSystemTables.setChecked(True) actionMenuTable.setVisible(False) # add actions to the toolbar self.toolBar.addAction(self.actionRefresh) self.toolBar.addAction(self.actionSqlWindow) self.toolBar.addAction(self.actionImport) self.toolBar.addAction(self.actionExport)
class DAyarlar(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(600, 375) self.gridLayout = QGridLayout(self) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.treeWidget = QTreeWidget(self) self.treeWidget.setMaximumSize(200, 1500) self.virux = QTreeWidgetItem(self.treeWidget) self.virux.setExpanded(True) icon = QIcon() icon.addPixmap(QPixmap("data/logo.png"), QIcon.Normal, QIcon.On) self.virux.setIcon(0, icon) item_1 = QTreeWidgetItem(self.virux) item_1 = QTreeWidgetItem(self.virux) self.dialog = QTreeWidgetItem(self.treeWidget) self.dialog.setExpanded(True) item_1 = QTreeWidgetItem(self.dialog) item_1 = QTreeWidgetItem(self.dialog) self.treeWidget.header().setVisible(False) self.gridLayout.addWidget(self.treeWidget, 0, 0, 1, 1) self.groupBox = QGroupBox(self) self.groupBox.setFlat(True) self.gridLayout_3 = QGridLayout(self.groupBox) self.gridLayout_3.setMargin(0) self.gridLayout_3.setSpacing(0) self.widget = QWidget(self.groupBox) self.gridLayout_4 = QGridLayout(self.widget) self.gridLayout_4.setMargin(0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setMargin(0) spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 0, 0, 1, 1) self.gridLayout_3.addWidget(self.widget, 0, 0, 1, 1) self.gridLayout.addWidget(self.groupBox, 0, 1, 1, 1) self.pButton = QPushButton(self) self.pButton.setText("asd") self.pButton.setDefault(True) self.buttonBox = QDialogButtonBox(self) self.buttonBox.addButton(self.pButton, QDialogButtonBox.AcceptRole) #self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 2) self.setWindowTitle("Virux Ayarlar") self.treeWidget.headerItem().setText(0, "") self.treeWidget.topLevelItem(0).setText(0, u"Virux") self.treeWidget.topLevelItem(0).child(0).setText(0, u"Virux1") self.treeWidget.topLevelItem(0).child(1).setText(0, u"Virux2") self.treeWidget.topLevelItem(1).setText(0, u"Dialog") self.treeWidget.topLevelItem(1).child(0).setText(0, u"Dialog1") self.treeWidget.topLevelItem(1).child(1).setText(0, u"Dialog2") self.groupBox.setTitle(u"GroupBox") self.groupYaz() self.treeWidget.itemPressed.connect(self.lale) def lale(self, item): print item self.groupBox.setTitle(item.text(0)) def groupYaz(self): for option in DOptions: if hasattr(option, "getOption"): #self.gridLayout_3.addWidget(option.getOption(), 0, 0, 1, 1) item = QTreeWidgetItem(self.dialog) a = option.getOption() if hasattr(a, "name"): item.setText(0, a.name) else: item.setText(0, "F**k")
class Parcala(QWidget): def __init__(self): QWidget.__init__(self) self.resize(350, 225) self.setMinimumSize(QSize(350, 225)) self.setMaximumSize(QSize(400, 250)) self.setWindowTitle(QApplication.applicationName()+" "+QApplication.applicationVersion()) icon = QIcon() icon.addPixmap(QPixmap(":/resim/parcala.png")) self.setWindowIcon(icon) self.gridLayout = QGridLayout(self) self.parcalaButton = QPushButton(self) self.parcalaButton.setMinimumSize(QSize(150, 50)) self.parcalaButton.setText(self.trUtf8("Parçala")) self.parcalaButton.clicked.connect(self.parcala) self.gridLayout.addWidget(self.parcalaButton, 3, 0, 1, 1) self.birlestirButton = QPushButton(self) self.birlestirButton.setMinimumSize(QSize(150, 50)) self.birlestirButton.setText(self.trUtf8("Birleştir")) self.birlestirButton.clicked.connect(self.birlestir) self.gridLayout.addWidget(self.birlestirButton, 3, 2, 1, 1) self.dogrulaButton = QPushButton(self) self.dogrulaButton.setMinimumSize(QSize(150, 50)) self.dogrulaButton.setText(self.trUtf8("Doğrula")) self.dogrulaButton.clicked.connect(self.dogrula) self.gridLayout.addWidget(self.dogrulaButton, 7, 0, 1, 1) self.hakkindaButton = QPushButton(self) self.hakkindaButton.setMinimumSize(QSize(150, 50)) self.hakkindaButton.setText(self.trUtf8("Hakkında")) self.hakkindaButton.clicked.connect(self.hakkinda) self.gridLayout.addWidget(self.hakkindaButton, 7, 2, 1, 1) self.bilgiLabel = QLabel(self) self.bilgiLabel.setText(self.trUtf8(u"%s %s \u00a9 2011 - www.metehan.us"%(QApplication.applicationName(),QApplication.applicationVersion()))) self.bilgiLabel.setAlignment(Qt.AlignCenter) self.gridLayout.addWidget(self.bilgiLabel, 9, 0, 1, 3) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 3, 1, 1, 1) spacerItem1 = QSpacerItem(0, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(spacerItem1, 4, 1, 1, 1) spacerItem2 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(spacerItem2, 2, 1, 1, 1) spacerItem3 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(spacerItem3, 8, 1, 1, 1) def hakkinda(self): h = Hakkinda(self) h.show() def dogrula(self): d = DogrulaDialog(self) d.show() def parcala(self): d = ParcalaDialog(self) d.show() def birlestir(self): d = BirlestirDialog(self) d.show()
def __init__(self, params_pipe, number_pipe, templates_pipe, spikes_pipe, probe_path=None, screen_resolution=None): QMainWindow.__init__(self) # Receive parameters. params = params_pipe[0].recv() self.probe = load_probe(probe_path) self._nb_samples = params['nb_samples'] self._sampling_rate = params['sampling_rate'] self._display_list = [] self._params = { 'nb_samples': self._nb_samples, 'sampling_rate': self._sampling_rate, 'time': { 'min': 10.0, # ms 'max': 100.0, # ms 'init': 100.0, # ms }, 'voltage': { 'min': -200, # µV 'max': 20e+1, # µV 'init': 50.0, # µV }, 'templates': self._display_list } self._canvas_mea = MEACanvas(probe_path=probe_path, params=self._params) self._canvas_template = TemplateCanvas(probe_path=probe_path, params=self._params) self._canvas_rate = RateCanvas(probe_path=probe_path, params=self._params) self._canvas_isi = ISICanvas(probe_path=probe_path, params=self._params) self.cells = Cells({}) self._nb_buffer = 0 # TODO ISI self.isi_bin_width, self.isi_x_max = 2, 25.0 canvas_template_widget = self._canvas_template.native canvas_mea = self._canvas_mea.native canvas_rate = self._canvas_rate.native canvas_isi = self._canvas_isi.native # Create controls widgets. label_time = QLabel() label_time.setText(u"time") label_time_unit = QLabel() label_time_unit.setText(u"ms") self._dsp_time = QDoubleSpinBox() self._dsp_time.setMinimum(self._params['time']['min']) self._dsp_time.setMaximum(self._params['time']['max']) self._dsp_time.setValue(self._params['time']['init']) self._dsp_time.valueChanged.connect(self._on_time_changed) label_voltage = QLabel() label_voltage.setText(u"voltage") label_voltage_unit = QLabel() label_voltage_unit.setText(u"µV") self._dsp_voltage = QDoubleSpinBox() self._dsp_voltage.setMinimum(self._params['voltage']['min']) self._dsp_voltage.setMaximum(self._params['voltage']['max']) self._dsp_voltage.setValue(self._params['voltage']['init']) self._dsp_voltage.valueChanged.connect(self._on_voltage_changed) label_binsize = QLabel() label_binsize.setText(u"Bin size") label_binsize_unit = QLabel() label_binsize_unit.setText(u"second") self._dsp_binsize = QDoubleSpinBox() self._dsp_binsize.setRange(0.1, 10) self._dsp_binsize.setSingleStep(0.1) self.bin_size = 1 self._dsp_binsize.setValue(self.bin_size) self._dsp_binsize.valueChanged.connect(self._on_binsize_changed) label_zoomrates = QLabel() label_zoomrates.setText(u'Zoom rates') self._zoom_rates = QDoubleSpinBox() self._zoom_rates.setRange(1, 50) self._zoom_rates.setSingleStep(0.1) self._zoom_rates.setValue(1) self._zoom_rates.valueChanged.connect(self._on_zoomrates_changed) label_time_window = QLabel() label_time_window.setText(u'Time window rates') label_time_window_unit = QLabel() label_time_window_unit.setText(u'second') self._dsp_tw_rate = QDoubleSpinBox() self._dsp_tw_rate.setRange(1, 50) self._dsp_tw_rate.setSingleStep(self.bin_size) self._dsp_tw_rate.setValue(50 * self.bin_size) self._dsp_tw_rate.valueChanged.connect(self._on_time_window_changed) label_tw_from_start = QLabel() label_tw_from_start.setText('Time scale from start') self._tw_from_start = QCheckBox() self._tw_from_start.setChecked(True) self._selection_templates = QTableWidget() self._selection_templates.setSelectionMode( QAbstractItemView.ExtendedSelection ) self._selection_templates.setColumnCount(3) self._selection_templates.setVerticalHeaderLabels(['Nb template', 'Channel', 'Amplitude']) self._selection_templates.insertRow(0) self._selection_templates.setItem(0, 0, QTableWidgetItem('Nb template')) self._selection_templates.setItem(0, 1, QTableWidgetItem('Channel')) self._selection_templates.setItem(0, 2, QTableWidgetItem('Amplitude')) # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291)) # for i in range(self.nb_templates): # numRows = self.tableWidget.rowCount() # self.tableWidget.insertRow(numRows) # item = QTableWidgetItem("Template %i" % i) # self._selection_templates.addItem(item) # self._selection_templates.item(i).setSelected(False) spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create controls grid. grid = QGridLayout() # # Add time row. grid.addWidget(label_time, 0, 0) grid.addWidget(self._dsp_time, 0, 1) grid.addWidget(label_time_unit, 0, 2) # # Add voltage row. grid.addWidget(label_voltage, 1, 0) grid.addWidget(self._dsp_voltage, 1, 1) grid.addWidget(label_voltage_unit, 1, 2) # # Add binsize row. grid.addWidget(label_binsize, 2, 0) grid.addWidget(self._dsp_binsize, 2, 1) grid.addWidget(label_binsize_unit, 2, 2) # # Add zoom rate grid.addWidget(label_zoomrates, 3, 0) grid.addWidget(self._zoom_rates, 3, 1) # Add a double checkbox for time window grid.addWidget(label_time_window, 4, 0) grid.addWidget(self._dsp_tw_rate, 4, 1) grid.addWidget(label_time_window_unit, 4, 2) ## Add checkbox to display the rates from start grid.addWidget(label_tw_from_start, 5, 0) grid.addWidget(self._tw_from_start, 5, 1) # # Add spacer. grid.addItem(spacer) # # Create info group. controls_group = QGroupBox() controls_group.setLayout(grid) # Create info grid. templates_grid = QGridLayout() # # Add Channel selection # grid.addWidget(label_selection, 3, 0) templates_grid.addWidget(self._selection_templates, 0, 1) def add_template(): items = self._selection_templates.selectedItems() self._display_list = [] for i in range(len(items)): self._display_list.append(i) self._on_templates_changed() # self._selection_templates.itemClicked.connect(add_template) # Template selection signals self._selection_templates.itemSelectionChanged.connect(lambda: self.selected_templates( self.nb_templates)) # Checkbox to display all the rates self._tw_from_start.stateChanged.connect(self.time_window_rate_full) # self._selection_templates.itemPressed(0, 1).connect(self.sort_template()) # # Add spacer. templates_grid.addItem(spacer) # Create controls group. templates_group = QGroupBox() templates_group.setLayout(templates_grid) # # Create controls dock. templates_dock = QDockWidget() templates_dock.setWidget(templates_group) templates_dock.setWindowTitle("Channels selection") # # Create controls dock. control_dock = QDockWidget() control_dock.setWidget(controls_group) control_dock.setWindowTitle("Controls") # Create info widgets. label_time = QLabel() label_time.setText(u"time") self._label_time_value = QLineEdit() self._label_time_value.setText(u"0") self._label_time_value.setReadOnly(True) self._label_time_value.setAlignment(Qt.AlignRight) label_time_unit = QLabel() label_time_unit.setText(u"s") info_buffer_label = QLabel() info_buffer_label.setText(u"buffer") self._info_buffer_value_label = QLineEdit() self._info_buffer_value_label.setText(u"0") self._info_buffer_value_label.setReadOnly(True) self._info_buffer_value_label.setAlignment(Qt.AlignRight) info_buffer_unit_label = QLabel() info_buffer_unit_label.setText(u"") info_probe_label = QLabel() info_probe_label.setText(u"probe") info_probe_value_label = QLineEdit() info_probe_value_label.setText(u"{}".format(probe_path)) info_probe_value_label.setReadOnly(True) # TODO place the following info in another grid? info_probe_unit_label = QLabel() info_probe_unit_label.setText(u"") info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create info grid. info_grid = QGridLayout() # # Time row. info_grid.addWidget(label_time, 0, 0) info_grid.addWidget(self._label_time_value, 0, 1) info_grid.addWidget(label_time_unit, 0, 2) # # Buffer row. info_grid.addWidget(info_buffer_label, 1, 0) info_grid.addWidget(self._info_buffer_value_label, 1, 1) info_grid.addWidget(info_buffer_unit_label, 1, 2) # # Probe row. info_grid.addWidget(info_probe_label, 2, 0) info_grid.addWidget(info_probe_value_label, 2, 1) info_grid.addWidget(info_probe_unit_label, 2, 2) # # Spacer. info_grid.addItem(info_spacer) # Create info group. info_group = QGroupBox() info_group.setLayout(info_grid) # Create info dock. info_dock = QDockWidget() info_dock.setWidget(info_group) info_dock.setWindowTitle("Info") # Create thread. thread = Thread(number_pipe, templates_pipe, spikes_pipe) thread.number_signal.connect(self._number_callback) thread.reception_signal.connect(self._reception_callback) thread.start() # Add dockable windows. self.addDockWidget(Qt.LeftDockWidgetArea, control_dock) self.addDockWidget(Qt.LeftDockWidgetArea, info_dock) self.addDockWidget(Qt.LeftDockWidgetArea, templates_dock) # Add Grid Layout for canvas canvas_grid = QGridLayout() group_canv_temp = QDockWidget() group_canv_temp.setWidget(canvas_template_widget) group_canv_mea = QDockWidget() group_canv_mea.setWidget(canvas_mea) group_canv_rate = QDockWidget() group_canv_rate.setWidget(canvas_rate) group_canv_isi = QDockWidget() group_canv_isi.setWidget(canvas_isi) canvas_grid.addWidget(group_canv_temp, 0, 0) canvas_grid.addWidget(group_canv_mea, 0, 1) canvas_grid.addWidget(group_canv_rate, 1, 1) canvas_grid.addWidget(group_canv_isi, 1, 0) canvas_group = QGroupBox() canvas_group.setLayout(canvas_grid) # Set central widget. self.setCentralWidget(canvas_group) # Set window size. if screen_resolution is not None: screen_width = screen_resolution.width() screen_height = screen_resolution.height() self.resize(screen_width, screen_height) # Set window title. self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display") print(" ") # TODO remove?
class NewView(BaseView): def _setup(self): self._setupUi() self.pluginList = ListviewModel(self.model.plugin_list, self.pluginListView) self.pluginListView.doubleClicked.connect(self.model.open_selected_plugin) self.networthButton.clicked.connect(self.networthButtonClicked) self.profitButton.clicked.connect(self.profitButtonClicked) self.transactionButton.clicked.connect(self.transactionButtonClicked) self.gledgerButton.clicked.connect(self.gledgerButtonClicked) self.scheduleButton.clicked.connect(self.scheduleButtonClicked) self.budgetButton.clicked.connect(self.budgetButtonClicked) self.docpropsButton.clicked.connect(self.docpropsButtonClicked) self.shortcut1.activated.connect(self.networthButtonClicked) self.shortcut2.activated.connect(self.profitButtonClicked) self.shortcut3.activated.connect(self.transactionButtonClicked) self.shortcut4.activated.connect(self.gledgerButtonClicked) self.shortcut5.activated.connect(self.scheduleButtonClicked) self.shortcut6.activated.connect(self.budgetButtonClicked) self.shortcut7.activated.connect(self.docpropsButtonClicked) def _setupUi(self): self.resize(400, 300) self.gridLayout = QGridLayout(self) self.label = QLabel(tr("Choose a type for this tab:")) self.label.setAlignment(Qt.AlignCenter) self.gridLayout.addWidget(self.label, 0, 0, 1, 3) self.gridLayout.addItem(horizontalSpacer(), 1, 0, 1, 1) self.verticalLayout = QVBoxLayout() self.networthButton = QPushButton(tr("1. Net Worth")) self.networthButton.setIcon(QIcon(QPixmap(':/balance_sheet_16'))) self.verticalLayout.addWidget(self.networthButton) self.profitButton = QPushButton(tr("2. Profit && Loss")) self.profitButton.setIcon(QIcon(QPixmap(':/income_statement_16'))) self.verticalLayout.addWidget(self.profitButton) self.transactionButton = QPushButton(tr("3. Transactions")) self.transactionButton.setIcon(QIcon(QPixmap(':/transaction_table_16'))) self.verticalLayout.addWidget(self.transactionButton) self.gledgerButton = QPushButton(tr("4. General Ledger")) self.gledgerButton.setIcon(QIcon(QPixmap(':/gledger_16'))) self.verticalLayout.addWidget(self.gledgerButton) self.scheduleButton = QPushButton(tr("5. Schedules")) self.scheduleButton.setIcon(QIcon(QPixmap(':/schedules_16'))) self.verticalLayout.addWidget(self.scheduleButton) self.budgetButton = QPushButton(tr("6. Budgets")) self.budgetButton.setIcon(QIcon(QPixmap(':/budget_16'))) self.verticalLayout.addWidget(self.budgetButton) self.docpropsButton = QPushButton(tr("7. Document Properties")) self.docpropsButton.setIcon(QIcon(QPixmap(':/gledger_16'))) self.verticalLayout.addWidget(self.docpropsButton) self.pluginLabel = QLabel(tr("Plugins (double-click to open)")) self.pluginLabel.setAlignment(Qt.AlignCenter) self.verticalLayout.addWidget(self.pluginLabel) self.pluginListView = QListView() self.pluginListView.setSelectionBehavior(QAbstractItemView.SelectRows) self.verticalLayout.addWidget(self.pluginListView) self.gridLayout.addLayout(self.verticalLayout, 1, 1, 1, 1) self.gridLayout.addItem(horizontalSpacer(), 1, 2, 1, 1) self.gridLayout.addItem(verticalSpacer(), 2, 1, 1, 1) for i in range(1, 8): shortcut = QShortcut(QKeySequence(str(i)), self, None, None, Qt.WidgetShortcut) setattr(self, 'shortcut{0}'.format(i), shortcut) #--- Event Handlers def networthButtonClicked(self): self.model.select_pane_type(PaneType.NetWorth) def profitButtonClicked(self): self.model.select_pane_type(PaneType.Profit) def transactionButtonClicked(self): self.model.select_pane_type(PaneType.Transaction) def gledgerButtonClicked(self): self.model.select_pane_type(PaneType.GeneralLedger) def scheduleButtonClicked(self): self.model.select_pane_type(PaneType.Schedule) def budgetButtonClicked(self): self.model.select_pane_type(PaneType.Budget) def docpropsButtonClicked(self): self.model.select_pane_type(PaneType.DocProps)
def initUi(self): """初始化界面""" self.setWindowTitle(u'交易') self.setMaximumWidth(500) self.setFrameShape(self.Box) # 设置边框 self.setLineWidth(1) # 左边部分 labelSymbol = QLabel(u'代码') labelName = QLabel(u'名称') labelDirection = QLabel(u'方向类型') labelOffset = QLabel(u'开平') labelPrice = QLabel(u'价格') labelVolume = QLabel(u'数量') labelPriceType = QLabel(u'价格类型') labelExchange = QLabel(u'交易所') labelCurrency = QLabel(u'货币') labelProductClass = QLabel(u'产品类型') labelUrgency = QLabel(u'紧急度') self.lineSymbol = QLineEdit() self.lineName = QLineEdit() self.comboDirection = QComboBox() self.comboDirection.addItems(self.directionList) self.comboOffset = QComboBox() self.comboOffset.addItem('') self.comboOffset.addItems(self.offsetList) self.comboOffset.setEnabled(False) self.tickOffset = QCheckBox(u'指定') self.spinPrice = QDoubleSpinBox() self.spinPrice.setDecimals(4) self.spinPrice.setMinimum(0) self.spinPrice.setMaximum(100000) self.spinVolume = QSpinBox() self.spinVolume.setMinimum(0) self.spinVolume.setMaximum(1000000) self.comboPriceType = QComboBox() self.comboPriceType.addItems(self.priceTypeList) self.comboExchange = QComboBox() self.comboExchange.addItems(self.exchangeList) self.comboExchange.setEnabled(False) self.comboCurrency = QComboBox() self.comboCurrency.addItems(self.currencyList) self.comboCurrency.setEnabled(False) self.comboProductClass = QComboBox() self.comboProductClass.addItems(self.productClassList) self.comboProductClass.setEnabled(False) self.spinUrgency = QSpinBox() self.spinUrgency.setMinimum(1) self.spinUrgency.setMaximum(9) self.spinUrgency.setSingleStep(1) self.spinUrgency.setValue(5) gridleft = QGridLayout() gridleft.addWidget(labelSymbol, 0, 0) gridleft.addWidget(labelName, 1, 0) gridleft.addWidget(labelDirection, 2, 0) gridleft.addWidget(labelOffset, 3, 0) gridleft.addWidget(labelPrice, 4, 0) gridleft.addWidget(labelVolume, 5, 0) gridleft.addWidget(labelPriceType, 6, 0) gridleft.addWidget(labelUrgency, 7, 0) gridleft.addWidget(labelExchange, 8, 0) gridleft.addWidget(labelProductClass, 9, 0) gridleft.addWidget(labelCurrency, 10, 0) gridleft.addWidget(self.lineSymbol, 0, 1) gridleft.addWidget(self.lineName, 1, 1) gridleft.addWidget(self.comboDirection, 2, 1) hbox1 = QHBoxLayout() hbox1.addWidget(self.comboOffset) lable1 = QLabel() hbox1.addWidget(lable1) hbox1.addWidget(self.tickOffset) hbox1.setStretchFactor(self.comboOffset, 4) hbox1.setStretchFactor(lable1, 1) hbox1.setStretchFactor(self.tickOffset, 3) gridleft.addItem(hbox1, 3, 1) gridleft.addWidget(self.spinPrice, 4, 1) gridleft.addWidget(self.spinVolume, 5, 1) gridleft.addWidget(self.comboPriceType, 6, 1) gridleft.addWidget(self.spinUrgency, 7, 1) gridleft.addWidget(self.comboExchange, 8, 1) gridleft.addWidget(self.comboProductClass, 9, 1) gridleft.addWidget(self.comboCurrency, 10, 1) # 右边部分 labelBid1 = QLabel(u'买一') labelBid2 = QLabel(u'买二') labelBid3 = QLabel(u'买三') labelBid4 = QLabel(u'买四') labelBid5 = QLabel(u'买五') labelAsk1 = QLabel(u'卖一') labelAsk2 = QLabel(u'卖二') labelAsk3 = QLabel(u'卖三') labelAsk4 = QLabel(u'卖四') labelAsk5 = QLabel(u'卖五') self.labelBidPrice1 = QLabel() self.labelBidPrice2 = QLabel() self.labelBidPrice3 = QLabel() self.labelBidPrice4 = QLabel() self.labelBidPrice5 = QLabel() self.labelBidVolume1 = QLabel() self.labelBidVolume2 = QLabel() self.labelBidVolume3 = QLabel() self.labelBidVolume4 = QLabel() self.labelBidVolume5 = QLabel() self.labelAskPrice1 = QLabel() self.labelAskPrice2 = QLabel() self.labelAskPrice3 = QLabel() self.labelAskPrice4 = QLabel() self.labelAskPrice5 = QLabel() self.labelAskVolume1 = QLabel() self.labelAskVolume2 = QLabel() self.labelAskVolume3 = QLabel() self.labelAskVolume4 = QLabel() self.labelAskVolume5 = QLabel() labelLast = QLabel(u'最新') self.labelLastPrice = QLabel() self.labelReturn = QLabel() self.labelLastPrice.setMinimumWidth(60) self.labelReturn.setMinimumWidth(60) gridRight = QGridLayout() gridRight.addWidget(labelAsk5, 0, 0) gridRight.addWidget(labelAsk4, 1, 0) gridRight.addWidget(labelAsk3, 2, 0) gridRight.addWidget(labelAsk2, 3, 0) gridRight.addWidget(labelAsk1, 4, 0) gridRight.addWidget(labelLast, 5, 0) gridRight.addWidget(labelBid1, 6, 0) gridRight.addWidget(labelBid2, 7, 0) gridRight.addWidget(labelBid3, 8, 0) gridRight.addWidget(labelBid4, 9, 0) gridRight.addWidget(labelBid5, 10, 0) gridRight.addWidget(self.labelAskPrice5, 0, 1) gridRight.addWidget(self.labelAskPrice4, 1, 1) gridRight.addWidget(self.labelAskPrice3, 2, 1) gridRight.addWidget(self.labelAskPrice2, 3, 1) gridRight.addWidget(self.labelAskPrice1, 4, 1) gridRight.addWidget(self.labelLastPrice, 5, 1) gridRight.addWidget(self.labelBidPrice1, 6, 1) gridRight.addWidget(self.labelBidPrice2, 7, 1) gridRight.addWidget(self.labelBidPrice3, 8, 1) gridRight.addWidget(self.labelBidPrice4, 9, 1) gridRight.addWidget(self.labelBidPrice5, 10, 1) gridRight.addWidget(self.labelAskVolume5, 0, 2) gridRight.addWidget(self.labelAskVolume4, 1, 2) gridRight.addWidget(self.labelAskVolume3, 2, 2) gridRight.addWidget(self.labelAskVolume2, 3, 2) gridRight.addWidget(self.labelAskVolume1, 4, 2) gridRight.addWidget(self.labelReturn, 5, 2) gridRight.addWidget(self.labelBidVolume1, 6, 2) gridRight.addWidget(self.labelBidVolume2, 7, 2) gridRight.addWidget(self.labelBidVolume3, 8, 2) gridRight.addWidget(self.labelBidVolume4, 9, 2) gridRight.addWidget(self.labelBidVolume5, 10, 2) # 发单按钮 buttonSendOrder = QPushButton(u'发单') buttonCancelAll = QPushButton(u'全撤') size = buttonSendOrder.sizeHint() buttonSendOrder.setMinimumHeight(size.height() * 2) # 把按钮高度设为默认两倍 buttonCancelAll.setMinimumHeight(size.height() * 2) # 整合布局 hbox = QHBoxLayout() hbox.addLayout(gridleft) hbox.addLayout(gridRight) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(buttonSendOrder) vbox.addWidget(buttonCancelAll) vbox.addStretch() self.setLayout(vbox) # 关联更新 buttonSendOrder.clicked.connect(self.sendOrder) buttonCancelAll.clicked.connect(self.cancelAll) self.lineSymbol.returnPressed.connect(self.updateSymbol) self.comboDirection.currentIndexChanged.connect(self.updateOffset) self.tickOffset.stateChanged.connect(self.updateOffset) self.labelAskPrice1.mouseDoubleClickEvent = self.ask1clicked self.labelAskPrice2.mouseDoubleClickEvent = self.ask2clicked self.labelAskPrice3.mouseDoubleClickEvent = self.ask3clicked self.labelAskPrice4.mouseDoubleClickEvent = self.ask4clicked self.labelAskPrice5.mouseDoubleClickEvent = self.ask5clicked self.labelBidPrice1.mouseDoubleClickEvent = self.bid1clicked self.labelBidPrice2.mouseDoubleClickEvent = self.bid2clicked self.labelBidPrice3.mouseDoubleClickEvent = self.bid3clicked self.labelBidPrice4.mouseDoubleClickEvent = self.bid4clicked self.labelBidPrice5.mouseDoubleClickEvent = self.bid5clicked self.labelLastPrice.mouseDoubleClickEvent = self.lastclicked
class DBManager(QMainWindow): def __init__(self, iface, parent=None): QMainWindow.__init__(self, parent) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi() self.iface = iface # restore the window state settings = QSettings() self.restoreGeometry( settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray)) self.restoreState( settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray)) self.connect(self.tabs, SIGNAL("currentChanged(int)"), self.tabChanged) self.connect(self.tree, SIGNAL("selectedItemChanged"), self.itemChanged) self.itemChanged(None) def closeEvent(self, e): self.unregisterAllActions() # save the window state settings = QSettings() settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState()) settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry()) QMainWindow.closeEvent(self, e) def refreshItem(self, item=None): QApplication.setOverrideCursor(Qt.WaitCursor) try: if item is None: item = self.tree.currentItem() self.tree.refreshItem(item) # refresh item children in the db tree except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() def itemChanged(self, item): QApplication.setOverrideCursor(Qt.WaitCursor) try: self.reloadButtons() self.refreshTabs() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() def reloadButtons(self): db = self.tree.currentDatabase() if not hasattr(self, '_lastDb'): self._lastDb = db elif db == self._lastDb: return # remove old actions if self._lastDb is not None: self.unregisterAllActions() # add actions of the selected database self._lastDb = db if self._lastDb is not None: self._lastDb.registerAllActions(self) def tabChanged(self, index): QApplication.setOverrideCursor(Qt.WaitCursor) try: self.refreshTabs() except BaseError as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() def refreshTabs(self): index = self.tabs.currentIndex() item = self.tree.currentItem() table = self.tree.currentTable() # enable/disable tabs self.tabs.setTabEnabled(self.tabs.indexOf(self.table), table is not None) self.tabs.setTabEnabled( self.tabs.indexOf(self.preview), table is not None and table.type in [table.VectorType, table.RasterType] and table.geomColumn is not None) # show the info tab if the current tab is disabled if not self.tabs.isTabEnabled(index): self.tabs.setCurrentWidget(self.info) current_tab = self.tabs.currentWidget() if current_tab == self.info: self.info.showInfo(item) elif current_tab == self.table: self.table.loadData(item) elif current_tab == self.preview: self.preview.loadPreview(item) def refreshActionSlot(self): self.info.setDirty() self.table.setDirty() self.preview.setDirty() self.refreshItem() def importActionSlot(self): db = self.tree.currentDatabase() if db is None: self.infoBar.pushMessage( self.tr( "No database selected or you are not connected to it."), QgsMessageBar.INFO, self.iface.messageTimeout()) return outUri = db.uri() schema = self.tree.currentSchema() if schema: outUri.setDataSource(schema.name, "", "", "") from .dlg_import_vector import DlgImportVector dlg = DlgImportVector(None, db, outUri, self) dlg.exec_() def exportActionSlot(self): table = self.tree.currentTable() if table is None: self.infoBar.pushMessage( self.tr("Select the table you want export to file."), QgsMessageBar.INFO, self.iface.messageTimeout()) return inLayer = table.toMapLayer() from .dlg_export_vector import DlgExportVector dlg = DlgExportVector(inLayer, table.database(), self) dlg.exec_() inLayer.deleteLater() def runSqlWindow(self): db = self.tree.currentDatabase() if db is None: self.infoBar.pushMessage( self.tr( "No database selected or you are not connected to it."), QgsMessageBar.INFO, self.iface.messageTimeout()) # force displaying of the message, it appears on the first tab (i.e. Info) self.tabs.setCurrentIndex(0) return from dlg_sql_window import DlgSqlWindow query = DlgSqlWindow(self.iface, db, self) dbname = db.connection().connectionName() tabname = self.tr("Query") + u" (%s)" % dbname index = self.tabs.addTab(query, tabname) self.tabs.setTabIcon(index, db.connection().icon()) self.tabs.setCurrentIndex(index) query.nameChanged.connect( functools.partial(self.update_query_tab_name, index, dbname)) def update_query_tab_name(self, index, dbname, queryname): if not queryname: queryname = self.tr("Query") tabname = u"%s (%s)" % (queryname, dbname) self.tabs.setTabText(index, tabname) def showSystemTables(self): self.tree.showSystemTables(self.actionShowSystemTables.isChecked()) def registerAction(self, action, menuName, callback=None): """ register an action to the manager's main menu """ if not hasattr(self, '_registeredDbActions'): self._registeredDbActions = {} if callback is not None: invoke_callback = lambda x: self.invokeCallback(callback) if menuName is None or menuName == "": self.addAction(action) if menuName not in self._registeredDbActions: self._registeredDbActions[menuName] = list() self._registeredDbActions[menuName].append(action) if callback is not None: QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback) return True # search for the menu actionMenu = None helpMenuAction = None for a in self.menuBar.actions(): if not a.menu() or a.menu().title() != menuName: continue if a.menu() != self.menuHelp: helpMenuAction = a actionMenu = a break # not found, add a new menu before the help menu if actionMenu is None: menu = QMenu(menuName, self) if helpMenuAction is not None: actionMenu = self.menuBar.insertMenu(helpMenuAction, menu) else: actionMenu = self.menuBar.addMenu(menu) menu = actionMenu.menu() menuActions = menu.actions() # get the placeholder's position to insert before it pos = 0 for pos in range(len(menuActions)): if menuActions[pos].isSeparator() and menuActions[pos].objectName( ).endswith("_placeholder"): menuActions[pos].setVisible(True) break if pos < len(menuActions): before = menuActions[pos] menu.insertAction(before, action) else: menu.addAction(action) actionMenu.setVisible(True) # show the menu if menuName not in self._registeredDbActions: self._registeredDbActions[menuName] = list() self._registeredDbActions[menuName].append(action) if callback is not None: QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback) return True def invokeCallback(self, callback, *params): """ Call a method passing the selected item in the database tree, the sender (usually a QAction), the plugin mainWindow and optionally additional parameters. This method takes care to override and restore the cursor, but also catches exceptions and displays the error dialog. """ QApplication.setOverrideCursor(Qt.WaitCursor) try: callback(self.tree.currentItem(), self.sender(), self, *params) except BaseError as e: # catch database errors and display the error dialog DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() def unregisterAction(self, action, menuName): if not hasattr(self, '_registeredDbActions'): return if menuName is None or menuName == "": self.removeAction(action) if menuName in self._registeredDbActions: if self._registeredDbActions[menuName].count(action) > 0: self._registeredDbActions[menuName].remove(action) action.deleteLater() return True for a in self.menuBar.actions(): if not a.menu() or a.menu().title() != menuName: continue menu = a.menu() menuActions = menu.actions() menu.removeAction(action) if menu.isEmpty(): # hide the menu a.setVisible(False) if menuName in self._registeredDbActions: if self._registeredDbActions[menuName].count(action) > 0: self._registeredDbActions[menuName].remove(action) # hide the placeholder if there're no other registered actions if len(self._registeredDbActions[menuName]) <= 0: for i in range(len(menuActions)): if menuActions[i].isSeparator() and menuActions[ i].objectName().endswith("_placeholder"): menuActions[i].setVisible(False) break action.deleteLater() return True return False def unregisterAllActions(self): if not hasattr(self, '_registeredDbActions'): return for menuName in self._registeredDbActions: for action in list(self._registeredDbActions[menuName]): self.unregisterAction(action, menuName) del self._registeredDbActions def close_tab(self, index): widget = self.tabs.widget(index) if widget not in [self.info, self.table, self.preview]: self.tabs.removeTab(index) widget.deleteLater() def setupUi(self): self.setWindowTitle(self.tr("DB Manager")) self.setWindowIcon(QIcon(":/db_manager/icon")) self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint())) # create central tab widget and add the first 3 tabs: info, table and preview self.tabs = QTabWidget() self.info = InfoViewer(self) self.tabs.addTab(self.info, self.tr("Info")) self.table = TableViewer(self) self.tabs.addTab(self.table, self.tr("Table")) self.preview = LayerPreview(self) self.tabs.addTab(self.preview, self.tr("Preview")) self.setCentralWidget(self.tabs) # display close button for all tabs but the first 3 ones, i.e. # HACK: just hide the close button where not needed (GS) self.tabs.setTabsClosable(True) self.tabs.tabCloseRequested.connect(self.close_tab) tabbar = self.tabs.tabBar() for i in range(3): btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton( i, QTabBar.RightSide) else tabbar.tabButton( i, QTabBar.LeftSide) btn.resize(0, 0) btn.hide() # Creates layout for message bar self.layout = QGridLayout(self.info) self.layout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layout.addItem(spacerItem, 1, 0, 1, 1) # init messageBar instance self.infoBar = QgsMessageBar(self.info) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.infoBar.setSizePolicy(sizePolicy) self.layout.addWidget(self.infoBar, 0, 0, 1, 1) # create database tree self.dock = QDockWidget("Tree", self) self.dock.setObjectName("DB_Manager_DBView") self.dock.setFeatures(QDockWidget.DockWidgetMovable) self.tree = DBTree(self) self.dock.setWidget(self.tree) self.addDockWidget(Qt.LeftDockWidgetArea, self.dock) # create status bar self.statusBar = QStatusBar(self) self.setStatusBar(self.statusBar) # create menus self.menuBar = QMenuBar(self) self.menuDb = QMenu(self.tr("&Database"), self) self.menuBar.addMenu(self.menuDb) self.menuSchema = QMenu(self.tr("&Schema"), self) actionMenuSchema = self.menuBar.addMenu(self.menuSchema) self.menuTable = QMenu(self.tr("&Table"), self) actionMenuTable = self.menuBar.addMenu(self.menuTable) self.menuHelp = None # QMenu(self.tr("&Help"), self) # actionMenuHelp = self.menuBar.addMenu(self.menuHelp) self.setMenuBar(self.menuBar) # create toolbar self.toolBar = QToolBar("Default", self) self.toolBar.setObjectName("DB_Manager_ToolBar") self.addToolBar(self.toolBar) # create menus' actions # menu DATABASE sep = self.menuDb.addSeparator() sep.setObjectName("DB_Manager_DbMenu_placeholder") sep.setVisible(False) self.actionRefresh = self.menuDb.addAction( QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"), self.refreshActionSlot, QKeySequence("F5")) self.actionSqlWindow = self.menuDb.addAction( QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"), self.runSqlWindow, QKeySequence("F2")) self.menuDb.addSeparator() self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q")) # menu SCHEMA sep = self.menuSchema.addSeparator() sep.setObjectName("DB_Manager_SchemaMenu_placeholder") sep.setVisible(False) actionMenuSchema.setVisible(False) # menu TABLE sep = self.menuTable.addSeparator() sep.setObjectName("DB_Manager_TableMenu_placeholder") sep.setVisible(False) self.actionImport = self.menuTable.addAction( QIcon(":/db_manager/actions/import"), self.tr("&Import layer/file"), self.importActionSlot) self.actionExport = self.menuTable.addAction( QIcon(":/db_manager/actions/export"), self.tr("&Export to file"), self.exportActionSlot) self.menuTable.addSeparator() #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables) #self.actionShowSystemTables.setCheckable(True) #self.actionShowSystemTables.setChecked(True) actionMenuTable.setVisible(False) # add actions to the toolbar self.toolBar.addAction(self.actionRefresh) self.toolBar.addAction(self.actionSqlWindow) self.toolBar.addAction(self.actionImport) self.toolBar.addAction(self.actionExport)
class ParcalaDialog(QDialog): def __init__(self, ui): QDialog.__init__(self, ui) self.ui = ui self.resize(450, 170) self.setMinimumSize(QSize(450, 170)) self.setMaximumSize(QSize(500, 200)) self.setWindowTitle(self.trUtf8("Parçala")) self.gridLayout = QGridLayout(self) self.neredenButton = QPushButton(self) self.neredenButton.setText(self.trUtf8("Nereden")) self.neredenButton.clicked.connect(self.nereden) self.gridLayout.addWidget(self.neredenButton, 0, 4, 1, 1) self.nereyeButton = QPushButton(self) self.nereyeButton.setText(self.trUtf8("Nereye")) self.nereyeButton.clicked.connect(self.nereye) self.gridLayout.addWidget(self.nereyeButton, 2, 4, 1, 1) self.parcalaButton = QPushButton(self) self.parcalaButton.setText(self.trUtf8("Parçala")) self.parcalaButton.clicked.connect(self.parcala) self.gridLayout.addWidget(self.parcalaButton, 5, 4, 1, 1) self.neredenEdit = QLineEdit(self) self.neredenEdit.setReadOnly(True) self.gridLayout.addWidget(self.neredenEdit, 0, 0, 1, 4) self.nereyeEdit = QLineEdit(self) self.nereyeEdit.setReadOnly(True) self.gridLayout.addWidget(self.nereyeEdit, 2, 0, 1, 4) self.mbLabel = QLabel(self) self.mbLabel.setText(self.trUtf8("Mb")) self.gridLayout.addWidget(self.mbLabel, 5, 3, 1, 1) self.boyutLabel = QLabel(self) self.boyutLabel.setText(self.trUtf8("Parçalama Boyutu:")) self.gridLayout.addWidget(self.boyutLabel, 5, 1, 1, 1) self.mbEdit = QLineEdit(self) self.mbEdit.returnPressed.connect(self.parcalaButton.animateClick) val = QIntValidator(1, 10000,self) self.mbEdit.setValidator(val) self.gridLayout.addWidget(self.mbEdit, 5, 2, 1, 1) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 5, 0, 1, 1) spacerItem1 = QSpacerItem(20, 15, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gridLayout.addItem(spacerItem1, 1, 1, 1, 1) spacerItem2 = QSpacerItem(20, 15, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gridLayout.addItem(spacerItem2, 3, 1, 1, 1) self.karaWidget = KaraWidget(self, "-") self.karaWidget.hide() def nereden(self): dosya = QFileDialog.getOpenFileName(self, "", settings().value("Genel/Yol").toString()) if dosya == "": pass elif QFile.exists(dosya): self.neredenEdit.setText(dosya) self.nereyeEdit.setText(dosya+".001") from os.path import abspath, dirname settings().setValue("Genel/Yol", abspath(dirname(str(dosya)))) else: QMessageBox.warning(self, self.trUtf8("Hata!"), self.trUtf8("Böyle bir dosya mevcut değil!")) def nereye(self): dosya = QFileDialog.getSaveFileName(self, "", settings().value("Genel/Yol").toString()) if not dosya == "": if dosya[-3:] == "001": self.nereyeEdit.setText(dosya) from os.path import abspath, dirname settings().setValue("Genel/Yol", abspath(dirname(str(dosya)))) return self.nereyeEdit.setText(dosya+".001") from os.path import abspath, dirname settings().setValue("Genel/Yol", abspath(dirname(str(dosya)))) def parcala(self): if self.neredenEdit.text() == "": QMessageBox.warning(self, self.trUtf8("Hata!"), self.trUtf8("Dosya seçmediniz!")) elif self.mbEdit.text() == "" or int(self.mbEdit.text()) == 0: QMessageBox.warning(self, self.trUtf8("Hata!"), self.trUtf8("Dosya boyutu girmediniz!")) elif int(self.mbEdit.text()) > QFile(self.neredenEdit.text()).size()/(1024*1024): QMessageBox.warning(self, self.trUtf8("Hata!"), self.trUtf8("Dosya büyüklüğünden fazla değer girdiniz!")) else: self.karaWidget.show() self.karaWidget.start() def keyPressEvent(self, event): pass def resizeEvent(self, event): self.karaWidget.setGeometry(0,0, event.size().width(), event.size().height())
def __init__(self, parent): QDialog.__init__(self, parent) self.tmpPref = {} self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.currLocale = self.parent().prm['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.audioManager = parent.audioManager self.mailer = emailSender(self) self.newMailerMessage.connect(self.popMailerMessage) self.tabWidget = QTabWidget() self.tabWidget.currentChanged.connect(self.tabChanged) self.appPrefWidget = QWidget() self.soundPrefWidget = QWidget() self.notificationPrefWidget = QWidget() self.eegPrefWidget = QWidget() #the gui widget for these are in an external dialog self.wavsPref = {} self.wavsPref['endMessageFiles'] = self.tmpPref['pref']['general']['endMessageFiles'] self.wavsPref['endMessageFilesUse'] = self.tmpPref['pref']['general']['endMessageFilesUse'] self.wavsPref['endMessageFilesID'] = self.tmpPref['pref']['general']['endMessageFilesID'] self.wavsPref['endMessageLevels'] = self.tmpPref['pref']['general']['endMessageLevels'] #GENERAL PREF appPrefGrid = QGridLayout() n = 0 self.languageChooserLabel = QLabel(self.tr('Language (requires restart):')) appPrefGrid.addWidget(self.languageChooserLabel, n, 0) self.languageChooser = QComboBox() self.languageChooser.addItems(self.parent().prm['appData']['available_languages']) self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.languageChooser.currentIndexChanged[int].connect(self.onLanguageChooserChange) appPrefGrid.addWidget(self.languageChooser, n, 1) n = n+1 self.countryChooserLabel = QLabel(self.tr('Country (requires restart):')) appPrefGrid.addWidget(self.countryChooserLabel, n, 0) self.countryChooser = QComboBox() self.countryChooser.addItems(self.parent().prm['appData']['available_countries'][self.tmpPref['pref']['language']]) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) appPrefGrid.addWidget(self.countryChooser, n, 1) n = n+1 self.responseBoxLanguageChooserLabel = QLabel(self.tr('Response Box Language (requires restart):')) appPrefGrid.addWidget(self.responseBoxLanguageChooserLabel, n, 0) self.responseBoxLanguageChooser = QComboBox() self.responseBoxLanguageChooser.addItems(self.parent().prm['appData']['available_languages']) self.responseBoxLanguageChooser.setCurrentIndex(self.responseBoxLanguageChooser.findText(self.tmpPref['pref']['responseBoxLanguage'])) self.responseBoxLanguageChooser.currentIndexChanged[int].connect(self.onResponseBoxLanguageChooserChange) appPrefGrid.addWidget(self.responseBoxLanguageChooser, n, 1) n = n+1 self.responseBoxCountryChooserLabel = QLabel(self.tr('Response Box Country (requires restart):')) appPrefGrid.addWidget(self.responseBoxCountryChooserLabel, n, 0) self.responseBoxCountryChooser = QComboBox() self.responseBoxCountryChooser.addItems(self.parent().prm['appData']['available_countries'][self.tmpPref['pref']['responseBoxLanguage']]) self.responseBoxCountryChooser.setCurrentIndex(self.responseBoxCountryChooser.findText(self.tmpPref['pref']['responseBoxCountry'])) appPrefGrid.addWidget(self.responseBoxCountryChooser, n, 1) n = n+1 self.csvSeparatorLabel = QLabel(self.tr('csv separator:')) appPrefGrid.addWidget(self.csvSeparatorLabel, n, 0) self.csvSeparatorWidget = QLineEdit(self.tmpPref['pref']["general"]["csvSeparator"]) appPrefGrid.addWidget(self.csvSeparatorWidget, n, 1) n = n+1 self.listenerNameWarnCheckBox = QCheckBox(self.tr('Warn if listener name missing')) self.listenerNameWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["listenerNameWarn"]) appPrefGrid.addWidget(self.listenerNameWarnCheckBox, n, 0) n = n+1 self.sessionLabelWarnCheckBox = QCheckBox(self.tr('Warn if session label missing')) self.sessionLabelWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["sessionLabelWarn"]) appPrefGrid.addWidget(self.sessionLabelWarnCheckBox, n, 0) n = n+1 self.dpCorrCheckBox = QCheckBox(self.tr('d-prime correction')) self.dpCorrCheckBox.setChecked(self.tmpPref['pref']['general']['dprimeCorrection']) self.dpCorrCheckBox.setWhatsThis(self.tr("If checked, when automatically processing result files, convert hit rates of 0 and 1 to 1/2N and 1-1/(2N) respectively, where N is the number of trials, to avoid infinite values of d'")) appPrefGrid.addWidget(self.dpCorrCheckBox, n, 0) n = n+1 self.recursionLimitLabel = QLabel(self.tr('Max Recursion Depth (requires restart):')) appPrefGrid.addWidget(self.recursionLimitLabel, n, 0) self.recursionLimitWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["maxRecursionDepth"])) self.recursionLimitWidget.setValidator(QIntValidator(self)) appPrefGrid.addWidget(self.recursionLimitWidget, n, 1) n = n+1 n = n+1 self.startupCommandLabel = QLabel(self.tr('Execute command at startup:')) appPrefGrid.addWidget(self.startupCommandLabel, n, 0) self.startupCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["startupCommand"]) appPrefGrid.addWidget(self.startupCommandWidget, n, 1) n = n+1 self.appPrefWidget.setLayout(appPrefGrid) self.appPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) #SOUND PREF soundPrefGrid = QGridLayout() n = 0 self.playChooser = QComboBox() self.playChooser.addItems(self.parent().prm['appData']['available_play_commands']) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['sound']['playCommandType'])) self.playChooser.currentIndexChanged[int].connect(self.onPlayChooserChange) self.playChooserLabel = QLabel(self.tr('Play Command:')) soundPrefGrid.addWidget(self.playChooserLabel, 0, 0) soundPrefGrid.addWidget(self.playChooser, 0, 1) n = n+1 self.playCommandLabel = QLabel(self.tr('Command:')) soundPrefGrid.addWidget(self.playCommandLabel, n, 0) self.playCommandWidget = QLineEdit(self.tmpPref['pref']['sound']['playCommand']) if self.playChooser.currentText() != self.tr('custom'): self.playCommandWidget.setReadOnly(True) soundPrefGrid.addWidget(self.playCommandWidget, n, 1) n = n+1 foo = self.playChooser.currentText() if foo != self.tr('custom'): self.playCommandLabel.hide() self.playCommandWidget.hide() #if alsaaudio is selected, provide device list chooser if self.parent().prm["appData"]["alsaaudioAvailable"] == True: self.alsaaudioPlaybackCardList = self.listAlsaaudioPlaybackCards() self.alsaaudioDeviceLabel = QLabel(self.tr('Device:')) soundPrefGrid.addWidget(self.alsaaudioDeviceLabel, n, 0) self.alsaaudioDeviceChooser = QComboBox() self.alsaaudioDeviceChooser.addItems(self.alsaaudioPlaybackCardList) self.alsaaudioDeviceChooser.setCurrentIndex(self.alsaaudioDeviceChooser.findText(self.tmpPref["pref"]["sound"]["alsaaudioDevice"])) soundPrefGrid.addWidget(self.alsaaudioDeviceChooser, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] != "alsaaudio": self.alsaaudioDeviceLabel.hide() self.alsaaudioDeviceChooser.hide() #if pyaudio is selected, provide device list chooser if self.parent().prm["appData"]["pyaudioAvailable"] == True: self.listPyaudioPlaybackDevices() self.pyaudioDeviceLabel = QLabel(self.tr('Device:')) soundPrefGrid.addWidget(self.pyaudioDeviceLabel, n, 0) self.pyaudioDeviceChooser = QComboBox() self.pyaudioDeviceChooser.addItems(self.pyaudioDeviceListName) try: self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref["pref"]["sound"]["pyaudioDevice"])) except: self.tmpPref["pref"]["sound"]["pyaudioDevice"] = self.pyaudioDeviceListIdx[0] self.parent().prm["pref"]["sound"]["pyaudioDevice"] = self.pyaudioDeviceListIdx[0] self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref["pref"]["sound"]["pyaudioDevice"])) soundPrefGrid.addWidget(self.pyaudioDeviceChooser, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] != "pyaudio": self.pyaudioDeviceLabel.hide() self.pyaudioDeviceChooser.hide() if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: self.bufferSizeLabel = QLabel(self.tr('Buffer Size (samples):')) soundPrefGrid.addWidget(self.bufferSizeLabel, n, 0) self.bufferSizeWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["sound"]["bufferSize"])) self.bufferSizeWidget.setValidator(QIntValidator(self)) soundPrefGrid.addWidget(self.bufferSizeWidget, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] not in ["alsaaudio", "pyaudio"]: self.bufferSizeLabel.hide() self.bufferSizeWidget.hide() self.samplerateLabel = QLabel(self.tr('Default Sampling Rate:')) soundPrefGrid.addWidget(self.samplerateLabel, n, 0) self.samplerateWidget = QLineEdit(self.tmpPref["pref"]["sound"]["defaultSampleRate"]) #self.samplerateWidget.setValidator(QIntValidator(self)) soundPrefGrid.addWidget(self.samplerateWidget, n, 1) n = n+1 self.nbitsLabel = QLabel(self.tr('Default Bits:')) self.nbitsChooser = QComboBox() self.nbitsChooser.addItems(self.parent().prm["nBitsChoices"]) self.nbitsChooser.setCurrentIndex(self.parent().prm["nBitsChoices"].index(self.tmpPref["pref"]["sound"]["defaultNBits"])) soundPrefGrid.addWidget(self.nbitsLabel, n, 0) soundPrefGrid.addWidget(self.nbitsChooser, n, 1) n = n+1 self.wavmanagerLabel = QLabel(self.tr('Wav Manager (requires restart):')) self.wavmanagerChooser = QComboBox() self.wavmanagerChooser.addItems(self.parent().prm['appData']['wavmanagers']) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager'])) soundPrefGrid.addWidget(self.wavmanagerLabel, n, 0) soundPrefGrid.addWidget(self.wavmanagerChooser, n, 1) n = n+1 self.writewav = QCheckBox(self.tr('Write wav file')) self.writewav.setChecked(self.tmpPref["pref"]["sound"]["writewav"]) soundPrefGrid.addWidget(self.writewav, n, 0) n = n+1 self.writeSndSeqSegments = QCheckBox(self.tr('Write sound sequence segments wavs')) self.writeSndSeqSegments.setChecked(self.tmpPref["pref"]["sound"]["writeSndSeqSegments"]) soundPrefGrid.addWidget(self.writeSndSeqSegments, n, 0) n = n+1 self.appendSilenceLabel = QLabel(self.tr('Append silence to each sound (ms):')) soundPrefGrid.addWidget(self.appendSilenceLabel, n, 0) self.appendSilenceWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["sound"]["appendSilence"])) soundPrefGrid.addWidget(self.appendSilenceWidget, n, 1) n = n+1 self.soundPrefWidget.setLayout(soundPrefGrid) self.soundPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) # NOTIFICATION PREF notificationPrefGrid = QGridLayout() n = 0 self.playEndMessage = QCheckBox(self.tr('Play End Message')) self.playEndMessage.setChecked(self.tmpPref["pref"]["general"]["playEndMessage"]) notificationPrefGrid.addWidget(self.playEndMessage, n, 0) self.endMessageButton = QPushButton(self.tr("Choose Wav"), self) self.endMessageButton.clicked.connect(self.onClickEndMessageButton) notificationPrefGrid.addWidget(self.endMessageButton, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.nBlocksLabel = QLabel(self.tr('blocks before end of experiment:')) notificationPrefGrid.addWidget(self.nBlocksLabel, n, 1) self.nBlocksWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['email']['nBlocksNotify'])) notificationPrefGrid.addWidget(self.nBlocksWidget, n, 0) n = n+1 self.emailNotify = QCheckBox(self.tr('Send Notification e-mail')) self.emailNotify.setChecked(self.tmpPref["pref"]["email"]["notifyEnd"]) notificationPrefGrid.addWidget(self.emailNotify, n, 0) n = n+1 self.nBlocksCustomCommandLabel = QLabel(self.tr('Execute custom command:')) notificationPrefGrid.addWidget(self.nBlocksCustomCommandLabel, n, 0) self.nBlocksCustomCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["nBlocksCustomCommand"]) notificationPrefGrid.addWidget(self.nBlocksCustomCommandWidget, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.atEndLabel = QLabel(self.tr('At the end of the experiment:')) notificationPrefGrid.addWidget(self.atEndLabel, n, 0) n = n+1 self.sendData = QCheckBox(self.tr('Send data via e-mail')) self.sendData.setChecked(self.tmpPref["pref"]["email"]["sendData"]) notificationPrefGrid.addWidget(self.sendData, n, 0) n = n+1 self.atEndCustomCommandLabel = QLabel(self.tr('Execute custom command:')) notificationPrefGrid.addWidget(self.atEndCustomCommandLabel, n, 0) self.atEndCustomCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["atEndCustomCommand"]) notificationPrefGrid.addWidget(self.atEndCustomCommandWidget, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.serverLabel = QLabel(self.tr('Outgoing server (SMTP):')) notificationPrefGrid.addWidget(self.serverLabel, n, 0) self.serverWidget = QLineEdit(self.tmpPref['pref']['email']['SMTPServer']) notificationPrefGrid.addWidget(self.serverWidget, n, 1) n = n+1 self.serverPortLabel = QLabel(self.tr('Port:')) notificationPrefGrid.addWidget(self.serverPortLabel, n, 0) self.serverPortWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['email']['SMTPServerPort'])) self.serverPortWidget.setValidator(QIntValidator(self)) notificationPrefGrid.addWidget(self.serverPortWidget, n, 1) n = n+1 self.serverSecurityLabel = QLabel(self.tr('Security:')) notificationPrefGrid.addWidget(self.serverSecurityLabel, n, 0) self.serverSecurityChooser = QComboBox() self.serverSecurityChooser.addItems(["TLS/SSL (a)", "TLS/SSL (b)", "none"]) self.serverSecurityChooser.setCurrentIndex(self.serverSecurityChooser.findText(self.tmpPref['pref']['email']['SMTPServerSecurity'])) notificationPrefGrid.addWidget(self.serverSecurityChooser, n, 1) n = n+1 self.serverRequiresAuthCheckBox = QCheckBox(self.tr('Server requires authentication')) self.serverRequiresAuthCheckBox.setChecked(self.tmpPref["pref"]["email"]["serverRequiresAuthentication"]) notificationPrefGrid.addWidget(self.serverRequiresAuthCheckBox, n, 0, 1, 2) n = n+1 self.usernameLabel = QLabel(self.tr('Username:'******'pref']['email']['fromUsername']) notificationPrefGrid.addWidget(self.usernameWidget, n, 1) n = n+1 self.passwordLabel = QLabel(self.tr('Password:'******'pref']['email']['fromPassword']) self.passwordWidget.setEchoMode(QLineEdit.Password) notificationPrefGrid.addWidget(self.passwordWidget, n, 1) n = n+1 self.passwordWarningLabel = QLabel(self.tr('Password is NOT stored safely (see manual), use at your own risk!')) notificationPrefGrid.addWidget(self.passwordWarningLabel, n, 0, 1, 2) n = n+1 self.testEmailButton = QPushButton(self.tr("Send test e-mail"), self) self.testEmailButton.clicked.connect(self.onClickTestEmailButton) self.testEmailButton.setToolTip(self.tr("Send a test e-mail")) notificationPrefGrid.addWidget(self.testEmailButton, n, 0, 1, 2) self.notificationPrefWidget.setLayout(notificationPrefGrid) self.notificationPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) ##--#--#--#--#-- # EEG PREF GRID eegPrefGrid = QGridLayout() n = 0 self.ONTriggerLabel = QLabel(self.tr('ON Trigger:')) eegPrefGrid.addWidget(self.ONTriggerLabel, n, 0) self.ONTriggerWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["ONTrigger"])) eegPrefGrid.addWidget(self.ONTriggerWidget, n, 1) n = n+1 self.OFFTriggerLabel = QLabel(self.tr('OFF Trigger:')) eegPrefGrid.addWidget(self.OFFTriggerLabel, n, 0) self.OFFTriggerWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["OFFTrigger"])) eegPrefGrid.addWidget(self.OFFTriggerWidget, n, 1) n = n+1 self.triggerDurLabel = QLabel(self.tr('Trigger Duration (ms):')) eegPrefGrid.addWidget(self.triggerDurLabel, n, 0) self.triggerDurWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["triggerDur"])) eegPrefGrid.addWidget(self.triggerDurWidget, n, 1) self.eegPrefWidget.setLayout(eegPrefGrid) self.eegPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) # ........................ self.tabWidget.addTab(self.appPrefWidget, self.tr("Genera&l")) self.tabWidget.addTab(self.soundPrefWidget, self.tr("Soun&d")) self.tabWidget.addTab(self.notificationPrefWidget, self.tr("Notification&s")) self.tabWidget.addTab(self.eegPrefWidget, self.tr("EE&G")) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply) layout = QVBoxLayout() layout.addWidget(self.tabWidget) layout.addWidget(buttonBox) self.setLayout(layout)
class Cryptographie(Panel_simple): titre = u"Cryptographie" # Donner un titre à chaque module def __init__(self, *args, **kw): Panel_simple.__init__(self, *args, **kw) self._freeze = False self.widget_modifie = None # La clé est la permutation de l'alphabet actuellement utilisée # pour le codage par substitution mono-alphabétique. self.generer_cle() # La clé de chiffrement pour le codage par substitution poly-alphabétique # (appelé aussi chiffre de Vigenère). self.cle_vigenere = 'EXEMPLE' # Signe indiquant un caractère non déchiffré self.symbole = '-' # '.' self.sizer = QVBoxLayout() self.textes = QGridLayout() self.textes.setSpacing(5) size = (400, 300) txt_clair = QLabel(u"<b>Texte en clair</b>") self.clair = QTextEdit() self.clair.setMinimumSize(*size) formater_clair = partial(self.formater, widget=self.clair) self.clair.textChanged.connect(formater_clair) self.clair.cursorPositionChanged.connect(formater_clair) self.copier_clair = QPushButton(u'Copier le texte en clair') self.copier_clair.clicked.connect(partial(self.copier, widget=self.clair)) txt_code = QLabel(u"<b>Texte codé</b>") self.code = QTextEdit() self.code.setMinimumSize(*size) self.code.textChanged.connect(self.code_modifie) self.code.cursorPositionChanged.connect(partial(self.formater, widget=self.code)) self.copier_code = QPushButton(u'Copier le texte codé') self.copier_code.clicked.connect(partial(self.copier, widget=self.code)) self.textes.addWidget(txt_clair, 0, 0) self.textes.addItem(QSpacerItem(50, 1), 0, 1) self.textes.addWidget(txt_code, 0, 2) self.textes.addWidget(self.clair, 1, 0) self.textes.addWidget(self.code, 1, 2) self.textes.addWidget(self.copier_code, 2, 2) self.textes.addWidget(self.copier_clair, 2, 0) self.table = QGridLayout() self.table.setSpacing(3) self.cases = {} self.table.addWidget(QLabel(u"Codé : ", self), 0, 0) self.table.addWidget(QLabel(u"Clair : ", self), 1, 0) ##self.table.setColumnStretch(0, 100) for i, l in enumerate(majuscules): lettre = QLineEdit(l, self) lettre.setAlignment(Qt.AlignCenter) lettre.setReadOnly(True) lettre.setEnabled(False) self.table.addWidget(lettre, 0, i + 1) ##self.table.setColumnStretch(i + 1, 1) for i, l in enumerate(majuscules): c = self.cases[l] = CaseLettre(self) c.setMaxLength(1) self.table.addWidget(c, 1, i + 1) c.textChanged.connect(self.decoder) self.sizer.addLayout(self.textes) self.sizer.addLayout(self.table) self.setLayout(self.sizer) ##self.adjustSize() self.couleur1 = "5A28BE" # sky blue self.couleur2 = "C86400" # Lime Green self.couleur_position = "FFCDB3" self.reg = re.compile("([-A-Za-z]|<##>|</##>)+") ##couleur_position = wx.Color(255, 205, 179) # FFCDB3 ##couleur1 = wx.Color(90, 40, 190) # 5A28BE ##couleur2 = wx.Color(200, 100, 0) # C86400 ##black = wx.Color(0, 0, 0) # 000000 ##white = wx.Color(255, 255, 255) # FFFFFF ##self.special = wx.TextAttr(wx.NullColour, couleur_position) ##self.fond = wx.TextAttr(couleur1, wx.NullColour) #"sky blue" ##self.fond2 = wx.TextAttr(couleur2, wx.NullColour) # "Lime Green" ##self.defaut = wx.TextAttr(black, white) ## ##self.Bind(wx.EVT_IDLE, self.OnIdle) timer = QTimer(self) timer.timeout.connect(self.OnIdle) timer.start(100) # DEBUG: ##self.code.setPlainText('WR IRAMXPZRHRDZ IK HRYYOVR AL IRYYBKY RYZ NOALWLZR POM WR NOLZ FKR W BD O VOMIR WRY YLVDRY IR PBDAZKOZLBD RZ WRY RYPOARY RDZMR WRY HBZY OWBMY FKR I QOELZKIR BD VMBKPR WRY WRZZMRY ALDF POM ALDF') def copier(self, evt=None, widget=None): self.vers_presse_papier(widget.toPlainText()) def DlgModifierCle(self, evt=None): while True: text, ok = QInputDialog.getText(self, u"Modifier la clé", u"La clé doit être une permutation de l'alphabet,\n" u"ou un chiffre qui indique de combien l'alphabet est décalé.", text=str(self.cle)) if ok: try: self.modifier_cle(text) except: print_error() continue break def generer_cle(self): l = list(majuscules) shuffle(l) self.cle = ''.join(l) def modifier_cle(self, cle): cle = cle.strip().upper() if cle.isdigit(): n = int(cle) cle = majuscules[n:] + majuscules[:n] # On teste qu'il s'agit bien d'une permutation de l'alphabet: assert ''.join(sorted(cle)) == majuscules self.cle = cle def coder(self, evt=None, cle=None, espaces=False): cle = (self.cle if cle is None else cle) clair = self.clair.toPlainText().upper() for key, val in dict_accents.items(): clair = clair.replace(key, val) d = dict(zip(majuscules, cle)) code = ''.join(d.get(s, ' ') for s in clair) code = re.sub(' +', ' ', code) if not espaces: code = code.replace(' ', '') self.code.setPlainText(code) return code @staticmethod def _vigenere(l1, l2): return chr((ord(l1) + ord(l2) - 130)%26 + 65) def coder_vigenere(self, evt=None, msg=None, cle=None, ask=False): def gen(): length = len(cle) n = 0 for car in clair: if car.isalpha(): yield self._vigenere(cle[n%length], car) n += 1 else: yield car if ask: self.DlgModifierCleVigenere() if cle is None: cle = self.cle_vigenere if msg is None: msg = self.clair.toPlainText() msg = msg.upper() if cle is None: pass # Pour l'instant, les espaces ne sont pas supportés clair = msg.replace(' ', '') clair = self.clair.toPlainText().upper() for key, val in dict_accents.items(): clair = clair.replace(key, val) code = ''.join(gen()) self.code.setPlainText(code) return code def DlgModifierCleVigenere(self, evt=None): while True: text, ok = QInputDialog.getText(self, u"Modifier la clé pour Vigenère", u"La clé doit contenir uniquement des lettres.", text=self.cle_vigenere) if ok: text = text.strip() if not text.isalpha(): continue self.cle_vigenere = text.upper() break def decoder(self, txt=None): code = self.code.toPlainText().upper() def f(s): if s in majuscules: return self.cases[s].text() or self.symbole return s clair = ''.join(f(s) for s in code) self.clair.setPlainText(clair) def code_modifie(self, txt=None): self.decoder(txt) self.formater(txt, widget=self.code) def formater(self, evt=None, widget=None): ##evt.Skip() if self._freeze: return self.widget_modifie = widget def _formater(self, widget_modifie): # Impossible de formater les 2 textes de la même manière s'ils # ne sont pas de la même longueur. # Cela ne devrait se produire que temporairement (par ex., # l'utilisateur copie un nouveau texte) if len(self.code.toPlainText()) != len(self.clair.toPlainText()): if self.code.toPlainText() and self.clair.toPlainText(): print(u'Warning: le message codé et le message en clair ne sont ' u'pas de même longueur.') return def colorier(m, col1=[self.couleur1], col2=[self.couleur2]): s = m.group(0) s = "<font color='#%s'>%s</font>" % (col1[0], s) col1[0], col2[0] = col2[0], col1[0] return s self._freeze = True pos = widget_modifie.textCursor().position() for w in (self.code, self.clair): txt = w.toPlainText() if pos != len(txt): txt = txt[:pos] + '<##>' + txt[pos] + '</##>' + txt[pos + 1:] new_txt = re.sub(self.reg, colorier, txt) new_txt = new_txt.replace("<##>", "<font style='background-color: #%s;'>" % self.couleur_position) new_txt = new_txt.replace("</##>", "</font>") w.setHtml(new_txt) cursor = widget_modifie.textCursor() cursor.setPosition(pos) widget_modifie.setTextCursor(cursor) self._freeze = False self.widget_modifie = None def OnIdle(self, evt=None): if self.widget_modifie is not None and not self.parent.parent.closing: self._formater(self.widget_modifie)
class ShellOutputScintilla(QsciScintilla): def __init__(self, parent=None): super(ShellOutputScintilla, self).__init__(parent) self.parent = parent self.shell = self.parent.shell self.settings = QSettings() # Creates layout for message bar self.layout = QGridLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layout.addItem(spacerItem, 1, 0, 1, 1) # messageBar instance self.infoBar = QgsMessageBar() sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.infoBar.setSizePolicy(sizePolicy) self.layout.addWidget(self.infoBar, 0, 0, 1, 1) # Enable non-ascii chars for editor self.setUtf8(True) sys.stdout = writeOut(self, sys.stdout) sys.stderr = writeOut(self, sys.stderr, "_traceback") self.insertInitText() self.refreshSettingsOutput() self.setReadOnly(True) # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) # Margin 0 is used for line numbers self.setMarginWidth(0, 0) self.setMarginWidth(1, 0) self.setMarginWidth(2, 0) #fm = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(1, "00000") self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor("#3E3EE3")) self.setMarginsBackgroundColor(QColor("#f9f9f9")) self.setCaretLineVisible(True) self.setCaretWidth(0) self.setMinimumHeight(120) self.setWrapMode(QsciScintilla.WrapCharacter) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self) self.runScut.setContext(Qt.WidgetShortcut) self.runScut.activated.connect(self.enteredSelected) # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view self.copyShortcut = QShortcut(QKeySequence.Copy, self) self.copyShortcut.activated.connect(self.copy) self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self) self.selectAllShortcut.activated.connect(self.selectAll) def insertInitText(self): txtInit = QCoreApplication.translate( "PythonConsole", "Python Console \n" "Use iface to access QGIS API interface or Type help(iface) for more info" ) ## some translation string for the console header ends without '\n' ## and the first command in console will be appended at the header text. ## The following code add a '\n' at the end of the string if not present. if txtInit.endswith('\n'): self.setText(txtInit) else: self.setText(txtInit + '\n') def refreshSettingsOutput(self): # Set Python lexer self.setLexers() caretLineColor = self.settings.value("pythonConsole/caretLineColor", QColor("#fcf3ed")) cursorColor = self.settings.value("pythonConsole/cursorColor", QColor(Qt.black)) self.setCaretLineBackgroundColor(caretLineColor) self.setCaretForegroundColor(cursorColor) def setLexers(self): self.lexer = QsciLexerPython() loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace") fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int) font = QFont(loadFont) font.setFixedPitch(True) font.setPointSize(fontSize) font.setStyleHint(QFont.TypeWriter) font.setStretch(QFont.SemiCondensed) font.setLetterSpacing(QFont.PercentageSpacing, 87.0) font.setBold(False) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor( QColor( self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black)))) self.lexer.setColor( QColor( self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1) self.lexer.setColor( QColor( self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5) self.lexer.setColor( QColor( self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8) self.lexer.setColor( QColor( self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9) self.lexer.setColor( QColor( self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15) self.lexer.setColor( QColor( self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12) self.lexer.setColor( QColor( self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4) self.lexer.setColor( QColor( self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3) self.lexer.setColor( QColor( self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6) self.lexer.setColor( QColor( self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7) self.lexer.setColor(QColor(Qt.red), 14) self.lexer.setFont(font, 1) self.lexer.setFont(font, 2) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) for style in range(0, 33): paperColor = QColor( self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white))) self.lexer.setPaper(paperColor, style) self.setLexer(self.lexer) def clearConsole(self): self.setText('') self.insertInitText() self.shell.setFocus() def contextMenuEvent(self, e): menu = QMenu(self) iconRun = QgsApplication.getThemeIcon("console/iconRunConsole.png") iconClear = QgsApplication.getThemeIcon("console/iconClearConsole.png") iconHideTool = QgsApplication.getThemeIcon( "console/iconHideToolConsole.png") iconSettings = QgsApplication.getThemeIcon( "console/iconSettingsConsole.png") menu.addAction( iconHideTool, QCoreApplication.translate("PythonConsole", "Hide/Show Toolbar"), self.hideToolBar) menu.addSeparator() showEditorAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Show Editor"), self.showEditor) menu.addSeparator() runAction = menu.addAction( iconRun, QCoreApplication.translate("PythonConsole", "Enter Selected"), self.enteredSelected, QKeySequence(Qt.CTRL + Qt.Key_E)) clearAction = menu.addAction( iconClear, QCoreApplication.translate("PythonConsole", "Clear Console"), self.clearConsole) menu.addSeparator() copyAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Copy"), self.copy, QKeySequence.Copy) selectAllAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Select All"), self.selectAll, QKeySequence.SelectAll) menu.addSeparator() menu.addAction( iconSettings, QCoreApplication.translate("PythonConsole", "Options..."), self.parent.openSettings) runAction.setEnabled(False) clearAction.setEnabled(False) copyAction.setEnabled(False) selectAllAction.setEnabled(False) showEditorAction.setEnabled(True) if self.hasSelectedText(): runAction.setEnabled(True) copyAction.setEnabled(True) if not self.text(3) == '': selectAllAction.setEnabled(True) clearAction.setEnabled(True) if self.parent.tabEditorWidget.isVisible(): showEditorAction.setEnabled(False) menu.exec_(self.mapToGlobal(e.pos())) def hideToolBar(self): tB = self.parent.toolBar tB.hide() if tB.isVisible() else tB.show() self.shell.setFocus() def showEditor(self): Ed = self.parent.splitterObj if not Ed.isVisible(): Ed.show() self.parent.showEditorButton.setChecked(True) self.shell.setFocus() def copy(self): """Copy text to clipboard... or keyboard interrupt""" if self.hasSelectedText(): text = unicode(self.selectedText()) text = text.replace('>>> ', '').replace('... ', '').strip() # removing prompts QApplication.clipboard().setText(text) else: self.emit(SIGNAL("keyboard_interrupt()")) def enteredSelected(self): cmd = self.selectedText() self.shell.insertFromDropPaste(cmd) self.shell.entered() def keyPressEvent(self, e): # empty text indicates possible shortcut key sequence so stay in output txt = e.text() if len(txt) and txt >= " ": self.shell.append(txt) self.shell.move_cursor_to_end() self.shell.setFocus() e.ignore() else: # possible shortcut key sequence, accept it e.accept() def widgetMessageBar(self, iface, text): timeout = iface.messageTimeout() self.infoBar.pushMessage(text, QgsMessageBar.INFO, timeout)
def __init__(self, parent): super(ProjectExecution, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(self.tr("Main File:")), 0, 0) self.path = QLineEdit() ui_tools.LineEditButton(self.path, self.path.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.path.setText(self._parent._item.mainFile) self.path.setReadOnly(True) self.btnBrowse = QPushButton(QIcon( self.style().standardPixmap(self.style().SP_FileIcon)), '') grid.addWidget(self.path, 0, 1) grid.addWidget(self.btnBrowse, 0, 2) # this should be changed, and ALL pythonPath names to # python_custom_interpreter or something like that. this is NOT the # PYTHONPATH self.txtPythonPath = QLineEdit() self.txtPythonPath.setText(self._parent._item.pythonPath) self.btnPythonPath = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Python Custom Interpreter:")), 1, 0) grid.addWidget(self.txtPythonPath, 1, 1) grid.addWidget(self.btnPythonPath, 1, 2) # THIS IS THE MODAFUCKA REAL PYTHONPATH BRO, YEAH !!! grid.addWidget(QLabel(self.tr("Custom PYTHONPATH:")), 2, 0) self.PYTHONPATH = QPlainTextEdit() # TODO : better widget self.PYTHONPATH.setPlainText(self._parent._item.PYTHONPATH) self.PYTHONPATH.setToolTip(self.tr("One path per line")) grid.addWidget(self.PYTHONPATH, 2, 1) # Additional builtins/globals for pyflakes grid.addWidget(QLabel(self.tr("Additional builtins/globals:")), 3, 0) self.additional_builtins = QLineEdit() self.additional_builtins.setText( ' '.join(self._parent._item.additional_builtins)) self.additional_builtins.setToolTip(self.tr( "Space-separated list of symbols that will be considered as " "builtin in every file")) grid.addWidget(self.additional_builtins, 3, 1) self.txtPreExec = QLineEdit() ui_tools.LineEditButton(self.txtPreExec, self.txtPreExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPreExec.setReadOnly(True) self.txtPreExec.setText(self._parent._item.preExecScript) self.btnPreExec = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Pre-exec Script:")), 4, 0) grid.addWidget(self.txtPreExec, 4, 1) grid.addWidget(self.btnPreExec, 4, 2) self.txtPostExec = QLineEdit() ui_tools.LineEditButton(self.txtPostExec, self.txtPostExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPostExec.setReadOnly(True) self.txtPostExec.setText(self._parent._item.postExecScript) self.btnPostExec = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Post-exec Script:")), 5, 0) grid.addWidget(self.txtPostExec, 5, 1) grid.addWidget(self.btnPostExec, 5, 2) grid.addItem(QSpacerItem(5, 10, QSizePolicy.Expanding, QSizePolicy.Expanding), 6, 0) # Properties grid.addWidget(QLabel(self.tr("Properties:")), 7, 0) self.txtParams = QLineEdit() self.txtParams.setToolTip( self.tr("Separate the params with commas (ie: help, verbose)")) self.txtParams.setText(self._parent._item.programParams) grid.addWidget(QLabel(self.tr("Params (comma separated):")), 8, 0) grid.addWidget(self.txtParams, 8, 1) #Widgets for virtualenv properties self.txtVenvPath = QLineEdit() ui_tools.LineEditButton(self.txtVenvPath, self.txtVenvPath.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtVenvPath.setText(self._parent._item.venv) self._dir_completer = QCompleter() self._dir_completer.setModel(QDirModel(self._dir_completer)) self.txtVenvPath.setCompleter(self._dir_completer) self.btnVenvPath = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Virtualenv Folder:")), 9, 0) grid.addWidget(self.txtVenvPath, 9, 1) grid.addWidget(self.btnVenvPath, 9, 2) self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_file) self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path) self.connect(self.btnVenvPath, SIGNAL("clicked()"), self._load_python_venv) self.connect(self.btnPreExec, SIGNAL("clicked()"), self.select_pre_exec_script) self.connect(self.btnPostExec, SIGNAL("clicked()"), self.select_post_exec_script)
class ClientDialog(QDialog): """a simple popup dialog for asking the player what he wants to do""" def __init__(self, client, parent=None): QDialog.__init__(self, parent) self.setWindowTitle(m18n('Choose') + ' - Kajongg') self.setObjectName('ClientDialog') self.client = client self.layout = QGridLayout(self) self.progressBar = QProgressBar() self.timer = QTimer() if not client.game.autoPlay: self.timer.timeout.connect(self.timeout) self.deferred = None self.buttons = [] self.setWindowFlags(Qt.SubWindow | Qt.WindowStaysOnTopHint) self.setModal(False) self.btnHeight = 0 self.answered = False def keyPressEvent(self, event): """ESC selects default answer""" if not self.client.game or self.client.game.autoPlay: return if event.key() in [Qt.Key_Escape, Qt.Key_Space]: self.selectButton() event.accept() else: for btn in self.buttons: if str(event.text()).upper() == btn.message.shortcut: self.selectButton(btn) event.accept() return QDialog.keyPressEvent(self, event) def __declareButton(self, message): """define a button""" maySay = self.client.sayable[message] if Preferences.showOnlyPossibleActions and not maySay: return btn = DlgButton(message, self) btn.setAutoDefault(True) btn.clicked.connect(self.selectedAnswer) self.buttons.append(btn) def focusTileChanged(self): """update icon and tooltip for the discard button""" if not self.client.game: return for button in self.buttons: button.decorate(self.client.game.myself.handBoard.focusTile) for tile in self.client.game.myself.handBoard.lowerHalfTiles(): txt = [] for button in self.buttons: _, _, tileTxt = button.message.toolTip(button, tile) if tileTxt: txt.append(tileTxt) txt = '<br><br>'.join(txt) tile.graphics.setToolTip(txt) if self.client.game.activePlayer == self.client.game.myself: Internal.field.handSelectorChanged(self.client.game.myself.handBoard) def checkTiles(self): """does the logical state match the displayed tiles?""" for player in self.client.game.players: logExposed = list() physExposed = list() physConcealed = list() for tile in player.bonusTiles: logExposed.append(tile.element) for tile in player.handBoard.tiles: if tile.yoffset == 0 or tile.element[0] in 'fy': physExposed.append(tile.element) else: physConcealed.append(tile.element) for meld in player.exposedMelds: logExposed.extend(meld.pairs) logConcealed = sorted(player.concealedTileNames) logExposed.sort() physExposed.sort() physConcealed.sort() assert logExposed == physExposed, '%s != %s' % (logExposed, physExposed) assert logConcealed == physConcealed, '%s != %s' % (logConcealed, physConcealed) def messages(self): """a list of all messages returned by the declared buttons""" return list(x.message for x in self.buttons) def proposeAction(self): """either intelligently or first button by default. May also focus a proposed tile depending on the action.""" result = self.buttons[0] game = self.client.game if game.autoPlay or Preferences.propose: answer, parameter = self.client.intelligence.selectAnswer( self.messages()) result = [x for x in self.buttons if x.message == answer][0] result.setFocus() if answer in [Message.Discard, Message.OriginalCall]: for tile in game.myself.handBoard.tiles: if tile.element == parameter: game.myself.handBoard.focusTile = tile return result def askHuman(self, move, answers, deferred): """make buttons specified by answers visible. The first answer is default. The default button only appears with blue border when this dialog has focus but we always want it to be recognizable. Hence setBackgroundRole.""" self.move = move self.deferred = deferred for answer in answers: self.__declareButton(answer) self.focusTileChanged() self.show() self.checkTiles() game = self.client.game myTurn = game.activePlayer == game.myself prefButton = self.proposeAction() if game.autoPlay: self.selectButton(prefButton) return prefButton.setFocus() self.progressBar.setVisible(not myTurn) if not myTurn: msecs = 50 self.progressBar.setMinimum(0) self.progressBar.setMaximum(game.ruleset.claimTimeout * 1000 // msecs) self.progressBar.reset() self.timer.start(msecs) def placeInField(self): """place the dialog at bottom or to the right depending on space.""" field = Internal.field cwi = field.centralWidget() view = field.centralView geometry = self.geometry() if not self.btnHeight: self.btnHeight = self.buttons[0].height() vertical = view.width() > view.height() * 1.2 if vertical: height = (len(self.buttons) + 1) * self.btnHeight * 1.2 width = (cwi.width() - cwi.height() ) // 2 geometry.setX(cwi.width() - width) geometry.setY(min(cwi.height()//3, cwi.height() - height)) else: handBoard = self.client.game.myself.handBoard if not handBoard: # we are in the progress of logging out return hbLeftTop = view.mapFromScene(handBoard.mapToScene(handBoard.rect().topLeft())) hbRightBottom = view.mapFromScene(handBoard.mapToScene(handBoard.rect().bottomRight())) width = hbRightBottom.x() - hbLeftTop.x() height = self.btnHeight geometry.setY(cwi.height() - height) geometry.setX(hbLeftTop.x()) for idx, btn in enumerate(self.buttons + [self.progressBar]): self.layout.addWidget(btn, idx+1 if vertical else 0, idx+1 if not vertical else 0) idx = len(self.buttons) + 2 spacer = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Expanding) self.layout.addItem(spacer, idx if vertical else 0, idx if not vertical else 0) geometry.setWidth(width) geometry.setHeight(height) self.setGeometry(geometry) def showEvent(self, dummyEvent): """try to place the dialog such that it does not cover interesting information""" self.placeInField() def timeout(self): """the progressboard wants an update""" pBar = self.progressBar if isAlive(pBar): pBar.setValue(pBar.value()+1) pBar.setVisible(True) if pBar.value() == pBar.maximum(): # timeout: we always return the original default answer, not the one with focus self.selectButton() pBar.setVisible(False) def selectButton(self, button=None): """select default answer. button may also be of type Message.""" self.timer.stop() self.answered = True if button is None: button = self.focusWidget() if isinstance(button, Message): assert any(x.message == button for x in self.buttons) answer = button else: answer = button.message if not self.client.sayable[answer]: Sorry(m18n('You cannot say %1', answer.i18nName)) return Internal.field.clientDialog = None self.deferred.callback(answer) def selectedAnswer(self, dummyChecked): """the user clicked one of the buttons""" game = self.client.game if game and not game.autoPlay: self.selectButton(self.sender())
def __init__(self, parent): super(ProjectExecution, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(translations.TR_PROJECT_MAIN_FILE), 0, 0) self.path = QLineEdit() self.path.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'main.py')) ui_tools.LineEditButton( self.path, self.path.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.path.setText(self._parent.project.main_file) self.path.setReadOnly(True) self.btnBrowse = QPushButton( QIcon(self.style().standardPixmap(self.style().SP_FileIcon)), '') grid.addWidget(self.path, 0, 1) grid.addWidget(self.btnBrowse, 0, 2) # this should be changed, and ALL pythonPath names to # python_custom_interpreter or something like that. this is NOT the # PYTHONPATH self.txtPythonInterpreter = QLineEdit() self.txtPythonInterpreter.setText(self._parent.project.python_exec) self.txtPythonInterpreter.setCompleter( QCompleter( ('python', 'python2', 'python3', 'python.exe', 'pythonw.exe'))) self.txtPythonInterpreter.setPlaceholderText("python") self.btnPythonPath = QPushButton(QIcon(":img/open"), '') grid.addWidget(QLabel(translations.TR_PROJECT_PYTHON_INTERPRETER), 1, 0) grid.addWidget(self.txtPythonInterpreter, 1, 1) grid.addWidget(self.btnPythonPath, 1, 2) grid.addWidget(QLabel(translations.TR_PROJECT_PYTHON_PATH), 2, 0) self.txtPythonPath = QPlainTextEdit() # TODO : better widget self.txtPythonPath.setPlainText(self._parent.project.python_path) self.txtPythonPath.setToolTip(translations.TR_PROJECT_PATH_PER_LINE) grid.addWidget(self.txtPythonPath, 2, 1) # Additional builtins/globals for pyflakes grid.addWidget(QLabel(translations.TR_PROJECT_BUILTINS), 3, 0) self.additional_builtins = QLineEdit() self.additional_builtins.setText(' '.join( self._parent.project.additional_builtins)) self.additional_builtins.setToolTip( translations.TR_PROJECT_BUILTINS_TOOLTIP) grid.addWidget(self.additional_builtins, 3, 1) self.txtPreExec = QLineEdit() ui_tools.LineEditButton( self.txtPreExec, self.txtPreExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPreExec.setReadOnly(True) self.txtPreExec.setText(self._parent.project.pre_exec_script) self.txtPreExec.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'script.sh')) self.btnPreExec = QPushButton(QIcon(":img/open"), '') grid.addWidget(QLabel(translations.TR_PROJECT_PRE_EXEC), 4, 0) grid.addWidget(self.txtPreExec, 4, 1) grid.addWidget(self.btnPreExec, 4, 2) self.txtPostExec = QLineEdit() ui_tools.LineEditButton( self.txtPostExec, self.txtPostExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPostExec.setReadOnly(True) self.txtPostExec.setText(self._parent.project.post_exec_script) self.txtPostExec.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'script.sh')) self.btnPostExec = QPushButton(QIcon(":img/open"), '') grid.addWidget(QLabel(translations.TR_PROJECT_POST_EXEC), 5, 0) grid.addWidget(self.txtPostExec, 5, 1) grid.addWidget(self.btnPostExec, 5, 2) grid.addItem( QSpacerItem(5, 10, QSizePolicy.Expanding, QSizePolicy.Expanding), 6, 0) # Properties grid.addWidget(QLabel(translations.TR_PROJECT_PROPERTIES), 7, 0) self.txtParams = QLineEdit() self.txtParams.setToolTip(translations.TR_PROJECT_PARAMS_TOOLTIP) self.txtParams.setText(self._parent.project.program_params) self.txtParams.setPlaceholderText('verbose, debug, force') grid.addWidget(QLabel(translations.TR_PROJECT_PARAMS), 8, 0) grid.addWidget(self.txtParams, 8, 1) #Widgets for virtualenv properties self.txtVenvPath = QLineEdit() ui_tools.LineEditButton( self.txtVenvPath, self.txtVenvPath.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtVenvPath.setText(self._parent.project.venv) self._dir_completer = QCompleter() self._dir_completer.setModel(QDirModel(self._dir_completer)) self.txtVenvPath.setCompleter(self._dir_completer) self.txtVenvPath.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'virtualenv')) self.btnVenvPath = QPushButton(QIcon(":img/open"), '') grid.addWidget(QLabel(translations.TR_PROJECT_VIRTUALENV), 9, 0) grid.addWidget(self.txtVenvPath, 9, 1) grid.addWidget(self.btnVenvPath, 9, 2) self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_file) self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path) self.connect(self.btnVenvPath, SIGNAL("clicked()"), self._load_python_venv) self.connect(self.btnPreExec, SIGNAL("clicked()"), self.select_pre_exec_script) self.connect(self.btnPostExec, SIGNAL("clicked()"), self.select_post_exec_script)
def __init__(self, parent): super(ProjectExecution, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(self.tr("Main File:")), 0, 0) self.path = QLineEdit() ui_tools.LineEditButton( self.path, self.path.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.path.setText(self._parent._item.mainFile) self.path.setReadOnly(True) self.btnBrowse = QPushButton( QIcon(self.style().standardPixmap(self.style().SP_FileIcon)), '') grid.addWidget(self.path, 0, 1) grid.addWidget(self.btnBrowse, 0, 2) # this should be changed, and ALL pythonPath names to # python_custom_interpreter or something like that. this is NOT the # PYTHONPATH self.txtPythonPath = QLineEdit() self.txtPythonPath.setText(self._parent._item.pythonPath) self.btnPythonPath = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Python Custom Interpreter:")), 1, 0) grid.addWidget(self.txtPythonPath, 1, 1) grid.addWidget(self.btnPythonPath, 1, 2) # THIS IS THE MODAFUCKA REAL PYTHONPATH BRO, YEAH !!! grid.addWidget(QLabel(self.tr("Custom PYTHONPATH:")), 2, 0) self.PYTHONPATH = QPlainTextEdit() # TODO : better widget self.PYTHONPATH.setPlainText(self._parent._item.PYTHONPATH) self.PYTHONPATH.setToolTip(self.tr("One path per line")) grid.addWidget(self.PYTHONPATH, 2, 1) self.txtPreExec = QLineEdit() ui_tools.LineEditButton( self.txtPreExec, self.txtPreExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPreExec.setReadOnly(True) self.txtPreExec.setText(self._parent._item.preExecScript) self.btnPreExec = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Pre-exec Script:")), 3, 0) grid.addWidget(self.txtPreExec, 3, 1) grid.addWidget(self.btnPreExec, 3, 2) self.txtPostExec = QLineEdit() ui_tools.LineEditButton( self.txtPostExec, self.txtPostExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPostExec.setReadOnly(True) self.txtPostExec.setText(self._parent._item.postExecScript) self.btnPostExec = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Post-exec Script:")), 4, 0) grid.addWidget(self.txtPostExec, 4, 1) grid.addWidget(self.btnPostExec, 4, 2) grid.addItem( QSpacerItem(5, 10, QSizePolicy.Expanding, QSizePolicy.Expanding), 5, 0) # Properties grid.addWidget(QLabel(self.tr("Properties:")), 6, 0) self.txtParams = QLineEdit() self.txtParams.setToolTip( self.tr("Separate the params with commas (ie: help, verbose)")) self.txtParams.setText(self._parent._item.programParams) grid.addWidget(QLabel(self.tr("Params (comma separated):")), 7, 0) grid.addWidget(self.txtParams, 7, 1) #Widgets for virtualenv properties self.txtVenvPath = QLineEdit() ui_tools.LineEditButton( self.txtVenvPath, self.txtVenvPath.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtVenvPath.setText(self._parent._item.venv) self.txtVenvPath.setReadOnly(True) self.btnVenvPath = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Virtualenv Folder:")), 8, 0) grid.addWidget(self.txtVenvPath, 8, 1) grid.addWidget(self.btnVenvPath, 8, 2) self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_file) self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path) self.connect(self.btnVenvPath, SIGNAL("clicked()"), self._load_python_venv) self.connect(self.btnPreExec, SIGNAL("clicked()"), self.select_pre_exec_script) self.connect(self.btnPostExec, SIGNAL("clicked()"), self.select_post_exec_script)
def __init__(self, params_pipe, number_pipe, data_pipe, mads_pipe, peaks_pipe, probe_path=None, screen_resolution=None): QMainWindow.__init__(self) # Receive parameters. params = params_pipe[0].recv() self._nb_samples = params['nb_samples'] self._sampling_rate = params['sampling_rate'] self._params = { 'nb_samples': self._nb_samples, 'sampling_rate': self._sampling_rate, 'time': { 'min': 10.0, # ms 'max': 1000.0, # ms 'init': 100.0, # ms }, 'voltage': { 'min': 10.0, # µV 'max': 10e+3, # µV 'init': 100.0, # µV }, } self._canvas = VispyCanvas(probe_path=probe_path, params=self._params) central_widget = self._canvas.native # Create controls widgets. label_time = QLabel() label_time.setText(u"time") label_voltage = QLabel() label_voltage.setText(u"voltage") self._dsp_time = QDoubleSpinBox() self._dsp_time.setMinimum(self._params['time']['min']) self._dsp_time.setMaximum(self._params['time']['max']) self._dsp_time.setValue(self._params['time']['init']) self._dsp_time.valueChanged.connect(self._on_time_changed) self._dsp_voltage = QDoubleSpinBox() self._dsp_voltage.setMinimum(self._params['voltage']['min']) self._dsp_voltage.setMaximum(self._params['voltage']['max']) self._dsp_voltage.setValue(self._params['voltage']['init']) self._dsp_voltage.valueChanged.connect(self._on_voltage_changed) label_time_unit = QLabel() label_time_unit.setText(u"ms") label_voltage_unit = QLabel() label_voltage_unit.setText(u"µV") spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create controls grid. grid = QGridLayout() # # Add time row. grid.addWidget(label_time, 0, 0) grid.addWidget(self._dsp_time, 0, 1) grid.addWidget(label_time_unit, 0, 2) # # Add voltage row. grid.addWidget(label_voltage, 1, 0) grid.addWidget(self._dsp_voltage, 1, 1) grid.addWidget(label_voltage_unit, 1, 2) # # Add spacer. grid.addItem(spacer) # Create controls group. controls_group = QGroupBox() controls_group.setLayout(grid) # Create controls dock. dock = QDockWidget() dock.setWidget(controls_group) dock.setWindowTitle("Controls") # Create info widgets. label_time = QLabel() label_time.setText(u"time") self._label_time_value = QLineEdit() self._label_time_value.setText(u"0") self._label_time_value.setReadOnly(True) self._label_time_value.setAlignment(Qt.AlignRight) label_time_unit = QLabel() label_time_unit.setText(u"s") info_buffer_label = QLabel() info_buffer_label.setText(u"buffer") self._info_buffer_value_label = QLineEdit() self._info_buffer_value_label.setText(u"0") self._info_buffer_value_label.setReadOnly(True) self._info_buffer_value_label.setAlignment(Qt.AlignRight) info_buffer_unit_label = QLabel() info_buffer_unit_label.setText(u"") info_probe_label = QLabel() info_probe_label.setText(u"probe") info_probe_value_label = QLineEdit() info_probe_value_label.setText(u"{}".format(probe_path)) info_probe_value_label.setReadOnly(True) # TODO place the following info in another grid? info_probe_unit_label = QLabel() info_probe_unit_label.setText(u"") info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create info grid. info_grid = QGridLayout() # # Time row. info_grid.addWidget(label_time, 0, 0) info_grid.addWidget(self._label_time_value, 0, 1) info_grid.addWidget(label_time_unit, 0, 2) # # Buffer row. info_grid.addWidget(info_buffer_label, 1, 0) info_grid.addWidget(self._info_buffer_value_label, 1, 1) info_grid.addWidget(info_buffer_unit_label, 1, 2) # # Probe row. info_grid.addWidget(info_probe_label, 2, 0) info_grid.addWidget(info_probe_value_label, 2, 1) info_grid.addWidget(info_probe_unit_label, 2, 2) # # Spacer. info_grid.addItem(info_spacer) # Create info group. info_group = QGroupBox() info_group.setLayout(info_grid) # Create info dock. info_dock = QDockWidget() info_dock.setWidget(info_group) info_dock.setWindowTitle("Info") # Create thread. thread = Thread(number_pipe, data_pipe, mads_pipe, peaks_pipe) thread.number_signal.connect(self._number_callback) thread.reception_signal.connect(self._reception_callback) thread.start() # Add dockable windows. self.addDockWidget(Qt.LeftDockWidgetArea, dock) self.addDockWidget(Qt.LeftDockWidgetArea, info_dock) # Set central widget. self.setCentralWidget(central_widget) # Set window size. if screen_resolution is not None: screen_width = screen_resolution.width() screen_height = screen_resolution.height() self.resize(screen_width, screen_height) # Set window title. self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display") print("#####") # TODO remove?
def __init__(self, params_pipe, number_pipe, data_pipe, mads_pipe, peaks_pipe, probe_path=None, screen_resolution=None): QMainWindow.__init__(self) # Receive parameters. params = params_pipe[0].recv() self.probe = load_probe(probe_path) self._nb_samples = params['nb_samples'] self._sampling_rate = params['sampling_rate'] self._display_list = list(range(self.probe.nb_channels)) self._params = { 'nb_samples': self._nb_samples, 'sampling_rate': self._sampling_rate, 'time': { 'min': 10.0, # ms 'max': 1000.0, # ms 'init': 100.0, # ms }, 'voltage': { 'min': 10.0, # µV 'max': 10e+3, # µV 'init': 20.0, # µV }, 'mads': { 'min': 0.0, # µV 'max': 100, # µV 'init': 3, # µV }, 'channels': self._display_list } self._canvas = TraceCanvas(probe_path=probe_path, params=self._params) central_widget = self._canvas.native # Create controls widgets. label_time = QLabel() label_time.setText(u"time") label_time_unit = QLabel() label_time_unit.setText(u"ms") self._dsp_time = QDoubleSpinBox() self._dsp_time.setMinimum(self._params['time']['min']) self._dsp_time.setMaximum(self._params['time']['max']) self._dsp_time.setValue(self._params['time']['init']) self._dsp_time.valueChanged.connect(self._on_time_changed) label_display_mads = QLabel() label_display_mads.setText(u"Display Mads") self._display_mads = QCheckBox() self._display_mads.stateChanged.connect(self._on_mads_display) label_display_peaks = QLabel() label_display_peaks.setText(u"Display Peaks") self._display_peaks = QCheckBox() self._display_peaks.stateChanged.connect(self._on_peaks_display) label_mads = QLabel() label_mads.setText(u"Mads") label_mads_unit = QLabel() label_mads_unit.setText(u"unit") self._dsp_mads = QDoubleSpinBox() self._dsp_mads.setMinimum(self._params['mads']['min']) self._dsp_mads.setMaximum(self._params['mads']['max']) self._dsp_mads.setValue(self._params['mads']['init']) self._dsp_mads.valueChanged.connect(self._on_mads_changed) label_voltage = QLabel() label_voltage.setText(u"voltage") label_voltage_unit = QLabel() label_voltage_unit.setText(u"µV") self._dsp_voltage = QDoubleSpinBox() self._dsp_voltage.setMinimum(self._params['voltage']['min']) self._dsp_voltage.setMaximum(self._params['voltage']['max']) self._dsp_voltage.setValue(self._params['voltage']['init']) self._dsp_voltage.valueChanged.connect(self._on_voltage_changed) # Color spikes self._color_spikes = QCheckBox() self._color_spikes.setText('See Spikes color') self._color_spikes.setCheckState(Qt.Checked) self._color_spikes.stateChanged.connect(self.display_spikes_color) # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291)) spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create controls grid. grid = QGridLayout() # # Add time row. grid.addWidget(label_time, 0, 0) grid.addWidget(self._dsp_time, 0, 1) grid.addWidget(label_time_unit, 0, 2) # # Add voltage row. grid.addWidget(label_voltage, 1, 0) grid.addWidget(self._dsp_voltage, 1, 1) grid.addWidget(label_voltage_unit, 1, 2) # # Add Mads widgets grid.addWidget(label_display_mads, 3, 0) grid.addWidget(self._display_mads, 3, 1) grid.addWidget(label_mads, 4, 0) grid.addWidget(self._dsp_mads, 4, 1) grid.addWidget(label_mads_unit, 4, 2) grid.addWidget(self._color_spikes, 5, 0) # # Add spacer. grid.addItem(spacer) # # Create info group. controls_group = QGroupBox() controls_group.setLayout(grid) self._selection_channels = QListWidget() self._selection_channels.setSelectionMode( QAbstractItemView.ExtendedSelection ) for i in range(self.probe.nb_channels): item = QListWidgetItem("Channel %i" % i) self._selection_channels.addItem(item) self._selection_channels.item(i).setSelected(True) def add_channel(): items = self._selection_channels.selectedItems() self._display_list = [] for i in range(len(items)): self._display_list.append(i) self._on_channels_changed() # self._selection_channels.itemClicked.connect(add_channel) nb_channel = self.probe.nb_channels self._selection_channels.itemSelectionChanged.connect(lambda: self.selected_channels(nb_channel)) # Create info grid. channels_grid = QGridLayout() # # Add Channel selection # grid.addWidget(label_selection, 3, 0) channels_grid.addWidget(self._selection_channels, 0, 1) # # Add spacer. channels_grid.addItem(spacer) # Create controls group. channels_group = QGroupBox() channels_group.setLayout(channels_grid) # # Create controls dock. channels_dock = QDockWidget() channels_dock.setWidget(channels_group) channels_dock.setWindowTitle("Channels selection") # # Create controls dock. control_dock = QDockWidget() control_dock.setWidget(controls_group) control_dock.setWindowTitle("Controls") # Create info widgets. label_time = QLabel() label_time.setText(u"time") self._label_time_value = QLineEdit() self._label_time_value.setText(u"0") self._label_time_value.setReadOnly(True) self._label_time_value.setAlignment(Qt.AlignRight) label_time_unit = QLabel() label_time_unit.setText(u"s") info_buffer_label = QLabel() info_buffer_label.setText(u"buffer") self._info_buffer_value_label = QLineEdit() self._info_buffer_value_label.setText(u"0") self._info_buffer_value_label.setReadOnly(True) self._info_buffer_value_label.setAlignment(Qt.AlignRight) info_buffer_unit_label = QLabel() info_buffer_unit_label.setText(u"") info_probe_label = QLabel() info_probe_label.setText(u"probe") info_probe_value_label = QLineEdit() info_probe_value_label.setText(u"{}".format(probe_path)) info_probe_value_label.setReadOnly(True) # TODO place the following info in another grid? info_probe_unit_label = QLabel() info_probe_unit_label.setText(u"") info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create info grid. info_grid = QGridLayout() # # Time row. info_grid.addWidget(label_time, 0, 0) info_grid.addWidget(self._label_time_value, 0, 1) info_grid.addWidget(label_time_unit, 0, 2) # # Buffer row. info_grid.addWidget(info_buffer_label, 1, 0) info_grid.addWidget(self._info_buffer_value_label, 1, 1) info_grid.addWidget(info_buffer_unit_label, 1, 2) # # Probe row. info_grid.addWidget(info_probe_label, 2, 0) info_grid.addWidget(info_probe_value_label, 2, 1) info_grid.addWidget(info_probe_unit_label, 2, 2) # # Spacer. info_grid.addItem(info_spacer) # Create info group. info_group = QGroupBox() info_group.setLayout(info_grid) # Create info dock. info_dock = QDockWidget() info_dock.setWidget(info_group) info_dock.setWindowTitle("Info") # Create thread. thread = Thread(number_pipe, data_pipe, mads_pipe, peaks_pipe) thread.number_signal.connect(self._number_callback) thread.reception_signal.connect(self._reception_callback) thread.start() # Add dockable windows. self.addDockWidget(Qt.LeftDockWidgetArea, control_dock) self.addDockWidget(Qt.LeftDockWidgetArea, info_dock) self.addDockWidget(Qt.LeftDockWidgetArea, channels_dock) # Set central widget. self.setCentralWidget(central_widget) # Set window size. if screen_resolution is not None: screen_width = screen_resolution.width() screen_height = screen_resolution.height() self.resize(screen_width, screen_height) # Set window title. self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display") print(" ") # TODO remove?
def __init__(self, parent): super(ProjectExecution, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(self.tr("Main File:")), 0, 0) self.path = QLineEdit() ui_tools.LineEditButton(self.path, self.path.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.path.setText(self._parent._item.mainFile) self.path.setReadOnly(True) self.btnBrowse = QPushButton(QIcon( self.style().standardPixmap(self.style().SP_FileIcon)), '') grid.addWidget(self.path, 0, 1) grid.addWidget(self.btnBrowse, 0, 2) self.txtPythonPath = QLineEdit() self.txtPythonPath.setText(self._parent._item.pythonPath) self.btnPythonPath = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Python Path:")), 1, 0) grid.addWidget(self.txtPythonPath, 1, 1) grid.addWidget(self.btnPythonPath, 1, 2) self.txtPreExec = QLineEdit() ui_tools.LineEditButton(self.txtPreExec, self.txtPreExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPreExec.setReadOnly(True) self.txtPreExec.setText(self._parent._item.preExecScript) self.btnPreExec = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Pre-exec Script:")), 2, 0) grid.addWidget(self.txtPreExec, 2, 1) grid.addWidget(self.btnPreExec, 2, 2) self.txtPostExec = QLineEdit() ui_tools.LineEditButton(self.txtPostExec, self.txtPostExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPostExec.setReadOnly(True) self.txtPostExec.setText(self._parent._item.postExecScript) self.btnPostExec = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Post-exec Script:")), 3, 0) grid.addWidget(self.txtPostExec, 3, 1) grid.addWidget(self.btnPostExec, 3, 2) grid.addItem(QSpacerItem(5, 10, QSizePolicy.Expanding, QSizePolicy.Expanding), 4, 0) # Properties grid.addWidget(QLabel(self.tr("Properties:")), 5, 0) self.txtParams = QLineEdit() self.txtParams.setToolTip( self.tr("Separate the params with commas (ie: help, verbose)")) self.txtParams.setText(self._parent._item.programParams) grid.addWidget(QLabel(self.tr("Params (comma separated):")), 6, 0) grid.addWidget(self.txtParams, 6, 1) #Widgets for virtualenv properties self.txtVenvPath = QLineEdit() ui_tools.LineEditButton(self.txtVenvPath, self.txtVenvPath.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtVenvPath.setText(self._parent._item.venv) self.txtVenvPath.setReadOnly(True) self.btnVenvPath = QPushButton(QIcon(resources.IMAGES['open']), '') grid.addWidget(QLabel(self.tr("Virtualenv Folder:")), 7, 0) grid.addWidget(self.txtVenvPath, 7, 1) grid.addWidget(self.btnVenvPath, 7, 2) self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_file) self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path) self.connect(self.btnVenvPath, SIGNAL("clicked()"), self._load_python_venv) self.connect(self.btnPreExec, SIGNAL("clicked()"), self.select_pre_exec_script) self.connect(self.btnPostExec, SIGNAL("clicked()"), self.select_post_exec_script)
class ShellOutputScintilla(QsciScintilla): def __init__(self, parent=None): super(ShellOutputScintilla, self).__init__(parent) self.parent = parent self.shell = self.parent.shell self.settings = QSettings() # Creates layout for message bar self.layout = QGridLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layout.addItem(spacerItem, 1, 0, 1, 1) # messageBar instance self.infoBar = QgsMessageBar() sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.infoBar.setSizePolicy(sizePolicy) self.layout.addWidget(self.infoBar, 0, 0, 1, 1) # Enable non-ascii chars for editor self.setUtf8(True) sys.stdout = writeOut(self, sys.stdout) sys.stderr = writeOut(self, sys.stderr, "_traceback") self.insertInitText() self.refreshSettingsOutput() self.setReadOnly(True) # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) # Margin 0 is used for line numbers self.setMarginWidth(0, 0) self.setMarginWidth(1, 0) self.setMarginWidth(2, 0) #fm = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(1, "00000") self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor("#3E3EE3")) self.setMarginsBackgroundColor(QColor("#f9f9f9")) self.setCaretLineVisible(True) self.setCaretWidth(0) self.setMinimumHeight(120) self.setWrapMode(QsciScintilla.WrapCharacter) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self) self.runScut.setContext(Qt.WidgetShortcut) self.runScut.activated.connect(self.enteredSelected) # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view self.copyShortcut = QShortcut(QKeySequence.Copy, self) self.copyShortcut.activated.connect(self.copy) self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self) self.selectAllShortcut.activated.connect(self.selectAll) def insertInitText(self): txtInit = QCoreApplication.translate("PythonConsole", "Python Console \n" "Use iface to access QGIS API interface or Type help(iface) for more info") ## some translation string for the console header ends without '\n' ## and the first command in console will be appended at the header text. ## The following code add a '\n' at the end of the string if not present. if txtInit.endswith('\n'): self.setText(txtInit) else: self.setText(txtInit + '\n') def refreshSettingsOutput(self): # Set Python lexer self.setLexers() caretLineColor = self.settings.value("pythonConsole/caretLineColor", QColor("#fcf3ed")) cursorColor = self.settings.value("pythonConsole/cursorColor", QColor(Qt.black)) self.setCaretLineBackgroundColor(caretLineColor) self.setCaretForegroundColor(cursorColor) def setLexers(self): self.lexer = QsciLexerPython() loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace") fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int) font = QFont(loadFont) font.setFixedPitch(True) font.setPointSize(fontSize) font.setStyleHint(QFont.TypeWriter) font.setStretch(QFont.SemiCondensed) font.setLetterSpacing(QFont.PercentageSpacing, 87.0) font.setBold(False) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black)))) self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1) self.lexer.setColor(QColor(self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5) self.lexer.setColor(QColor(self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8) self.lexer.setColor(QColor(self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9) self.lexer.setColor(QColor(self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15) self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12) self.lexer.setColor(QColor(self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4) self.lexer.setColor(QColor(self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3) self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6) self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7) self.lexer.setColor(QColor(Qt.red), 14) self.lexer.setFont(font, 1) self.lexer.setFont(font, 2) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) for style in range(0, 33): paperColor = QColor(self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white))) self.lexer.setPaper(paperColor, style) self.setLexer(self.lexer) def clearConsole(self): self.setText('') self.insertInitText() self.shell.setFocus() def contextMenuEvent(self, e): menu = QMenu(self) iconRun = QgsApplication.getThemeIcon("console/iconRunConsole.png") iconClear = QgsApplication.getThemeIcon("console/iconClearConsole.png") iconHideTool = QgsApplication.getThemeIcon("console/iconHideToolConsole.png") iconSettings = QgsApplication.getThemeIcon("console/iconSettingsConsole.png") menu.addAction(iconHideTool, QCoreApplication.translate("PythonConsole", "Hide/Show Toolbar"), self.hideToolBar) menu.addSeparator() showEditorAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Show Editor"), self.showEditor) menu.addSeparator() runAction = menu.addAction(iconRun, QCoreApplication.translate("PythonConsole", "Enter Selected"), self.enteredSelected, QKeySequence(Qt.CTRL + Qt.Key_E)) clearAction = menu.addAction(iconClear, QCoreApplication.translate("PythonConsole", "Clear console"), self.clearConsole) menu.addSeparator() copyAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Copy"), self.copy, QKeySequence.Copy) menu.addSeparator() selectAllAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Select All"), self.selectAll, QKeySequence.SelectAll) menu.addSeparator() menu.addAction(iconSettings, QCoreApplication.translate("PythonConsole", "Settings"), self.parent.openSettings) runAction.setEnabled(False) clearAction.setEnabled(False) copyAction.setEnabled(False) selectAllAction.setEnabled(False) showEditorAction.setEnabled(True) if self.hasSelectedText(): runAction.setEnabled(True) copyAction.setEnabled(True) if not self.text(3) == '': selectAllAction.setEnabled(True) clearAction.setEnabled(True) if self.parent.tabEditorWidget.isVisible(): showEditorAction.setEnabled(False) menu.exec_(self.mapToGlobal(e.pos())) def hideToolBar(self): tB = self.parent.toolBar tB.hide() if tB.isVisible() else tB.show() self.shell.setFocus() def showEditor(self): Ed = self.parent.splitterObj if not Ed.isVisible(): Ed.show() self.parent.showEditorButton.setChecked(True) self.shell.setFocus() def copy(self): """Copy text to clipboard... or keyboard interrupt""" if self.hasSelectedText(): text = unicode(self.selectedText()) text = text.replace('>>> ', '').replace('... ', '').strip() # removing prompts QApplication.clipboard().setText(text) else: self.emit(SIGNAL("keyboard_interrupt()")) def enteredSelected(self): cmd = self.selectedText() self.shell.insertFromDropPaste(cmd) self.shell.entered() def keyPressEvent(self, e): # empty text indicates possible shortcut key sequence so stay in output txt = e.text() if len(txt) and txt >= " ": self.shell.append(txt) self.shell.move_cursor_to_end() self.shell.setFocus() e.ignore() else: # possible shortcut key sequence, accept it e.accept() def widgetMessageBar(self, iface, text): timeout = iface.messageTimeout() self.infoBar.pushMessage(text, QgsMessageBar.INFO, timeout)
class DAyarlar(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(600, 375) self.gridLayout = QGridLayout(self) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.treeWidget = QTreeWidget(self) self.treeWidget.setMaximumSize(200, 1500) self.virux = QTreeWidgetItem(self.treeWidget) self.virux.setExpanded(True) icon = QIcon() icon.addPixmap(QPixmap("data/logo.png"), QIcon.Normal, QIcon.On) self.virux.setIcon(0, icon) item_1 = QTreeWidgetItem(self.virux) item_1 = QTreeWidgetItem(self.virux) self.dialog = QTreeWidgetItem(self.treeWidget) self.dialog.setExpanded(True) item_1 = QTreeWidgetItem(self.dialog) item_1 = QTreeWidgetItem(self.dialog) self.treeWidget.header().setVisible(False) self.gridLayout.addWidget(self.treeWidget, 0, 0, 1, 1) self.groupBox = QGroupBox(self) self.groupBox.setFlat(True) self.gridLayout_3 = QGridLayout(self.groupBox) self.gridLayout_3.setMargin(0) self.gridLayout_3.setSpacing(0) self.widget = QWidget(self.groupBox) self.gridLayout_4 = QGridLayout(self.widget) self.gridLayout_4.setMargin(0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setMargin(0) spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 0, 0, 1, 1) self.gridLayout_3.addWidget(self.widget, 0, 0, 1, 1) self.gridLayout.addWidget(self.groupBox, 0, 1, 1, 1) self.pButton = QPushButton(self) self.pButton.setText("asd") self.pButton.setDefault(True) self.buttonBox = QDialogButtonBox(self) self.buttonBox.addButton(self.pButton, QDialogButtonBox.AcceptRole) #self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 2) self.setWindowTitle("Virux Ayarlar") self.treeWidget.headerItem().setText(0, "") self.treeWidget.topLevelItem(0).setText(0, u"Virux") self.treeWidget.topLevelItem(0).child(0).setText(0, u"Virux1") self.treeWidget.topLevelItem(0).child(1).setText(0, u"Virux2") self.treeWidget.topLevelItem(1).setText(0, u"Dialog") self.treeWidget.topLevelItem(1).child(0).setText(0, u"Dialog1") self.treeWidget.topLevelItem(1).child(1).setText(0, u"Dialog2") self.groupBox.setTitle(u"GroupBox") self.groupYaz() self.treeWidget.itemPressed.connect(self.lale) def lale(self, item): print item self.groupBox.setTitle(item.text(0)) def groupYaz(self): for option in DOptions: if hasattr(option, "getOption"): #self.gridLayout_3.addWidget(option.getOption(), 0, 0, 1, 1) item = QTreeWidgetItem(self.dialog) a = option.getOption() if hasattr(a, "name"): item.setText(0, a.name) else: item.setText(0, "F**k") #self.gridLayout_3.addWidget(a, 0, 0, 1, 1)
def __init__(self, parent): super(ProjectExecution, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(translations.TR_PROJECT_MAIN_FILE), 0, 0) self.path = QLineEdit() self.path.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'main.py')) ui_tools.LineEditButton(self.path, self.path.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.path.setText(self._parent.project.main_file) self.path.setReadOnly(True) self.btnBrowse = QPushButton(QIcon( self.style().standardPixmap(self.style().SP_FileIcon)), '') grid.addWidget(self.path, 0, 1) grid.addWidget(self.btnBrowse, 0, 2) # this should be changed, and ALL pythonPath names to # python_custom_interpreter or something like that. this is NOT the # PYTHONPATH self.txtPythonInterpreter = QLineEdit() self.txtPythonInterpreter.setText(self._parent.project.python_exec) self.txtPythonInterpreter.setCompleter(QCompleter(('python', 'python2', 'python3', 'python.exe', 'pythonw.exe'))) self.btnPythonPath = QPushButton(QIcon(":img/open"), '') grid.addWidget(QLabel( translations.TR_PROJECT_PYTHON_INTERPRETER), 1, 0) grid.addWidget(self.txtPythonInterpreter, 1, 1) grid.addWidget(self.btnPythonPath, 1, 2) grid.addWidget(QLabel(translations.TR_PROJECT_PYTHON_PATH), 2, 0) self.txtPythonPath = QPlainTextEdit() # TODO : better widget self.txtPythonPath.setPlainText(self._parent.project.python_path) self.txtPythonPath.setToolTip(translations.TR_PROJECT_PATH_PER_LINE) grid.addWidget(self.txtPythonPath, 2, 1) # Additional builtins/globals for pyflakes grid.addWidget(QLabel(translations.TR_PROJECT_BUILTINS), 3, 0) self.additional_builtins = QLineEdit() self.additional_builtins.setText( ' '.join(self._parent.project.additional_builtins)) self.additional_builtins.setToolTip( translations.TR_PROJECT_BUILTINS_TOOLTIP) grid.addWidget(self.additional_builtins, 3, 1) self.txtPreExec = QLineEdit() ui_tools.LineEditButton(self.txtPreExec, self.txtPreExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPreExec.setReadOnly(True) self.txtPreExec.setText(self._parent.project.pre_exec_script) self.txtPreExec.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'script.sh')) self.btnPreExec = QPushButton(QIcon(":img/open"), '') grid.addWidget(QLabel(translations.TR_PROJECT_PRE_EXEC), 4, 0) grid.addWidget(self.txtPreExec, 4, 1) grid.addWidget(self.btnPreExec, 4, 2) self.txtPostExec = QLineEdit() ui_tools.LineEditButton(self.txtPostExec, self.txtPostExec.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtPostExec.setReadOnly(True) self.txtPostExec.setText(self._parent.project.post_exec_script) self.txtPostExec.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'script.sh')) self.btnPostExec = QPushButton(QIcon(":img/open"), '') grid.addWidget(QLabel(translations.TR_PROJECT_POST_EXEC), 5, 0) grid.addWidget(self.txtPostExec, 5, 1) grid.addWidget(self.btnPostExec, 5, 2) grid.addItem(QSpacerItem(5, 10, QSizePolicy.Expanding, QSizePolicy.Expanding), 6, 0) # Properties grid.addWidget(QLabel(translations.TR_PROJECT_PROPERTIES), 7, 0) self.txtParams = QLineEdit() self.txtParams.setToolTip(translations.TR_PROJECT_PARAMS_TOOLTIP) self.txtParams.setText(self._parent.project.program_params) self.txtParams.setPlaceholderText('verbose, debug, force') grid.addWidget(QLabel(translations.TR_PROJECT_PARAMS), 8, 0) grid.addWidget(self.txtParams, 8, 1) #Widgets for virtualenv properties self.txtVenvPath = QLineEdit() ui_tools.LineEditButton(self.txtVenvPath, self.txtVenvPath.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtVenvPath.setText(self._parent.project.venv) self._dir_completer = QCompleter() self._dir_completer.setModel(QDirModel(self._dir_completer)) self.txtVenvPath.setCompleter(self._dir_completer) self.txtVenvPath.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'virtualenv')) self.btnVenvPath = QPushButton(QIcon(":img/open"), '') grid.addWidget(QLabel(translations.TR_PROJECT_VIRTUALENV), 9, 0) grid.addWidget(self.txtVenvPath, 9, 1) grid.addWidget(self.btnVenvPath, 9, 2) self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_file) self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path) self.connect(self.btnVenvPath, SIGNAL("clicked()"), self._load_python_venv) self.connect(self.btnPreExec, SIGNAL("clicked()"), self.select_pre_exec_script) self.connect(self.btnPostExec, SIGNAL("clicked()"), self.select_post_exec_script)
class DHakkinda(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(500, 350) self.setMaximumSize(500, 350) self.gLayout = QGridLayout(self) self.logo = QLabel(self) self.logo.setPixmap(QPixmap(":/logo/data/logo.png")) self.gLayout.addWidget(self.logo, 0, 0, 2, 1) self.appName = QLabel(self) font = QFont() font.setPointSize(32) font.setWeight(50) self.appName.setFont(font) self.gLayout.addWidget(self.appName, 0, 1, 1, 2) self.appVersion = QLabel(self) font = QFont() font.setPointSize(9) font.setWeight(75) font.setBold(True) self.appVersion.setFont(font) self.appVersion.setAlignment(Qt.AlignHCenter | Qt.AlignTop) self.gLayout.addWidget(self.appVersion, 1, 1, 1, 2) self.gBox = QGroupBox(self) font = QFont() font.setPointSize(12) font.setWeight(75) font.setBold(True) self.gBox.setFont(font) self.gLayout2 = QGridLayout(self.gBox) self.scrollArea = QScrollArea(self.gBox) self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setWidgetResizable(True) self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setGeometry(0, 0, 476, 199) self.gLayout3 = QGridLayout(self.scrollAreaWidgetContents) self.appHakkinda = QLabel(self.scrollAreaWidgetContents) font = QFont() font.setPointSize(9) font.setWeight(50) font.setBold(False) self.appHakkinda.setFont(font) self.appHakkinda.setWordWrap(True) self.gLayout3.addWidget(self.appHakkinda, 0, 0, 1, 1) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.gLayout2.addWidget(self.scrollArea, 0, 0, 1, 1) self.gLayout.addWidget(self.gBox, 2, 0, 2, 4) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gLayout.addItem(spacerItem, 0, 3, 1, 1) spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gLayout.addItem(spacerItem1, 2, 1, 1, 2) self.setWindowTitle(u"Virux Hakkında") self.appName.setText(u"Virux") self.appVersion.setText(u"Sürüm %s" % QApplication.applicationVersion()) self.gBox.setTitle(u"Hakkında") self.appHakkinda.setText(u""" <p>Virux, platform bağımsız bir antivirüs yazılımıdır :P</p> <p>Yazılımıın bir arayüzü yoktur. Sadece sistem çubuğunda bir tepsi oluşur. Bu tepsi animasyon şeklindedir.</p> <p>Rasgele zamanlarda mevcut olan dialoglardan bir tanesi ekranda gözükecektir. Sadece eğlence amacıyla yapılmıştır...</p> <p><b>Geliştirici:</b> Metehan Özbek - <a href='mailto:[email protected]'>[email protected]</a></p> <p><b>Görsel Çalışma:</b> Yasin Özcan - <a href='mailto:[email protected]'>[email protected]</a></p> <p><b>Katkı Yapanlar:</b> Yaşar Arabacı - <a href='mailto:[email protected]'>[email protected]</a></p> <p><b>Lisans:</b> GPL v3</p> <p></p>""")